问:
How to combine three char to one
I had three char inside the array , which contain X1 X2 and X3

```<code>char array[3]={X1,X2,X3}
</code>```

I want to combine three data which inside the array to one char

```<code>strcat(array[0]," ");
strcat(array[0],array[1]);
strcat(array[0]," ");
strcat(array[0],array[2]);

printf("%s",array[0])
</code>```

I expect to get the result like this "X1 X2 X3"

答:
You could convert each individual char to a string, then concatenate them. </p>

<p>e.g. </p>

```<code>    char c = 'c';
    char d = 'd';
    string s1(1, c);
    string s2(1, c);
    string cd = s1 + s2;
</code>```

Title: How to combine three char to one

Body:
I had three char inside the array , which contain X1 X2 and X3

char array[3]={X1,X2,X3}

I want to combine three data which inside the array to one char

strcat(array[0]," ");
strcat(array[0],array[1]);
strcat(array[0]," ");
strcat(array[0],array[2]);

printf("%s",array[0])

I expect to get the result like this "X1 X2 X3"

Body:
You could convert each individual char to a string, then concatenate them.

e.g.

    char c = 'c';
    char d = 'd';
    string s1(1, c);
    string s2(1, c);
    string cd = s1 + s2;


来源: stackexchange

问:
Java: trying to convert an int value to a String
In my method format(int n) I am simply trying to return the passed int value as a string. using the toString() method.

```<code>public String format(int n) {

    return n.toString();
}
</code>```

However, I keep getting the error int cannot be dereferenced. From what I understand, this is happening because I am treating a primitive int value as if it were an object, but I do not know how to fix it. I would appreciate any help with this.

答:
You could also concatenate the int with the empty String like this:

```<code>public String format(int n) {
    return "" + n;
}
</code>```

Under the hood this ends up calling String.valueOf(n) and uses a StringBuilder to append the two together, but modern compilers will optimize that out for you so it is not a performance trade off.

ContentLicense: CC BY-SA 3.0

Body:
In my method format(int n) I am simply trying to return the passed int value as a string. using the toString() method.

public String format(int n) {

    return n.toString();
}

However, I keep getting the error int cannot be dereferenced. From what I understand, this is happening because I am treating a primitive int value as if it were an object, but I do not know how to fix it. I would appreciate any help with this.

Body:
You could also concatenate the int with the empty String like this:

public String format(int n) {
    return "" + n;
}

Under the hood this ends up calling String.valueOf(n) and uses a StringBuilder to append the two together, but modern compilers will optimize that out for you so it is not a performance trade off.


问:
complex query in mysql?
```<code> -table : events
 [id=>1 , data_id =>1 , events_reference =>5 , g_id=>0
  id=>5  , data_id=>1 , events_reference =>NULL , g_id=>1,
  id=>6 . , data_id=>3, events_reference => 5 ,g_id=>0 ]

 - table : data
 [id=> 0 , name=>test1,
  id=>1 , name=>test2,
  id=>3 , name=>tes3 ]
</code>```

I want to get column name g_id_1 including the data name if g_id_1 equal to data.id in data table(not the data_id column), and also I want to get column name g_id_2 that show the data name based on the events reference

ALSO, I want only bring the data that the data.id = 1 for example so event.id =6 will not appear

expected result: (get all events and + new columns calls "g_id_1" + "g_id_2")

```<code>{
 "id"=>1,
 events_reference => 5,
 "g_id_1" = > "test 1"
 "g_id_2" => "test 2"
},
{
 "id"=>5,
 events_reference => NULL,
 "g_id_1" = > "test 2"
 "g_id_2" => NULL
}
</code>```

How can I do that, I tried with sub select but I manage to get the first level but not the second level because the events_reference is reference to another row in the same table

```<code>select id,events_reference , (SELECT name from data as d where events.events_reference = d.id) as g_id_1,
(SELECT name from data as d,events as e where e.events_reference = d.id) as g_id_1
</code>```

答:
Join the tables. You need to use multiple joins of the same tables to get the nested references. And you have to use LEFT JOIN to handle the cases where there's no match.

```<code>SELECT e1.id, e1.events_reference, d1.name AS g_id_1, d2.name AS g_id_2
FROM events AS e1
LEFT JOIN data AS d1 ON e1.g_id = d1.id
LEFT JOIN events AS e2 ON e1.events_reference = e2.id
LEFT JOIN data AS d2 ON e2.g_id = d2.id
</code>```

DEMO

ContentLicense: CC BY-SA 4.0

Title: complex query in mysql?

Body:
 -table : events
 [id=>1 , data_id =>1 , events_reference =>5 , g_id=>0
  id=>5  , data_id=>1 , events_reference =>NULL , g_id=>1,
  id=>6 . , data_id=>3, events_reference => 5 ,g_id=>0 ]

 - table : data
 [id=> 0 , name=>test1,
  id=>1 , name=>test2,
  id=>3 , name=>tes3 ]

I want to get column name g_id_1 including the data name if g_id_1 equal to data.id in data table(not the data_id column), and also I want to get column name g_id_2 that show the data name based on the events reference

ALSO, I want only bring the data that the data.id = 1 for example so event.id =6 will not appear

expected result: (get all events and + new columns calls "g_id_1" + "g_id_2")

{
 "id"=>1,
 events_reference => 5,
 "g_id_1" = > "test 1"
 "g_id_2" => "test 2"
},
{
 "id"=>5,
 events_reference => NULL,
 "g_id_1" = > "test 2"
 "g_id_2" => NULL
}

How can I do that, I tried with sub select but I manage to get the first level but not the second level because the events_reference is reference to another row in the same table

select id,events_reference , (SELECT name from data as d where events.events_reference = d.id) as g_id_1,
(SELECT name from data as d,events as e where e.events_reference = d.id) as g_id_1

Body:
Join the tables. You need to use multiple joins of the same tables to get the nested references. And you have to use LEFT JOIN to handle the cases where there's no match.

SELECT e1.id, e1.events_reference, d1.name AS g_id_1, d2.name AS g_id_2
FROM events AS e1
LEFT JOIN data AS d1 ON e1.g_id = d1.id
LEFT JOIN events AS e2 ON e1.events_reference = e2.id
LEFT JOIN data AS d2 ON e2.g_id = d2.id

DEMO


问:
Reflect is not defined when my project is deployed to the server

I'm trying to deploy my node.js project to the openshift server,
My project runs fine on my local machine but when deployed on the server it complains as follows

```<code>/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:22
    if (Reflect.hasOwnMetadata(metadataKey, annotationTarget) === true) {
        ^

ReferenceError: Reflect is not defined
    at _tagParameterOrProperty (/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:22:9)
    at Object.tagProperty (/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:12:5)
    at /opt/app-root/src/node_modules/inversify/lib/annotation/inject.js:13:31
    at __decorate (/opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:5:110)
    at /opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:17:5
    at Object.<anonymous> (/opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:25:2)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
</code>```

On VS code when I track the file and try to see where does it get from the Reflect I can see that it reads it from lib.es6.d.ts in vs code libraries so I guess that file isn't available on the server but I don't know how can I include it in the server?

Edit 1:
I'm not using docker and my package.js is as follow:

```<code>{
  "name": "mmm",
  "version": "1.0.0",
  "description": "",
  "main": "build/bootstrap.js",
  "scripts": {
    "compile": "tsc --declaration && node build/bootstrap.js",
    "dev": "nodemon -e ts  --exec \"npm run compile\"",
    "start": "nodemon -e ts  --exec \"npm run compile\"",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "author": "mmmm",
  "license": "ISC",
  "dependencies": {
    "@types/body-parser": "^1.16.5",
    "@types/express": "^4.0.39",
    "@types/node": "^8.0.44",
    "bluebird": "^3.5.1",
    "body-parser": "^1.18.2",
    "commander": "^2.12.2",
    "deep-diff": "^0.3.8",
    "express": "^4.16.2",
    "fs-finder": "^1.8.1",
    "inversify": "^4.5.2",
    "inversify-express-utils": "^4.0.1",
    "keypress": "^0.2.1",
    "knex": "^0.13.0",
    "mysql": "^2.15.0",
    "pg": "^7.3.0",
    "reflect-metadata": "^0.1.10",
    "request": "^2.83.0",
    "tape": "^4.8.0",
    "typeorm": "^0.1.1"
  },
  "devDependencies": {
    "nodemon": "^1.12.1",
    "typescript": "^2.6.2"
  }
}
</code>```

and my tsconfig.json is:

```<code>{
    "compilerOptions": {
       "target": "es6",
        "lib": ["es6", "dom"],
        "types": ["reflect-metadata"],
        "module": "commonjs",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "outDir": "build",
        "declarationDir": "declaration",
        "watch": false
    },
    "exclude": [
        "node_modules",
        "build",
        "declaration"
    ]
}
</code>```

答: You must import reflect-metadata somewhere at your app root, either client or server-side. See Inversify documentation.

Body:
I'm trying to deploy my node.js project to the openshift server,
My project runs fine on my local machine but when deployed on the server it complains as follows

/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:22
    if (Reflect.hasOwnMetadata(metadataKey, annotationTarget) === true) {
        ^

ReferenceError: Reflect is not defined
    at _tagParameterOrProperty (/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:22:9)
    at Object.tagProperty (/opt/app-root/src/node_modules/inversify/lib/annotation/decorator_utils.js:12:5)
    at /opt/app-root/src/node_modules/inversify/lib/annotation/inject.js:13:31
    at __decorate (/opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:5:110)
    at /opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:17:5
    at Object.<anonymous> (/opt/app-root/src/node_modules/inversify-express-utils/lib/base_http_controller.js:25:2)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)

On VS code when I track the file and try to see where does it get from the Reflect I can see that it reads it from lib.es6.d.ts in vs code libraries so I guess that file isn't available on the server but I don't know how can I include it in the server?

Edit 1:
I'm not using docker and my package.js is as follow:

