问:
How to read text from a file, identify adjacent duplicated words, and report their location in the text file?
I am trying to read a quote from a text file and find any duplicated words that appear next to each other. The following is the quote:

```<code>"He that would make his own liberty liberty secure,

must guard even his enemy from oppression;

for for if he violates this duty, he

he establishes a precedent that will reach to himself."
-- Thomas Paine
</code>```

The output should be the following:

Found word: "Liberty" on line 1

Found word: "for" on line 3

Found word: "he" on line 4

I have written the code to read the text from the file but I am having trouble with the code to identify the duplicates. I have tried enumerating each word in the file and checking if the word at one index is equal to the the word at the following index. However, I am getting an index error because the loop continues outside of the index range. Here's what I've come up with so far:

```<code>import string
file_str = input("Enter file name: ")
input_file = open(file_str, 'r')

word_list = []
duplicates = []

for line in input_file:
    line_list = line_str.split()
    for word in line_list:
        if word != "--":
            word_list.append(word)

for idx, word in enumerate(word_list):
    print(idx, word)
    if word_list[idx] == word_list[idx + 1]:
        duplicates.append(word)
</code>```

Any help with the current method I'm trying would be appreciated, or suggestions for another method.

答:
Here's another approach.

```<code>from itertools import tee, izip
from collections import defaultdict

dups = defaultdict(set)
with open('file.txt') as f:
    for no, line in enumerate(f, 1):
        it1, it2 = tee(line.split())
        next(it2, None)
        for word, follower in izip(it1, it2):
            if word != '--' and word == follower:
                dups[no].add(word)
</code>```

which yields

```<code>>>> dups
defaultdict(<type 'set'>, {1: set(['liberty']), 3: set(['for'])})
</code>```

which is a dictionary which holds a set of pair-duplicates for each line, e.g.

```<code>>>> dups[3]
set(['for'])
</code>```

