问:
Adb install failure: INSTALL_CANCELED_BY_USER
I try to install app via adb and get a error:

```<code>$ ./adb -d install /Users/dimon/Projects/one-place/myprogram/platforms/android/build/outputs/apk/android-debug.apk -r -g
3704 KB/s (4595985 bytes in 1.211s)
    pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_CANCELED_BY_USER]
</code>```

In device I do nothing in this moment.
Device is Xiaomi MI5, MIUI 7.2.13, Android 6.0. Developer mode enabled.
How to fix this?

The same error I get when try to run "ionic run android" command.

UPD

Here is logs from 'adb logcat' command getting in moment of installation program:

```<code>06-06 10:04:20.051   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.063   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.078 13397 13397 E ANDR-PERF-MPCTL: Unable to create control service (stage=2, rc=-1)
06-06 10:04:20.082   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.079 13396 13396 W iop     : type=1400 audit(0.0:527): avc: denied { write } for name="socket" dev="tmpfs" ino=14686 scontext=u:r:dumpstate:s0 tcontext=u:object_r:socket_device:s0 tclass=dir permissive=0
06-06 10:04:20.088   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.926 13400 13400 D AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
06-06 10:04:20.930 13400 13400 D AndroidRuntime: CheckJNI is OFF
06-06 10:04:20.966 13400 13400 D ICU     : No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
06-06 10:04:20.995 13400 13400 I Radio-JNI: register_android_hardware_Radio DONE
06-06 10:04:21.004 13400 13400 E         : WFDWhiteListing : library initialized successfully
06-06 10:04:21.020 13400 13400 D AndroidRuntime: Calling main entry com.android.commands.pm.Pm
06-06 10:04:21.027 13400 13400 I Timeline: Timeline: Activity_launch_request time:973226
06-06 10:04:21.028  1497  2996 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=file:///data/local/tmp/android-debug.apk typ=application/vnd.android.package-archive flg=0x18000000 cmp=com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity (has extras)} from uid 2000 on display 0
06-06 10:04:21.033  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.033  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.033  1497  2996 E         : Service not available yet
06-06 10:04:21.034  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.037  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.037  1497  2996 E         : Service not available yet
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.050  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity}
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: notify state normal_state enter...
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: foreground_change:
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_cpu_powermode(middle)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_cpu_powermode
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_lcd_mode(ui)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_lcd_mode
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:528): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:529): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  3247  4440 I octvm_power: power mode [normal] start 1465200261
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_cpu_powermode(middle) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_power_profile -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2113 have been add to group sys_standby.
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_lcd_mode(ui) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_lcd_mode -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2900 have been add to group sys_standby.
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:530): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  2533  2887 I octvm   : task pid 4553 have been add to group sys_standby.
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.051  3247  4440 I octvm_power: onPowerModeChanged[normal] called
06-06 10:04:21.052  2875  3093 I FirstNotificationController: handleUnlockState: stoped
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_ready time:973254
06-06 10:04:21.055  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_stopped time:973255
06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:531): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:532): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.072  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.072  1497  2230 E         : Service not available yet
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.073  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.073  1497  2230 E         : Service not available yet
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.075  1497  2230 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.076  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.android.settings/com.android.settings.Settings$WifiSettingsActivity}
06-06 10:04:21.069  2887  2887 W EventReader: type=1400 audit(0.0:533): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_ready time:973275
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_stopped time:973275
06-06 10:04:21.076  2533  2887 I octvm   : task pid 2060 have been add to group sys_standby.
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.077  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.090 13400 13400 I art     : System.exit called, status: 1
06-06 10:04:21.090 13400 13400 I AndroidRuntime: VM exiting with result code 1.
06-06 10:04:21.100  2060  2130 V MI_STAT : disabled local event upload
</code>```

I see when android-debug.apk creates, but I don't understand why it's not installs. Maybe the key strings is:

```<code>06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
</code>```

but this is not error strings, just warning and debug.
Also strange line:

```<code>06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
</code>```

but I don't know if it is a problem.

Also I tried to install via adb some other apps, not only self-written. But no results.

答:
The problem seems to be with Instant Run feature.Go to "File -> Settings -> Build, Execution, Deployment -> Instant Run" and just disable it.

Hope this works if above answers doesnt work..

Body:
I try to install app via adb and get a error:

$ ./adb -d install /Users/dimon/Projects/one-place/myprogram/platforms/android/build/outputs/apk/android-debug.apk -r -g
3704 KB/s (4595985 bytes in 1.211s)
    pkg: /data/local/tmp/android-debug.apk
Failure [INSTALL_CANCELED_BY_USER]

In device I do nothing in this moment.
Device is Xiaomi MI5, MIUI 7.2.13, Android 6.0. Developer mode enabled.
How to fix this?

The same error I get when try to run "ionic run android" command.

UPD

Here is logs from 'adb logcat' command getting in moment of installation program:

06-06 10:04:20.051   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.063   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.078 13397 13397 E ANDR-PERF-MPCTL: Unable to create control service (stage=2, rc=-1)
06-06 10:04:20.082   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.079 13396 13396 W iop     : type=1400 audit(0.0:527): avc: denied { write } for name="socket" dev="tmpfs" ino=14686 scontext=u:r:dumpstate:s0 tcontext=u:object_r:socket_device:s0 tclass=dir permissive=0
06-06 10:04:20.088   788   903 I DisplayFeatureService: void android::update_watchlist(const prop_info*, void*): sys.boot_completed: 1
06-06 10:04:20.926 13400 13400 D AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 2000 <<<<<<
06-06 10:04:20.930 13400 13400 D AndroidRuntime: CheckJNI is OFF
06-06 10:04:20.966 13400 13400 D ICU     : No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
06-06 10:04:20.995 13400 13400 I Radio-JNI: register_android_hardware_Radio DONE
06-06 10:04:21.004 13400 13400 E         : WFDWhiteListing : library initialized successfully
06-06 10:04:21.020 13400 13400 D AndroidRuntime: Calling main entry com.android.commands.pm.Pm
06-06 10:04:21.027 13400 13400 I Timeline: Timeline: Activity_launch_request time:973226
06-06 10:04:21.028  1497  2996 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=file:///data/local/tmp/android-debug.apk typ=application/vnd.android.package-archive flg=0x18000000 cmp=com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity (has extras)} from uid 2000 on display 0
06-06 10:04:21.033  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.033  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.033  1497  2996 E         : Service not available yet
06-06 10:04:21.034  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.037  1497  2996 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.037  1497  2996 E         : Service not available yet
06-06 10:04:21.037  1497  2996 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.050  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.miui.securitycenter/com.miui.permcenter.install.AdbInstallActivity}
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: notify state normal_state enter...
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: foreground_change:
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_cpu_powermode(middle)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_cpu_powermode
06-06 10:04:21.051  2875  3036 D PowerKeeperExecutor: set_lcd_mode(ui)
06-06 10:04:21.051  2875  3036 I PowerKeeperExecutor: no local quick execution method for set_lcd_mode
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:528): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:529): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  3247  4440 I octvm_power: power mode [normal] start 1465200261
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_cpu_powermode(middle) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_power_profile -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2113 have been add to group sys_standby.
06-06 10:04:21.051  3247  4440 I octvm_power: Action: set_lcd_mode(ui) for [foreground_change]
06-06 10:04:21.051  3247  4440 I octvm_drv: common drv: platform_set_lcd_mode -> platform not support
06-06 10:04:21.051  2533  2887 I octvm   : task pid 2900 have been add to group sys_standby.
06-06 10:04:21.049  2887  2887 W EventReader: type=1400 audit(0.0:530): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.051  2533  2887 I octvm   : task pid 4553 have been add to group sys_standby.
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.051  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.051  3247  4440 I octvm_power: onPowerModeChanged[normal] called
06-06 10:04:21.052  2875  3093 I FirstNotificationController: handleUnlockState: stoped
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_ready time:973254
06-06 10:04:21.055  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.055  1497  2996 I Timeline: Timeline: App_transition_stopped time:973255
06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:531): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk
06-06 10:04:21.059  4553  4553 W .securitycenter: type=1400 audit(0.0:532): avc: denied { search } for name="tmp" dev="dm-0" ino=28 scontext=u:r:system_app:s0 tcontext=u:object_r:shell_data_file:s0 tclass=dir permissive=0
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.072  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.072  1497  2230 E         : Service not available yet
06-06 10:04:21.072  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient ctor Context = 0x0, Cb = 0x0
06-06 10:04:21.073  1497  2230 E         : getWFDMMServiceInstance get new Instance
06-06 10:04:21.073  1497  2230 E         : Service not available yet
06-06 10:04:21.073  1497  2230 E         : WFDMMServiceClient::~WFDMMServiceClient
06-06 10:04:21.075  1497  2230 E ActivityManager: Invalid thumbnail dimensions: 0x0
06-06 10:04:21.076  2875  3077 D PowerKeeperEventLogManager: notifyForegroundCompomentChanged ComponentInfo{com.android.settings/com.android.settings.Settings$WifiSettingsActivity}
06-06 10:04:21.069  2887  2887 W EventReader: type=1400 audit(0.0:533): avc: denied { search } for name="756" dev="proc" ino=16099 scontext=u:r:system_app:s0 tcontext=u:r:zygote:s0 tclass=dir permissive=0
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_ready time:973275
06-06 10:04:21.076  1497  2230 I Timeline: Timeline: App_transition_stopped time:973275
06-06 10:04:21.076  2533  2887 I octvm   : task pid 2060 have been add to group sys_standby.
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks max single write time: 0ms
06-06 10:04:21.076  2533  2887 I octvm   : [sys_standby]cgroup_add_tasks total time consume: 0ms
06-06 10:04:21.077  1976  1976 V PhoneStatusBarPolicy: updateManagedProfile: mManagedProfileFocused: false mKeyguardVisible: true
06-06 10:04:21.090 13400 13400 I art     : System.exit called, status: 1
06-06 10:04:21.090 13400 13400 I AndroidRuntime: VM exiting with result code 1.
06-06 10:04:21.100  2060  2130 V MI_STAT : disabled local event upload