{
  "name": "mmm",
  "version": "1.0.0",
  "description": "",
  "main": "build/bootstrap.js",
  "scripts": {
    "compile": "tsc --declaration && node build/bootstrap.js",
    "dev": "nodemon -e ts  --exec \"npm run compile\"",
    "start": "nodemon -e ts  --exec \"npm run compile\"",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "author": "mmmm",
  "license": "ISC",
  "dependencies": {
    "@types/body-parser": "^1.16.5",
    "@types/express": "^4.0.39",
    "@types/node": "^8.0.44",
    "bluebird": "^3.5.1",
    "body-parser": "^1.18.2",
    "commander": "^2.12.2",
    "deep-diff": "^0.3.8",
    "express": "^4.16.2",
    "fs-finder": "^1.8.1",
    "inversify": "^4.5.2",
    "inversify-express-utils": "^4.0.1",
    "keypress": "^0.2.1",
    "knex": "^0.13.0",
    "mysql": "^2.15.0",
    "pg": "^7.3.0",
    "reflect-metadata": "^0.1.10",
    "request": "^2.83.0",
    "tape": "^4.8.0",
    "typeorm": "^0.1.1"
  },
  "devDependencies": {
    "nodemon": "^1.12.1",
    "typescript": "^2.6.2"
  }
}

and my tsconfig.json is:

{
    "compilerOptions": {
       "target": "es6",
        "lib": ["es6", "dom"],
        "types": ["reflect-metadata"],
        "module": "commonjs",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "outDir": "build",
        "declarationDir": "declaration",
        "watch": false
    },
    "exclude": [
        "node_modules",
        "build",
        "declaration"
    ]
}


问:
How to get device serialno without ask runtime permission READ_PHONE_STATE in Android O
I'm trying to get the serial number of the device on Android O, I have looked around and found:

```<code> 1. Build.SERIAL is deprecated so we have to use Build.getSerial();
 2. ro.serialno is no more accessible: "Access denied finding property "ro.serialno""
</code>```

As regards the first approach my problem is that it requires the READ_PHONE_STATE and it must be asked at runtime. I need a way to do it without impact user experience any idea on how to do it?

Is it possible?

答:
The value is deprecated, not hidden; and even this, only for apps with targetSdkVersion 26 and higher. Which means that you can still use it without runtime permissions if you target Android N. Furthermore, if you use targetSdkVersion 23 or less, you can request READ_PHONE_STATE permission without popups. And then, when the app upgrades to target Oreo, the system will already have the permission granted to this app_id.

This said, I must confess that we had been worried about the runtime permission popups until we were forced to push targetSdkVersion to 24, but our concerns proved to be baseless. We don't experience significant changes in usage patterns.

Finally, I would also recommend not to rely on Build.SERIAL. As a remote fingerprint, adid is quite adequate; in situations when your fingerprint must survive udid reset, Build.SERIAL does provide protection with rooted device or cracked APK.

Body:
I'm trying to get the serial number of the device on Android O, I have looked around and found:

 1. Build.SERIAL is deprecated so we have to use Build.getSerial();
 2. ro.serialno is no more accessible: "Access denied finding property "ro.serialno""

As regards the first approach my problem is that it requires the READ_PHONE_STATE and it must be asked at runtime. I need a way to do it without impact user experience any idea on how to do it?

Is it possible?


问:
Reshape input_data(shape=[None, 28, 28, 1]) to input_data(shape=[None, 28, 28])
I have a variable :

```<code>network = input_data(shape=[None, 28, 28, 1])
</code>```

I want to convert it to the above shape. I'm doing it with help of tflearn.reshape but it isn't working properly. Here is the code "

```<code>network = tflearn.reshape(network,(-1, 28, 28))
</code>```

I don't want to redeclare it to shape [None,28,28] as I have elements in it. Any help on how to do it?

答:
the problem is in the shape you put. it should be [-1,28,28] format.

So your code will be :

```<code>network = tflearn.reshape(network,[-1, 28, 28])
</code>```

Regards

Body:
I have a variable :

network = input_data(shape=[None, 28, 28, 1])

I want to convert it to the above shape. I'm doing it with help of tflearn.reshape but it isn't working properly. Here is the code "

network = tflearn.reshape(network,(-1, 28, 28))

I don't want to redeclare it to shape [None,28,28] as I have elements in it. Any help on how to do it?

Body:
the problem is in the shape you put. it should be [-1,28,28] format.

So your code will be :

network = tflearn.reshape(network,[-1, 28, 28])

Regards


问:
Send and recieve files in python
So,  I am making something in my computer science class where you can send files to a remote server and that works, but cant recv them back.
SERVER.PY

```<code>import socket   # Import socket module
import os #imports os module
def RecvFile():
    while True: # allows it to always save files and not have to be restarted.
        c, addr = s.accept()
        print ('Connection Accepted From',addr)# this prints out connection and port
        print ("File is comming ....")
        file = c.recv(1024)     #recieves file name from client

        f = open(file,'wb')      #open that file or create one
        l = c.recv(1024)         #now recieves the contents of the file
        while (l):

            print ("Receiving...File Data")
            f.write(l)            #save input to file
            l = c.recv(1024)      #get again until done
        print("The file",file,"has been succesfully saved to the server\nConnection from:",addr)
        f.close()

def SendFile():
    c, addr = s.accept()
    print("Connection Accepted From",addr)
    filename = c.recv(1024)
    if os.path.isfile(filename):
        s.send("EXISTS"+str(os.pthat.getsize(filename)))
        response = c.recv(1024)
        if response[:2] == 'OK':
            with open(filename, 'rb') as f:
                s.sendall(f.read)
            f.close()
    else:
        s.send("ERR")
    s.close()

def main():
    s = socket.socket()
    s.bind(('139.59.173.187', 8000)) # Binds port and IP address
    s.listen(3)

    print("Server Started")
    while True:
        c, addr = s.accept()
        option = c.recv(1024)
        if option == "S":
            RecvFile()
        elif option == "R":
            SendFile()
        else:
            s.send("Incorrect input".encode('utf-8'))

main()

#if errors occur
c.close()
</code>```

I think the server.py is the problem

Client .py

```<code>    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('139.59.173.187',8000))
    print("=========================Welcome to the File System =========================")
    option = input("Here are your options:\n--> Press S to upload files\n--> Press R to retrieve files")
    if option == "S" or option == "s":
        s.send("S".encode('utf-8'))
        file_name = input("Please input the file name\n>>>")
        name = input("What would you like it to be saved as?\n>>>")

        s.send(name.encode('utf-8'))

        with open(file_name,'rb') as f:
            s.sendall(f.read())
        print("File has been sent to the server")
        main()

    elif option == "R" or option == "r":
        s.send("R".encode('utf-8'))
        filename = input("What is the filename you wish to recieve\n>>>")
        s.send(filename.encode('utf-8'))

        print ("File is comming ....")
        f = open(filename,'wb')      #open that file or create one
        l = c.recv(1024)         #now recieves the contents of the file
        while (l):

            print ("Receiving...File Data")
            f.write(l)            #save input to file
            l = c.recv(1024)      #get again until done
        print("The file",filename,"has been succesfully saved to your computer")
        f.close()
</code>```

I have put 7 hours into learning this and the asignment is due in friday. rather than saying the code could you comment how it works etc.

答:
In server.py, SendFile and RecvFile both use a socket object s that they have no access to. I recommend that you pass it as an argument :

```<code>def RecvFile(s):
#...

def SendFile(s):
#...
</code>```

And then in main :

```<code>if option == "S":
    RecvFile(s)
elif option == "R":
    SendFile(s)
</code>```

Title: Send and recieve files in python

Body:
So,  I am making something in my computer science class where you can send files to a remote server and that works, but cant recv them back.
SERVER.PY

import socket   # Import socket module
import os #imports os module
def RecvFile():
    while True: # allows it to always save files and not have to be restarted.
        c, addr = s.accept()
        print ('Connection Accepted From',addr)# this prints out connection and port
        print ("File is comming ....")
        file = c.recv(1024)     #recieves file name from client

        f = open(file,'wb')      #open that file or create one
        l = c.recv(1024)         #now recieves the contents of the file
        while (l):

            print ("Receiving...File Data")
            f.write(l)            #save input to file
            l = c.recv(1024)      #get again until done
        print("The file",file,"has been succesfully saved to the server\nConnection from:",addr)
        f.close()

def SendFile():
    c, addr = s.accept()
    print("Connection Accepted From",addr)
    filename = c.recv(1024)
    if os.path.isfile(filename):
        s.send("EXISTS"+str(os.pthat.getsize(filename)))
        response = c.recv(1024)
        if response[:2] == 'OK':
            with open(filename, 'rb') as f:
                s.sendall(f.read)
            f.close()
    else:
        s.send("ERR")
    s.close()

def main():
    s = socket.socket()
    s.bind(('139.59.173.187', 8000)) # Binds port and IP address
    s.listen(3)

    print("Server Started")
    while True:
        c, addr = s.accept()
        option = c.recv(1024)
        if option == "S":
            RecvFile()
        elif option == "R":
            SendFile()
        else:
            s.send("Incorrect input".encode('utf-8'))

main()

#if errors occur
c.close()

I think the server.py is the problem

Client .py

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('139.59.173.187',8000))
    print("=========================Welcome to the File System =========================")
    option = input("Here are your options:\n--> Press S to upload files\n--> Press R to retrieve files")
    if option == "S" or option == "s":
        s.send("S".encode('utf-8'))
        file_name = input("Please input the file name\n>>>")
        name = input("What would you like it to be saved as?\n>>>")

        s.send(name.encode('utf-8'))

        with open(file_name,'rb') as f:
            s.sendall(f.read())
        print("File has been sent to the server")
        main()

    elif option == "R" or option == "r":
        s.send("R".encode('utf-8'))
        filename = input("What is the filename you wish to recieve\n>>>")
        s.send(filename.encode('utf-8'))

        print ("File is comming ....")
        f = open(filename,'wb')      #open that file or create one
        l = c.recv(1024)         #now recieves the contents of the file
        while (l):

            print ("Receiving...File Data")
            f.write(l)            #save input to file
            l = c.recv(1024)      #get again until done
        print("The file",filename,"has been succesfully saved to your computer")
        f.close()

I have put 7 hours into learning this and the asignment is due in friday. rather than saying the code could you comment how it works etc.

Body:
In server.py, SendFile and RecvFile both use a socket object s that they have no access to. I recommend that you pass it as an argument :

def RecvFile(s):
#...

def SendFile(s):
#...

And then in main :

if option == "S":
    RecvFile(s)
elif option == "R":
    SendFile(s)


问:
Only show non-default attributes in repr of attr.s class
I'm using attrs to define simple classes without boilerplate code. The decorator automatically generates a __repr__ that shows the values for all attributes. I'd like to only show attributes that do not have their default values:

```<code>>>> import attr
>>> @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=0, y=0)  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=1)  # wanted output: Coordinates(x=1)
Coordinates(x=1, y=0)
>>> Coordinates(x=1, y=1)  # output OK
Coordinates(x=1, y=1)
</code>```

Is there any reasonably easy way to achieve this?

答:
I think I figured out a way, with the following class decorator:

def no_default_vals_in_repr(cls):
    """Class decorator on top of attr.s that omits attributes from srepr that
    have their default value"""

    defaults = OrderedDict()
    for attribute in cls.__attrs_attrs__:
        defaults[attribute.name] = attribute.default

    def repr_(self):
        real_cls = self.__class__
        qualname = getattr(real_cls, "__qualname__", None)
        if qualname is not None:
            class_name = qualname.rsplit(">.", 1)[-1]
        else:
            class_name = real_cls.__name__
        attributes = defaults.keys()
        return "{0}({1})".format(
            class_name,
            ", ".join(
                name + "=" + repr(getattr(self, name))
                for name in attributes
                if getattr(self, name) != defaults[name]))

    cls.__repr__ = repr_
    return cls