(I don't know why you expect "he" to be found on line four, it is certainly not doubled in your sample file.)

Body:
I am trying to read a quote from a text file and find any duplicated words that appear next to each other. The following is the quote:

"He that would make his own liberty liberty secure,

must guard even his enemy from oppression;

for for if he violates this duty, he

he establishes a precedent that will reach to himself."
-- Thomas Paine

The output should be the following:

Found word: "Liberty" on line 1

Found word: "for" on line 3

Found word: "he" on line 4

I have written the code to read the text from the file but I am having trouble with the code to identify the duplicates. I have tried enumerating each word in the file and checking if the word at one index is equal to the the word at the following index. However, I am getting an index error because the loop continues outside of the index range. Here's what I've come up with so far:

import string
file_str = input("Enter file name: ")
input_file = open(file_str, 'r')

word_list = []
duplicates = []

for line in input_file:
    line_list = line_str.split()
    for word in line_list:
        if word != "--":
            word_list.append(word)

for idx, word in enumerate(word_list):
    print(idx, word)
    if word_list[idx] == word_list[idx + 1]:
        duplicates.append(word)

Any help with the current method I'm trying would be appreciated, or suggestions for another method.

Body:
Here's another approach.

from itertools import tee, izip
from collections import defaultdict

dups = defaultdict(set)
with open('file.txt') as f:
    for no, line in enumerate(f, 1):
        it1, it2 = tee(line.split())
        next(it2, None)
        for word, follower in izip(it1, it2):
            if word != '--' and word == follower:
                dups[no].add(word)

which yields

>>> dups
defaultdict(<type 'set'>, {1: set(['liberty']), 3: set(['for'])})

which is a dictionary which holds a set of pair-duplicates for each line, e.g.

>>> dups[3]
set(['for'])

(I don't know why you expect "he" to be found on line four, it is certainly not doubled in your sample file.)


来源: stackexchange

问:
Block all traffic to all possible sub domains on RHEL?
I am running into a problem. Essentially, my company uses a security software suit that performs a query against its main servers to check for the latest updates. However, our environment this host is on has no internet access, by design, for a specific customer for security purposes. Every time this software tries to "phone home", we get a security alert from our security team because its trying to query/search for home when its not supposed to.

The main problem, is that the FQDNs it searches for are based on an MD5 hash, so its a different subdomain every time, so the first time it might be like, 5215-af.domain.com, the second time it will be like gz5q-fjs.domain.com. So I cant just do a simple edit of the /etc/hosts file.

So, how do I go about blocking a domain and all possible subdomains? I want to route everything back to the local host, because the DNS server itself is what sets off the alarm, and the host still needs the DNS server to tell it about local things (its in a cloud environment so new hosts spin up all the time so I need DNS)

答:
Not the perfect solution, but you could give a try to the string match of iptables,

```<code>     iptables -t nat -A OUTPUT -p udp --dport 53 \
     -m string --hex-string "domain|03|com" --algo bm \
     -j REDIRECT

     iptables -t nat -A OUTPUT -p tcp --dport 53 \
     -m string --hex-string "domain|03|com" --algo bm \
     -j REDIRECT
</code>```

This rules redirect the DNS petitions for any subdomain "domain.com" to localhost, the number between bars is the lenght of the string that follows instead of fullstops as DNS protocol encodes strings.

ContentLicense: CC BY-SA 3.0

Body:
Not the perfect solution, but you could give a try to the string match of iptables,

     iptables -t nat -A OUTPUT -p udp --dport 53 \
     -m string --hex-string "domain|03|com" --algo bm \
     -j REDIRECT

     iptables -t nat -A OUTPUT -p tcp --dport 53 \
     -m string --hex-string "domain|03|com" --algo bm \
     -j REDIRECT

This rules redirect the DNS petitions for any subdomain "domain.com" to localhost, the number between bars is the lenght of the string that follows instead of fullstops as DNS protocol encodes strings.


问:
java.lang.ClassNotFoundException: Didn't find class ... on path: DexPathList
I am making an android project game which I recently added some libraries to this project, and since I did I get the same error:

```<code>dex2oat : Failed to create oat file: /data/dalvik-cache/arm/data@app@***.*******.*************-2@base.apk@classes.dex: Permission denied
    java.lang.ClassNotFoundException: Didn't find class "***.*******.*************.MainActivity" on path: DexPathList[[zip file "/data/app/***.*******.*************-1/base.apk"],nativeLibraryDirectories=[/data/app/***.*******.*************-1/lib/arm, /vendor/lib, /system/lib]]
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3132)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:148)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:7325)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
03-25 10:34:07.084 15904 15904 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.compgal.stealthsmiley.MainActivity" on path: DexPathList[[zip file "/data/app/com.compgal.stealthsmiley-1/base.apk"],nativeLibraryDirectories=[/data/app/com.compgal.stealthsmiley-1/lib/arm, /vendor/lib, /system/lib]]
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.Instrumentation.newActivity(Instrumentation.java:1096)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        ... 9 more
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        Suppressed: java.io.IOException: Failed to open dex files from /data/app/com.compgal.stealthsmiley-1/base.apk
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexFile.openDexFileNative(Native Method)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexFile.openDexFile(DexFile.java:295)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexFile.<init>(DexFile.java:80)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexFile.<init>(DexFile.java:59)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexPathList.loadDexFile(DexPathList.java:279)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexPathList.makePathElements(DexPathList.java:248)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexPathList.<init>(DexPathList.java:120)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:48)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:65)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:86)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:47)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.LoadedApk.getClassLoader(LoadedApk.java:438)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.LoadedApk.makeApplication(LoadedApk.java:663)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6395)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ActivityThread.access$1800(ActivityThread.java:229)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1887)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                ... 6 more
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        Suppressed: java.lang.ClassNotFoundException: ***.*******.*************.MainActivity
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at java.lang.Class.classForName(Native Method)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                ... 12 more
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
</code>```

I believe I should say that all the projects / library projects are using the same target "android-23". I have checked all the answers on StackOverflow and other websites and could'nt find any answer that solved my problem.
Thanks for helping!

EDIT

The project is written on Netbeans IDE framework, not on android studio and the project isnt using gradle.
here is the AndroidManifest.xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="***.*******.*************"
          android:versionCode="7"
          android:versionName="1.5">
    <application android:label="@string/app_name" android:icon="@drawable/icon"
    >
        <meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
        <activity
            android:screenOrientation="landscape"
            android:name="MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>
</code>```

EDIT #2

After a little bit of digging it seems like there is a problem with the dex2oat trying to create oat file:

```<code>dex2oat : Failed to create oat file: /data/dalvik-cache/arm/data@app@***.*******.*************-2@base.apk@classes.dex: Permission denied
</code>```

I have no idea what to do now.
Referenced libraries: Google Play Services and Android Support v13.
If I remove the libraries the project works fine... so what is the problem?

答:
Alright, so after a long time of searching it turns out the problem was with the sdk manager of android - I downloaded all the build tools when I only had to download one.
So I deleted all the unnecessary packages and the project is now working fine.
Thanks for those who tried to help!</p>

Body:
I am making an android project game which I recently added some libraries to this project, and since I did I get the same error:

dex2oat : Failed to create oat file: /data/dalvik-cache/arm/data@app@***.*******.*************-2@base.apk@classes.dex: Permission denied
    java.lang.ClassNotFoundException: Didn't find class "***.*******.*************.MainActivity" on path: DexPathList[[zip file "/data/app/***.*******.*************-1/base.apk"],nativeLibraryDirectories=[/data/app/***.*******.*************-1/lib/arm, /vendor/lib, /system/lib]]
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3132)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.os.Handler.dispatchMessage(Handler.java:102)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.os.Looper.loop(Looper.java:148)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.main(ActivityThread.java:7325)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at java.lang.reflect.Method.invoke(Native Method)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
03-25 10:34:07.084 15904 15904 E AndroidRuntime: Caused by: java.lang.ClassNotFoundException: Didn't find class "com.compgal.stealthsmiley.MainActivity" on path: DexPathList[[zip file "/data/app/com.compgal.stealthsmiley-1/base.apk"],nativeLibraryDirectories=[/data/app/com.compgal.stealthsmiley-1/lib/arm, /vendor/lib, /system/lib]]
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.Instrumentation.newActivity(Instrumentation.java:1096)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        ... 9 more
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        Suppressed: java.io.IOException: Failed to open dex files from /data/app/com.compgal.stealthsmiley-1/base.apk
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexFile.openDexFileNative(Native Method)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexFile.openDexFile(DexFile.java:295)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexFile.<init>(DexFile.java:80)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexFile.<init>(DexFile.java:59)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexPathList.loadDexFile(DexPathList.java:279)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexPathList.makePathElements(DexPathList.java:248)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.DexPathList.<init>(DexPathList.java:120)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:48)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:65)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:86)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:47)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.LoadedApk.getClassLoader(LoadedApk.java:438)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.LoadedApk.makeApplication(LoadedApk.java:663)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6395)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ActivityThread.access$1800(ActivityThread.java:229)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1887)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                ... 6 more
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        Suppressed: java.lang.ClassNotFoundException: ***.*******.*************.MainActivity
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at java.lang.Class.classForName(Native Method)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
03-25 10:34:07.084 15904 15904 E AndroidRuntime:                ... 12 more
03-25 10:34:07.084 15904 15904 E AndroidRuntime:        Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available

I believe I should say that all the projects / library projects are using the same target "android-23". I have checked all the answers on StackOverflow and other websites and could'nt find any answer that solved my problem.
Thanks for helping!

EDIT

The project is written on Netbeans IDE framework, not on android studio and the project isnt using gradle.
here is the AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="***.*******.*************"
          android:versionCode="7"
          android:versionName="1.5">
    <application android:label="@string/app_name" android:icon="@drawable/icon"
    >
        <meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
        <activity
            android:screenOrientation="landscape"
            android:name="MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

EDIT #2

After a little bit of digging it seems like there is a problem with the dex2oat trying to create oat file:

dex2oat : Failed to create oat file: /data/dalvik-cache/arm/data@app@***.*******.*************-2@base.apk@classes.dex: Permission denied

I have no idea what to do now.
Referenced libraries: Google Play Services and Android Support v13.
If I remove the libraries the project works fine... so what is the problem?


问:
Converting Curl to a Request in Python
I am trying to work out how to convert curl request to python, but I am not 100% sure what is what. How do you pull apart a curl request so it will work with a pyhton request (I would prefer not use any 3rd party packages)

```<code>curl -i -XPOST 'http://10.16.1.35:8086/write?db=maintenance' --data-binary 'temperature,pi=Raspberry,sensor=Blue value=64.50 1490643440916250112'
</code>```

and

```<code>curl -i -XPOST 'http://localhost:8086/write?db=mydb' --data-binary @cpu_data.txt
</code>```

I don't understand what elements in here are what so I can convert the request.

Thankyou!

答:
I believe you can do this in two ways.

Using pycurl library which acts like an interface to cURL library. You can take a look at the documentation here

You can send a http request with content type, header and parameters using the requests library for python. You can take a look at their documentation here.

I hope this helps.

Title: Converting Curl to a Request in Python

Body:
I am trying to work out how to convert curl request to python, but I am not 100% sure what is what. How do you pull apart a curl request so it will work with a pyhton request (I would prefer not use any 3rd party packages)

curl -i -XPOST 'http://10.16.1.35:8086/write?db=maintenance' --data-binary 'temperature,pi=Raspberry,sensor=Blue value=64.50 1490643440916250112'

and

curl -i -XPOST 'http://localhost:8086/write?db=mydb' --data-binary @cpu_data.txt

I don't understand what elements in here are what so I can convert the request.

Thankyou!


问:
how to debug the code which is hang
I have a multithreaded code which is hang in some case. I want to know what's the recommended way to debug?</p>

答: Because it is multi-threaded, you can't debug such as setting breakpoints, trace the statements and pause to see the values of the variables.  The only way in my opinion is to print to the console and see the status from there.</p>

ContentLicense: CC BY-SA 2.5

Title: how to debug the code which is hang


问:
determine effective permission source In Active directory
How can I determine the source of a permission?

A user, from the root of the domain has write permission to all group objects and their properties. I can see this access in the effective permissions but I can't tell where it comes from.

Access in the ACLS shows accounts and groups with access but I can't figure out where this access is coming from.

Here's what I've tried

```<code>dsacls dc=contoso,dc=org|findstr "username"
</code>```

but it doesn't do anything.

```<code>get-acl AD:dc=contoso,dc=org
</code>```

How do you find the source of a user's privileges in Active Directory?

How do you find what the "effective permissions tab used to calculate the access"?

A screenshot of the Advanced Security Settings dialog

答:
Instead of this:

```<code>get-acl AD:dc=contoso,dc=org
</code>```

Could you please try this:

```<code>get-acl "AD:\dc=contoso,dc=org"
</code>```

If you pipe it to Get-Member, you would be able to see all the useful methods for the same. You can directly access them using Dot. That should fulfill your requirement I believe.

```<code>  (Get-Acl (Get-ADUser User).distinguishedname).access | select identityreference, accesscontroltype
</code>```

For Non-inherited users, try the below ; else remove the where condition:

```<code>(Get-ACL "AD:CN=User,OU=Users,DC=Contoso,DC=com").Access | Where {$_.IsInherited -eq $FALSE}| Select IdentityReference,AccessControlType, IsInherited
</code>```

Body:
How can I determine the source of a permission?

A user, from the root of the domain has write permission to all group objects and their properties. I can see this access in the effective permissions but I can't tell where it comes from.

Access in the ACLS shows accounts and groups with access but I can't figure out where this access is coming from.

Here's what I've tried

dsacls dc=contoso,dc=org|findstr "username"

but it doesn't do anything.

get-acl AD:dc=contoso,dc=org

How do you find the source of a user's privileges in Active Directory?

How do you find what the "effective permissions tab used to calculate the access"?

A screenshot of the Advanced Security Settings dialog

Body:
Instead of this:

get-acl AD:dc=contoso,dc=org

Could you please try this:

get-acl "AD:\dc=contoso,dc=org"

If you pipe it to Get-Member, you would be able to see all the useful methods for the same. You can directly access them using Dot. That should fulfill your requirement I believe.

  (Get-Acl (Get-ADUser User).distinguishedname).access | select identityreference, accesscontroltype

For Non-inherited users, try the below ; else remove the where condition:

(Get-ACL "AD:CN=User,OU=Users,DC=Contoso,DC=com").Access | Where {$_.IsInherited -eq $FALSE}| Select IdentityReference,AccessControlType, IsInherited


问:
search a keyword in postgresql json field
I am currently using postgres 9.3.3

Following is how my table looks like -

```<code> Column       |           Type           |                             Modifiers                              | Storage  | Stats target | Description
--------------------+--------------------------+--------------------------------------------------------------------+----------+--------------+-------------
 id                 | integer                  | not null default nextval('playerbase_palyerdata_id_seq'::regclass) | plain    |              |
 date_joined        | timestamp with time zone | not null                                                           | plain    |              |
 belongs_to_camp_id  | integer                  | not null                                                           | plain    |              |
 belongs_to_coach_id | integer                  | not null                                                           | plain    |              |
 json_kvps          | character varying(2000)  | not null                                                           | extended |              |
</code>```

One sample data is as follows -

```<code>id |      date_joined   | belongs_to_camp_id | belongs_to_coach_id | json_kvps

1  | 2014-03-07 18:10:45.824749+05:30 |                 1 |                  1 | {"alumnicode": "2003360009", "emailusername": "aaron@hotmail.com", "altemail": "", "salutation": "Mrs", "fname": "Aaron", "mname": "V", "lname": "Schwartz", "fullname": "Aaraon M Scwartz", "programmename": "MEP", "batchyearin": "2003"}
</code>```

Now I want to search the entire table, and find a user with "emailusername":"aaron@hotmail.com"

As mentioned here -
http://www.postgresql.org/docs/current/static/functions-json.html

I try to write a query as follows -

```<code>SELECT * FROM playerbase_playerdata WHERE json_kvps->>'emailusername' = 'aaron@hotmail.com';
</code>```

I was expecting a column as above, instead I got the following error -

```<code>ERROR:  operator does not exist: character varying ->> unknown
LINE 1: ...ELECT * FROM memberbase_memberdata WHERE json_kvps->>'emailu...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.
</code>```

Could someone please tell me, what am I missing?

答:
For PostgreSQL 9.3 or higher, one possible solution could be using a cast to json:

SELECT * FROM playerbase_playerdata WHERE json_kvps->>'emailusername' = 'aaron@hotmail.com';

SELECT * FROM playerbase_playerdata WHERE CAST(json_kvps AS JSON)->>'emailusername' = 'aaron@hotmail.com';

Body:
I am currently using postgres 9.3.3

Following is how my table looks like -

 Column       |           Type           |                             Modifiers                              | Storage  | Stats target | Description
--------------------+--------------------------+--------------------------------------------------------------------+----------+--------------+-------------
 id                 | integer                  | not null default nextval('playerbase_palyerdata_id_seq'::regclass) | plain    |              |
 date_joined        | timestamp with time zone | not null                                                           | plain    |              |
 belongs_to_camp_id  | integer                  | not null                                                           | plain    |              |
 belongs_to_coach_id | integer                  | not null                                                           | plain    |              |
 json_kvps          | character varying(2000)  | not null                                                           | extended |              |

One sample data is as follows -

id |      date_joined   | belongs_to_camp_id | belongs_to_coach_id | json_kvps

1  | 2014-03-07 18:10:45.824749+05:30 |                 1 |                  1 | {"alumnicode": "2003360009", "emailusername": "aaron@hotmail.com", "altemail": "", "salutation": "Mrs", "fname": "Aaron", "mname": "V", "lname": "Schwartz", "fullname": "Aaraon M Scwartz", "programmename": "MEP", "batchyearin": "2003"}

Now I want to search the entire table, and find a user with "emailusername":"aaron@hotmail.com"

As mentioned here -
http://www.postgresql.org/docs/current/static/functions-json.html

I try to write a query as follows -

SELECT * FROM playerbase_playerdata WHERE json_kvps->>'emailusername' = 'aaron@hotmail.com';

I was expecting a column as above, instead I got the following error -

ERROR:  operator does not exist: character varying ->> unknown
LINE 1: ...ELECT * FROM memberbase_memberdata WHERE json_kvps->>'emailu...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Could someone please tell me, what am I missing?


问:
How to update SSRS Subscription through metadata (Database)
Please help me to update all SSRS Subscriptions once using SQL Server database.

I appreciate your help.

Thanks!

答: You might want to look into Data Driven Subscriptions if you have enterprise edition. That way you can save and change values within a table vs having to touch the SSRS database.</p>


问:
functions with different names but same arguments
I have a set of functions with the same number of arguments, but different names (suppose each implement different method). I have the name of the requested method in a string. Is it possible to call the corresponding function using the method name. to make it clear, suppose that I have the following function (I just mentioned their name and argument):

```<code>search_esa(int a, int b);
search_tss(int a, int b);
search_fss(int a, int b);
search_ds(int a, int b);
</code>```

now lets assume I have the name of the requested method, lets assume esa, in a string:

```<code>string methodName = "esa"
</code>```

is it possible to call the corresponding function by using macros?
I tested

```<code>#define CALL_SEARCH_MV(method) search_##method
</code>```

and then try to call it by:

```<code>CALL_SEARCH_MV(methodName.c_str())
</code>```

but it calls search_methodName function, which does not exist. Any other suggestions would be greatly appreciated (except suggesting switch case method or if).

答:
You can store function pointers in containers. So you can map pretty much anything. The syntax is pretty simple:

```<code>#include <iostream>
#include <map>
using namespace std;

int f1(int a, int b) { return a+b; }
int f2(int a, int b) { return a*b; }

int main() {
    int x = 5;
    int y = 3;
    map<string, int(*)(int, int)> f;

    f["add"] = &f1;
    f["mul"] = &f2;

    cout << f["add"](x,y) << "\n";
    cout << f["mul"](x,y) << "\n";
    return 0;
}
</code>```

Live: http://ideone.com/wLjw1i.

So you can store any function with matching signature (+return type). This is a the expense of one indirection. The means they are harder to be optimized, because the jump target is set in the run time.

You can make it a bit more general using std::function, again at slight performance expense.

Body:
I have a set of functions with the same number of arguments, but different names (suppose each implement different method). I have the name of the requested method in a string. Is it possible to call the corresponding function using the method name. to make it clear, suppose that I have the following function (I just mentioned their name and argument):

search_esa(int a, int b);
search_tss(int a, int b);
search_fss(int a, int b);
search_ds(int a, int b);

now lets assume I have the name of the requested method, lets assume esa, in a string:

string methodName = "esa"

is it possible to call the corresponding function by using macros?
I tested

#define CALL_SEARCH_MV(method) search_##method

and then try to call it by:

CALL_SEARCH_MV(methodName.c_str())

but it calls search_methodName function, which does not exist. Any other suggestions would be greatly appreciated (except suggesting switch case method or if).

Body:
You can store function pointers in containers. So you can map pretty much anything. The syntax is pretty simple:

#include <iostream>
#include <map>
using namespace std;

int f1(int a, int b) { return a+b; }
int f2(int a, int b) { return a*b; }

int main() {
    int x = 5;
    int y = 3;
    map<string, int(*)(int, int)> f;

    f["add"] = &f1;
    f["mul"] = &f2;

    cout << f["add"](x,y) << "\n";
    cout << f["mul"](x,y) << "\n";
    return 0;
}

Live: http://ideone.com/wLjw1i.

So you can store any function with matching signature (+return type). This is a the expense of one indirection. The means they are harder to be optimized, because the jump target is set in the run time.

You can make it a bit more general using std::function, again at slight performance expense.


问:
Doesn't show scroll in JScrollPane with JTable after Upgrade Java 7 to Java 8
I've to upgrade project to Java 8. After running my application, scroll from JScrollPane doesn't show. Same piece of code works in Java 7 and everything is ok.

```<code>public static void main(String[] a){
    JPanel contentPane = new JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
    contentPane.setLayout(new javax.swing.BoxLayout(contentPane, javax.swing.BoxLayout.Y_AXIS));

    JPanel aggregates = new JPanel("Aggregates", new Insets(40, 0, 0, 0));
    GridBagConstraints gbc_aggregates = new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, 1, new Insets(10, 10, 10, 10), 0, 0);
    gbl_panel.setConstraints(aggregates, gbc_aggregates);

    GridBagLayout gbl_agregats = new GridBagLayout();
    addParametersLayout(gbl_agregats, new int[]{0,0,0}, new int[]{0, 0},new double[]{ 0.0, 0.0, Double.MIN_VALUE}, new double[]{0.0, Double.MIN_VALUE} );
    aggregates.setLayout(gbl_agregats);

    JTable table = new JTable(new MyTableModel(null));
    table.setPreferredSize(new Dimension(850, Const.rowHeight));

    JScrollPane scrollPane = new JScrollPane(table);
    table.setPreferredScrollableViewportSize(new Dimension(850, 10 *Const.rowHeight));
    GridBagConstraints gbc_scrollPane= new GridBagConstraints(0, 1, 3, 1, 0.0, 0.0, GridBagConstraints.WEST, 1, new Insets(5, 5, 20, 5), 0, 0);
    gbl_agregats.setConstraints(scrollPane, gbc_scrollPane);
    aggregates.add(scrollPane);

    JPanel main_panel = new JPanel();
    main_panel.add(aggregates);

    JScrollPane scrPane = new JScrollPane(main_panel);
    scrPane.getVerticalScrollBar().setUnitIncrement(16);
    scrPane.setBorder(BorderFactory.createEmptyBorder());
    scrPane.getInsets().set(0, 0, 0, 0);
    contentPane.add(scrPane);
    setContentPane(contentPane);
}

public static void addParametersLayout(GridBagLayout gbl,
int[] columnWidths, int[] rowHeights, double[] columnWeights,
double[] rowWeights) {
    gbl.columnWidths = columnWidths;
    gbl.rowHeights = rowHeights;
    gbl.columnWeights = columnWeights;
    gbl.rowWeights = rowWeights;
}
</code>```

Question: What was changed in Java 8 ? Why same scroll looks ok in older Java version ?

Edited:

Maybe i'm not too specific.
When i compile my project i see something like that (just bar):

I can scroll my table because it's working, but it's invisible (i see just a bar).

答:
```<code>          import java.awt.Color;
          import java.awt.Dimension;
          import java.awt.GridBagConstraints;
          import java.awt.GridBagLayout;
          import java.awt.Insets;
          import java.awt.LayoutManager;
          import javax.swing.BorderFactory;
          import javax.swing.JPanel;
          import javax.swing.JScrollPane;
          import javax.swing.JTab
          import javax.swing.border.EmptyBorder;

          public class source8 {

          public static void main(String[] a){
          JPanel contentPane = new JPanel();
          contentPane.setBackground(Color.WHITE);
          contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
          contentPane.setLayout(new javax.swing.BoxLayout(contentPane,

          javax.swing.BoxLayout.Y_AXIS));

          JPanel aggregates = new JPanel((LayoutManager) new Insets(40, 0,0,
          0));
          GridBagConstraints gbc_aggregates = new GridBagConstraints(0, 2,
          1, 1, 0.0, 0.0, GridBagConstraints.WEST, 1, new Insets(10, 10, 10,
          10), 0, 0);
          GridBagLayout gbl_panel = new GridBagLayout();

          gbl_panel.setConstraints(aggregates, gbc_aggregates);

          GridBagLayout gbl_agregats = new GridBagLayout();
          addParametersLayout(gbl_agregats, new int[]{0,0,0}, new int[]{0,
          0},new double[]{ 0.0, 0.0, Double.MIN_VALUE}, new double[]{0.0,
          Double.MIN_VALUE} );
          aggregates.setLayout(gbl_agregats);

          JTable table = new JTable(new MyTableModel(null));
          table.setPreferredSize(new Dimension(850, Const.rowHeight));

          JScrollPane scrollPane = new JScrollPane(table);
          table.setPreferredScrollableViewportSize(new Dimension(850, 10
          *Const.rowHeight));
          GridBagConstraints gbc_scrollPane= new GridBagConstraints(0, 1, 3,
          1, 0.0, 0.0, GridBagConstraints.WEST, 1, new Insets(5, 5, 20, 5),
          0, 0);
          gbl_agregats.setConstraints(scrollPane, gbc_scrollPane);
          aggregates.add(scrollPane);

          JPanel main_panel = new JPanel();
          main_panel.add(aggregates);

          JScrollPane scrPane = new JScrollPane(main_panel);
          scrPane.getVerticalScrollBar().setUnitIncrement(16);
          scrPane.setBorder(BorderFactory.createEmptyBorder());
          scrPane.getInsets().set(0, 0, 0, 0);
          contentPane.add(scrPane);
          setContentPane(contentPane);
          }

          public static void addParametersLayout(GridBagLayout gbl,
          int[] columnWidths, int[] rowHeights, double[] columnWeights,
          double[] rowWeights) {
          gbl.columnWidths = columnWidths;
          gbl.rowHeights = rowHeights;
          gbl.columnWeights = columnWeights;
          gbl.rowWeights = rowWeights;
          }

          private static void setContentPane(JPanel contentPane) {
          throw new UnsupportedOperationException("Not supported yet.");
          //To change body of generated methods, choose Tools | Templates.
          }
           }
</code>```

some change in code hope it works for you §§thanks

Body:
I've to upgrade project to Java 8. After running my application, scroll from JScrollPane doesn't show. Same piece of code works in Java 7 and everything is ok.

public static void main(String[] a){
    JPanel contentPane = new JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
    contentPane.setLayout(new javax.swing.BoxLayout(contentPane, javax.swing.BoxLayout.Y_AXIS));

    JPanel aggregates = new JPanel("Aggregates", new Insets(40, 0, 0, 0));
    GridBagConstraints gbc_aggregates = new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, 1, new Insets(10, 10, 10, 10), 0, 0);
    gbl_panel.setConstraints(aggregates, gbc_aggregates);

    GridBagLayout gbl_agregats = new GridBagLayout();
    addParametersLayout(gbl_agregats, new int[]{0,0,0}, new int[]{0, 0},new double[]{ 0.0, 0.0, Double.MIN_VALUE}, new double[]{0.0, Double.MIN_VALUE} );
    aggregates.setLayout(gbl_agregats);

    JTable table = new JTable(new MyTableModel(null));
    table.setPreferredSize(new Dimension(850, Const.rowHeight));

    JScrollPane scrollPane = new JScrollPane(table);
    table.setPreferredScrollableViewportSize(new Dimension(850, 10 *Const.rowHeight));
    GridBagConstraints gbc_scrollPane= new GridBagConstraints(0, 1, 3, 1, 0.0, 0.0, GridBagConstraints.WEST, 1, new Insets(5, 5, 20, 5), 0, 0);
    gbl_agregats.setConstraints(scrollPane, gbc_scrollPane);
    aggregates.add(scrollPane);

    JPanel main_panel = new JPanel();
    main_panel.add(aggregates);

    JScrollPane scrPane = new JScrollPane(main_panel);
    scrPane.getVerticalScrollBar().setUnitIncrement(16);
    scrPane.setBorder(BorderFactory.createEmptyBorder());
    scrPane.getInsets().set(0, 0, 0, 0);
    contentPane.add(scrPane);
    setContentPane(contentPane);
}

public static void addParametersLayout(GridBagLayout gbl,
int[] columnWidths, int[] rowHeights, double[] columnWeights,
double[] rowWeights) {
    gbl.columnWidths = columnWidths;
    gbl.rowHeights = rowHeights;
    gbl.columnWeights = columnWeights;
    gbl.rowWeights = rowWeights;
}

Question: What was changed in Java 8 ? Why same scroll looks ok in older Java version ?

Edited:

Maybe i'm not too specific.
When i compile my project i see something like that (just bar):

I can scroll my table because it's working, but it's invisible (i see just a bar).

Body:
          import java.awt.Color;
          import java.awt.Dimension;
          import java.awt.GridBagConstraints;
          import java.awt.GridBagLayout;
          import java.awt.Insets;
          import java.awt.LayoutManager;
          import javax.swing.BorderFactory;
          import javax.swing.JPanel;
          import javax.swing.JScrollPane;
          import javax.swing.JTab
          import javax.swing.border.EmptyBorder;

          public class source8 {

          public static void main(String[] a){
          JPanel contentPane = new JPanel();
          contentPane.setBackground(Color.WHITE);
          contentPane.setBorder(new EmptyBorder(0, 0, 0, 0));
          contentPane.setLayout(new javax.swing.BoxLayout(contentPane,

          javax.swing.BoxLayout.Y_AXIS));

          JPanel aggregates = new JPanel((LayoutManager) new Insets(40, 0,0,
          0));
          GridBagConstraints gbc_aggregates = new GridBagConstraints(0, 2,
          1, 1, 0.0, 0.0, GridBagConstraints.WEST, 1, new Insets(10, 10, 10,
          10), 0, 0);
          GridBagLayout gbl_panel = new GridBagLayout();

          gbl_panel.setConstraints(aggregates, gbc_aggregates);

          GridBagLayout gbl_agregats = new GridBagLayout();
          addParametersLayout(gbl_agregats, new int[]{0,0,0}, new int[]{0,
          0},new double[]{ 0.0, 0.0, Double.MIN_VALUE}, new double[]{0.0,
          Double.MIN_VALUE} );
          aggregates.setLayout(gbl_agregats);

          JTable table = new JTable(new MyTableModel(null));
          table.setPreferredSize(new Dimension(850, Const.rowHeight));

          JScrollPane scrollPane = new JScrollPane(table);
          table.setPreferredScrollableViewportSize(new Dimension(850, 10
          *Const.rowHeight));
          GridBagConstraints gbc_scrollPane= new GridBagConstraints(0, 1, 3,
          1, 0.0, 0.0, GridBagConstraints.WEST, 1, new Insets(5, 5, 20, 5),
          0, 0);
          gbl_agregats.setConstraints(scrollPane, gbc_scrollPane);
          aggregates.add(scrollPane);

          JPanel main_panel = new JPanel();
          main_panel.add(aggregates);

          JScrollPane scrPane = new JScrollPane(main_panel);
          scrPane.getVerticalScrollBar().setUnitIncrement(16);
          scrPane.setBorder(BorderFactory.createEmptyBorder());
          scrPane.getInsets().set(0, 0, 0, 0);
          contentPane.add(scrPane);
          setContentPane(contentPane);
          }

          public static void addParametersLayout(GridBagLayout gbl,
          int[] columnWidths, int[] rowHeights, double[] columnWeights,
          double[] rowWeights) {
          gbl.columnWidths = columnWidths;
          gbl.rowHeights = rowHeights;
          gbl.columnWeights = columnWeights;
          gbl.rowWeights = rowWeights;
          }

          private static void setContentPane(JPanel contentPane) {
          throw new UnsupportedOperationException("Not supported yet.");
          //To change body of generated methods, choose Tools | Templates.
          }
           }

some change in code hope it works for you §§thanks


问:
Two floats throw TypeError: unsupported operand type(s) for +: 'float' and 'str'
I am running into an issue with the following line of code:

underground['distributed_load_C'] = float(ugLineList[21])*1000 + ('+' if float(ugLineList[24]) >= 0.0 else '-') + abs(float(ugLineList[24]))*1000j

The original values pulled from ugLineList are strings and I try to type cast them into floats before addition. Even though I try to type cast them I am getting the following error:

TypeError: unsupported operand type(s) for +: 'float' and 'str'

I've tried type casting them before this statement, and checking that the code snippets are truly floats:
print type(float(ugLineList[21])*1000), type(float(ugLineList[24]))
---> <type 'float'> <type 'float'>

I am really confused as to what is going on here so any help is greatly appreciated.

Thanks!!

答:
It looks like you have strings while trying to do an aritmetic operation

```<code>+ ('+' if float(ugLineList[24]) >= 0.0 else '-')
</code>```

like '+'

do you really need the condition? '+' if float(ugLineList[24]) >= 0.0

try yo cast individual variales and do the operations with them before put all in one line

Body:
It looks like you have strings while trying to do an aritmetic operation

+ ('+' if float(ugLineList[24]) >= 0.0 else '-')

like '+'

do you really need the condition? '+' if float(ugLineList[24]) >= 0.0

try yo cast individual variales and do the operations with them before put all in one line


问:
what's the meaning of "#define __cdecl" in my C++ code?
I'm working on an existing c++ project with visual studio, and I found out that almost every function declaration gets a __cdecl in front of the function name, like:void __cdecl functionName(). Then I jump to the definition of __cdecl, which locates in the winnt.h file:

```<code>#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
#define NTAPI __stdcall
#else
#define _cdecl
#define __cdecl
#define NTAPI
#endif
</code>```

I've searched cdecl and got that it's the default calling convention for C and C++ programs, but code above tells me that __cdecl extends to nothing. So why place a __cdecl before function name as it's just nothing ? or did I misunderstand the code above?

答:
It means that if an API is defined as using NTAPI it will generate code that uses the __stdcall calling convention - a variation of the Pascal calling convention in which the callee cleans the stack.  With __cdecl, the caller cleans the stack (so it supports variadic type functions).

And all of this is conditional on the #if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)

ContentLicense: CC BY-SA 4.0

Body:
I'm working on an existing c++ project with visual studio, and I found out that almost every function declaration gets a __cdecl in front of the function name, like:void __cdecl functionName(). Then I jump to the definition of __cdecl, which locates in the winnt.h file:

#if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED)
#define NTAPI __stdcall
#else
#define _cdecl
#define __cdecl
#define NTAPI
#endif

I've searched cdecl and got that it's the default calling convention for C and C++ programs, but code above tells me that __cdecl extends to nothing. So why place a __cdecl before function name as it's just nothing ? or did I misunderstand the code above?


问:
SSH to a server and have session running with all commands executed to have them saved in local file
I basically want to SSH to a server and then the commands executed in a server and its outputs be saved into a local file. I thought below one would save the output to a file but is exiting once commands are executed *i can understand its done with its execution so its exiting but i do not wish to exit unless i exit from the server

SSH to server via script

Save the output of all execution in server in local file

Come out , if exit found

Here is the basic code:

#! /usr/bin/bash

ssh user@server > file.log << EOF

pwd;hostname;

EOF

答:
If you're just trying to save the output of an interactive SSH session, do this:

```<code>ssh userid@server | tee logfile
</code>```

Your example implies that you want to run some commands (pwd, hostname) from your shell script, and then keep the ssh connection open for interactive use.  I'd suggest instead adding those commands to your login script on the server (.profile or whatever.)

If you really want to use your method, take a look at https://unix.stackexchange.com/questions/103885/piping-data-to-a-processs-stdin-without-causing-eof-afterward

Body:
If you're just trying to save the output of an interactive SSH session, do this:

ssh userid@server | tee logfile

Your example implies that you want to run some commands (pwd, hostname) from your shell script, and then keep the ssh connection open for interactive use.  I'd suggest instead adding those commands to your login script on the server (.profile or whatever.)

If you really want to use your method, take a look at https://unix.stackexchange.com/questions/103885/piping-data-to-a-processs-stdin-without-causing-eof-afterward


问:
Regex for links in html text
I hope this question is not a RTFM one.
I am trying to write a Python script that extracts links from a standard HTML webpage (the <link href... tags).
I have searched the web for matching regexen and found many different patterns. Is there any agreed, standard regex to match links?

Adam

UPDATE:
I am actually looking for two different answers:

What's the library solution for parsing HTML links. Beautiful Soup seems to be a good solution (thanks, Igal Serban and cletus!)

Can a link be defined using a regex?

答: Regexes with HTML get messy.  Just use a DOM parser like Beautiful Soup.</p>

OwnerDisplayName: Udi Pasmon

Title: Regex for links in html text

LastEditorDisplayName: Udi Pasmon

OwnerDisplayName: cletus


问:
Why is the gets function so dangerous that it should not be used?
When I try to compile C code that uses the gets() function with GCC, I get this warning:

(.text+0x34): warning: the `gets' function is dangerous and should not be used.

I remember this has something to do with stack protection and security, but I'm not sure exactly why.

How can I remove this warning and why is there such a warning about using gets()?

If gets() is so dangerous then why can't we remove it?

答:
fgets.

To read from the stdin:

```<code>char string[512];

fgets(string, sizeof(string), stdin); /* no buffer overflows here, you're safe! */
</code>```

Body:
fgets.

To read from the stdin:

char string[512];

fgets(string, sizeof(string), stdin); /* no buffer overflows here, you're safe! */


问:
Can I store an object constructor into an array or hashtable?
Let's say I have a class Foo and another class Bar that both extends from a superclass Foobar, each one with it's own  constructor.

So, I want to make an application in Java 8 that let's a user choose from a list of objects to implement, and add them to a list —I was thinking of using an array or hashtable—, in this case I want to show a message like:

```<code>Choose an object of the following list:
 [1] Foo
 [2] Bar
</code>```

The idea is to let the user create multiple instances of such classes and add them to an array. For example, if the user chooses 1, I want to assign a variable with a[0] = new Foo(), and then if he chooses 2, a[1] = new Bar(), but then, if the user chooses 1 again, then a[2] should be a new instance of Foo. My first idea was to initialize an array with the constructors like:

```<code>anArray[1] = new Foo();
anArray[2] = new Bar();
</code>```

The problem with that implementation is that if I call a[0] = anArray[1] and then a[1] = anArray[1], then a[0]and a[1] would be the same object.

What I am looking for is if there is a way of creating an undefined number of instances of each object without having to implement it as a chain of if else (because in reality I have more than 2 type of objects). I was thinking of using an array or a hashtable, but I don't know if there is actually a way of doing it.

答:
A select case statement will be most suitable for this.
The problem here is this, unless they have a known superclass except object, they cannot be put in an array.So assuming that i will proceed.
You can do this using java reflection API.
There, you can load and create instance at runtime.
For the array, make a Constructor[]. Study reflection to know what I mean.
This might help you.

Body:
Let's say I have a class Foo and another class Bar that both extends from a superclass Foobar, each one with it's own  constructor.

So, I want to make an application in Java 8 that let's a user choose from a list of objects to implement, and add them to a list —I was thinking of using an array or hashtable—, in this case I want to show a message like:

Choose an object of the following list:
 [1] Foo
 [2] Bar

The idea is to let the user create multiple instances of such classes and add them to an array. For example, if the user chooses 1, I want to assign a variable with a[0] = new Foo(), and then if he chooses 2, a[1] = new Bar(), but then, if the user chooses 1 again, then a[2] should be a new instance of Foo. My first idea was to initialize an array with the constructors like:

anArray[1] = new Foo();
anArray[2] = new Bar();

The problem with that implementation is that if I call a[0] = anArray[1] and then a[1] = anArray[1], then a[0]and a[1] would be the same object.

What I am looking for is if there is a way of creating an undefined number of instances of each object without having to implement it as a chain of if else (because in reality I have more than 2 type of objects). I was thinking of using an array or a hashtable, but I don't know if there is actually a way of doing it.


问:
Cannot filter files using Kendo Upload with rRazor
I saw no information on this topic really, except for info on how to filter files when using the latest Kendo library. So I am posting how I did it for others to use if they need to.</p>

答:
This is Kendo being used in Razor Syntax:

```<code>@(Html.Kendo().Upload()
                      .Name("procfiles")
                      .Async(a => a
                          .Save("SavePF", "AccountEvent", new { id = Model.SeqNum })
                                  .Remove("RemovePF", "AccountEvent", new { id = Model.SeqNum })
                          .AutoUpload(true)

                      ).Files(f =>
                      {
                          if (Model != null && !string.IsNullOrEmpty(Model.ProcedureFile))
                          {
                              f.Add().Name(Path.GetFileName(Model.ProcedureFile));
                          }
                      })
                      .Multiple(false)
                      .ShowFileList(true)
                      .Events(e =>
                      {
                          e.Error("accountEventEditController.uploadProcFileError");
                          e.Select("accountEventEditController.onProcFileUploadSelect");
                          e.Upload("accountEventEditController.onProcFileUpload");
                          e.Success("accountEventEditController.onProcFileSuccess");
                          e.Remove("accountEventEditController.onProcFileRemove");
                          e.Complete("accountEventEditController.onProcFileComplete");
                      })
                    )
</code>```

As you can see, you can hook into the "Select" event. Then I have a .js controller handler file, that executes the following code to filter file types.

```<code>var onChkFileUploadSelect = function (e, type) {

    var files = e.files;
    var acceptedFiles = [".pdf", ".xlsx"];
    var isAcceptedImageFormat = ($.inArray(files[0].extension, acceptedFiles)) != -1;
    console.log(files[0].extension);

     if (!isAcceptedImageFormat) {

        e.preventDefault();

        $(targetErrorControl).fadeIn('slow').delay(3000).fadeOut('slow');
    }
}
</code>```

Hopefully this helps some out there.

Body:
This is Kendo being used in Razor Syntax:

@(Html.Kendo().Upload()
                      .Name("procfiles")
                      .Async(a => a
                          .Save("SavePF", "AccountEvent", new { id = Model.SeqNum })
                                  .Remove("RemovePF", "AccountEvent", new { id = Model.SeqNum })
                          .AutoUpload(true)

                      ).Files(f =>
                      {
                          if (Model != null && !string.IsNullOrEmpty(Model.ProcedureFile))
                          {
                              f.Add().Name(Path.GetFileName(Model.ProcedureFile));
                          }
                      })
                      .Multiple(false)
                      .ShowFileList(true)
                      .Events(e =>
                      {
                          e.Error("accountEventEditController.uploadProcFileError");
                          e.Select("accountEventEditController.onProcFileUploadSelect");
                          e.Upload("accountEventEditController.onProcFileUpload");
                          e.Success("accountEventEditController.onProcFileSuccess");
                          e.Remove("accountEventEditController.onProcFileRemove");
                          e.Complete("accountEventEditController.onProcFileComplete");
                      })
                    )

As you can see, you can hook into the "Select" event. Then I have a .js controller handler file, that executes the following code to filter file types.

var onChkFileUploadSelect = function (e, type) {

    var files = e.files;
    var acceptedFiles = [".pdf", ".xlsx"];
    var isAcceptedImageFormat = ($.inArray(files[0].extension, acceptedFiles)) != -1;
    console.log(files[0].extension);

     if (!isAcceptedImageFormat) {

        e.preventDefault();

        $(targetErrorControl).fadeIn('slow').delay(3000).fadeOut('slow');
    }
}

Hopefully this helps some out there.


问:
Safely dynamically change SQL statement
I have the following method in my class. My goal is basically to find all managers in the database but with the option to limit the sql statement. For example " AND U.username='jake56' or " AND A.firstName='Jake'. I am wondering if this is safe to have the option to add the limits for it is susceptible to SQL injection.

```<code>/**
  * Returns an array of manager Users
  * @param string (optional) $limits - limit the query EX: 'AND U.userId > 7'
  * @return an array of managers with associative arrays
  */
  public function find_all_managers($limits = '') {
    $sql = "SELECT U.*, A.*
     FROM Users U
    JOIN Address A
    ON U.addressId=A.addressId
    WHERE U.role='manager' " . $limits;
    // run the query
    $result = $this->query($query);
    $managers = mysqli_fetch_all($result, MYSQLI_ASSOC);
    return $managers;
  }
</code>```

Is this safe to have that parameter? I was told this method is susceptible for SQL injection but I don't see another way around limiting the query if I want.
For example I might want to $db->find_all_managers(' WHERE A.lastName='smith')

答:
Do this

```<code>public function find_all_managers($limitA = 0,$limitB = 0) {
     //now create the limit part here, if real numbers given
     //if(is_numeric($limitA) and $limitA > 0)
}
</code>```

So know you create the limit and nothing else can be injected.

Title: Safely dynamically change SQL statement

Body:
I have the following method in my class. My goal is basically to find all managers in the database but with the option to limit the sql statement. For example " AND U.username='jake56' or " AND A.firstName='Jake'. I am wondering if this is safe to have the option to add the limits for it is susceptible to SQL injection.

/**
  * Returns an array of manager Users
  * @param string (optional) $limits - limit the query EX: 'AND U.userId > 7'
  * @return an array of managers with associative arrays
  */
  public function find_all_managers($limits = '') {
    $sql = "SELECT U.*, A.*
     FROM Users U
    JOIN Address A
    ON U.addressId=A.addressId
    WHERE U.role='manager' " . $limits;
    // run the query
    $result = $this->query($query);
    $managers = mysqli_fetch_all($result, MYSQLI_ASSOC);
    return $managers;
  }

Is this safe to have that parameter? I was told this method is susceptible for SQL injection but I don't see another way around limiting the query if I want.
For example I might want to $db->find_all_managers(' WHERE A.lastName='smith')

Body:
Do this

public function find_all_managers($limitA = 0,$limitB = 0) {
     //now create the limit part here, if real numbers given
     //if(is_numeric($limitA) and $limitA > 0)
}

So know you create the limit and nothing else can be injected.


问:
Best way to read/parse a untyped binary file in Delphi
I would like to know what is the best way to parse an untyped binary file. For example, a EBML file. (http://ebml.sourceforge.net/). EBML is basically a binary xml file. It can store basically anything, but its predominate use right now are MKV video files (matroska).

To read a EBML file at the byte level, reading the header making sure it is a EBML file and retrieving information on the file. MKV files can be huge, 1-30gb in size.

The binary file could be anything, jpeg, bmp, avi etc ...
I just want to learn how to read them.

答:
Basically, you do

```<code>const
  MAGIC_WORD = $535B;

type
  TMyFileTypeHeader = packed record
    MagicWord: word; // = MAGIC_WORD
    Size: cardinal;
    Version: cardinal;
    Width: cardinal;
    Height: cardinal;
    ColorDepth: cardinal;
    Title: array[0..31] of char;
  end;

procedure ReadFile(const FileName: string);
var
  f: file;
  amt: integer;
  FileHeader: TMyFileTypeHeader;
begin

  FileMode := fmOpenRead;
  AssignFile(f, FileName);

  try
    Reset(f, 1);

    BlockRead(f, FileHeader, sizeof(TMyFileTypeHeader), amt);

    if FileHeader.MagicWord <> MAGIC_WORD then
      raise Exception.Create(Format('File "%s" is not a valid XXX file.', [FileName]));

    // Read, parse, and do something

  finally
    CloseFile(f);
  end;

end;
</code>```

For instance, a bitmap file begins with a BITMAPFILEHEADER structure, followed (in version 3) by a BITMAPINFOHEADER. Followed by an optional array of palette items, followed by uncompressed RGB pixel data (in the simplest case, here in 24-bit format): BBGGRRBBGGRRBBGGRR...

Reading a JPG, on the other hand, is very complicated, because the JPG data is compressed in a way that requires a lot of advanced mathematics to even understand (I think -- I have actually never really dug into the JPG specs). At least, this is true for a lot of modern image file formats. BMP, on the other hand, is trivial -- the "worst" thing that can happen is that the image is RLE compressed.

The "details" of parsing a file depends entirely on the file format. The file format specification tells the developer how the data is stored in binary form (above, the two bitmap structures are part of the Windows bitmap specification). It is like a contract, signed (not literally) by all encoders/decoders of such files. In the case of EBML, the specification appears to be available here.

Body:
Basically, you do

const
  MAGIC_WORD = $535B;

type
  TMyFileTypeHeader = packed record
    MagicWord: word; // = MAGIC_WORD
    Size: cardinal;
    Version: cardinal;
    Width: cardinal;
    Height: cardinal;
    ColorDepth: cardinal;
    Title: array[0..31] of char;
  end;

procedure ReadFile(const FileName: string);
var
  f: file;
  amt: integer;
  FileHeader: TMyFileTypeHeader;
begin

  FileMode := fmOpenRead;
  AssignFile(f, FileName);

  try
    Reset(f, 1);

    BlockRead(f, FileHeader, sizeof(TMyFileTypeHeader), amt);

    if FileHeader.MagicWord <> MAGIC_WORD then
      raise Exception.Create(Format('File "%s" is not a valid XXX file.', [FileName]));

    // Read, parse, and do something

  finally
    CloseFile(f);
  end;

end;

For instance, a bitmap file begins with a BITMAPFILEHEADER structure, followed (in version 3) by a BITMAPINFOHEADER. Followed by an optional array of palette items, followed by uncompressed RGB pixel data (in the simplest case, here in 24-bit format): BBGGRRBBGGRRBBGGRR...

Reading a JPG, on the other hand, is very complicated, because the JPG data is compressed in a way that requires a lot of advanced mathematics to even understand (I think -- I have actually never really dug into the JPG specs). At least, this is true for a lot of modern image file formats. BMP, on the other hand, is trivial -- the "worst" thing that can happen is that the image is RLE compressed.

The "details" of parsing a file depends entirely on the file format. The file format specification tells the developer how the data is stored in binary form (above, the two bitmap structures are part of the Windows bitmap specification). It is like a contract, signed (not literally) by all encoders/decoders of such files. In the case of EBML, the specification appears to be available here.


问:
celery and long running tasks
I just watch a youtube video where the presenter mentioned that one should design his/her celery to be short. Tasks running several minutes are bad.

Is this correct? What I do see is that I have some long running task, which takes say 10 minutes to finish. When these kind of task is scheduled frequently, the queue is swamped and no other tasks get scheduled. Is this the reason?

If so, what should be used for long running tasks?

答:
Augment the basic Task definition to optionally treat the task instantiation as a generator, and check for TERM or soft timeout on every iteration through the generator.  Generically inject a "state" dict kwarg into tasks that support it.  If it's the first time the task is run, allocate a new one in results cache, otherwise look up the existing one from results cache.

In your task, figure out a good place to yield which results in short execution times.  Update the state parameter as necessary.

When control returns to the master task class, check for TERM or soft timeout, and if there is one, save off the state object and respond to the signal.

Title: celery and long running tasks


问:
PHP: echo selected value from a drop down list
I have this drop-down list that I created using one of MySQL table. The drop-down list is working fine but for some reason I am not able to echo the selected value here is my code:

```<code><?php
      require_once('config.php');
      // CONNECT
       mysql_connect('localhost', 'root', 'password');
       mysql_select_db('Database');

 ?>
 // other.php is another php file
 <form action="other.php" method="POST">

            <label>Quantity:</label>
            <input type="number" min="1" name="quantity" value="1"/>
            <br/>
            <hr/>

            <?php
                    echo makeFormEntry('Product Type', 'type', $types);
                    echo makeFormEntry('Product Occasion', 'occasion', $occasions);
                    echo makeFormEntry('Product Size', 'size', $sizes);
            $sql = "SELECT * FROM Table";
            $result = mysql_query($sql);
            echo "<b>Name : </b>" . "<select id='Name' name='Name'>";
            while ($row = mysql_fetch_array($result)) {
             echo "<option value='" . $row['Name'] . "'>" . $row['Name'] . "</option>";
            }
                    echo "</select><br>";
               echo "<input type='submit'/><input type='reset'/>";
  ?>
  </form>
</code>```

here is what I have tried:

```<code>  $n=$_POST['Name'];
   echo $n;
</code>```

答:
Try this way</p>

```<code>  echo "<option if($row["Name"]=="Doe") ? "selected='selected'":"" value='".$row['Name']."'>".$row["Name"]."</option>";
</code>```

Body:
I have this drop-down list that I created using one of MySQL table. The drop-down list is working fine but for some reason I am not able to echo the selected value here is my code:

<?php
      require_once('config.php');
      // CONNECT
       mysql_connect('localhost', 'root', 'password');
       mysql_select_db('Database');

 ?>
 // other.php is another php file
 <form action="other.php" method="POST">

            Quantity:
            <input type="number" min="1" name="quantity" value="1"/>

            <?php
                    echo makeFormEntry('Product Type', 'type', $types);
                    echo makeFormEntry('Product Occasion', 'occasion', $occasions);
                    echo makeFormEntry('Product Size', 'size', $sizes);
            $sql = "SELECT * FROM Table";
            $result = mysql_query($sql);
            echo "Name : " . "<select id='Name' name='Name'>";
            while ($row = mysql_fetch_array($result)) {
             echo "<option value='" . $row['Name'] . "'>" . $row['Name'] . "</option>";
            }
                    echo "</select>
";
               echo "<input type='submit'/><input type='reset'/>";
  ?>
  </form>

here is what I have tried:

  $n=$_POST['Name'];
   echo $n;

Body:
Try this way

  echo "<option if($row["Name"]=="Doe") ? "selected='selected'":"" value='".$row['Name']."'>".$row["Name"]."</option>";


问:
Use analog output as digital in relay pins
I can use digital pins from 1-13 as usual.
For example

```<code>relays.firstRelay = new five.Relay ( {
pin:13,
type:'NO'
});
</code>```

But I am unable to set pin:14. I don't get any output.

Is there a way to set A0 as digital pin and use it in relay?

I am using Arduino Uno

答: On the UNO, the analog pins will need to be treated a bit differently because of the need to set their pin type. But otherwise having an array of pin objects should be fine. You just need to get the analog pins setup early as operating digitally instead. You may also want to try addressing the pin as A0 instead of 14.</p>

Body:
I can use digital pins from 1-13 as usual.
For example

relays.firstRelay = new five.Relay ( {
pin:13,
type:'NO'
});

But I am unable to set pin:14. I don't get any output.

Is there a way to set A0 as digital pin and use it in relay?

I am using Arduino Uno


问:
Display data in dynamic matrix format using jquery
I will get the below json from webapi and I need to display this data in matrix format on UI. How would I do this?

The json data looks like this:

```<code>[
 {"ShippingLine_Cd":"AAC","SizeType_Cd":"20BU","ERIStatus_Cd":"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"ACL","SizeType_Cd":"20BU","ERIStatus_Cd" :"Active","Shift_Nbr":"2"},
 {"ShippingLine_Cd":"AMA","SizeType_Cd":"20DR","ERIStatus_Cd" :"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"ABC","SizeType_Cd":"20DR","ERIStatus_Cd" :"Pending","Shift_Nbr":"2"},
 {"ShippingLine_Cd":"CDE","SizeType_Cd":"20DR","ERIStatus_Cd" :"Pending","Shift_Nbr":"3"},
 {"ShippingLine_Cd":"AAC","SizeType_Cd":"20DR","ERIStatus_Cd" :"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"CDE","SizeType_Cd":"20BU","ERIStatus_Cd" :"Pending","Shift_Nbr":"1"}
]
</code>```

This desired UI format:

答:
Because your question shows no code, I will only answer in pseudo code, its up to you to write the real code.

you could do something like this (after you first created your html table):

```<code>data.forEach(item => {
     var x = item.SizeType_Cd == ("20BU" ? 2 : 0) + item.Shift_Nbr;
     var y = 0; //some logic here to get the y coordinate
     table.children[y].chilren[x].text = item.ERIStatus_Cd; //set the status text
})
</code>```

Body:
I will get the below json from webapi and I need to display this data in matrix format on UI. How would I do this?

The json data looks like this:

[
 {"ShippingLine_Cd":"AAC","SizeType_Cd":"20BU","ERIStatus_Cd":"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"ACL","SizeType_Cd":"20BU","ERIStatus_Cd" :"Active","Shift_Nbr":"2"},
 {"ShippingLine_Cd":"AMA","SizeType_Cd":"20DR","ERIStatus_Cd" :"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"ABC","SizeType_Cd":"20DR","ERIStatus_Cd" :"Pending","Shift_Nbr":"2"},
 {"ShippingLine_Cd":"CDE","SizeType_Cd":"20DR","ERIStatus_Cd" :"Pending","Shift_Nbr":"3"},
 {"ShippingLine_Cd":"AAC","SizeType_Cd":"20DR","ERIStatus_Cd" :"Active","Shift_Nbr":"1"},
 {"ShippingLine_Cd":"CDE","SizeType_Cd":"20BU","ERIStatus_Cd" :"Pending","Shift_Nbr":"1"}
]

This desired UI format:

Body:
Because your question shows no code, I will only answer in pseudo code, its up to you to write the real code.

you could do something like this (after you first created your html table):

data.forEach(item => {
     var x = item.SizeType_Cd == ("20BU" ? 2 : 0) + item.Shift_Nbr;
     var y = 0; //some logic here to get the y coordinate
     table.children[y].chilren[x].text = item.ERIStatus_Cd; //set the status text
})


问:
Simple validation with attribute pattern in HTML
I do not really mastered this, but i want to validation checks form HTML attribute, that is "pattern", this example my own:

```<code><input type='text' pattern='[-+]?[0-9]*[.,]?[0-9]+' />
</code>```

This validates only one number. How can I validate a comma-separated list of numbers?

答:
You seem to want to validate a string of comma-separated numbers that meet your pattern.

Use

```<code>pattern="[-+]?[0-9]*[.,]?[0-9]+(?:,[-+]?[0-9]*[.,]?[0-9]+)*"
</code>```

The pattern is anchored by default, so no need using ^ at the start and $ at the end.

Details:

[-+]? - an optional - or +

[0-9]*  - 0+ digits

[.,]? - an optional . or ,

[0-9]+ - 1+ digits

(?:,[-+]?[0-9]*[.,]?[0-9]+)* - zero or more  sequences of:

, - a comma

[-+]?[0-9]*[.,]?[0-9]+ - the number pattern (described above).

See a demo below:

input:valid {
  color: green;
}
input:invalid {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="form1">
 <input pattern="[-+]?[0-9]*[.,]?[0-9]+(?:,[-+]?[0-9]*[.,]?[0-9]+)*" title=""/>
 <input type="Submit"/>
</form></code>```

Body:
I do not really mastered this, but i want to validation checks form HTML attribute, that is "pattern", this example my own:

<input type='text' pattern='[-+]?[0-9]*[.,]?[0-9]+' />

This validates only one number. How can I validate a comma-separated list of numbers?

Body:
You seem to want to validate a string of comma-separated numbers that meet your pattern.

Use

pattern="[-+]?[0-9]*[.,]?[0-9]+(?:,[-+]?[0-9]*[.,]?[0-9]+)*"

The pattern is anchored by default, so no need using ^ at the start and $ at the end.

Details:

[-+]? - an optional - or +

[0-9]*  - 0+ digits

[.,]? - an optional . or ,

[0-9]+ - 1+ digits

(?:,[-+]?[0-9]*[.,]?[0-9]+)* - zero or more  sequences of:

, - a comma

[-+]?[0-9]*[.,]?[0-9]+ - the number pattern (described above).

See a demo below:

input:valid {
  color: green;
}
input:invalid {
  color: red;
}

<form name="form1">
 <input pattern="[-+]?[0-9]*[.,]?[0-9]+(?:,[-+]?[0-9]*[.,]?[0-9]+)*" title=""/>
 <input type="Submit"/>
</form>


问:
Python: Best way to decorate a function only locally
What is the best way to decorate a function, but only in a local scope. For example we have the following:

```<code>def a():
    do stuff
    b()
    do stuff
</code>```

I want to make a function c() that does the same stuff but decorates b so it adds some extra stuff. I found a way to do that but it changes b() globally:

```<code>def c():
    global b
    b = decorator(b)
    a()
</code>```

Is there a way to do that but without changing the function b globally?

答:
You can patch the function b, and replace it with another function. Use unittest.mock in Python 3, or mock in Python 2 for this:

```<code>from unittest.mock import patch

def c():
    with patch('b', decorator(b)):
        a()

# Or, as a decorator
@patch('b', decorator(b))
def c():
    a()
</code>```

By patching, you're essentially replacing the b instance with your own.

Body:
What is the best way to decorate a function, but only in a local scope. For example we have the following:

def a():
    do stuff
    b()
    do stuff

I want to make a function c() that does the same stuff but decorates b so it adds some extra stuff. I found a way to do that but it changes b() globally:

def c():
    global b
    b = decorator(b)
    a()

Is there a way to do that but without changing the function b globally?

Body:
You can patch the function b, and replace it with another function. Use unittest.mock in Python 3, or mock in Python 2 for this:

from unittest.mock import patch

def c():
    with patch('b', decorator(b)):
        a()

# Or, as a decorator
@patch('b', decorator(b))
def c():
    a()

By patching, you're essentially replacing the b instance with your own.


问:
Camel - set value in processor but is null outside processor
I'm trying to populate an ApplicationScoped POJO inside an an Apache Camel processor. I set, and check that the values are set, inside a processor, but outside, the processor the POJO is null.

```<code>//Get login token from our service
    from(inputEndpoint).routeId("getAuthToken").streamCaching()
        .process(new Processor() {

            @Override
            public void process(Exchange arg) throws Exception {
                arg.getOut().setBody(new LoginVM("admin", "admin", true));

            }
        })
    .marshal().json(JsonLibrary.Jackson, true)
    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
    .to("http://localhost:8080/api/authenticate")
    .log("RESULT FROM AUTH ENDPOINT IS ${body}") // CORRECT RESULT
    .unmarshal().json(JsonLibrary.Jackson, AuthToken.class)
    .process(new Processor() {

        @Override
        public void process(Exchange exch) throws Exception {
            authToken=exch.getIn().getBody(AuthToken.class);
            System.out.println("VALUE IS " + authToken.getId_token()); // CORRECT RESULT - SET VALUE OF authToken
            exch.getOut().setBody(authToken);
        }
    })
    .log("Bearer is :" + authToken.getId_token()) //TODO - this shouldnt be null!
</code>```

My AuthToken POJO is

```<code>import javax.enterprise.context.ApplicationScoped;
import javax.inject.Singleton;

@Singleton
public class AuthToken {

    String id_token;

    public String getId_token() {
        return id_token;
    }

    public void setId_token(String id_token) {
        this.id_token = id_token;
        System.out.println("The value in AuthToken is " + this.id_token);
    }

}
</code>```

I cannot see why it loses its value.

答:
This code

.log("Bearer is :" + authToken.getId_token())

Is only executed once when Camel is starting and creates the route.

If you want to do dynamic logging, then use the simple language which is baked in the log EIP: http://camel.apache.org/simple

From simple you can call methods on the message body to be logged

.log("xxx ${body.getId_token()}");

Body:
I'm trying to populate an ApplicationScoped POJO inside an an Apache Camel processor. I set, and check that the values are set, inside a processor, but outside, the processor the POJO is null.

//Get login token from our service
    from(inputEndpoint).routeId("getAuthToken").streamCaching()
        .process(new Processor() {

            @Override
            public void process(Exchange arg) throws Exception {
                arg.getOut().setBody(new LoginVM("admin", "admin", true));

            }
        })
    .marshal().json(JsonLibrary.Jackson, true)
    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
    .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
    .to("http://localhost:8080/api/authenticate")
    .log("RESULT FROM AUTH ENDPOINT IS ${body}") // CORRECT RESULT
    .unmarshal().json(JsonLibrary.Jackson, AuthToken.class)
    .process(new Processor() {

        @Override
        public void process(Exchange exch) throws Exception {
            authToken=exch.getIn().getBody(AuthToken.class);
            System.out.println("VALUE IS " + authToken.getId_token()); // CORRECT RESULT - SET VALUE OF authToken
            exch.getOut().setBody(authToken);
        }
    })
    .log("Bearer is :" + authToken.getId_token()) //TODO - this shouldnt be null!

My AuthToken POJO is

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Singleton;

@Singleton
public class AuthToken {

    String id_token;

    public String getId_token() {
        return id_token;
    }

    public void setId_token(String id_token) {
        this.id_token = id_token;
        System.out.println("The value in AuthToken is " + this.id_token);
    }

}

I cannot see why it loses its value.


问:
API - Python - Request Library
I've been digging a hole deeper and deeper trying to work out my api script in python. I'm not sure if i'm just doing something wrong, or i'm misunderstanding the way the projection section is to be written.

Here is the information I'll provide.. So we have two ways to get information from our API through JSON or via socketJS. The socket JS code i will provide down the bottom which essentially does the same thing..

What's going wrong is that it doesn't seem to be processing the parameters correctly, all i get is the same values as i would if i have added no filters or projections.. Does anyone have any ideas on what i'm doing wrong? I suspect i'm not using the requests library correctly, however i have looked and i don't seem to find anything for my particular case in the documentation.

Working SocketJS:

```<code>{
"address": "service",
"body": {
    "action": "getControlers",
    "params": {
        "filter": {
            "deviceClass": {
            "$like" : "*mainControllers*"
        }
        },
        "projection": {
        "tagValues": {
            "IdMap": 1,
            "StateDevice": 1
                }

            },
        "limit":1000
    }

}
</code>```

}

equivalent line via API-Rest outside of Python:

```<code>https://URLURL/rest/service/controlers?projection={"tagValues":{"StateDevice": 1}}&filter= {"DeviceClass": {"$like" : "*Controlers*"}}
</code>```

My script is as follows:

```<code>import requests
import json
import os

header = {"Authorization": 'access_token *Iputakeyheretomakethingswork*'}

parameters = {"Filter": {"deviceClass": {"$like" : "*Controller*"}},

"Projection": {"tagValues":{"IdStateMap": 1, "stateDevice": 1}}}

response = requests.get("https://urlgoeshere", headers=header, params=parameters)
print(response.status_code)

data = response.json()

with open('data.txt', 'w') as outfile:
     json.dump(data, outfile, sort_keys = True, indent = 4,
           ensure_ascii = False)
</code>```

答:
params does not take a nested dictionary structure. Your API is essentially asking for JSON formatted values in the query string, but you are not providing those.

Moreover, your example URL uses lowercased parameter names, your dictionary contains uppercased parameters.

Instead, requests will convert the any container in params to a string by taking each element, before encoding it with URL encoding. For a dictionary, that means only the keys are used; you are essentially producing the following URL:

```<code>>>> import requests
>>> parameters = {"Filter": {"deviceClass": {"$like" : "*Controller*"}},
... "Projection": {"tagValues":{"IdStateMap": 1, "stateDevice": 1}}}
>>> prepped = requests.Request('GET', 'http://example.com/', params=parameters).prepare()
>>> prepped.url
'http://example.com/?Filter=deviceClass&Projection=tagValues'
</code>```

The following would produce the equivalent of your sample URL:

```<code>parameters = {
    "filter": '{"deviceClass": {"$like": "*Controller*"}}',
    "projection": '{"tagValues": {"IdStateMap": 1, "stateDevice": 1}}'
}
</code>```

Note that I lowercased the keys and the values are just strings. You could use the json.dumps() function to produce those strings from Python dictionaries if need be:

```<code>import json

filter = {"deviceClass": {"$like": "*Controller*"}}
projection = {"tagValues": {"IdStateMap": 1, "stateDevice": 1}}
parameters = {
    "filter": json.dumps(filter),
    "projection": json.dumps(projection),
}
</code>```

Demo:

```<code>>>> parameters = {
...     "filter": '{"deviceClass": {"$like" : "*Controller*"}}',
...     "projection": '{"tagValues":{"IdStateMap": 1, "stateDevice": 1}}'
... }
>>> prepped = requests.Request('GET', 'http://example.com/', params=parameters).prepare()
>>> prepped.url
'http://example.com/?filter=%7B%22deviceClass%22%3A+%7B%22%24like%22+%3A+%22%2AController%2A%22%7D%7D&projection=%7B%22tagValues%22%3A%7B%22IdStateMap%22%3A+1%2C+%22stateDevice%22%3A+1%7D%7D'
>>> from urllib.parse import urlparse, parse_qsl
>>> parse_qsl(urlparse(prepped.url).query)
[('filter', '{"deviceClass": {"$like" : "*Controller*"}}'), ('projection', '{"tagValues":{"IdStateMap": 1, "stateDevice": 1}}')]
</code>```

Title: API - Python - Request Library

Body:
I've been digging a hole deeper and deeper trying to work out my api script in python. I'm not sure if i'm just doing something wrong, or i'm misunderstanding the way the projection section is to be written.

Here is the information I'll provide.. So we have two ways to get information from our API through JSON or via socketJS. The socket JS code i will provide down the bottom which essentially does the same thing..

What's going wrong is that it doesn't seem to be processing the parameters correctly, all i get is the same values as i would if i have added no filters or projections.. Does anyone have any ideas on what i'm doing wrong? I suspect i'm not using the requests library correctly, however i have looked and i don't seem to find anything for my particular case in the documentation.

Working SocketJS:

{
"address": "service",
"body": {
    "action": "getControlers",
    "params": {
        "filter": {
            "deviceClass": {
            "$like" : "*mainControllers*"
        }
        },
        "projection": {
        "tagValues": {
            "IdMap": 1,
            "StateDevice": 1
                }

            },
        "limit":1000
    }

}

}

equivalent line via API-Rest outside of Python:

https://URLURL/rest/service/controlers?projection={"tagValues":{"StateDevice": 1}}&filter= {"DeviceClass": {"$like" : "*Controlers*"}}

My script is as follows:

import requests
import json
import os

header = {"Authorization": 'access_token *Iputakeyheretomakethingswork*'}

parameters = {"Filter": {"deviceClass": {"$like" : "*Controller*"}},

"Projection": {"tagValues":{"IdStateMap": 1, "stateDevice": 1}}}

response = requests.get("https://urlgoeshere", headers=header, params=parameters)
print(response.status_code)

data = response.json()

with open('data.txt', 'w') as outfile:
     json.dump(data, outfile, sort_keys = True, indent = 4,
           ensure_ascii = False)

Body:
params does not take a nested dictionary structure. Your API is essentially asking for JSON formatted values in the query string, but you are not providing those.

Moreover, your example URL uses lowercased parameter names, your dictionary contains uppercased parameters.

Instead, requests will convert the any container in params to a string by taking each element, before encoding it with URL encoding. For a dictionary, that means only the keys are used; you are essentially producing the following URL:

>>> import requests
>>> parameters = {"Filter": {"deviceClass": {"$like" : "*Controller*"}},
... "Projection": {"tagValues":{"IdStateMap": 1, "stateDevice": 1}}}
>>> prepped = requests.Request('GET', 'http://example.com/', params=parameters).prepare()
>>> prepped.url
'http://example.com/?Filter=deviceClass&Projection=tagValues'

The following would produce the equivalent of your sample URL:

parameters = {
    "filter": '{"deviceClass": {"$like": "*Controller*"}}',
    "projection": '{"tagValues": {"IdStateMap": 1, "stateDevice": 1}}'
}

Note that I lowercased the keys and the values are just strings. You could use the json.dumps() function to produce those strings from Python dictionaries if need be:

import json

filter = {"deviceClass": {"$like": "*Controller*"}}
projection = {"tagValues": {"IdStateMap": 1, "stateDevice": 1}}
parameters = {
    "filter": json.dumps(filter),
    "projection": json.dumps(projection),
}

Demo:

>>> parameters = {
...     "filter": '{"deviceClass": {"$like" : "*Controller*"}}',
...     "projection": '{"tagValues":{"IdStateMap": 1, "stateDevice": 1}}'
... }
>>> prepped = requests.Request('GET', 'http://example.com/', params=parameters).prepare()
>>> prepped.url
'http://example.com/?filter=%7B%22deviceClass%22%3A+%7B%22%24like%22+%3A+%22%2AController%2A%22%7D%7D&projection=%7B%22tagValues%22%3A%7B%22IdStateMap%22%3A+1%2C+%22stateDevice%22%3A+1%7D%7D'
>>> from urllib.parse import urlparse, parse_qsl
>>> parse_qsl(urlparse(prepped.url).query)
[('filter', '{"deviceClass": {"$like" : "*Controller*"}}'), ('projection', '{"tagValues":{"IdStateMap": 1, "stateDevice": 1}}')]


问:
Using macros for string concatenation
I want to create macro that receives 2 arguments: NSString and ObjCBool and returns NSString.

I'm not familiar a lot with macros, anyway this is what I did so far:

```<code>#define fooOne(url)\
          @"1111111" url

 #define fooTwo(url)\
          @"2222222" url

#define root(url, flag)\
   if(!flag)fooOne(url)\
   else fooTwo(url)
</code>```

Here I have 2 problems:

1) when I call fooOne as:

```<code>NSString *url = @"zzz";
NSLog(@"%@", fooOne(url));
// expected log should be: "1111111 zzz"
</code>```

I get error: Expected ')'

2) When I call root(url, flag) as:

```<code>BOOL flag = YES;
NSString *url = @"zzz";
NSLog(@"%@", root(url, flag));
// expected log should be: "2222222 zzz"
</code>```

I get an error: Expected expression

please help,

答:
Compile-time string concatenation only works with string literals. At compile time @"hello, " @"world" is combined into a new string literal @"hello, world". This doesn't work with strings contained in variables — @"blabla" url is not a valid expression, even if url contains a string literal at runtime. You would have to call your macros with the literal inside: fooOne(@"zzz"), which would expand to @"blabla" @"zzz".

If you want to combine strings at runtime, you'll need to use +[NSString stringWithFormat:], or append the strings.

Title: Using macros for string concatenation

Body:
I want to create macro that receives 2 arguments: NSString and ObjCBool and returns NSString.

I'm not familiar a lot with macros, anyway this is what I did so far:

#define fooOne(url)\
          @"1111111" url

 #define fooTwo(url)\
          @"2222222" url

#define root(url, flag)\
   if(!flag)fooOne(url)\
   else fooTwo(url)

Here I have 2 problems:

1) when I call fooOne as:

NSString *url = @"zzz";
NSLog(@"%@", fooOne(url));
// expected log should be: "1111111 zzz"

I get error: Expected ')'

2) When I call root(url, flag) as:

BOOL flag = YES;
NSString *url = @"zzz";
NSLog(@"%@", root(url, flag));
// expected log should be: "2222222 zzz"

I get an error: Expected expression

please help,


答:
Suppose they implement a common interface (or superclass) Common:

```<code>public interface Common {
}

public class Foo implements Common {
}

public class Bar implements Common {
}
</code>```

Then, in Java 8 we can define an array of Suppliers:

```<code>List<Supplier<Common>> anArray = new ArrayList<>();

anArray.add(Foo::new);
anArray.add(Bar::new);

//or with lambdas:
anArray.add(() -> new Bar());
</code>```

Usage:

```<code>Common aNewCommon = anArray.get(0).get();
</code>```

Without a Common interface (or superclass) you'll have to do some less-than-ideal casting from Object.

Title: Can I store an object constructor into an array or hashtable?

Body:
Let's say I have a class Foo and another class Bar that both extends from a superclass Foobar, each one with it's own  constructor.

So, I want to make an application in Java 8 that let's a user choose from a list of objects to implement, and add them to a list —I was thinking of using an array or hashtable—, in this case I want to show a message like:

Choose an object of the following list:
 [1] Foo
 [2] Bar

The idea is to let the user create multiple instances of such classes and add them to an array. For example, if the user chooses 1, I want to assign a variable with a[0] = new Foo(), and then if he chooses 2, a[1] = new Bar(), but then, if the user chooses 1 again, then a[2] should be a new instance of Foo. My first idea was to initialize an array with the constructors like:

anArray[1] = new Foo();
anArray[2] = new Bar();

The problem with that implementation is that if I call a[0] = anArray[1] and then a[1] = anArray[1], then a[0]and a[1] would be the same object.

What I am looking for is if there is a way of creating an undefined number of instances of each object without having to implement it as a chain of if else (because in reality I have more than 2 type of objects). I was thinking of using an array or a hashtable, but I don't know if there is actually a way of doing it.

Body:
Suppose they implement a common interface (or superclass) Common:

public interface Common {
}

public class Foo implements Common {
}

public class Bar implements Common {
}

Then, in Java 8 we can define an array of Suppliers:

List<Supplier<Common>> anArray = new ArrayList<>();

anArray.add(Foo::new);
anArray.add(Bar::new);

//or with lambdas:
anArray.add(() -> new Bar());

Usage:

Common aNewCommon = anArray.get(0).get();

Without a Common interface (or superclass) you'll have to do some less-than-ideal casting from Object.


问:
In visual studio code - what is the name of the ins key on the num pad (keybindings.json)
I would like to assign the ins key on the numpad to paste.

I have tried

```<code>{ "key": "numpad_ins",                "command": "editor.action.clipboardPasteAction",
                                     "when": "editorTextFocus && !editorReadonly" }
</code>```

答:
When the numpad is activated, it's numpad0, and when it's not: insert.

You can test your bindings in the keybindings.json by pressing Ctrl+K on Windows and Linux or with ⌘+K on macOS, two times in a row. A little popup window will appear and you can then press various keys to test for their names.

Body:
I would like to assign the ins key on the numpad to paste.

I have tried

{ "key": "numpad_ins",                "command": "editor.action.clipboardPasteAction",
                                     "when": "editorTextFocus && !editorReadonly" }