I see when android-debug.apk creates, but I don't understand why it's not installs. Maybe the key strings is:

06-06 10:04:21.066  4553  4553 W asset   : Asset path /data/local/tmp/android-debug.apk is neither a directory nor file (type=0).
06-06 10:04:21.066  4553  4553 D AdbInstallActivity:  parsePackage is null , path ：/data/local/tmp/android-debug.apk

but this is not error strings, just warning and debug.
Also strange line:

06-06 10:04:21.059  1497  2996 E ActivityManager: Invalid thumbnail dimensions: 0x0

but I don't know if it is a problem.

Also I tried to install via adb some other apps, not only self-written. But no results.


来源: stackexchange

问:
Python's pyparsing: Implementing grammar to parse logical AND expression
I am trying to parse and evaluate expressions, given to me as input from a file, of the form:

```<code>var[3] = 0 and var[2] = 1
var[0] = 1 and var[2] = 0 and var[3] = 1
...
</code>```

(actually I also allow "multibit access" (i.e. var[X:Y]) but let's ignore it for now...)

Where var is an integer, and the [] indicates bit access.

For example, for var = 0x9, the first expression above should be evaluated to False, and the second should be evaluated to True since 0x9 = b1001.

and and = are the only binary operators I allow, and for the = operator, the left operand is always var[X] and the right operand is always a number.

I tried to look around a bit and found that this could be achieved with Python's pyparsing, but I ran into some difficulties trying to implement it.

Here's what I've tried so far, based roughly on this example (which is one of many examples provided here):

```<code>#!/usr/bin/env python
from pyparsing import Word, alphas, nums, infixNotation, opAssoc

class BoolAnd():
    def __init__(self, pattern):
        self.args = pattern[0][0::2]

    def __bool__(self):
        return all(bool(a) for a in self.args)

    __nonzero__ = __bool__

class BoolEqual():
    def __init__(self, pattern):
        self.bit_offset = int(pattern[0][1])
        self.value = int(pattern[0][-1])

    def __bool__(self):
        return True if (0xf >> self.bit_offset) & 0x1 == self.value else False # for now, let's assume var == 0xf

    __nonzero__ = __bool__

variable_name   = 'var'
bit_access      = variable_name + '[' + Word(nums) + ']'
multibit_access = variable_name + '[' + Word(nums) + ':' + Word(nums) + ']'
value = Word(nums)

operand = bit_access | multibit_access | value

expression = infixNotation(operand,
    [
    ('=',   2, opAssoc.LEFT,  BoolEqual),
    ('AND', 2, opAssoc.LEFT,  BoolAnd),
    ])

p = expression.parseString('var[3] = 1 AND var[1] = 0', True)

print 'SUCCESS' if bool(p) else 'FAIL'
</code>```

I have three problems I need help with.

For multibit access of the form var[X:Y] = Z, how do I enforce that:

a. X > Y

b. Z < 2^{X - Y + 1}

I assume this can't be enforced by the grammar itself (for example, for single-bit access of the form var[X] = Y, I can enforce by the grammar that Y will be either 0 or 1, and this will cause the expression.parseString() to fail with exception if Y != 0/1).

Most importantly: Why does it always print SUCCESS? What am I doing wrong?

For the input var[3] = 1 AND var[1] = 0 it should be print FAIL (you can see in my example that I hardcoded var to be 0xf, so var[3] = 1 is True but var[1] = 0 is False).

Which brings me to my third problem: var is not a class member of BoolEqual nor is it global... is there a way to somehow send it to BoolEqual's __init__ function?

答:
How about converting the variable to a list of 1 and 0's and using eval to evaluate the boolean expressions (with a small modification, changing = into ==) :

```<code>def parse(lines, v):
    var = map(int,list(bin(v)[2:]))
    result = []

    for l in lines:
        l = l.replace('=','==')
        result.append(eval(l))

    return result

inp = \
"""
var[3] = 0 and var[2] = 1
var[0] = 1 and var[2] = 0 and var[3] = 1
"""

lines = inp.split('\n')[1:-1]
v = 0x09

print parse(lines, v)
</code>```

Output:

```<code>[False, True]
</code>```

Note that you should only use eval if your trust the input.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to parse and evaluate expressions, given to me as input from a file, of the form:

var[3] = 0 and var[2] = 1
var[0] = 1 and var[2] = 0 and var[3] = 1
...

(actually I also allow "multibit access" (i.e. var[X:Y]) but let's ignore it for now...)

Where var is an integer, and the [] indicates bit access.

For example, for var = 0x9, the first expression above should be evaluated to False, and the second should be evaluated to True since 0x9 = b1001.

and and = are the only binary operators I allow, and for the = operator, the left operand is always var[X] and the right operand is always a number.

I tried to look around a bit and found that this could be achieved with Python's pyparsing, but I ran into some difficulties trying to implement it.

Here's what I've tried so far, based roughly on this example (which is one of many examples provided here):

#!/usr/bin/env python
from pyparsing import Word, alphas, nums, infixNotation, opAssoc

class BoolAnd():
    def __init__(self, pattern):
        self.args = pattern[0][0::2]

    def __bool__(self):
        return all(bool(a) for a in self.args)

    __nonzero__ = __bool__

class BoolEqual():
    def __init__(self, pattern):
        self.bit_offset = int(pattern[0][1])
        self.value = int(pattern[0][-1])

    def __bool__(self):
        return True if (0xf >> self.bit_offset) & 0x1 == self.value else False # for now, let's assume var == 0xf

    __nonzero__ = __bool__

variable_name   = 'var'
bit_access      = variable_name + '[' + Word(nums) + ']'
multibit_access = variable_name + '[' + Word(nums) + ':' + Word(nums) + ']'
value = Word(nums)

operand = bit_access | multibit_access | value

expression = infixNotation(operand,
    [
    ('=',   2, opAssoc.LEFT,  BoolEqual),
    ('AND', 2, opAssoc.LEFT,  BoolAnd),
    ])

p = expression.parseString('var[3] = 1 AND var[1] = 0', True)

print 'SUCCESS' if bool(p) else 'FAIL'

I have three problems I need help with.

For multibit access of the form var[X:Y] = Z, how do I enforce that:

a. X > Y

b. Z < 2^{X - Y + 1}

I assume this can't be enforced by the grammar itself (for example, for single-bit access of the form var[X] = Y, I can enforce by the grammar that Y will be either 0 or 1, and this will cause the expression.parseString() to fail with exception if Y != 0/1).

Most importantly: Why does it always print SUCCESS? What am I doing wrong?

For the input var[3] = 1 AND var[1] = 0 it should be print FAIL (you can see in my example that I hardcoded var to be 0xf, so var[3] = 1 is True but var[1] = 0 is False).

Which brings me to my third problem: var is not a class member of BoolEqual nor is it global... is there a way to somehow send it to BoolEqual's __init__ function?

Body:
How about converting the variable to a list of 1 and 0's and using eval to evaluate the boolean expressions (with a small modification, changing = into ==) :

def parse(lines, v):
    var = map(int,list(bin(v)[2:]))
    result = []

    for l in lines:
        l = l.replace('=','==')
        result.append(eval(l))

    return result

inp = \
"""
var[3] = 0 and var[2] = 1
var[0] = 1 and var[2] = 0 and var[3] = 1
"""

lines = inp.split('\n')[1:-1]
v = 0x09

print parse(lines, v)

Output:

[False, True]

Note that you should only use eval if your trust the input.

ContentLicense: CC BY-SA 3.0


问:
weak linking in shared object not working as expected
I'm trying to use the cmocka unit test framework which suggests to use weak linking to be able to select a user-defined implementation over the actual implementation of a function. In my environment I have a shared object which I want to unit test. I've implemented the unit tests in a separate file which I compile and link to the shared object. My problem is that calling a function bar in the shared object which in turn calls a function foo in that shared object always leads to the real implementation of foo and not the custom one. I've created a simplified implementation of the shared object and of the unit test.

The shared library, a.c:

```<code>#include <stdio.h>

void foo(void); __attribute__((weak))
void bar(void); __attribute__((weak))

void foo(void) {
    printf("called real foo\n");
}

void bar(void) {
    printf("called real bar calling\n");
    foo();
}
</code>```

The unit test, b.c:

```<code>#include <stdio.h>
#include <stdbool.h>

bool orig_foo;
bool orig_bar;

void __wrap_foo(void) {
    printf("in foo wrapper\n");
    if (orig_foo)
            __real_foo();
    else
            printf("called wrapped foo\n");
}

void __wrap_bar() {
    printf("in bar wrapper\n");
    if (orig_bar)
            __real_bar();
    else
            printf("called wrapped bar\n");
}

int main(void) {

    orig_bar = true;
    orig_foo = false;

    printf("calling foo from main\n");
    foo();

    printf("\n");

    printf("calling bar from main\n");
    bar();

    return 0;
}
</code>```

And finally, the Makefile:

```<code>all: a.out

a.out: b.c a.so
    gcc -Wall b.c a.so -Wl,--wrap=foo -Wl,--wrap=bar

a.so: a.c
    gcc -Wall -c a.c -shared -o a.so

clean:
    rm -f a.so a.out
</code>```

Running a.out produces the following output:

```<code># ./a.out
calling foo from main
in foo wrapper
called wrapped foo

calling bar from main
in bar wrapper
called real bar
called real foo
</code>```

From main, the direct call to foo results in __wrap_foo being called, as expected.

Next, I call bar from main which correctly results in __wrap_bar being called, where I redirect the call to the real implementation of bar (__real_bar). bar then calls foo but the real implementation is used, not the wrapped one. Why isn't the wrapped implementation of foo called in this case? It looks like the issue is related to from where the function call originates.

In function bar, if I replaced the called to foo with __wrap_foo I do get the expected behaviour however I don't think that this is an elegant solution.

I've managed to bypass this problem using normal linking and dlopen(3) and friends however I'm curious as to why weak linking isn't working in my case.

答:
Ld's --wrap works by replacing calls to real functions by calls to their wrappers only in files which are linked with this flag. Your library isn't, so it just does plain foo and bar calls. So they get resolved to where they are implemented (a.so).

As for weak symbols, dynamic linker ignores their weakness and treats them as normal symbols (unless you run with LD_DYNAMIC_WEAK which isn't recommended).

In your particular case (overriding symbols in shared library) you'd probably need to apply --wrap to a.so as well. Or - you could use standard symbol interposition. Say if library-under-test is in libsut.so and you want to replace some functions with custom implementations in libstub.so, link them to driver program in a proper order:

```<code>LDFLAGS += -lstub -lsut
</code>```

Then definitions in libstub.so will prevail over libsut.so ones.

Body:
I'm trying to use the cmocka unit test framework which suggests to use weak linking to be able to select a user-defined implementation over the actual implementation of a function. In my environment I have a shared object which I want to unit test. I've implemented the unit tests in a separate file which I compile and link to the shared object. My problem is that calling a function bar in the shared object which in turn calls a function foo in that shared object always leads to the real implementation of foo and not the custom one. I've created a simplified implementation of the shared object and of the unit test.

The shared library, a.c:

#include <stdio.h>

void foo(void); __attribute__((weak))
void bar(void); __attribute__((weak))

void foo(void) {
    printf("called real foo\n");
}

void bar(void) {
    printf("called real bar calling\n");
    foo();
}

The unit test, b.c:

#include <stdio.h>
#include <stdbool.h>

bool orig_foo;
bool orig_bar;

void __wrap_foo(void) {
    printf("in foo wrapper\n");
    if (orig_foo)
            __real_foo();
    else
            printf("called wrapped foo\n");
}

void __wrap_bar() {
    printf("in bar wrapper\n");
    if (orig_bar)
            __real_bar();
    else
            printf("called wrapped bar\n");
}

int main(void) {

    orig_bar = true;
    orig_foo = false;

    printf("calling foo from main\n");
    foo();

    printf("\n");

    printf("calling bar from main\n");
    bar();

    return 0;
}

And finally, the Makefile:

all: a.out

a.out: b.c a.so
    gcc -Wall b.c a.so -Wl,--wrap=foo -Wl,--wrap=bar

a.so: a.c
    gcc -Wall -c a.c -shared -o a.so

clean:
    rm -f a.so a.out

Running a.out produces the following output:

# ./a.out
calling foo from main
in foo wrapper
called wrapped foo

calling bar from main
in bar wrapper
called real bar
called real foo

From main, the direct call to foo results in __wrap_foo being called, as expected.

Next, I call bar from main which correctly results in __wrap_bar being called, where I redirect the call to the real implementation of bar (__real_bar). bar then calls foo but the real implementation is used, not the wrapped one. Why isn't the wrapped implementation of foo called in this case? It looks like the issue is related to from where the function call originates.

In function bar, if I replaced the called to foo with __wrap_foo I do get the expected behaviour however I don't think that this is an elegant solution.

I've managed to bypass this problem using normal linking and dlopen(3) and friends however I'm curious as to why weak linking isn't working in my case.

Body:
Ld's --wrap works by replacing calls to real functions by calls to their wrappers only in files which are linked with this flag. Your library isn't, so it just does plain foo and bar calls. So they get resolved to where they are implemented (a.so).

As for weak symbols, dynamic linker ignores their weakness and treats them as normal symbols (unless you run with LD_DYNAMIC_WEAK which isn't recommended).

In your particular case (overriding symbols in shared library) you'd probably need to apply --wrap to a.so as well. Or - you could use standard symbol interposition. Say if library-under-test is in libsut.so and you want to replace some functions with custom implementations in libstub.so, link them to driver program in a proper order:

LDFLAGS += -lstub -lsut

Then definitions in libstub.so will prevail over libsut.so ones.


问:
ArangoDB - Collection not found error though the collection is created
I am creating an edge "has_taken" between two documents as follows:

sin_graph.createEdge("has_taken", userDoc._id, tripDoc._id, edgeAttributes={})

And I am getting the following error:

File "/Library/Python/2.7/site-packages/pyArango/graph.py", line 135, in createEdge
raise CreationError("Unable to create edge, %s" % r.json()["errorMessage"], data)
CreationError: Unable to create edge, collection not found. Errors: {u'code': 404, u'errorNum': 1203, u'errorMessage': u'collection not found', u'error': True}

The collection with the name "has_taken" is present and yet I am getting the above error.

答:
I have transpiled the social graph example example to pyArango; It ilustrates the sequence of things to do when maintaining graph data with it:</p>

```<code>#!/usr/bin/python
import sys
from pyArango.connection import *
from pyArango.graph import *
from pyArango.collection import *

class Social(object):
        class male(Collection) :
            _fields = {
                "name" : Field()
            }

        class female(Collection) :
            _fields = {
                "name" : Field()
            }

        class relation(Edges) :
            _fields = {
                "number" : Field()
            }

        class social(Graph) :

            _edgeDefinitions = (EdgeDefinition ('relation',
                                                fromCollections = ["female", "male"],
                                                toCollections = ["female", "male"]),)
            _orphanedCollections = []

        def __init__(self):
               self.conn = Connection(username="root", password="")

               self.db = self.conn["_system"]
               if self.db.hasGraph('social'):
                   raise Exception("The social graph was already provisioned! remove it first")

               self.female   = self.db.createCollection("female")
               self.male     = self.db.createCollection("male")

               self.relation = self.db.createCollection("relation")

               g = self.db.createGraph("social")

               a = g.createVertex('female', {"name": 'Alice',  "_key": 'alice'});
               b = g.createVertex('male',  {"name": 'Bob',    "_key": 'bob'});
               c = g.createVertex('male',   {"name": 'Charly', "_key": 'charly'});
               d = g.createVertex('female', {"name": 'Diana',  "_key": 'diana'});
               a.save()
               b.save()
               c.save()
               d.save()

               g.link('relation', a, b, {"type": 'married', "_key": 'aliceAndBob'})
               g.link('relation', a, c, {"type": 'friend', "_key": 'aliceAndCharly'})
               g.link('relation', c, d, {"type": 'married', "_key": 'charlyAndDiana'})
               g.link('relation', b, d, {"type": 'friend', "_key": 'bobAndDiana'})

Social()
</code>```

Body:
I have transpiled the social graph example example to pyArango; It ilustrates the sequence of things to do when maintaining graph data with it:

#!/usr/bin/python
import sys
from pyArango.connection import *
from pyArango.graph import *
from pyArango.collection import *

class Social(object):
        class male(Collection) :
            _fields = {
                "name" : Field()
            }

        class female(Collection) :
            _fields = {
                "name" : Field()
            }

        class relation(Edges) :
            _fields = {
                "number" : Field()
            }

        class social(Graph) :

            _edgeDefinitions = (EdgeDefinition ('relation',
                                                fromCollections = ["female", "male"],
                                                toCollections = ["female", "male"]),)
            _orphanedCollections = []

        def __init__(self):
               self.conn = Connection(username="root", password="")

               self.db = self.conn["_system"]
               if self.db.hasGraph('social'):
                   raise Exception("The social graph was already provisioned! remove it first")

               self.female   = self.db.createCollection("female")
               self.male     = self.db.createCollection("male")

               self.relation = self.db.createCollection("relation")

               g = self.db.createGraph("social")

               a = g.createVertex('female', {"name": 'Alice',  "_key": 'alice'});
               b = g.createVertex('male',  {"name": 'Bob',    "_key": 'bob'});
               c = g.createVertex('male',   {"name": 'Charly', "_key": 'charly'});
               d = g.createVertex('female', {"name": 'Diana',  "_key": 'diana'});
               a.save()
               b.save()
               c.save()
               d.save()

               g.link('relation', a, b, {"type": 'married', "_key": 'aliceAndBob'})
               g.link('relation', a, c, {"type": 'friend', "_key": 'aliceAndCharly'})
               g.link('relation', c, d, {"type": 'married', "_key": 'charlyAndDiana'})
               g.link('relation', b, d, {"type": 'friend', "_key": 'bobAndDiana'})

Social()


问:
PDO query binding string instead of integer returns results
I have a table with and auto increment id and was just testing a few scenarios when I stumbled across a problem whereby PDO or mysql seems to convert a string to an integer when in an array.  Does anyone know why?

If my query is as follows:

```<code>$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>1));
</code>```

it retrieves 1 record - all fine, but if the query uses a string either by design or mistake as follows:

```<code>$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>'1 OR id > 0'));
</code>```

it still retrieves a record with id=1.

Surely nothing should be found?  I appreciate I should never allow the 2nd scenario to happen but why is PDO / mysql converting the string to an integer and how is it doing it?

Body:
I have a table with and auto increment id and was just testing a few scenarios when I stumbled across a problem whereby PDO or mysql seems to convert a string to an integer when in an array.  Does anyone know why?

If my query is as follows:

$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>1));

it retrieves 1 record - all fine, but if the query uses a string either by design or mistake as follows:

$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>'1 OR id > 0'));