```
<p>This results in the following correct behavior:</p>
<pre class="lang-py prettyprint-override"><code>>>> @no_default_vals_in_repr
... @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()
Coordinates()
>>> Coordinates(x=0, y=0)
Coordinates()
>>> Coordinates(x=1)
Coordinates(x=1)
>>> Coordinates(x=1, y=1)
Coordinates(x=1, y=1)
</code>```

Body:
I'm using attrs to define simple classes without boilerplate code. The decorator automatically generates a __repr__ that shows the values for all attributes. I'd like to only show attributes that do not have their default values:

>>> import attr
>>> @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=0, y=0)  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=1)  # wanted output: Coordinates(x=1)
Coordinates(x=1, y=0)
>>> Coordinates(x=1, y=1)  # output OK
Coordinates(x=1, y=1)

Is there any reasonably easy way to achieve this?

Body:
I think I figured out a way, with the following class decorator:

def no_default_vals_in_repr(cls):
    """Class decorator on top of attr.s that omits attributes from srepr that
    have their default value"""

    defaults = OrderedDict()
    for attribute in cls.__attrs_attrs__:
        defaults[attribute.name] = attribute.default

    def repr_(self):
        real_cls = self.__class__
        qualname = getattr(real_cls, "__qualname__", None)
        if qualname is not None:
            class_name = qualname.rsplit(">.", 1)[-1]
        else:
            class_name = real_cls.__name__
        attributes = defaults.keys()
        return "{0}({1})".format(
            class_name,
            ", ".join(
                name + "=" + repr(getattr(self, name))
                for name in attributes
                if getattr(self, name) != defaults[name]))

    cls.__repr__ = repr_
    return cls

This results in the following correct behavior:

>>> @no_default_vals_in_repr
... @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()
Coordinates()
>>> Coordinates(x=0, y=0)
Coordinates()
>>> Coordinates(x=1)
Coordinates(x=1)
>>> Coordinates(x=1, y=1)
Coordinates(x=1, y=1)


问:
Drupal problem, how to create a fast content module?
Hi I need to create a module in drupal to display some data, not being a drupal developer and after reading a couple of tutorials, i cant seem to display anything.

I have the next code:

```<code><?php
function helloworld_perm() {
  return array('access helloworld content');
}

function helloworld_listado(){
 return "yea";
}

function helloworld_menu(){
    $items = array();
    $items["listado"] = array(
        'title' => t('Listado de empresas'),
        'callback' => 'helloworld_listado',
        'access' => array('access helloworld content'),
        'type' => MENU_NORMAL_ITEM
      );
    return $items;
}
</code>```

When i enter /listado i get a Access denied
You are not authorized to access this page.

Any idea what im doing wrong?
If i go to the admin->module->permissions, i have checked the permision for all roles to access hellowold content.

Ty!

答:
From the way that your menu array is structured in helloworld_menu(), I'm assuming that this is Drupal 6. If so, you need to rename 'access' to 'access arguments'. See http://api.drupal.org/api/function/hook_menu/6.

The Drupal API documentation also includes a heavily-commented page_example.module that's doing basically what you're doing here, which you might want to check out: http://api.drupal.org/api/file/developer/examples/page_example.module/6/source

Hope that helps!

Oh. And don't forget to clear your cache afterwards from the "Clear cache" button on Administer >> Site configuration >> Performance.

OwnerDisplayName: DFectuoso

ContentLicense: CC BY-SA 2.5

Body:
Hi I need to create a module in drupal to display some data, not being a drupal developer and after reading a couple of tutorials, i cant seem to display anything.

I have the next code:

<?php
function helloworld_perm() {
  return array('access helloworld content');
}

function helloworld_listado(){
 return "yea";
}

function helloworld_menu(){
    $items = array();
    $items["listado"] = array(
        'title' => t('Listado de empresas'),
        'callback' => 'helloworld_listado',
        'access' => array('access helloworld content'),
        'type' => MENU_NORMAL_ITEM
      );
    return $items;
}

When i enter /listado i get a Access denied
You are not authorized to access this page.

Any idea what im doing wrong?
If i go to the admin->module->permissions, i have checked the permision for all roles to access hellowold content.

Ty!


问:
Updated version of the mysql World database?
I know it's meant only as a test database, but I can;t find an (updated) copy of the World DB anywhere. The one on the Mysql site is out of date for most countries (presidents/heads of state have changed, etc). Anyone know where this data came from?</p>

答: It does not seem like there is an updated version. The source is Statistics Finland, according to MySQL's setup page.</p>


问:
How to Get Only Matched Result from An Array Field of Document in Mongo Using Spring Data
I am using spring boot 1.5.1 and MongoDB version 3.4.6 .

I have a mongo document Hotel which has a list of Review .

The Review class has property userName.

```<code>@Document
public class Hotel {

    @Id
    private String id;
    private List<Review> reviews;
</code>```

I want to search all the hotel by Review userName.

My HotelRepository has public List<Hotel> findByReviewsUserName(String userName);

When I am calling with user 'Salman' -

```<code>List<Hotel> list = this.hotelRepository.findByReviewsUserName(user);
</code>```

this method returns result like below :

```<code>[
    {
        "id": "59b23c39c70ff63135f76b14",
        "name": "Signature",
        "reviews": [
            {
                "id": 1,
                "userName": "Salman",
                "rating": 8,
                "approved": true
            },
            {
                "id": 2,
                "userName": "Shahrukh",
                "rating": 5,
                "approved": false
            }
        ]
    }
]
</code>```

What I want the reviews only of 'Salman' but it's also returning for others also.

What am I missing or how to do it?

What I have noticed is that if a single review user matched it returns the whole list of reviews which I don't want, I want reviews I have searched by name.

答:
Great answer from @barbakini, but that also can be done without creating custom repository implementation with Criteria, just 'describe' which fields you would like to get, where 0 - .exclude, 1 - .include(

```<code>@Query(fields = "{ '_id': 0, 'reviews.$': 1 }")
List<Hotel> findByReviewsUserName(String userName);
</code>```

Body:
I am using spring boot 1.5.1 and MongoDB version 3.4.6 .

I have a mongo document Hotel which has a list of Review .

The Review class has property userName.

@Document
public class Hotel {

    @Id
    private String id;
    private List<Review> reviews;

I want to search all the hotel by Review userName.

My HotelRepository has public List<Hotel> findByReviewsUserName(String userName);

When I am calling with user 'Salman' -

List<Hotel> list = this.hotelRepository.findByReviewsUserName(user);

this method returns result like below :

[
    {
        "id": "59b23c39c70ff63135f76b14",
        "name": "Signature",
        "reviews": [
            {
                "id": 1,
                "userName": "Salman",
                "rating": 8,
                "approved": true
            },
            {
                "id": 2,
                "userName": "Shahrukh",
                "rating": 5,
                "approved": false
            }
        ]
    }
]

What I want the reviews only of 'Salman' but it's also returning for others also.

What am I missing or how to do it?

What I have noticed is that if a single review user matched it returns the whole list of reviews which I don't want, I want reviews I have searched by name.

Body:
Great answer from @barbakini, but that also can be done without creating custom repository implementation with Criteria, just 'describe' which fields you would like to get, where 0 - .exclude, 1 - .include(

@Query(fields = "{ '_id': 0, 'reviews.$': 1 }")
List<Hotel> findByReviewsUserName(String userName);


问:
Local Dev Server for AWS Lambdas
Is there a dev server that runs AWS Lambdas locally? My requirements would be

nodejs server, no ruby or go or anything need to install other than node and npm packages

Creates a server that I can query via wget / curl or an API testing tool to send various events to

I should be able to specify a js file that the server uses as lambda and the server should restart / update when I change that file

答: Have you checked out SAM Local? https://github.com/awslabs/aws-sam-local</p>

Title: Local Dev Server for AWS Lambdas


问:
How do I read an audio file into an array in C#
I am trying to read a WAV file into a buffer array in c# but am having some problems. I am using a file stream to manage the audio file. Here is what I have...

```<code>FileStream WAVFile = new FileStream(@"test.wav", FileMode.Open);

        //Buffer for the wave file...
        BinaryReader WAVreader = new BinaryReader(WAVFile);

        //Read information from the header.
        chunkID = WAVreader.ReadInt32();
        chunkSize = WAVreader.ReadInt32();
        RiffFormat = WAVreader.ReadInt32();

        ...

        channels = WAVreader.ReadInt16();
        samplerate = WAVreader.ReadInt32();
        byteRate = WAVreader.ReadInt32();
        blockAllign = WAVreader.ReadInt16();
        bitsPerSample = WAVreader.ReadInt16();

        dataID = WAVreader.ReadInt32();
        dataSize = WAVreader.ReadInt32();
</code>```

The above is reading data from the WAV file header. Then I have this:

```<code>musicalData = WAVreader.ReadBytes(dataSize);
</code>```

...to read the actual sample data  but this is only 26 bytes for 60 seconds of audio. Is this correct?

How would I go about converting the byte[] array to double[]?

答:
It's been a good 10-15 years since I touched WAVE file processing, but unlike the first impression that most people get about wave files as simple fixed-size header followed by PCM encoded audio data, WAVE files are a bit more complex RIFF format files.

Instead of re-engineering RIFF file processing and various cases, I would suggest to use interop and call on APIs that deal with RIFF file format.

You can see example of how to open and get data buffer (and meta information about what buffer is) in this example. It's in C++, but it shows use of mmioOpen, mmioRead, mmioDescend, mmioAscend APIs that you would need to use to get your hands on a proper audio buffer.

Body:
I am trying to read a WAV file into a buffer array in c# but am having some problems. I am using a file stream to manage the audio file. Here is what I have...

FileStream WAVFile = new FileStream(@"test.wav", FileMode.Open);

        //Buffer for the wave file...
        BinaryReader WAVreader = new BinaryReader(WAVFile);

        //Read information from the header.
        chunkID = WAVreader.ReadInt32();
        chunkSize = WAVreader.ReadInt32();
        RiffFormat = WAVreader.ReadInt32();

        ...

        channels = WAVreader.ReadInt16();
        samplerate = WAVreader.ReadInt32();
        byteRate = WAVreader.ReadInt32();
        blockAllign = WAVreader.ReadInt16();
        bitsPerSample = WAVreader.ReadInt16();

        dataID = WAVreader.ReadInt32();
        dataSize = WAVreader.ReadInt32();

The above is reading data from the WAV file header. Then I have this:

musicalData = WAVreader.ReadBytes(dataSize);

...to read the actual sample data  but this is only 26 bytes for 60 seconds of audio. Is this correct?

How would I go about converting the byte[] array to double[]?


问:
How to deny s3 bucket access for an AWS account
I have an AWS account with ID 11111 and I would like to deny access to certain parts of an s3 bucket to the same account the bucket belongs to, even if the role accessing that object has full s3 access.

It is my understanding that setting a DENY rule on a s3 bucket policy should do that, so I tried the s3 policy below

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Deny",
            "Principal": {
                "AWS": "arn:aws:iam::111111:root"
            },
            "Action": [
                "s3:PutObject",
                "s3:GetObjectVersion",
                "s3:GetObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::mybucket/production/*"
            ]
        }
    ]
}

