title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Appium 'Failed to connect to the server. Please check that it is running' using Inspector
39,965,136
<p>What must be done to use Aappium's inspector?</p> <p>The screenshot and logs are attached</p> <ol> <li>my appium server is set to start an app (with path checked)</li> <li>the AVD emulator is launched</li> <li>the tests script is launched, with the app successfully loading on the emulator</li> <li>when clicking on the 'inspector' button, the above error occurs</li> </ol> <p><a href="http://i.stack.imgur.com/VXyah.png" rel="nofollow"><img src="http://i.stack.imgur.com/VXyah.png" alt="Error displayed"></a></p> <blockquote> <p>Launching Appium server with command: C:\Program Files (x86)\Appium\node.exe lib\server\main.js --address 127.0.0.1 --port 4723 --app C:\test\TimeWorksMobile.apk --platform-name Android --platform-version 23 --automation-name Appium --log-no-color info: Welcome to Appium v1.4.16 (REV ae6877eff263066b26328d457bd285c0cc62430d) info: Appium REST http interface listener started on 127.0.0.1:4723 info: [debug] Non-default server args: {"app":"C:\test\TimeWorksMobile.apk","address":"127.0.0.1","logNoColors":true,"platformName":"Android","platformVersion":"23","automationName":"Appium"} info: Console LogLevel: debug info: --> POST /wd/hub/session {"requiredCapabilities":{},"desiredCapabilities":{"platformVersion":"5.1","app":"C:\test\TimeWorksMobile.apk","deviceName":"Android Emulator","platformName":"Android"}} info: Client User-Agent string: Python-urllib/3.5 info: [debug] No appActivity desired capability or server param. Parsing from apk. info: [debug] No appPackage desired capability or server param. Parsing from apk. info: [debug] Using local app from desired caps: C:\test\TimeWorksMobile.apk info: [debug] Creating new appium session 2c9eecab-c67b-45e0-b97f-0faa98dfd000 info: Starting android appium info: [debug] Getting Java version info: Java version is: 1.8.0_101 info: [debug] Checking whether adb is present info: [debug] Using adb from C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe info: [debug] Parsing package and activity from app manifest info: [debug] Checking whether aapt is present info: [debug] Using aapt from C:\Users\mwebster\AppData\Local\Android\sdk\build-tools\24.0.2\aapt.exe info: [debug] Extracting package and launch activity from manifest. info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\build-tools\24.0.2\aapt.exe dump badging C:\test\TimeWorksMobile.apk info: [debug] badging package: com.SwipeClock.SCeConnect info: [debug] badging act: com.SwipeClock.SCeConnect.MainActivity info: [debug] Parsed package and activity are: com.SwipeClock.SCeConnect/com.SwipeClock.SCeConnect.MainActivity info: [debug] Using fast reset? true info: [debug] Preparing device for session info: [debug] Checking whether app is actually present info: Retrieving device info: [debug] Trying to find a connected android device info: [debug] Getting connected devices... info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe devices info: [debug] 1 device(s) connected info: Found device emulator-5554 info: [debug] Setting device id to emulator-5554 info: [debug] Waiting for device to be ready and to respond to shell commands (timeout = 5) info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 wait-for-device info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "echo 'ready'" info: [debug] Starting logcat capture info: [debug] Getting device API level info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk" info: [debug] Device is at API Level 23 info: Device API level is: 23 info: [debug] Extracting strings for language: default info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop persist.sys.language" info: [debug] Current device persist.sys.language: info: [debug] java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\appium_apk_tools.jar" "stringsFromApk" "C:\test\TimeWorksMobile.apk" "C:\Users\mwebster\AppData\Local\Temp\com.SwipeClock.SCeConnect" info: [debug] Reading strings from converted strings.json info: [debug] Setting language to default info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Users\mwebster\AppData\Local\Temp\com.SwipeClock.SCeConnect\strings.json" /data/local/tmp info: [debug] Checking whether aapt is present info: [debug] Using aapt from C:\Users\mwebster\AppData\Local\Android\sdk\build-tools\24.0.2\aapt.exe info: [debug] Retrieving process from manifest. info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\build-tools\24.0.2\aapt.exe dump xmltree C:\test\TimeWorksMobile.apk AndroidManifest.xml info: [debug] Set app process to: com.SwipeClock.SCeConnect info: [debug] Not uninstalling app since server not started with --full-reset info: [debug] Checking app cert for C:\test\TimeWorksMobile.apk. info: [debug] executing cmd: java -jar "C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-adb\jars\verify.jar" C:\test\TimeWorksMobile.apk info: [debug] App already signed. info: [debug] Zip-aligning C:\test\TimeWorksMobile.apk info: [debug] Checking whether zipalign is present info: [debug] Using zipalign from C:\Users\mwebster\AppData\Local\Android\sdk\build-tools\24.0.2\zipalign.exe info: [debug] Zip-aligning apk. info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\build-tools\24.0.2\zipalign.exe -f 4 C:\test\TimeWorksMobile.apk C:\Users\mwebster\AppData\Local\Temp\116910-12700-dn10cl\appium.tmp info: [debug] MD5 for app is 49680e5f3c45e35b7ae704bcc2859d86 info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "ls /data/local/tmp/49680e5f3c45e35b7ae704bcc2859d86.apk" info: [debug] Getting install status for com.SwipeClock.SCeConnect info: [debug] Getting device API level info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk" info: [debug] Device is at API Level 23 info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "pm list packages -3 com.SwipeClock.SCeConnect" info: [debug] App is installed info: App is already installed, resetting app info: [debug] Running fast reset (stop and clear) info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "am force-stop com.SwipeClock.SCeConnect" info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "pm clear com.SwipeClock.SCeConnect" info: [debug] Forwarding system:4724 to device:4724 info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 forward tcp:4724 tcp:4724 info: [debug] Pushing appium bootstrap to device... info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 push "C:\Program Files (x86)\Appium\node_modules\appium\build\android_bootstrap\AppiumBootstrap.jar" /data/local/tmp/ info: [debug] Pushing settings apk to device... info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 install "C:\Program Files (x86)\Appium\node_modules\appium\build\settings_apk\settings_apk-debug.apk" info: [debug] Pushing unlock helper app to device... info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 install "C:\Program Files (x86)\Appium\node_modules\appium\build\unlock_apk\unlock_apk-debug.apk" info: Starting App info: [debug] Attempting to kill all 'uiautomator' processes info: [debug] Getting all processes with 'uiautomator' info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "ps 'uiautomator'" info: [debug] No matching processes found info: [debug] Running bootstrap info: [debug] spawning: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell uiautomator runtest AppiumBootstrap.jar -c io.appium.android.bootstrap.Bootstrap -e pkg com.SwipeClock.SCeConnect -e disableAndroidWatchers false info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: numtests=1 info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: stream= info: [debug] [UIAUTOMATOR STDOUT] io.appium.android.bootstrap.Bootstrap: info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: id=UiAutomatorTestRunner info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: test=testRunServer info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: class=io.appium.android.bootstrap.Bootstrap info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: current=1 info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS_CODE: 1 info: [debug] [BOOTSTRAP] [debug] Socket opened on port 4724 info: [debug] [BOOTSTRAP] [debug] Appium Socket Server Ready info: [debug] [BOOTSTRAP] [debug] Loading json... info: [debug] [BOOTSTRAP] [debug] json loading complete. info: [debug] [BOOTSTRAP] [debug] Registered crash watchers. info: [debug] Waking up device if it's not alive info: [debug] Pushing command to appium work queue: ["wake",{}] info: [debug] [BOOTSTRAP] [debug] Client connected info: [debug] [BOOTSTRAP] [debug] Got data from client: {"cmd":"action","action":"wake","params":{}} info: [debug] [BOOTSTRAP] [debug] Got command of type ACTION info: [debug] [BOOTSTRAP] [debug] Got command action: wake info: [debug] [BOOTSTRAP] [debug] Returning result: {"status":0,"value":true} info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "dumpsys window" info: [debug] Screen already unlocked, continuing. info: [debug] Pushing command to appium work queue: ["getDataDir",{}] info: [debug] [BOOTSTRAP] [debug] Got data from client: {"cmd":"action","action":"getDataDir","params":{}} info: [debug] dataDir set to: /data info: [debug] Pushing command to appium work queue: ["compressedLayoutHierarchy",{"compressLayout":false}] info: [debug] [BOOTSTRAP] [debug] Got command of type ACTION info: [debug] [BOOTSTRAP] [debug] Got command action: getDataDir info: [debug] [BOOTSTRAP] [debug] Returning result: {"status":0,"value":"/data"} info: [debug] [BOOTSTRAP] [debug] Got data from client: {"cmd":"action","action":"compressedLayoutHierarchy","params":{"compressLayout":false}} info: [debug] [BOOTSTRAP] [debug] Got command of type ACTION info: [debug] [BOOTSTRAP] [debug] Got command action: compressedLayoutHierarchy info: [debug] Getting device API level info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.sdk" info: [debug] [BOOTSTRAP] [debug] Returning result: {"status":0,"value":false} info: [debug] Device is at API Level 23 info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "am start -S -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -f 0x10200000 -n com.SwipeClock.SCeConnect/com.SwipeClock.SCeConnect.MainActivity" info: [debug] Waiting for pkg "com.SwipeClock.SCeConnect" and activity "com.SwipeClock.SCeConnect.MainActivity" to be focused info: [debug] Getting focused package and activity info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "dumpsys window windows" info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "getprop ro.build.version.release" info: [debug] Device is at release version 6.0 info: [debug] Device launched! Ready for commands info: [debug] Setting command timeout to the default of 60 secs info: [debug] Appium session started with sessionId 2c9eecab-c67b-45e0-b97f-0faa98dfd000 info: &lt;-- POST /wd/hub/session 303 4044.963 ms - 74 info: --> GET /wd/hub/session/2c9eecab-c67b-45e0-b97f-0faa98dfd000 {} info: [debug] Responding to client with success: {"status":0,"value":{"platform":"LINUX","browserName":"Android","platformVersion":"6.0","webStorageEnabled":false,"takesScreenshot":true,"javascriptEnabled":true,"databaseEnabled":false,"networkConnectionEnabled":true,"locationContextEnabled":false,"warnings":{},"desired":{"platformVersion":"5.1","app":"C:\test\TimeWorksMobile.apk","deviceName":"Android Emulator","platformName":"Android"},"app":"C:\test\TimeWorksMobile.apk","deviceName":"emulator-5554","platformName":"Android"},"sessionId":"2c9eecab-c67b-45e0-b97f-0faa98dfd000"} info: &lt;-- GET /wd/hub/session/2c9eecab-c67b-45e0-b97f-0faa98dfd000 200 3.418 ms - 538 {"status":0,"value":{"platform":"LINUX","browserName":"Android","platformVersion":"6.0","webStorageEnabled":false,"takesScreenshot":true,"javascriptEnabled":true,"databaseEnabled":false,"networkConnectionEnabled":true,"locationContextEnabled":false,"warnings":{},"desired":{"platformVersion":"5.1","app":"C:\test\TimeWorksMobile.apk","deviceName":"Android Emulator","platformName":"Android"},"app":"C:\test\TimeWorksMobile.apk","deviceName":"emulator-5554","platformName":"Android"},"sessionId":"2c9eecab-c67b-45e0-b97f-0faa98dfd000"} {"platform":"LINUX","browserName":"Android","platformVersion":"6.0","webStorageEnabled":false,"takesScreenshot":true,"javascriptEnabled":true,"databaseEnabled":false,"networkConnectionEnabled":true,"locationContextEnabled":false,"warnings":{},"desired":{"platformVersion":"5.1","app":"C:\test\TimeWorksMobile.apk","deviceName":"Android Emulator","platformName":"Android"},"app":"C:\test\TimeWorksMobile.apk","deviceName":"emulator-5554","platformName":"Android"},"sessionId":"2c9eecab-c67b-45e0-b97f-0faa98dfd000"} info: --> POST /wd/hub/session {"desiredCapabilities":{"app":"C:\test\TimeWorksMobile.apk","platformName":"Android"}} info: Client User-Agent string: undefined error: Failed to start an Appium session, err was: Error: Requested a new session but one was in progress info: [debug] Error: Requested a new session but one was in progress at [object Object].Appium.start (C:\Program Files (x86)\Appium\node_modules\appium\lib\appium.js:139:15) at exports.createSession (C:\Program Files (x86)\Appium\node_modules\appium\lib\server\controller.js:188:16) at Layer.handle [as handle_request] (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\layer.js:82:5) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:110:13) at Route.dispatch (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:91:3) at Layer.handle [as handle_request] (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\layer.js:82:5) at C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:267:22 at Function.proto.process_params (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:321:12) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:261:10) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:100:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at C:\Program Files (x86)\Appium\node_modules\appium\lib\server\controller.js:39:7 at Layer.handle [as handle_request] (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\layer.js:82:5) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:110:13) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:104:14) at Route.dispatch (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\route.js:91:3) at Layer.handle [as handle_request] (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\layer.js:82:5) at C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:267:22 at Function.proto.process_params (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:321:12) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:261:10) at methodOverride (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\method-override\index.js:79:5) at Layer.handle [as handle_request] (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\layer.js:82:5) at trim_prefix (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:302:13) at C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:270:7 at Function.proto.process_params (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:321:12) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:261:10) at logger (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\morgan\index.js:136:5) at Layer.handle [as handle_request] (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\layer.js:82:5) at trim_prefix (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:302:13) at C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:270:7 at Function.proto.process_params (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:321:12) at next (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\express\lib\router\index.js:261:10) at C:\Program Files (x86)\Appium\node_modules\appium\node_modules\body-parser\lib\read.js:111:5 at done (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\body-parser\node_modules\raw-body\index.js:248:14) at IncomingMessage.onEnd (C:\Program Files (x86)\Appium\node_modules\appium\node_modules\body-parser\node_modules\raw-body\index.js:294:7) at IncomingMessage.g (events.js:199:16) at IncomingMessage.emit (events.js:104:17) at _stream_readable.js:908:16 at process._tickDomainCallback (node.js:381:11) info: [debug] Responding to client with error: {"status":33,"value":{"message":"A new session could not be created. (Original error: Requested a new session but one was in progress)","origValue":"Requested a new session but one was in progress"},"sessionId":"2c9eecab-c67b-45e0-b97f-0faa98dfd000"} info: &lt;-- POST /wd/hub/session 500 6.272 ms - 250 info: [debug] Didn't get a new command in 60 secs, shutting down... info: Shutting down appium session info: [debug] Pressing the HOME button info: [debug] executing cmd: C:\Users\mwebster\AppData\Local\Android\sdk\platform-tools\adb.exe -s emulator-5554 shell "input keyevent 3" info: [debug] Stopping logcat capture info: [debug] Logcat terminated with code null, signal SIGTERM info: [debug] [BOOTSTRAP] [debug] Got data from client: {"cmd":"shutdown"} info: [debug] [BOOTSTRAP] [debug] Got command of type SHUTDOWN info: [debug] [BOOTSTRAP] [debug] Returning result: {"status":0,"value":"OK, shutting down"} info: [debug] [BOOTSTRAP] [debug] Closed client connection info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: numtests=1 info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: stream=. info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: id=UiAutomatorTestRunner info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: test=testRunServer info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: class=io.appium.android.bootstrap.Bootstrap info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: current=1 info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS_CODE: 0 info: [debug] Sent shutdown command, waiting for UiAutomator to stop... info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS: stream= info: [debug] [UIAUTOMATOR STDOUT] Test results for WatcherResultPrinter=. info: [debug] [UIAUTOMATOR STDOUT] Time: 61.482 info: [debug] [UIAUTOMATOR STDOUT] OK (1 test) info: [debug] [UIAUTOMATOR STDOUT] INSTRUMENTATION_STATUS_CODE: -1 info: [debug] UiAutomator shut down normally info: [debug] Cleaning up android objects info: [debug] Cleaning up appium session info: [debug] We shut down because no new commands came in</p> </blockquote>
0
2016-10-10T19:08:34Z
39,990,945
<p>Appium internally uses UIAutomator to find elements. If you are executing your code using appium then your UIAutomator is already in use and if you try to use it manually then appium will loose the control of UIAutomator.</p>
0
2016-10-12T05:14:02Z
[ "python", "appium", "inspector" ]
How do I fix: ImportError: cannot import name 'PandaRequest'?
39,965,157
<p>This is my first time using a jupyter notebook. </p> <p>I was trying to import the panda module:</p> <pre><code>import panda as pd </code></pre> <p>but I get the following error:</p> <pre><code>/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/panda/__init__.py in &lt;module&gt;() ----&gt; 1 from request import PandaRequest ImportError: cannot import name 'PandaRequest' </code></pre> <p>How to fix this?</p> <p>Edit: I wanted to use pandas but typed panda instead. :'D</p>
1
2016-10-10T19:10:05Z
39,965,180
<p>Execute <code>pip install panda</code>. You don't have the Panda module.</p> <p>Edit: My mistake, it looks like there's an error within the Panda module itself. Does it rely on PandaRequest?</p>
0
2016-10-10T19:12:18Z
[ "python", "ipython", "jupyter", "jupyter-notebook" ]
Save HDFS To MongoDB using Spark-DataFrame
39,965,271
<p>I'm trying to save a Spark-DataFrame using PyMongo connecter. Following is my code, but every-time I run the code I get an error: </p> <pre><code>java.io.IOException: No FileSystem for scheme: mongodb </code></pre> <p>following is my code:</p> <pre><code>import pymongo import pymongo_spark pymongo_spark.activate() from pyspark import SparkContext, SparkConf from pyspark.sql import SQLContext conf = SparkConf() sc = SparkContext(conf=conf) sqlContext=SQLContext(sc) from pyspark.sql import SparkSession from pyspark.sql import SparkSession path = "hdfs://localhost:9000/home/hadoop/h_data/sales_ord_univ.csv" df=sqlContext.read.format("com.databricks.spark.csv").option("header", "true").option("inferSchema", "true").load(path) collections=df.collect() df.write.format('mongodb://localhost:27017/test.sales_order_2').save() </code></pre> <p>I have a pretty naive code since Im a newbie to this, but any help towards this would be greatly appreciated. Im using Spark- 2.0.0, Python 2.7.6,MongoDB: 3.2.9</p>
1
2016-10-10T19:18:42Z
39,970,201
<blockquote> <p>I'm trying to save a Spark-DataFrame using PyMongo connector</p> </blockquote> <p>You can try to use <a href="https://docs.mongodb.com/spark-connector/" rel="nofollow">MongoDB Connector for Spark</a>. Using your setup environment of <a href="https://spark.apache.org/releases/spark-release-2-0-0.html" rel="nofollow">Apache Spark v2.0.x</a>, Python v2.7.x, and <a href="https://www.mongodb.com/" rel="nofollow">MongoDB</a> v3.2.x, you can do something like below: </p> <pre><code>from pyspark.sql import SparkSession spark = SparkSession.builder.appName("Application Name").getOrCreate() dataframe = spark.read.csv("path/to/file.csv", header=True, mode="DROPMALFORMED") dataframe.write.format("com.mongodb.spark.sql.DefaultSource")\ .option("spark.mongodb.output.uri", "mongodb://localhost:27017/database.collection")\ .save() </code></pre> <p>The full version of Python example file can be found on <a href="https://github.com/sindbach/mongodb-pyspark-docker/blob/master/pyspark/files/examples.py#L57" rel="nofollow">MongoDB PySpark Docker: examples.py</a> . Which includes an example to use <a href="https://docs.mongodb.com/manual/aggregation/" rel="nofollow">MongoDB Aggregation</a> in Spark, and <a href="https://docs.mongodb.com/spark-connector/spark-sql/" rel="nofollow">Spark SQL</a>.</p> <p>If you are familiar with <a href="https://www.docker.com/" rel="nofollow">docker</a>, you can execute the git project <a href="https://github.com/sindbach/mongodb-pyspark-docker" rel="nofollow">MongoDB PySpark Docker</a> using <a href="https://docs.docker.com/compose/" rel="nofollow">docker-compose</a> and run some of the PySpark examples.</p> <p>You may find the following resources useful:</p> <ul> <li><a href="https://docs.mongodb.com/spark-connector/python-api/" rel="nofollow">Spark Connector Python API</a></li> <li><a href="https://university.mongodb.com/courses/M233/about" rel="nofollow">Free online course M233: Getting Started with Spark and MongoDB</a></li> </ul>
1
2016-10-11T03:43:18Z
[ "python", "mongodb", "csv", "hadoop", "apache-spark" ]
Python copy files from Linux to WIndows
39,965,297
<p>I'm building a website which has a form which captures user data and runs some cgi on the user data. One of the first steps of the cgi is that it needs to copy files from the linux webserver to windows machines. The server would be using an active directory role acount for the copy credential. I had hoped to simply use something like this:</p> <p><pre><code></p> <pre><code>mount -t cifs -o username=someUsername,password=somePasword //someMachine/someShare /someMountPoint </code></pre> <p></pre></code></p> <p>Unfortunately I get errors about the password attributed being invalid when I run that command in bash. Ideally I would use this method to mount the remote windows c$ share and then copy the files but I'm willing to try other modules if they make more sense.</p> <p>I had something like this but it doesn't work, creates the necessary temporary directories but never mounts anything. I'm happy to try using something else but would love to know what's wrong here. <pre><code></p> <pre><code>import subprocess import random def makeDir(): tempDir = random.randrange(111111,999999) subprocess.Popen(["mkdir","/mntDir/"+str(tempDir)]) return tempDir def mountShare(hostname, username, password): mountDir = makeDir() try: subprocess.Popen(["mount","-t","cifs", "-o", "username="+username+",password="+password, "//"+hostname+"/c$", "/mntDir/"+mountDir]) except: print("Mounting failed") </code></pre> <p></pre></code></p>
0
2016-10-10T19:21:49Z
39,965,444
<p>This approach has two drawbacks: the first one is that you mount windows share from your webserver. You don;t need to mount it dynamically and in no account you should not mount it for every request. Separate your implementation and infrastructure. Mount required directory in /etc/fstab and let your webserver to rely on existence of the directory.</p> <p>But then there is another problem: what for you are copying the files to another machine? Do you want to process them there? How you want to notify windows machine that it needs to process data? Why not to run another web server on it and send it requests when you need to process something. And at this point you can drop all that network file systems and send the files within the requests. So you will have linux based frontend server which performs some actions by sending HTTP requests to windows backend server. This will also allow you to notify frontend when the processing is ready.</p>
0
2016-10-10T19:31:56Z
[ "python", "linux", "windows", "cifs" ]
Python copy files from Linux to WIndows
39,965,297
<p>I'm building a website which has a form which captures user data and runs some cgi on the user data. One of the first steps of the cgi is that it needs to copy files from the linux webserver to windows machines. The server would be using an active directory role acount for the copy credential. I had hoped to simply use something like this:</p> <p><pre><code></p> <pre><code>mount -t cifs -o username=someUsername,password=somePasword //someMachine/someShare /someMountPoint </code></pre> <p></pre></code></p> <p>Unfortunately I get errors about the password attributed being invalid when I run that command in bash. Ideally I would use this method to mount the remote windows c$ share and then copy the files but I'm willing to try other modules if they make more sense.</p> <p>I had something like this but it doesn't work, creates the necessary temporary directories but never mounts anything. I'm happy to try using something else but would love to know what's wrong here. <pre><code></p> <pre><code>import subprocess import random def makeDir(): tempDir = random.randrange(111111,999999) subprocess.Popen(["mkdir","/mntDir/"+str(tempDir)]) return tempDir def mountShare(hostname, username, password): mountDir = makeDir() try: subprocess.Popen(["mount","-t","cifs", "-o", "username="+username+",password="+password, "//"+hostname+"/c$", "/mntDir/"+mountDir]) except: print("Mounting failed") </code></pre> <p></pre></code></p>
0
2016-10-10T19:21:49Z
39,965,528
<p>First, drop the exception block as it hides error details, anyway <code>Popen</code> and other <code>subprocess</code> methods only throw exceptions when they cannot start commands (because of command not found), which means that <code>mount</code> is actually called.</p> <p>Second, you really don't need <code>Popen</code>, but <code>call</code> (and as a bonus you get the return code directly)</p> <pre><code>rc = subprocess.call(["mount","-t","cifs", "-o", "username="+username+",password="+password, "//"+hostname+"/c$", "/mntDir/"+mountDir]) if rc: print("mount failed") </code></pre> <p>In your case, the problem <em>is</em> the general exception block.</p> <p>This method:</p> <pre><code>def makeDir(): tempDir = random.randrange(111111,999999) subprocess.Popen(["mkdir","/mntDir/"+str(tempDir)]) return tempDir </code></pre> <p>returns an <em>integer</em>, so if you remove the exception block you get error because you're adding a string with an integer (<code>TypeError: Can't convert 'int' object to str implicitly</code>). It's a simple mistake that you could have seen if it hadn't for the stupid exception catch which mislead you.</p> <p>But with the generic <code>try/except</code> block without any argument, you just get <code>mount failed</code> useless message. <em>never</em> protect your statements with <code>try:/except:</code>, that's counter-productive.</p> <p>If you <em>really</em> want to do that,do this:</p> <pre><code>try: some_command except Exception as e: # print detailed exception, not just "error" print("Something went wrong "+str(e)) </code></pre> <p>Now to sum it up, here's a fixed version of your code (with some slight improvements as a bonus):</p> <pre><code>import subprocess,os import random def makeDir(): # directly create directory name as a string tempDir = "/mntDir/{}".format(random.randrange(111111,999999)) # no need for a subprocess, python handles this well! os.mkdir(tempDir) # returns the absolute directory name, as string return tempDir def mountShare(hostname, username, password): mountDir = makeDir() rc = subprocess.call(["mount","-t","cifs", "-o", "username="+username+",password="+password, "//"+hostname+"/c$", mountDir]) if rc!=0: print("Mounting failed") </code></pre>
0
2016-10-10T19:38:03Z
[ "python", "linux", "windows", "cifs" ]
Python copy files from Linux to WIndows
39,965,297
<p>I'm building a website which has a form which captures user data and runs some cgi on the user data. One of the first steps of the cgi is that it needs to copy files from the linux webserver to windows machines. The server would be using an active directory role acount for the copy credential. I had hoped to simply use something like this:</p> <p><pre><code></p> <pre><code>mount -t cifs -o username=someUsername,password=somePasword //someMachine/someShare /someMountPoint </code></pre> <p></pre></code></p> <p>Unfortunately I get errors about the password attributed being invalid when I run that command in bash. Ideally I would use this method to mount the remote windows c$ share and then copy the files but I'm willing to try other modules if they make more sense.</p> <p>I had something like this but it doesn't work, creates the necessary temporary directories but never mounts anything. I'm happy to try using something else but would love to know what's wrong here. <pre><code></p> <pre><code>import subprocess import random def makeDir(): tempDir = random.randrange(111111,999999) subprocess.Popen(["mkdir","/mntDir/"+str(tempDir)]) return tempDir def mountShare(hostname, username, password): mountDir = makeDir() try: subprocess.Popen(["mount","-t","cifs", "-o", "username="+username+",password="+password, "//"+hostname+"/c$", "/mntDir/"+mountDir]) except: print("Mounting failed") </code></pre> <p></pre></code></p>
0
2016-10-10T19:21:49Z
39,981,706
<p>The solution was not to mount the share but rather to copy on the fly using smbclient. The command I'm using refers to an authfile which contains an account with the relevant permissions in the form:</p> <pre><code>username = yourUsername password = yourPassword domain = yourDomain </code></pre> <p>The permissions on this file are set to 500.</p> <p>The smbclient command is then used to create a directory on the remote machine and copy files to that directory.</p> <pre><code>smbclient //hostname/c$ -A /authfile -c "mkdir someDir; cd someDir/; lcd /folderToCopyFrom; prompt; recurse; mput *; exit;" </code></pre> <p>Thank you all for the advice, most helpful!</p>
0
2016-10-11T16:02:58Z
[ "python", "linux", "windows", "cifs" ]
How do I find the coordinates of the nodes in a binary tree given as a heap in the input?
39,965,328
<p>Given a heap as input, such as:</p> <pre><code>1 2 3 - 5 - 7 </code></pre> <p>Where '-' represents an empty node, I want to find the coordinates of the nodes, which would for the input above be:</p> <pre><code>[1, 0] [0, 2] [2, 2] [-1, -1] [1, 4] [-1, -1] [3, 4] </code></pre> <p>The rules for the coordinate transform is as follows:</p> <ul> <li>There should be 1 row of space between each "layer" of the tree, meaning we increment the Y value with 2 for each layer.</li> <li>The leftmost node should have it's X-coordinate = 0.</li> <li>There should be at least one space between each node.</li> <li>All coordinates should be whole numbers.</li> <li>If a root node has two children, the root should be placed in the middle of it's two children. </li> <li>If a root node only has one child, the child should be placed one left or one right of the root, depending on it being the left or right child of the root.</li> <li>If a root node has two subtrees then all the x-coordinates to the nodes of the right subtree be bigger than the x-coordinates to the nodes of the left subtree</li> <li>An empty node should have the coordinates [-1,-1]</li> </ul> <p>I can't for the life of me figure out how I would solve this issue, so any help would be greatly appreciated.</p>
-2
2016-10-10T19:24:08Z
39,980,261
<p>If you look at a heap, you'll notice that each level has twice as many nodes as the previous level. So you have the progression 1, 2, 4, 8, 16, etc.</p> <p>Given a node's index in the input array, you can easily determine the level it's on by taking the base-2 logarithm of the index and rounding down. That is, if we use 1-based indexing, then:</p> <pre><code>log2(1) = 0 log2(2) = 1 log2(3) = 1 log2(4) = 2 log2(5) = 2 log2(6) = 2 log2(7) = 2 </code></pre> <p>Multiply those values by 2 to get your <code>Y</code> coordinate.</p> <p>For the <code>X</code> coordinates, if you take an index and subtract the number of nodes that occur on all levels above it, you have the index of that item <em>on its row</em>. Consider the 4th (1-based) item in your list. You know that it's at level 2. The number of nodes that come before it, then is <code>(2^2)-1</code>, or 3. And <code>4-3 = 1</code>. So the 4th item in the list is at index 1 on its level.</p> <p>It's unclear from your question how you want to transform the row indexes. It looks like on your last row the X coordinates would be 0, 1, 2, 3 if all of the items had values. If that's how you want to do each row, then you just subtract 1 from the calculation described in the previous paragraph.</p>
0
2016-10-11T14:56:57Z
[ "python", "heap", "binary-tree" ]
replacing a column in DataFrame using regex
39,965,414
<p>I have a data frame with 4 columns, col4 is a string including texts and digits:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 PD380_003 %LINK-3-UPDOWN Syslog 2016,09,17 1 NM380_005 %BGP-5-NBR_RESET Syslog 2016,09,14 1 NM380_005 %BGP-5-NBR_RESET Syslog 2016,09,08 1 DO NOT TICKET LO380_004 %SYS-5-CONFIG_I Config </code></pre> <p>i need to keep a substring of that column and delete anything else, so I used regex and i made a pattern but when i run the following query the result is not what i want, it replace everything with the pattern itself:</p> <pre><code>data.replace({'Col4':{'.*':'([A-Z]{2}[0-9]{3}_[0-9]{3})'}},regex=True) </code></pre> <p>desired result is:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 PD380_003 Syslog 2016,09,17 1 NM380_005 Syslog 2016,09,14 1 LO380_004 Syslog 2016,09,08 1 LO380_004 </code></pre> <p>but the result i get is like:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,17 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,14 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,08 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) </code></pre> <p>what am i doing wrong?</p>
2
2016-10-10T19:29:42Z
39,965,536
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.extract.html" rel="nofollow"><code>extract</code></a>:</p> <pre><code>data.Col4 = data.Col4.str.extract('([A-Z]{2}[0-9]{3}_[0-9]{3})', expand=False) print (data) Col1 Col2 Col3 Col4 0 Syslog 2016,09,17 1 PD380_003 1 Syslog 2016,09,17 1 NM380_005 2 Syslog 2016,09,14 1 NM380_005 3 Syslog 2016,09,08 1 LO380_004 </code></pre>
2
2016-10-10T19:38:19Z
[ "python", "pandas" ]
replacing a column in DataFrame using regex
39,965,414
<p>I have a data frame with 4 columns, col4 is a string including texts and digits:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 PD380_003 %LINK-3-UPDOWN Syslog 2016,09,17 1 NM380_005 %BGP-5-NBR_RESET Syslog 2016,09,14 1 NM380_005 %BGP-5-NBR_RESET Syslog 2016,09,08 1 DO NOT TICKET LO380_004 %SYS-5-CONFIG_I Config </code></pre> <p>i need to keep a substring of that column and delete anything else, so I used regex and i made a pattern but when i run the following query the result is not what i want, it replace everything with the pattern itself:</p> <pre><code>data.replace({'Col4':{'.*':'([A-Z]{2}[0-9]{3}_[0-9]{3})'}},regex=True) </code></pre> <p>desired result is:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 PD380_003 Syslog 2016,09,17 1 NM380_005 Syslog 2016,09,14 1 LO380_004 Syslog 2016,09,08 1 LO380_004 </code></pre> <p>but the result i get is like:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,17 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,14 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,08 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) </code></pre> <p>what am i doing wrong?</p>
2
2016-10-10T19:29:42Z
39,966,171
<p>You were using RegEx in a wrong way.</p> <p><code>{'Col4':{'.*':'([A-Z]{2}[0-9]{3}_[0-9]{3})'}}</code> - means replace a whatever string in the <code>Col4</code> column with <code>'([A-Z]{2}[0-9]{3}_[0-9]{3})'</code></p> <p>Try this:</p> <pre><code>In [87]: df.replace({'Col4':{r'.*?([A-Z]{2}[0-9]{3}_[0-9]{3}).*':r'\1'}}, regex=True) Out[87]: Col1 Col2 Col3 Col4 0 Syslog 2016,09,17 1 PD380_003 1 Syslog 2016,09,17 1 NM380_005 2 Syslog 2016,09,14 1 NM380_005 3 Syslog 2016,09,08 1 LO380_004 </code></pre>
0
2016-10-10T20:24:04Z
[ "python", "pandas" ]
replacing a column in DataFrame using regex
39,965,414
<p>I have a data frame with 4 columns, col4 is a string including texts and digits:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 PD380_003 %LINK-3-UPDOWN Syslog 2016,09,17 1 NM380_005 %BGP-5-NBR_RESET Syslog 2016,09,14 1 NM380_005 %BGP-5-NBR_RESET Syslog 2016,09,08 1 DO NOT TICKET LO380_004 %SYS-5-CONFIG_I Config </code></pre> <p>i need to keep a substring of that column and delete anything else, so I used regex and i made a pattern but when i run the following query the result is not what i want, it replace everything with the pattern itself:</p> <pre><code>data.replace({'Col4':{'.*':'([A-Z]{2}[0-9]{3}_[0-9]{3})'}},regex=True) </code></pre> <p>desired result is:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 PD380_003 Syslog 2016,09,17 1 NM380_005 Syslog 2016,09,14 1 LO380_004 Syslog 2016,09,08 1 LO380_004 </code></pre> <p>but the result i get is like:</p> <pre><code> Col1 Col2 Col3 Col4 Syslog 2016,09,17 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,17 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,14 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) Syslog 2016,09,08 1 ([A-Z]{2}[0-9]{3}_[0-9]{3}) </code></pre> <p>what am i doing wrong?</p>
2
2016-10-10T19:29:42Z
39,966,535
<p>First, you have the wrong regex's in the wrong positions. The <code>to_replace</code> argument to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html?highlight=replace#pandas-dataframe-replace" rel="nofollow">.replace</a> needs to match what to replace and what to delete. So you need a <code>^.*</code> in front of and a <code>.*$</code> behind your regex in this case since you want to trim the string outside the match:</p> <pre><code>^.*([A-Z]{2}[0-9]{3}_[0-9]{3}).*$ </code></pre> <p><a href="https://www.regex101.com/r/X6cypX/3" rel="nofollow">Demo</a></p> <p>Second, the <code>replace</code> argument, if a regex, needs to be a capturing group or fixed string. In this case <code>\1</code> will do. </p> <p>Last, the Series form of <code>.replace</code> has a littler simpler syntax (at least for me) to understand. </p> <p>So given:</p> <pre><code>&gt;&gt;&gt; df Col1 Col2 Col3 Col4 0 SysLog 2016,09,17 1 PD380_003 %LINK-3-UPDOWN 1 SysLog 2016,09,17 1 NM380_005 %BGP-5-NBR_RESET 2 SysLog 2016,09,17 1 NM380_005 %BGP-5-NBR_RESET 3 SysLog 2016,09,17 1 DO NOT TICKET LO380_004 %SYS-5-CONFIG_I Config </code></pre> <p>You can do:</p> <pre><code>&gt;&gt;&gt; df['Col4'].replace(to_replace='^.*([A-Z]{2}[0-9]{3}_[0-9]{3}).*$', value=r'\1', regex=True) 0 PD380_003 1 NM380_005 2 NM380_005 3 LO380_004 Name: Col4, dtype: object </code></pre> <p>You can also use a positional argument version if easier: </p> <pre><code>df['Col4'].replace('^.*([A-Z]{2}[0-9]{3}_[0-9]{3}).*$', r'\1', regex=True) </code></pre> <p>but you need to have <code>regex=True</code> since the replacement string is to be interpreted as a regex -- not just a static string.</p> <p>Finally, assign directly into the original:</p> <pre><code>&gt;&gt;&gt; df['Col4']=df['Col4'].replace('^.*([A-Z]{2}[0-9]{3}_[0-9]{3}).*$', r'\1', regex=True) &gt;&gt;&gt; df Col1 Col2 Col3 Col4 0 SysLog 2016,09,17 1 PD380_003 1 SysLog 2016,09,17 1 NM380_005 2 SysLog 2016,09,17 1 NM380_005 3 SysLog 2016,09,17 1 LO380_004 </code></pre>
1
2016-10-10T20:49:56Z
[ "python", "pandas" ]
beautiful soup - python - table scraping
39,965,416
<p>Trying to scrape a table from a website using beautiful soup in order to parse the data. How would I go about parsing it by its headers? So far, I can't even manage to print the entire table.Thanks in advance.</p> <p>Here is the code:</p> <pre><code>import urllib2 from bs4 import BeautifulSoup optionstable = "http://www.barchart.com/options/optdailyvol?type=stocks" page = urllib2.urlopen(optionstable) soup = BeautifulSoup(page, 'lxml') table = soup.find("div", {"class":"dataTables_wrapper","id": "options_wrapper"}) table1 = table.find_all('table') print table1 </code></pre>
1
2016-10-10T19:29:45Z
39,965,708
<p>The page is a dynamic page. It uses the <a href="https://datatables.net/" rel="nofollow">DataTables</a> jquery plugin to display the table. If you look at the page source you'll see an empty table. It is filled after the page is loaded.</p> <p>You have two choices here. Either figure out which URL the Javascript code running in the browser accesses to get the table data, and hope that simply accessing this URL will work. If it does, the response will probably be in JSON, so you don't need to parse anything.</p> <p>The second choice is to use a tool like Selenium or PhantomJS to load the page and run the Javascript code. Then you can access the already populated table and get its data.</p>
0
2016-10-10T19:49:23Z
[ "python", "parsing", "web-scraping", "beautifulsoup" ]
beautiful soup - python - table scraping
39,965,416
<p>Trying to scrape a table from a website using beautiful soup in order to parse the data. How would I go about parsing it by its headers? So far, I can't even manage to print the entire table.Thanks in advance.</p> <p>Here is the code:</p> <pre><code>import urllib2 from bs4 import BeautifulSoup optionstable = "http://www.barchart.com/options/optdailyvol?type=stocks" page = urllib2.urlopen(optionstable) soup = BeautifulSoup(page, 'lxml') table = soup.find("div", {"class":"dataTables_wrapper","id": "options_wrapper"}) table1 = table.find_all('table') print table1 </code></pre>
1
2016-10-10T19:29:45Z
39,965,760
<p>You need to mimic the ajax request to get the table data:</p> <pre><code>import requests from time import time optionstable = "http://www.barchart.com/options/optdailyvol?type=stocks" params = {"type": "stocks", "dir": "desc", "_": str(time()), "f": "base_symbol,type,strike,expiration_date,bid,ask,last,volume,open_interest,volatility,timestamp", "sEcho": "1", "iDisplayStart": "0", "iDisplayLength": "100", "iSortCol_0": "7", "sSortDir_0": "desc", "iSortingCols": "1", "bSortable_0": "true", "bSortable_1": "true", "bSortable_2": "true", "bSortable_3": "true", "bSortable_4": "true", "bSortable_5": "true", "bSortable_6": "true", "bSortable_7": "true", "bSortable_82": "true", "bSortable_9": "true", "bSortable_10": "true", "sortby": "Volume"} </code></pre> <p>Then do a get passing the params:</p> <pre><code>js = requests.get("http://www.barchart.com/option-center/getData.php", params=params).json() </code></pre> <p>Which gives you:</p> <pre><code>{u'aaData': [[u'&lt;a href="/quotes/BAC"&gt;BAC&lt;/a&gt;', u'Call', u'16.00', `u'12/16/16', u'0.89', u'0.90', u'0.91', u'52,482', u'146,378', u'0.26', u'01:43'], [u'&lt;a href="/quotes/ETE"&gt;ETE&lt;/a&gt;', u'Call', u'20.00', u'01/20/17', u'0.38', u'0.41', u'0.40', u'40,785', u'72,011', u'0.42', u'01:27'], [u'&lt;a href="/quotes/BAC"&gt;BAC&lt;/a&gt;', u'Call', u'15.00', u'10/21/16', u'1.34', u'1.36', u'1.33', u'35,663', u'90,342', u'0.35', u'01:44'], [u'&lt;a href="/quotes/COTY"&gt;COTY&lt;/a&gt;', u'Put', u'38.00', u'10/21/16', u'15.00', u'15.30', u'15.10', u'32,321', u'242,382', u'1.24', u'01:44'], [u'&lt;a href="/quotes/COTY"&gt;COTY&lt;/a&gt;', u'Call', u'38.00', u'10/21/16', u'0.00', u'0.05', u'0.01', u'32,320', u'256,589', u'1.34', u'01:44'], [u'&lt;a href="/quotes/WFC"&gt;WFC&lt;/a&gt;', u'Put', u'40.00', u'10/21/16', u'0.01', u'0.03', u'0.02', u'32,121', u'37,758', u'0.39', u'01:43'], [u'&lt;a href="/quotes/WFC"&gt;WFC&lt;/a&gt;', u'Put', u'40.00', u'11/18/16', u'0.16', u'0.17', u'0.16', u'32,023', u'8,789', u'0.30', u'01:44'].................. </code></pre> <p>There are many more params you can pass, if you watch the request in chrome tools under the <em>XHR</em> tab, you can see all the <em>params</em>, the ones above were the minimum needed to get a result. There are quite a lot so I won't post them all here and leave you to figure out how you can influence the results.</p> <p>If you iterate over <code>js[u'aaData']</code>, you can see each sublist where each entry corresponds to the columns like:</p> <pre><code>#base_symbol,type,strike,expiration_date,bid,ask,last,volume,open_interest,volatility,timestamp [u'&lt;a href="/quotes/AAPL"&gt;AAPL&lt;/a&gt;', u'Call', u'116.00', u'10/14/16', u'1.36', u'1.38', u'1.37', u'21,812', u'7,258', u'0.23', u'10/10/16'] </code></pre> <p>So if you want to filter rows based on some criteria i.e strike > 15:</p> <pre><code>for d in filter(lambda row: float(row[2]) &gt; 15, js[u'aaData']): print(d) </code></pre> <p>You might also find pandas useful, with a little bit of tidying up we can create a nice df:</p> <pre><code># extract base_symbol text for v in js[u'aaData']: v[0] = BeautifulSoup(v[0]).a.text import pandas as pd cols = "base_symbol,type,strike,expiration_date,bid,ask,last,volume,open_interest,volatility,timestamp" df = pd.DataFrame(js[u'aaData'], columns=cols.split(",")) print(df.head(5)) </code></pre> <p>That gives you a nice df to work with:</p> <pre><code> base_symbol type strike expiration_date bid ask last volume \ 0 BAC Call 16.00 12/16/16 0.89 0.90 0.91 52,482 1 ETE Call 20.00 01/20/17 0.38 0.41 0.40 40,785 2 BAC Call 15.00 10/21/16 1.34 1.36 1.33 35,663 3 COTY Put 38.00 10/21/16 15.00 15.30 15.10 32,321 4 COTY Call 38.00 10/21/16 0.00 0.05 0.01 32,320 open_interest volatility timestamp 0 146,378 0.26 10/10/16 1 72,011 0.42 10/10/16 2 90,342 0.35 10/10/16 3 242,382 1.24 10/10/16 4 256,589 1.34 10/10/16 </code></pre> <p>You might just want to change the dtypes <code>df["strike"] = df["strike"].astype(float)</code> etc.. </p>
2
2016-10-10T19:52:33Z
[ "python", "parsing", "web-scraping", "beautifulsoup" ]
Horizontal Bar Chart on Pandas Data Frame with Dynamic Column Names
39,965,440
<p>I have the following source data (which comes from a csv file):</p> <pre><code>ABC,2016-6-9 0:00,95,"{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}" ABC,2016-6-10 0:00,0,"{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}" ABC,2016-6-11 0:00,0,"{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}" ABC,2016-6-12 0:00,0,"{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}" ABC,2016-6-13 0:00,0,"{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}" DEF,2016-6-16 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}" DEF,2016-6-17 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}" DEF,2016-6-18 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}" DEF,2016-6-19 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}" DEF,2016-6-20 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}" </code></pre> <p>I use <a href="http://stackoverflow.com/questions/39928273/how-to-remove-curly-braces-apostrophes-and-square-brackets-from-dictionaries-in">How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)</a> to transform that data into a Data Frame that I can use to plot certain variables. The Data Frame looks as follows (note: not the same data as what's in the source csv file, but the structure is the same):</p> <pre><code> Company Date Code Yellow Blue White Black 0 ABC 2016-6-9 115 403 16 19 472 1 ABC 2016-6-10 219 381 90 20 2474 2 ABC 2016-6-11 817 21 31 88 54 3 ABC 2016-6-12 80 2011 8888 0 21 4 ABC 2016-6-13 21 15 46 20 56 5 DEF 2016-6-16 64 42 76 4 41 6 DEF 2016-6-17 694 13 84 50 986 7 DEF 2016-6-18 325 485 38 60 174 8 DEF 2016-6-19 418 35 174 251 11 9 DEF 2016-6-20 50 56 59 19 03 </code></pre> <p>I need to create several time series plots of the colors (which I can do very easily, given the way that the data frame is constructed). </p> <p>But, I also want to be able to make a horizontal bar plot <strong>as of a specific date</strong> (see <a href="https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_barplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_barplot.html</a> for an example).</p> <p>For instance, using my data, as of June 9, 2016, the bar plot would look as follows (not to scale):</p> <pre><code>Black: ******************************** Yellow: ************************** White: *** Blue: ** </code></pre> <p>The problem I'm having is that the column names (e.g. 'yellow', 'blue', 'white' and 'black') can change, as can the number of columns.</p> <p>Does anyone know if it is possible to loop through a certain number of columns <strong>to the right</strong> of the 'Code' column and then use those to create a horizontal bar chart similar to what's above? Or, perhaps take a slice of the data to the right of the 'Code' column? </p> <p>Or, does the Data Frame itself need to be structured differently such that it can be used to make both a time series plot and a horizontal bar chart?</p> <p>Thanks!</p>
0
2016-10-10T19:31:25Z
39,966,184
<p>in order to loop through a certain number of columns to the right of the 'code' column I would do something of the form</p> <pre><code>for col in df.columns[3:]: plot(col) </code></pre> <p>However this only works if you can guarantee that your columns will always be in the same order. Alternatively you could make sure that the columns of interest for that particular chart are named in a systematic way.</p> <p>Hope this helps!</p>
0
2016-10-10T20:24:56Z
[ "python", "pandas", "matplotlib", "plot", "seaborn" ]
Horizontal Bar Chart on Pandas Data Frame with Dynamic Column Names
39,965,440
<p>I have the following source data (which comes from a csv file):</p> <pre><code>ABC,2016-6-9 0:00,95,"{'//Purple': [115L], '//Yellow': [403L], '//Blue': [16L], '//White-XYZ': [0L]}" ABC,2016-6-10 0:00,0,"{'//Purple': [219L], '//Yellow': [381L], '//Blue': [90L], '//White-XYZ': [0L]}" ABC,2016-6-11 0:00,0,"{'//Purple': [817L], '//Yellow': [21L], '//Blue': [31L], '//White-XYZ': [0L]}" ABC,2016-6-12 0:00,0,"{'//Purple': [80L], '//Yellow': [2011L], '//Blue': [8888L], '//White-XYZ': [0L]}" ABC,2016-6-13 0:00,0,"{'//Purple': [32L], '//Yellow': [15L], '//Blue': [4L], '//White-XYZ': [0L]}" DEF,2016-6-16 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [3L]}" DEF,2016-6-17 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [0L]}" DEF,2016-6-18 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [7L]}" DEF,2016-6-19 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [14L]}" DEF,2016-6-20 0:00,0,"{'//Purple': [32L], '//Black': [15L], '//Pink': [4L], '//NPO-Green': [21L]}" </code></pre> <p>I use <a href="http://stackoverflow.com/questions/39928273/how-to-remove-curly-braces-apostrophes-and-square-brackets-from-dictionaries-in">How to remove curly braces, apostrophes and square brackets from dictionaries in a Pandas dataframe (Python)</a> to transform that data into a Data Frame that I can use to plot certain variables. The Data Frame looks as follows (note: not the same data as what's in the source csv file, but the structure is the same):</p> <pre><code> Company Date Code Yellow Blue White Black 0 ABC 2016-6-9 115 403 16 19 472 1 ABC 2016-6-10 219 381 90 20 2474 2 ABC 2016-6-11 817 21 31 88 54 3 ABC 2016-6-12 80 2011 8888 0 21 4 ABC 2016-6-13 21 15 46 20 56 5 DEF 2016-6-16 64 42 76 4 41 6 DEF 2016-6-17 694 13 84 50 986 7 DEF 2016-6-18 325 485 38 60 174 8 DEF 2016-6-19 418 35 174 251 11 9 DEF 2016-6-20 50 56 59 19 03 </code></pre> <p>I need to create several time series plots of the colors (which I can do very easily, given the way that the data frame is constructed). </p> <p>But, I also want to be able to make a horizontal bar plot <strong>as of a specific date</strong> (see <a href="https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_barplot.html" rel="nofollow">https://stanford.edu/~mwaskom/software/seaborn/examples/horizontal_barplot.html</a> for an example).</p> <p>For instance, using my data, as of June 9, 2016, the bar plot would look as follows (not to scale):</p> <pre><code>Black: ******************************** Yellow: ************************** White: *** Blue: ** </code></pre> <p>The problem I'm having is that the column names (e.g. 'yellow', 'blue', 'white' and 'black') can change, as can the number of columns.</p> <p>Does anyone know if it is possible to loop through a certain number of columns <strong>to the right</strong> of the 'Code' column and then use those to create a horizontal bar chart similar to what's above? Or, perhaps take a slice of the data to the right of the 'Code' column? </p> <p>Or, does the Data Frame itself need to be structured differently such that it can be used to make both a time series plot and a horizontal bar chart?</p> <p>Thanks!</p>
0
2016-10-10T19:31:25Z
39,966,630
<p>IIUC you can do it this way:</p> <p>Original DF:</p> <pre><code>In [127]: df Out[127]: Company Date Code Yellow Blue White Black 0 ABC 2016-06-09 115 403 16 19 472 1 ABC 2016-06-10 219 381 90 20 2474 2 ABC 2016-06-11 817 21 31 88 54 3 ABC 2016-06-12 80 2011 8888 0 21 4 ABC 2016-06-13 21 15 46 20 56 5 DEF 2016-06-16 64 42 76 4 41 6 DEF 2016-06-17 694 13 84 50 986 7 DEF 2016-06-18 325 485 38 60 174 8 DEF 2016-06-19 418 35 174 251 11 9 DEF 2016-06-20 50 56 59 19 3 </code></pre> <p>set <code>Date</code> as index:</p> <pre><code>In [128]: df = df.set_index('Date') In [129]: df Out[129]: Company Code Yellow Blue White Black Date 2016-06-09 ABC 115 403 16 19 472 2016-06-10 ABC 219 381 90 20 2474 2016-06-11 ABC 817 21 31 88 54 2016-06-12 ABC 80 2011 8888 0 21 2016-06-13 ABC 21 15 46 20 56 2016-06-16 DEF 64 42 76 4 41 2016-06-17 DEF 694 13 84 50 986 2016-06-18 DEF 325 485 38 60 174 2016-06-19 DEF 418 35 174 251 11 2016-06-20 DEF 50 56 59 19 3 In [130]: cols = df.drop(['Company','Code'], 1).columns.tolist() In [131]: cols Out[131]: ['Yellow', 'Blue', 'White', 'Black'] In [139]: %paste import matplotlib matplotlib.style.use('ggplot') In [140]: df.ix['2016-06-09', cols].plot.barh(rot=0, color=cols) Out[140]: &lt;matplotlib.axes._subplots.AxesSubplot at 0x1890a898&gt; </code></pre> <p><a href="http://i.stack.imgur.com/zVm75.png" rel="nofollow"><img src="http://i.stack.imgur.com/zVm75.png" alt="enter image description here"></a></p> <p>or if you want to plot is sorted:</p> <pre><code>In [142]: srt = df.ix['2016-06-09', cols].sort_values() In [143]: srt.plot.barh(color=srt.index) Out[143]: &lt;matplotlib.axes._subplots.AxesSubplot at 0x1cf16748&gt; </code></pre> <p><a href="http://i.stack.imgur.com/Wz81B.png" rel="nofollow"><img src="http://i.stack.imgur.com/Wz81B.png" alt="enter image description here"></a></p>
0
2016-10-10T20:56:45Z
[ "python", "pandas", "matplotlib", "plot", "seaborn" ]
What is the proper way to write a syslog function in python?
39,965,535
<p>Despite my efforts I have been unable to figure out how to create a function that works with logging in python. No matter what I do, I get a duplicate syslog entry.</p> <pre><code>def send_syslog(input): my_logger = logging.getLogger() my_logger.setLevel(logging.DEBUG) handler = logging.handlers.SysLogHandler(address='/dev/log', facility=19) my_logger.addHandler(handler) my_logger.info("SYSTEM MESSAGE: " + str(input)) def main(): send_syslog("Everything is working okay!") if __name__ == "__main__": main() </code></pre> <p>I have tried re-ordering, writing like this but I get the same thing: </p> <pre><code>def send_syslog(input): my_logger.info("SYSTEM MESSAGE: " + str(input)) def main(): my_logger = logging.getLogger() my_logger.setLevel(logging.DEBUG) handler = logging.handlers.SysLogHandler(address='/dev/log', facility=19) my_logger.addHandler(handler) send_syslog("Everything is working okay!") if __name__ == "__main__": main() </code></pre> <p>What is the proper way to write a syslog function I can reuse in my own program?</p>
0
2016-10-10T19:38:17Z
39,965,571
<p>You should use the python <a href="https://docs.python.org/2/library/syslog.html" rel="nofollow">syslog</a> module:</p> <pre><code>import syslog def main(): syslog.syslog(syslog.LOG_INFO, "Everything is working okay!") syslog.syslog(syslog.LOG_ERR, 'This is logged at the error level.') if __name__ == "__main__": main() </code></pre>
0
2016-10-10T19:40:06Z
[ "python", "function", "logging", "syslog" ]
Python sympy dsolve error
39,965,537
<p>After reinstalling Python, the following simple code</p> <pre><code>import sympy as sm x = sm.Symbol('x') f = sm.Function('f') y = sm.dsolve(sm.diff(f (x),x)-3*f(x)(1-0.5f(x)),f(x)) print(y) </code></pre> <p>gives the following output:</p> <pre><code>Eq(x + 0.333333333333333*log(1.0*f(x) - 2.0) - 0.333333333333333*log(1.0*f(x)), C1) </code></pre> <p>but before it used to give me the right answer: <code>f(x) == -2.0/(C1*exp(-3.0*x) - 1.0)</code>.</p> <p>Can someone help me to fix this, please?</p>
1
2016-10-10T19:38:19Z
39,966,548
<p>You can try to use <code>Rational</code> instead of float number, as follow:</p> <pre><code>&gt;&gt;&gt; import sympy as sym &gt;&gt;&gt; x = sym.Symbol('x') &gt;&gt;&gt; f = sym.Function('f')(x) &gt;&gt;&gt; y = sym.dsolve(sym.diff(f,x)-3*f*(1-sym.Rational(1, 2)*f),f) &gt;&gt;&gt; print y Eq(f(x), -2/(C1*exp(-3*x) - 1)) </code></pre>
1
2016-10-10T20:51:27Z
[ "python", "sympy", "dsolve" ]
Python sympy dsolve error
39,965,537
<p>After reinstalling Python, the following simple code</p> <pre><code>import sympy as sm x = sm.Symbol('x') f = sm.Function('f') y = sm.dsolve(sm.diff(f (x),x)-3*f(x)(1-0.5f(x)),f(x)) print(y) </code></pre> <p>gives the following output:</p> <pre><code>Eq(x + 0.333333333333333*log(1.0*f(x) - 2.0) - 0.333333333333333*log(1.0*f(x)), C1) </code></pre> <p>but before it used to give me the right answer: <code>f(x) == -2.0/(C1*exp(-3.0*x) - 1.0)</code>.</p> <p>Can someone help me to fix this, please?</p>
1
2016-10-10T19:38:19Z
39,997,796
<p>First of all I am sorry about the syntax and editing mistakes in the first post. Actually, right now I am running exactly the same code in two computers, one with Anaconda for Windows other with Spyder for Ubuntu, both have Python 2.7, and got two different answers. The code is:</p> <p>import sympy as sm</p> <p>x = sm.Symbol('x') f = sm.Function('f')(x)</p> <p>y=sm.dsolve(sm.diff(f,x)-3*f*(1-0.5*f),f) print(y)</p> <p>In the Ubuntu version I obtain the explicit solution f(x) == -2.0/(C1*exp(-3.0*x) - 1.0) While in the windows machine I obtain the implicit solution Eq(x + 0.3333333333333*log(1.0*f(x) - 2.0) - 0.333333333333*log(1.0*f(x)), C1)</p>
0
2016-10-12T11:46:06Z
[ "python", "sympy", "dsolve" ]
append pandas series in loop
39,965,632
<p>I have tries using pandas.Series().append() inside a loop but the return is the same Series that went into this method. I need this method to return a pandas Series with repeating values. The number of repetitions decided by num.</p> <pre><code>def expand(ser, num): sers = ser x = 0 while(x &lt; num): sers.append(sers).reset_index(drop=True) x+=1 return sers </code></pre>
0
2016-10-10T19:44:42Z
39,965,707
<p>Is there a reason you don't want to use <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.Series.repeat.html" rel="nofollow"><code>pandas.Series.repeat</code></a>?</p> <pre><code>import pandas as pd import numpy as np s = pd.Series(np.random.randn(3), index=['a', 'b', 'c']) num = 3 repeated_s = s.repeat(num) repeated_s a 1.445775 a 1.445775 a 1.445775 b -1.672416 b -1.672416 b -1.672416 c 1.551762 c 1.551762 c 1.551762 dtype: float64 </code></pre>
0
2016-10-10T19:49:14Z
[ "python", "pandas" ]
Django Translation Don't Work
39,965,689
<p>Try to translate block this block and load i18n:</p> <pre><code>{% load i18n %} &lt;p&gt;{% trans "Welcome to our page" %}&lt;/p&gt; {% language 'ru' %} &lt;p&gt;{% trans "Welcome to our page" %}&lt;/p&gt; {% endlanguage %} </code></pre> <p>settings.py</p> <pre><code>SE_I18N = True USE_L10N = True LANGUAGES = ( ('en', _('English')), ('ru', _('Russian')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) TEMPLATES = [ { 'context_processors': [ 'django.template.context_processors.i18n', MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] </code></pre> <p>.po</p> <pre><code>msgid "Welcome to our page" msgstr "Приветствую вас!" #: project/settings.py:172 msgid "English" msgstr "Английский" #: project/settings.py:173 msgid "Russian" msgstr "Русский" </code></pre> <p>mo.</p> <pre><code>Report-Msgid-Bugs-To: POT-Creation-Date: 2016-10-10 19:24+0000 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME &lt;EMAIL@ADDRESS&gt; Language-Team: LANGUAGE &lt;LL@li.org&gt; Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Английский Русский Приветствую вас! </code></pre> <p>urls.py</p> <pre><code>import os from django.conf.urls import url, include from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^', include('account_management.urls')), url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), ] urlpatterns += staticfiles_urlpatterns() </code></pre> <p>But result is:</p> <p>Welcome to our page Welcome to our page</p> <p>I used this doc <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/i18n/translation/</a></p> <p>Maybe I forgot something?</p>
0
2016-10-10T19:48:19Z
39,966,481
<p>So what is going on, is that you have just ordinary urls, when you needed <code>i18n_patterns</code>,</p> <p>So, change your urls to </p> <pre><code>import os from django.conf.urls import url, include from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( url(r'^', include('account_management.urls')), # put here urls that you need to translate ) urlpatterns += staticfiles_urlpatterns() </code></pre> <p>The docs can be found here <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#module-django.conf.urls.i18n" rel="nofollow"><code>i18n_patterns</code></a></p>
0
2016-10-10T20:46:19Z
[ "python", "django" ]
Django Translation Don't Work
39,965,689
<p>Try to translate block this block and load i18n:</p> <pre><code>{% load i18n %} &lt;p&gt;{% trans "Welcome to our page" %}&lt;/p&gt; {% language 'ru' %} &lt;p&gt;{% trans "Welcome to our page" %}&lt;/p&gt; {% endlanguage %} </code></pre> <p>settings.py</p> <pre><code>SE_I18N = True USE_L10N = True LANGUAGES = ( ('en', _('English')), ('ru', _('Russian')), ) LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) TEMPLATES = [ { 'context_processors': [ 'django.template.context_processors.i18n', MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] </code></pre> <p>.po</p> <pre><code>msgid "Welcome to our page" msgstr "Приветствую вас!" #: project/settings.py:172 msgid "English" msgstr "Английский" #: project/settings.py:173 msgid "Russian" msgstr "Русский" </code></pre> <p>mo.</p> <pre><code>Report-Msgid-Bugs-To: POT-Creation-Date: 2016-10-10 19:24+0000 PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE Last-Translator: FULL NAME &lt;EMAIL@ADDRESS&gt; Language-Team: LANGUAGE &lt;LL@li.org&gt; Language: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Английский Русский Приветствую вас! </code></pre> <p>urls.py</p> <pre><code>import os from django.conf.urls import url, include from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ url(r'^', include('account_management.urls')), url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), ] urlpatterns += staticfiles_urlpatterns() </code></pre> <p>But result is:</p> <p>Welcome to our page Welcome to our page</p> <p>I used this doc <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/i18n/translation/</a></p> <p>Maybe I forgot something?</p>
0
2016-10-10T19:48:19Z
39,967,009
<p>You need to use <code>{% get_current_language as LANGUAGE_CODE %}</code> tag which updates the <code>LANGUAGE_CODE</code> setting. See <a href="https://docs.djangoproject.com/en/1.10/topics/i18n/translation/#how-django-discovers-language-preference" rel="nofollow">how-django-discovers-language-preference</a>.</p> <pre><code>{% load i18n %} &lt;p&gt;{% trans "Welcome to our page" %}&lt;/p&gt; {% language 'ru' %} {% get_current_language as LANGUAGE_CODE %} &lt;p&gt;{% trans "Welcome to our page" %}&lt;/p&gt; {% endlanguage %} </code></pre> <p>Hope this helps.</p>
1
2016-10-10T21:27:33Z
[ "python", "django" ]
1064, "You have an error in your SQL syntax;..." Python MySQL
39,965,697
<p>So I have been working on this since last Friday and cannot get around this error:</p> <blockquote> <p>1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[u'161010-035670'] WHERE order_id=87' at line 1" or something along the same lines as this error.</p> </blockquote> <p>Basically my python will grab data from MySQL database, it creates a case in SalesForce using Simple-Salesforce and then queries that case it created correctly but I need it to write that case number back into the database in a column I created specifically for the ticket number. </p> <p>Current Code:</p> <pre><code>for rowx in xrange(1, sheet.nrows): SN = sheet.row_values(rowx, start_colx=3, end_colx=None)[0] print SN Id = sheet.row_values(rowx, start_colx=6, end_colx=None)[0] print Id d = sf.query("SELECT CaseNumber FROM Case WHERE Serial_Number__c ='%s' AND Status = 'New Portal RMA'" % SN) data = [e["CaseNumber"] for e in d["records"]] print (data) try: con = MySQLdb.connect(user=ur, passwd=pd, host=ht, port=pt, db=db) cursor = con.cursor() cursor.execute("UPDATE tplinkus_rma.rma_order SET rma_num=%s WHERE order_id=%s" % (data, Id)) con.commit() except Error as error: print(error) finally: cursor.close() con.close() </code></pre> <p>Main issue is with this line of code:</p> <pre><code> cursor.execute("UPDATE tplinkus_rma.rma_order SET rma_num=%s WHERE order_id=%s" % (data, Id)) </code></pre> <p>I have tried with and without '%s' with no difference, tried "...WHERE order_id=%s", (data, Id)) with same error. If I replace "order_id=87" and let data stay there with cursor.execute("UPDATE tplinkus_rma.rma_order SET rma_num=%s WHERE order_id=87" % (data)) then it works fine and writes the case number in the correct format into the database, as soon as I add "Id" as a factor with %s then it gives me errors. I have also tried with %d with same result.</p> <p>Any help would be greatly appreciated. </p>
1
2016-10-10T19:48:43Z
39,965,783
<p>The <code>data</code> value is a <em>list</em> and you are trying to format it into the query. And, <strong>don't use string formatting to insert variables into a query</strong> - use a proper <em>query parameterization</em> instead:</p> <pre><code>cursor.execute(""" UPDATE tplinkus_rma.rma_order SET rma_num=%s WHERE order_id=%s""", (data[0], Id)) </code></pre> <p>Note how the query parameters are placed in a tuple and passed as a separate argument.</p>
0
2016-10-10T19:54:10Z
[ "python", "mysql", "python-2.7", "salesforce", "mysql-python" ]
python log formatter that shows all kwargs in extra
39,965,807
<p>I hope to add the following log points to my application and display the full contents of <code>extra</code> on console, e.g., </p> <pre><code>logger.info('Status', extra={'foo':data}) logger.info('Status', extra={'bar':data}) logger.info('Status', extra={'foo':data, 'bar':data}) </code></pre> <p>and I hope to see:</p> <pre><code>2016-10-10 15:28:31,408, INFO, Status, foo=data 2016-10-10 15:38:31,408, INFO, Status, bar=data 2016-10-10 15:48:31,408, INFO, Status, foo=data, bar=data </code></pre> <p>Is this even possible? According to official logging documentation, the <code>Formatter</code> must be set up with a format string that expects <code>foo</code> and <code>bar</code> but in my case all I want is to dump out the entire kwargs of <code>extra</code> without prior knowledge of <code>foo</code> and <code>bar</code>.</p>
1
2016-10-10T19:56:14Z
39,974,319
<p>Trying to solve the same problem right now. The problem is that anything passed to extra is added as a property of LogRecord and the formatter cannot distinguish it from other LogRecord properties. I only came up with a hackish approach of creating a dummy record and comparing it with the actual one:</p> <pre><code>class ExtraLogFormatter(logging.Formatter): def format(self, record): dummy = logging.LogRecord(None,None,None,None,None,None,None) extra_txt = '' for k,v in record.__dict__.items(): if k not in dummy.__dict__: extra_txt += ', {}={}'.format(k,v) message = super().format(record) return message + extra_txt </code></pre>
0
2016-10-11T09:33:32Z
[ "python", "logging" ]
Python ignoring property setter in favor of property getter
39,965,824
<p>I have created a class that has a property with a setter. There are 2 different ways to use this class, so the values of some of the object components may be set in a different order depending on the scenario (i.e. I don't want to set them during <code>__init__</code>). I have included a non-property with its own set function here to illustrate what is and isn't working.</p> <pre><code>class Dumbclass(object): def __init__(self): self.name = None self.__priority = None @property def priority(self): return self.__priority @priority.setter def priority(self, p): self.__priority = p def set_name(self, name): self.name = "dumb " + name def all_the_things(self, name, priority=100): self.set_name(name) self.priority(priority) print self.name print self.priority </code></pre> <p>When I run the following, it returns <code>TypeError: 'NoneType' object is not callable</code>. I investigated with pdb, and found that it was calling the getter instead of the setter at <code>self.priority(priority)</code>.</p> <pre><code>if __name__ == '__main__': d1 = Dumbclass() d1.all_the_things("class 1") d2 = Dumbclass() d2.all_the_things("class 2", 4) </code></pre> <p>What's going on here?</p>
1
2016-10-10T19:57:06Z
39,966,260
<p>Short Answer: Please change your line <code>self.priority(priority)</code> to <code>self.priority = priority</code></p> <p>Explanation: Setter is called only when you assign something to the attribute. In your code, you are not doing an assignment operation.</p> <p>Here are some nice references if you want to understand more:</p> <ol> <li><a href="http://www.ibm.com/developerworks/library/os-pythondescriptors/" rel="nofollow">Python descriptors</a></li> <li><a href="http://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work">How does the @property decorator work?</a></li> <li><a href="http://www.programiz.com/python-programming/property" rel="nofollow">Real Life Example</a></li> </ol>
2
2016-10-10T20:29:47Z
[ "python", "properties" ]
Python ignoring property setter in favor of property getter
39,965,824
<p>I have created a class that has a property with a setter. There are 2 different ways to use this class, so the values of some of the object components may be set in a different order depending on the scenario (i.e. I don't want to set them during <code>__init__</code>). I have included a non-property with its own set function here to illustrate what is and isn't working.</p> <pre><code>class Dumbclass(object): def __init__(self): self.name = None self.__priority = None @property def priority(self): return self.__priority @priority.setter def priority(self, p): self.__priority = p def set_name(self, name): self.name = "dumb " + name def all_the_things(self, name, priority=100): self.set_name(name) self.priority(priority) print self.name print self.priority </code></pre> <p>When I run the following, it returns <code>TypeError: 'NoneType' object is not callable</code>. I investigated with pdb, and found that it was calling the getter instead of the setter at <code>self.priority(priority)</code>.</p> <pre><code>if __name__ == '__main__': d1 = Dumbclass() d1.all_the_things("class 1") d2 = Dumbclass() d2.all_the_things("class 2", 4) </code></pre> <p>What's going on here?</p>
1
2016-10-10T19:57:06Z
39,966,297
<p>You are facing this issue due to trying to treat priority as a method in your all_the_things method. At this point it is already a property, so you assign to it like a variable:</p> <pre><code>def all_the_things(self, name, priority=100): self.set_name(name) self.priority = priority </code></pre>
0
2016-10-10T20:32:06Z
[ "python", "properties" ]
obtaining boundary of polygon embedded in a matrix and other post-processing techniques
39,965,825
<p>I have a 100x100 Boolean matrix called <code>mat</code>. All cells have false value except a continuous patch of polygonal area. I can read the cells belonging to this polygon by running through each cell of the matrix and finding true cells.</p> <pre><code>region_of_interest=false(size(mat)); for i=1:size(mat,1) for j=1:size(mat,2) if mat(i,j) region_of_interest(i,j)=true; end end end </code></pre> <p>Now I want to do further processing of this polygon like store only the boundary cells. How to do this? I tried visiting each polygonal cell and seeing if all its four neighbors are in the polygon or not. But this did not seem very efficient. Are there better algorithms out there?</p> <p>If there are other post-processing methods that can be run in this scenario please suggest. Suggestions outside of Matlab are also welcome.</p>
2
2016-10-10T19:57:08Z
39,966,227
<p>This is neither Python nor a convex-hull problem.</p> <p>However, I would point out that boundary cells inside the polygon are true and have at least one neighbor which is false, and boundary cells outside the polygon are false and have at least one neighbor which is true.</p> <p>It's up to you to decide whether you want inner or outer boundary cells, and what a "neighbor" is. For example, are the neighbors of a cell the four neighbors in cardinal directions, or the eight neighbors in diagonal directions too? If it's the former, then you'll still have to search through the eight neighbors to use the algorithm I describe below to get from cell 1 to cell 2 in cases like the following:</p> <pre><code>...XX ...2X XX1XX XXXXX </code></pre> <p>That being said, it would depend on what your data is like as to how you'd want to write the algorithm. If you know that there is a single contiguous block with no holes in it, which seems to be what your question implies, then once you find a boundary cell, you simply need to walk along the boundary until you find the first cell again. So search neighbors until you find the next boundary cell, and then do it again.</p> <p>The problem is finding that first boundary cell.</p> <p>One method would be just searching randomly until you find a cell within the patch, and, then walking in any direction until you find a boundary.</p> <p>Another would be to do some sort of uniform search, perhaps in a grid, until you find that same first cell as described above. If you know that your patch size is always at least x-cells large, you could adjust your grid size based on that.</p> <p>Without more specific information, these ideas should at least help you reach a solution. Good luck!</p>
0
2016-10-10T20:27:57Z
[ "python", "matlab", "convex-hull" ]
plot legends of a correlation matrix
39,965,891
<p>I have a correlation mat obtained from a data frame</p> <pre><code>&gt;&gt;&gt; mat Lcaud Rcaud Left_cereb_gm Right_cereb_gm Lamyg Rcaud 0.931934 1.000000 0.856891 0.715523 0.924995 Left_cereb_gm 0.915274 0.856891 1.000000 0.938301 0.601521 Right_cereb_gm 0.744007 0.715523 0.938301 1.000000 0.445450 Lamyg 0.754676 0.924995 0.601521 0.445450 1.000000 Rput 0.717757 0.876985 0.635881 0.462773 0.912815 </code></pre> <p>I can nicely plot it with : </p> <pre><code>heatmap = plt.pcolor(mat, cmap=matplotlib.cm.Blues) </code></pre> <p>but I would like to get the legends 'Lcaud', 'Rcaud' etc... on the plot. </p> <p>How can I achieve this?</p>
0
2016-10-10T20:00:57Z
39,966,568
<p>I assume that you don't really want an <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend" rel="nofollow">actual legend</a> since there is no easy way to define what color corresponds to each label or label-label pair. Instead, I think you are asking about setting the ticklabels? For example, given this data:</p> <pre><code>df = pd.DataFrame(np.random.rand(50, 5), columns=list('ABCDE')) df.corr() A B C D E A 1.000000 0.184661 0.125002 0.024962 0.115385 B 0.184661 1.000000 0.224653 -0.178857 -0.185907 C 0.125002 0.224653 1.000000 -0.011785 0.238073 D 0.024962 -0.178857 -0.011785 1.000000 0.171649 E 0.115385 -0.185907 0.238073 0.171649 1.000000 </code></pre> <p>we can do the following:</p> <pre><code>import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.pcolor(df.corr(), cmap=plt.cm.Blues) ax.set_xticks(np.arange(5)+0.5) # center x ticks ax.set_yticks(np.arange(5)+0.5) # center y ticks ax.set_xticklabels(df.columns) ax.set_yticklabels(df.columns) </code></pre> <p>which yields this: <a href="http://i.stack.imgur.com/Dcjpl.png" rel="nofollow"><img src="http://i.stack.imgur.com/Dcjpl.png" alt="enter image description here"></a></p> <p>Alternatively, Pandas has a helper function to help visualize the correlation among dataframe columns, called <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html#scatter-matrix-plot" rel="nofollow"><code>scatter_matrix</code></a>:</p> <pre><code>from pandas import scatter_matrix scatter_matrix(df, diagonal='kde') </code></pre> <p>yields <a href="http://i.stack.imgur.com/6kWqv.png" rel="nofollow"><img src="http://i.stack.imgur.com/6kWqv.png" alt="enter image description here"></a></p>
2
2016-10-10T20:52:31Z
[ "python", "pandas", "matplotlib" ]
Python/Psychopy: passing information between functions
39,965,944
<p>I am having some trouble passing information between two functions. Within my 'trial' function (see code below) I am checking for keypresses and expecting to exit out of the while loop if a 'g or 'h' key is pressed. The while loop is dependent on test=1. From within my 'check_keys' function, as soon as the 'g' or 'h' key is pressed, test switches to 2; I would then expect to exit the while loop. As it stands, as I'm pressing keys, I can see they are being registered (due to the print statements), but it is not exiting the while loop. There seems to be an issue getting my main while loop to see that 'test' has switched to 2 from within my 'check_keys' function. I have tried changing 'test' to a global variable, but I'm still stuck with the same issue. Clearly information isn't being passed between both functions. </p> <pre><code>window = visual.Window([600,600],fullscr=False,color=("black"), allowGUI=True, monitor='testMonitor', units='deg') global test def check_keys(): allKeys = event.getKeys(keyList = ('g','h','escape')) for thisKey in allKeys: if thisKey == 'g': print "g" test = 2 elif thisKey == 'h': print "h" test = 2 def trial(): global test test = 1 while test ==1: check_keys() for i in range(1): trial() </code></pre> <p>In short; why am I stuck in the while loop despite that my conditional 'test' variable has changed?</p> <p>Cheers, Steve</p>
0
2016-10-10T20:05:36Z
39,966,069
<p>You're stuck because you haven't declared test as a global inside of your check_keys() method. That being said, what you should do is have check_keys return the value of test, and then just keep track of it in main:</p> <pre><code>def trial(): test = 1 while test == 1: test = check_keys() </code></pre>
1
2016-10-10T20:14:52Z
[ "python", "psychopy" ]
[Pandas]The way to assign a new column based on if statement
39,965,946
<p>I know assign could help to create/change one column based on lambda function like this: </p> <pre><code>df.assign(c = lambda x: x.sum()) </code></pre> <p>But I couldn't find a way to do this with if-statement if I want to make the statement inline instead of doing it separately outside of the operation. </p> <p>Is it possible to realize this without doing anything else outside of the operation:</p> <pre><code>df.assign(c = lambda x: x.num_col.sum() if x.num_col &gt; 0) </code></pre> <p>The above command returns "<strong>SyntaxError</strong>: invalid syntax"</p>
1
2016-10-10T20:05:43Z
39,966,571
<p>The syntax is invalid because you're using the ternary condition, but only the first half.</p> <p>The ternary condition allows you to write an <code>if</code> statement like this:</p> <pre><code>a = 1 if b &gt; 0 else 0 </code></pre> <p>In your case, you could write something like:</p> <pre><code>df = ( df .assign(c = lambda x: x.num_col.sum() if x.num_col &gt; 0 else 0) ) </code></pre> <p>Note the addition of the <code>else 0</code> at the end.</p>
0
2016-10-10T20:52:41Z
[ "python", "pandas", "dataframe" ]
[Pandas]The way to assign a new column based on if statement
39,965,946
<p>I know assign could help to create/change one column based on lambda function like this: </p> <pre><code>df.assign(c = lambda x: x.sum()) </code></pre> <p>But I couldn't find a way to do this with if-statement if I want to make the statement inline instead of doing it separately outside of the operation. </p> <p>Is it possible to realize this without doing anything else outside of the operation:</p> <pre><code>df.assign(c = lambda x: x.num_col.sum() if x.num_col &gt; 0) </code></pre> <p>The above command returns "<strong>SyntaxError</strong>: invalid syntax"</p>
1
2016-10-10T20:05:43Z
39,967,182
<p>IIUC you can do it this way:</p> <p><strong>Data:</strong></p> <pre><code>In [6]: df = pd.DataFrame(np.random.randn(10,2),columns=list('ab')) In [7]: df Out[7]: a b 0 0.493970 1.095644 1 0.128510 -0.542144 2 0.136247 -0.544499 3 -0.540835 -0.100574 4 0.052725 -0.164856 5 -1.201619 1.578153 6 1.921872 0.505875 7 -2.519725 0.282050 8 -1.581868 -0.240352 9 -0.071207 -1.366953 In [8]: df.ix[:6] Out[8]: a b 0 0.493970 1.095644 1 0.128510 -0.542144 2 0.136247 -0.544499 3 -0.540835 -0.100574 4 0.052725 -0.164856 5 -1.201619 1.578153 6 1.921872 0.505875 </code></pre> <p>let's find a sum of positive values in <code>a</code> column for the indexes: <code>[0:6]</code>:</p> <pre><code>In [9]: df.ix[:6].query('a &gt; 0').a.sum() Out[9]: 2.733322288547374 </code></pre> <p><strong>Solution:</strong></p> <pre><code>In [10]: df.ix[:6].assign(c=lambda x: x.query('a &gt; 0').a.sum()) Out[10]: a b c 0 0.493970 1.095644 2.733322 1 0.128510 -0.542144 2.733322 2 0.136247 -0.544499 2.733322 3 -0.540835 -0.100574 2.733322 4 0.052725 -0.164856 2.733322 5 -1.201619 1.578153 2.733322 6 1.921872 0.505875 2.733322 </code></pre> <p>the same with renamed columns:</p> <pre><code>In [11]: df.ix[:6].rename(columns={'a':'AAA', 'b':'BBB'}).assign(c=lambda x: x.query('AAA &gt; 0').AAA.sum()) Out[11]: AAA BBB c 0 0.493970 1.095644 2.733322 1 0.128510 -0.542144 2.733322 2 0.136247 -0.544499 2.733322 3 -0.540835 -0.100574 2.733322 4 0.052725 -0.164856 2.733322 5 -1.201619 1.578153 2.733322 6 1.921872 0.505875 2.733322 </code></pre>
2
2016-10-10T21:41:27Z
[ "python", "pandas", "dataframe" ]
Flask blueprint cannot read sqlite3 DATABASES from config file
39,965,970
<p>I would like Python Flask to read from configuration file the location of the sqlite3 database name <strong>without explicitly writing database name</strong>. Templates used are: <a href="http://flask.pocoo.org/docs/0.11/patterns/sqlite3/" rel="nofollow">http://flask.pocoo.org/docs/0.11/patterns/sqlite3/</a> and <a href="http://flask.pocoo.org/docs/0.11/tutorial/dbcon/" rel="nofollow">http://flask.pocoo.org/docs/0.11/tutorial/dbcon/</a>.</p> <p>When I try to read 'DATABASE' from my config file I get the following error message:</p> <p>File "/app/my_cool_app/app/<strong>init</strong>.py", line 42, in before_request g.db = connect_db()</p> <p>File "/app/my_cool_app/app/<strong>init</strong>.py", line 36, in connect_db return sqlite3.connect(my_cool_app.config['DATABASE'])</p> <p>AttributeError: 'Blueprint' object has no attribute 'config'</p> <p>Here is my <strong>init</strong>.py code when I try to read from the configuration file and get the above error:</p> <pre><code>import sqlite3 from flask import Flask, g from .views import my_cool_app # create application def create_app(debug=True): app = Flask(__name__, instance_relative_config=True) app.debug = debug app.config.from_object('config') app.config.from_pyfile('config.py') app.register_blueprint(my_cool_app) return app def connect_db(): return sqlite3.connect(my_cool_app.config['DATABASE']) &lt;= LINE 36 @my_cool_app.before_request def before_request(): g.db = connect_db() @my_cool_app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is not None: db.close() </code></pre> <p>Here is my run.py (I don't change it):</p> <pre><code>from app import create_app app = create_app() </code></pre> <p>Here is my <strong>init</strong>.py code that works when I explicitly write DB name (not what I want):</p> <pre><code>import sqlite3 from flask import Flask, g from .views import my_cool_app DATABASE='/app/myappname/my_sqlite3_database_name.db' # create application def create_app(debug=True): app = Flask(__name__, instance_relative_config=True) app.debug = debug app.config.from_object('config') app.config.from_pyfile('config.py') app.register_blueprint(my_cool_app) return app def connect_db(): return sqlite3.connect(DATABASE) </code></pre>
0
2016-10-10T20:07:45Z
39,966,366
<p>Your <code>my_cool_app</code> is an instance of <code>Blueprint</code> which doesn't have a <code>config</code> attribute. You need to use <code>current_app</code>:</p> <pre><code>import sqlite3 from flask import Flask, g, current_app from .views import my_cool_app # create application def create_app(debug=True): app = Flask(__name__, instance_relative_config=True) app.debug = debug app.config.from_object('config') app.config.from_pyfile('config.py') app.register_blueprint(my_cool_app) return app def connect_db(): return sqlite3.connect(current_app.config['DATABASE']) @my_cool_app.before_request def before_request(): g.db = connect_db() @my_cool_app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None) if db is not None: db.close() </code></pre>
1
2016-10-10T20:37:20Z
[ "python", "flask", "sqlite3", "blueprint" ]
Same attribute for 4 different classes
39,965,976
<p>I have a problem for a script in a 3D GIS software (Infraworks). I need to say to a 3D model to have the same random value for 4 different attributes, x,y and z scale and z movement. Someone knows how to do it?</p> <p>At the moment I wrote this script, but cause I'm not a proper programmer I don't know if it's the right way.</p> <p><strong>[TREES.MODEL_SCALE_X, TREES.MODEL_SCALE_Y, TREES.MODEL_SCALE_Z, TREES.MODEL_TRANSLATE_Z] = Math.random()*3+1</strong></p>
-1
2016-10-10T20:08:14Z
39,966,045
<p>Assuming I understand you correctly, you'll want to first create the value, then store the same one into all four places:</p> <pre><code>random_value = Math.random()*3+1 TREES.MODEL_SCALE_X = random_value TREES.MODEL_SCALE_Y = random_value TREES.MODEL_SCALE_Z = random_value TREES.MODEL_TRANSLATE_Z = random_value </code></pre> <p>Also, in Python it's actually the <code>random</code> module which you'd want, not "Math". So the following would actually be what you want in Python:</p> <pre><code>import random random_value = random.random()*3+1 TREES.MODEL_SCALE_X = random_value TREES.MODEL_SCALE_Y = random_value TREES.MODEL_SCALE_Z = random_value TREES.MODEL_TRANSLATE_Z = random_value </code></pre>
0
2016-10-10T20:13:13Z
[ "python", "3d", "gis", "autodesk" ]
Memory-friendly way to add a field to a structured ndarray — without duplicating data?
39,965,994
<p>To add a field to a structured numpy array, it is quite simply to create a new array with a new dtype, copy over the old fields, and add the new field. However, I need to do this for an array that takes a lot of memory, and I would rather not duplicate all of it. Both my own implementation and the (slow) implementation in <code>numpy.lib.recfunctions.append_fields</code> duplicate memory.</p> <p>Is there a way to add a field to a structured <code>ndarray</code>, without duplicating memory? That means, either a way that avoids creating a new <code>ndarray</code>, <em>or</em> a way to create a new <code>ndarray</code> that points to the same data as the old?</p> <p>Solutions that do duplicate RAM:</p> <ul> <li><p><a href="http://stackoverflow.com/questions/1201817/adding-a-field-to-a-structured-numpy-array">Adding a field to a structured numpy array</a></p></li> <li><p><a href="http://stackoverflow.com/questions/5288736/adding-a-field-to-a-structured-numpy-array-2">Adding a field to a structured numpy array (2)</a></p></li> <li><p><a href="http://stackoverflow.com/questions/21413947/adding-a-field-to-a-structured-numpy-array-3">Adding a field to a structured numpy array (3)</a></p></li> </ul> <p>There is a <a href="http://stackoverflow.com/questions/37079175/how-to-remove-a-column-from-a-structured-numpy-array-without-copying-it">similar question</a> where the challenge is to <em>remove</em>, not add, fields. The solution uses a view, which should work for a subset of the original data, but I'm not sure if it can be amended when I rather want to <em>add</em> fields.</p>
1
2016-10-10T20:09:27Z
39,966,624
<p>A structured array is stored, like a regular one, as a contiguous buffer of bytes, one record following the previous. The records are, thus, a bit like the last dimension of a multidimensional array. You can't add a column to a 2d array without making a new array via concatenation.</p> <p>Adding a field, say <code>I4</code> dtype to dtype that is, say, 20 bytes long, means changing the record (element) length to 24, i.e. adding 4 bytes to the buffer every 20th byte. <code>numpy</code> can't do that without making a new data buffer and copying values from the old (and the new).</p> <p>Actually even if we were talking about adding a new record to the array, i.e. concatenating on a new array, it would still require creating a new data buffer. Arrays are fixed sized.</p> <p>Fields in a structured array are not like objects in a list or a dictionary. You can't add a field by just adding a pointer to an object elsewhere in memory.</p> <p>Maybe you should be using a dictionary, with <code>item</code> being an array. Then you can freely add a key/item without copying the existing ones. But then access by 'rows' will be slow.</p>
2
2016-10-10T20:56:26Z
[ "python", "arrays", "numpy", "memory", "structured-array" ]
Solving second order ODE using odeint in Python
39,966,019
<p>I want to solve this equation:</p> <p>y'' + A<em>y' - B</em>y = 0</p> <p>where y, A and B are functions of the same variable "a"</p> <p>I tried the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as pyplot from scipy.integrate import odeint x0 = 0.,0.1 # initial conditions oe = 0.0 # cosmological constant density parameter om = 1. # matter density parameter h = 2.3E-18 # Hubble constant w = -1. a = np.linspace(0.1,1,10) # scale factor def H(a): # Hubble rate equation return h*np.sqrt((om/(a**3.))+(oe/(a**(3.*(1.+w))))) def A(a): # differential equation term return (-3./(2.*a)) def B(a): # differential equation term return (3.*om*(h**2.))/((2.*(a**5.))*(H(a)**2.)) def system(X,a): # differential equation system X0 = X[0] X1 = X[1] X2 = -A(a)*X1 + B(a)*X0 return X1,X2 x = odeint(system,x0,a) pyplot.semilogx(a,x, linestyle='-', c="k", linewidth="2") </code></pre> <p>It returns a plot that doesn't make sense. I should get just one plot, with the maximum value of "x" being 1 at a=1. But I get the following plot:</p> <p>Plot that I get:</p> <p><img src="http://i.stack.imgur.com/bxW08.png" alt="Plot that I get"></p> <p>And the expected result is like the continuous line of the following graph:</p> <p><img src="http://i.stack.imgur.com/4slPW.png" alt="enter image description here"></p> <p>Any suggestions? </p>
0
2016-10-10T20:10:53Z
39,967,419
<p>Please try to change sign before B(a)*X0 in the function system(X, a). It should be negative according to your initial equation.</p>
0
2016-10-10T22:01:36Z
[ "python", "ode" ]
align rows by date in pandas dataframe
39,966,021
<p>An excerpt of the Dateframe could look like this (it's certainly much larger):</p> <pre><code> Date1 Log1 Date2 Log2 Date3 Log3 Index 0 01.01.2000 1000 02.01.2000 2000 01.01.2000 3000 1 02.01.2000 1050 03.01.2000 1950 02.01.2000 3020 2 03.01.2000 1100 04.01.2000 2000 03.01.2000 3000 </code></pre> <p>Is there a quick way to align the rows so that the dates (here in Columns <code>Date3</code> and <code>Log3</code>) match with those in column <code>Date1</code>?</p> <pre><code> Date1 Log1 Date2 Log2 Date3 Log3 Index 0 01.01.2000 1000 NaN 01.01.2000 3000 1 02.01.2000 1050 02.01.2000 2000 02.01.2000 3020 2 03.01.2000 1100 03.01.2000 1950 03.01.2000 3000 </code></pre> <p>Many thanks in advance</p>
1
2016-10-10T20:11:05Z
39,966,889
<p>I am assuming you only want to keep values from ['Date2', 'Log2'] and ['Date3', 'Log3'] when the dates have a match in Date1.</p> <p>You can read the different columns into separate dataframes and use <code>merge</code>. Then filter to only keep rows where the Date1 column is not null.</p> <pre><code>df &gt;&gt;&gt; Date1 Log1 Date2 Log2 Date3 Log3 0 01.01.2000 1000 02.01.2000 2000 01.01.2000 3000 1 02.01.2000 1050 03.01.2000 1950 02.01.2000 3020 2 03.01.2000 1100 04.01.2000 2000 03.01.2000 3000 df1 = df[['Date1', 'Log1']] df2 = df[['Date2', 'Log2']] df3 = df[['Date3', 'Log3']] df_out = df1.merge(df2, how='outer', left_on='Date1', right_on='Date2') df_out = df_out.merge(df3, how='outer', left_on='Date1', right_on='Date3') df_out = df_out[df_out['Date1'].notnull()] df_out &gt;&gt;&gt; Date1 Log1 Date2 Log2 Date3 Log3 0 01.01.2000 1000.0 NaN NaN 01.01.2000 3000.0 1 02.01.2000 1050.0 02.01.2000 2000.0 02.01.2000 3020.0 2 03.01.2000 1100.0 03.01.2000 1950.0 03.01.2000 3000.0 </code></pre>
1
2016-10-10T21:17:59Z
[ "python", "pandas", "dataframe" ]
align rows by date in pandas dataframe
39,966,021
<p>An excerpt of the Dateframe could look like this (it's certainly much larger):</p> <pre><code> Date1 Log1 Date2 Log2 Date3 Log3 Index 0 01.01.2000 1000 02.01.2000 2000 01.01.2000 3000 1 02.01.2000 1050 03.01.2000 1950 02.01.2000 3020 2 03.01.2000 1100 04.01.2000 2000 03.01.2000 3000 </code></pre> <p>Is there a quick way to align the rows so that the dates (here in Columns <code>Date3</code> and <code>Log3</code>) match with those in column <code>Date1</code>?</p> <pre><code> Date1 Log1 Date2 Log2 Date3 Log3 Index 0 01.01.2000 1000 NaN 01.01.2000 3000 1 02.01.2000 1050 02.01.2000 2000 02.01.2000 3020 2 03.01.2000 1100 03.01.2000 1950 03.01.2000 3000 </code></pre> <p>Many thanks in advance</p>
1
2016-10-10T20:11:05Z
39,966,891
<p>A dictionary to represent your data, this is just a convenience to load the sample data to dataframe.</p> <pre><code>d = {'Date1': {0: '01.01.2000', 1: '02.01.2000', 2: '03.01.2000'}, 'Date3': {0: '01.01.2000', 1: '02.01.2000', 2: '03.01.2000'}, 'Date2': {0: '02.01.2000', 1: '03.01.2000', 2: '04.01.2000'}, 'Log2': {0: 2000, 1: 1950, 2: 2000}, 'Log3': {0: 3000, 1: 3020, 2: 3000}, 'Log1': {0: 1000, 1: 1050, 2: 1100}} df = pd.DataFrame(d) df = df[['Date1','Log1','Date2','Log2','Date3','Log3']] df.index.names = ['Index'] print df </code></pre> <p><strong>Starting Dataframe:</strong></p> <pre><code> Date1 Log1 Date2 Log2 Date3 Log3 Index 0 01.01.2000 1000 02.01.2000 2000 01.01.2000 3000 1 02.01.2000 1050 03.01.2000 1950 02.01.2000 3020 2 03.01.2000 1100 04.01.2000 2000 03.01.2000 3000 </code></pre> <p>This is crude but does the job:</p> <pre><code>list_dfs = [] for i in range(1,4): column_subset = [col for col in df.columns if str(i) in col] df_subset_columns = df[column_subset] df_subset_columns.columns = ['Date','Log'] df_subset_columns['id'] = i list_dfs.append(df_subset_columns) df = pd.concat(list_dfs,axis=0,ignore_index=True) df = df.set_index(['Date','id']) df = df.unstack('id') df.columns = df.columns.droplevel(0) </code></pre> <p>At this point I think this is what you are looking logically:</p> <pre><code>id 1 2 3 Date 01.01.2000 1,000 nan 3,000 02.01.2000 1,050 2,000 3,020 03.01.2000 1,100 1,950 3,000 04.01.2000 nan 2,000 nan </code></pre> <p>But to revert back to the desired output</p> <pre><code>list_dfs = [] for i in range(1,4): df_s = df[i].to_frame() df_s.columns = ['Log' + str(i)] print df_s list_dfs.append(df_s.reset_index()) print pd.concat(list_dfs,axis=1) </code></pre>
1
2016-10-10T21:18:19Z
[ "python", "pandas", "dataframe" ]
align rows by date in pandas dataframe
39,966,021
<p>An excerpt of the Dateframe could look like this (it's certainly much larger):</p> <pre><code> Date1 Log1 Date2 Log2 Date3 Log3 Index 0 01.01.2000 1000 02.01.2000 2000 01.01.2000 3000 1 02.01.2000 1050 03.01.2000 1950 02.01.2000 3020 2 03.01.2000 1100 04.01.2000 2000 03.01.2000 3000 </code></pre> <p>Is there a quick way to align the rows so that the dates (here in Columns <code>Date3</code> and <code>Log3</code>) match with those in column <code>Date1</code>?</p> <pre><code> Date1 Log1 Date2 Log2 Date3 Log3 Index 0 01.01.2000 1000 NaN 01.01.2000 3000 1 02.01.2000 1050 02.01.2000 2000 02.01.2000 3020 2 03.01.2000 1100 03.01.2000 1950 03.01.2000 3000 </code></pre> <p>Many thanks in advance</p>
1
2016-10-10T20:11:05Z
39,967,371
<p>Solution with <code>list comprehension</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>, last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> all data together:</p> <pre><code>dates = [col for col in df.columns if 'Date' in col] logs = [col for col in df.columns if 'Log' in col] print ([df[[col[0], col[1]]].set_index(col[0], drop=False) .reindex(df.Date1) for col in zip(dates, logs)]) [ Date1 Log1 Date1 01.01.2000 01.01.2000 1000 02.01.2000 02.01.2000 1050 03.01.2000 03.01.2000 1100, Date2 Log2 Date1 01.01.2000 NaN NaN 02.01.2000 02.01.2000 2000.0 03.01.2000 03.01.2000 1950.0, Date3 Log3 Date1 01.01.2000 01.01.2000 3000 02.01.2000 02.01.2000 3020 03.01.2000 03.01.2000 3000] df1 = pd.concat([df[[col[0], col[1]]] .set_index(col[0], drop=False) .reindex(df.Date1) for col in zip(dates, logs)], axis=1) df1.reset_index(inplace=True, drop=True) print (df1) Date1 Log1 Date2 Log2 Date3 Log3 0 01.01.2000 1000 NaN NaN 01.01.2000 3000 1 02.01.2000 1050 02.01.2000 2000.0 02.01.2000 3020 2 03.01.2000 1100 03.01.2000 1950.0 03.01.2000 3000 </code></pre>
1
2016-10-10T21:56:59Z
[ "python", "pandas", "dataframe" ]
How to introduce parameters in a cypher query?
39,966,055
<p>I have this cypher query in a Python program:</p> <pre><code>prevNode = graph_db.data("OPTIONAL MATCH (n:Node) WHERE n.property = {param} RETURN n") </code></pre> <p>The line of code above gives the next error: 'py2neo.database.status.ClientError: Expected a parameter named param'</p> <p>param is well defined at this point of the program because I print it a line before executing the query.</p> <p>I have tried to put the value in the query instead of the parameter, like this:</p> <pre><code>prevNode = graph_db.data("OPTIONAL MATCH (n:Node) WHERE n.property = '1234' RETURN n") </code></pre> <p>And worked well.</p> <p>Does anyone knows where is the mistake? Thanks in advanced. </p>
0
2016-10-10T20:13:34Z
39,966,144
<p>You didn't pass any substitution variables into the function.</p> <pre><code>graph_db.data("OPTIONAL MATCH (n:Node) WHERE n.property = {param} RETURN n", param='1234') </code></pre> <p>You can also explicitly pass in the <code>locals()</code> dictionary; this will use any local variables you have defined of the appropriate names:</p> <pre><code>graph_db.data("OPTIONAL MATCH (n:Node) WHERE n.property = {param} RETURN n", **locals()) </code></pre>
2
2016-10-10T20:22:13Z
[ "python", "neo4j", "cypher", "py2neo" ]
How to directly set the gradient of a layer before backpropagation?
39,966,149
<p>Imagine a tiny network defined as follows, where linear is a typical helper function defining TensorFlow variables for a weight matrix and activation function:</p> <p><code>final_layer = linear(linear(_input,10,tf.nn.tanh),20)</code></p> <p>Normally this would be optimized via gradient descent on a loss:</p> <p><code>loss = tf.reduce_sum(tf.square(final_layer - _target)) train_step = tf.train.AdamOptimizer().minimmize(loss)</code></p> <p>But assume I'm getting the derivatives of the loss w.r.t. final_layer from an external source (e.g. a tf.placeholder named _deriv). How can I use this gradient information with one of the builtin optimizers to backpropagate and update the network parameters?</p> <p>The workaround I'm currently using is to construct an artificial loss consisting of the inner product between _deriv and final_layer (since the derivatives of this loss w.r.t. final_layer will be equal to _deriv). </p> <p><code>loss = tf.reduce_sum(final_layer*_deriv) train_step = tf.train.AdamOptimizer().minimmize(loss)</code></p> <p>This is very wasteful though, as it needs to do this unnecessary inner product and calculate its derivative for every training step even though I already know this information. Is there a better way?</p> <p>For those thinking this an odd thing to need to do, it is necessary for implementing <a href="https://arxiv.org/abs/1608.05343" rel="nofollow">synthetic gradients</a>.</p>
3
2016-10-10T20:22:41Z
39,974,148
<p><code>tf.gradients</code> provides this functionality via its <code>grad_ys</code> argument, see <a href="https://www.tensorflow.org/versions/r0.11/api_docs/python/train.html#gradients" rel="nofollow">here</a>. In your case, <code>tf.gradients([final_layer], list_of_variables, grad_ys=[_deriv])</code> would compute the gradients you want.</p> <p>Unfortunately, it looks like the build-in optimizers don't pass a <code>grad_ys</code> argument to <code>tf.gradients</code>. You might have to hack something into the <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/optimizer.py#L200" rel="nofollow">compute_gradients</a> method of the optimizer class.</p>
1
2016-10-11T09:24:21Z
[ "python", "tensorflow", "backpropagation", "gradient-descent" ]
How to zip a list of lists in python?
39,966,187
<p>I have a list of lists</p> <pre><code>sample = [['A','T','N','N'],['T', 'C', 'C', 'C']],[['A','T','T','N'],['T', 'T', 'C', 'C']]. </code></pre> <p>I am trying to zip the file such that only A/T/G/C are in lists and the output needs to be a list</p> <pre><code>[['AT','TCCC'],['ATT','TTCC']] </code></pre> <p>When I use this code:</p> <pre><code>tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in sample] </code></pre> <p>However, I only get the output as:</p> <pre><code>['ATT','TTCC'] </code></pre> <p>Any suggestions where I am going wrong?</p> <p>In my actual code I am first transposing the lists:</p> <pre><code>seq_list = [['TCCGGGGGTATC', 'TCCGTGGGTATC', ...]] # one nested list numofpops = len(seq_list) ### Tranposing. Moving along the columns only #column_list = [] for k in range(len(seq_list)): column_list = [[] for i in range(len(seq_list[k][0]))] for seq in seq_list[k]: for i, nuc in enumerate(seq): column_list[i].append(nuc) ddd = column_list print ddd tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in ddd] print tt </code></pre>
-2
2016-10-10T20:25:06Z
39,966,316
<p>I assume the input you've given are two items in one list. Then, you would use a <em>list comprehension</em> with 2 levels of nesting. At the deepest level, you filter out items that are not <code>A, T, G</code> or <code>C</code> and then <code>join</code> the others:</p> <pre><code>sample = [[['A','T','N','N'],['T', 'C', 'C', 'C']], [['A','T','T','N'],['T', 'T', 'C', 'C']]] result = [[''.join(i for i in lst if i in 'ATGC') for lst in sub] for sub in sample] # ^&lt;- filter items # ^&lt;- join the matching items print(result) # [['AT', 'TCCC'], ['ATT', 'TTCC']] </code></pre>
0
2016-10-10T20:32:56Z
[ "python", "list" ]
How to zip a list of lists in python?
39,966,187
<p>I have a list of lists</p> <pre><code>sample = [['A','T','N','N'],['T', 'C', 'C', 'C']],[['A','T','T','N'],['T', 'T', 'C', 'C']]. </code></pre> <p>I am trying to zip the file such that only A/T/G/C are in lists and the output needs to be a list</p> <pre><code>[['AT','TCCC'],['ATT','TTCC']] </code></pre> <p>When I use this code:</p> <pre><code>tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in sample] </code></pre> <p>However, I only get the output as:</p> <pre><code>['ATT','TTCC'] </code></pre> <p>Any suggestions where I am going wrong?</p> <p>In my actual code I am first transposing the lists:</p> <pre><code>seq_list = [['TCCGGGGGTATC', 'TCCGTGGGTATC', ...]] # one nested list numofpops = len(seq_list) ### Tranposing. Moving along the columns only #column_list = [] for k in range(len(seq_list)): column_list = [[] for i in range(len(seq_list[k][0]))] for seq in seq_list[k]: for i, nuc in enumerate(seq): column_list[i].append(nuc) ddd = column_list print ddd tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in ddd] print tt </code></pre>
-2
2016-10-10T20:25:06Z
39,966,362
<p>You want to do the following:</p> <pre><code>sample = [[['A','T','N','N'],['T', 'C', 'C', 'C']], [['A','T','T','N'],['T', 'T', 'C', 'C']]] </code></pre> <p>And then:</p> <pre><code>tt = [[''.join([c for c in sublist if c in 'AGTC']) for sublist in doublet] for doublet in sample] </code></pre> <p>Perhaps more readable this way:</p> <pre><code>tt = [ [''.join([c for c in sublist if c in 'AGTC']) for sublist in doublet] for doublet in sample ] </code></pre> <p>It gives the desired result:</p> <pre><code>[['AT', 'TCCC'], ['ATT', 'TTCC']] </code></pre>
1
2016-10-10T20:36:45Z
[ "python", "list" ]
How to zip a list of lists in python?
39,966,187
<p>I have a list of lists</p> <pre><code>sample = [['A','T','N','N'],['T', 'C', 'C', 'C']],[['A','T','T','N'],['T', 'T', 'C', 'C']]. </code></pre> <p>I am trying to zip the file such that only A/T/G/C are in lists and the output needs to be a list</p> <pre><code>[['AT','TCCC'],['ATT','TTCC']] </code></pre> <p>When I use this code:</p> <pre><code>tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in sample] </code></pre> <p>However, I only get the output as:</p> <pre><code>['ATT','TTCC'] </code></pre> <p>Any suggestions where I am going wrong?</p> <p>In my actual code I am first transposing the lists:</p> <pre><code>seq_list = [['TCCGGGGGTATC', 'TCCGTGGGTATC', ...]] # one nested list numofpops = len(seq_list) ### Tranposing. Moving along the columns only #column_list = [] for k in range(len(seq_list)): column_list = [[] for i in range(len(seq_list[k][0]))] for seq in seq_list[k]: for i, nuc in enumerate(seq): column_list[i].append(nuc) ddd = column_list print ddd tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in ddd] print tt </code></pre>
-2
2016-10-10T20:25:06Z
39,966,371
<p>You can first create a helper function:</p> <pre><code>def filterJoin(s): return ''.join(x for x in s if x in 'ATGC') </code></pre> <p>Then:</p> <pre><code>&gt;&gt;&gt; sample = [['A','T','N','N'],['T', 'C', 'C', 'C']],[['A','T','T','N'],['T', 'T', 'C', 'C']] &gt;&gt;&gt; [[filterJoin(s) for s in t] for t in sample] [['AT', 'TCCC'], ['ATT', 'TTCC']] </code></pre>
1
2016-10-10T20:37:34Z
[ "python", "list" ]
How to zip a list of lists in python?
39,966,187
<p>I have a list of lists</p> <pre><code>sample = [['A','T','N','N'],['T', 'C', 'C', 'C']],[['A','T','T','N'],['T', 'T', 'C', 'C']]. </code></pre> <p>I am trying to zip the file such that only A/T/G/C are in lists and the output needs to be a list</p> <pre><code>[['AT','TCCC'],['ATT','TTCC']] </code></pre> <p>When I use this code:</p> <pre><code>tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in sample] </code></pre> <p>However, I only get the output as:</p> <pre><code>['ATT','TTCC'] </code></pre> <p>Any suggestions where I am going wrong?</p> <p>In my actual code I am first transposing the lists:</p> <pre><code>seq_list = [['TCCGGGGGTATC', 'TCCGTGGGTATC', ...]] # one nested list numofpops = len(seq_list) ### Tranposing. Moving along the columns only #column_list = [] for k in range(len(seq_list)): column_list = [[] for i in range(len(seq_list[k][0]))] for seq in seq_list[k]: for i, nuc in enumerate(seq): column_list[i].append(nuc) ddd = column_list print ddd tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in ddd] print tt </code></pre>
-2
2016-10-10T20:25:06Z
39,966,400
<p>Your actual code is <em>discarding lists</em>. You only ever process the <em>last entry</em>.</p> <p>Your code works fine otherwise. Just do that <em>in the loop</em> and then append the result to some final list:</p> <pre><code>results = [] for k in range(len(seq_list)): column_list = [[] for i in range(len(seq_list[k][0]))] for seq in seq_list[k]: for i, nuc in enumerate(seq): column_list[i].append(nuc) # process `column_list` here, in the loop (no need to assign to ddd) tt = ["".join(y for y in x if y in {'A','G','T','C'}) for x in column_list] results.append(tt) </code></pre> <p>Note that you could use the <code>zip()</code> function instead of your transposition list:</p> <pre><code>results = [] for sequence in seq_list: for column_list in zip(*sequence): tt = [''.join([y for y in x if y in 'AGTC']) for x in column_list] results.append(tt) </code></pre>
3
2016-10-10T20:39:18Z
[ "python", "list" ]
TypeError: __init__() takes exactly 8 arguments (7 given) Python Homework
39,966,231
<p>I can't figure out why I am getting the TypeError. Below is a class and two sub-classes. The first two work fine. The Final sub-class(OperatingSys) is where I am finding difficulty. I have put my Error input at the very bottom. Thanks in advance! </p> <pre><code>class InventoryItem(object): def __init__(self, title, description, price, store_id): self.title = title self.description = description self.price = price self.store_id = store_id def __str__(self): return self.title def __eq__(self, other): if self.store_id == other.title: return True else: return False def change_description(self, description=""): if not description: description = raw_input("Please give me a description:") self.description = description def change_price(self, price = -1): while price &lt; 0: price = raw_input("Please give me the new price [X.XX]: ") try: price = float(price) break except: print "I'm sorry but {} isn't valid.".format(price) self.price = price def change_title(self, title=""): if not title: title = raw_input("Please give me a new title: ") self.title = title class Book(InventoryItem): def __init__(self, title, description, price, format, author, store_id): super(Book, self).__init__(title=title, description = description, price = price, store_id=store_id) self.format = format self.author = author def __str__(self): book_line = "{title} by {author}".format(title = self.title, author = self.author) return book_line def __eq__(self, other): if self.title == other.title and self.author == other.author: return True else: return False def change_format(self, format): if not format: format = raw_input("Please give me the new format: ") self.format = format def change_author(self, author): if not author: author = raw_input("Please give me the enw author: ") class OperatingSys(InventoryItem): def __init__(self, InventoryItem, title, price, description, opsys, rating, store_id): super(OperatingSys, self).__init__(title=title, price=price, description=description, store_id=store_id) self.opsys = opsys self.rating = rating def __str__(self): opsys_line = "{title} for {OpSys}, price is {price}".format(title = self.title, OpSys=self.OpSys, price = self.price) return opsys_line def __eq__(self, other): if self.title == other.title and self.author == other.author: return True else: return False def change_opsys(self, opsys): if not opsys: opsys = raw_input("Please give me a new Operating System: ") self.opsys = opsys def change_rating(self, rating): if not rating: rating = raw_input("Plese assign the appropriate rating: ") self.rating = rating TheDivision = OperatingSys(title="The Division",description="third person shooter", price=69.99, opsys="", rating="", store_id=3908657) </code></pre> <hr> <pre><code>Traceback (most recent call last): File "&lt;pyshell#128&gt;", line 1, in &lt;module&gt; TheDivision = OperatingSys(title="The Division",description="third person shooter", price=69.99, opsys="", rating="", store_id=3908657) TypeError: __init__() takes exactly 8 arguments (7 given) </code></pre>
-3
2016-10-10T20:28:01Z
39,966,298
<p>When you try and create <code>OperatingSys</code> you are passing in 6 parameters — which together with <code>self</code> make 7:</p> <pre><code>OperatingSys( title="The Division", # 1 description="third person shooter", # 2 price=69.99, # 3 opsys="", # 4 rating="", # 5 store_id=3908657 # 6 ) </code></pre> <p>But your definition requires 7 (8 including <code>self</code>):</p> <pre><code>def __init__(self, InventoryItem, title, price, description, opsys, rating, store_id): </code></pre> <p>I suspect that the <code>InventoryItem</code> there is a mistake — you don't need to include the parent class as a parameter in the init definition.</p> <pre><code>def __init__(self, title, price, description, opsys, rating, store_id): </code></pre>
0
2016-10-10T20:32:08Z
[ "python", "typeerror" ]
How do you use multiple arguments in {} when using the .format() method in Python
39,966,239
<p>I want a table in python to print like this: </p> <p><img src="https://i.imgur.com/ymGkIdQ.png" alt=""></p> <p>Clearly, I want to use the .format() method, but I have long floats that look like this: <code>1464.1000000000001</code> I need the floats to be rounded, so that they look like this: <code>1464.10</code> (always two decimal places, even if both are zeros, so I can't use the round() function).</p> <p>I can round the floats using <code>"{0:.2f}".format("1464.1000000000001")</code>, but then they do not print into nice tables. </p> <p>I can put them into nice tables by doing <code>"{0:&gt;15}.format("1464.1000000000001")</code>, but then they are not rounded.</p> <p>Is there a way to do both? Something like <code>"{0:&gt;15,.2f}.format("1464.1000000000001")</code>?</p>
3
2016-10-10T20:28:23Z
39,966,269
<p>You were almost there, just remove the comma (and pass in a float number, not a string):</p> <pre><code>"{0:&gt;15.2f}".format(1464.1000000000001) </code></pre> <p>See the <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow"><em>Format Specification Mini-Language</em> section</a>:</p> <blockquote> <pre><code>format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type] fill ::= &lt;any character&gt; align ::= "&lt;" | "&gt;" | "=" | "^" sign ::= "+" | "-" | " " width ::= integer precision ::= integer type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" </code></pre> </blockquote> <p>Breaking the above format down then:</p> <pre><code>fill: &lt;empty&gt; align: &lt; # left sign: &lt;not specified&gt; width: 15 precision: 2 type: `f` </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; "{0:&gt;15.2f}".format(1464.1000000000001) ' 1464.10' </code></pre> <p>Note that for numbers, the default alignment is to the right, so the <code>&gt;</code> could be omitted.</p>
5
2016-10-10T20:30:37Z
[ "python", "python-3.x", "rounding", "string-formatting", "string.format" ]
How do you use multiple arguments in {} when using the .format() method in Python
39,966,239
<p>I want a table in python to print like this: </p> <p><img src="https://i.imgur.com/ymGkIdQ.png" alt=""></p> <p>Clearly, I want to use the .format() method, but I have long floats that look like this: <code>1464.1000000000001</code> I need the floats to be rounded, so that they look like this: <code>1464.10</code> (always two decimal places, even if both are zeros, so I can't use the round() function).</p> <p>I can round the floats using <code>"{0:.2f}".format("1464.1000000000001")</code>, but then they do not print into nice tables. </p> <p>I can put them into nice tables by doing <code>"{0:&gt;15}.format("1464.1000000000001")</code>, but then they are not rounded.</p> <p>Is there a way to do both? Something like <code>"{0:&gt;15,.2f}.format("1464.1000000000001")</code>?</p>
3
2016-10-10T20:28:23Z
39,966,275
<pre><code>"{0:15.2f}".format(1464.1000000000001) </code></pre> <p>I always find this site useful for this stuff:</p> <p><a href="https://pyformat.info/" rel="nofollow">https://pyformat.info/</a></p>
3
2016-10-10T20:31:01Z
[ "python", "python-3.x", "rounding", "string-formatting", "string.format" ]
PyQt: Window is closed but process still running
39,966,309
<p>Just a simple problem (not for me): when I close the window, the program is still running. Here is the code:</p> <pre><code>from PyQt4 import QtCore, QtGui from PyQt4.Qt import QString import sys import sensors from sensors import * import threading class MainWindow(QtGui.QWidget): signalUpdate = QtCore.pyqtSignal() # 1 - define a new signal in mainwindow class # 2 -connect this signal to the update() function #emit signal #main window def __init__(self): #vars for core temp and name self.tempValue = 0 self.name = '0' super(MainWindow, self).__init__() self.setGeometry(50, 50, 250, 150) self.setWindowTitle("Title here") self.setFixedSize(250, 150) self.home() #make widgets (progressBar and labe) def home(self): self.prgB = QtGui.QProgressBar(self) self.prgB.setGeometry(20, 20, 210, 20) #self.prgB.setOrientation(QtCore.Qt.Vertical) QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("motif"))#stles -&gt; motif, Plastique, Windows self.lbl = QtGui.QLabel(self) self.lbl.setGeometry(60, 40, 210, 20) self.signalUpdate.connect(self.update) #connect this signal to the update() function lay = QtGui.QVBoxLayout() lay.addWidget(self.prgB) lay.addWidget(self.lbl) self.setLayout(lay) self.tmp() self.show() #update() to update label and progressbar values def update(self): textas = ('%s : %.1f' % (self.name, self.tempValue)) self.lbl.setText(str(textas + ' C')) self.prgB.setFormat(QString.number(self.tempValue)+ ' C') self.prgB.setValue(self.tempValue) #temp() to get chip data from sensors (temp, name etc) def tmp(self): sensors.init() try: for chip in sensors.iter_detected_chips(): #print (chip) #print('Adapter:', chip.adapter_name) for feature in chip: if feature.label == 'Physical id 0': self.tempValue = feature.get_value() self.name = feature.label #print ('%s (%r): %.1f' % (feature.name, feature.label, feature.get_value())) threading.Timer(2.0, self.tmp).start() self.signalUpdate.emit() #emit signal #print finally: sensors.cleanup() def run(): QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtGui.QApplication(sys.argv) GUI = MainWindow() sys.exit(app.exec_()) run() </code></pre> <p>Why is that happening, and how to fix it? (I was trying to research on google and yes there are many forums with same question but I get no luck so far to fix it).</p> <p>EDIT: problem is still not fixed, can someone show/tell how to stop threading.Time on program exit? Please :)</p>
0
2016-10-10T20:32:35Z
39,968,421
<p>Call the timer's cancel() method in your widget's (overridden) closeEvent() method:</p> <pre><code>def tmp(self): ... self.timer = threading.Timer(2.0, self.tmp) self.timer.start() self.signalUpdate.emit() #emit signal def closeEvent(self): self.timer.cancel() </code></pre> <p>I've tested that this works: </p> <ul> <li>without the threading, app exits; </li> <li>with the threading.Timer, but without the timer cancel, app never exits; </li> <li>with the timer cancel, app exits</li> </ul>
1
2016-10-10T23:45:08Z
[ "python", "python-2.7", "pyqt" ]
Drawing box around message
39,966,393
<p>I'm working on this Python task that I can't figure out. It is the last of 3 functions and the first 2 were much easier to program then this one. The instructions are "Given a message that may contain multiple lines, utilize the split() function to identify the individual lines, and the format() function so that when printed, it draws a box around the message's lines, all centered. Box uses vertical bars &amp; dashes on the sides (|, -), +'s in the corners (+), and there is always a column of spaces to the left and right of the widest line of the message." </p> <p>Some examples for what this function needs to do: </p> <p>test that: border_msg('a') == '+---+\n| a |\n+---+\n'</p> <p>test that: border_msg('hello') == '+-------+\n| hello |\n+-------+\n'</p> <p>test that: border_msg("hi!\nhow are you?\ndrive safely!") == '+---------------+\n| hi! |\n| how are you? |\n| drive safely! |\n+---------------+\n'</p> <p>I think it needs to print the above tests so that the words in the middle are surrounded by the "+------+ on the top and bottom and "|"'s on the sides.</p> <p>Here is the code I have so far. I'm not sure where I would go from here.</p> <pre><code>def border_msg(msg): border_msg.split("\n") '%s'.format(msg) return border_msg(msg) print border_msg(msg) </code></pre>
-3
2016-10-10T20:39:02Z
39,966,497
<p>Find out the length of your longest line N; <code>(N+2) * '-'</code> gives you the top and bottom borders. Before each line add a bar: '|'; pad each line with <code>N - n</code> spaces, where n is the length of that line. Append to each line a bar. Print in the correct order: top, line 1, line2, ..., line L, bottom.</p>
-1
2016-10-10T20:47:40Z
[ "python", "drawing", "message", "rectangles" ]
Drawing box around message
39,966,393
<p>I'm working on this Python task that I can't figure out. It is the last of 3 functions and the first 2 were much easier to program then this one. The instructions are "Given a message that may contain multiple lines, utilize the split() function to identify the individual lines, and the format() function so that when printed, it draws a box around the message's lines, all centered. Box uses vertical bars &amp; dashes on the sides (|, -), +'s in the corners (+), and there is always a column of spaces to the left and right of the widest line of the message." </p> <p>Some examples for what this function needs to do: </p> <p>test that: border_msg('a') == '+---+\n| a |\n+---+\n'</p> <p>test that: border_msg('hello') == '+-------+\n| hello |\n+-------+\n'</p> <p>test that: border_msg("hi!\nhow are you?\ndrive safely!") == '+---------------+\n| hi! |\n| how are you? |\n| drive safely! |\n+---------------+\n'</p> <p>I think it needs to print the above tests so that the words in the middle are surrounded by the "+------+ on the top and bottom and "|"'s on the sides.</p> <p>Here is the code I have so far. I'm not sure where I would go from here.</p> <pre><code>def border_msg(msg): border_msg.split("\n") '%s'.format(msg) return border_msg(msg) print border_msg(msg) </code></pre>
-3
2016-10-10T20:39:02Z
39,966,926
<p>I've stitched up a little piece of code which implements the boxed messages. To be honest it's not the nicest piece of code, but it does the job and hopefully will help you to do it yourself (and better). For that purpose I've decided not to include comment, so you have to think that through for yourself. Maybe not the best educational method, but let's try it anyway:]</p> <p>Code on <a href="https://github.com/quapka/expecto-anything/blob/master/boxed_msg.py" rel="nofollow"><code>Github</code></a>.</p> <pre><code>from math import ceil, floor def boxed_msg(msg): lines = msg.split('\n') max_length = max([len(line) for line in lines]) horizontal = '+' + '-' * (max_length + 2) + '+\n' res = horizontal for l in lines: res += format_line(l, max_length) res += horizontal return res.strip() def format_line(line, max_length): half_dif = (max_length - len(line)) / 2 # in Python 3.x float division return '| ' + ' ' * ceil(half_dif) + line + ' ' * floor(half_dif) + ' |\n' print(boxed_msg('first_line\nsecond_line\nthe_ultimate_longest_line')) # +---------------------------+ # | first_line | # | second_line | # | the_ultimate_longest_line | # +---------------------------+ </code></pre>
-1
2016-10-10T21:21:36Z
[ "python", "drawing", "message", "rectangles" ]
Plotting timestamps in Python
39,966,417
<p>I am new to Python and am trying to create a simple line graph with time on the x axis and values on the y. I have a CSV file from which to import the data.</p> <p>A sample of the data looks like this</p> <p><a href="http://i.stack.imgur.com/GIygc.png" rel="nofollow"><img src="http://i.stack.imgur.com/GIygc.png" alt="Data Extract"></a></p> <p>I have tried to use the following code:</p> <pre><code> import pandas as pd import numpy as np import matplotlib.pyplot as plt a_data = pd.read_csv("Data Sampler.csv") plt.plot(a_data.Timestamp, a_data.a) </code></pre> <p>However, I am receiving an error message: AttributeError: 'Series' object has no attribute 'find'</p> <p>a_data.dtypes tells me that Timestamp is an object and A is float 64.</p> <p>Can anyone help? From googling a solution, it looks like I need to convert the timestamp to a datetime within Python - however I am not having much luck with this (lots of error messages).</p> <p>Thanks in advance.</p>
0
2016-10-10T20:41:31Z
39,966,990
<p>If you're using <code>matplotlib.__version__ &gt;= 1.5.0</code>, then the following should work:</p> <pre><code>In [4]: df Out[4]: Timestamp A 0 03/10/2016 16:00 0.033361 1 04/10/2016 16:01 0.123108 2 05/10/2016 16:02 0.021805 In [5]: df.index = pd.to_datetime(df.Timestamp, dayfirst=True) In [6]: df Out[6]: Timestamp A Timestamp 2016-10-03 16:00:00 03/10/2016 16:00 0.033361 2016-10-04 16:01:00 04/10/2016 16:01 0.123108 2016-10-05 16:02:00 05/10/2016 16:02 0.021805 In [7]: plt.plot('A', data=df) Out[7]: [&lt;matplotlib.lines.Line2D at 0x7f8e3c0e8150&gt;] In [7]: plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/kkRLe.png" rel="nofollow"><img src="http://i.stack.imgur.com/kkRLe.png" alt="enter image description here"></a></p> <p>Depending on the scale of your data, you can adjust the tick formatting of the x-axis using the appropriate tick formatters, see <a href="http://matplotlib.org/examples/pylab_examples/date_demo2.html" rel="nofollow">here</a> for an example.</p>
1
2016-10-10T21:26:25Z
[ "python", "datetime", "matplotlib", "timestamp" ]
Django Admin Panel
39,966,433
<p>I am trying to set up a new blog. I want to keep all my project templates folder in the same folder as where my settings.py is. To do this I did the following... [...]</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates/")], 'APP_DIRS': False, 'OPTIONS': { 'context_processors': [ </code></pre> <p>[...]</p> <p>But now, my admin panel layout doesn't work. How can I circumvent the above solution when using the admin panel? I get the error </p> <p><code>Exception Type: TemplateDoesNotExist Exception Value: admin/login.html</code></p>
0
2016-10-10T20:42:32Z
39,966,733
<p>By disabling APP_DIRS you're forcing Django to look for your templates in the templates folder of your basedir regardless of where the app specifies them. This will break any plugins and also prevents you from namespacing templates. Its generally a bad idea. </p> <p>DIRS is a list, so you can specify multiple locations if desperately want to hold the templates in a different locationand maintain access to teh admin</p>
0
2016-10-10T21:04:29Z
[ "python", "django" ]
Flask API blocking OPTIONS requests
39,966,446
<p>I have an API written in Flask, when I am trying to use this API from AngularJS I am getting an 401 error unauthorized, same request with same credentials is working fine from Postman or HTTPie. This is happening with GET or POST request.</p> <p>I noticed that the difference between HTTPie and Angular request is that Angular is calling OPTIONS before a GET request.</p> <p>This is my python code where authentication is required(api is a blueprint):</p> <pre><code>@api.before_request @rate_limit(limit=5, period=15) @auth_token.login_required def before_request(): """All routes in this blueprint require authentication.""" pass </code></pre> <p>The only method that is working from my api is one that is outside of this blueprint, my conclusion is that the @api.before_request and @auth_token.login_required are expecting credentials to be sent for the OPTIONS request, any idea what can I do?</p> <p>Thank you very much</p>
0
2016-10-10T20:43:25Z
39,969,521
<p>I figure out the problem, I solved after updating the plugin Flask-HTTPAuth.</p> <p>I was having the version 2.2.1 and after moving to 3.2.1 it solved.</p> <p>Tried the same on an instance of Amazon EC2 and solved with the same solution so I am quite sure it was this.</p>
0
2016-10-11T02:16:37Z
[ "python", "angularjs", "flask", "restful-architecture" ]
Pandas: Generating hourly data from daily data from csv
39,966,456
<p>I have a CSV file which has daily data as follows:</p> <pre><code>DateTime Price 10/3/2016 0:00 2.84 9/30/2016 0:00 2.84 9/29/2016 0:00 2.98 9/28/2016 0:00 3.07 </code></pre> <p>I wanted to create 24 hour price series for each day above and the hourly prices will be same as the daily price I read from the csv file.</p> <p>I am doing the following:</p> <pre><code>import pandas as pd price4mCSV = pd.read_csv(r'C:\Price.csv', index_col='DateTime', parse_dates=['DateTime']).asfreq('1H', method='ffill') </code></pre> <p>However, <code>price4mCSV</code> is blank.</p>
0
2016-10-10T20:44:00Z
39,966,507
<p>try this:</p> <pre><code>In [125]: df.set_index('DateTime').resample('H').pad() Out[125]: Price DateTime 2016-09-28 00:00:00 3.07 2016-09-28 01:00:00 3.07 2016-09-28 02:00:00 3.07 2016-09-28 03:00:00 3.07 2016-09-28 04:00:00 3.07 2016-09-28 05:00:00 3.07 2016-09-28 06:00:00 3.07 2016-09-28 07:00:00 3.07 2016-09-28 08:00:00 3.07 2016-09-28 09:00:00 3.07 2016-09-28 10:00:00 3.07 2016-09-28 11:00:00 3.07 2016-09-28 12:00:00 3.07 2016-09-28 13:00:00 3.07 2016-09-28 14:00:00 3.07 2016-09-28 15:00:00 3.07 2016-09-28 16:00:00 3.07 2016-09-28 17:00:00 3.07 2016-09-28 18:00:00 3.07 2016-09-28 19:00:00 3.07 2016-09-28 20:00:00 3.07 2016-09-28 21:00:00 3.07 2016-09-28 22:00:00 3.07 2016-09-28 23:00:00 3.07 2016-09-29 00:00:00 2.98 ... ... 2016-10-02 00:00:00 2.84 2016-10-02 01:00:00 2.84 2016-10-02 02:00:00 2.84 2016-10-02 03:00:00 2.84 2016-10-02 04:00:00 2.84 2016-10-02 05:00:00 2.84 2016-10-02 06:00:00 2.84 2016-10-02 07:00:00 2.84 2016-10-02 08:00:00 2.84 2016-10-02 09:00:00 2.84 2016-10-02 10:00:00 2.84 2016-10-02 11:00:00 2.84 2016-10-02 12:00:00 2.84 2016-10-02 13:00:00 2.84 2016-10-02 14:00:00 2.84 2016-10-02 15:00:00 2.84 2016-10-02 16:00:00 2.84 2016-10-02 17:00:00 2.84 2016-10-02 18:00:00 2.84 2016-10-02 19:00:00 2.84 2016-10-02 20:00:00 2.84 2016-10-02 21:00:00 2.84 2016-10-02 22:00:00 2.84 2016-10-02 23:00:00 2.84 2016-10-03 00:00:00 2.84 [121 rows x 1 columns] </code></pre> <p>or this if you don't want to have <code>DateTime</code> as an index:</p> <pre><code>df.set_index('DateTime').resample('H').pad() </code></pre>
0
2016-10-10T20:48:18Z
[ "python", "pandas", "dataframe" ]
Selenium in Python - open every link within a drop down menu
39,966,486
<p>I'm new to Python, but I've been searching for the past hour about how to do this and this code almost works. I need to open up every category on a collapsing (dropdown) menu, and then Ctrl+t every link within that now .active class. The browser opens and all the categories open as well, but I'm not getting any of the .active links being opened in new tabs. I would appreciate any help. </p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get("pioneerdoctor.com/productpage.cfm") cat = driver.find_elements_by_css_selector("a[href*='Product_home']") for i in cat: i.click() child = driver.find_elements_by_css_selector("li.active &gt; a[href*='ProductPage']") for m in child: m.send_keys(Keys.CONTROL + 't') </code></pre> <hr> <p>EDIT:</p> <p>Here's the current workaround I got going by writing to a text file and using webbrowser. The only issue I'm seeing is that it's writing duplicates of the results multiple times. I'll be looking through the comments later to see if I can get it working a better way (which I'm sure there is).</p> <pre><code>from selenium import webdriver import webbrowser print("Opening Google Chrome..") driver = webdriver.Chrome() driver.get("http://pioneerdoctor.com/productpage.cfm") driver.implicitly_wait(.5) driver.maximize_window() cat = driver.find_elements_by_css_selector("a[href*='Product_home']") print("Writing URLS to file..") for i in cat: i.click() child = driver.find_elements_by_css_selector("a[href*='ProductPage']") for i in child: child = i.get_attribute("href") file = open("Output.txt", "a") file.write(str(child) + '\n') file.close() driver.quit file = open("Output.txt", "r") Loop = input("Loop Number, Enter 0 to quit: ") Loop = int(Loop) x = 0 if Loop == 0: print("Quitting..") else: for z in file: if x == Loop: break print("Done.\n") else: webbrowser.open_new_tab(z) x += 1 </code></pre>
1
2016-10-10T20:46:32Z
39,968,427
<p>None of the links in those categories are not found because the css selector for the links is incorrect. Remove the <code>&gt;</code> in <code>li.active &gt; a[href*='ProductPage']</code>. Why ? <code>p &gt; q</code> gives you the immediate children of p. Space or "p q" gives you all the "q" inside p. The links you are interested in are NOT the immediate children of li. They are inside a UL which is inside the li.</p> <p>The other problem is the way you open links in new tabs. Use this code instead:</p> <pre><code>combo = Keys.chord(Keys.CONTROL, Keys.RETURN) m.sendKeys(combo) </code></pre> <p>Thats how I do it in Java. I think that python should have Keys.chord. If I were you, then I would open the links in another browser instance. I have seen that switching between tabs and windows is not supported well by selenium itself. Bad things can happen.</p> <p>Before you try any tabbing, make a simple example to open a new tab and switch back to the previous tab. Do the back and forth 3-4 times. Does it work smoothly ? Good. Then, do that with 3-5 tabs. Tell me how was your experience.</p>
0
2016-10-10T23:46:18Z
[ "python", "selenium" ]
SQLAlchemy: deny column copy for multiple one-to-manies
39,966,503
<p>I've had a set of relationships running SQLAlchemy 0.9.10 in production for over a year and I'm looking to upgrade to 1.0+. All the tests pass after simply upgrading the package, however, new warnings are now being logged.</p> <blockquote> <p>SAWarning: relationship 'A.c' will copy column test_c.a_id to column test_a.id, which conflicts with relationship(s): 'A.b' (copies test_b.a_id to test_a.id). Consider applying viewonly=True to read-only relationships, or provide a primaryjoin condition marking writable columns with the foreign() annotation.</p> </blockquote> <p>I've simplified the tables as much as possible to demonstrate.</p> <p>The idea is that the parent <code>A</code> has two one-to-many child relationships (<code>B</code> and <code>C</code>) that behave as one-to-ones by each child denoting their "current" ID on the parent.</p> <pre><code>class A(Base): __tablename__ = 'test_a' id = Column(BigInteger, primary_key=True, autoincrement='ignore_fk') b_id = Column(BigInteger) c_id = Column(BigInteger) __table_args__ = ( ForeignKeyConstraint( ['id', 'b_id'], ['test_b.a_id', 'test_b.id'], use_alter=True, name='a_b_fk', ), ForeignKeyConstraint( ['id', 'c_id'], ['test_c.a_id', 'test_c.id'], use_alter=True, name='a_c_fk', ), ) class B(Base): __tablename__ = 'test_b' id = Column(BigInteger, autoincrement=True, primary_key=True) a_id = Column(ForeignKey('test_a.id'), primary_key=True) class C(Base): __tablename__ = 'test_c' id = Column(BigInteger, autoincrement=True, primary_key=True) a_id = Column(ForeignKey('test_a.id'), primary_key=True) # A has exactly one *current* B A.b = sa_orm.relationship( B, primaryjoin=sa_sql.and_(A.id == B.a_id, A.b_id == B.id), uselist=False, ) # Every C refers to a single A C.a = sa_orm.relationship( A, primaryjoin=C.a_id == A.id, foreign_keys=[C.a_id], ) # Conversely, every A has zero or one C A.c = sa_orm.relationship( C, primaryjoin=sa_sql.and_(A.id == C.a_id, A.c_id == C.id), uselist=False, ) </code></pre> <p>Using <code>viewonly</code> isn't an option as some columns in the relationships do write. I've tried every combination of I can think of to denote <code>foreign()</code> on the relationship definitions, but I haven't been able to get the warnings to stop while still having the code function. After reading the docs and a good chunk of the SA code base, I'm seem to be stuck on how to set this up.</p> <p>As far as I understand, I need to denote on <code>B</code> and <code>C</code> that the value of <code>A.id</code> is immutable. </p> <ul> <li>Am I on the right track? </li> <li>Are there any examples worth looking at outside of <a href="http://docs.sqlalchemy.org/en/latest/orm/join_conditions.html#creating-custom-foreign-conditions" rel="nofollow">the docs</a> to help with this?</li> <li>Is my pain caused by the fact that the <code>primaryjoin</code>s use <code>and_()</code>?</li> </ul>
0
2016-10-10T20:48:12Z
39,967,792
<p>Your problem comes from the fact you have two relationships that can modify <code>A.id</code>, which in turn stems from the fact that you've named it as part of two separate relationships. Whereas technically SQL allows you to do this, SQLAlchemy is more rigid in the patterns that it allows you to model.</p> <p>The correct solution is to not have <code>A.id</code> be part of the join, since it's not strictly necessary. <code>b_id</code> and <code>c_id</code> columns have all the information you need to find the right column in <code>B</code> and <code>C</code> tables. You can keep the reference to <code>A.id</code> in the foreign keys if you like, if you are concern about data integrity.</p>
0
2016-10-10T22:36:27Z
[ "python", "postgresql", "sqlalchemy" ]
Invalid XML code generated by web service
39,966,513
<p>It seems like the <code>@service.xml</code> decorator is broken in <a href="http://web2py.com/books/default/chapter/29/10/services#Remote-procedure-calls" rel="nofollow">web services RPC</a>.</p> <pre><code>@service.xml def concat(a, b): return a + b </code></pre> <p>The result is:</p> <pre><code>&gt;&gt;&gt; from urllib import urlopen &gt;&gt;&gt; r = urlopen("http://127.0.0.1:8000/webservice/default/call/xml/concat/hello/ world") &gt;&gt;&gt; r.read() '&lt;?xml version="1.0" encoding="UTF-8"?&gt;helloworld' </code></pre> <p>The last part is missing which produces invalid XML.</p> <p>However, JSON and CSV work well.</p> <pre><code>@service.json def concat(a, b): return a + b </code></pre> <p>Test:</p> <pre><code>&gt;&gt;&gt; r = urlopen("http://127.0.0.1:8000/webservice/default/call/json/concat/hello /world") &gt;&gt;&gt; r.read() '"helloworld"' </code></pre> <p>I'm testing this in a copy of the scaffolding application. Am I missing something or this is really an issue?</p>
0
2016-10-10T20:48:36Z
39,978,876
<p>I think it is just a bad example in the book. To produce valid XML, the function should return a list or dictionary (or an object with a <code>.as_list</code>, <code>.as_dict</code>, or <code>.custom_xml</code> method). For example:</p> <pre><code>@service.xml def concat(a, b): return dict(result=a + b) </code></pre> <p>produces:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;document&gt; &lt;result&gt;helloworld&lt;/result&gt; &lt;/document&gt; </code></pre>
1
2016-10-11T13:51:43Z
[ "python", "xml", "python-2.7", "web-services", "web2py" ]
Sortable Kivy List
39,966,541
<p>I'm creating a Kivy/Python app that generates a formatted report. The report itself is generated with pandas dataframes and then written to Excel. I'd like to add something to the UI that would allow users to apply custom sorting to the report.</p> <p>So, for instance, if the dataframe has a "Category" field with values "Cat1", "Cat2", "Cat3", I'd like to add a feature where a user could organize those categories in a custom order.</p> <p>What I'm envisioning is a list of items on the Kivy UI that a user could re-sort by dragging and dropping the items? Or, even just a simple list with an up/down arrow would suffice. I believe this is generally called a listbox, but I can't seem to find that widget in Kivy. Currently, I'm managing sorting by just having an external mapping document, but I'd like to integrate this into the app functionality instead. </p> <p>Note: I'm not looking for detailed code or anything--just some ideas on what modules/widgets/approach might work here.</p> <p>Any thoughts would be greatly appreciated!</p> <p>Thanks</p>
0
2016-10-10T20:50:23Z
39,986,069
<p>Store the data inside a <a href="https://kivy.org/docs/api-kivy.properties.html#kivy.properties.ListProperty" rel="nofollow">list property</a>.</p> <p>Create a table out of a grid layout, on which you would like to show the content of the <code>data</code> list. The headers of the table would be buttons that do some sorting on the list. Each time the list changes, an <code>on_data</code> callback will be triggered. Use the callback to redraw the table rows.</p>
0
2016-10-11T20:22:51Z
[ "python", "pandas", "kivy" ]
ValueError: If using all scalar values, you must pass an index
39,966,543
<p>I have the following code:</p> <pre><code>import datetime import MySQLdb as mdb import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd import pprint import statsmodels.tsa.stattools as ts from pandas.stats.api import ols if __name__ == "__main__": # Connect to the MySQL instance db_host2 = '192.168.200.128' db_user2 = 'sec_master' db_pass2 = 'PASS' db_name2 = 'EUR-USD' con = mdb.connect(db_host2, db_user2, db_pass2, db_name2) sql2 = """SELECT `TIME`.`BID-CLOSE` FROM `EUR-USD`.`tbl_EUR-USD_1-Day` WHERE TIME &gt;= '2006-12-15 22:00:00' AND TIME &lt;= '2007-01-03 22:00:00' ORDER BY TIME ASC;""" # Create a pandas dataframe from the SQL query eurusd = pd.read_sql_query(sql2, con=con, index_col='TIME') idx = pd.date_range('2006-12-17 22:00:00', '2007-01-03 22:00:00') eurusd.reindex(idx, fill_value=None) </code></pre> <p>This gives an output of </p> <pre><code> BID-CLOSE 2006-12-17 22:00:00 1.30971 2006-12-18 22:00:00 1.31971 2006-12-19 22:00:00 1.31721 2006-12-20 22:00:00 1.31771 2006-12-21 22:00:00 1.31411 2006-12-22 22:00:00 NaN 2006-12-23 22:00:00 NaN 2006-12-24 22:00:00 NaN 2006-12-25 22:00:00 1.30971 2006-12-26 22:00:00 1.31131 2006-12-27 22:00:00 1.31491 2006-12-28 22:00:00 1.32021 2006-12-29 22:00:00 NaN 2006-12-30 22:00:00 NaN 2006-12-31 22:00:00 1.32731 2007-01-01 22:00:00 1.32731 2007-01-02 22:00:00 1.31701 2007-01-03 22:00:00 1.30831 </code></pre> <p>I then assign:</p> <pre><code>eurusd = eurusd.reindex(idx, fill_value=None) </code></pre> <p>Next I use:</p> <pre><code>methods = ['linear', 'quadratic', 'cubic'] </code></pre> <p>When I use the next line a get an error.</p> <pre><code>pd.DataFrame({m: eurusd.interpolate(method=m) for m in methods}) </code></pre> <p>The error is:</p> <pre><code>ValueError: If using all scalar values, you must pass an index </code></pre> <p>I am following (trying to) the Interpolation section of this guide <a href="http://pandas.pydata.org/pandas-docs/stable/missing_data.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/missing_data.html</a></p> <p>How do I correctly 'pass an index' in this situation?</p> <p>Update 1</p> <p>The output of <code>eurusd.interpolate('linear')</code></p> <pre><code> BID-CLOSE 2006-12-17 22:00:00 1.309710 2006-12-18 22:00:00 1.319710 2006-12-19 22:00:00 1.317210 2006-12-20 22:00:00 1.317710 2006-12-21 22:00:00 1.314110 2006-12-22 22:00:00 1.313010 2006-12-23 22:00:00 1.311910 2006-12-24 22:00:00 1.310810 2006-12-25 22:00:00 1.309710 2006-12-26 22:00:00 1.311310 2006-12-27 22:00:00 1.314910 2006-12-28 22:00:00 1.320210 2006-12-29 22:00:00 1.322577 2006-12-30 22:00:00 1.324943 2006-12-31 22:00:00 1.327310 2007-01-01 22:00:00 1.327310 2007-01-02 22:00:00 1.317010 2007-01-03 22:00:00 1.308310 </code></pre> <p>Update 2</p> <pre><code>In[9]: pd.DataFrame({m: eurusd['BID-CLOSE'].interpolate(method=m) for m in methods}) Out[9]: cubic linear quadratic 2006-12-17 22:00:00 1.309710 1.309710 1.309710 2006-12-18 22:00:00 1.319710 1.319710 1.319710 2006-12-19 22:00:00 1.317210 1.317210 1.317210 2006-12-20 22:00:00 1.317710 1.317710 1.317710 2006-12-21 22:00:00 1.314110 1.314110 1.314110 2006-12-22 22:00:00 1.310762 1.313010 1.307947 2006-12-23 22:00:00 1.309191 1.311910 1.305159 2006-12-24 22:00:00 1.308980 1.310810 1.305747 2006-12-25 22:00:00 1.309710 1.309710 1.309710 2006-12-26 22:00:00 1.311310 1.311310 1.311310 2006-12-27 22:00:00 1.314910 1.314910 1.314910 2006-12-28 22:00:00 1.320210 1.320210 1.320210 2006-12-29 22:00:00 1.323674 1.322577 1.321632 2006-12-30 22:00:00 1.325553 1.324943 1.323998 2006-12-31 22:00:00 1.327310 1.327310 1.327310 2007-01-01 22:00:00 1.327310 1.327310 1.327310 2007-01-02 22:00:00 1.317010 1.317010 1.317010 2007-01-03 22:00:00 1.308310 1.308310 1.308310 </code></pre>
1
2016-10-10T20:50:50Z
39,967,491
<p>The problem is that when you use the <code>DataFrame</code> constructor:</p> <pre><code>pd.DataFrame({m: eurusd.interpolate(method=m) for m in methods}) </code></pre> <p>the value for each <code>m</code> is a <code>DataFrame</code>, which will be interpreted as a scalar value, which is admittedly confusing. This constructer expects some sort of sequence or <code>Series</code>. The following should solve the problem:</p> <pre><code>pd.DataFrame({m: eurusd['BID-CLOSE'].interpolate(method=m) for m in methods}) </code></pre> <p>Since subsetting on a column returns a <code>Series</code>. So, for example instead of:</p> <pre><code>In [34]: pd.DataFrame({'linear':df.interpolate('linear')}) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-34-4b6c095c6da3&gt; in &lt;module&gt;() ----&gt; 1 pd.DataFrame({'linear':df.interpolate('linear')}) /home/juan/anaconda3/lib/python3.5/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy) 222 dtype=dtype, copy=copy) 223 elif isinstance(data, dict): --&gt; 224 mgr = self._init_dict(data, index, columns, dtype=dtype) 225 elif isinstance(data, ma.MaskedArray): 226 import numpy.ma.mrecords as mrecords /home/juan/anaconda3/lib/python3.5/site-packages/pandas/core/frame.py in _init_dict(self, data, index, columns, dtype) 358 arrays = [data[k] for k in keys] 359 --&gt; 360 return _arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype) 361 362 def _init_ndarray(self, values, index, columns, dtype=None, copy=False): /home/juan/anaconda3/lib/python3.5/site-packages/pandas/core/frame.py in _arrays_to_mgr(arrays, arr_names, index, columns, dtype) 5229 # figure out the index, if necessary 5230 if index is None: -&gt; 5231 index = extract_index(arrays) 5232 else: 5233 index = _ensure_index(index) /home/juan/anaconda3/lib/python3.5/site-packages/pandas/core/frame.py in extract_index(data) 5268 5269 if not indexes and not raw_lengths: -&gt; 5270 raise ValueError('If using all scalar values, you must pass' 5271 ' an index') 5272 ValueError: If using all scalar values, you must pass an index </code></pre> <p>Use this instead:</p> <pre><code>In [35]: pd.DataFrame({'linear':df['BID-CLOSE'].interpolate('linear')}) Out[35]: linear timestamp 2016-10-10 22:00:00 1.309710 2016-10-10 22:00:00 1.319710 2016-10-10 22:00:00 1.317210 2016-10-10 22:00:00 1.317710 2016-10-10 22:00:00 1.314110 2016-10-10 22:00:00 1.313010 2016-10-10 22:00:00 1.311910 2016-10-10 22:00:00 1.310810 2016-10-10 22:00:00 1.309710 2016-10-10 22:00:00 1.311310 2016-10-10 22:00:00 1.314910 2016-10-10 22:00:00 1.320210 2016-10-10 22:00:00 1.322577 2016-10-10 22:00:00 1.324943 2016-10-10 22:00:00 1.327310 2016-10-10 22:00:00 1.327310 2016-10-10 22:00:00 1.317010 2016-10-10 22:00:00 1.308310 </code></pre> <p>Fair warning, though, I am getting a <code>LinAlgError: singular matrix</code> error when I try <code>'quadratic'</code> and <code>'cubic'</code> interpolation on your data. Not sure why though.</p>
1
2016-10-10T22:06:59Z
[ "python", "pandas", "quantitative-finance" ]
Creating time stamps using .format()
39,966,552
<p>Basically in this assignment we have to create a time, based on values of ran(hour,min):. Below I will post the code I have and then the error message I receive. Is my code just really bad or there something I'm missing? What does it mean by "Can't convert 'int' object to str implicitly.</p> <pre><code>def show_time(hour,min): if(hour &gt; 12): hour = hour -12 if(min &lt; 10): min = "0"+min print("{hour}:{min}".format(show_time())) </code></pre> <hr> <pre><code>Traceback (most recent call last): File "zyLabsUnitTestRunner.py", line 10, in &lt;module&gt; passed = test_passed(test_passed_output_file) File "/home/runner/local/unit_test_student_code/zyLabsUnitTest.py", line 33, in test_passed ans = show_time(hour,min) File "/home/runner/local/unit_test_student_code/main.py", line 15, in show_time min = "0"+min TypeError: Can't convert 'int' object to str implicitly </code></pre>
-1
2016-10-10T20:51:41Z
39,966,620
<p>In the following line:</p> <pre><code>if(min&lt;10): min = "0"+min </code></pre> <p>you are attempting to concatenate a string and an integer, which python cannot do. To convert a string to an int, use int(str), and to convert an int to a string, use str(int)</p>
0
2016-10-10T20:56:12Z
[ "python" ]
Creating time stamps using .format()
39,966,552
<p>Basically in this assignment we have to create a time, based on values of ran(hour,min):. Below I will post the code I have and then the error message I receive. Is my code just really bad or there something I'm missing? What does it mean by "Can't convert 'int' object to str implicitly.</p> <pre><code>def show_time(hour,min): if(hour &gt; 12): hour = hour -12 if(min &lt; 10): min = "0"+min print("{hour}:{min}".format(show_time())) </code></pre> <hr> <pre><code>Traceback (most recent call last): File "zyLabsUnitTestRunner.py", line 10, in &lt;module&gt; passed = test_passed(test_passed_output_file) File "/home/runner/local/unit_test_student_code/zyLabsUnitTest.py", line 33, in test_passed ans = show_time(hour,min) File "/home/runner/local/unit_test_student_code/main.py", line 15, in show_time min = "0"+min TypeError: Can't convert 'int' object to str implicitly </code></pre>
-1
2016-10-10T20:51:41Z
39,966,642
<p>The reason you are getting this error is because you are concatenating <code>"0"</code> (a string) with <code>min</code>, which is an integer.</p> <pre><code>&gt;&gt;&gt; '0' + 3 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: Can't convert 'int' object to str implicitly </code></pre> <p>You would avoid this by casting <code>min</code> as a string:</p> <pre><code>&gt;&gt;&gt; '0' + str(3) '03' </code></pre> <p>The best solution, though, would be to save this kind of formatting for--you guessed it!--<code>str.format()</code>. It has a <a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">rich syntax</a> that allows you to keep these transformations where they belong. Here is an example:</p> <pre><code>&gt;&gt;&gt; '{:02d}'.format(3) '03' </code></pre> <p>As it stands, your code has several issues:</p> <ol> <li>You are calling it without arguments in your code snippet.</li> <li>You are using the variable <em>inside</em> the format function rather than in its arguments: you appear to be mixing up passing in keyword parameters like so:</li> </ol> <pre> >>> '{a}:{b}'.format(**{'a':1, 'b':2}) '1:2' </pre> <ol start="3"> <li>You are not returning anything with the function. </li> <li><code>min</code> is a bad name for a variable since it is a built-in function.</li> </ol> <p>Here is a much easier way of doing everything in one block:</p> <pre><code>print("{}:{:02d}".format(hour % 12, minute)) </code></pre>
0
2016-10-10T20:57:58Z
[ "python" ]
Creating time stamps using .format()
39,966,552
<p>Basically in this assignment we have to create a time, based on values of ran(hour,min):. Below I will post the code I have and then the error message I receive. Is my code just really bad or there something I'm missing? What does it mean by "Can't convert 'int' object to str implicitly.</p> <pre><code>def show_time(hour,min): if(hour &gt; 12): hour = hour -12 if(min &lt; 10): min = "0"+min print("{hour}:{min}".format(show_time())) </code></pre> <hr> <pre><code>Traceback (most recent call last): File "zyLabsUnitTestRunner.py", line 10, in &lt;module&gt; passed = test_passed(test_passed_output_file) File "/home/runner/local/unit_test_student_code/zyLabsUnitTest.py", line 33, in test_passed ans = show_time(hour,min) File "/home/runner/local/unit_test_student_code/main.py", line 15, in show_time min = "0"+min TypeError: Can't convert 'int' object to str implicitly </code></pre>
-1
2016-10-10T20:51:41Z
39,966,656
<p>I think you use format incorrectly and you cannot concatenate 'str' and 'int' objects (min = "0"+min). I think this works:</p> <pre><code>def show_time(hour,min): if(hour &gt; 12): hour = hour -12 if(min &lt; 10): min = "0" + str(min) print "{}:{}".format(hour, min) </code></pre>
0
2016-10-10T20:59:09Z
[ "python" ]
Calculating subtotals in pandas pivot_table with MultiIndex
39,966,663
<p>I have the following raw data, in a dataframe:</p> <pre><code> BROKER VENUE QUANTITY 0 BrokerA Venue_1 300 1 BrokerA Venue_2 400 2 BrokerA Venue_2 1400 3 BrokerA Venue_3 800 4 BrokerB Venue_2 500 5 BrokerB Venue_3 1100 6 BrokerC Venue_1 1000 7 BrokerC Venue_1 1200 8 BrokerC Venue_2 17000 </code></pre> <p>I want to do some summarization of the data to see how much each broker sent to each venue, so I created a pivot_table:</p> <pre><code>pt = df.pivot_table(index=['BROKER', 'VENUE'], values=['QUANTITY'], aggfunc=np.sum) </code></pre> <p>Result, as expected:</p> <pre><code> QUANTITY BROKER VENUE BrokerA Venue_1 300.0 Venue_2 1800.0 Venue_3 800.0 BrokerB Venue_2 500.0 Venue_3 1100.0 BrokerC Venue_1 2200.0 Venue_2 17000.0 </code></pre> <p>I also want how much was sent to each broker overall. and show it in this same table. I can get that information by typing <code>df.groupby('BROKER').sum()</code>, but how can I add this to my pivot table as a column named, say, BROKER_TOTAL?</p> <p>Note: This question is similar but seems to be on an older version, and my best guess at adapting it to my situation didn't work: <a href="http://stackoverflow.com/questions/15570099/pandas-pivot-tables-row-subtotals">Pandas Pivot tables row subtotals</a></p>
1
2016-10-10T20:59:47Z
39,966,738
<p>You can create <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.from_arrays.html" rel="nofollow"><code>MultiIndex.from_arrays</code></a> for <code>df1</code>, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> it to <code>pt</code> and last <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_index.html" rel="nofollow"><code>sort_index</code></a>:</p> <pre><code>df1 = df.groupby('BROKER').sum() df1.index = pd.MultiIndex.from_arrays([df1.index + '_total', len(df1.index) * ['']]) print (df1) QUANTITY BrokerA_total 2900 BrokerB_total 1600 BrokerC_total 19200 print (pd.concat([pt, df1]).sort_index()) QUANTITY BROKER VENUE BrokerA Venue_1 300 Venue_2 1800 Venue_3 800 BrokerA_total 2900 BrokerB Venue_2 500 Venue_3 1100 BrokerB_total 1600 BrokerC Venue_1 2200 Venue_2 17000 BrokerC_total 19200 </code></pre>
0
2016-10-10T21:04:48Z
[ "python", "pandas" ]
Django Custom Auth Migration
39,966,691
<p>I was trying to alter something on my user model in django and in the process I used makemigration to generate the migration file for it. But then decided against the whole thing, but now I have an unmigrated migration file located somewhere and I can't find it. I don't have an auth migrations folder in my app and I looked in the django auth migrations file and it's not there either. It shows up when I run python manage.py showmigrations as unmigrated, but I don't see the file anywhere. It doesn't show up when I do git status either. </p> <p>Now I'm stuck because I can't run migrate without it trying to migrate it and erroring. This is probably something silly that I'm overlooking. :-/</p>
0
2016-10-10T21:01:45Z
39,967,078
<p>You can either delete the table manually or inspect all migrations with:</p> <pre><code>./manage.py showmigrations my_app </code></pre>
0
2016-10-10T21:32:31Z
[ "python", "django" ]
Install cx_oracle on solaris 11 sparc
39,966,698
<p>Most of the cx_Oracle 5.2.1 version builds are for Windows and Linux. How do I install/get an install for a Solaris 11 Sparc?</p> <p>I tried to install using the following: cx_Oracle-5.2.1.tar.gz from sourceforge.net But resulted in the following error:</p> <pre><code>/tmp/cx_Oracle-5.2.1$ python setup.py build running build running build_ext building 'cx_Oracle' extension creating build creating build/temp.solaris-2.11-sun4v.32bit-2.7-11g cc -DNDEBUG -KPIC -DPIC -I/u01/app/oracle/product/11.2.0.4/dbhome_1/rdbms/demo -I/u01/app/oracle/product/11.2.0.4/dbhome_1/rdbms/public -I/usr/include/python2.7 -c cx_Oracle.c -o build/temp.solaris-2.11-sun4v.32bit-2.7-11g/cx_Oracle.o -DBUILD_VERSION=5.2.1 unable to execute 'cc': No such file or directory error: command 'cc' failed with exit status 1 </code></pre> <p>Please advise.</p>
0
2016-10-10T21:01:56Z
39,978,837
<p>I do not know the exact reason for the error you are getting. It looks, however, like the "cc" compiler is not installed. You should be able to find that package and install it. Or you will need to adjust your configuration to use gcc instead. This link may help:</p> <p><a href="http://www.unix.com/solaris/114262-command-cc-failed-even-though-gcc-installed.html" rel="nofollow">http://www.unix.com/solaris/114262-command-cc-failed-even-though-gcc-installed.html</a></p>
0
2016-10-11T13:50:13Z
[ "python", "python-2.7", "solaris", "cx-oracle" ]
How to iterate in a certain order?
39,966,707
<p>I'm wondering how I can iterate through a list in a certain order in Python.</p> <p>Given the list, <code>lst = [1, 3, -1, 2]</code>, I want my function to iterate such that the next number iterated over will be the index of the value of the current number.</p> <p>lst[0] -> lst[1] -> lst[3] -> lst[2] 1 -> 3 -> 2 -> -1</p>
-3
2016-10-10T21:02:32Z
39,966,824
<p>There are a couple variables that you have not specified:</p> <ol> <li>What kind of error handling should this include? </li> <li>Do you want it to loop indefinitely?</li> </ol> <p>Assuming that the respective answers are "None" and "Yes", here's one way of doing it:</p> <pre><code>def create_iter(arr): i = 0 while True: yield arr[i] i = arr[i] lst = [1,3,-1,2] my_iterator = create_iter(lst) </code></pre> <p>This gives:</p> <pre><code>&gt;&gt;&gt; for _ in range(10): &gt;&gt;&gt; print (next(my_iterator)) 1 3 2 -1 2 -1 2 -1 2 -1 </code></pre>
3
2016-10-10T21:13:07Z
[ "python", "loops", "for-loop", "iteration", "next" ]
How to iterate in a certain order?
39,966,707
<p>I'm wondering how I can iterate through a list in a certain order in Python.</p> <p>Given the list, <code>lst = [1, 3, -1, 2]</code>, I want my function to iterate such that the next number iterated over will be the index of the value of the current number.</p> <p>lst[0] -> lst[1] -> lst[3] -> lst[2] 1 -> 3 -> 2 -> -1</p>
-3
2016-10-10T21:02:32Z
39,966,892
<p>Given that you check that each value is within the list except that you must have an end of list condition, then you would have</p> <pre><code>index = 0 while True: newindex = mylist[index] if newindex &gt;= len(mylist): break elif newindex == index: break else: index = newindex </code></pre> <p>Note that if every entry in the list is a valid index, then you would get an infinite loop.</p>
0
2016-10-10T21:18:21Z
[ "python", "loops", "for-loop", "iteration", "next" ]
How to open a window by clicking on a specific point on a chart?
39,966,763
<p>I have the task to build up an interactive plot which i have already done more or less. But now I am supposed to give specific information about a point in a graph for example P(8|6) and by clicking on this point there should open a new window with specific information. Adding the information to the window wont be the problem but the window itself. How I can open a window by clicking on this specific point (keep in mind, it is no button since it changes from graph to graph)?</p>
0
2016-10-10T21:06:46Z
39,990,158
<p>The answer is qwt! Study the documentation and examples for that project like your life depended on it, and you will find exactly what you need.</p> <p>I wrote up a pretty complete example a year or so ago; but it is in C++; converting it to python should be pretty straight forward.</p> <p><a href="https://github.com/peteristhegreat/qwt_generic" rel="nofollow">https://github.com/peteristhegreat/qwt_generic</a></p> <p>Hope that helps.</p>
0
2016-10-12T03:42:19Z
[ "python", "qt", "window", "new-window" ]
ODBC access from Mac install of Python to Access database installed in Parallels
39,966,839
<p>I want to link my Python packages to my Access database, but I get this error. I use python 2.7.12 (shell).</p> <pre><code>import pypyodbc #create connection con = pypyodbc.connect('DRIVER={Microsoft Access-Treiber (*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=//Users/123GuteLaune/DatabaseMAformat.mdb') cursor = con.cursor() #Select Data cursor.execute("SELECT * from TW-DS") for row in cursor.fetchone(): print(row)} </code></pre> <p>Traceback (most recent call last):<br> File "", line 1, in <br> import pypyodbc<br> ImportError: No module named pypyodbc </p> <p><strong>Edit</strong></p> <p>Hi after second installation following error occurs </p> <p>Traceback (most recent call last): File "/Users/123GuteLaune/Python/connectionprogramm.py", line 4, in con = pypyodbc.connect('DRIVER={Microsoft Access-Treiber (*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=//Users/123GuteLaune/DatabaseMAformat.mdb') File "build/bdist.macosx-10.6-intel/egg/pypyodbc.py", line 2435, in init self.connect(connectString, autocommit, ansi, timeout, unicode_results, readonly) File "build/bdist.macosx-10.6-intel/egg/pypyodbc.py", line 2484, in connect check_success(self, ret) File "build/bdist.macosx-10.6-intel/egg/pypyodbc.py", line 989, in check_success ctrl_err(SQL_HANDLE_DBC, ODBC_obj.dbc_h, ret, ODBC_obj.ansi) File "build/bdist.macosx-10.6-intel/egg/pypyodbc.py", line 976, in ctrl_err err_list.append((from_buffer_u(state), from_buffer_u(Message), NativeError.value)) File "build/bdist.macosx-10.6-intel/egg/pypyodbc.py", line 483, in UCS_dec uchar = buffer.raw[i:i + ucs_length].decode(odbc_decoding) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_32.py", line 11, in decode return codecs.utf_32_decode(input, errors, True) UnicodeDecodeError: 'utf32' codec can't decode bytes in position 0-1: truncated data</p> <p><strong>Edit on 12.10.2016</strong></p> <p>I use a Mac with macOS El Captain. I have the program "Parallels" on my laptop for using Access in a virtual machine. Python is installed on the Mac side.</p> <p>What must I change that Python can use the ODBC interface to Access?</p> <p><strong>Edit 13.10.2016</strong></p> <p>I find a the toolkit "pyodbc" i think this should work on mac but again i can not ran the setup file i got the error. I already installed homebrew and find this dokumentation for installing (<a href="https://github.com/lionheart/django-pyodbc/wiki/Mac-setup-to-connect-to-a-MS-SQL-Server" rel="nofollow">https://github.com/lionheart/django-pyodbc/wiki/Mac-setup-to-connect-to-a-MS-SQL-Server</a>) </p> <p>Error in python: Traceback (most recent call last): File "/Users/123GuteLaune/connectionprogramm.py", line 1, in import pyodbc ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyodbc.so, 2): Library not loaded: /usr/local/lib/libodbc.2.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pyodbc.so Reason: image not found</p>
0
2016-10-10T21:14:21Z
40,006,328
<p>If you are running Python on the Mac side then you need to use a driver that is compatible with macOS. The <code>Microsoft Access-Trebier (*.mdb)</code> ODBC driver is a Windows DLL (ODBCJT32.DLL) and I doubt very much that the Mac version of Python can use it.</p> <p>You may be interested in the related question here:</p> <p><a href="http://stackoverflow.com/q/25596737/2144390">Read an Access database in Python on non-Windows platform (Linux or Mac)</a></p>
0
2016-10-12T18:56:51Z
[ "python", "osx", "python-2.7", "ms-access", "pypyodbc" ]
importing from another folder in virtualenv
39,966,967
<p>I'm following the <a href="http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world" rel="nofollow">Flask Mega Tutorial</a>, and I'm running into an issue once I get to the second part and restructure my folder structure to match theirs, I cannot import Flask.</p> <p>My current folder structure is as follows</p> <pre><code>/FlaskTest /app /static, templates etc /flask /virtualenv folders etc /tmp run.py </code></pre> <p>as far as I can tell, the folder structures are identical other than naming of the top level directory.</p> <p>in my __init__.py file (/app/__init__.py), I'm doing as instructed in the tutorial, </p> <pre><code>from flask import Flask app = Flask(__name__) from app import views </code></pre> <p>I'm getting an Import Error that "cannot import name 'Flask'". I'm guessing the issue is because the flask package was installed to /flask/lib/site-packages.</p> <p>My question: How can I reference the sub folder of flask/site-packages?</p> <p>I've read through the python <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">import system documentation</a> and from what I can make of it through the first pass of reading it over, I would need to likely do something like from flask import flask.Flask or something to that effect.</p> <p><strong>UPDATE</strong>: So after cd'ing around the directory and checking pip list, I realized that flask wasn't accessible to my app directory. I ran pip install flask in the app directory. Now my site runs, but I'm not sure if this is the best practice of doing things with Python. Please provide some clarity as what the best practice is for installing packages and where the packages reside.</p> <p><strong>UPDATE 2</strong>: After creating a directory called standalone. In this folder, I created a virtual environment called standalone-test. Once, I did that, I also mkdir'ed app and copied it's contents from FlaskTest so that way the code would be identical. I was able to run the run.py script by using <code>python run.py</code>, but I can't run <code>python -m app</code> like you had said without running into an error. The error is as follows if it helps.</p> <p>"No module name app.<strong>main</strong>; 'app' is a package and cannot be directly executed. </p> <p>I am able to run <code>python run.py</code> as I mentioned, but I'm not able to run the <code>python -m app</code> command as you had mentioned</p>
0
2016-10-10T21:24:29Z
39,967,717
<p>I think something went wrong in your execution environment. Here are some explanations.</p> <h3>The virtualenv</h3> <p>See the documentation of <a href="https://virtualenv.pypa.io/en/stable/userguide/" rel="nofollow">virtualenv</a></p> <p>If you have followed the tutorial:</p> <ul> <li>The <code>flask</code> directory is your virtualenv,</li> <li>On posix system, you have a <code>flask/bin</code> subdirectory, or</li> <li>On Windows system, you have a <code>flask\Scripts</code> subdirectory.</li> </ul> <p>I make the assumption that you are on posix system.</p> <p>To activate your virtualenv, run:</p> <pre><code>source flask/bin/activate </code></pre> <p>Your prompt should change to something like: <code>(flask)$</code>. </p> <p>To list the installed libraries use <code>pip</code>:</p> <pre><code>pip list </code></pre> <p>Make sure you see Flask. The tutorial encourages you to install a lot of Flask plugins, so there are a lot of Flask-Something…</p> <p>If Flask is missing, install it:</p> <pre><code>pip install Flask </code></pre> <h3>Run your app</h3> <p>Your application is in the <code>app</code> directory, it has an <code>__init__.py</code> file (it's a Python package).</p> <p>In this file, you have:</p> <pre><code>from flask import Flask app = Flask(__name__) from app import views </code></pre> <p>From your <code>FlaskTest/</code> directory, try to run this script like this:</p> <pre><code>cd FlaskTest/ # if not in this directory python -m app </code></pre> <p>This should import <code>Flask</code>, instanciate your <code>app</code> (but don't run it), import the <code>views</code> module.</p> <p>If <code>app/views.py</code> exist you should have no error.</p> <p>=> at this point, we have simulated what <code>run.py</code> imports…</p> <p>Now write <code>run.py</code> in your <code>FlaskTest/</code> directory:</p> <pre><code>#!flask/bin/python from app import app app.run(debug=True) </code></pre> <p>Run it like this:</p> <pre><code>python run.py </code></pre> <p>Note that the shebang <code>#!flask/bin/python</code> is unusual, but should work in the context of the tutorial.</p> <p>This should start your http server…</p>
1
2016-10-10T22:29:33Z
[ "python", "flask", "pip", "virtualenv" ]
Call function from python with tuple return in c
39,966,982
<p>I'm trying to call a python function from my C script. I success to return a double variable from the python function and print it in my C script. The problem I have now is that I need to return multiple variables (tuple) from python. How can I success that? My code with a single variable return is as follows: </p> <pre><code>#include &lt;python2.7/Python.h&gt; int main(){ PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; int i; double read; Py_Initialize(); PyObject* sysPath = PySys_GetObject((char*)"path"); PyList_Append(sysPath, PyString_FromString(".")); pName = PyString_FromString("eadata"); //Primer posible error pModule = PyImport_Import(pName); Py_DECREF(pName); if(pModule != NULL){ pFunc = PyObject_GetAttrString(pModule,"lectura"); if(pFunc &amp;&amp; PyCallable_Check(pFunc)){ pValue = PyObject_CallObject(pFunc,NULL); if(pValue != NULL){ printf("Result of call: %lf \n", PyFloat_AsDouble(pValue)); Py_DECREF(pValue); } else{ Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } } else{ PyErr_Print(); fprintf(stderr, "Error al cargar eadata.py \n"); } } </code></pre> <p>My python script is:</p> <pre><code>def lectura(): device = '/dev/ttyUSB0' baudrate = 115200 mt=mtdevice1.MTDevice(device, baudrate) ax=mtdevice1.acx ay=mtdevice1.acy az=mtdevice1.acz wx=mtdevice1.wx wy=mtdevice1.wy wz=mtdevice1.wz mx=mtdevice1.mx my=mtdevice1.my mz=mtdevice1.mz roll = mtdevice1.roll pitch = mtdevice1.pitch yaw = mtdevice1.yaw pc = mtdevice1.pc return ax </code></pre> <p>This works, but I want to return other variables at the same time such as ay,az, and so on. Is my first time using embedded python and I really don't know how to do this. </p>
0
2016-10-10T21:25:39Z
39,967,681
<p><a href="http://stackoverflow.com/questions/23200484/pyarg-parsetuple-on-arbitrary-tuples">With a small caveat</a>, you can use <a href="https://docs.python.org/3/c-api/arg.html#c.PyArg_ParseTuple" rel="nofollow"><code>PyArg_ParseTuple</code></a> to take apart the tuple returned by the function you call. </p> <p>This will work fine as long as the returned tuple matches the format string you provide to <code>PyArg_ParseTuple</code>. If there is a mismatch, the error produced by <code>PyArg_ParseTuple</code> will be misleading because it assumes that the tuple is an argument tuple.</p> <p>A less convenient but more general approach is to use the <a href="https://docs.python.org/3/c-api/tuple.html" rel="nofollow">tuple API</a>.</p>
1
2016-10-10T22:25:50Z
[ "python", "c" ]
I'm getting an List index out of range error for an index that exist
39,967,037
<p>Im using feed parser to obtain rss objects. When I run </p> <pre><code>live_leak.links </code></pre> <p>I get</p> <pre><code>[{'type': 'text/html', 'rel': 'alternate', 'href': 'http://www.liveleak.com/view?i=abf_1476121939'}, {'type': 'application/x-shockwave-flash', 'rel': 'enclosure', 'href': 'http://www.liveleak.com/e/abf_1476121939'}] </code></pre> <p>But when i try this</p> <pre><code>live_leak.links[1] </code></pre> <p>I get list index out of range, mind you this was working earlier then all of a sudden this didn't work. I had this in my code and it took me hours to find because I didn't realize it was this that wasn't working. If no one knows I'll do a string replace as a hack but I rather do what was already working.</p> <p>this also works </p> <pre><code>live_leak[0] </code></pre> <p>it returns</p> <pre><code>[{'type': 'text/html', 'rel': 'alternate', 'href': 'http://www.liveleak.com/view?i=abf_1476121939'}] </code></pre> <p>which is weird because the other one won't work</p> <h1>EDIT</h1> <pre><code>def pan_task(): url = 'http://www.liveleak.com/rss?featured=1' name = 'live leak' live_leaks = [i for i in feedparser.parse(url).entries] the_count = len(live_leaks) ky = feedparser.parse(url).keys() oky = [i.keys() for i in feedparser.parse(url).entries][:12] # shows what I can pull try: live_entries = [{ 'html': live_leak.links, 'href': live_leak.links[0]['href'], 'src': live_leak.media_thumbnail[0]['url'], 'text': live_leak.title, 'comments': live_leak.description, 'url': live_leak.links[0]['href'], 'embed': live_leak.links[1]['href'], 'text': live_leak.title, 'comments': live_leak.description, 'name': name, 'url': live_leak.link, # this is the link to the source 'author': None, 'video': False } for live_leak in live_leaks] except IndexError: print('error check logs') live_entries = [] # for count, elem in enumerate(live_entries): # the_html = requests.get(live_entries[count]['url']) # a specific text return print(live_entries[0]) </code></pre>
4
2016-10-10T21:29:35Z
39,967,086
<p>You can index <strong>live_leak</strong>, but <strong>live_leak.links</strong> appears to be some other type of construct that returns the elements of <strong>live_leak</strong>. Try <strong>live_leak[1]</strong>, perhaps?</p>
0
2016-10-10T21:33:16Z
[ "python", "rss", "feedparser" ]
I'm getting an List index out of range error for an index that exist
39,967,037
<p>Im using feed parser to obtain rss objects. When I run </p> <pre><code>live_leak.links </code></pre> <p>I get</p> <pre><code>[{'type': 'text/html', 'rel': 'alternate', 'href': 'http://www.liveleak.com/view?i=abf_1476121939'}, {'type': 'application/x-shockwave-flash', 'rel': 'enclosure', 'href': 'http://www.liveleak.com/e/abf_1476121939'}] </code></pre> <p>But when i try this</p> <pre><code>live_leak.links[1] </code></pre> <p>I get list index out of range, mind you this was working earlier then all of a sudden this didn't work. I had this in my code and it took me hours to find because I didn't realize it was this that wasn't working. If no one knows I'll do a string replace as a hack but I rather do what was already working.</p> <p>this also works </p> <pre><code>live_leak[0] </code></pre> <p>it returns</p> <pre><code>[{'type': 'text/html', 'rel': 'alternate', 'href': 'http://www.liveleak.com/view?i=abf_1476121939'}] </code></pre> <p>which is weird because the other one won't work</p> <h1>EDIT</h1> <pre><code>def pan_task(): url = 'http://www.liveleak.com/rss?featured=1' name = 'live leak' live_leaks = [i for i in feedparser.parse(url).entries] the_count = len(live_leaks) ky = feedparser.parse(url).keys() oky = [i.keys() for i in feedparser.parse(url).entries][:12] # shows what I can pull try: live_entries = [{ 'html': live_leak.links, 'href': live_leak.links[0]['href'], 'src': live_leak.media_thumbnail[0]['url'], 'text': live_leak.title, 'comments': live_leak.description, 'url': live_leak.links[0]['href'], 'embed': live_leak.links[1]['href'], 'text': live_leak.title, 'comments': live_leak.description, 'name': name, 'url': live_leak.link, # this is the link to the source 'author': None, 'video': False } for live_leak in live_leaks] except IndexError: print('error check logs') live_entries = [] # for count, elem in enumerate(live_entries): # the_html = requests.get(live_entries[count]['url']) # a specific text return print(live_entries[0]) </code></pre>
4
2016-10-10T21:29:35Z
39,967,124
<p>One is looking for links under live_leak the other is just looking at live_leak itself.</p> <p>for example: live_leak[1] </p> <p>should return: [{'type': 'application/x-shockwave-flash', 'rel': 'enclosure', 'href': '<a href="http://www.liveleak.com/e/abf_1476121939" rel="nofollow">http://www.liveleak.com/e/abf_1476121939</a>'}]</p>
0
2016-10-10T21:36:33Z
[ "python", "rss", "feedparser" ]
Why does django date filter gives me entries from the next day as welll
39,967,155
<p>I am trying to access a database which has say two entries for 2016,9,25 and two entries for 2016,9,26, each of those entries have different time... I view them by listing each of them using the task.start_time in my template following is the list that I get</p> <pre><code>TASK Task.title duration start_time project project_color user 1st task This is the first task 0:02:40 Sept. 25, 2016, 11:42 p.m. Unassigned NO COLOR faizank 2nd task This is the second task 0:01:30 Sept. 25, 2016, 11:47 p.m. Unassigned NO COLOR faizank 3rd task asdasdasdasd 0:20:00 Sept. 26, 2016, 12:19 a.m. Unassigned NO COLOR faizank 3rd task this is the problem 0:20:00 Sept. 26, 2016, 12:22 a.m. Unassigned NO COLOR faizank </code></pre> <p>start_time is a datetime_field, now i am filtering the datetime object using the following queries</p> <pre><code>&gt;&gt;&gt; c= Task.objects.filter(start_time__date=datetime.date(2016,9,25) </code></pre> <p>This gives me </p> <pre><code>&lt;QuerySet [&lt;Task: 1st task&gt;, &lt;Task: 2nd task&gt;, &lt;Task: 3rd task&gt;, &lt;Task: 3rd task&gt;]&gt; </code></pre> <p>but when I change the date to 26 it gives me an empty set....</p> <p>I even did this </p> <pre><code>&gt;&gt;&gt; c= Task.objects.filter(start_time__date=datetime.datetime(2016,9,25,0,0,0,0,pytz.UTC) </code></pre> <p>got the same result.</p> <p>So why is the date returning the entries from 26 as well....and on querring 26 it returns an empty set....</p> <p>EDIT 1: So i just figured out, the dates are stored with different times, I dont know why the template does not show the actual times. So in case of the above entries I checked the actual times and found the following...</p> <pre><code>&gt;&gt;&gt; d= &lt;QuerySet [&lt;Task: 1st task&gt;, &lt;Task: 2nd task&gt;, &lt;Task: 3rd task&gt;, &lt;Task: 3rd task&gt;]&gt; &gt;&gt;&gt; d[2].start_time </code></pre> <p>and got the following datetime.datetime(2016, 9, 25, 19, 19, 59, 477000, tzinfo=)</p> <p>which clearly shows that the 3rd task is stored at a different time and the one it is showing in the template, in fact I think it is exactly -5h from the time it is displaying which is GMT, so the real question now is why is template showing different time for the same model....and more importantly how can I correct it...</p>
1
2016-10-10T21:38:52Z
39,967,350
<p>According to the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#date" rel="nofollow">Django QuerySet reference for <code>date</code></a>:</p> <blockquote> <p>When <code>USE_TZ</code> is True, fields are converted to the current time zone before filtering.</p> </blockquote> <p>Given that both the tasks occur shortly after midnight, I suspect that the conversion to your set timezone is causing the issue you are seeing.</p>
2
2016-10-10T21:55:15Z
[ "python", "django", "sqlite" ]
Propagating arguments to decorator which combines other decorators
39,967,240
<p>I have a scenario like:</p> <pre><code>@decorator_one(1) @foo @bar def my_decorated_func(): pass </code></pre> <p>I am trying to condense this into something like:</p> <pre><code>@my_custom_decorator(1) def my_decorated_func(): pass </code></pre> <p>This is straightforward if I have decorators that do not have <code>(1)</code> option:</p> <pre><code>def my_custom_decorator(f): @decorator_one @foo @bar def wrapped(): pass return wrapped </code></pre> <p>However I am uncertain how to properly propagate the argument to the first wrapper. </p> <p>In this case, I am comfortable assuming that if I pass 1 to my_custom_decorator that it will always and only be the arg for decorator_one.</p>
1
2016-10-10T21:46:11Z
39,967,298
<p><code>@decorator_one(1)</code> means that there is a callable that returns a decorator; call it a decorator <em>factory</em>. <code>decorator_one(1)</code> returns the decorator that is then applied to the function.</p> <p>Just pass on the arguments from your own decorator factory:</p> <pre><code>def my_custom_decorator(*args, **kwargs): # the factory def decorator(f): # the decorator @decorator_one(*args, **kwargs) @foo @bar def wrapped(): pass return wrapped return decorator </code></pre> <p>I used <code>*args, **kwargs</code> to pass on arbitrary arguments to the wrapped decorator factory <code>decorator_one()</code>, but you could also use explicitly named paramaters.</p>
4
2016-10-10T21:50:40Z
[ "python", "decorator", "python-decorators" ]
Propagating arguments to decorator which combines other decorators
39,967,240
<p>I have a scenario like:</p> <pre><code>@decorator_one(1) @foo @bar def my_decorated_func(): pass </code></pre> <p>I am trying to condense this into something like:</p> <pre><code>@my_custom_decorator(1) def my_decorated_func(): pass </code></pre> <p>This is straightforward if I have decorators that do not have <code>(1)</code> option:</p> <pre><code>def my_custom_decorator(f): @decorator_one @foo @bar def wrapped(): pass return wrapped </code></pre> <p>However I am uncertain how to properly propagate the argument to the first wrapper. </p> <p>In this case, I am comfortable assuming that if I pass 1 to my_custom_decorator that it will always and only be the arg for decorator_one.</p>
1
2016-10-10T21:46:11Z
39,968,096
<p>Yes, you need a decorator factory.</p> <p>I found the solution using a class more attractive because it separates the factory and the decorator:</p> <pre><code>class my_custom_decorator(object): __init__(self, *args, **kwargs): # the factory self.args = args self.kwargs = kwargs __call__(self, f): # the decorator @decorator_one(*self.args, **self.kwargs) @foo @bar def wrapped(): pass return wrapped </code></pre>
0
2016-10-10T23:09:24Z
[ "python", "decorator", "python-decorators" ]
Virtualenv within single executable
39,967,250
<p>I currently have an executable file that is running Python code inside a zipfile following this: <a href="https://blogs.gnome.org/jamesh/2012/05/21/python-zip-files/" rel="nofollow">https://blogs.gnome.org/jamesh/2012/05/21/python-zip-files/</a></p> <p>The nice thing about this is that I release a single file containing the app. The problems arise in the dependencies. I have attempted to install files using pip in custom locations and when I embed them in the zip I always have import issues or issues that end up depending on host packages. </p> <p>I then started looking into virtual environments as a way to ensure package dependencies. However, it seems that the typical workflow on the target machine is to source the activation script and run the code within the virtualenv. What I would like to do is have a single file containing a Python script and all its dependencies and for the user to just execute the file. Is this possible given that the Python interpreter is actually packaged with the virtualenv? Is it possible to invoke the Python interpreter from within the zip file? What is the recommended approach for this from a Python point of view?</p>
0
2016-10-10T21:46:44Z
39,967,509
<p>You can create a bash script that creates the virtual env and runs the python scripts aswell. </p> <pre><code>!#/bin/bash virtualenv .venv .venv/bin/pip install &lt;python packages&gt; .venv/bin/python script </code></pre>
0
2016-10-10T22:08:21Z
[ "python", "linux", "virtualenv", "executable" ]
Python: Remove a portion of a string from a list of strings
39,967,304
<p>I used xlrd to extract a column from an excel sheet to make into a list.</p> <pre><code>from xlrd import open_workbook book = xlrd.open_workbook("HEENT.xlsx").sheet_by_index(0) med_name = [] for row in sheet.col(2): med_name.append(row) med_school = [] for row in sheet.col(3): med_school.append(row) print(med_school) </code></pre> <p>Below is a snippet of the list: med_school.</p> <pre><code>[text:'University of San Francisco', text: 'Harvard University', text:'Class of 2016, University of Maryland School of Medicine', text:'Class of 2015, Johns Hopkins University School of Medicine', text:'Class of 2014, Raymond and Ruth Perelman School of Medicine at the University of Pennsylvania'] </code></pre> <p>I want to remove "text:'Class of 2014" from each string in the list. I tried list comprehension, but I got an attribute error: 'Cell' object has no attribute 'strip'. Does anyone know of a way to create a list of medical school names that have just the medical school names without the class year and the word "text"?</p>
0
2016-10-10T21:51:27Z
39,967,409
<p>Use the given separator to cut off the head of each string. Check first to make sure it has "Class", so we know the comma-space is there.</p> <pre><code>med_school = ["text:'Class of 2016, University of Maryland School of Medicine'", "text:'Class of 2015, Johns Hopkins University School of Medicine'", "text:'Class of 2014, Raymond and Ruth Perelman School of Medicine at the University of Pennsylvania'", "text:'Class of 1989, Rush Medical School / Knox College'", "text:'Bernie\'s Back-Alley School of Black-Market Techniques'" ] school_name = [] for first in med_school: name = first.value if ", " in name: cut = name.index(", ") name = name[cut+2:] else: name = name[6:-1] school_name.append(name) print school_name </code></pre> <p>output (with extra line feeds to improve readability):</p> <pre><code>["University of Maryland School of Medicine'", "Johns Hopkins University School of Medicine'", "Raymond and Ruth Perelman School of Medicine at the University of Pennsylvania'" "Rush Medical School / Knox College'", "Bernie's Back-Alley School of Black-Market Techniques"] </code></pre> <p>You could also wrap the loop into a list comprehension:</p> <pre><code>school_name = [name.value[name.value.index(", ")+2:] \ if ", " in name \ else name[6:-1] \ for name in med_school] </code></pre>
1
2016-10-10T22:00:46Z
[ "python", "xlrd" ]
Python: Remove a portion of a string from a list of strings
39,967,304
<p>I used xlrd to extract a column from an excel sheet to make into a list.</p> <pre><code>from xlrd import open_workbook book = xlrd.open_workbook("HEENT.xlsx").sheet_by_index(0) med_name = [] for row in sheet.col(2): med_name.append(row) med_school = [] for row in sheet.col(3): med_school.append(row) print(med_school) </code></pre> <p>Below is a snippet of the list: med_school.</p> <pre><code>[text:'University of San Francisco', text: 'Harvard University', text:'Class of 2016, University of Maryland School of Medicine', text:'Class of 2015, Johns Hopkins University School of Medicine', text:'Class of 2014, Raymond and Ruth Perelman School of Medicine at the University of Pennsylvania'] </code></pre> <p>I want to remove "text:'Class of 2014" from each string in the list. I tried list comprehension, but I got an attribute error: 'Cell' object has no attribute 'strip'. Does anyone know of a way to create a list of medical school names that have just the medical school names without the class year and the word "text"?</p>
0
2016-10-10T21:51:27Z
39,967,440
<p>The <code>xlrd</code> does not return you strings, it returns you instances of a class called <code>Cell</code>. This has a property <code>value</code> that contains the string you are seeing. </p> <p>To modify these simply:</p> <pre><code>for cell in med_school: cell.value = cell.value[:15] </code></pre> <p>This will remove the first 15 characters ("Class of 2014, "). Alternatively you could use other approaches like string splitting (on ",") or a regex.</p> <p>The point here is that you shouldn't be working directly on the values in the <code>med_schools</code> list, but on their <code>.value</code> property. Or extract it to somewhere else you could work on it.</p> <p>For example, to get all of the text properties, dropping the prefix:</p> <pre><code>values = [cell.value[15:] for cell in med_schools] </code></pre> <p>Or using a regex to replace to replace only those actualling containing the offending data</p> <pre><code>values = [re.sub(r"^Class of \d{4}, ", "", cell.value) for cell in med_schools] </code></pre>
4
2016-10-10T22:02:40Z
[ "python", "xlrd" ]
Python Nested List Comprehension Error
39,967,377
<p>I'm trying to convert a normal nested iteration into a nest list comp and I'm having trouble.</p> <pre><code>for k in r.json()['app_list']: for i in titles: if k['name'] == i['name'] and k['platform'] == i['platform']: array.append(session.get(k['api_url'], headers=headers).json()) return array </code></pre> <p>Works fine, however</p> <pre><code>return [session.get(k['api_url'], headers=headers).json() for i in titles for k in r.json() if k['name'] == i['name'] and k['platform'] == i['platform']] </code></pre> <p>throws this error</p> <pre><code>if k['name'] == i['name'] and k['platform'] == i['platform']] TypeError: string indices must be integers </code></pre>
-1
2016-10-10T21:57:28Z
39,967,401
<p>You have your nesting order wrong and you forgot to get the <code>'app_list'</code> key from the <code>r.json()</code> dictionary.</p> <p>List comprehension loops are still listed in the same order, left to right as you nest them. In other words, use the <em>same order</em> as your original nested <code>for</code> statements:</p> <pre><code>return [session.get(k['api_url'], headers=headers).json() for k in r.json()['app_list'] for i in titles if k['name'] == i['name'] and k['platform'] == i['platform']] </code></pre> <p>The above was reached simply by putting everything in the <code>array.append()</code> call <em>at the front</em>, then removing the <code>:</code> colons from the <code>for</code> and <code>if</code> statements and putting the result inside <code>[...]</code> square brackets.</p> <p>You forgot the <code>['app_list']</code> subscription to the <code>r.json()</code>, and that's the actual cause of the exception; <code>r.json()</code> produces a dictionary, so each <code>k</code> was bound to a <em>key</em> from that dictionary, making the <code>k['name']</code> subscription fail.</p>
2
2016-10-10T22:00:30Z
[ "python", "list-comprehension" ]
Python elif not working in order I want
39,967,410
<p><code>Transaction_Code</code> == <code>"W"</code>, <code>"w"</code>, <code>"D"</code> or <code>"d"</code></p> <p>if not, it should be running <code>Process_Invalid_Code(Previous_Balance)</code></p> <p>What is happening, however is if input for <code>Transaction_Code</code> != <code>"W"</code>, <code>"w"</code>, <code>"D"</code> or <code>"d"</code>, it then continues to run the <code>"What is your previous balance?"</code> and <code>"How much is the transaction amount?"</code> input... </p> <p>ONLY THEN, after you give input for those does it run <code>Invalid_Transaction_Code</code></p> <p>What I WANT to happen is for it to throw <code>Invalid_Transaction_Code ("Invalid Transaction Code!")</code> etc. BEFORE without wasting the users time asking for Previous Balance and Transaction..</p> <p>Does that make sense?</p> <p>Here is the code</p> <pre><code>#The main function definition def main(): Name = input("What is your name? ") Account_ID = input("What is your account ID? ") Transaction_Code = input("Press W or w for Withdrawal, Press D or d for Deposit: ") Previous_Balance = float(input("What is your previous balance? ")) Transaction_Amount = float(input("How much is the transaction amount? ")) if Transaction_Code == "W" or Transaction_Code == "w": Withdrawal_Process(Previous_Balance, Transaction_Amount) elif Transaction_Code == "D" or Transaction_Code == "d": Deposit_Process(Previous_Balance, Transaction_Amount) else: Process_Invalid_Code(Previous_Balance) #Defines the Deposit Process def Deposit_Process(Previous_Balance, Transaction_Amount): New_Balance = Transaction_Amount + Previous_Balance Print_Function(New_Balance) #Defines the Withdrawal Process def Withdrawal_Process(Previous_Balance, Transaction_Amount): if Transaction_Amount &gt; Previous_Balance: print("Invalid Transaction: Not Sufficient Funds!") New_Balance = Previous_Balance Print_Function(New_Balance) else: New_Balance = Previous_Balance - Transaction_Amount Print_Function(New_Balance) #The Invalid Code Function Definition def Process_Invalid_Code(Previous_Balance): New_Balance = Previous_Balance print ("Invalid Transaction Code!") print ("Please type W or w for Withdrawal") print ("or type D or d for Deposit") Print_Function(New_Balance) #Defines the Print Function def Print_Function(New_Balance): print ("Your balance is now $", format(New_Balance, '.2f')) #Call the main function main() </code></pre>
0
2016-10-10T22:00:53Z
39,967,634
<p>Since all of your desired actions need <code>Previous_Balance</code> you must ask for it in any case:</p> <pre><code>def main(): # never used, lets ask anyway Name = input("What is your name? ") # we need this information at a minimum Previous_Balance = float(input("What is your previous balance? ")) Transaction_Code = input("Press W or w for Withdrawal, Press D or d for Deposit: ") # if its a withdrawal/deposit, find the amount and account if Transaction_Code.upper() in "WD": # we never use this Account_ID ... Account_ID = input("What is your account ID? ") Transaction_Amount = float(input("How much is the transaction amount? ")) if Transaction_Code.upper() == "W": Withdrawal_Process(Previous_Balance, Transaction_Amount) else: Deposit_Process(Previous_Balance, Transaction_Amount) else: # they've entered a bad code Process_Invalid_Code(Previous_Balance) </code></pre>
4
2016-10-10T22:21:19Z
[ "python" ]
Python elif not working in order I want
39,967,410
<p><code>Transaction_Code</code> == <code>"W"</code>, <code>"w"</code>, <code>"D"</code> or <code>"d"</code></p> <p>if not, it should be running <code>Process_Invalid_Code(Previous_Balance)</code></p> <p>What is happening, however is if input for <code>Transaction_Code</code> != <code>"W"</code>, <code>"w"</code>, <code>"D"</code> or <code>"d"</code>, it then continues to run the <code>"What is your previous balance?"</code> and <code>"How much is the transaction amount?"</code> input... </p> <p>ONLY THEN, after you give input for those does it run <code>Invalid_Transaction_Code</code></p> <p>What I WANT to happen is for it to throw <code>Invalid_Transaction_Code ("Invalid Transaction Code!")</code> etc. BEFORE without wasting the users time asking for Previous Balance and Transaction..</p> <p>Does that make sense?</p> <p>Here is the code</p> <pre><code>#The main function definition def main(): Name = input("What is your name? ") Account_ID = input("What is your account ID? ") Transaction_Code = input("Press W or w for Withdrawal, Press D or d for Deposit: ") Previous_Balance = float(input("What is your previous balance? ")) Transaction_Amount = float(input("How much is the transaction amount? ")) if Transaction_Code == "W" or Transaction_Code == "w": Withdrawal_Process(Previous_Balance, Transaction_Amount) elif Transaction_Code == "D" or Transaction_Code == "d": Deposit_Process(Previous_Balance, Transaction_Amount) else: Process_Invalid_Code(Previous_Balance) #Defines the Deposit Process def Deposit_Process(Previous_Balance, Transaction_Amount): New_Balance = Transaction_Amount + Previous_Balance Print_Function(New_Balance) #Defines the Withdrawal Process def Withdrawal_Process(Previous_Balance, Transaction_Amount): if Transaction_Amount &gt; Previous_Balance: print("Invalid Transaction: Not Sufficient Funds!") New_Balance = Previous_Balance Print_Function(New_Balance) else: New_Balance = Previous_Balance - Transaction_Amount Print_Function(New_Balance) #The Invalid Code Function Definition def Process_Invalid_Code(Previous_Balance): New_Balance = Previous_Balance print ("Invalid Transaction Code!") print ("Please type W or w for Withdrawal") print ("or type D or d for Deposit") Print_Function(New_Balance) #Defines the Print Function def Print_Function(New_Balance): print ("Your balance is now $", format(New_Balance, '.2f')) #Call the main function main() </code></pre>
0
2016-10-10T22:00:53Z
39,967,764
<p>You may want to also try and use raw_input() as oppose to input() where necessary or cast the output using <code>variable_name</code> to get rid of tracback error.</p>
1
2016-10-10T22:33:44Z
[ "python" ]
Using Pandas to Create DateOffset of Paydays
39,967,460
<p>I'm trying to use Pandas to create a time index in Python with entries corresponding to a recurring payday. Specifically, I'd like to have the index correspond to the first and third Friday of the month. Can somebody please give a code snippet demonstrating this?</p> <p>Something like:</p> <pre><code>import pandas as pd idx = pd.date_range("2016-10-10", periods=26, freq=&lt;offset here?&gt;) </code></pre>
2
2016-10-10T22:04:43Z
39,967,582
<p>try this:</p> <pre><code>In [6]: pd.date_range("2016-10-10", periods=26, freq='WOM-1FRI').union(pd.date_range("2016-10-10", periods=26, freq='WOM-3FRI')) Out[6]: DatetimeIndex(['2016-10-21', '2016-11-04', '2016-11-18', '2016-12-02', '2016-12-16', '2017-01-06', '2017-01-20', '2017-02-03', '2017-02-17', '2017-03-03', '2017-03-17', '2017-04-07', '2017-04-21', '2017-05-05', '2017-05-19', '2017-06-02', '2017-06-16', '2017-07-07', '2017-07-21', '2017-08-04', '2017-08-18', '2017-09-01', '2017-09-15', '2017-10-06', '2017-10-20', '2017-11-03', '2017-11-17', '2017-12-01', '2017-12-15', '2018-01-05', '2018-01-19', '2018-02-02', '2018-02-16', '2018-03-02', '2018-03-16', '2018-04-06', '2018-04-20', '2018-05-04', '2018-05-18', '2018-06-01', '2018-06-15', '2018-07-06', '2018-07-20', '2018-08-03', '2018-08-17', '2018-09-07', '2018-09-21', '2018-10-05', '2018-10-19', '2018-11-02', '2018-11-16', '2018-12-07'], dtype='datetime64[ns]', freq=None) </code></pre>
2
2016-10-10T22:15:46Z
[ "python", "pandas" ]
Capture semantic version in django url
39,967,532
<p>I have the following url <code> http://localhost:8000/api/package/printf/release/v0.0.1 </code></p> <p>I need to capture the version at the end. What is the right way for the same. The url regex that i have now is</p> <p><code> /package/(?P&lt;pk&gt;[a-z]+)/release/(?P&lt;version[a-z]+)/$ </code></p> <p>The semantic version should be passed as a single parameter and not as multiple int with <code>major</code> and <code>minor</code> version etc as different parameters.</p>
0
2016-10-10T22:11:04Z
39,967,569
<p>You may rely on negated character class <code>[^/]</code> (that matches any character but <code>/</code>) and also make the last <code>/</code> optional by adding a <code>?</code> (1 or 0 occurrences) quantifier after it:</p> <pre><code>/package/(?P&lt;pk&gt;[^/]+)/release/(?P&lt;version&gt;[^/]+)/?$ </code></pre> <p>See the <a href="https://regex101.com/r/UZQFPd/1" rel="nofollow">regex demo</a></p>
1
2016-10-10T22:14:43Z
[ "python", "regex", "django" ]
Capture semantic version in django url
39,967,532
<p>I have the following url <code> http://localhost:8000/api/package/printf/release/v0.0.1 </code></p> <p>I need to capture the version at the end. What is the right way for the same. The url regex that i have now is</p> <p><code> /package/(?P&lt;pk&gt;[a-z]+)/release/(?P&lt;version[a-z]+)/$ </code></p> <p>The semantic version should be passed as a single parameter and not as multiple int with <code>major</code> and <code>minor</code> version etc as different parameters.</p>
0
2016-10-10T22:11:04Z
39,967,762
<p>Looks to me like you are close. Just need to tweak your regex a bit:</p> <pre><code>/package/(?P&lt;pk&gt;[a-z]+)/release/(?P&lt;version&gt;v\d{1,2}\.\d{1,2}\.\d{1,2})/?$ </code></pre> <p>This would match any version that has three digits, and each one being either 1 or 2 numbers. For example:</p> <pre><code>v0.0.1 # True v1.0.10 # True v99.99.99 # True v1.0 # False </code></pre> <p>Depending on your requirements, you can tweak this to your specifications. I just took a guess based upon your URL above.</p>
1
2016-10-10T22:33:20Z
[ "python", "regex", "django" ]
does groupby concatenate the columns?
39,967,540
<p>i have a "1000 rows * 4 columns" DataFrame:</p> <pre><code>a b c d 1 aa 93 4 2 bb 32 3 ... 1000 nn 78 2 **[1283 rows x 4 columns]** </code></pre> <p>and I use groupby to group them based on 3 of the columns:</p> <pre><code>df.groupby(['a','b','c']).sum() print(df) a b c d 1 aa 93 12 2 bb 32 53 ... 1000 nn 78 38 **[1283 rows x 1 columns]** </code></pre> <p>however the result give me a "1000 rows * 1 columns" Dataframe. SO my question is if Groupby concatenate columns as one Column? if yes how can I prevent that. I want to plot my data after grouping it but i can't since it only see one column instead of all 4.</p> <p>edit: when i call the columns i only get the last column, it means it can't read 'a','b','c' as columns, why is that and how can i markl them as column again.</p> <pre><code>df.columns Index([u'd'], dtype='object') </code></pre>
-1
2016-10-10T22:11:54Z
39,967,706
<p>you can do it this way:</p> <pre><code>df.groupby(['a','b','c'], as_index=False).sum() </code></pre> <p>or:</p> <pre><code>df.groupby(['a','b','c']).sum().reset_index() </code></pre>
1
2016-10-10T22:28:36Z
[ "python", "pandas" ]
Efficiently creating a Pandas DataFrame Column that contains the instance number of a value in another column
39,967,568
<p>Assume that you have a Pandas column with the following information:</p> <pre><code>&gt;&gt; df num 0 0 1 1 2 1 3 2 4 3 5 3 </code></pre> <p>The column to the left of the num column is the index column. I want to create an instance column that tells me what instance of num appears. This is the outcome that I want:</p> <pre><code>&gt;&gt; df num instance 0 0 1 1 1 1 2 1 2 3 2 1 4 3 1 5 3 2 </code></pre> <p>Here's the code that I wrote to do this:</p> <pre><code>&gt;&gt; my_list = [] &gt;&gt; for index, row in df.iterrows(): &gt;&gt; my_list.append(df.loc[index,'num']) &gt;&gt; # The IF condition is done to prevent my_list from growing too big. &gt;&gt; if len(my_list)&gt;1: &gt;&gt; if my_list[len(my_list)-1] == my_list[len(my_list)-2]: &gt;&gt; del my_list[:len(my_list)-2] &gt;&gt; my_list['instance'] = len([element for element in my_list if \ element == df.loc[index,'num']) </code></pre> <p>This code works perfectly for small DataFrames, but it takes an exorbitantly long amount of time to complete when the num column consists of several million lines. Is there a way of creating the instance column in the manner that I'm thinking without using .iterrows()?</p>
1
2016-10-10T22:14:39Z
39,967,617
<p>try this:</p> <pre><code>In [11]: df['instance'] = df.groupby('num').cumcount()+1 In [12]: df Out[12]: num instance 0 0 1 1 1 1 2 1 2 3 2 1 4 3 1 5 3 2 </code></pre>
1
2016-10-10T22:19:20Z
[ "python", "pandas", "dataframe" ]
Efficiently creating a Pandas DataFrame Column that contains the instance number of a value in another column
39,967,568
<p>Assume that you have a Pandas column with the following information:</p> <pre><code>&gt;&gt; df num 0 0 1 1 2 1 3 2 4 3 5 3 </code></pre> <p>The column to the left of the num column is the index column. I want to create an instance column that tells me what instance of num appears. This is the outcome that I want:</p> <pre><code>&gt;&gt; df num instance 0 0 1 1 1 1 2 1 2 3 2 1 4 3 1 5 3 2 </code></pre> <p>Here's the code that I wrote to do this:</p> <pre><code>&gt;&gt; my_list = [] &gt;&gt; for index, row in df.iterrows(): &gt;&gt; my_list.append(df.loc[index,'num']) &gt;&gt; # The IF condition is done to prevent my_list from growing too big. &gt;&gt; if len(my_list)&gt;1: &gt;&gt; if my_list[len(my_list)-1] == my_list[len(my_list)-2]: &gt;&gt; del my_list[:len(my_list)-2] &gt;&gt; my_list['instance'] = len([element for element in my_list if \ element == df.loc[index,'num']) </code></pre> <p>This code works perfectly for small DataFrames, but it takes an exorbitantly long amount of time to complete when the num column consists of several million lines. Is there a way of creating the instance column in the manner that I'm thinking without using .iterrows()?</p>
1
2016-10-10T22:14:39Z
39,967,633
<p>You can <code>groupby</code> on 'num' column and call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rank.html" rel="nofollow"><code>rank</code></a> with param <code>method=dense'</code>:</p> <pre><code>In [5]: df['instance'] = df.groupby('num').transform(lambda x: x.rank(method='dense')) df Out[5]: num instance 0 0 1 1 1 1 2 1 2 3 2 1 4 3 1 5 3 2 </code></pre>
0
2016-10-10T22:21:11Z
[ "python", "pandas", "dataframe" ]
Formatting loop for strings
39,967,583
<p>I'm having trouble formatting the strings below. Trying to keep the message centered with the borders, but having a hard time executing it. Below is what output I want and below that is my code I have so far. Note: I need to have a space on the left and right columns of the longest line and I need to utilize the split() func.</p> <pre><code>+---------------+ | STOP! | | DANGER AHEAD | | Drive Safely! | +---------------+ def border_sign(note): letter_count = 0 for i in note: letter_count += 1 return "+-------+\n| {} |\n+-------+\n".format(note) border_sign("STOP\nDANGER AHEAD\nDrive safely!") </code></pre>
0
2016-10-10T22:15:51Z
39,967,679
<p>Split the string into separate lines, then center each line. Remember to either print each line immediately within the function, build up a list, or yield each line rather than returning after the first line. You can also determine and use a calculated width rather than a static value.</p> <pre><code>def border_sign(note): note = note.splitlines() m = len(max(note, key=len)) yield ('-'*m).join('++') for line in note: yield ("|{:^%d}|" % m).format(line) yield ('-'*m).join('++') print(*border_sign("STOP\nDANGER AHEAD\nDrive safely!"), sep='\n') </code></pre>
2
2016-10-10T22:25:22Z
[ "python", "function", "python-3.x" ]
Formatting loop for strings
39,967,583
<p>I'm having trouble formatting the strings below. Trying to keep the message centered with the borders, but having a hard time executing it. Below is what output I want and below that is my code I have so far. Note: I need to have a space on the left and right columns of the longest line and I need to utilize the split() func.</p> <pre><code>+---------------+ | STOP! | | DANGER AHEAD | | Drive Safely! | +---------------+ def border_sign(note): letter_count = 0 for i in note: letter_count += 1 return "+-------+\n| {} |\n+-------+\n".format(note) border_sign("STOP\nDANGER AHEAD\nDrive safely!") </code></pre>
0
2016-10-10T22:15:51Z
39,967,710
<p>Quick sample to consider, not production ready code:</p> <pre><code>def border_sign(note): rows = note.splitlines() mlen = len(max(rows, key=len)) print "+" + "-" * (2+mlen) + "+" for row in rows: print ("| {:^"+str(mlen)+"} |").format(row) print "+" + "-" * (2+mlen) + "+" </code></pre>
1
2016-10-10T22:29:01Z
[ "python", "function", "python-3.x" ]
Formatting loop for strings
39,967,583
<p>I'm having trouble formatting the strings below. Trying to keep the message centered with the borders, but having a hard time executing it. Below is what output I want and below that is my code I have so far. Note: I need to have a space on the left and right columns of the longest line and I need to utilize the split() func.</p> <pre><code>+---------------+ | STOP! | | DANGER AHEAD | | Drive Safely! | +---------------+ def border_sign(note): letter_count = 0 for i in note: letter_count += 1 return "+-------+\n| {} |\n+-------+\n".format(note) border_sign("STOP\nDANGER AHEAD\nDrive safely!") </code></pre>
0
2016-10-10T22:15:51Z
39,968,980
<pre><code>def border_sign(x): splitted = x.splitlines() M = max(map(len,splitted)) horiz = '+-%s-+' % (M*'-') patiz = '| {0: ^%d} |' % M print(horiz,*map(patiz.format,splitted), horiz, sep='\n') border_sign("STOP\nDANGER AHEAD\nDrive safely!") </code></pre> <p><code>patiz.format</code> is a function, then can be used in <code>map</code></p>
0
2016-10-11T01:03:44Z
[ "python", "function", "python-3.x" ]
create a graph with too many edges
39,967,599
<p>I have 100 nodes and 4950 edges. What is the fastest way to create a graph in Python (not planning at all to visualize or draw it) so that I can have access to node information so that I would need what each item in the 2d matrix mean by saying node 1 is connected to node 3? (also I don't need to save it as matrix).</p> <pre><code>import gensim import nltk from gensim.models import word2vec from nltk.corpus import stopwords import logging import re import itertools import glob from collections import defaultdict import networkx as nx logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) sentences = word2vec.Text8Corpus("/home/mona/mscoco/text8") model = word2vec.Word2Vec(sentences, workers = 16) #model.init_sims(replace = True) model_name = "text8_data" model.save(model_name) stopwords = nltk.corpus.stopwords.words('english') path = "/home/mona/mscoco/caption_files/*.txt" files = glob.glob(path) adj_list = defaultdict(lambda: defaultdict(lambda: 0)) for file in files: g.add_nodes(file) for file1, file2 in itertools.combinations(files, 2): with open(file1) as f1: f1_text = f1.read() f1_words = re.sub("[^a-zA-Z]", ' ', f1_text).lower().split() f1_words = [w for w in f1_words if w not in stopwords] print(f1_text) f1.close() with open(file2) as f2: f2_text = f2.read() f2_words = re.sub("[^a-zA-Z]", ' ', f2_text).lower().split() f2_words = [w for w in f2_words if w not in stopwords] print(f2_text) f2.close() print('{0}: {1}: {2}'.format(file1, file2, model.wmdistance(f1_words, f2_words))) g.add_edge(file1, file2, model.wmdistance(f1_words, f2_words)) print(g.number_of_edges()) print(g.number_of_edges()) nx.write_gml(g, "gensim.gml") </code></pre> <p>Please let me know if you have better suggestion that my current code. I will eventually have something like 20 nodes and 190 edges. I am mostly looking for something that processing its output would be easy to another program like MATLAB. I am not sure if .gml files are easy to process in MATLAB.</p>
0
2016-10-10T22:18:01Z
39,967,984
<p>I think generating a GML file for the precise purpose of reusing in Matlab is probably fine. This question has some more information about that.</p> <p><a href="http://stackoverflow.com/questions/15918791/convert-gml-file-to-adjacency-matrix-in-matlab#15919696">Convert GML file to adjacency matrix in matlab</a></p>
1
2016-10-10T22:57:19Z
[ "python", "graph", "networkx" ]
"type" object is not subscriptable error in Python Selenium
39,967,608
<p>I'm a newbie to Python Selenium environment. This is my piece of code.</p> <pre><code>from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait import unittest class LoginTest(unittest.TestCase): def setUp(self): self.driver= webdriver.Firefox() self.driver.get("https://www.facebook.com/") def test_Login(self): driver=self.driver facebookUsername ="somoe@gmail.com" facebookPassword ="basabasa" emailFieldID = "email" passFieldID = "pass" loginButtonXpath = "//input[@value= 'Log In']" fbLogoXpath = "(//a[contains(href , 'logo')])[1]" emailFieldElement = WebDriverWait[driver, 10].until(lambda driver:driver.find_element_by_id(emailFieldID)) passwordFieldElement = WebDriverWait[driver, 10].until(lambda driver:driver.find_element_by_id(passFieldID)) loginButtonElement = WebDriverWait[driver, 10].until(lambda driver:driver.find_element_by_xpath(loginButtonXpath)) emailFieldElement.clear() emailFieldElement.send_keys(facebookUsername) passFieldElement.clear() passFieldElement.send_keys(facebookPassword) loginButtonElement.click() loginButtonElement=WebDriverWait[driver, 10].until(lambda driver : driver.find_element_by_xpath(fbLogoXpath)) def tearDown(self): self.driver.quit() if __name__=='__main__': unittest.main() </code></pre> <p>This code loads Facebook when it runs but does not autofill the email and password area and returns with the error mentioned above. </p>
-3
2016-10-10T22:18:30Z
39,967,658
<p>You're trying to index a <code>WebDriverWait</code> object instead of initializing it. </p> <p>You should replace all the:</p> <pre><code>WebDriverWait[driver, 10] </code></pre> <p>with</p> <pre><code>WebDriverWait(driver, 10) # ^ ^ </code></pre> <hr> <p>Reference:</p> <p><a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">Selenium explicit waits</a></p>
2
2016-10-10T22:22:50Z
[ "python", "python-3.x", "selenium" ]
ValueError: need more than 3 values to unpack when using optimize.minimize
39,967,614
<p>I'm pretty new to python and I got stuck on this: I'd like to use <code>scipy.optimize.minimize</code> to maximize a function and I'm having some problem with the extra arguments of the function I defined.</p> <p>I looked for a solution in tons of answered questions but I can't find anything that solves my problem. I saw in <a href="http://stackoverflow.com/questions/19843752/structure-of-inputs-to-scipy-minimize-function">Structure of inputs to scipy minimize function</a> how to pass extra arguments that one wants to be constant in the minimization of the function and my code seems fine to me from this point of view.</p> <p>This is my code:</p> <pre><code>import numpy as np from scipy.stats import pearsonr import scipy.optimize as optimize def min_pears_function(a,exp): (b,c,d,e)=a return (1-(pearsonr(b + exp[0] * c + exp[1] * d + exp[2],e)[0])) a = (log_x,log_y,log_t,log_z) # where log_x, log_y, log_t and log_z are numpy arrays with same length guess_PF=[0.6,2.0,0.2] res = optimize.minimize(min_pears_function, guess_PF, args=(a,), options={'xtol': 1e-8, 'disp': True}) </code></pre> <p>When running the code I get the following error:</p> <blockquote> <p>ValueError: need more than 3 values to unpack</p> </blockquote> <p>But I can't see what needed argument I'm missing. The function seems to work fine, so I guess the problem is in <code>optimize.minimize</code> call?</p>
0
2016-10-10T22:19:17Z
39,967,745
<p>Your error occurs here:</p> <pre><code>def min_pears_function(a,exp): # XXX: This is your error line (b,c,d,e)=a return (1-(pearsonr(b + exp[0] * c + exp[1] * d + exp[2],e)[0])) </code></pre> <p>This is because:</p> <ul> <li>the initial value you pass to <code>optimize.minimize</code> is <code>guessPF</code> which has just three values (<code>[0.6,2.0,0.2]</code>). </li> <li>this initial value is passed to <code>min_pears_function</code> as the variable <code>a</code>. </li> </ul> <p>Did you mean for it to be passed as <code>exp</code>? Is it <code>exp</code> you wish to solve for? In that case, redefine the signature as:</p> <pre><code>def min_pears_function(exp, a): ... </code></pre>
0
2016-10-10T22:31:47Z
[ "python" ]
What is this doing in the Python lambda function?
39,967,638
<p>In the following Python script where "aDict" is a dictionary, what does "_: _[0]" do in the lambda function?</p> <pre><code>sorted(aDict.items(), key=lambda _: _[0]) </code></pre>
-1
2016-10-10T22:21:26Z
39,967,759
<p>In Python, lambda is used to create an anonymous function. The first underscore in your example is simply the argument to the lambda function. After the colon (i.e. function signature), the <code>_[0]</code> retrieves the first element of the variable <code>_</code>.</p> <p>Admittedly, this can be confusing; the lambda component of your example could be re-written as <code>lambda x: x[0]</code> with the same result. Conventionally, though, underscore variable names in Python are used for "throwaway variables". In this case, it implies that the only thing we care about in each dictionary item is the key. Nuanced to a fault, perhaps.</p>
2
2016-10-10T22:33:05Z
[ "python", "sorting", "lambda", "key" ]
What is this doing in the Python lambda function?
39,967,638
<p>In the following Python script where "aDict" is a dictionary, what does "_: _[0]" do in the lambda function?</p> <pre><code>sorted(aDict.items(), key=lambda _: _[0]) </code></pre>
-1
2016-10-10T22:21:26Z
39,967,898
<p>In Python <code>_</code> (underscore) is a valid identifier and can be used as a variable name, e.g.</p> <pre><code>&gt;&gt;&gt; _ = 10 &gt;&gt;&gt; print(_) 10 </code></pre> <p>It can therefore also be used as the name of an argument to a lambda expression - which is like an unnamed function.</p> <p>In your example <code>sorted()</code> passes tuples produced by <code>aDict.items()</code> to its <code>key</code> function. The key function returns the first element of that tuple which <code>sorted()</code> then uses as the key, i.e that value to be compared with other values to determine the order.</p> <p>Note that, in this case, the same result can be produced without a key function because tuples are naturally sorted according to the first element, then the second element, etc. So </p> <pre><code>sorted(aDict.items()) </code></pre> <p>will produce the same result. Because dictionaries can not contain duplicate keys, the first element of each tuple is unique, so the second element is never considered when sorting.</p>
2
2016-10-10T22:47:38Z
[ "python", "sorting", "lambda", "key" ]
What is this doing in the Python lambda function?
39,967,638
<p>In the following Python script where "aDict" is a dictionary, what does "_: _[0]" do in the lambda function?</p> <pre><code>sorted(aDict.items(), key=lambda _: _[0]) </code></pre>
-1
2016-10-10T22:21:26Z
39,968,068
<p>Lets pick that apart.</p> <p>1) Suppose you have a dict, di:</p> <pre><code>di={'one': 1, 'two': 2, 'three': 3} </code></pre> <p>2) Now suppose you want each of its key, value pairs:</p> <pre><code> &gt;&gt;&gt; di.items() [('three', 3), ('two', 2), ('one', 1)] </code></pre> <p>3) Now you want to sort them (since dicts are unordered):</p> <pre><code>&gt;&gt;&gt; sorted(di.items()) [('one', 1), ('three', 3), ('two', 2)] </code></pre> <p>Notice that the tuples are sorted lexicographically -- by the text in the first element of the tuple. This is a equivalent to the <code>t[0]</code> of a series of tuples. </p> <p>Suppose you wanted it sorted by the number instead. You would you use a <code>key</code> function:</p> <pre><code>&gt;&gt;&gt; sorted(di.items(), key=lambda t: t[1]) [('one', 1), ('two', 2), ('three', 3)] </code></pre> <p>The statement you have <code>sorted(aDict.items(), key=lambda _: _[0])</code> is just using <code>_</code> as a variable name. It also does nothing, since <code>aDict.items()</code> produces tuples and if you did not use a key it sorts by the first element of the tuple anyway. The key function in your example is completely useless.</p> <p>There might be a use case for the form (other than for tuples) to consider. If you had strings instead, then you would be sorting by the first character and ignoring the rest:</p> <pre><code>&gt;&gt;&gt; li=['car','auto','aardvark', 'arizona'] &gt;&gt;&gt; sorted(li, key=lambda c:c[0]) ['auto', 'aardvark', 'arizona', 'car'] </code></pre> <p>Vs:</p> <pre><code>&gt;&gt;&gt; sorted(li) ['aardvark', 'arizona', 'auto', 'car'] </code></pre> <p>I still would not use <code>_</code> in the lambda however. The use of <code>_</code> is for a throway variable that has minimal chance of side-effects. Python has namespaces that mostly makes that worry not a real worry. </p> <p>Consider:</p> <pre><code>&gt;&gt;&gt; c=22 &gt;&gt;&gt; sorted(li, key=lambda c:c[0]) ['auto', 'aardvark', 'arizona', 'car'] &gt;&gt;&gt; c 22 </code></pre> <p>The value of <code>c</code> is preserved because of the local namespace inside the <code>lambda</code>. </p> <p><em>However</em> (under Python 2.x but not Python 3.x) this can be a problem:</p> <pre><code>&gt;&gt;&gt; c=22 &gt;&gt;&gt; [c for c in '123'] ['1', '2', '3'] &gt;&gt;&gt; c '3' </code></pre> <p>So the (light) convention became using <code>_</code> for a variable either in the case of a list comprehension or a tuple expansion, etc where you worry less about trampling on one of your names. The message is: If it is named <code>_</code>, I don't really care about it except right here...</p>
1
2016-10-10T23:05:37Z
[ "python", "sorting", "lambda", "key" ]
Exposing a class with a constructor containing a nested private class in constructor using Boost Python
39,967,640
<p>I'm new to Boost Python and I'm looking to expose a class that looks like this: </p> <pre><code>///Header File structure class A { public: A(); ~A(); void B(); private: class Impl; std::unique_ptr Impl impl_; }; ///Class Implementation class A::Impl { public: void C(); } A::A():impl_(new Impl) { } A::~A() { } void A::B() { void C(); } </code></pre> <p>Can someone suggest how to do it since the current methods I've tried gives errors since Impl is private and also an accessing already deleted function error:</p> <pre><code>BOOST_PYTHON_MODULE(libA) { class_&lt;A::Impl&gt;("Impl") .def("C", &amp;A::Impl::C) class_&lt;A&gt;("A",init&lt;std::unique_ptr&gt;) .def("B", &amp;A::B) } </code></pre>
-1
2016-10-10T22:21:29Z
39,967,689
<p>The whole point of the pimpl idiom is that it's private and completely transparent to the users of the class. You don't expose it.</p> <p>What you do need to do is make it clear that <code>A</code> isn't copyable:</p> <pre><code>class_&lt;A, noncopyable&gt;("A", init&lt;&gt;()) .def("B", &amp;A::B) ; </code></pre>
1
2016-10-10T22:26:59Z
[ "python", "c++", "class", "boost", "boost-python" ]
Python - Selenium : Scroll down not working because of PopUp
39,967,680
<p>I am writing a python script using selenium to login to Facebook and then do some scrapping. For that purpose, <strong>I have to scroll down to the bottom of the page. I think the pop that you can see in the picture is the cause of this.</strong> Here is the snippet of code which does the following thing</p> <pre><code>elem = driver.find_element_by_id("email") elem.send_keys(usr) elem = driver.find_element_by_id("pass") elem.send_keys(pwd) elem.send_keys(Keys.RETURN) driver.get("https://www.facebook.com/jatin.wadhwa.52/friends?source_ref=pb_friends_tl") time.sleep(10) element_new = driver.find_element_by_tag_name('html') element_new.send_keys(Keys.ESCAPE) element_new.send_keys(Keys.END) #driver.execute_script("window.scrollTo(0, 1000);") f = driver.find_elements_by_xpath("//ul") </code></pre> <p><a href="http://i.stack.imgur.com/ryA44.png" rel="nofollow"><img src="http://i.stack.imgur.com/ryA44.png" alt="Picture of Pop up on browser"></a></p>
0
2016-10-10T22:25:47Z
39,967,846
<p>Solved.</p> <p>Adding this will resolve and woulndt allow any such pop ups.</p> <pre><code> chrome_options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notifications" : 2} chrome_options.add_experimental_option("prefs",prefs) #driver = webdriver.Chrome(chrome_options=chrome_options) driver = webdriver.Chrome(r"C:\Users\jatin\Downloads\chromedriver_win32\chromedriver.exe",chrome_options=chrome_options) </code></pre>
1
2016-10-10T22:43:09Z
[ "python", "facebook", "selenium" ]
AttributeError: 'module' object has no attribute 'openssl_md_meth_names'
39,967,742
<p>I am calling a python script from another python script,irrespective of the output the python script I am calling I get the following error in <code>stderr</code>,I googled but couldn't find anything concrete,am clueless as to why am getting this error?does anyone have any idea on how to fix it?</p> <pre><code>Traceback (most recent call last): File "C:\Python27\lib\runpy.py", line 151, in _run_module_as_main mod_name, loader, code, fname = _get_module_details(mod_name) File "C:\Python27\lib\runpy.py", line 109, in _get_module_details return _get_module_details(pkg_main_name) File "C:\Python27\lib\runpy.py", line 101, in _get_module_details loader = get_loader(mod_name) File "C:\Python27\lib\pkgutil.py", line 464, in get_loader return find_loader(fullname) File "C:\Python27\lib\pkgutil.py", line 474, in find_loader for importer in iter_importers(fullname): File "C:\Python27\lib\pkgutil.py", line 430, in iter_importers __import__(pkg) File "C:\Python27\lib\site-packages\pip\__init__.py", line 14, in &lt;module&gt; from pip.utils import get_installed_distributions, get_prog File "C:\Python27\lib\site-packages\pip\utils\__init__.py", line 27, in &lt;module&gt; from pip._vendor import pkg_resources File "C:\Python27\lib\site-packages\pip\_vendor\pkg_resources\__init__.py", line 35, import email.parser File "C:\Python27\lib\email\parser.py", line 12, in &lt;module&gt; from email.feedparser import FeedParser File "C:\Python27\lib\email\feedparser.py", line 27, in &lt;module&gt; from email import message File "C:\Python27\lib\email\message.py", line 16, in &lt;module&gt; import email.charset File "C:\Python27\lib\email\charset.py", line 13, in &lt;module&gt; import email.base64mime File "C:\Python27\lib\email\base64mime.py", line 40, in &lt;module&gt; from email.utils import fix_eols File "C:\Python27\lib\email\utils.py", line 27, in &lt;module&gt; import random File "C:\Python27\lib\random.py", line 49, in &lt;module&gt; import hashlib as _hashlib File "C:\Python27\lib\hashlib.py", line 138, in &lt;module&gt; _hashlib.openssl_md_meth_names) AttributeError: 'module' object has no attribute 'openssl_md_meth_names' </code></pre>
0
2016-10-10T22:31:35Z
39,967,801
<p>Try to run <code>brew cleanup</code> and after that <code>brew postinstall python</code>. </p> <p>For more info see <a href="https://github.com/Homebrew/legacy-homebrew/issues/36346" rel="nofollow">this thread</a></p>
0
2016-10-10T22:37:39Z
[ "python" ]
python argparse in separate function inside a class and calling args from init
39,967,787
<p>I have a question regarding passing args to variables inside <strong>init</strong></p> <p>Here are my working version of code.</p> <pre><code>class A: def __init__(self): self.id = args.id self.pw = args.pw self.endpoint = args.endpoint def B: ..do something.. if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-i', '--id', type=str, help = 'username') parser.add_argument('-p', '--pw', type=str, help ='password') parser.add_argument('-e', '--end_point', type=str , help='end point of api') args = parser.parse_args() </code></pre> <p>The above code works, but what I am trying right now is to put all the argparse codes inside a function inside class A and assign arg to init. I looked in the web and I couldn't find a good solution.</p> <pre><code>class A: def __init__(self): self.id = self.parse_args(id) self.pw = self.parse_args(pw) self.endpoint = self.parse_args(endpoint) def B: ..do something.. def parse_args(self,args): parser = argparse.ArgumentParser() parser.add_argument('-i', '--id', type=str, help = 'username') parser.add_argument('-p', '--pw', type=str, help ='password') parser.add_argument('-e', '--end_point', type=str , help='end point of api') return parser.parse_args(args) </code></pre> <p>Ok, so to be exact, I'm not sure how I should approach this problem.</p> <p>In above example, I just called args.variable for args to work but in this case I call self.id = self.parse_args.id? </p> <p>parse_args function return args and I also tried self.id = self.parse_args(id) and this is giving me </p> <pre><code> TypeError: 'builtin_function_or_method' object is not iterable </code></pre> <p>The part of reason why I want to separate args into a separate function is to simplify my unit test with argparse.</p> <p>Any help will be appreciated.</p>
0
2016-10-10T22:36:00Z
39,967,973
<p>So in the first case, you must be doing</p> <pre><code>if __name__ ... .... args = parser.parse_args() a = A() </code></pre> <p>The <code>A.__init__</code> can see <code>args</code> because it is global.</p> <p>I'm don't see why you'd want to make the argparse code part of <code>A</code>; you don't want it to run every time you use <code>A()</code> do you? You could only make one set of values.</p> <p>I think it would be test to make the <code>parse_args</code> code a method, that can be run, at will, after creating the class.</p> <p>Here's an approach that has, I think, pretty good flexibility:</p> <pre><code>import argparse class A: def __init__(self, id=None, pw=None, endpoint=None): self.id = id self.pw = pw self.endpoint = endpoint def parse_args(self, argv=None): parser = argparse.ArgumentParser() parser.add_argument('-i', '--id', type=str, help = 'username') parser.add_argument('-p', '--pw', type=str, help ='password') parser.add_argument('-e', '--end_point', type=str , help='end point of api') args = parser.parse_args(argv) self.id = args.id self.pw = args.pw self.endpoint = args.end_point def __str__(self): return 'A(%s,...)'%self.id if __name__ == "__main__": a = A() print(a) a.parse_args() print(a) b = A(id='you') print(b) b.parse_args(['--id','me']) print(b) </code></pre> <p>Values can be set during object creation, from commandline or from custom argv</p> <pre><code>1610:~/mypy$ python stack39967787.py --id joe A(None,...) A(joe,...) A(you,...) A(me,...) </code></pre> <p>==================</p> <p>My 1st method (temporarily deleted)</p> <pre><code>class A(): def __init__(self): args = self.parse_args() self.a = args.a etc @static_method def parse_args(self): parser = .... return parser.parse_args() </code></pre> <p>=====================</p> <p>Your <code>class A</code> could be used as <code>Namespace</code>, letting <code>parse_args</code> update the artributes directly (it uses <code>setattr</code>.</p> <pre><code>import argparse class A: def __init__(self, id=None, pw=None, endpoint=None): self.id = id self.pw = pw self.endpoint = endpoint if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('-i', '--id', type=str, help = 'username') parser.add_argument('-p', '--pw', type=str, help ='password') parser.add_argument('-e', '--endpoint', type=str , help='end point of api') args = parser.parse_args() print(args) a = A() parser.parse_args(namespace=a) print(vars(a)) </code></pre> <p>producing:</p> <pre><code>1719:~/mypy$ python stack39967787_1.py --id joe --pw=xxxx -e1 Namespace(endpoint='1', id='joe', pw='xxxx') {'endpoint': '1', 'id': 'joe', 'pw': 'xxxx'} </code></pre>
1
2016-10-10T22:56:29Z
[ "python", "function", "class", "argparse" ]
How to convert a string into a list without including a specific character plus without using replace and split methods?
39,967,795
<p>Let's say you have:</p> <pre><code>x = "1,2,13" </code></pre> <p>and you want to achieve:</p> <pre><code>list = ["1","2","13"] </code></pre> <p>Can you do it without the split and replace methods?</p> <p>What I have tried:</p> <pre><code>list=[] for number in x: if number != ",": list.append(number) print(list) # ['1', '2', '1', '3'] </code></pre> <p>but this works only if its a single digit</p>
0
2016-10-10T22:36:56Z
39,967,919
<p>Here is a way using that assumes integers using <code>itertools</code>:</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; x = "1,88,22" &gt;&gt;&gt; ["".join(g) for b,g in itertools.groupby(x,str.isdigit) if b] ['1', '88', '22'] &gt;&gt;&gt; </code></pre> <p>Here is a method that uses traditional looping:</p> <pre><code>&gt;&gt;&gt; digit = "" &gt;&gt;&gt; digit_list = [] &gt;&gt;&gt; for c in x: ... if c.isdigit(): ... digit += c ... elif c == ",": ... digit_list.append(digit) ... digit = "" ... else: ... digit_list.append(digit) ... &gt;&gt;&gt; digit_list ['1', '88', '22'] &gt;&gt;&gt; </code></pre> <p>In the real world, you'd probably just use regex...</p>
2
2016-10-10T22:50:01Z
[ "python" ]