it still retrieves a record with id=1.

Surely nothing should be found?  I appreciate I should never allow the 2nd scenario to happen but why is PDO / mysql converting the string to an integer and how is it doing it?

Body:
For good or bad, that's how MySQL is designed to behave:

mysql> SELECT CASE
    -> WHEN 123='123 pink elephants' THEN 'Equal'
    -> ELSE 'Different' END
    -> AS 'How are they?';
+---------------+
| How are they? |
+---------------+
| Equal         |
+---------------+
1 row in set, 1 warning (0.00 sec)

As you can see, though, it triggers a warning:

mysql> SHOW WARNINGS;
+---------+------+--------------------------------------------------------+
| Level   | Code | Message                                                |
+---------+------+--------------------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: '123 pink elephants' |
+---------+------+--------------------------------------------------------+
1 row in set (0.00 sec)


答: With prepared statements and placeholders, the database knows to expect a value that suits the column type.  I would expect that it sees your numeric id column and casts the '1 or id > 0' to a number - so you just get the 1.</p>

Title: PDO query binding string instead of integer returns results


问:
Is this a bad practice to catch a non-specific exception such as System.Exception? Why?
I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? If so, how do I explain to my colleague that this is wrong (stubborn type...)?

Catch a generic exception (Exception ex)

The use of "if (ex is something)" instead of having another catch block