However an ec2 machine in the same account as the s3 bucket with an iam role to allow full access to the bucket (s3:*) is still able to write/read to mybucket/production/*

Am I missing something? Shouldn't the DENY bucket rule take precedence? How does one handle this situation? I want to avoid having to remove the full access from the ec2 role but rather be able to deny on top of that.

答:
I believe the following is going on here:

The account 111111 owns the S3 bucket and the IAM entity (in this case an IAM role).

Since, the request is being made from an IAM role in the same account (bucket owner), S3 will only check the "User Context".

While evaluating the "User Context", S3 will take into account:

Policies attached to the IAM role

Bucket policy

Bucket and Object ACL (if any)

The request is allowed via the IAM role's permission policy and there is no explicit Deny for the IAM Role because the Principal in the bucket policy is actually for the "Root User" and NOT covering the IAM entities in 111111 account since both accounts (bucket owner and 111111) are same.

I tested this and using the similar policy my Root user cannot delete or upload objects into the bucket. However, root can gain access by deleting the bucket policy.

As @John Hanley mentioned, you can use the IAM role's as a principal to deny access in production "folder" but as the role has S3fullaccess, it can delete the bucket policy, so I'd recommend to deny that capability also.


问:
Schema users and permissions
From the documentation I understood that the schemas are related to one user. I want to create 6 schemas that each will have its tables, but I want just one user that can connect through php and insert some data in those tables (will hace access to the other schemas).

I know you can just assign the CONNECT and RESOURCE roles to those users, but from what i read its not the best option regarding security.

I thought about making 2 roles, one for the schema users and another for the php user.

For the php user: GRANT CREATE SESSION, UNLIMITED TABLESPACE to
For the schema users; but do i need some privileges for these users? Since they will not be accessed

Is this a correct way to do this?

答: In Oracle each schema is also a user. You can lock users that you do not want people to log in to and then give the user that you want to login privileges on the objects in the other schemas.</p>

Title: Schema users and permissions


问:
How to make an "alias" for a long path?
I tried to make an "alias" for a path that I use often while shell scripting. I tried something, but it failed:

```<code>myFold="~/Files/Scripts/Main"
cd myFold

bash: cd: myFold: No such file or directory
</code>```

How do I make it work ?

However, cd ~/Files/Scripts/Mainworks.

答:
Another option would be to use a symbolic link. ie:

```<code>ln -s ~/Files/Scripts/Main ~/myFold
</code>```

After that you can perform operations to ~/myFold, such as:

```<code>cp some_file.txt ~/myFold
</code>```

which will put the file in ~/Files/Scripts/Main. You can remove the symbolic link at any time with rm ~/myFold, which will keep the original directory.

Title: How to make an "alias" for a long path?

Body:
I tried to make an "alias" for a path that I use often while shell scripting. I tried something, but it failed:

myFold="~/Files/Scripts/Main"
cd myFold

bash: cd: myFold: No such file or directory

How do I make it work ?

However, cd ~/Files/Scripts/Mainworks.

Body:
Another option would be to use a symbolic link. ie:

ln -s ~/Files/Scripts/Main ~/myFold

After that you can perform operations to ~/myFold, such as:

cp some_file.txt ~/myFold

which will put the file in ~/Files/Scripts/Main. You can remove the symbolic link at any time with rm ~/myFold, which will keep the original directory.


问:
How do I make sure there are no repeated numbers when using random()?
I have this code that displays 100 random numbers, then adds a break for every 10 numbers. How would I ensure that these 100 random numbers do not have repeats? I know maybe there's something to do with more if statements?

Thanks,
J

<!DOCTYPE html>

Random Numbers and Breaks (for loops)

This will display 100 numbers and insert a break in 10-number intervals:

```

答:
How would I ensure that these 100 random numbers do not have repeats?

You need to save returned values (by random number generator) so that same value is not returned again.

```<code>function randomNumberGenerator( min, max )
{
   var returnedValues = [];
   return function()
   {
       var num = null;
       while( num == null ||  returnedValues.indexOf( num ) != -1 )
       {
           num  = Math.floor((Math.random() * (max-min)) + min);
       }
       return num;
   }
}
</code>```

Now you can call this n number of times ( n < (max - min) )

```<code>var nRandomNumbers = 10;
var randomNumArr = [];
var ran1 = randomNumberGenerator(1,100); //initialize the randomNumberGenerator
for( var counter = 0; counter < nRandomNumbers; counter++ )
{
  randomNumArr.push( ran1() );
}
</code>```

Body:
How would I ensure that these 100 random numbers do not have repeats?

You need to save returned values (by random number generator) so that same value is not returned again.

function randomNumberGenerator( min, max )
{
   var returnedValues = [];
   return function()
   {
       var num = null;
       while( num == null ||  returnedValues.indexOf( num ) != -1 )
       {
           num  = Math.floor((Math.random() * (max-min)) + min);
       }
       return num;
   }
}

Now you can call this n number of times ( n < (max - min) )

var nRandomNumbers = 10;
var randomNumArr = [];
var ran1 = randomNumberGenerator(1,100); //initialize the randomNumberGenerator
for( var counter = 0; counter < nRandomNumbers; counter++ )
{
  randomNumArr.push( ran1() );
}


问:
How to retrieve BlobStore file name from BlobReferenceProperty?
I'm having a hard time understanding how to do something that should be straightforward.

```<code>class Spam(db.Model):
    egg = blobstore.BlobReferenceProperty(blobstore.BlobKey, required=False)

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        spam = models.Spam(egg=blob_info.key())
        spam.put()
</code>```

So far so good right?  Now I want to display the file.

```<code>egg_blob = blobstore.BlobInfo.get(spam.egg) #error below is thrown here

self.redirect('/serve/%s' % egg_blob.key())

BadArgumentError: Expected str or BlobKey; received <google.appengine.ext.blobstore.blobstore.BlobInfo object at 0x3ed8970> (a BlobInfo)
</code>```

What am I missing?  spam.egg, IS a BlobKey.

答:
No, I think egg_blob (aka spam.egg) is a BlobInfo.  Once you have spam.egg I don't think you need to go back to the blobstore for it, do you?  Have you tried just using the spam.egg reference? i.e. do</p>

```<code>self.redirect('/serve/%s' % spam.egg.key())
</code>```

Body:
I'm having a hard time understanding how to do something that should be straightforward.

class Spam(db.Model):
    egg = blobstore.BlobReferenceProperty(blobstore.BlobKey, required=False)

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        spam = models.Spam(egg=blob_info.key())
        spam.put()

So far so good right?  Now I want to display the file.

egg_blob = blobstore.BlobInfo.get(spam.egg) #error below is thrown here

self.redirect('/serve/%s' % egg_blob.key())

BadArgumentError: Expected str or BlobKey; received <google.appengine.ext.blobstore.blobstore.BlobInfo object at 0x3ed8970> (a BlobInfo)

What am I missing?  spam.egg, IS a BlobKey.

Body:
No, I think egg_blob (aka spam.egg) is a BlobInfo.  Once you have spam.egg I don't think you need to go back to the blobstore for it, do you?  Have you tried just using the spam.egg reference? i.e. do

self.redirect('/serve/%s' % spam.egg.key())


问:
Laravel Fluent Query Builder Update Query
I want to add two columns while using update, like this:

```<code> Update purchase_stock inner join stock on purchase_stock.fkstockid=stock.stockid SET currentavailable=currentavailable+subquantity where fkorderid='1';
</code>```

Here is the current Fluent code:

```<code> DB::table('purchase_stock')->join('stock','stock.stockid','=','purchase_stock.fkstockid')->where('fkorderid',$orderId)->update(array('currentavailable'=>'currentavailable'+'subquantity'));**
</code>```

But it throws error as below:

```<code>"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '=>'"
</code>```

Does any one have solution?

答:
You were very close with your fluent attempt, but there were two issues:

The plus sign needs to be inside the quotes, since you want the math done in SQL, not in PHP.

Need a DB::raw() around the value so Laravel doesn't think you're actually trying to set it to the string "currentavailable + subquantity"

So the final product looks like this:

```<code>DB::table('purchase_stock')
    ->join('stock', 'stock.stockid', '=', 'purchase_stock.fkstockid')
    ->where('fkorderid', $orderId)
    ->update(['currentavailable' => DB::raw('currentavailable + subquantity')]);
</code>```

Body:
I want to add two columns while using update, like this:

 Update purchase_stock inner join stock on purchase_stock.fkstockid=stock.stockid SET currentavailable=currentavailable+subquantity where fkorderid='1';

Here is the current Fluent code:

 DB::table('purchase_stock')->join('stock','stock.stockid','=','purchase_stock.fkstockid')->where('fkorderid',$orderId)->update(array('currentavailable'=>'currentavailable'+'subquantity'));**

But it throws error as below:

"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '=>'"

Does any one have solution?

Body:
You were very close with your fluent attempt, but there were two issues:

The plus sign needs to be inside the quotes, since you want the math done in SQL, not in PHP.

Need a DB::raw() around the value so Laravel doesn't think you're actually trying to set it to the string "currentavailable + subquantity"

So the final product looks like this:

DB::table('purchase_stock')
    ->join('stock', 'stock.stockid', '=', 'purchase_stock.fkstockid')
    ->where('fkorderid', $orderId)
    ->update(['currentavailable' => DB::raw('currentavailable + subquantity')]);


问:
Call cv::VideoCapture constructor conditionally
I want to call the cv::VideoCapture constructor conditionally. If argc == 2, then the user has specified a video file and I want to load that. Otherwise use the default camera.

```<code>#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main(int argc, char* argv[])
{
    VideoCapture cap(argc == 2 ? argv[1] : 0);

    return 0;
}
</code>```

I compile and run it

```<code>$ g++ -g -Wall -o main main.cpp `pkg-config opencv --cflags --libs`
$ ./main
</code>```

But sadly it doesn't seem to work and I get

```<code>OpenCV: Couldn't read movie file ""
</code>```

The ternary operator returns a string in one case and an integer in another. I reckon this won't work because of some idiosyncrasy of C++ constructors I'm not aware of.

What's the cleanest way to do what I want? Can I do it without using new so that I don't have to free memory myself at the end of the program?

答:
You're over-complicating this. Use open:

```<code>VideoCapture cap;
if(argc == 2) {
    cap.open(argv[1]); // calls: open(const String& filename)
} else {
    cap.open(0);       // calls: open(int index)
}
</code>```

In the ternary operator the two operands must be of the same type. See here for details. But yours have type int and char*, so, even of the code may compile, it can result in runtime errors.

Body:
I want to call the cv::VideoCapture constructor conditionally. If argc == 2, then the user has specified a video file and I want to load that. Otherwise use the default camera.

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main(int argc, char* argv[])
{
    VideoCapture cap(argc == 2 ? argv[1] : 0);

    return 0;
}

I compile and run it

$ g++ -g -Wall -o main main.cpp `pkg-config opencv --cflags --libs`
$ ./main

But sadly it doesn't seem to work and I get

OpenCV: Couldn't read movie file ""

The ternary operator returns a string in one case and an integer in another. I reckon this won't work because of some idiosyncrasy of C++ constructors I'm not aware of.

What's the cleanest way to do what I want? Can I do it without using new so that I don't have to free memory myself at the end of the program?

Body:
You're over-complicating this. Use open:

VideoCapture cap;
if(argc == 2) {
    cap.open(argv[1]); // calls: open(const String& filename)
} else {
    cap.open(0);       // calls: open(int index)
}

In the ternary operator the two operands must be of the same type. See here for details. But yours have type int and char*, so, even of the code may compile, it can result in runtime errors.


问:
Windows Console and Qt Unicode Text
I spent a whole day trying to figure this out with no luck.  I looked Everywhere but no luck with working code.

OS: Win XP Sp2
IDE & FRAMEWORK: C++, Qt Creator 2.0.

I am trying to output some unicode (UTF-8) text to the windows console but all I see is gibberish in place of the unicode chars.  I know the win console does support unicode (since win 2000)... at least according to Wikipedia and many on the net but I don't see how to make it work with Qt.  Most "solutions" I've seen (haven't seen many) use C++ and WInAPI tech... which I can't use because that is not the Qt way.  I am using QStrings and Qt!

Code is bellow.  I took out all the different things I tried to keep the code simple for the post.  Hope someone can get the code to work.

```<code>#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    QTextStream qout(stdout);

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    //I want this text console output to be in red text color.
    qout << "Bellow are some unicode characters: " << endl;

    //The Win XP console does not display the unicode chars correctly!!
    //The cosole does not display unicode chars even though it is capable
    //according to wikipedia.  I just don't know how with Qt.
    //I want this text output in white(or default font color, not red.)
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = QString::fromUtf8(qin.readLine());
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

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

答: I think it's because your code needs to use WriteConsoleW instead of WriteFile internally, and the runtime library might not use that function. If it doesn't use WriteFileW, then you can't write Unicode.

Title: Windows Console and Qt Unicode Text

Body:
I spent a whole day trying to figure this out with no luck.  I looked Everywhere but no luck with working code.

OS: Win XP Sp2
IDE & FRAMEWORK: C++, Qt Creator 2.0.

I am trying to output some unicode (UTF-8) text to the windows console but all I see is gibberish in place of the unicode chars.  I know the win console does support unicode (since win 2000)... at least according to Wikipedia and many on the net but I don't see how to make it work with Qt.  Most "solutions" I've seen (haven't seen many) use C++ and WInAPI tech... which I can't use because that is not the Qt way.  I am using QStrings and Qt!

Code is bellow.  I took out all the different things I tried to keep the code simple for the post.  Hope someone can get the code to work.

#include <QtCore/QCoreApplication>
#include <QString>
#include <QTextStream>
#include <QDate>
#include <QFile>
using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QTextStream qin(stdin);
    QTextStream qout(stdout);

    //The last 2 chars in QString each need a double slash for an accent.
    QString szqLine = QString::fromUtf8("abc áéüóöú őű");

    //I want this text console output to be in red text color.
    qout << "Bellow are some unicode characters: " << endl;

    //The Win XP console does not display the unicode chars correctly!!
    //The cosole does not display unicode chars even though it is capable
    //according to wikipedia.  I just don't know how with Qt.
    //I want this text output in white(or default font color, not red.)
    qout << szqLine << endl;

    //Would be nice to get some unicode input from console too.
    qout << "Write some unicode chars like above: " << endl;
    QString szqInput;
    szqInput = QString::fromUtf8(qin.readLine());
    qout << "You wrote: " << endl;
    qout << szqInput << endl;

    return app.exec();
}


问:
Angular2 showing null in IE
I have the following in an Angular2 component:

Chrome & Safari work fine - but IE is showing null in the DIV. I have no idea why... heading is undefined, double-checked!

答:
For those who don't like the fact that you have to do ngIf whenever the innerHTML may be undefined, here's a solution to resolve this across your app:

```<code>constructor(sanitize: DomSanitizer) {
    // override the sanitize method so that it returns an empty string instead of null so that IE doesn't show "null" in the DOM
    sanitize.sanitize = function(context: SecurityContext, value: SafeValue | string | null) {
        return (sanitize as any).__proto__.sanitize.call((sanitize as any), context, value) || '';
    };
}
</code>```

I place this in the app.module constructor.

You may ask, "why such a hacky approach?" That's largely because DomSanitizer is an interface acting as a class. The real sanitization happens in the DomSanitizerImpl class that isn't publicly exposed.

EDIT 6/18/19
Here's one for textContent as its done differently but produces undefined in IE

```<code>constructor(renderer: Renderer2) {
    /**
     * in IE, textContent = undefined gets put in the DOM as string, "undefined".
     * this is to override that behavior. We would put this in app.module
     * with the hack for DOM sanitization but in order to access the renderer,
     * we need to be in a component
     */
    const setProperty = (renderer as any).__proto__.setProperty;
    (renderer as any).__proto__.setProperty = function(el: Element, name: string, value: string) {
      if (name === 'textContent' && value === undefined) {
        value = '';
      }
      setProperty.call(this, el, name, value);
    };
  }