We eat SoapException, HttpException and WebException. But if the Web Service failed, there not much to do.

Code:

```<code>try
{
    // Call to a WebService
}
catch (Exception ex)
{
    if (ex is SoapException || ex is HttpException || ex is WebException)
    {
        // Log Error and eat it.
    }
    else
    {
        throw;
    }
}
</code>```

答:
Sometimes that is to only way to handle "catch every exception" scenarios, without actually catching every exception.

I think sometimes, say, lowlevel framework / runtime code needs to make sure that no exception is ever escaping.  Unfortunately, there is also no way the framework code can know which exceptions are raised by the code executed by the thread.

In that case a possible catch block could look like this:

```<code>try
{
   // User code called here
}
catch (Exception ex)
{
   if (ExceptionIsFatal(ex))
     throw;

   Log(ex);
}
</code>```

There are three important points here, however:

This isn't something for every situation. In code reviews we are very picky about places where this is actually neccessary and thus allowed.

The ExceptionIsFatal() method assures that we don't eat exceptions which should never be swallowed (ExecutionEngineException, OutOfMemoryException, ThreadAbortException, etc.)

What is swallowed is carefully logged (event-log, log4net, YMMV)

Typically, I'm all for the practice of letting uncaught exceptions simply "crash" the application by terminating the CLR. However, especially in server applications, this is sometimes not sensible. If one thread encounters a problem which is deemed non-fatal, there is no reason in ripping the whole process down, killing off all other running requests (WCF, for example, handles some cases this way).

ContentLicense: CC BY-SA 2.5

Body:
I am currently doing a code review and the following code made me jump. I see multiple issues with this code. Do you agree with me? If so, how do I explain to my colleague that this is wrong (stubborn type...)?

Catch a generic exception (Exception ex)

The use of "if (ex is something)" instead of having another catch block

We eat SoapException, HttpException and WebException. But if the Web Service failed, there not much to do.

Code:

try
{
    // Call to a WebService
}
catch (Exception ex)
{
    if (ex is SoapException || ex is HttpException || ex is WebException)
    {
        // Log Error and eat it.
    }
    else
    {
        throw;
    }
}

LastEditorDisplayName: Michael Haren

Body:
Sometimes that is to only way to handle "catch every exception" scenarios, without actually catching every exception.

I think sometimes, say, lowlevel framework / runtime code needs to make sure that no exception is ever escaping.  Unfortunately, there is also no way the framework code can know which exceptions are raised by the code executed by the thread.

In that case a possible catch block could look like this:

try
{
   // User code called here
}
catch (Exception ex)
{
   if (ExceptionIsFatal(ex))
     throw;

   Log(ex);
}

There are three important points here, however:

This isn't something for every situation. In code reviews we are very picky about places where this is actually neccessary and thus allowed.

The ExceptionIsFatal() method assures that we don't eat exceptions which should never be swallowed (ExecutionEngineException, OutOfMemoryException, ThreadAbortException, etc.)

What is swallowed is carefully logged (event-log, log4net, YMMV)

Typically, I'm all for the practice of letting uncaught exceptions simply "crash" the application by terminating the CLR. However, especially in server applications, this is sometimes not sensible. If one thread encounters a problem which is deemed non-fatal, there is no reason in ripping the whole process down, killing off all other running requests (WCF, for example, handles some cases this way).


问:
How to mail in C# with the Gmail SMTP server?

Possible Duplicate:

  Sending email through Gmail SMTP server with C#

For mailing with C# and using the Gmail SMTP server is there any kind of tricky thing that we should do? Because after lot of searching I found some ways for doing this, but I'm getting a failure exception as a result. I guess it's because I don't handle TSL for Gmail (because it works with TSL), but I don't know how to handle TSL with C# for doing this. I really appreciate any help or link to a useful sample. Here's my code:

```<code>public string SendMail(string senderMail, string receiverMail, string attachmentPath)
{
  var fromMailAddress = new MailAddress(senderMail);
  var toMailAddress = new MailAddress(receiverMail);

  MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress);
  mailMessage.Subject = "My Subject";
  mailMessage.Body = "This is the body of this message for testing purposes";

  Attachment attachFile = new Attachment(attachmentPath);
  mailMessage.Attachments.Add(attachFile);

  SmtpClient emailClient = new SmtpClient();

  NetworkCredential credential = new NetworkCredential();
  credential.UserName = fromMailAddress.User;
  credential.Password = "password";

  emailClient.Credentials = credential;
  emailClient.Port = 587;
  emailClient.Host = "smtp.gmail.com";

  //emailClient.EnableSsl = true; //Here should be for TSL, but how?

  emailClient.Send(mailMessage);
}
</code>```

答:
You should tell the message of the exception.
But yes, uncomment that emailClient.EnableSsl = true;
If it still not working, your firewall or router is problably blocking the ports.</p>

Body:
Possible Duplicate:

  Sending email through Gmail SMTP server with C#

For mailing with C# and using the Gmail SMTP server is there any kind of tricky thing that we should do? Because after lot of searching I found some ways for doing this, but I'm getting a failure exception as a result. I guess it's because I don't handle TSL for Gmail (because it works with TSL), but I don't know how to handle TSL with C# for doing this. I really appreciate any help or link to a useful sample. Here's my code:

public string SendMail(string senderMail, string receiverMail, string attachmentPath)
{
  var fromMailAddress = new MailAddress(senderMail);
  var toMailAddress = new MailAddress(receiverMail);

  MailMessage mailMessage = new MailMessage(fromMailAddress, toMailAddress);
  mailMessage.Subject = "My Subject";
  mailMessage.Body = "This is the body of this message for testing purposes";

  Attachment attachFile = new Attachment(attachmentPath);
  mailMessage.Attachments.Add(attachFile);

  SmtpClient emailClient = new SmtpClient();

  NetworkCredential credential = new NetworkCredential();
  credential.UserName = fromMailAddress.User;
  credential.Password = "password";

  emailClient.Credentials = credential;
  emailClient.Port = 587;
  emailClient.Host = "smtp.gmail.com";

  //emailClient.EnableSsl = true; //Here should be for TSL, but how?

  emailClient.Send(mailMessage);
}


问:
GET Web API Method returns method not allowed
I am developing web api project that will be mediator between our website and third party service and my website need to call my api where my api will adapt the request in the way third party service is expecting it, however I am getting method not allowed on my get method and I am kinda stuck. I've tried enabling CORS, but it still doesn't help , I've checked if our website is really calling with GET verb and it does, but my Web API is still returning:

The remote server returned an error: (405) Method Not Allowed.

This is the code of the method that our website is calling:

```<code>public IHttpActionResult CommitReserve()
{
    var request = this.Request;
    this.Logger.InfoFormat("CommitReserve: {0}", request.RequestUri);

    try
    {
        var customerID = request.GetRequestParameter<string>("cust_id");
        var reserveID = request.GetRequestParameter<int>("reserve_id");
        this.Logger.InfoFormat("CommitReserve: ReserveId: {0}, CustID: {1}", reserveID, customerID);

        HttpResponseMessage response = new HttpResponseMessage();
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("error_code=" + 0);
        sb.AppendLine("error_message=");
        sb.AppendLine("trx_id=" + reserveID);
        sb.Append("balance=" + 0);

        response.Content = new StringContent(sb.ToString());
        response.StatusCode = HttpStatusCode.OK;
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

        return this.ResponseMessage(response);
   }
   catch (Exception ex)
   {
        this.Logger.ErrorFormat("CommitReserve: {0}" + ex);
        return this.BadRequest(ex.Message);
   }
}
</code>```

and this is how I enabled CORS:

```<code>config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
</code>```

I know its bad the way I did it but it is just for test t osee if this is really the problem , turns out it is not.

This is the request that I am sending with postman and it fails:

```<code>GET http://localhost:60747/api/Reserve/CommitReserve?cust_id=32569_5001&reserve_id=62150259&SportTypeID=sport HTTP/1.1
Host: localhost:60747
Proxy-Connection: keep-alive
Postman-Token: 8f26fb31-d59d-78c8-2399-3b46c4beeff5
Cache-Control: no-cache
cust_id: 32569_5001
reserve_id: 62148599
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36
amount: 2
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,pt;q=0.6
</code>```

So I ran out of options here..

**EDITS **

WebApiConfig.cs as requested:

```<code>public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}
</code>```

答:
Are you returning JSON? If so, you need to explicitly allow GET:</p>

```<code>return Json(data, JsonRequestBehavior.AllowGet);
</code>```

Body:
I am developing web api project that will be mediator between our website and third party service and my website need to call my api where my api will adapt the request in the way third party service is expecting it, however I am getting method not allowed on my get method and I am kinda stuck. I've tried enabling CORS, but it still doesn't help , I've checked if our website is really calling with GET verb and it does, but my Web API is still returning:

The remote server returned an error: (405) Method Not Allowed.

This is the code of the method that our website is calling:

public IHttpActionResult CommitReserve()
{
    var request = this.Request;
    this.Logger.InfoFormat("CommitReserve: {0}", request.RequestUri);

    try
    {
        var customerID = request.GetRequestParameter<string>("cust_id");
        var reserveID = request.GetRequestParameter<int>("reserve_id");
        this.Logger.InfoFormat("CommitReserve: ReserveId: {0}, CustID: {1}", reserveID, customerID);

        HttpResponseMessage response = new HttpResponseMessage();
        StringBuilder sb = new StringBuilder();

        sb.AppendLine("error_code=" + 0);
        sb.AppendLine("error_message=");
        sb.AppendLine("trx_id=" + reserveID);
        sb.Append("balance=" + 0);

        response.Content = new StringContent(sb.ToString());
        response.StatusCode = HttpStatusCode.OK;
        response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");

        return this.ResponseMessage(response);
   }
   catch (Exception ex)
   {
        this.Logger.ErrorFormat("CommitReserve: {0}" + ex);
        return this.BadRequest(ex.Message);
   }
}

and this is how I enabled CORS:

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

I know its bad the way I did it but it is just for test t osee if this is really the problem , turns out it is not.

This is the request that I am sending with postman and it fails:

GET http://localhost:60747/api/Reserve/CommitReserve?cust_id=32569_5001&reserve_id=62150259&SportTypeID=sport HTTP/1.1
Host: localhost:60747
Proxy-Connection: keep-alive
Postman-Token: 8f26fb31-d59d-78c8-2399-3b46c4beeff5
Cache-Control: no-cache
cust_id: 32569_5001
reserve_id: 62148599
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,    like Gecko) Chrome/56.0.2924.87 Safari/537.36
amount: 2
Accept: */*
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,pt;q=0.6

So I ran out of options here..

**EDITS **

WebApiConfig.cs as requested:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Body:
Are you returning JSON? If so, you need to explicitly allow GET:

return Json(data, JsonRequestBehavior.AllowGet);


问:
What is the meaning of the specific digits in eclipse log?
I need  to know what is the meaning of part of the Eclipse log. For example:

```<code>!ENTRY org.eclipse.ui.navigator 2 0 2017-03-31 13:07:11.248
!MESSAGE Warning: popupMenuId of ".....
</code>```

After the plugin ID there are 2 and 0, I think the 2 is the severity, which is warning in this case but could  you tell me about the second digit?

答:
The first number is the severity.

The second number is the 'bundle code' which is an error number from the code generating the error. This is usually from the IStatus getCode value. For example in:

```<code>IStatus status = new Status(IStatus.ERROR, "plugin id", 123, "message", exception);

Activator.getLog().log(status);
</code>```

123 is the error number.

Some plugins such as org.eclipse.core.resources use the error number a lot to distinguish different errors (see IResourceStatus), other plugins less so.

Body:
I need  to know what is the meaning of part of the Eclipse log. For example:

!ENTRY org.eclipse.ui.navigator 2 0 2017-03-31 13:07:11.248
!MESSAGE Warning: popupMenuId of ".....

After the plugin ID there are 2 and 0, I think the 2 is the severity, which is warning in this case but could  you tell me about the second digit?

Body:
The first number is the severity.

The second number is the 'bundle code' which is an error number from the code generating the error. This is usually from the IStatus getCode value. For example in:

IStatus status = new Status(IStatus.ERROR, "plugin id", 123, "message", exception);

Activator.getLog().log(status);

123 is the error number.

Some plugins such as org.eclipse.core.resources use the error number a lot to distinguish different errors (see IResourceStatus), other plugins less so.


问:
querySelector needs time out in ionic page / angular
This works:

```<code> ionViewDidLoad() {

  var that = this;

          setTimeout(function () {
              that.img = that.el.nativeElement.querySelector('.user-image');
              alert(that.img.src);
          }, 300);
}
</code>```

This doesn't

```<code>ionViewDidLoad() {

      var that = this;
      that.img = that.el.nativeElement.querySelector('.user-image');
      alert(that.img.src);

}
</code>```

I am sure this is not correct behavior. And I really don't want to have to set a time out to get this. So why is this the case and how can it be fixed?

Int the html file I have:

```<code><img class="user-image img-responsive full-width " *ngIf="user.pictureURL" src="myurl.com{{user.pictureURL}}"  />
</code>```

答:
This is because the html template may get loaded after the call.
You need to use ViewChild to get the ElementRef

```<code><img #imageId class="user-image img-responsive full-width " *ngIf="user.pictureURL" src="myurl.com{{user.pictureURL}}"  /><!--set id with # -->
</code>```

In component:

```<code>import {ViewChild, ElementRef} from '@angular/core';

//...In class,
@ViewChild('imageId') imageElement:ElementRef;

ionViewDidLoad() {
   alert(this.imageElement.nativeElement.src);

}
</code>```

Body:
This works:

 ionViewDidLoad() {

  var that = this;

          setTimeout(function () {
              that.img = that.el.nativeElement.querySelector('.user-image');
              alert(that.img.src);
          }, 300);
}

This doesn't

ionViewDidLoad() {

      var that = this;
      that.img = that.el.nativeElement.querySelector('.user-image');
      alert(that.img.src);

}

I am sure this is not correct behavior. And I really don't want to have to set a time out to get this. So why is this the case and how can it be fixed?

Int the html file I have:

Body:
This is because the html template may get loaded after the call.
You need to use ViewChild to get the ElementRef

<img #imageId class="user-image img-responsive full-width " *ngIf="user.pictureURL" src="myurl.com{{user.pictureURL}}"  /><!--set id with # -->

In component:

import {ViewChild, ElementRef} from '@angular/core';

//...In class,
@ViewChild('imageId') imageElement:ElementRef;

ionViewDidLoad() {
   alert(this.imageElement.nativeElement.src);

}


问:
Update records from MySQL to SQL Server
I have the same tables in two different databases, one is on MySQL and the other one on SQL Server. I want to run a query to get the data from a MySQL table to a SQL Server table to update the records on daily basis.

E.g. I have 200 record in MySQL today by tomorrow it might be 300. I want to update 200 records today and the only 100 new record tomorrow.

Can any one help me please?

Thanks in advance

答:
Probably the best way to manage this is from the SQL Server database.  This allows that database to pull the data in every day, rather than having the MySQL database push the data.

The place to start is by linking the servers.  Start with the documentation on the subject.  Next, set up a job in SQL Server Agent.  This job would do the following:

Connect to the MySQL server.

Load the data into a staging table.

Validate the data.

Update or insert the data into the final table.

You can schedule this job to run every day.

Note that 200 or 300 records is very small by the standards of databases (unless the records are really, really big).

Title: Update records from MySQL to SQL Server


问:
How do you compile the Hello World program for Java?
I am at step 6 in the process of installing JDK onto windows using instructions from  this website .

When I attempt to “Set the Current Drive to the drive where you saved your source file Hello.java” by typing “c:”, nothing happens (the instructions indicate that something like C:\xxx> should appear).

I have saved the hello world file in the C: directory as indicated in the previous step (step 5).

I am trying to start learning Java and any help would be appreciated.

答:
1)After Installing JDK, Make Sure Java_Home Path is set. Find it Here!

2)After that, Create a new file at Desktop and name it "MyFirstJavaProgram.java"

3) Right click and open newly created file in notepad.
4) Insert following code into it.

```<code>public class MyFirstJavaProgram {

   /* This is my first java program.
    * This will print 'Hello World' as the output
    */

   public static void main(String []args) {
      System.out.println("Hello World"); // prints Hello World
   }
}
</code>```

5) To Compile that program, open command prompt and browse its current path to Desktop.

6) Write command "javac MyFirstJavaProgram.java"

7) to watch output of your program write command "java MyFirstJavaProgram" your output will be at console.

Body:
1)After Installing JDK, Make Sure Java_Home Path is set. Find it Here!

2)After that, Create a new file at Desktop and name it "MyFirstJavaProgram.java"

3) Right click and open newly created file in notepad.
4) Insert following code into it.

public class MyFirstJavaProgram {

   /* This is my first java program.
    * This will print 'Hello World' as the output
    */

   public static void main(String []args) {
      System.out.println("Hello World"); // prints Hello World
   }
}

5) To Compile that program, open command prompt and browse its current path to Desktop.

6) Write command "javac MyFirstJavaProgram.java"

7) to watch output of your program write command "java MyFirstJavaProgram" your output will be at console.


问:
Yii Framework 2.0 -findModel returns an empty object
I am trying to show the form values which I have stored in the database.But it's not happening and also returning the empty values.I have added whatever I did.

Controller

```<code>protected function findModel($id)
    {
        if (($model = UserRegistration::find($id)->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
</code>```

Model

this is my model.I have declared all variables as public.Is that a problem? If I remove im getting error also.

```<code>class UserRegistration extends ActiveRecord
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $Country;
    public $State;
    public $City;
    public $phone_number;
    public $about_me;
    public $password;
    public $verify_password;
    public $photo;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['username','password', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'teespring_id'], 'integer'],
            [['username','lastname','firstname', 'password_hash', 'password_reset_token', 'email','about_me'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['role'], 'string', 'max' => 10],
            [['email','username'],'email'],
            [['email','username','password_reset_token'], 'unique'],
            ['phone_number','string','length'=>10],
            [['Country','State','City'],'string'],
            ['verify_password','compare','compareAttribute'=>'password'],
            [['photo'],'file', 'extensions' => 'png, jpg']
        ];
    }
}
</code>```

Update: I have tried $model = UserRegistration::findOne($id) also.no luck
Please help me.

答:
Its look strange. This model looks like a ModelForm for User registration and it doesn`t need to have a table.