</code>```

Title: Angular2 showing null in IE

Body:
For those who don't like the fact that you have to do ngIf whenever the innerHTML may be undefined, here's a solution to resolve this across your app:

constructor(sanitize: DomSanitizer) {
    // override the sanitize method so that it returns an empty string instead of null so that IE doesn't show "null" in the DOM
    sanitize.sanitize = function(context: SecurityContext, value: SafeValue | string | null) {
        return (sanitize as any).__proto__.sanitize.call((sanitize as any), context, value) || '';
    };
}

I place this in the app.module constructor.

You may ask, "why such a hacky approach?" That's largely because DomSanitizer is an interface acting as a class. The real sanitization happens in the DomSanitizerImpl class that isn't publicly exposed.

EDIT 6/18/19
Here's one for textContent as its done differently but produces undefined in IE

constructor(renderer: Renderer2) {
    /**
     * in IE, textContent = undefined gets put in the DOM as string, "undefined".
     * this is to override that behavior. We would put this in app.module
     * with the hack for DOM sanitization but in order to access the renderer,
     * we need to be in a component
     */
    const setProperty = (renderer as any).__proto__.setProperty;
    (renderer as any).__proto__.setProperty = function(el: Element, name: string, value: string) {
      if (name === 'textContent' && value === undefined) {
        value = '';
      }
      setProperty.call(this, el, name, value);
    };
  }


问:
Python how convert single quotes to double quotes to format as json string
I have a file where on each line I have text like this (representing cast of a film):

```<code>[{'cast_id': 23, 'character': "Roger 'Verbal' Kint", 'credit_id': '52fe4260c3a36847f8019af7', 'gender': 2, 'id': 1979, 'name': 'Kevin Spacey', 'order': 5, 'profile_path': '/x7wF050iuCASefLLG75s2uDPFUu.jpg'}, {'cast_id': 27, 'character': 'Edie's Finneran', 'credit_id': '52fe4260c3a36847f8019b07', 'gender': 1, 'id': 2179, 'name': 'Suzy Amis', 'order': 6, 'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}]
</code>```

I need to convert it in a valid json string, thus converting only the necessary single quotes to double quotes (e.g. the single quotes around word Verbal must not be converted, eventual apostrophes in the text also should not be converted).

I am using python 3.x. I need to find a regular expression which will convert only the right single quotes to double quotes, thus the whole text resulting in a valid json string. Any idea?

答:
First of all, the line you gave as example is not parsable! … 'Edie's Finneran' … contains a syntax error, not matter what.

Assuming that you have control over the input, you could simply use eval() to read in the file. (Although, in that case one would wonder why you can't produce valid JSON in the first place…)

```<code>>>> f = open('list.txt', 'r')
>>> s = f.read().strip()
>>> l = eval(s)