I think you have a User model also, so u should try to User::findOne($id)

If you have just one model for User and Registration, then you should not set attributes as public if it in table.

So you need just public $verify_password, because u dont have this row in table i guess. And i think you dont have the photo row in table, because usually photos name is user_id. In that case u should set it as public too.

Can u get all your rows from User table so i can create a right model for u?

Body:
I am trying to show the form values which I have stored in the database.But it's not happening and also returning the empty values.I have added whatever I did.

Controller

protected function findModel($id)
    {
        if (($model = UserRegistration::find($id)->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

Model

this is my model.I have declared all variables as public.Is that a problem? If I remove im getting error also.

class UserRegistration extends ActiveRecord
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $Country;
    public $State;
    public $City;
    public $phone_number;
    public $about_me;
    public $password;
    public $verify_password;
    public $photo;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['username','password', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'teespring_id'], 'integer'],
            [['username','lastname','firstname', 'password_hash', 'password_reset_token', 'email','about_me'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['role'], 'string', 'max' => 10],
            [['email','username'],'email'],
            [['email','username','password_reset_token'], 'unique'],
            ['phone_number','string','length'=>10],
            [['Country','State','City'],'string'],
            ['verify_password','compare','compareAttribute'=>'password'],
            [['photo'],'file', 'extensions' => 'png, jpg']
        ];
    }
}

Update: I have tried $model = UserRegistration::findOne($id) also.no luck
Please help me.


问:
ffmpeg library is not working
I have got FFmpeg compiled (libffmpeg.so) on Android. Now I have to build either an application like RockPlayer or use existing Android multimedia framework to invoke FFmpeg along with video playing.

Do you have steps / procedures / code / example on integrating FFmpeg on Android / StageFright?

Can you please guide me on how can I use this library for multimedia
  playback?

I already did rendering, mixing.

答:
compile 'com.writingminds:FFmpegAndroid:0.3.2'   add this to gradle

Add this inside onCreate :

ffmpeg = FFmpeg.getInstance(this.getApplicationContext());

(Declare FFmpeg ffmpeg; first)

Load library :    loadFFMpegBinary();

Code to add audio to video using ffmpeg:

call function using  execFFmpegBinaryShortest(null);

**

```<code>private void execFFmpegBinaryShortest(final String[] command) {
    final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");

   String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};

            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {

                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");

                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }

            }
</code>```

**

Title: ffmpeg library is not working

Body:
compile 'com.writingminds:FFmpegAndroid:0.3.2'   add this to gradle

Add this inside onCreate :

ffmpeg = FFmpeg.getInstance(this.getApplicationContext());

(Declare FFmpeg ffmpeg; first)

Load library :    loadFFMpegBinary();

Code to add audio to video using ffmpeg:

call function using  execFFmpegBinaryShortest(null);

**

private void execFFmpegBinaryShortest(final String[] command) {
    final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");

   String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};

            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {

                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");

                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }

            }

**


问:
How do I go about writing new controls in VB6?
I'm looking to create controls based on text boxes that validate numeric fields and restrict them to certain ranges without having to write all the callbacks for each control on the form.

Does anyone know of a tutorial on how to create and use such things?

Or alternatively, as I can't be the first person to have this requirement, are there a set of such controls available for use anywhere?

答:
The simplest way is to use control arrays. Google turned up this tutorial. You could encode the minimum/maximum range into the Tag property of each individual control, or you could use the Index to look them up from arrays.

You can create a user-defined control in VB6 but I'm not sure it's worthwhile for this task. You have to write a lot of boilerplate code.


问:
Using a shell script involving echo to add student header to C++ files: Replaces \n with actual newline, any way to change behavior?
I'm taking a C++ course that requires a student header at the top of every submitted file. Typing it or yank/paste-ing is so tedious, I've been working on a script to just add it for me. I've got something that works for me so far, but I just noticed that every \n in any string in the files that it operates on are replaced with an actual newline. I'm guessing this is either a result of the use of cat or echo in the script, and I'm trying to figure out how to avoid that.

The manpage for echo says that the default behavior is to ignore backslash escapes, but I'm not entirely sure how that relates to what I'm trying to do.

My script is:

```<code>#!/bin/bash

NAME="Joseph Morgan"
CLASS="CISP 400 MoWe 3:00pm"
ASSIGNMENT=$1
DATE=$(date -I)

if [[ $# -eq 0 ]] ; then
    echo 'Argument required:'
    echo 'Usage: SOME_PROJECT_NAME [Adds project name to header] | d [Deletes header]'
    exit 0
fi

if [ $1 == "d" ] ; then
    echo 'Deleting header - Be careful! If no header is present, the first five lines of your files will be deleted'
    read -p "Are you sure? (y/n)" -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
        for f in ./*.cpp ;
        do
            echo "$(tail -n +6 $f)" > $f
        done
        for f in ./*.h ;
        do
            echo "$(tail -n +6 $f)" > $f
        done
    fi
    exit 0
fi

for f in ./*.cpp ;
do
    echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n$(cat $f)" > $f
done

for f in ./*.h ;
do
    echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n$(cat $f)" > $f
done
</code>```

If there is another way entirely to accomplish this, feel free to suggest it. I'm much more interested in learning here, the script was just for fun/education so it's not incredibly important.

Thanks!

答:
The problem is with -e parameter given to echo(1) command, which makes it interpret \n as a new line. Delete that -e and it will work. I mean, you need that -e, when you write your own headers, but you should move the $(cat $f) outside of the "echo -e". For example, in two lines:

```<code>echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n" > $f
echo "$(cat $f)" >> $f    # notice the double angle >>
</code>```

BUT BEWARE, that would erase your file before reading it. Even here there is a problem:

echo "$(tail -n +6 $f)" > $f

because it could erase (empty) the "$f" file before reading it. You could do instead:

```<code>newcontent=$(tail -n +6 $f)
echo "$newcontent" > $f
</code>```

So, to add your headers, use two distinct echoes, but read the file before writing in it:

```<code>newcontent="$(cat $f)"
echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n" > $f
echo "$newcontent" >> $f    # notice the double angle >>
</code>```

I hope it helps.

Body:
I'm taking a C++ course that requires a student header at the top of every submitted file. Typing it or yank/paste-ing is so tedious, I've been working on a script to just add it for me. I've got something that works for me so far, but I just noticed that every \n in any string in the files that it operates on are replaced with an actual newline. I'm guessing this is either a result of the use of cat or echo in the script, and I'm trying to figure out how to avoid that.

The manpage for echo says that the default behavior is to ignore backslash escapes, but I'm not entirely sure how that relates to what I'm trying to do.

My script is:

#!/bin/bash

NAME="Joseph Morgan"
CLASS="CISP 400 MoWe 3:00pm"
ASSIGNMENT=$1
DATE=$(date -I)

if [[ $# -eq 0 ]] ; then
    echo 'Argument required:'
    echo 'Usage: SOME_PROJECT_NAME [Adds project name to header] | d [Deletes header]'
    exit 0
fi

if [ $1 == "d" ] ; then
    echo 'Deleting header - Be careful! If no header is present, the first five lines of your files will be deleted'
    read -p "Are you sure? (y/n)" -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]
    then
        for f in ./*.cpp ;
        do
            echo "$(tail -n +6 $f)" > $f
        done
        for f in ./*.h ;
        do
            echo "$(tail -n +6 $f)" > $f
        done
    fi
    exit 0
fi

for f in ./*.cpp ;
do
    echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n$(cat $f)" > $f
done

for f in ./*.h ;
do
    echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n$(cat $f)" > $f
done

If there is another way entirely to accomplish this, feel free to suggest it. I'm much more interested in learning here, the script was just for fun/education so it's not incredibly important.

Thanks!

Body:
The problem is with -e parameter given to echo(1) command, which makes it interpret \n as a new line. Delete that -e and it will work. I mean, you need that -e, when you write your own headers, but you should move the $(cat $f) outside of the "echo -e". For example, in two lines:

echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n" > $f
echo "$(cat $f)" >> $f    # notice the double angle >>

BUT BEWARE, that would erase your file before reading it. Even here there is a problem:

echo "$(tail -n +6 $f)" > $f

because it could erase (empty) the "$f" file before reading it. You could do instead:

newcontent=$(tail -n +6 $f)
echo "$newcontent" > $f

So, to add your headers, use two distinct echoes, but read the file before writing in it:

newcontent="$(cat $f)"
echo -e "// $NAME\n// $CLASS\n// $ASSIGNMENT\n// $DATE\n\n" > $f
echo "$newcontent" >> $f    # notice the double angle >>

I hope it helps.


问:
Does Chrome support the HTTP Vary header
Does Chrome's cache support the HTTP Vary header? For a specific url request the server responds two different html files depending if it's an ajax request or not. So I added the Vary header to X-Requested-With. I was expecting Chrome to record two cache entries, but it doesn't seem to be the case. I always get a cache hit of the first request I made. Is this the normal behavior?

Thanks.

答:
For the record. I have not been able to use the HTTP Vary header with X-Requested-With in Chrome. Chrome didn't consider the HTTP Vary header when caching. So the cache hit returned always the same content.

As a workaround I added a question string (like ?ajax=1) only when doing the request with ajax.

Ex:
http://localhost/myrequest.php
http://localhost/myrequest.php?ajax=1

This way Chrome stored two cache entries, one with ajax and one without.


问:
Enabling publishing infrastructure feature in sharepoint 2010
Hi can I enable publishing infrastructure feature in sharepoint 2010
Thanks</p>

答:
You need to activate Publishing Infrastructure in the Site Collection where you want to use Publishing.

Go to the Top level site of the Site Collection and choose Site Actions > Site Settings. On the Site Settings page in the Site Collection Administration column choose Site Collection Features.  Activate SharePoint Server Publishing Infrastructure Feature.

Then go back to the Site Settings page and choose Manage site features in the Site Actions column.  Activate the Sharepoint server Publishing Feature.

Now you can activate Publishing on any site in this site collection.  For other site collections repeat the process.


问:
Matlab: Replace NaN element values by value of the precious row
I'm trying to replace all my matrix's NaN values by the value of the element in the previous row. How can I do that? This is what I tried (for the first column only) but somehow it doesn't work...

```<code>for i=1:1935 %number of rows
if RSPB0916v05NEW5(i,1)==NaN
    RSPB0916v05NEW5(i,1) = RSPB0916v05NEW5((i-1),1)
end
end
</code>```

Thanks so much for your help, much appreciated!

Best,

Michael

答:
Assuming you do not have NaN in the first row, and remembering that NaN is never equal to NaN:

```<code>for ii=2:size(RSPB0916v05NEW5,1)%number of rows
    idx=find(isnan(RSPB0916v05NEW5(ii,:))); % find the index of NaNs
    RSPB0916v05NEW5(ii,indx)=RSPB0916v05NEW5(ii-1,indx); % replace them from the previous row
end
</code>```

Note that if the first row has NaN values, you need to handle it separately.

Body:
I'm trying to replace all my matrix's NaN values by the value of the element in the previous row. How can I do that? This is what I tried (for the first column only) but somehow it doesn't work...

for i=1:1935 %number of rows
if RSPB0916v05NEW5(i,1)==NaN
    RSPB0916v05NEW5(i,1) = RSPB0916v05NEW5((i-1),1)
end
end

Thanks so much for your help, much appreciated!

Best,

Michael

Body:
Assuming you do not have NaN in the first row, and remembering that NaN is never equal to NaN:

for ii=2:size(RSPB0916v05NEW5,1)%number of rows
    idx=find(isnan(RSPB0916v05NEW5(ii,:))); % find the index of NaNs
    RSPB0916v05NEW5(ii,indx)=RSPB0916v05NEW5(ii-1,indx); % replace them from the previous row
end

Note that if the first row has NaN values, you need to handle it separately.


问:
TypeError: Cannot read property 'libelle' of undefined
Error:
TypeError:Cannot read proprety 'libelle of undefined file:

this searche.html

```<code>import { Component,OnInit } from "@angular/core";
import { Router,NavigationExtras } from "@angular/router";
import observable = require("data/observable");
import { VoitureService } from "../../voiture/voiture.service";

@Component({
selector: "searche",
moduleId:module.id,
templateUrl: './searche.html',
providers: [VoitureService]

})
export class SearcheComponent {
    public constructor(private router:Router,private postsService:VoitureService) {
}
voitures: voiture[];
clients:voiture;
req:string='1';
DT:Date;
idClient:number=0;
refClient:string="";
libelleClient:string;

ngOnInit(){
    this.postsService. getPosts(this.req)
    .subscribe(results => this.voitures=results );
        }

    public clicked(IDV:string,LDV:string,RDV:string){
    this.postsService. getClient(IDV)
    .subscribe(results => this.clients=results );
    this.libelleClient=this.clients.libelle;
    this.refClient=this.clients.ref;
    let navigationExtras: NavigationExtras = {
        queryParams:{
            libClient: this.libelleClient,
            refclient : this.refClient,

        }
    }
        this.router.navigate(["page1"], navigationExtras);
}
}

interface voiture{
id:number;
libelle:string;
ref:string;
}
</code>```

this searche.html

```<code><stackLayout  class="searcheview">
<stackLayout>

    <SearchBar class="input"  hint="MAchine" ></SearchBar>
        <ListView [items]="voitures" >
            <ng-template let-voiture="item">
                <StackLayout   rows="auto, auto"  columns="*, auto" class="list-group-item"  (tap)="clicked(voiture.id,voiture.libelle,voiture.ref)">
                    <Label   text="{{ voiture.id }}" row="0" col="0"></Label>
                    <Label   text="{{ voiture.libelle }}" row="0" col="0"></Label>
                    <label text="{{ voiture.ref }} " row="1" col="0"></label>
                </StackLayout>
            </ng-template>
        </ListView>
</stackLayout>
</stackLayout>
</code>```

when i call function clicked()  im getting the error
TypeError: Cannot read property 'libelle' of undefined
please help

答:
The error is self-explanatory - this.clients is undefined at the moment you are referencing it. This is because you are subscribed to an asynchronous call and you should do your assigning operation inside subsribe. Possible reason for your error is because the code snippet is not formatted properly, which prevents the easy reading of your code scopes. As a recommendation use the proper indent and avoid using the short syntax for callbacks and fallbacks.

e.g.

```<code>public clicked(IDV: string, LDV: string, RDV: string) {
    this.postsService.getClient(IDV)
        .subscribe(results => {
            this.clients = results;

            this.libelleClient = this.clients.libelle;
            this.refClient = this.clients.ref;

            let navigationExtras: NavigationExtras = {
                queryParams: {
                    libClient: this.libelleClient,
                    refclient: this.refClient
                }
            }
        });
}
</code>```

Body:
Error:
TypeError:Cannot read proprety 'libelle of undefined file:

this searche.html

import { Component,OnInit } from "@angular/core";
import { Router,NavigationExtras } from "@angular/router";
import observable = require("data/observable");
import { VoitureService } from "../../voiture/voiture.service";

@Component({
selector: "searche",
moduleId:module.id,
templateUrl: './searche.html',
providers: [VoitureService]

})
export class SearcheComponent {
    public constructor(private router:Router,private postsService:VoitureService) {
}
voitures: voiture[];
clients:voiture;
req:string='1';
DT:Date;
idClient:number=0;
refClient:string="";
libelleClient:string;

ngOnInit(){
    this.postsService. getPosts(this.req)
    .subscribe(results => this.voitures=results );
        }

    public clicked(IDV:string,LDV:string,RDV:string){
    this.postsService. getClient(IDV)
    .subscribe(results => this.clients=results );
    this.libelleClient=this.clients.libelle;
    this.refClient=this.clients.ref;
    let navigationExtras: NavigationExtras = {
        queryParams:{
            libClient: this.libelleClient,
            refclient : this.refClient,

        }
    }
        this.router.navigate(["page1"], navigationExtras);
}
}

interface voiture{
id:number;
libelle:string;
ref:string;
}

this searche.html

<stackLayout  class="searcheview">
<stackLayout>

    <SearchBar class="input"  hint="MAchine" ></SearchBar>
        <ListView [items]="voitures" >
            <ng-template let-voiture="item">
                <StackLayout   rows="auto, auto"  columns="*, auto" class="list-group-item"  (tap)="clicked(voiture.id,voiture.libelle,voiture.ref)">

                </StackLayout>
            </ng-template>
        </ListView>
</stackLayout>
</stackLayout>

when i call function clicked()  im getting the error
TypeError: Cannot read property 'libelle' of undefined
please help

Body:
The error is self-explanatory - this.clients is undefined at the moment you are referencing it. This is because you are subscribed to an asynchronous call and you should do your assigning operation inside subsribe. Possible reason for your error is because the code snippet is not formatted properly, which prevents the easy reading of your code scopes. As a recommendation use the proper indent and avoid using the short syntax for callbacks and fallbacks.

e.g.

public clicked(IDV: string, LDV: string, RDV: string) {
    this.postsService.getClient(IDV)
        .subscribe(results => {
            this.clients = results;

            this.libelleClient = this.clients.libelle;
            this.refClient = this.clients.ref;

            let navigationExtras: NavigationExtras = {
                queryParams: {
                    libClient: this.libelleClient,
                    refclient: this.refClient
                }
            }
        });
}


问:
SQL date comparision in yyyy/mm/dd
Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this

```<code>d.date_begin >= DATEADD(day,-7, GETDATE())
</code>```

is not working :), i'm TERRIBLE at convert and data type..

答:
SQL server 2012 onwards, if date_begin is of datatype date

```<code>where d.date_begin >= cast(DATEADD(day,-7, GETDATE()) as date)
</code>```

This will get anything in the last 7 days, regardless of time

Title: SQL date comparision in yyyy/mm/dd

Body:
Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this

d.date_begin >= DATEADD(day,-7, GETDATE())

is not working :), i'm TERRIBLE at convert and data type..

Body:
SQL server 2012 onwards, if date_begin is of datatype date

where d.date_begin >= cast(DATEADD(day,-7, GETDATE()) as date)

This will get anything in the last 7 days, regardless of time


问:
PDO query binding string instead of integer returns results
I have a table with and auto increment id and was just testing a few scenarios when I stumbled across a problem whereby PDO or mysql seems to convert a string to an integer when in an array.  Does anyone know why?

If my query is as follows:

```<code>$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>1));
</code>```

it retrieves 1 record - all fine, but if the query uses a string either by design or mistake as follows:

```<code>$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>'1 OR id > 0'));
</code>```

it still retrieves a record with id=1.

Surely nothing should be found?  I appreciate I should never allow the 2nd scenario to happen but why is PDO / mysql converting the string to an integer and how is it doing it?

Body:
I have a table with and auto increment id and was just testing a few scenarios when I stumbled across a problem whereby PDO or mysql seems to convert a string to an integer when in an array.  Does anyone know why?

If my query is as follows:

$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>1));

it retrieves 1 record - all fine, but if the query uses a string either by design or mistake as follows:

$check = $db->prepare("SELECT * FROM tbl_test WHERE id=:id");
$check->execute(array(':id'=>'1 OR id > 0'));

it still retrieves a record with id=1.

Surely nothing should be found?  I appreciate I should never allow the 2nd scenario to happen but why is PDO / mysql converting the string to an integer and how is it doing it?

Body:
This is a MySQL bug/oversight in string to integer conversion. Instead of raising an error when given an incorrect integer literal, it simply issues a warning.

mysql> select '1'+0;
+-------+
| '1'+0 |
+-------+
|     1 |
+-------+
1 row in set (0,00 sec)

mysql> select '1 hello world'+0;
+-------------------+
| '1 hello world'+0 |
+-------------------+
|                 1 |
+-------------------+
1 row in set, 1 warning (0,00 sec)

mysql> show warnings;
+---------+------+---------------------------------------------------+
| Level   | Code | Message                                           |
+---------+------+---------------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: '1 hello world' |
+---------+------+---------------------------------------------------+
1 row in set (0,00 sec)


问:
Circular Progress with a floating action button
I`m studing the new material design and I'm having some problems.

I would like to know if some of you know how can I do a progress bar with the floating action button like this
https://dribbble.com/shots/1644982-Animated-circle-loader-FAB-with-integration-gif

Is there any api on Android L for this?

Thanks

答:
This worked for me, I used a Relative-layout and fitted both in the center of the Relative-Layout. </p>

```<code>...
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|right"
    android:layout_margin="16dp"
    app:layout_anchor="@id/my_recycler_view"
    app:layout_anchorGravity="bottom|right|end"
    >

    <ProgressBar
        android:id="@+id/fabProgress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:indeterminateTint="@color/colorPrimary"
        />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/newReportButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_email"
        app:fabSize="normal"
        android:layout_centerInParent="true"
        />

</RelativeLayout>
...
</code>```

Body:
This worked for me, I used a Relative-layout and fitted both in the center of the Relative-Layout.

...
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|right"
    android:layout_margin="16dp"
    app:layout_anchor="@id/my_recycler_view"
    app:layout_anchorGravity="bottom|right|end"
    >

    <ProgressBar
        android:id="@+id/fabProgress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:indeterminateTint="@color/colorPrimary"
        />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/newReportButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@android:drawable/ic_dialog_email"
        app:fabSize="normal"
        android:layout_centerInParent="true"
        />

</RelativeLayout>
...


问:
What is wrong with my logic my button only changes once and the onclick function stops?
I want a button to switch between F and C each time i do the click but when i click the button a third time it just doesn't work even though i set back the class to <code>.temp</code>. </p>

```<code>$(".temp").click(function() {
  $('#temperature').empty();
  $("#temperature").append(temp.main.temp + " <a class='temper' href='#'>C</a>");

  $(".temper").click(function() {
    $('#temperature').empty();
    $('#temperature').append(data.main.temp +" <a class='temp' href='#'>F</a>");
  });
});
</code>```

答:
why you wrote the code of temper.click inside the temp.click function?
correct it as :</p>

```<code>$(".temp").click(function(){

  $('#temperature').empty();
  $("#temperature").append(temp.main.temp+" <a class='temper' href='#'>C</a>");
});

$(".temper").click(function(){

   $('#temperature').empty();
   $('#temperature').append(data.main.temp+" <a class='temp' href='#'>F</a>"  );
});
</code>```

Body:
I want a button to switch between F and C each time i do the click but when i click the button a third time it just doesn't work even though i set back the class to .temp.

$(".temp").click(function() {
  $('#temperature').empty();
  $("#temperature").append(temp.main.temp + " C");

  $(".temper").click(function() {
    $('#temperature').empty();
    $('#temperature').append(data.main.temp +" F");
  });
});

Body:
why you wrote the code of temper.click inside the temp.click function?
correct it as :

$(".temp").click(function(){

  $('#temperature').empty();
  $("#temperature").append(temp.main.temp+" <a class='temper' href='#'>C</a>");
});

$(".temper").click(function(){

   $('#temperature').empty();
   $('#temperature').append(data.main.temp+" <a class='temp' href='#'>F</a>"  );
});


问:
In JSF the "saveState()" method is being called twice. Why?
I put two output statements, one at the beginning of "save()" and one at the end for a custom JSF component. The "saveState()" is in the UIComponent object. Why ar e my output statements being printed twice? Basically this is what I see

```<code>"entering save"
"ending save"
"entering save"
"ending save"
</code>```

Thanks.

答:
There might be 2 threads executing the same prints.
Set a breakpoint and you'll see :D</p>

Body:
I put two output statements, one at the beginning of "save()" and one at the end for a custom JSF component. The "saveState()" is in the UIComponent object. Why ar e my output statements being printed twice? Basically this is what I see

"entering save"
"ending save"
"entering save"
"ending save"

Thanks.