>>> import pprint
>>> pprint.pprint(l)
[{'cast_id': 23,
  'character': "Roger 'Verbal' Kint",
  ...
  'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}]

>>> import json
>>> json.dumps(l)
'[{"cast_id": 23, "character": "Roger \'Verbal\' Kint", "credit_id": "52fe4260ca36847f8019af7", "gender": 2, "id": 1979, "name": "Kevin Spacey", "order": 5, "rofile_path": "/x7wF050iuCASefLLG75s2uDPFUu.jpg"}, {"cast_id": 27, "character":"Edie\'s Finneran", "credit_id": "52fe4260c3a36847f8019b07", "gender": 1, "id":2179, "name": "Suzy Amis", "order": 6, "profile_path": "/b1pjkncyLuBtMUmqD1MztDSG80.jpg"}]'
</code>```

If you don't have control over the input, this is very dangerous, as it opens you up to code injection attacks.

I cannot emphasize enough that the best solution would be to produce valid JSON in the first place.

Body:
I have a file where on each line I have text like this (representing cast of a film):

[{'cast_id': 23, 'character': "Roger 'Verbal' Kint", 'credit_id': '52fe4260c3a36847f8019af7', 'gender': 2, 'id': 1979, 'name': 'Kevin Spacey', 'order': 5, 'profile_path': '/x7wF050iuCASefLLG75s2uDPFUu.jpg'}, {'cast_id': 27, 'character': 'Edie's Finneran', 'credit_id': '52fe4260c3a36847f8019b07', 'gender': 1, 'id': 2179, 'name': 'Suzy Amis', 'order': 6, 'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}]

I need to convert it in a valid json string, thus converting only the necessary single quotes to double quotes (e.g. the single quotes around word Verbal must not be converted, eventual apostrophes in the text also should not be converted).

I am using python 3.x. I need to find a regular expression which will convert only the right single quotes to double quotes, thus the whole text resulting in a valid json string. Any idea?

Body:
First of all, the line you gave as example is not parsable! … 'Edie's Finneran' … contains a syntax error, not matter what.

Assuming that you have control over the input, you could simply use eval() to read in the file. (Although, in that case one would wonder why you can't produce valid JSON in the first place…)

>>> f = open('list.txt', 'r')
>>> s = f.read().strip()
>>> l = eval(s)

>>> import pprint
>>> pprint.pprint(l)
[{'cast_id': 23,
  'character': "Roger 'Verbal' Kint",
  ...
  'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}]

>>> import json
>>> json.dumps(l)
'[{"cast_id": 23, "character": "Roger \'Verbal\' Kint", "credit_id": "52fe4260ca36847f8019af7", "gender": 2, "id": 1979, "name": "Kevin Spacey", "order": 5, "rofile_path": "/x7wF050iuCASefLLG75s2uDPFUu.jpg"}, {"cast_id": 27, "character":"Edie\'s Finneran", "credit_id": "52fe4260c3a36847f8019b07", "gender": 1, "id":2179, "name": "Suzy Amis", "order": 6, "profile_path": "/b1pjkncyLuBtMUmqD1MztDSG80.jpg"}]'

If you don't have control over the input, this is very dangerous, as it opens you up to code injection attacks.

I cannot emphasize enough that the best solution would be to produce valid JSON in the first place.


问:
NSAttributedString freeze UITableView
Application really freeze while scrolling with NSAttributedString (When I use NSString it works fine), so there my method:

```<code>- (void)setSubtitleForCell:(TTTableViewCell *)cell item:(TTPhotoPost *)item
{
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:
                                            [item.caption dataUsingEncoding:NSUnicodeStringEncoding]
                                                                            options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                                                 documentAttributes:nil
                                                                              error:nil];

    [cell.descriptionLabel setAttributedText:attributedString];
}
</code>```

Any mistakes there? or some way to make att.string faster?

答:
make it asynchronously (I think the issue is connected that scroll view is using main thread as well):</p>

```<code>- (void)setSubtitleForCell:(TTTableViewCell *)cell item:(TTPhotoPost *)item
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:
                                                [item.caption dataUsingEncoding:NSUnicodeStringEncoding]
                                                                                options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                                                     documentAttributes:nil
                                                                                error:nil];
        dispatch_on_main_queue(^{
            [cell.descriptionLabel setAttributedText:attributedString];
        });
    });
}
</code>```

Title: NSAttributedString freeze UITableView

Body:
Application really freeze while scrolling with NSAttributedString (When I use NSString it works fine), so there my method:

- (void)setSubtitleForCell:(TTTableViewCell *)cell item:(TTPhotoPost *)item
{
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:
                                            [item.caption dataUsingEncoding:NSUnicodeStringEncoding]
                                                                            options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                                                 documentAttributes:nil
                                                                              error:nil];

    [cell.descriptionLabel setAttributedText:attributedString];
}

Any mistakes there? or some way to make att.string faster?

Body:
make it asynchronously (I think the issue is connected that scroll view is using main thread as well):

- (void)setSubtitleForCell:(TTTableViewCell *)cell item:(TTPhotoPost *)item
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:
                                                [item.caption dataUsingEncoding:NSUnicodeStringEncoding]
                                                                                options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType }
                                                                     documentAttributes:nil
                                                                                error:nil];
        dispatch_on_main_queue(^{
            [cell.descriptionLabel setAttributedText:attributedString];
        });
    });
}


问:
how to convert text file to adjancency matrix in python
I have text file which includes:

1 2

1 5

2 3

2 5

3 4

I am new in python, How can I convert those data from .txt into adjacency matrix in python? Many thanks in advance.

答:
Here is the code

that will read from input file and builds adjacency matrix

```<code>f = open("graph.txt", 'r')
graph = {}
n = 0
for i in f.readlines():
    nodes = i.split(" ")
    n1 = int(nodes[0])
    n2 = int(nodes[1])
    if n < n1 and n1 > n2:
        n = n1
    if n < n2 and n2 > n1:
        n = n2
    if n1 not in list(graph):
        graph[n1] = []
    adjacencyList = graph[n1]
    adjacencyList.append(n2)
    graph[n1] = adjacencyList

adjacencyMatrix = []
for i in range(1,n+1):
    row = []
    for j in range(1,n+1):
        if i in list(graph) and j in graph[i]:
            row.append(1)
        else:
            row.append(0)
    adjacencyMatrix.append(row)

for i in range(n):
    row = ""
    for j in range(n):
        row += str(adjacencyMatrix[i][j])+" "

    print(row)
</code>```

Body:
Here is the code

that will read from input file and builds adjacency matrix

f = open("graph.txt", 'r')
graph = {}
n = 0
for i in f.readlines():
    nodes = i.split(" ")
    n1 = int(nodes[0])
    n2 = int(nodes[1])
    if n < n1 and n1 > n2:
        n = n1
    if n < n2 and n2 > n1:
        n = n2
    if n1 not in list(graph):
        graph[n1] = []
    adjacencyList = graph[n1]
    adjacencyList.append(n2)
    graph[n1] = adjacencyList

adjacencyMatrix = []
for i in range(1,n+1):
    row = []
    for j in range(1,n+1):
        if i in list(graph) and j in graph[i]:
            row.append(1)
        else:
            row.append(0)
    adjacencyMatrix.append(row)

for i in range(n):
    row = ""
    for j in range(n):
        row += str(adjacencyMatrix[i][j])+" "

    print(row)


问:
What's the easiest way to create an Excel table with C#?
I have some tabular data that I'd like to turn into an Excel table.

Software available:

.NET 4 (C#)

Excel 2010 (using the Excel API is OK)

I prefer not to use any 3rd party libraries

Information about the data:

A couple million rows

5 columns, all strings (very simple and regular table structure)

In my script I'm currently using a nested List data structure but I can change that

Performance of the script is not critical

Searching online gives many results, and I'm confused whether I should use OleDb, ADO RecordSets, or something else. Some of these technologies seem like overkill for my scenario, and some seem like they might be obsolete.

What is the very simplest way to do this?

Edit: this is a one-time script I intend to run from my attended desktop.

答:
Some things for your consideration...

If this is a client side solution, there is nothing wrong with using Interops.
If this is a server side solution, Don't use Interops.  Good alternative is OpenXML SDK from Microsoft if you don't want 3rd party solution.  It's free.  I believe the latest one has similar object model that Excel has.  It's a lot faster, A LOT, in generating the workbook vs going the interops way which can bog down your server.


问:
'function' undefined only in Edge and Explorer
I'm developing a we page in SharePoint but only in Internet Explorer 11 and Microsoft Edge the onclick referenced function throws an error. In Chrome, Firefox, Opera it's ok.

```<code><script type="text/javascript">
function BuildCategory( element )
{
    for( let button of pathButtons )
    {
        button.style.borderBottom = "1px solid #999999";
        button.style.boxShadow = "0.5px 1.5px 0.5px #AFAFAF";
        button.style.color = "#888888";
        button.style.backgroundColor = "transparent";
    }
    element.style.backgroundColor = "#FEFEFE";
    element.style.color = "#111111";
    element.style.borderBottom = "1px solid #709BE5";
    element.style.boxShadow = "0.5px 1.5px 0.5px #709BE5";

    careerArea = element.innerHTML;
    BuildPath( careerPath, careerArea, careerRole );
}

function BuildRole( element )
{
    for( let button of roleButtons )
    {
        button.style.color = "#888888";
        button.style.borderBottomColor = "#000000";
    }
    element.style.color = "#111111";
    element.style.borderBottomColor = "#709BE5";

    careerRole = element.innerHTML;
    careerRole = careerRole == 'Trainee' ? Trainee : careerRole == 'Proficient' ? Proficient : careerRole == 'Senior' ? Senior : careerRole;
    BuildPath( careerPath, careerArea, careerRole );
}
</script>
<span class="PathTitle">
    BlackBox Career Path
</span>
<div class="PathSelector">
    <span class="PathButton Sixth" onclick="BuildCategory( this )">Testing Process</span>
    <span class="PathButton Sixth" onclick="BuildCategory( this )">Tools</span>
    <span class="PathButton Sixth" onclick="BuildCategory( this )">Certification</span>
    <span class="PathButton Sixth" onclick="BuildCategory( this )">Consulting</span>
    <span class="PathButton Sixth" onclick="BuildCategory( this )">QA/PI</span>
    <span class="PathButton Sixth" onclick="BuildCategory( this )">PM</span>
    <span class="PathButton Sixth" onclick="BuildCategory( this )">All Categories</span>
</div>
<div class="RoleSelector">
    <span class="RoleButton Octet" onclick="BuildRole( this )">Trainee</span>
    <span class="RoleButton Octet" onclick="BuildRole( this )">Junior</span>
    <span class="RoleButton Octet" onclick="BuildRole( this )">Proficient</span>
    <span class="RoleButton Octet" onclick="BuildRole( this )">Senior</span>
    <span class="RoleButton Octet" onclick="BuildRole( this )">QA Lead</span>
    <span class="RoleButton Octet" onclick="BuildRole( this )">Expert</span>
    <span class="RoleButton Octet" onclick="BuildRole( this )">QA Manager</span>
    <span class="RoleButton Octet" onclick="BuildRole( this )">QA Consultant</span>
    <span class="RoleButton Octet" onclick="BuildRole( this )">All Roles</span>
</div>
<div class="CourseSelector" id="courseSelector">
</div>
</code>```

In non Microsoft browsers the function works and throws no error.

I get 'BuildCategory' is undefined when I click a 'PathButton' or 'BuildRole' is undefined when clicking a 'RoleButton'.

答: Just solved, issue was that I'm using for..of/in statement, which isn't compatible with IE and some versions of Edge. I had a long time viewing why the console said that a ';' was missing in Testing Process. I decided to put alerts in the function and I noticed that the alert inside the for was not executing. I used the classic for(var ...) and everything is ok

Body:
I'm developing a we page in SharePoint but only in Internet Explorer 11 and Microsoft Edge the onclick referenced function throws an error. In Chrome, Firefox, Opera it's ok.

    BlackBox Career Path

    Testing Process
    Tools
    Certification
    Consulting
    QA/PI
    PM
    All Categories

    Trainee
    Junior
    Proficient
    Senior
    QA Lead
    Expert
    QA Manager
    QA Consultant
    All Roles

In non Microsoft browsers the function works and throws no error.

I get 'BuildCategory' is undefined when I click a 'PathButton' or 'BuildRole' is undefined when clicking a 'RoleButton'.

Body: Just solved, issue was that I'm using for..of/in statement, which isn't compatible with IE and some versions of Edge. I had a long time viewing why the console said that a ';' was missing in <span class="PathButton Sixth" onclick="BuildCategory( this )">Testing Process</span>. I decided to put alerts in the function and I noticed that the alert inside the for was not executing. I used the classic for(var ...) and everything is ok


问:
IllegalStateException - Fragment no longer exists
I see IllegalStateException in Google-Play Console, which I can't reproduce.

Here is the stack trace:

```<code>java.lang.RuntimeException:
      at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3253)
      at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3349)
      at android.app.ActivityThread.access$1100 (ActivityThread.java:221)
      at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1794)
      at android.os.Handler.dispatchMessage (Handler.java:102)
      at android.os.Looper.loop (Looper.java:158)
      at android.app.ActivityThread.main (ActivityThread.java:7224)
      at java.lang.reflect.Method.invoke (Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1230)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)
Caused by: java.lang.IllegalStateException:
      at android.support.v4.app.FragmentManagerImpl.getFragment (FragmentManager.java:668)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:999)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1252)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1234)
      at android.support.v4.app.FragmentManagerImpl.dispatchCreate (FragmentManager.java:2041)
      at android.support.v4.app.Fragment.performCreate (Fragment.java:1964)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1029)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1252)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1234)
      at android.support.v4.app.FragmentManagerImpl.dispatchCreate (FragmentManager.java:2041)
      at android.support.v4.app.Fragment.performCreate (Fragment.java:1964)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1029)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1252)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1234)
      at android.support.v4.app.FragmentManagerImpl.dispatchCreate (FragmentManager.java:2041)
      at android.support.v4.app.FragmentController.dispatchCreate (FragmentController.java:163)
      at android.support.v4.app.FragmentActivity.onCreate (FragmentActivity.java:331)
      at android.support.v7.app.AppCompatActivity.onCreate (AppCompatActivity.java:85)
      at com.example.eliran.forum.RootActivity.onCreate (RootActivity.java:53)
      at com.example.eliran.forum.MainActivity.onCreate (MainActivity.java:58)
      at android.app.Activity.performCreate (Activity.java:6876)
      at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1135)
      at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3206)
</code>```

I have activity with NavigationView which contains fragments.

I suspect that this exception happens when the user press on the back button and a function that contains the following code is called:

```<code>if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
    getSupportFragmentManager().popBackStack();
}
</code>```

Google-Play console doesn't display this, but this is the exception error:

```<code>    throwException(new IllegalStateException("Fragment no longer exists for key "
            + key + ": index " + index));
</code>```

答:
You probably use setTargetFragment() somewhere in your code.
Just avoid using it.
Instead, communicate between the fragemnts via callback and listener like this:
In fragmentDialog -

protected OnRemovedTopicListener callback = null;

```<code>public interface OnRemovedTopicListener {
    public abstract void onTopicRemoved(int position);
}

public void setOnRemovedTopicListener(OnRemovedTopicListener l){
    callback = l;
}
</code>```

and using the callback -
callback.onTopicRemoved(position);

In the parent fragment -

```<code>    dialogFragment.setOnRemovedTopicListener(new ForumTopicDialogFragment.OnRemovedTopicListener() {
        @Override
        public void onTopicRemoved(int position) {
            // you code here
        }
    });
</code>```

Body:
I see IllegalStateException in Google-Play Console, which I can't reproduce.

Here is the stack trace:

java.lang.RuntimeException:
      at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3253)
      at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3349)
      at android.app.ActivityThread.access$1100 (ActivityThread.java:221)
      at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1794)
      at android.os.Handler.dispatchMessage (Handler.java:102)
      at android.os.Looper.loop (Looper.java:158)
      at android.app.ActivityThread.main (ActivityThread.java:7224)
      at java.lang.reflect.Method.invoke (Native Method)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1230)
      at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)
Caused by: java.lang.IllegalStateException:
      at android.support.v4.app.FragmentManagerImpl.getFragment (FragmentManager.java:668)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:999)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1252)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1234)
      at android.support.v4.app.FragmentManagerImpl.dispatchCreate (FragmentManager.java:2041)
      at android.support.v4.app.Fragment.performCreate (Fragment.java:1964)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1029)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1252)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1234)
      at android.support.v4.app.FragmentManagerImpl.dispatchCreate (FragmentManager.java:2041)
      at android.support.v4.app.Fragment.performCreate (Fragment.java:1964)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1029)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1252)
      at android.support.v4.app.FragmentManagerImpl.moveToState (FragmentManager.java:1234)
      at android.support.v4.app.FragmentManagerImpl.dispatchCreate (FragmentManager.java:2041)
      at android.support.v4.app.FragmentController.dispatchCreate (FragmentController.java:163)
      at android.support.v4.app.FragmentActivity.onCreate (FragmentActivity.java:331)
      at android.support.v7.app.AppCompatActivity.onCreate (AppCompatActivity.java:85)
      at com.example.eliran.forum.RootActivity.onCreate (RootActivity.java:53)
      at com.example.eliran.forum.MainActivity.onCreate (MainActivity.java:58)
      at android.app.Activity.performCreate (Activity.java:6876)
      at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1135)
      at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3206)

I have activity with NavigationView which contains fragments.

I suspect that this exception happens when the user press on the back button and a function that contains the following code is called:

if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
    getSupportFragmentManager().popBackStack();
}

Google-Play console doesn't display this, but this is the exception error:

    throwException(new IllegalStateException("Fragment no longer exists for key "
            + key + ": index " + index));

Body:
You probably use setTargetFragment() somewhere in your code.
Just avoid using it.
Instead, communicate between the fragemnts via callback and listener like this:
In fragmentDialog -

protected OnRemovedTopicListener callback = null;

public interface OnRemovedTopicListener {
    public abstract void onTopicRemoved(int position);
}

public void setOnRemovedTopicListener(OnRemovedTopicListener l){
    callback = l;
}

and using the callback -
callback.onTopicRemoved(position);

In the parent fragment -

    dialogFragment.setOnRemovedTopicListener(new ForumTopicDialogFragment.OnRemovedTopicListener() {
        @Override
        public void onTopicRemoved(int position) {
            // you code here
        }
    });


答:
This code should do the trick. It converts a wave file to a normalized double array (-1 to 1), but it should be trivial to make it an int/short array instead (remove the /32768.0 bit and add 32768 instead). The right[] array will be set to null if the loaded wav file is found to be mono.

I can't claim it's completely bullet proof (potential off-by-one errors), but after creating a 65536 sample array, and creating a wave from -1 to 1, none of the samples appear to go 'through' the ceiling or floor.

```<code>// convert two bytes to one double in the range -1 to 1
static double bytesToDouble(byte firstByte, byte secondByte)
{
    // convert two bytes to one short (little endian)
    short s = (secondByte << 8) | firstByte;

    // convert to range from -1 to (just below) 1
    return s / 32768.0;
}

// Returns left and right double arrays. 'right' will be null if sound is mono.
public void openWav(string filename, out double[] left, out double[] right)
{
    byte[] wav = File.ReadAllBytes(filename);

    // Determine if mono or stereo
    int channels = wav[22];     // Forget byte 23 as 99.999% of WAVs are 1 or 2 channels

    // Get past all the other sub chunks to get to the data subchunk:
    int pos = 12;   // First Subchunk ID from 12 to 16

    // Keep iterating until we find the data chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
    while(!(wav[pos]==100 && wav[pos+1]==97 && wav[pos+2]==116 && wav[pos+3]==97))
    {
        pos += 4;
        int chunkSize = wav[pos] + wav[pos + 1] * 256 + wav[pos + 2] * 65536 + wav[pos + 3] * 16777216;
        pos += 4 + chunkSize;
    }

    pos += 8;

    // Pos is now positioned to start of actual sound data.
    int samples = (wav.Length - pos)/2;     // 2 bytes per sample (16 bit sound mono)

    if (channels == 2)
    {
        samples /= 2;        // 4 bytes per sample (16 bit stereo)
    }

    // Allocate memory (right will be null if only mono sound)
    left = new double[samples];

    if (channels == 2)
    {
        right = new double[samples];
    }
    else
    {
        right = null;
    }

    // Write to double array/s:
    int i=0;
    while (pos < length)
    {
        left[i] = bytesToDouble(wav[pos], wav[pos + 1]);
        pos += 2;

        if (channels == 2)
        {
            right[i] = bytesToDouble(wav[pos], wav[pos + 1]);
            pos += 2;
        }

        i++;
    }
}
</code>```

If you wanted to use plugins, then assuming your WAV file contains 16 bit PCM (which is the most common), you can use NAudio to read it out into a byte array, and then copy that into an array of 16 bit integers for convenience. If it is stereo, the samples will be interleaved left, right.

```<code>using (WaveFileReader reader = new WaveFileReader("myfile.wav"))
{
    Assert.AreEqual(16, reader.WaveFormat.BitsPerSample, "Only works with 16 bit audio");
    byte[] buffer = new byte[reader.Length];
    int read = reader.Read(buffer, 0, buffer.Length);
    short[] sampleBuffer = new short[read / 2];
    Buffer.BlockCopy(buffer, 0, sampleBuffer, 0, read);
}
</code>```

I personally try to avoid using third-party libraries as much as I can. But the option is still there if you'd like the code to look better and easier to handle.

Title: How do I read an audio file into an array in C#

Body:
I am trying to read a WAV file into a buffer array in c# but am having some problems. I am using a file stream to manage the audio file. Here is what I have...

FileStream WAVFile = new FileStream(@"test.wav", FileMode.Open);

        //Buffer for the wave file...
        BinaryReader WAVreader = new BinaryReader(WAVFile);

        //Read information from the header.
        chunkID = WAVreader.ReadInt32();
        chunkSize = WAVreader.ReadInt32();
        RiffFormat = WAVreader.ReadInt32();

        ...

        channels = WAVreader.ReadInt16();
        samplerate = WAVreader.ReadInt32();
        byteRate = WAVreader.ReadInt32();
        blockAllign = WAVreader.ReadInt16();
        bitsPerSample = WAVreader.ReadInt16();

        dataID = WAVreader.ReadInt32();
        dataSize = WAVreader.ReadInt32();

The above is reading data from the WAV file header. Then I have this:

musicalData = WAVreader.ReadBytes(dataSize);

...to read the actual sample data  but this is only 26 bytes for 60 seconds of audio. Is this correct?

How would I go about converting the byte[] array to double[]?

Body:
This code should do the trick. It converts a wave file to a normalized double array (-1 to 1), but it should be trivial to make it an int/short array instead (remove the /32768.0 bit and add 32768 instead). The right[] array will be set to null if the loaded wav file is found to be mono.

I can't claim it's completely bullet proof (potential off-by-one errors), but after creating a 65536 sample array, and creating a wave from -1 to 1, none of the samples appear to go 'through' the ceiling or floor.

// convert two bytes to one double in the range -1 to 1
static double bytesToDouble(byte firstByte, byte secondByte)
{
    // convert two bytes to one short (little endian)
    short s = (secondByte << 8) | firstByte;

    // convert to range from -1 to (just below) 1
    return s / 32768.0;
}

// Returns left and right double arrays. 'right' will be null if sound is mono.
public void openWav(string filename, out double[] left, out double[] right)
{
    byte[] wav = File.ReadAllBytes(filename);

    // Determine if mono or stereo
    int channels = wav[22];     // Forget byte 23 as 99.999% of WAVs are 1 or 2 channels

    // Get past all the other sub chunks to get to the data subchunk:
    int pos = 12;   // First Subchunk ID from 12 to 16

    // Keep iterating until we find the data chunk (i.e. 64 61 74 61 ...... (i.e. 100 97 116 97 in decimal))
    while(!(wav[pos]==100 && wav[pos+1]==97 && wav[pos+2]==116 && wav[pos+3]==97))
    {
        pos += 4;
        int chunkSize = wav[pos] + wav[pos + 1] * 256 + wav[pos + 2] * 65536 + wav[pos + 3] * 16777216;
        pos += 4 + chunkSize;
    }

    pos += 8;

    // Pos is now positioned to start of actual sound data.
    int samples = (wav.Length - pos)/2;     // 2 bytes per sample (16 bit sound mono)

    if (channels == 2)
    {
        samples /= 2;        // 4 bytes per sample (16 bit stereo)
    }

    // Allocate memory (right will be null if only mono sound)
    left = new double[samples];

    if (channels == 2)
    {
        right = new double[samples];
    }
    else
    {
        right = null;
    }

    // Write to double array/s:
    int i=0;
    while (pos < length)
    {
        left[i] = bytesToDouble(wav[pos], wav[pos + 1]);
        pos += 2;

        if (channels == 2)
        {
            right[i] = bytesToDouble(wav[pos], wav[pos + 1]);
            pos += 2;
        }

        i++;
    }
}

If you wanted to use plugins, then assuming your WAV file contains 16 bit PCM (which is the most common), you can use NAudio to read it out into a byte array, and then copy that into an array of 16 bit integers for convenience. If it is stereo, the samples will be interleaved left, right.

using (WaveFileReader reader = new WaveFileReader("myfile.wav"))
{
    Assert.AreEqual(16, reader.WaveFormat.BitsPerSample, "Only works with 16 bit audio");
    byte[] buffer = new byte[reader.Length];
    int read = reader.Read(buffer, 0, buffer.Length);
    short[] sampleBuffer = new short[read / 2];
    Buffer.BlockCopy(buffer, 0, sampleBuffer, 0, read);
}

I personally try to avoid using third-party libraries as much as I can. But the option is still there if you'd like the code to look better and easier to handle.


问:
How would I find the smallest number in an array and remove it then adding all the numbers together
I'm trying to find the smallest number in an array either multidimensional array or one dimensional array. Then remove the number and add all the numbers together. I am able to find the smallest number using the min method and add them together using the sum method. However I do not know how to remove the outcome from the min method.</p>

```<code>public void Calculatepredictionbtn_Click (object sender, EventArgs e)
{
    int firstymark1 = Int32.Parse(firsty_mark1.Text);
    int firstymark2 = Int32.Parse(firsty_mark2.Text);
    int firstymark3 = Int32.Parse(firsty_mark3.Text);
    int firstymark4 = Int32.Parse(firsty_mark4.Text);
    int firstymark5 = Int32.Parse(firsty_mark5.Text);
    int firstymark6 = Int32.Parse(firsty_mark6.Text);
    int firstymark7 = Int32.Parse(firsty_mark7.Text);
    int secondymark = Int32.Parse(secondy_mark1.Text);
    int[] modules = new int[] { firstymark1, firstymark2, firstymark3, firstymark4,
                                firstymark5, firstymark6, firstymark7 };
    int reduction = modules.Min();
    ///dont know how to remove the number
    int arrayadded = modules.Sum();
}
</code>```

答:
Since you want to remove a value it would be better to use a List instead of array, because resizing arrays is expensive. By using List you have the Remove method also:

```<code>List<int> modules =  new List<int>(){ firstymark1, firstymark2, firstymark3, firstymark4,
                                      firstymark5, firstymark6, firstymark7 };
int reduction = modules.Min();
modules.Remove(reduction);
int arrayadded = modules.Sum();
</code>```

Body:
I'm trying to find the smallest number in an array either multidimensional array or one dimensional array. Then remove the number and add all the numbers together. I am able to find the smallest number using the min method and add them together using the sum method. However I do not know how to remove the outcome from the min method.

public void Calculatepredictionbtn_Click (object sender, EventArgs e)
{
    int firstymark1 = Int32.Parse(firsty_mark1.Text);
    int firstymark2 = Int32.Parse(firsty_mark2.Text);
    int firstymark3 = Int32.Parse(firsty_mark3.Text);
    int firstymark4 = Int32.Parse(firsty_mark4.Text);
    int firstymark5 = Int32.Parse(firsty_mark5.Text);
    int firstymark6 = Int32.Parse(firsty_mark6.Text);
    int firstymark7 = Int32.Parse(firsty_mark7.Text);
    int secondymark = Int32.Parse(secondy_mark1.Text);
    int[] modules = new int[] { firstymark1, firstymark2, firstymark3, firstymark4,
                                firstymark5, firstymark6, firstymark7 };
    int reduction = modules.Min();
    ///dont know how to remove the number
    int arrayadded = modules.Sum();
}

Body:
Since you want to remove a value it would be better to use a List instead of array, because resizing arrays is expensive. By using List you have the Remove method also:

List<int> modules =  new List<int>(){ firstymark1, firstymark2, firstymark3, firstymark4,
                                      firstymark5, firstymark6, firstymark7 };
int reduction = modules.Min();
modules.Remove(reduction);
int arrayadded = modules.Sum();


问:
Trace the IPAddress
I like to know the IP address of the system from which user is connected to MSTSC or remote system. Here is my problem:-

I have web application wich run on intranet and when user need to access that webapplication they need to login to their office PC. Now to access their office PC user need to connect thorugh VPN. Now i want to know his IP address from which he has done the VPN when he access the webapplication. Your help is appriciated

Thanks,
Pankaj

答:
You can make use of the HttpWebRequest.UserHostAddress property</p>

```<code>String address = Request.UserHostAddress;
</code>```

Title: Trace the IPAddress

Body:
You can make use of the HttpWebRequest.UserHostAddress property

String address = Request.UserHostAddress;


问:
Java regex for string pattern
I would want to write a regex for this string pattern:

```<code><Col name="SKU_UPC_NBR">85634546495</Col>
</code>```

I want to fetch the value between Col tag.

I tried the below pattern :

```<code>Pattern TAG_REGEX = Pattern.compile("<Col name='SKU_UPC_NBR'>(.+?)</col>");
Matcher matcher = TAG_REGEX.matcher(str);
</code>```

The above is not matching my string and returns empty.
Please help me on this problem.

答:
You can try:

```<code><Col[^>]*>(.+?)<\/Col>
</code>```

<Col[^>]*> will match the opening tag. [^>]* means match any character but >, so that the match ends at the first > encountered.

(.+?) means grab 1 or more characters between the opening and closing tag

<\/Col> this matches the closing tag

Title: Java regex for string pattern

Body:
I would want to write a regex for this string pattern:

<Col name="SKU_UPC_NBR">85634546495</Col>

I want to fetch the value between Col tag.

I tried the below pattern :

Pattern TAG_REGEX = Pattern.compile("<Col name='SKU_UPC_NBR'>(.+?)</col>");
Matcher matcher = TAG_REGEX.matcher(str);

The above is not matching my string and returns empty.
Please help me on this problem.

Body:
You can try:

<Col[^>]*>(.+?)<\/Col>

<Col[^>]*> will match the opening tag. [^>]* means match any character but >, so that the match ends at the first > encountered.

(.+?) means grab 1 or more characters between the opening and closing tag

<\/Col> this matches the closing tag


答:
Regex matches exactly what you type.  It does not generalize, it does not understand that sometimes to you ' == ", it does not match mixing cases.

The data format you've specified is open tag, space, name attribute, equals, double quote, name attr data ...

The regex format you've specified is open tag, space, name attribute, equals, single quote, name attr data ...

What you need is

```<code>Pattern TAG_REGEX = Pattern.compile("<Col name=\"SKU_UPC_NBR\">(.+?)</Col>");
</code>```

NOTE: You may want to use (\d+?) instead of (.+?) as \d will match any digit, so the regex is more specific to the data you're matching, and is easier to read.  This won't work however, if you know some Col tags won't have just digits in them

You may want to refer to this neat interactive Regex tutorial for practice with regex's.

You also may want to refer to the Java documentation for Regex patterns, this is useful when you need special characters.

Title: Java regex for string pattern

Body:
Regex matches exactly what you type.  It does not generalize, it does not understand that sometimes to you ' == ", it does not match mixing cases.

The data format you've specified is open tag, space, name attribute, equals, double quote, name attr data ...

The regex format you've specified is open tag, space, name attribute, equals, single quote, name attr data ...

What you need is

Pattern TAG_REGEX = Pattern.compile("<Col name=\"SKU_UPC_NBR\">(.+?)</Col>");

NOTE: You may want to use (\d+?) instead of (.+?) as \d will match any digit, so the regex is more specific to the data you're matching, and is easier to read.  This won't work however, if you know some Col tags won't have just digits in them

You may want to refer to this neat interactive Regex tutorial for practice with regex's.

You also may want to refer to the Java documentation for Regex patterns, this is useful when you need special characters.


问:
Getting the next item in a python for loop
I have an HTML object that contains a list if an 'X' is found I want to print the x and the next item in the list:

```<code>for string in tr[30].strings:
      if string == 'X':
              print(string)
              print(string.next())
</code>```

Getting error:

TypeError: 'NavigableString' object is not callable

答:
Try this:

```<code>theIterator = iter(tr[30].strings)

for string in theIterator:
      if string == 'X':
              print(string)
              print(next(theIterator))
</code>```

But be aware that manipulating the iterator of a running for-loop is not recommend.

Body:
I have an HTML object that contains a list if an 'X' is found I want to print the x and the next item in the list:

for string in tr[30].strings:
      if string == 'X':
              print(string)
              print(string.next())

Getting error:

TypeError: 'NavigableString' object is not callable

Body:
Try this:

theIterator = iter(tr[30].strings)

for string in theIterator:
      if string == 'X':
              print(string)
              print(next(theIterator))

But be aware that manipulating the iterator of a running for-loop is not recommend.


问:
When to use a pipe in Angular
Is there any rule, or best practice to tell when a pipe is best over a component method ?

Maybe something like, when something is purly a view logic and doesn't contain any domain logic

答:
A Pipe takes in data as Input and Transforms it to a desired Output.

For example, in most use cases, users prefer to see a Date in a simple format like April 15, 1988 rather than the raw string format Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time), this format for showing just birth date is ugly and you can beatify this by Pipes.

Fri Apr 15 1988 00:00:00 GMT-0700 convert to April 15, 1988

Title: When to use a pipe in Angular