qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
sequencelengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
48,835,934
Installing Google Cloud SDK I get the response below: Note - I checked, and `C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython` does indeed lead to a python `2.7` that runs fine. ``` Output folder: C:\Users\jonat\AppData\Local\Google\Cloud SDK Downloading Google Cloud SDK core. Extracting Google Cloud SDK core. Create Google Cloud SDK bat file: C:\Users\jonat\AppData\Local\Google\Cloud SDK\cloud_env.bat Installing components. Welcome to the Google Cloud SDK! ERROR: gcloud failed to load: 'module' object has no attribute 'openssl_md_meth_names' gcloud_main = _import_gcloud_main() import googlecloudsdk.gcloud_main from googlecloudsdk.calliope import base from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.core import log from googlecloudsdk.core import properties from googlecloudsdk.core import config from googlecloudsdk.core.util import files as file_utils import hashlib _hashlib.openssl_md_meth_names) This usually indicates corruption in your gcloud installation or problems with your Python interpreter. Please verify that the following is the path to a working Python 2.7 executable: C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython\python.exe If it is not, please set the CLOUDSDK_PYTHON environment variable to point to a working Python 2.7 executable. If you are still experiencing problems, please reinstall the Cloud SDK using the instructions here: https://cloud.google.com/sdk/ Traceback (most recent call last): File "C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bootstrapping\install.py", line 8, in import bootstrapping File "C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bootstrapping\bootstrapping.py", line 15, in from googlecloudsdk.core import config File "C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\config.py", line 27, in from googlecloudsdk.core.util import files as file_utils File "C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\util\files.py", line 22, in import hashlib File "C:\Users\jonat\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython\lib\hashlib.py", line 138, in _hashlib.openssl_md_meth_names) AttributeError: 'module' object has no attribute 'openssl_md_meth_names' Failed to install. ```
2018/02/16
[ "https://Stackoverflow.com/questions/48835934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9371800/" ]
Here is a piece of code that may help: ``` mat = cbind(1:3, 4:6, 7) layout(mat, width = c(1,1,.25)) pal = colorRampPalette(c("white", "black"))(100) # empty plots for (i in 1:6) image(matrix(runif(100), 10), col = pal) # color scale par(las=1, mar = c(4, 1, 4, 5)) image(t(1:100), col = pal, axes = F, ann = F) axis(4) par(las=0) mtext(4, text = "new_ylab", line = 3) ``` You may have to tweak the margins!
Okay, figured it out with the help of [this post](https://stackoverflow.com/questions/9314658/colorbar-from-custom-colorramppalette) that uses a customised function to plot scales. I just had to remove the `dev.new()` call to avoid plotting the colour scale in a new device. The function is flexible but you still need to play around with the `par(mar = c())` parameter to adjust width and height of the vertical bar.
4,250,939
I started programming in january of this year and have covered a lot of ground. I have learnt javascript, ruby on rails, html, css, jquery and every now and then i like to try out some clojure but i will really get into that in the middle of next yr. I really didnt like rails and prefer using netbeans with pure javaScript, html and css, i just feel like i have more control. I really like javascript, but when it comes to sever side programming i have a problem.......for my level of experience i just feel like server side js will not be a good fit yet as it is still not as mature/user friendly as php or ruby on rails. What server side language should i invest in, should i learn php? There is so much info on source code on php. I know that there is node.js and emerging frameworks like geddy.js but i need something more user friendly....or am i just being a woos.I would really like some help on this. Thanks in advance PS. Update: Thanks all for advice, i have settled on python and web2py framework. I decided between django and web2py by doing a couple of simple tutorials and preferred web2py by a huge margin.
2010/11/22
[ "https://Stackoverflow.com/questions/4250939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390129/" ]
Not sure why you don't like rails, but you might want to try the newly released "Rails for Zombies" tutorials by Envy Labs: <http://railsforzombies.org/>. Or if you like books instead of online stuff, check out [Agile Web Development with Rails](http://pragprog.com/titles/rails4/agile-web-development-with-rails) As ben states, sinatra is nice for smallish stuff. A few things to choose from, broken down by language and order of their complexity/learning curve: **Ruby** * [Sinatra](http://www.sinatrarb.com/) * [Rails](http://rubyonrails.org/) **Python** * [web.py](http://webpy.org/) * [Django](http://www.djangoproject.com/) **PHP** * [Code Igniter](http://codeigniter.com/) * [CakePHP](http://cakedc.com/) * [Symfony](http://www.symfony-project.org/) EDIT: I removed my comment about php and added in some PHP specifics. Personally I started with Symfony but it is rather complex. Code Igniter would be a good starting place if you want to learn a PHP framework.
If you like ruby as programming language, but find rails to be just too much to take in it once, I'd recommend trying [Sinatra](http://www.sinatrarb.com/). It's also a ruby-based web framework, but it's a lot simpler than rails, and offers you a lot more control over how you want to set things up. For smaller projects, it's often a much better fit than Rails.
4,250,939
I started programming in january of this year and have covered a lot of ground. I have learnt javascript, ruby on rails, html, css, jquery and every now and then i like to try out some clojure but i will really get into that in the middle of next yr. I really didnt like rails and prefer using netbeans with pure javaScript, html and css, i just feel like i have more control. I really like javascript, but when it comes to sever side programming i have a problem.......for my level of experience i just feel like server side js will not be a good fit yet as it is still not as mature/user friendly as php or ruby on rails. What server side language should i invest in, should i learn php? There is so much info on source code on php. I know that there is node.js and emerging frameworks like geddy.js but i need something more user friendly....or am i just being a woos.I would really like some help on this. Thanks in advance PS. Update: Thanks all for advice, i have settled on python and web2py framework. I decided between django and web2py by doing a couple of simple tutorials and preferred web2py by a huge margin.
2010/11/22
[ "https://Stackoverflow.com/questions/4250939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390129/" ]
Not sure why you don't like rails, but you might want to try the newly released "Rails for Zombies" tutorials by Envy Labs: <http://railsforzombies.org/>. Or if you like books instead of online stuff, check out [Agile Web Development with Rails](http://pragprog.com/titles/rails4/agile-web-development-with-rails) As ben states, sinatra is nice for smallish stuff. A few things to choose from, broken down by language and order of their complexity/learning curve: **Ruby** * [Sinatra](http://www.sinatrarb.com/) * [Rails](http://rubyonrails.org/) **Python** * [web.py](http://webpy.org/) * [Django](http://www.djangoproject.com/) **PHP** * [Code Igniter](http://codeigniter.com/) * [CakePHP](http://cakedc.com/) * [Symfony](http://www.symfony-project.org/) EDIT: I removed my comment about php and added in some PHP specifics. Personally I started with Symfony but it is rather complex. Code Igniter would be a good starting place if you want to learn a PHP framework.
[`Python`](http://www.python.org/) language and [`Django`](http://www.djangoproject.com/) web framework are another good alternative. Both elegant and easy to get started with.
22,585,176
This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is: ``` John M John M Jim M Jim M Jim M Jim M Sally F Sally F ``` You'll notice that names repeat because I want the python code to count what names occur the most and provide lists of most common names, male name and female names. I am very new to python and my understanding of many elements are limited at best.
2014/03/22
[ "https://Stackoverflow.com/questions/22585176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3451030/" ]
You can use parameter android:showAsAction="Always" for each menu item in menu.xml to show your items in action bars ``` <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_add_size" android:title="@string/menu_add_item" android:orderInCategory="10" android:showAsAction="always" android:icon="@android:drawable/ic_menu_add" /> </menu> ``` And you have to remember: Android action bar menu view depends of device hardware control buttons type **EDIT** Just read [this](http://developer.android.com/design/patterns/compatibility.html) article to understand differences, enjoy! P.S. Sorry for my bad english :-(
in your **menu/main.xml:** ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/settings" android:title="@string/settings" android:orderInCategory="0" android:showAsAction="always" /> <item android:id="@+id/action_compose" android:title="hello" android:orderInCategory="1" android:showAsAction="always" /> </menu> ``` and in your **MainActivity** class you have to call the *onCreateOptionsMenu* function ``` @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { // action when action_search was selected case R.id.action_search: //****do something when the action_search item is clicked break; // action when action_compose was selected case R.id.action_compose: //****do something when the action_compose item is clicked break; default: break; } return true; } ```
22,585,176
This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is: ``` John M John M Jim M Jim M Jim M Jim M Sally F Sally F ``` You'll notice that names repeat because I want the python code to count what names occur the most and provide lists of most common names, male name and female names. I am very new to python and my understanding of many elements are limited at best.
2014/03/22
[ "https://Stackoverflow.com/questions/22585176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3451030/" ]
You can use parameter android:showAsAction="Always" for each menu item in menu.xml to show your items in action bars ``` <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_add_size" android:title="@string/menu_add_item" android:orderInCategory="10" android:showAsAction="always" android:icon="@android:drawable/ic_menu_add" /> </menu> ``` And you have to remember: Android action bar menu view depends of device hardware control buttons type **EDIT** Just read [this](http://developer.android.com/design/patterns/compatibility.html) article to understand differences, enjoy! P.S. Sorry for my bad english :-(
Govtart is generally right, but I can see that you have dependency on appcompat-v7 library. So you should use another namespace for actionbar-specific attributes: ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yourapp="http://schemas.android.com/apk/res-auto" > <item android:id="@+id/action_search" android:icon="@drawable/ic_action_search" android:title="@string/action_search" yourapp:showAsAction="ifRoom" /> ... </menu> ``` I used 'ifRoom' instead of 'always' as this is preferred option.
22,585,176
This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is: ``` John M John M Jim M Jim M Jim M Jim M Sally F Sally F ``` You'll notice that names repeat because I want the python code to count what names occur the most and provide lists of most common names, male name and female names. I am very new to python and my understanding of many elements are limited at best.
2014/03/22
[ "https://Stackoverflow.com/questions/22585176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3451030/" ]
You can use parameter android:showAsAction="Always" for each menu item in menu.xml to show your items in action bars ``` <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/menu_add_size" android:title="@string/menu_add_item" android:orderInCategory="10" android:showAsAction="always" android:icon="@android:drawable/ic_menu_add" /> </menu> ``` And you have to remember: Android action bar menu view depends of device hardware control buttons type **EDIT** Just read [this](http://developer.android.com/design/patterns/compatibility.html) article to understand differences, enjoy! P.S. Sorry for my bad english :-(
First of all, to get your options to show in the action bar, you can use `android:showAsAction="always"` or (the better solution) you can use `android:showAsAction="ifRoom"` and that way, it will only be in the action bar if it can fit. So your `menu/main.xml` would be this: ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_search" android:showAsAction="ifRoom" android:title="HIhi"/> <item android:id="@+id/action_compose" android:showAsAction="ifRoom" android:title="hello" /> </menu> ``` However, this will not create the three vertical dots you describe. To do that, you can use a hack with this code: ``` public void getOverflowMenu() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if(menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception ex) { // ignore } } ``` And then just call that method in your `onCreate` method like so: ``` getOverflowMenu(); ``` I don't think this works on *all* devices. I seem to remember this hack not working on an Android 2.2 device, but that could just be bad memory.
22,585,176
This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is: ``` John M John M Jim M Jim M Jim M Jim M Sally F Sally F ``` You'll notice that names repeat because I want the python code to count what names occur the most and provide lists of most common names, male name and female names. I am very new to python and my understanding of many elements are limited at best.
2014/03/22
[ "https://Stackoverflow.com/questions/22585176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3451030/" ]
Govtart is generally right, but I can see that you have dependency on appcompat-v7 library. So you should use another namespace for actionbar-specific attributes: ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yourapp="http://schemas.android.com/apk/res-auto" > <item android:id="@+id/action_search" android:icon="@drawable/ic_action_search" android:title="@string/action_search" yourapp:showAsAction="ifRoom" /> ... </menu> ``` I used 'ifRoom' instead of 'always' as this is preferred option.
in your **menu/main.xml:** ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/settings" android:title="@string/settings" android:orderInCategory="0" android:showAsAction="always" /> <item android:id="@+id/action_compose" android:title="hello" android:orderInCategory="1" android:showAsAction="always" /> </menu> ``` and in your **MainActivity** class you have to call the *onCreateOptionsMenu* function ``` @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { // action when action_search was selected case R.id.action_search: //****do something when the action_search item is clicked break; // action when action_compose was selected case R.id.action_compose: //****do something when the action_compose item is clicked break; default: break; } return true; } ```
22,585,176
This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is: ``` John M John M Jim M Jim M Jim M Jim M Sally F Sally F ``` You'll notice that names repeat because I want the python code to count what names occur the most and provide lists of most common names, male name and female names. I am very new to python and my understanding of many elements are limited at best.
2014/03/22
[ "https://Stackoverflow.com/questions/22585176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3451030/" ]
First of all, to get your options to show in the action bar, you can use `android:showAsAction="always"` or (the better solution) you can use `android:showAsAction="ifRoom"` and that way, it will only be in the action bar if it can fit. So your `menu/main.xml` would be this: ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_search" android:showAsAction="ifRoom" android:title="HIhi"/> <item android:id="@+id/action_compose" android:showAsAction="ifRoom" android:title="hello" /> </menu> ``` However, this will not create the three vertical dots you describe. To do that, you can use a hack with this code: ``` public void getOverflowMenu() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if(menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception ex) { // ignore } } ``` And then just call that method in your `onCreate` method like so: ``` getOverflowMenu(); ``` I don't think this works on *all* devices. I seem to remember this hack not working on an Android 2.2 device, but that could just be bad memory.
in your **menu/main.xml:** ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/settings" android:title="@string/settings" android:orderInCategory="0" android:showAsAction="always" /> <item android:id="@+id/action_compose" android:title="hello" android:orderInCategory="1" android:showAsAction="always" /> </menu> ``` and in your **MainActivity** class you have to call the *onCreateOptionsMenu* function ``` @Override public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { // action when action_search was selected case R.id.action_search: //****do something when the action_search item is clicked break; // action when action_compose was selected case R.id.action_compose: //****do something when the action_compose item is clicked break; default: break; } return true; } ```
22,585,176
This is my first ever post because I can't seem to find a solution to my problem. I have a text file that contains a simple line by line list of different names distinguished from male and female by an M or F next to it. A simple example of this is: ``` John M John M Jim M Jim M Jim M Jim M Sally F Sally F ``` You'll notice that names repeat because I want the python code to count what names occur the most and provide lists of most common names, male name and female names. I am very new to python and my understanding of many elements are limited at best.
2014/03/22
[ "https://Stackoverflow.com/questions/22585176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3451030/" ]
First of all, to get your options to show in the action bar, you can use `android:showAsAction="always"` or (the better solution) you can use `android:showAsAction="ifRoom"` and that way, it will only be in the action bar if it can fit. So your `menu/main.xml` would be this: ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_search" android:showAsAction="ifRoom" android:title="HIhi"/> <item android:id="@+id/action_compose" android:showAsAction="ifRoom" android:title="hello" /> </menu> ``` However, this will not create the three vertical dots you describe. To do that, you can use a hack with this code: ``` public void getOverflowMenu() { try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey"); if(menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception ex) { // ignore } } ``` And then just call that method in your `onCreate` method like so: ``` getOverflowMenu(); ``` I don't think this works on *all* devices. I seem to remember this hack not working on an Android 2.2 device, but that could just be bad memory.
Govtart is generally right, but I can see that you have dependency on appcompat-v7 library. So you should use another namespace for actionbar-specific attributes: ``` <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yourapp="http://schemas.android.com/apk/res-auto" > <item android:id="@+id/action_search" android:icon="@drawable/ic_action_search" android:title="@string/action_search" yourapp:showAsAction="ifRoom" /> ... </menu> ``` I used 'ifRoom' instead of 'always' as this is preferred option.
33,679,414
Suppose I have two types of axis aligned rectangles: a) Defined by left-up and right-bottom points: (x1, y1), (x2, y2) b) Defined by (x1, y1) and (width, height) The aim is to create pythonic-way code, that allows for conversion between these types. E.g. if there is a function, that performs calculations only in one of the representations, it calls the necessary conversion on the given rectangle object first. I can think of three ways of accomplishing that: 1. Create two classes inheriting from a base class. Create two "abstract" methods in the base for conversion to and back between a) and b) with a set of *isinstance* branches inside. Overload the methods in the inheriting classes, making empty methods for useless T -> T conversions. 2. Create a class with one static method, accepting two arguments, unrelated to a) and b) 3. Same as 2., but get rid of the class, just create a function in the global source file scope Which one do you think is the best way, or may be there is something better?
2015/11/12
[ "https://Stackoverflow.com/questions/33679414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2864143/" ]
Create one class, and give it two constructors. One the default `__init__` method, the other a classmethod accepting the other form to specify a rectangle: ``` class Rectangle(Shape): def __init__(self, x1, y1, x2, y2): # .... @classmethod def fromSize(cls, x1, y1, width, height): return cls(x1, y1, x1 + width, y1 + height) ``` The `Rectangle.fromSize()` class method converts the parameters to the 4-coordinate form and returns a new instance. You store just the one form to specify a rectangle, the extra classmethod is basically just a convenience method. I picked the 4-coordinate form as the 'canonical' definition here, but if storing the width and height makes more sense for your model, feel free to swap the default and classmethod factories.
I recommend creating one class and handling the inputs during your init to determine what is present/not present. Then add all the missing parameters based on a calculation. Here is a working example for your situation: ``` class RectangleClass: def __init__(self, x1, y1, x2=None, y2=None, width=None, height=None): if not x2 or not y2: self.x2, self.y2 = self.calculate_points(x1, y1, width, height) if not width or not height: self.height, self.width = self.calculate_dimensions(x1, y1, x2, y2) def calculate_points(self, x1, y1, width,height): x2 = x1 + width y2 = y1 + height return x2, y2 def calculate_dimensions(self, x1, y1, x2,y2): width = abs(x2 - x1) height = abs(y2 - y1) return height, width rectangle = RectangleClass(0, 0, x2=-1, y2=5) print "Rectangle 1: height: %s, width: %s" % (rectangle.height, rectangle.width) rectangle = RectangleClass(1, 3, height=2, width=2) print "Rectangle 2: x2: %s, y2: %s" % (rectangle.x2, rectangle.y2) ```
18,269,672
I mean the situation when lua is run not as embedded in another app but as standalone scripting language. I need something like `PHP_BINARY` or `sys.executable` in python. Is that possible with LUA ?
2013/08/16
[ "https://Stackoverflow.com/questions/18269672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/393087/" ]
Note that the the solution given by lhf is not the most general. If the interpreter has been called with additional command line parameters (if this may be your case) you will have to search `arg`. In general the interpreter name is stored at the most negative integer index defined for `arg`. See this test script: ``` local i_min = 0 while arg[ i_min ] do i_min = i_min - 1 end i_min = i_min + 1 -- so that i_min is the lowest int index for which arg is not nil for i = i_min, #arg do print( string.format( "arg[%d] = %s", i, arg[ i ] ) ) end ```
Try `arg[-1]`. But note that `arg` is not defined when Lua is executed interactively.
18,269,672
I mean the situation when lua is run not as embedded in another app but as standalone scripting language. I need something like `PHP_BINARY` or `sys.executable` in python. Is that possible with LUA ?
2013/08/16
[ "https://Stackoverflow.com/questions/18269672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/393087/" ]
Try `arg[-1]`. But note that `arg` is not defined when Lua is executed interactively.
If the directory that contains your Lua interpreter is in your PATH environment variable, and you invoked the Lua interpreter by its file name: ``` lua myprog.lua ``` then `arg[-1]` contains "lua", not the absolute path of the Lua interpreter. The following Lua program works for me on z/OS UNIX: ``` -- Print the path of the Lua interpreter running this program posix = require("posix") stringx = require("pl.stringx") -- Returns output from system command, trimmed function system(cmd) local f = assert(io.popen(cmd, "r")) local s = assert(f:read("*a")) f:close() return stringx.strip(s) end -- Get process ID of current process -- (the Lua interpreter running this Lua program) local pid = posix.getpid("pid") -- Get the "command" (path) of the executable program for this process local path = system("ps -o comm= -p " .. pid) -- Is the path a symlink? local symlink = posix.readlink(path) if symlink then print("Path (a symlink): " .. path) print("Symlink refers to: " .. symlink) else print("Path (actual file, not a symlink): " .. path) end ``` Alternatively, on UNIX operating systems that have a proc filesystem, you can use `readlink("/proc/self/exe")` to get the path.
18,269,672
I mean the situation when lua is run not as embedded in another app but as standalone scripting language. I need something like `PHP_BINARY` or `sys.executable` in python. Is that possible with LUA ?
2013/08/16
[ "https://Stackoverflow.com/questions/18269672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/393087/" ]
Note that the the solution given by lhf is not the most general. If the interpreter has been called with additional command line parameters (if this may be your case) you will have to search `arg`. In general the interpreter name is stored at the most negative integer index defined for `arg`. See this test script: ``` local i_min = 0 while arg[ i_min ] do i_min = i_min - 1 end i_min = i_min + 1 -- so that i_min is the lowest int index for which arg is not nil for i = i_min, #arg do print( string.format( "arg[%d] = %s", i, arg[ i ] ) ) end ```
If the directory that contains your Lua interpreter is in your PATH environment variable, and you invoked the Lua interpreter by its file name: ``` lua myprog.lua ``` then `arg[-1]` contains "lua", not the absolute path of the Lua interpreter. The following Lua program works for me on z/OS UNIX: ``` -- Print the path of the Lua interpreter running this program posix = require("posix") stringx = require("pl.stringx") -- Returns output from system command, trimmed function system(cmd) local f = assert(io.popen(cmd, "r")) local s = assert(f:read("*a")) f:close() return stringx.strip(s) end -- Get process ID of current process -- (the Lua interpreter running this Lua program) local pid = posix.getpid("pid") -- Get the "command" (path) of the executable program for this process local path = system("ps -o comm= -p " .. pid) -- Is the path a symlink? local symlink = posix.readlink(path) if symlink then print("Path (a symlink): " .. path) print("Symlink refers to: " .. symlink) else print("Path (actual file, not a symlink): " .. path) end ``` Alternatively, on UNIX operating systems that have a proc filesystem, you can use `readlink("/proc/self/exe")` to get the path.
29,321,077
I am trying to write a function to mix strings in python but I am getting stuck at the end. So for this example, I have 2 words, mix and pod. I would like to create a function that returns: pox mid My code only returns pox mix Code: ``` def mix_up(a, b): if len(a and b)>1: b=str.replace(b,b[2],a[2:3]) a=str.replace(a,a[2],b[2]) print b,"",a return mix_up('mix','pod') ``` I am seeking to do this for multiple words. So another example: if I used dog,dinner The output should return dig donner Thanks!
2015/03/28
[ "https://Stackoverflow.com/questions/29321077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120266/" ]
Little play on [string slicing](https://docs.python.org/2/tutorial/introduction.html#strings) ``` def mix_up(first, second): new_first = second[:2] + first[2:] new_second = first[:2] + second[2:] return " ".join((new_first, new_second)) assert mix_up('mix','pod') == 'pox mid' assert mix_up('dog','dinner') == 'dig donner' ```
If you simply wanted to put the 2nd word before the first word all the time: ``` def mix_up(a,b): return " ".join([b,a]) # Should return pod mix ``` Give that you aimed for `pox mix` suggests that you probably wanted to: 1) Replace the last character of word `b` with x 2) Place b before a. In that case, the function would be: ``` def mix_up(a,b): b = b.replace(b[len(b)-1], 'x') # 'x' could be any other character return " ".join([b,a]) # Should return pox mix ``` you can simply swap b with a in order to change the position of the words. If you didn't want the space in metween: ``` return "".join([b,a]) ``` **UPDATE** to "swap" the second letter between b and a, I simply correct your function like the following: ``` def mix_up(a, b): if len(a and b)>1: temp = b[1] # Store it in a temp b=str.replace(b,b[2],a[2:3]) a=str.replace(a,a[2],b[2]) print (b,"",a) return mix_up('mix','pod') ``` Your only problem was once you replaced `b`, you were using the **new** `b` to chose the 2nd letter and replace into `a`.
29,321,077
I am trying to write a function to mix strings in python but I am getting stuck at the end. So for this example, I have 2 words, mix and pod. I would like to create a function that returns: pox mid My code only returns pox mix Code: ``` def mix_up(a, b): if len(a and b)>1: b=str.replace(b,b[2],a[2:3]) a=str.replace(a,a[2],b[2]) print b,"",a return mix_up('mix','pod') ``` I am seeking to do this for multiple words. So another example: if I used dog,dinner The output should return dig donner Thanks!
2015/03/28
[ "https://Stackoverflow.com/questions/29321077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3120266/" ]
Little play on [string slicing](https://docs.python.org/2/tutorial/introduction.html#strings) ``` def mix_up(first, second): new_first = second[:2] + first[2:] new_second = first[:2] + second[2:] return " ".join((new_first, new_second)) assert mix_up('mix','pod') == 'pox mid' assert mix_up('dog','dinner') == 'dig donner' ```
```js def mix_up(a, b): if len(a) < 2 or len(b) < 2: return return (b[:2] + a[2:] + " " + a[:2] + b[2:]) ```
5,385,238
I've got a timestamp in a log file with the format like: ``` 2010-01-01 18:48:14.631829 ``` I've tried the usual suspects like strptime, and no matter what i do, I'm getting that it doesn't match the format I specify. `("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.%f")` I've even tried splitting the value by "." so I can just compare vs the value not having the microseconds on it, but it STILL tells me it doesn't match: "%Y-%m-%d %H:%M:%S" Ug, all I need to do is a simple time delta, haha. Why is python's time stuff so scattered? time, datetime, other various imports
2011/03/22
[ "https://Stackoverflow.com/questions/5385238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669983/" ]
You can use `strptime` like so (Python 2.6+ only): ``` >>> import datetime >>> s = "2010-01-01 18:48:14.631829" >>> datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f") datetime.datetime(2010, 1, 1, 18, 48, 14, 631829) ``` Docs: <http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior> > > ... > > > `%f` Microsecond as a decimal number [0,999999], zero-padded on the left > > > ... > > > If your on 2.5- *and* you don't care about the micros, you can just chop it off: ``` >>> import re >>> datetime.datetime.strptime(re.sub('\..*', '', s), "%Y-%m-%d %H:%M:%S") datetime.datetime(2010, 1, 1, 18, 48, 14) ```
Of course, splitting the string *does* work: ``` >>> print s 2010-01-01 18:48:14.631829 >>> time.strptime(s.split('.')[0], "%Y-%m-%d %H:%M:%S") time.struct_time(tm_year=2010, tm_mon=1, tm_mday=1, tm_hour=18, tm_min=48, tm_sec=14, tm_wday=4, tm_yday=1, tm_isdst=-1) >>> ```
5,385,238
I've got a timestamp in a log file with the format like: ``` 2010-01-01 18:48:14.631829 ``` I've tried the usual suspects like strptime, and no matter what i do, I'm getting that it doesn't match the format I specify. `("%Y-%m-%d %H:%M:%S" OR "%Y-%m-%d %H:%M:%S.%f")` I've even tried splitting the value by "." so I can just compare vs the value not having the microseconds on it, but it STILL tells me it doesn't match: "%Y-%m-%d %H:%M:%S" Ug, all I need to do is a simple time delta, haha. Why is python's time stuff so scattered? time, datetime, other various imports
2011/03/22
[ "https://Stackoverflow.com/questions/5385238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669983/" ]
You can use `strptime` like so (Python 2.6+ only): ``` >>> import datetime >>> s = "2010-01-01 18:48:14.631829" >>> datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f") datetime.datetime(2010, 1, 1, 18, 48, 14, 631829) ``` Docs: <http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior> > > ... > > > `%f` Microsecond as a decimal number [0,999999], zero-padded on the left > > > ... > > > If your on 2.5- *and* you don't care about the micros, you can just chop it off: ``` >>> import re >>> datetime.datetime.strptime(re.sub('\..*', '', s), "%Y-%m-%d %H:%M:%S") datetime.datetime(2010, 1, 1, 18, 48, 14) ```
The following works for me (Python 2.6): ``` >>> import datetime >>> string1 = '2010-01-01 18:48:14.631829' >>> string2 = '2010-01-09 13:04:39.540268' >>> time1 = datetime.datetime.strptime(string1, '%Y-%m-%d %H:%M:%S.%f') >>> time2 = datetime.datetime.strptime(string2, '%Y-%m-%d %H:%M:%S.%f') >>> time2 - time1 datetime.timedelta(7, 65784, 908439) ``` i.e., there are 7 days, 65784 seconds and 908439 microseconds between the two dates. See the [datetime docs](http://docs.python.org/library/datetime.html) for information on the `timedelta` object. **Edit:** Try the following if you cannot use the `%f` directive: ``` >>> time1 = datetime.datetime.strptime(string1.split('.')[0], '%Y-%m-%d %H:%M:%S') >>> time2 = datetime.datetime.strptime(string2.split('.')[0], '%Y-%m-%d %H:%M:%S') >>> time2 - time1 datetime.timedelta(7, 65785) ```
27,929,400
I am trying to make a program in python that will accept an argument of text input, then randomly change each letter to be a different color This is what I have: ``` color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white']; ``` I want to be able to have a program that can let me type out a paragraph, then it uses the colors in the list and randomly assigns them to each letter. For an output, I would like to to be something like this. ``` [color=random]H[/color][color=random]i[/color] [color=random]t[/color] [color=random]h[/color] [color=random]e[/color][color=random]r[/color][color=random]e[/color] ``` The colors should be random from the list I made. Is this possible to make?
2015/01/13
[ "https://Stackoverflow.com/questions/27929400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450564/" ]
This works for me: ``` from random import choice color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'] l = len(color) str = "Hit Here" html = '' for x in str: html += '[color=' + choice(color) + ']' + x + '[/color]' if len(x.strip()) > 0 else x print(html) ``` Sample output: ``` [color=yellow]H[/color][color=#f60]i[/color][color=yellow]t[/color] [color=black]H[/color][color=black]e[/color][color=white]r[/color][color=purple]e[/color] [color=purple]H[/color][color=white]i[/color][color=purple]t[/color] [color=black]H[/color][color=green]e[/color][color=red]r[/color][color=blue]e[/color] [color=yellow]H[/color][color=green]i[/color][color=#f60]t[/color] [color=blue]H[/color][color=white]e[/color][color=green]r[/color][color=pink]e[/color] ```
try like this: ``` import random #console color W = '\033[0m' # white (normal) R = '\033[31m' # red G = '\033[32m' # green O = '\033[33m' # orange B = '\033[34m' # blue P = '\033[35m' # purple my_color = [W, R, G, O, B, P] a = raw_input("Enter your text to be colourful: ") new_text ="" for x in a: new_text += x + random.choice(my_color) print new_text + W ``` ![enter image description here](https://i.stack.imgur.com/WXHuj.png) your Desired output: ``` >>> import random >>> color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'] >>> new_text = "" >>> import random >>> for x in text: ... new_text += "[color={}]{}[/color]".format(random.choice(color), x) ... >>> new_text '[color=#f60]h[/color][color=white]e[/color][color=blue]l[/color][color=#f60]l[/color][color=black]o[/color][color=white] [/color][color=purple]h[/color][color=white]o[/color][color=green]w[/color][color=pink] [/color][color=white]a[/color][color=white]r[/color][color=yellow]e[/color][color=red] [/color][color=#f60]y[/color][color=green]o[/color][color=red]u[/color]' ```
27,929,400
I am trying to make a program in python that will accept an argument of text input, then randomly change each letter to be a different color This is what I have: ``` color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white']; ``` I want to be able to have a program that can let me type out a paragraph, then it uses the colors in the list and randomly assigns them to each letter. For an output, I would like to to be something like this. ``` [color=random]H[/color][color=random]i[/color] [color=random]t[/color] [color=random]h[/color] [color=random]e[/color][color=random]r[/color][color=random]e[/color] ``` The colors should be random from the list I made. Is this possible to make?
2015/01/13
[ "https://Stackoverflow.com/questions/27929400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450564/" ]
This works for me: ``` from random import choice color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'] l = len(color) str = "Hit Here" html = '' for x in str: html += '[color=' + choice(color) + ']' + x + '[/color]' if len(x.strip()) > 0 else x print(html) ``` Sample output: ``` [color=yellow]H[/color][color=#f60]i[/color][color=yellow]t[/color] [color=black]H[/color][color=black]e[/color][color=white]r[/color][color=purple]e[/color] [color=purple]H[/color][color=white]i[/color][color=purple]t[/color] [color=black]H[/color][color=green]e[/color][color=red]r[/color][color=blue]e[/color] [color=yellow]H[/color][color=green]i[/color][color=#f60]t[/color] [color=blue]H[/color][color=white]e[/color][color=green]r[/color][color=pink]e[/color] ```
pip install pygments, then try this: ``` import random from pygments.console import codes string='some string here' print ''.join([random.choice(codes.values())+x+codes['reset'] for x in string]) ```
27,929,400
I am trying to make a program in python that will accept an argument of text input, then randomly change each letter to be a different color This is what I have: ``` color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white']; ``` I want to be able to have a program that can let me type out a paragraph, then it uses the colors in the list and randomly assigns them to each letter. For an output, I would like to to be something like this. ``` [color=random]H[/color][color=random]i[/color] [color=random]t[/color] [color=random]h[/color] [color=random]e[/color][color=random]r[/color][color=random]e[/color] ``` The colors should be random from the list I made. Is this possible to make?
2015/01/13
[ "https://Stackoverflow.com/questions/27929400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450564/" ]
pip install pygments, then try this: ``` import random from pygments.console import codes string='some string here' print ''.join([random.choice(codes.values())+x+codes['reset'] for x in string]) ```
try like this: ``` import random #console color W = '\033[0m' # white (normal) R = '\033[31m' # red G = '\033[32m' # green O = '\033[33m' # orange B = '\033[34m' # blue P = '\033[35m' # purple my_color = [W, R, G, O, B, P] a = raw_input("Enter your text to be colourful: ") new_text ="" for x in a: new_text += x + random.choice(my_color) print new_text + W ``` ![enter image description here](https://i.stack.imgur.com/WXHuj.png) your Desired output: ``` >>> import random >>> color = ['red' , 'blue', 'green' , 'purple' , 'yellow' , 'pink' , '#f60' , 'black' , 'white'] >>> new_text = "" >>> import random >>> for x in text: ... new_text += "[color={}]{}[/color]".format(random.choice(color), x) ... >>> new_text '[color=#f60]h[/color][color=white]e[/color][color=blue]l[/color][color=#f60]l[/color][color=black]o[/color][color=white] [/color][color=purple]h[/color][color=white]o[/color][color=green]w[/color][color=pink] [/color][color=white]a[/color][color=white]r[/color][color=yellow]e[/color][color=red] [/color][color=#f60]y[/color][color=green]o[/color][color=red]u[/color]' ```
12,135,555
I am trying to build my first Django project from scratch and am having difficulty setting the background image. I am new to programming in general so forgive me if this is a stupid question. I have read the documentation [here](https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles) on static file implementations and various stack overflow posts ([here](https://stackoverflow.com/questions/2451352/cant-figure-out-serving-static-images-in-django-dev-environment) [here](https://stackoverflow.com/questions/7057982/django-static-files-while-debug-mode-is-on) and [here](https://stackoverflow.com/questions/2148738/cannot-get-images-to-display-in-simple-django-site)) on setting the background image, but I still can't get it to work. I have: * installed the django.contrib.staticfiles as an installed app. * added this to the settings file: `TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.static", "django.core.context_processors.tz", "django.contrib.messages.context_processors.messages", )` * set the Static\_Root and Static\_URL files to STATIC\_ROOT = '/Users/user\_name/development/projects/ecollar\_site/static/' and '/static/' respectively * put this code at the end of my URLs file: ``` `if settings.DEBUG: urlpatterns += patterns('', (r'^/static/(?P<path>.*)$', 'django.views.static.serve', {'/ecollar_site/': settings.STATIC_ROOT, 'show_indexes' : True}), )` ``` * ran `python manage.py collectstatic` * and then put this line in the CSS file. `body{ font:16px/26px Helvetica, Helvetica Neue, Arial; background-image: url("{{ STATIC_URL }}img/IMG_0002.jpg"); }` I know the static files bit is working because the CSS is loaded. And I can change the background color by using background-color: blue. But the static image is simply not being put as the background image. Have I made a rookie mistake somewhere?
2012/08/27
[ "https://Stackoverflow.com/questions/12135555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1611337/" ]
Your css file is not rendered by Django template engine and so {{ STATIC\_URL }} is not being replaced. You'll have to use /static/img/IMG\_0002.jpg in the CSS file or move that bit of CSS in your html file's style tag.
Try this settings.py ``` MEDIA_URL = '/static_media/' ``` urly.py ``` if settings.DEBUG: urlpatterns += patterns('django.views.static', (r'^static_media/(?P<path>.*)$', 'serve', { 'document_root': '/path/to/static_media', 'show_indexes': True }),) ``` your css and jquery on template ``` <link rel="stylesheet" href="{{ MEDIA_URL }}base_min.css" type="text/css" media="screen"> ``` If your are using production version try this ``` MEDIA_URL = 'http://media.example.org/' Development: /static_media/base_min.css Production: http://media.example.org/base_min.css ``` Hope this will help you Don't forget to attached `'django.contrib.staticfiles',` in your INSTALLED\_APPS
39,675,898
I am reading [The Hitchhiker’s Guide to Python](http://docs.python-guide.org/en/latest/writing/structure/#mutable-and-immutable-types) and there is a short code snippet ``` foo = 'foo' bar = 'bar' foobar = foo + bar # This is good foo += 'ooo' # This is bad, instead you should do: foo = ''.join([foo, 'ooo']) ``` The author pointed out that `''.join()` is not always faster than `+`, so he is not against using `+` for string concatenation. But why is `foo += 'ooo'` bad practice whereas `foobar=foo+bar` is considered good? * is `foo += bar` good? * is `foo = foo + 'ooo'` good? Before this code snippet, the author wrote: > > One final thing to mention about strings is that using join() is not always best. In the instances where you are creating a new string from a pre-determined number of strings, using the addition operator is actually faster, but in cases like above or in cases where you are adding to an existing string, using join() should be your preferred method. > > >
2016/09/24
[ "https://Stackoverflow.com/questions/39675898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/534298/" ]
Is it bad practice? ------------------- It's reasonable to assume that it isn't bad practice for this example because: * The author doesn't give any reason. Maybe it's just disliked by him/her. * Python documentation doesn't mention it's bad practice (from what I've seen). * `foo += 'ooo'` is just as readable (according to me) and is approximately 100 times faster than `foo = ''.join([foo, 'ooo'])`. When should one be used over the other? --------------------------------------- Concatenation of strings have the disadvantage of needing to create a new string and allocate new memory *for every concatenation*! This is time consuming, but isn't that big of a deal with few and small strings. When you know the number of strings to concatenate and don't need more than maybe 2-4 concatenations I'd go for it. --- When joining strings Python only has to allocate new memory for the final string, which is much more efficient, but could take longer to compute. Also, because strings are immutable it's often more practical to use a list of strings to dynamically mutate, and only convert it to a string when needed. It's often convenient to create strings with str.join() since it takes an iterable. For example: ``` letters = ", ".join("abcdefghij") ``` To conclude ----------- In most cases it makes more sense to use `str.join()` but there are times when concatenation is just as viable. Using any form of string concatenation for huge or many strings would be bad practice just as using `str.join()` would be bad practice for short and few strings, in my own opinion. I believe that the author was just trying to create a rule of thumb to easier identify when to use what without going in too much detail or make it complicated.
If the number of string is small and strings are known in advance, I would go : ``` foo = f"{foo}ooo" ``` Using [f-strings](https://docs.python.org/fr/3/tutorial/inputoutput.html#formatted-string-literals). However, this is valid only since python 3.6.
73,453,875
Few days ago I uninstalled and then reinstalled python due to some error related to pip . Since then whenever I start my pc it shows python modify setup window 2 or 3 times [you can see popup here](https://i.stack.imgur.com/nrsLv.png) Though I can close these windows ; Whenever I open vs code it can be upwards of 10 pop-ups . What's bizarre about this is that I already have my VS Code set up properly . How do I prevent these annoying pop-ups?
2022/08/23
[ "https://Stackoverflow.com/questions/73453875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825726/" ]
If there's code I'm likely to use repeatedly (like checking whether a radio button is selected or not), I like to put it in a method so it's easily reusable. This method takes the parent DIV of the radio button and counts the number of SVG circles inside. If there's more than one, the radio button is selected. This way you can use this method for not only the One Way radio button but any radio button on the page. ``` public static boolean isSelected(By locator) { return new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(locator)).findElements(By.cssSelector("circle")).size() > 1; } ``` Simple examples ``` By oneWayLocator = By.cssSelector("div[data-testid='one-way-radio-button']"); By roundTripLocator = By.cssSelector("div[data-testid='round-trip-radio-button']"); boolean oneWaySelected = isSelected(oneWayLocator); boolean roundTripSelected = isSelected(roundTripLocator); ``` It sounds like you want to check to see if the One Way radio button is selected and if so, select Round Trip instead. To do that, ``` By oneWayLocator = By.cssSelector("div[data-testid='one-way-radio-button']"); By roundTripLocator = By.cssSelector("div[data-testid='round-trip-radio-button']"); if (isSelected(oneWayLocator)) { driver.findElement(roundTripLocator).click(); } ``` I declare driver as a property of the page object class so that I don't have to pass it around in all of my methods, e.g. ``` public class HomePage { WebDriver driver; ... public HomePage(WebDriver driver) { this.driver = driver; } ``` and then create an instance of the class while passing in the driver from my main/test method. ``` HomePage homePage = new HomePage(driver); ```
Most important thing a circle tag represents the one circle, not the svg tag. So svg tag which looks like selected radiobutton contains two circle tags. You can measure number of circle tags in svg tag and based on that consider the svg as un/selected. **Code:** ``` List<WebElement> svgTags = driver.findElements(By.tagName("svg")); for (WebElement svgTag: svgTags) { int circlesCount = svgTag.findElements(By.tagName("circle")).size(); if (circlesCount == 1) { System.out.println("looks like unselected radiobutton"); } else if (circlesCount > 1) { System.out.println("looks like selected radiobutton"); } else { System.out.println("no circle in svg"); } } ``` **Output:** ``` looks like selected radiobutton looks like unselected radiobutton ```
25,504,738
I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular. To demonstrate, this is my fixture ``` @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() a_dependency.teardown() ``` As you see, my fixture depends on `a_dependency` whose teardown() needs to be called as well. I know in the naive use-case, I could do this: ``` @yield_fixture def a_dependency(): yield teardown() @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() ``` However, while the `a_fixture` code can be put in a central place and re-used by all tests, the `a_dependecy` code is test-specific and each test possibly needs to create a new `a_dependency` object. I want to avoid copy-pasting both fixture and dependency to all my tests. If this was regular python code, I could just pass the `a_dependecy` as a function argument. How can I pass this object to my shared fixture?
2014/08/26
[ "https://Stackoverflow.com/questions/25504738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440380/" ]
In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this: ``` <div style="padding:25px; width:400px;"> <div style="background-color:#bf5b5b;"> <span>Yes</span> <span>No</span></div> <div id="option_one_div" style="display: table;"> <div id="ldiv" style="background-color:#74d4dd; width:150px;display:table-cell;"> <label for="rbutton_radio_1_0" style="margin-left:30px; margin-right:30px;"> <input for="rbutton_radio_1_0" type="radio" name="radio" value="0"/></label> <label for="rbutton_radio_1_1" style="margin-left:30px; margin-right:30px;"> <input for="rbutton_radio_1_1" type="radio" name="radio" value="1"/></label> </div> <div id="rdiv" style="display:table-cell; background-color:#74d4dd; margin-left:151px; padding-left: 20px; padding-right: 20px"> <span>Label of first group of Radio Buttons radio buttons.</span> </div> </div> </div> ``` [**fiddle**](http://jsfiddle.net/41209azo/6/) As you can see you don't need `floats`.
use width with float in div ``` <div id="rdiv" style="float:right; background-color: #74d4dd; /* margin-left: 151px; */ padding-left: 20px; width: 210px;padding-right: 20px"> <span>Label of first group of Radio Buttons radio buttons.</span> </div> ``` [plz check](http://jsfiddle.net/akash4pj/41209azo/1/)
25,504,738
I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular. To demonstrate, this is my fixture ``` @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() a_dependency.teardown() ``` As you see, my fixture depends on `a_dependency` whose teardown() needs to be called as well. I know in the naive use-case, I could do this: ``` @yield_fixture def a_dependency(): yield teardown() @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() ``` However, while the `a_fixture` code can be put in a central place and re-used by all tests, the `a_dependecy` code is test-specific and each test possibly needs to create a new `a_dependency` object. I want to avoid copy-pasting both fixture and dependency to all my tests. If this was regular python code, I could just pass the `a_dependecy` as a function argument. How can I pass this object to my shared fixture?
2014/08/26
[ "https://Stackoverflow.com/questions/25504738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440380/" ]
use width with float in div ``` <div id="rdiv" style="float:right; background-color: #74d4dd; /* margin-left: 151px; */ padding-left: 20px; width: 210px;padding-right: 20px"> <span>Label of first group of Radio Buttons radio buttons.</span> </div> ``` [plz check](http://jsfiddle.net/akash4pj/41209azo/1/)
the main problem is you didn't add width to the `id="rdiv"` and used `margin-left:151px` when you use some element with float, you have to add its width ``` <div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">a</div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">b</div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">c</div> </div> ``` to solve the problem, you can do one of the following things: 1: change your code to:(notice you set margin-left:151px; in th `id="rdiv"` and I changed it to lower value) ``` <div id="rdiv" style="float:right; background-color:#74d4dd; margin-left:15px; padding-left: 20px; padding-right: 20px; width:50px;"> ``` 2: remove your `float=right` in the `id="rdiv"` so the id="ldiv" could be in the float version of this element
25,504,738
I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular. To demonstrate, this is my fixture ``` @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() a_dependency.teardown() ``` As you see, my fixture depends on `a_dependency` whose teardown() needs to be called as well. I know in the naive use-case, I could do this: ``` @yield_fixture def a_dependency(): yield teardown() @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() ``` However, while the `a_fixture` code can be put in a central place and re-used by all tests, the `a_dependecy` code is test-specific and each test possibly needs to create a new `a_dependency` object. I want to avoid copy-pasting both fixture and dependency to all my tests. If this was regular python code, I could just pass the `a_dependecy` as a function argument. How can I pass this object to my shared fixture?
2014/08/26
[ "https://Stackoverflow.com/questions/25504738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440380/" ]
In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this: ``` <div style="padding:25px; width:400px;"> <div style="background-color:#bf5b5b;"> <span>Yes</span> <span>No</span></div> <div id="option_one_div" style="display: table;"> <div id="ldiv" style="background-color:#74d4dd; width:150px;display:table-cell;"> <label for="rbutton_radio_1_0" style="margin-left:30px; margin-right:30px;"> <input for="rbutton_radio_1_0" type="radio" name="radio" value="0"/></label> <label for="rbutton_radio_1_1" style="margin-left:30px; margin-right:30px;"> <input for="rbutton_radio_1_1" type="radio" name="radio" value="1"/></label> </div> <div id="rdiv" style="display:table-cell; background-color:#74d4dd; margin-left:151px; padding-left: 20px; padding-right: 20px"> <span>Label of first group of Radio Buttons radio buttons.</span> </div> </div> </div> ``` [**fiddle**](http://jsfiddle.net/41209azo/6/) As you can see you don't need `floats`.
the total width of the elements (incl. margin/border) can not be greater than the surrounding divs width of 400px else the floating elements will be put into the next line ... see akz's answer for a quick fix
25,504,738
I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular. To demonstrate, this is my fixture ``` @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() a_dependency.teardown() ``` As you see, my fixture depends on `a_dependency` whose teardown() needs to be called as well. I know in the naive use-case, I could do this: ``` @yield_fixture def a_dependency(): yield teardown() @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() ``` However, while the `a_fixture` code can be put in a central place and re-used by all tests, the `a_dependecy` code is test-specific and each test possibly needs to create a new `a_dependency` object. I want to avoid copy-pasting both fixture and dependency to all my tests. If this was regular python code, I could just pass the `a_dependecy` as a function argument. How can I pass this object to my shared fixture?
2014/08/26
[ "https://Stackoverflow.com/questions/25504738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440380/" ]
the total width of the elements (incl. margin/border) can not be greater than the surrounding divs width of 400px else the floating elements will be put into the next line ... see akz's answer for a quick fix
the main problem is you didn't add width to the `id="rdiv"` and used `margin-left:151px` when you use some element with float, you have to add its width ``` <div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">a</div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">b</div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">c</div> </div> ``` to solve the problem, you can do one of the following things: 1: change your code to:(notice you set margin-left:151px; in th `id="rdiv"` and I changed it to lower value) ``` <div id="rdiv" style="float:right; background-color:#74d4dd; margin-left:15px; padding-left: 20px; padding-right: 20px; width:50px;"> ``` 2: remove your `float=right` in the `id="rdiv"` so the id="ldiv" could be in the float version of this element
25,504,738
I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular. To demonstrate, this is my fixture ``` @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() a_dependency.teardown() ``` As you see, my fixture depends on `a_dependency` whose teardown() needs to be called as well. I know in the naive use-case, I could do this: ``` @yield_fixture def a_dependency(): yield teardown() @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() ``` However, while the `a_fixture` code can be put in a central place and re-used by all tests, the `a_dependecy` code is test-specific and each test possibly needs to create a new `a_dependency` object. I want to avoid copy-pasting both fixture and dependency to all my tests. If this was regular python code, I could just pass the `a_dependecy` as a function argument. How can I pass this object to my shared fixture?
2014/08/26
[ "https://Stackoverflow.com/questions/25504738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440380/" ]
In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this: ``` <div style="padding:25px; width:400px;"> <div style="background-color:#bf5b5b;"> <span>Yes</span> <span>No</span></div> <div id="option_one_div" style="display: table;"> <div id="ldiv" style="background-color:#74d4dd; width:150px;display:table-cell;"> <label for="rbutton_radio_1_0" style="margin-left:30px; margin-right:30px;"> <input for="rbutton_radio_1_0" type="radio" name="radio" value="0"/></label> <label for="rbutton_radio_1_1" style="margin-left:30px; margin-right:30px;"> <input for="rbutton_radio_1_1" type="radio" name="radio" value="1"/></label> </div> <div id="rdiv" style="display:table-cell; background-color:#74d4dd; margin-left:151px; padding-left: 20px; padding-right: 20px"> <span>Label of first group of Radio Buttons radio buttons.</span> </div> </div> </div> ``` [**fiddle**](http://jsfiddle.net/41209azo/6/) As you can see you don't need `floats`.
Just remove `float:right`. It will work. ``` <div id="rdiv" style="background-color:#74d4dd; margin-left:151px; padding-left: 20px; padding-right: 20px"> ``` [**DEMO**](http://jsfiddle.net/41209azo/2/)
25,504,738
I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular. To demonstrate, this is my fixture ``` @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() a_dependency.teardown() ``` As you see, my fixture depends on `a_dependency` whose teardown() needs to be called as well. I know in the naive use-case, I could do this: ``` @yield_fixture def a_dependency(): yield teardown() @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() ``` However, while the `a_fixture` code can be put in a central place and re-used by all tests, the `a_dependecy` code is test-specific and each test possibly needs to create a new `a_dependency` object. I want to avoid copy-pasting both fixture and dependency to all my tests. If this was regular python code, I could just pass the `a_dependecy` as a function argument. How can I pass this object to my shared fixture?
2014/08/26
[ "https://Stackoverflow.com/questions/25504738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440380/" ]
Just remove `float:right`. It will work. ``` <div id="rdiv" style="background-color:#74d4dd; margin-left:151px; padding-left: 20px; padding-right: 20px"> ``` [**DEMO**](http://jsfiddle.net/41209azo/2/)
the main problem is you didn't add width to the `id="rdiv"` and used `margin-left:151px` when you use some element with float, you have to add its width ``` <div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">a</div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">b</div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">c</div> </div> ``` to solve the problem, you can do one of the following things: 1: change your code to:(notice you set margin-left:151px; in th `id="rdiv"` and I changed it to lower value) ``` <div id="rdiv" style="float:right; background-color:#74d4dd; margin-left:15px; padding-left: 20px; padding-right: 20px; width:50px;"> ``` 2: remove your `float=right` in the `id="rdiv"` so the id="ldiv" could be in the float version of this element
25,504,738
I am not talking about the "Fixture Parametrizing" as defined by pytest, I am talking about real parameters that you pass to a function (the fixture function in this case) to make code more modular. To demonstrate, this is my fixture ``` @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() a_dependency.teardown() ``` As you see, my fixture depends on `a_dependency` whose teardown() needs to be called as well. I know in the naive use-case, I could do this: ``` @yield_fixture def a_dependency(): yield teardown() @yield_fixture def a_fixture(a_dependency): do_setup_work() yield do_teardown_work() ``` However, while the `a_fixture` code can be put in a central place and re-used by all tests, the `a_dependecy` code is test-specific and each test possibly needs to create a new `a_dependency` object. I want to avoid copy-pasting both fixture and dependency to all my tests. If this was regular python code, I could just pass the `a_dependecy` as a function argument. How can I pass this object to my shared fixture?
2014/08/26
[ "https://Stackoverflow.com/questions/25504738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2440380/" ]
In your situation you can use `display:table` in container(`#option_one_div`) in your example and `display:table-cell` in children elements(`#ldiv`, `#rdiv`) like this: ``` <div style="padding:25px; width:400px;"> <div style="background-color:#bf5b5b;"> <span>Yes</span> <span>No</span></div> <div id="option_one_div" style="display: table;"> <div id="ldiv" style="background-color:#74d4dd; width:150px;display:table-cell;"> <label for="rbutton_radio_1_0" style="margin-left:30px; margin-right:30px;"> <input for="rbutton_radio_1_0" type="radio" name="radio" value="0"/></label> <label for="rbutton_radio_1_1" style="margin-left:30px; margin-right:30px;"> <input for="rbutton_radio_1_1" type="radio" name="radio" value="1"/></label> </div> <div id="rdiv" style="display:table-cell; background-color:#74d4dd; margin-left:151px; padding-left: 20px; padding-right: 20px"> <span>Label of first group of Radio Buttons radio buttons.</span> </div> </div> </div> ``` [**fiddle**](http://jsfiddle.net/41209azo/6/) As you can see you don't need `floats`.
the main problem is you didn't add width to the `id="rdiv"` and used `margin-left:151px` when you use some element with float, you have to add its width ``` <div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">a</div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">b</div> <div style="float: left;width: 110px;height: 90px;margin: 5px;">c</div> </div> ``` to solve the problem, you can do one of the following things: 1: change your code to:(notice you set margin-left:151px; in th `id="rdiv"` and I changed it to lower value) ``` <div id="rdiv" style="float:right; background-color:#74d4dd; margin-left:15px; padding-left: 20px; padding-right: 20px; width:50px;"> ``` 2: remove your `float=right` in the `id="rdiv"` so the id="ldiv" could be in the float version of this element
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
The last time I saw a similar error it was because I was using the wrong version of `npm` and/or `node` for one of my dependencies. Try upgrading these and try again. Before trying again remove your `node_modules` directory. You may need to investigate what versions of `npm` and `node` your dependencies need. You could try the latest versions of all your dependencies, node and npm. Check what versions your colleagues are using. What OS are you using? That can have an impact as version of CLANG maybe different.
Install python2 and try running `npm install` again. This approach worked for me.
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
Based on the **node-gyp README**, update npm `npm i npm -g`, and will bring in a newer version of node-gyp. Hint: if you are on **windows** perform `npm install --global --production windows-build-tools` from an elevated PowerShell or CMD.exe (run as Administrator).
I am using yarn so I just ran `yarn global add node-gyp` to globally install `node-gyp` without using npm and it worked. I'm no more facing the error For those using npm can do it using `npm install -g node-gyp`. Make sure you know that running these commands will globally install node-gyp in your environment, probably outside the scope of your current app too. And in case you are running any other apps in the similar environment that are dependent on any particular version of `node-gyp`, you might face some troubles.
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
The error messages have caused confusion for me and have not helped me in resolving the errors completely. The [README.md](https://github.com/nodejs/node-gyp/blob/master/README.md "README.md") for [node-gyp](https://github.com/nodejs/node-gyp "node-gyp") project does a better job of listing down the installation instructions for Unix, Max OS X and **Windows**. In **Windows** systems you can either go with Option 1 or Option 2 but the main thing is that you need to install the [Visual C++ Build Tools](http://go.microsoft.com/fwlink/?LinkId=691126 "Visual C++ Build Tools"). The following quote is from the **Windows** installation section: > > * On Windows: > + Visual C++ Build Environment: > - Option 1: Install Visual C++ Build Tools using the Default Install option. > - Option 2: Install Visual Studio 2015 (or modify an existing installation) and select *Common Tools for Visual C++* during setup. This also works with the free Community and Express for Desktop editions. > > [Windows Vista / 7 only] requires .NET Framework 4.5.1 > + Install Python 2.7 (*v3.x.x* is not supported), and run > ``` > npm config set python python2.7 > ``` > (or see below for further instructions on specifying the proper Python version and path.) > + Launch cmd, > ``` > npm config set msvs_version 2015 > ``` > > > If the above steps didn't work for you, please visit Microsoft's Node.js Guidelines for Windows for additional tips. > > > Common instructions for Python configuration: > > If you have multiple Python versions installed, you can identify which Python version node-gyp uses by setting the '--python' variable: > > > ``` $ node-gyp --python /path/to/python2.7 ``` > > If node-gyp is called by way of npm and you have multiple versions of Python installed, then you can set npm's 'python' config key to the appropriate value: > > > ``` $ npm config set python /path/to/executable/python2.7 ``` Successfully configured my system following the above instructions. **System Info** ``` λ ver Microsoft Windows [Version 6.1.7601] λ node -v v6.2.0 λ npm -v 3.9.2 ``` Links to relevant tools / articles: [Visual C++ Build Tools](http://go.microsoft.com/fwlink/?LinkId=691126 "Visual C++ Build Tools") [Visual Studio 2015](https://www.visualstudio.com/products/visual-studio-community-vs "Visual Studio 2015") [.NET Framework 4.5.1](http://www.microsoft.com/en-us/download/details.aspx?id=40773 ".NET Framework 4.5.1") [Python 2.7](https://www.python.org/downloads/ "Python 2.7") [Microsoft's Node.js Guidelines for Windows](https://github.com/Microsoft/nodejs-guidelines/blob/master/windows-environment.md#compiling-native-addon-modules "Microsoft's Node.js Guidelines for Windows")
For Windows 8 or 10: Assuming node and npm installed already. My node and npm version (At the time of writing this answer) : node : 8.9.4 npm : 5.6.0 1. First install [python 2.x](https://www.python.org/downloads/release/python-2714/) 2. Make sure it is available on path 3. Install [Visual Studio Installer](https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=Community&rel=15) 4. After installation, run it 5. A new interface will open it where you can select various options. 6. Now select **Build Tools for Visual Studio 2017** from the available options and install it. You don't need to install Visual Studio. [![enter image description here](https://i.stack.imgur.com/iDZvr.jpg)](https://i.stack.imgur.com/iDZvr.jpg) After the installation it should work perfectly.
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
Try to install again with `--force option`: ``` npm install --force ``` If this doesn't work try to update npm globally: ``` npm update -g npm ``` and try again with the `--force` option.
Try delete current node\_modules folder and run Command as regular user, non administrator or root
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
If you are using "node-sass", upgrade it to version 5.0.0, make sure that you have build tools 2017 and Python 3 installed, and issue these commands prior to npm install `npm config set msvs_version 2017` `npm config set python npm config set python C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe`
I was stuck with the same error on my windows machine after a lot of troubleshooting with various stack answers I was not able to fix it, later did the following which made it work properly now. 1. npm cache clear --force 2. open explorer in address bar paste %appdata%, then delete the folders npm,npm-cache 3. uninstalled nodejs and reinstalled latest version. 4. then npm install worked fine for me
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
Try to install again with `--force option`: ``` npm install --force ``` If this doesn't work try to update npm globally: ``` npm update -g npm ``` and try again with the `--force` option.
Post my solution here in case anyone like me using **Windows 10** still has the error after installing many Microsoft associated build tools. All you need are: > > Windows 10 64 bit > > > python 2.7.x > > > [Visual Studio 2013](https://www.microsoft.com/en-gb/download/details.aspx?id=44914) > > > I've tried Visual Studio 2015 before but it didn't work at all. --- 1. First of all, I uninstall all the Microsoft associated build tools. (If you didn't install anything to try to solve this problem before, skip this step.) 2. Install Visual Studio 2013. 3. Config npm as @Sourav said: > > Config python: > > > > ``` > npm config set python /path/to/python2.7 > > ``` > > Config msvs\_version: > > > > ``` > npm config set msvs_version 2013 > > ``` > > Run a `npm install` or the npm command which occurs this error. It works for me! BTW, this solution is from [here](https://github.com/nodejs/node-gyp/issues/679).
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
Based on the **node-gyp README**, update npm `npm i npm -g`, and will bring in a newer version of node-gyp. Hint: if you are on **windows** perform `npm install --global --production windows-build-tools` from an elevated PowerShell or CMD.exe (run as Administrator).
Delete **package-lock.json** Then restart your machine(if there were changes made to take effect) then run ``` npm install --legacy-peer-deps ```
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
If you are using "node-sass", upgrade it to version 5.0.0, make sure that you have build tools 2017 and Python 3 installed, and issue these commands prior to npm install `npm config set msvs_version 2017` `npm config set python npm config set python C:\Users\username\AppData\Local\Programs\Python\Python39\python.exe`
Edit or remove your package-lock.json and run npm install
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
Try delete current node\_modules folder and run Command as regular user, non administrator or root
I am using yarn so I just ran `yarn global add node-gyp` to globally install `node-gyp` without using npm and it worked. I'm no more facing the error For those using npm can do it using `npm install -g node-gyp`. Make sure you know that running these commands will globally install node-gyp in your environment, probably outside the scope of your current app too. And in case you are running any other apps in the similar environment that are dependent on any particular version of `node-gyp`, you might face some troubles.
33,896,511
We are having problems running **"npm install"** on our project. A certain file cannot be found : ``` fatal error C1083: Cannot open include file: 'windows.h' ``` It appears to be coming from the **node-gyp** module : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > This node-gyp seems to be a never ending source of pain for us. At first it complained that it needed python, so we installed that. Then it complained that it needed VCBuild, which we installed (using .NET 2.0 SDK), now we have this error. It's almost as if the errors are getting more and more obscure, and it feels like we are going down some wrong path. The strange thing is, that other people in our team have zero problems running the npm-install. The full error looks like this : > > c:\Program > Files\nodejs\node\_modules\npm\node\_modules\node-gyp\src\win\_delay\_lo > ad\_hook.c(13): > > > fatal error C1083: Cannot open include file: 'windows.h': No suc h > file or directory > [D:\ngs-frontend-next\node\_modules\browser-sync\node\_module > s\socket.io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil\buil > d\binding.sln] > > > gyp ERR! build error gyp ERR! stack Error: > `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe` failed > with exit code: 1 stack at ChildProcess.onExit (C:\Program > Files\nodejs\node\_modules\npm\node > \_modules\node-gyp\lib\build.js:270:23) gyp ERR! stack at emitTwo (events.js:87:13) gyp ERR! stack at ChildProcess.emit > (events.js:172:7) gyp ERR! stack at > Process.ChildProcess.\_handle.onexit (internal/child\_proces > s.js:200:12) gyp ERR! System Windows\_NT 6.1.7601 gyp ERR! command > "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodej > s\node\_modules\npm\node\_modules\node-gyp\bin\node-gyp.js" > "rebuild" gyp ERR! cwd > D:\ngs-frontend-next\node\_modules\browser-sync\node\_modules\socket. > io\node\_modules\engine.io\node\_modules\ws\node\_modules\bufferutil gyp > ERR! node -v v4.2.2 gyp ERR! node-gyp -v v3.0.3 gyp ERR! not ok npm > WARN optional dep failed, continuing utf-8-validate@1.2.1 > > > > > > > gifsicle@3.0.3 postinstall D:\ngs-frontend-next\node\_modules\gulp-imagemin\nod > > e\_modules\imagemin\node\_modules\imagemin-gifsicle\node\_modules\gifsicle > > node lib/install.js > > > > > > > > > Out **pacakge.json** looks like this : ``` { "name": "Fast-nunjucks", "version": "0.0.1", "description": "A simple boilerplate using nunjucks as a template engine", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "https://github.com/willianjusten/Fast-nunjucks.git" }, "keywords": [ "nunjucks", "node", "gulp", "stylus" ], "author": "Willian Justen de Vasconcellos", "license": "ISC", "bugs": { "url": "https://github.com/willianjusten/Fast-nunjucks/issues" }, "homepage": "https://github.com/willianjusten/Fast-nunjucks", "devDependencies": { "autoprefixer-stylus": "^0.7.1", "browser-sync": "^2.8.2", "gulp": "^3.9.0", "gulp-cache": "^0.3.0", "gulp-concat": "^2.6.0", "gulp-if": "^1.2.5", "gulp-imagemin": "^2.3.0", "gulp-minify-html": "^1.0.4", "gulp-nunjucks-html": "^1.2.2", "gulp-order": "^1.1.1", "gulp-plumber": "^1.0.1", "gulp-stylus": "^2.0.6", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.6", "jeet": "^6.1.2", "kouto-swiss": "^0.11.13", "minimist": "^1.1.3", "rupture": "^0.6.1" }, "dependencies": { "gulp-install": "^0.6.0" } } ```
2015/11/24
[ "https://Stackoverflow.com/questions/33896511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022330/" ]
for this solved it ( OS X ): ```sh rm -rf ~/.node_gyp and sudo npm install -g node-gyp@3.4.0 cd /usr/local/lib sudo ln -s ../../lib/libSystem.B.dylib libgcc_s.10.5.dylib brew install gcc npm install ```
I was stuck with the same error on my windows machine after a lot of troubleshooting with various stack answers I was not able to fix it, later did the following which made it work properly now. 1. npm cache clear --force 2. open explorer in address bar paste %appdata%, then delete the folders npm,npm-cache 3. uninstalled nodejs and reinstalled latest version. 4. then npm install worked fine for me
16,007,094
I'm having problems with this method in python called findall. I'm accessing a web pages HTML and trying to return the name of a product in this case `'bread'` and print it out to the console.
2013/04/15
[ "https://Stackoverflow.com/questions/16007094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051382/" ]
Don't use regex for HTML parsing. There are a few solutions. I suggest BeautifulSoup (<http://www.crummy.com/software/BeautifulSoup/>) Having said so, however, in this particular case, RE will suffice. Just relax it a notch. There might be more or less spaces or maybe those are tabs. So instead of literal spaces use the space class **\s**: ``` product = re.findall(r'Item:\s*is\s*in\s*lane\s*12\s*(\w*)', content) print product[0] ``` Since The '\*', '+', and '?' qualifiers are all greedy (they match as much text as possible) you don't need to restrict it with **`[^<]*<br>`**
In case you still want to use regexps, here's a working one for your case: ``` product = re.findall(r'<br>\s*Item:\s+is\s+in\s+lane 12\s+(\w*)[^<]*<br>', content) ``` It takes into account DSM's space flexibility suggestion and non-letters after `(\w*)` that might appear before `<br>`.
21,790,203
I want to remove double open quotes and double close quotes from the text. By Double opening quotes i mean **“** not **"** I am trying to do it with python. But is unable to read **“**
2014/02/14
[ "https://Stackoverflow.com/questions/21790203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3288929/" ]
how about... ``` >>> s = "“hello“" >>> s.replace('“','') 'hello' >>> ```
Well, since you didn't want to say how you initially did it in excel, here's how you remove those: * Option 1: Use the Find/Replace with find `“` and replace with nothing then find `”` and replace with nothing. * Option 2: In excel, use `CHAR(147)` to have `“` and `CHAR(148)` to have `”`. Then `SUBSTITUTE` to remove them: ``` =SUBSTITUTE(SUBSTITUTE(A1, CHAR(147), ""), CHAR(148), "") ```
60,229,299
If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay more attention to comments): ``` # Drink some water to keep your body hydrated: initialize some parameters # Choice a glass: pick up the glass number one if the glass was dirty: wash the dishes # this would be difficult. # Pour the glass with water: while the glass is not filled up: pour the glass ``` All I'm saying we are looking for simplicity and when you are in the middle of a code, it's better to know where you are exactly. See the comments again but this time as headers: ``` # h1 initialize some parameters # h2: pick up the glass number one if the glass was dirty: wash the dishes # h2: while the glass is not filled up: pour the glass ``` so when you see the comment `h2`s it would be convenient to know that this part of code is subcode of `h1`: I used to make the first letter capital as `h1` for comments, and the following code blocks that are related are not capital. Let's wipe out the codes and just focus on the comments: ``` # Drink some water to keep your body hydrated: ... line of codes ... # choice a glass: ... line of codes ... # pour the glass with water: ... line of codes ... ``` There are some pros and coins with that: *pros:* * Easy to use. *coins:* * It doesn't come to the mind right of way. * If you have more subcategory code this doesn't work. So I was like "why don't I share this with others to see what they think and what they prefer or use", said it to myself.
2020/02/14
[ "https://Stackoverflow.com/questions/60229299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7643771/" ]
I think what you will find, is if you run your application, it will log an error like `requried a single bean but 2 were found`. What you can do however is remove the ambiguity using the @Qualifier where you need it injected and naming your bean definitions, i.e. for your example. ``` @Configuration public class Configuration { @Bean(name="restTemplateA") public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } @Bean(name="restTemplateB") public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } } ``` Then when you come to injecting and using the templates ``` @Service public class someClass { @Autowired @Qualifer("restTemplateA") private RestTemplate restTemplate; } ``` However, you can also mark one of the templates as a Primary with `@Primary`, and this bean will then be used in each place you do not qualify your autowired. ``` @Bean(name="restTemplateA") @Primary public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } ```
Actually, you cannot have both configuration classes, because you'll get a bean name conflict. To fix this, rename the method name: ``` @Bean @Qualifier("restTemplateB") public RestTemplate restTemplateB() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } ``` This way, two `RestTemplate` will be created with `restTemplate` and `restTemplateB` name respectively, and the first one will be injected in the service class.
60,229,299
If you're a python coder you may encounter looking for a way to comments your code better on subcategory code. My meaning by the subcategory code is you may have blocks of codes and then again blocks of codes that relate to the previous block. Here is an example (pay more attention to comments): ``` # Drink some water to keep your body hydrated: initialize some parameters # Choice a glass: pick up the glass number one if the glass was dirty: wash the dishes # this would be difficult. # Pour the glass with water: while the glass is not filled up: pour the glass ``` All I'm saying we are looking for simplicity and when you are in the middle of a code, it's better to know where you are exactly. See the comments again but this time as headers: ``` # h1 initialize some parameters # h2: pick up the glass number one if the glass was dirty: wash the dishes # h2: while the glass is not filled up: pour the glass ``` so when you see the comment `h2`s it would be convenient to know that this part of code is subcode of `h1`: I used to make the first letter capital as `h1` for comments, and the following code blocks that are related are not capital. Let's wipe out the codes and just focus on the comments: ``` # Drink some water to keep your body hydrated: ... line of codes ... # choice a glass: ... line of codes ... # pour the glass with water: ... line of codes ... ``` There are some pros and coins with that: *pros:* * Easy to use. *coins:* * It doesn't come to the mind right of way. * If you have more subcategory code this doesn't work. So I was like "why don't I share this with others to see what they think and what they prefer or use", said it to myself.
2020/02/14
[ "https://Stackoverflow.com/questions/60229299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7643771/" ]
**Case1:** Same method (bean) names in configuration classes. ``` @Configuration public class ConfigurationA { @Bean @Qualifier("restTemplateA") public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } } @Configuration public class ConfigurationB { @Bean @Qualifier("restTemplateB") public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } } ``` **Result:** restTemplate in ConfigrationB is injected. restTemplate in ConfiguratioA is **overridden** by restTemplate in ConfigurationB as can be found in the logs: > > o.s.b.f.s.DefaultListableBeanFactory : **Overriding bean definition** > for bean 'restTemplate' with a different definition: replacing ... > > > **Important Note**: Bean overriding is disabled by default from spring boot version 2.1 (you can check this [link](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.1-Release-Notes#bean-overriding)) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Case2:** Changing method name in ConfigurationB to restTemplateB. ``` @Configuration public class ConfigurationA { @Bean @Qualifier("restTemplateA") public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } } @Configuration public class ConfigurationB { @Bean @Qualifier("restTemplateB") public RestTemplate restTemplateB() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } } ``` **Result:** Both beans in ConfigurationA an ConfigurationB are created. Bean in ConfigurationA is injected. Because bean name will be used if a by-type autowiring doesn't find a single matching bean. Check [this](https://stackoverflow.com/a/30360853/10550738) for more information
Actually, you cannot have both configuration classes, because you'll get a bean name conflict. To fix this, rename the method name: ``` @Bean @Qualifier("restTemplateB") public RestTemplate restTemplateB() { RestTemplate restTemplate = new RestTemplate(); //setting some restTemplate properties return restTemplate; } ``` This way, two `RestTemplate` will be created with `restTemplate` and `restTemplateB` name respectively, and the first one will be injected in the service class.
72,587,334
In .Net c# there is a function Task.WhenAll that can take a list of tasks to await them. What should I use in python? I am trying to do the same with this: ``` tasks = ... #list of coroutines for task in tasks: await task ```
2022/06/11
[ "https://Stackoverflow.com/questions/72587334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11660685/" ]
After adding tasks to a list, you should use [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) that gives coroutines as an argument list and executes them asynchronously. Also, you could use [`asyncio.create_task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task) that gives a coroutine and calls concurrent tasks in the event loop. ```py import asyncio async def coro(i): await asyncio.sleep(i//2) async def main(): tasks = [] for i in range(5): tasks.append(coro(i)) await asyncio.gather(*tasks) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() ```
Use [`asyncio.gather`](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather) if you're on Python 3.7 or above. From the docs: > > Run awaitable objects in the aws sequence concurrently. > If any awaitable in aws is a coroutine, it is automatically scheduled as a Task. > If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws. > > >
16,808,349
I've installed following packages <https://github.com/zacharyvoase/django-postgres> via pip and virtualenv.: ``` pip install git+https://github.com/zacharyvoase/django-postgres.git ``` It was installed succesfully. I used it in my model(As described in its documentaion) ``` from django.db import models import django_postgres as pg USStates = pg.Enum('states_of_the_usa', ['AL', 'WY']) class Address(pg.CompositeType): line1 = models.CharField(max_length=100) line2 = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=100) zip_code = models.CharField(max_length=10) state = USStates() country = models.CharField(max_length=100) ``` when I try to sync it via shell, it throws an error: ``` (virtualenv) user$ python manage.py sync_pgviews Unknown command: 'sync_pgviews' Type 'manage.py help' for usage. ``` Have I left something after installing an app? And is it the correct way to install django new app?
2013/05/29
[ "https://Stackoverflow.com/questions/16808349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1089202/" ]
In order for management commands to work, the app has to be added to `INSTALLED_APPS`. However, a basic problem that you have is that the module doesn't support [`ENUM`](http://www.postgresql.org/docs/9.1/static/datatype-enum.html) yet. Its still a work in progress.
After adding new app: 1. add app to INSTALLED\_APPS in settings.py 2. run python manage.py syncdb 3. add urls to urls.py Perhaps you should go through this (again?) <https://docs.djangoproject.com/en/dev/intro/tutorial01/>
32,533,820
``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list. example\_List = [1,2,2,3,4] It should return True. So far I have this ``` def checkList(List1): for i in range(len(List1 - 1)): if list1[i] == 2 and list1[i+1] == 2: return True return False ``` I get the error, Error:unsupported operand type(s) for -: 'list' and 'int' Thanks!
2015/09/12
[ "https://Stackoverflow.com/questions/32533820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The issue is with this part: ``` len(List1 - 1) ``` You should change it into ``` len(List1) - 1 ``` And you should use the same case for variable List1. Change ``` if list1[i] == 2 and list1[i+1] == 2: ``` to: ``` if List1[i] == 2 and List1[i+1] == 2: ```
Replace ``` len(List1 - 1) ``` for ``` len(List1) - 1 ```
32,533,820
``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list. example\_List = [1,2,2,3,4] It should return True. So far I have this ``` def checkList(List1): for i in range(len(List1 - 1)): if list1[i] == 2 and list1[i+1] == 2: return True return False ``` I get the error, Error:unsupported operand type(s) for -: 'list' and 'int' Thanks!
2015/09/12
[ "https://Stackoverflow.com/questions/32533820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The issue is with this part: ``` len(List1 - 1) ``` You should change it into ``` len(List1) - 1 ``` And you should use the same case for variable List1. Change ``` if list1[i] == 2 and list1[i+1] == 2: ``` to: ``` if List1[i] == 2 and List1[i+1] == 2: ```
first of all, the error you are getting is because of ``` for i in range(len(List1 - 1)): ``` this should be ``` for i in range(len(List1) - 1)): ``` here is an example of code you can use ``` def checkList(List1): for i in range(len(List1) - 1)): if List1(i) == List(i+1): return True ```
32,533,820
``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list. example\_List = [1,2,2,3,4] It should return True. So far I have this ``` def checkList(List1): for i in range(len(List1 - 1)): if list1[i] == 2 and list1[i+1] == 2: return True return False ``` I get the error, Error:unsupported operand type(s) for -: 'list' and 'int' Thanks!
2015/09/12
[ "https://Stackoverflow.com/questions/32533820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The issue is with this part: ``` len(List1 - 1) ``` You should change it into ``` len(List1) - 1 ``` And you should use the same case for variable List1. Change ``` if list1[i] == 2 and list1[i+1] == 2: ``` to: ``` if List1[i] == 2 and List1[i+1] == 2: ```
Here is also a one liner: ``` def check( l,i ): return i in l and l[-1] != i and l[l.index(i)+1] == i ``` Admittedly not the nicest one but I guess still better than the nested loops
32,533,820
``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list. example\_List = [1,2,2,3,4] It should return True. So far I have this ``` def checkList(List1): for i in range(len(List1 - 1)): if list1[i] == 2 and list1[i+1] == 2: return True return False ``` I get the error, Error:unsupported operand type(s) for -: 'list' and 'int' Thanks!
2015/09/12
[ "https://Stackoverflow.com/questions/32533820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Replace ``` len(List1 - 1) ``` for ``` len(List1) - 1 ```
first of all, the error you are getting is because of ``` for i in range(len(List1 - 1)): ``` this should be ``` for i in range(len(List1) - 1)): ``` here is an example of code you can use ``` def checkList(List1): for i in range(len(List1) - 1)): if List1(i) == List(i+1): return True ```
32,533,820
``So I'm basically trying to see if two items in a python list are beside each other. For example, if I'm looking to see if the number 2 is beside an element in this list. example\_List = [1,2,2,3,4] It should return True. So far I have this ``` def checkList(List1): for i in range(len(List1 - 1)): if list1[i] == 2 and list1[i+1] == 2: return True return False ``` I get the error, Error:unsupported operand type(s) for -: 'list' and 'int' Thanks!
2015/09/12
[ "https://Stackoverflow.com/questions/32533820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Here is also a one liner: ``` def check( l,i ): return i in l and l[-1] != i and l[l.index(i)+1] == i ``` Admittedly not the nicest one but I guess still better than the nested loops
first of all, the error you are getting is because of ``` for i in range(len(List1 - 1)): ``` this should be ``` for i in range(len(List1) - 1)): ``` here is an example of code you can use ``` def checkList(List1): for i in range(len(List1) - 1)): if List1(i) == List(i+1): return True ```
50,205,683
I'm using Ubuntu 14.04 with Django 2.0.5 with Django Cookiecutter. I am trying to start a Django server on DigitalOcean and trying to bind gunicorn to 0.0.0.0:8000. python manage.py runserver works fine, but the issue is that it says it can't import environ. Any tips are greatly appreciated, Thanks. I've ran > > pip install-r base.txt > > > pip install-r local.txt > > > pip install-r production.txt > > > and reinstalled django-environ 0.4.4 **This is the error that I receive when I run the following gunicorn command:** > > sudo gunicorn --bind 0.0.0.0:8000 config.wsgi:application > > > ``` (venv) root@django-manaland:/home/django/mana/manaland# sudo gunicorn -b 0.0.0.0:8000 config.wsgi:application [2018-05-07 00:12:32 +0000] [20500] [INFO] Starting gunicorn 19.8.1 [2018-05-07 00:12:32 +0000] [20500] [INFO] Listening at: http://0.0.0.0:8000 (20500) [2018-05-07 00:12:32 +0000] [20500] [INFO] Using worker: sync [2018-05-07 00:12:32 +0000] [20503] [INFO] Booting worker with pid: 20503 [2018-05-07 00:12:32 +0000] [20503] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 129, in init_process self.load_wsgi() File "/usr/local/lib/python3.5/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load return self.load_wsgiapp() File "/usr/local/lib/python3.5/dist-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/local/lib/python3.5/dist-packages/gunicorn/util.py", line 350, in import_app __import__(module) File "/home/django/mana/manaland/config/wsgi.py", line 38, in <module> application = get_wsgi_application() File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 22, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.5/dist-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/django/mana/manaland/config/settings/production.py", line 3, in <module> from .base import * # noqa File "/home/django/mana/manaland/config/settings/base.py", line 5, in <module> import environ ImportError: No module named 'environ' [2018-05-07 00:12:32 +0000] [20503] [INFO] Worker exiting (pid: 20503) [2018-05-07 00:12:32 +0000] [20500] [INFO] Shutting down: Master [2018-05-07 00:12:32 +0000] [20500] [INFO] Reason: Worker failed to boot. ``` base.py file ``` """ Base settings to build other settings files upon. """ import environ ROOT_DIR = environ.Path(__file__) - 3 # (manaland/config/settings/base.py - 3 = manaland/) APPS_DIR = ROOT_DIR.path('manaland') env = environ.Env() READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=False) if READ_DOT_ENV_FILE: # OS environment variables take precedence over variables from .env env.read_env(str(ROOT_DIR.path('.env'))) # GENERAL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#debug DEBUG = env.bool('DJANGO_DEBUG', False) # Local time zone. Choices are # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # though not all of them may be available with every OS. # In Windows, this must be set to your system time zone. TIME_ZONE = 'UTC' # https://docs.djangoproject.com/en/dev/ref/settings/#language-code LANGUAGE_CODE = 'en-us' # https://docs.djangoproject.com/en/dev/ref/settings/#site-id SITE_ID = 1 # https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n USE_I18N = True # https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n USE_L10N = True # https://docs.djangoproject.com/en/dev/ref/settings/#use-tz USE_TZ = True # DATABASES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': env.db('DATABASE_URL', default='postgres:///manaland'), } DATABASES['default']['ATOMIC_REQUESTS'] = True # URLS # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf ROOT_URLCONF = 'config.urls' # https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application WSGI_APPLICATION = 'config.wsgi.application' # APPS # ------------------------------------------------------------------------------ DJANGO_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # 'django.contrib.humanize', # Handy template tags 'django.contrib.admin', ] THIRD_PARTY_APPS = [ 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', ] LOCAL_APPS = [ 'manaland.users.apps.UsersConfig', # Your stuff: custom apps go here ] # https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS # MIGRATIONS # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#migration-modules MIGRATION_MODULES = { 'sites': 'manaland.contrib.sites.migrations' } # AUTHENTICATION # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#authentication-backends AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] # https://docs.djangoproject.com/en/dev/ref/settings/#auth-user-model AUTH_USER_MODEL = 'users.User' # https://docs.djangoproject.com/en/dev/ref/settings/#login-redirect-url LOGIN_REDIRECT_URL = 'users:redirect' # https://docs.djangoproject.com/en/dev/ref/settings/#login-url LOGIN_URL = 'account_login' # PASSWORDS # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#password-hashers PASSWORD_HASHERS = [ # https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', ] # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # MIDDLEWARE # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] # STATIC # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = str(ROOT_DIR('staticfiles')) # https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = '/static/' # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = [ str(APPS_DIR.path('static')), ] # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] # MEDIA # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#media-root MEDIA_ROOT = str(APPS_DIR('media')) # https://docs.djangoproject.com/en/dev/ref/settings/#media-url MEDIA_URL = '/media/' # TEMPLATES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#templates TEMPLATES = [ { # https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-TEMPLATES-BACKEND 'BACKEND': 'django.template.backends.django.DjangoTemplates', # https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs 'DIRS': [ str(APPS_DIR.path('templates')), ], 'OPTIONS': { # https://docs.djangoproject.com/en/dev/ref/settings/#template-debug 'debug': DEBUG, # https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders # https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], # https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] # http://django-crispy-forms.readthedocs.io/en/latest/install.html#template-packs CRISPY_TEMPLATE_PACK = 'bootstrap4' # FIXTURES # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#fixture-dirs FIXTURE_DIRS = ( str(APPS_DIR.path('fixtures')), ) # EMAIL # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#email-backend EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.smtp.EmailBackend') # ADMIN # ------------------------------------------------------------------------------ # Django Admin URL regex. ADMIN_URL = r'^admin/' # https://docs.djangoproject.com/en/dev/ref/settings/#admins ADMINS = [ ("""dom""", 'hello@manaland.io'), ] # https://docs.djangoproject.com/en/dev/ref/settings/#managers MANAGERS = ADMINS # django-allauth # ------------------------------------------------------------------------------ ACCOUNT_ALLOW_REGISTRATION = env.bool('DJANGO_ACCOUNT_ALLOW_REGISTRATION', True) # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_AUTHENTICATION_METHOD = 'username' # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_REQUIRED = True # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_EMAIL_VERIFICATION = 'mandatory' # https://django-allauth.readthedocs.io/en/latest/configuration.html ACCOUNT_ADAPTER = 'manaland.users.adapters.AccountAdapter' # https://django-allauth.readthedocs.io/en/latest/configuration.html SOCIALACCOUNT_ADAPTER = 'manaland.users.adapters.SocialAccountAdapter' # Your stuff... # ------------------------------------------------------------------------------ ``` production.py imports ``` import logging from .base import * # noqa from .base import env ``` manage.py ``` #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django # noqa except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise # This allows easy placement of apps within the interior # manaland directory. current_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_path, "manaland")) execute_from_command_line(sys.argv) ```
2018/05/07
[ "https://Stackoverflow.com/questions/50205683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6907366/" ]
You need to run your manage.py file with the local settings ``` python manage.py runserver --settings=config.settings.production ```
you need to set environment variables for you database : if you are on linux machine : ``` $ export DATABASE_URL=postgres://postgres:<password>@127.0.0.1:5432/<DB name given to createdb> ``` cookiecutter doc can help you more for all this : link : <https://cookiecutter-django.readthedocs.io/en/latest/developing-locally.html>
22,882,125
I updated my system to Mavericks and I have a python code using pgdb. How can I install pgdb on my new mac? I tried ``` sudo pip install git+git://github.com/cancerhermit/pgdb.py.git ``` And ``` sudo pip install pgdb ``` And ``` brew install pgdb ``` And I have even tried to install it from PyCharm directly (my first try).
2014/04/05
[ "https://Stackoverflow.com/questions/22882125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/762435/" ]
**Assuming that you want to:** * Replace lower-case letters with lower-case letters * Replace upper-case letters with upper-case letters * Leave spaces and any other non-alphabetic characters as is --- ``` void encrypt (std::string &e) { int size = e.size(); for (int i=0; i<size; i++) { char c = e[i]; if (('A' <= c && c <= 'Z'-11) || ('a' <= c && c <= 'z'-11)) e[i] = c+11; else if ('Z'-11 < c && c <= 'Z') e[i] = c+11-'Z'+'A'; else if ('z'-11 < c && c <= 'z') e[i] = c+11-'z'+'a'; } } ```
You could do something like this: ``` char _character='X'; int _value=static_cast<int>(_character); if(_value!=32)//not space { int _newValue=((_value+11)%90); (_newValue<65)?_newValue+=65:_newValue+=0; char _newCharacter=static_cast<char>(_newValue); } ```
38,958,697
I am working on script in python with BeautifulSoup to find some data from html. I got a stacked and so much confused, my brain stopped working, I don't have any idea how to scrape full address of these elements: ``` <li class="spacer"> <span>Location:</span> <br>Some Sample Street<br> Abbeville, AL 00000 </li> ``` I have tried something like `location = info.find('li', 'spacer').text` but still I got only string "Location: " . Tried with many parents - child relations but still can't figure out how to scrape this one.. Can anybody help me?
2016/08/15
[ "https://Stackoverflow.com/questions/38958697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6285753/" ]
You can choose names for the nodes in your model by passing the optional `name="myname"` argument to pretty much any Tensorflow operator that builds a node. Tensorflow will pick names for graph nodes automatically if you don't specify them, but if you want to identify those nodes to a tool like freeze\_graph.py, then it's best to choose the names yourself. Those names are what you pass to output\_node\_names.
You can get all of the node names in your model with something like: ```py node_names = [node.name for node in tf.get_default_graph().as_graph_def().node] ``` Or with restoring the graph: ```py saver = tf.train.import_meta_graph(/path/to/meta/graph) sess = tf.Session() saver.restore(sess, /path/to/checkpoints) graph = sess.graph print([node.name for node in graph.as_graph_def().node]) ``` You may need to filter these to get only your output nodes, or only the nodes that you want, but this can at least help you get the names for a graph that you have already trained and cannot afford to retrain with `name='some_name'` defined for each node. Ideally, you want to define a `name` parameter for each operation or tensor that you are going to want to access later.
45,489,388
I am working on a Python/Django project, and we need to use two databases. Following the documentation I added a second database like this: ``` DATABASE_URL = os.getenv('DATABASE_URL', 'postgres://*******:********@aws-us-***********:*****/*****') CURRENCIES_URL = os.getenv('CURRENCIES_URL', 'postgres://*******:********@aws-us-***********:*****/*****') DATABASES = { 'default': dj_database_url.parse(DATABASE_URL), 'currencies': dj_database_url.parse(CURRENCIES_URL) } ``` The parse() method returns the data in the format the object is expecting. Then, I have this code: ``` currencies = connection['currencies'].cursor() ``` Basically this allows me to run custom SQL code on the database, by returning its cursor and storing it in `currencies` However when running this code I get this in the console: ``` url(r'^', include('btcmag.urls', namespace="btcmag")), File "/Users/john/.virtualenvs/btcmag/lib/python2.7/site-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/john/btcmag/btcmag/urls.py", line 7, in <module> from . import views File "/Users/john/btcmag/btcmag/views.py", line 4, in <module> from .apis import getTrendingArticles, getTickers, getCurrency, getHistory File "/Users/john/btcmag/btcmag/apis.py", line 9, in <module> currencies = connection['currencies'].cursor() TypeError: 'DefaultConnectionProxy' object has no attribute '__getitem__' ``` Some clarification: * When I run just `currencies = connection.cursor()` it uses the `default` database and works just fine, which tells me it's not the connection module * If I switch `currencies` and `default` in the databases settings it works also fine - running `currencies = connection.cursor()` - by using the Currencies DB as default. So the DB is not the issue either. What could be causing the issue here?
2017/08/03
[ "https://Stackoverflow.com/questions/45489388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7776359/" ]
There is a small but fatal typo in your code. It should be `django.db.connections` instead of your `connection` (you have not specified where that comes from). Quoting from <https://docs.djangoproject.com/en/1.11/topics/db/sql/#executing-custom-sql-directly> > > If you are using more than one database, you can use > django.db.connections to obtain the connection (and cursor) for a > specific database. `django.db.connections` is a dictionary-like object > that allows you to retrieve a specific connection using its alias: > > > > ``` > from django.db import connections > cursor = connections['my_db_alias'].cursor() > # Your code here... > > ``` > >
You can't access `connection` using bracket notation. Perhaps this will work: ``` currencies = DATABASES['currencies'].cursor() ```
52,306,134
I am pretty new to Django. I think I cannot run django application as sudo since all pip related modules are installed for the user and not for the sudo user. So, it's a kind of basic question like how do I run django app that can listen for port 80 as well as port 443. So, far I have tried following option - i.e pre-routing - NAT I run my app using the following command - ``` $python manage.py runserver Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. September 13, 2018 - 03:04:41 Django version 2.1.1, using settings 'WebBlogger.settings' Starting development server at http://127.0.0.1:8000/ ``` Next, here is my iptables settings nothing worked for me though sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000 =============================================================================== ``` $sudo iptables -t nat --line-numbers -n -L Chain PREROUTING (policy ACCEPT) num target prot opt source destination 1 DOCKER all -- 0.0.0.0/0 0.0.0.0/0 ADDRTYPE match dst-type LOCAL 2 REDIRECT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 redir ports 8000 Chain INPUT (policy ACCEPT) num target prot opt source destination Chain OUTPUT (policy ACCEPT) num target prot opt source destination 1 DOCKER all -- 0.0.0.0/0 !127.0.0.0/8 ADDRTYPE match dst-type LOCAL Chain POSTROUTING (policy ACCEPT) num target prot opt source destination 1 MASQUERADE all -- 172.17.0.0/16 0.0.0.0/0 2 RETURN all -- 192.168.122.0/24 224.0.0.0/24 3 RETURN all -- 192.168.122.0/24 255.255.255.255 4 MASQUERADE tcp -- 192.168.122.0/24 !192.168.122.0/24 masq ports: 1024-65535 5 MASQUERADE udp -- 192.168.122.0/24 !192.168.122.0/24 masq ports: 1024-65535 6 MASQUERADE all -- 192.168.122.0/24 !192.168.122.0/24 Chain DOCKER (2 references) num target prot opt source destination 1 RETURN all -- 0.0.0.0/0 0.0.0.0/0 ``` I did http:// and I see connection refused. I have no idea how to debug the NAT stuff whether it is actually hitting NAT or not. How can I debug and also what is the correct solution to it?
2018/09/13
[ "https://Stackoverflow.com/questions/52306134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10318265/" ]
Ideally module should go into your site packages. Do you see it there? If its there then check your package path. You package may be steplib, but have you checked if you are importing right package and module there. For example within your steplib folder you might have additional package and module within it. Say package is X and module is Y. Then you can import it as below. ``` from X import Y ``` Make sure you have **init**.py in your package to qualify that as a package.
Did you install the package in the python directory under Lib?
23,909,292
I am new to mqtt and still discovering this interesting protocol. I want to create a client in python that publishes every 10 seconds a message. Until now I succeed to publish only one message and keep the client connected to the broker. How can I make the publishing part a loop ? Below is my client: ``` import mosquitto mqttc=mosquitto.Mosquitto("ioana") mqttc.connect("127.0.0.1",1884,60,True) mqttc.publish("test","Hello") mqttc.subscribe("test/", 2) while mqttc.loop() == 0: pass ``` Thanks.
2014/05/28
[ "https://Stackoverflow.com/questions/23909292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3683176/" ]
You can sleep between calls: ``` import mosquitto import time # import time module mqttc=mosquitto.Mosquitto("ioana") mqttc.connect("127.0.0.1",8000,60,True) mqttc.subscribe("test/", 2) while mqttc.loop() == 0: mqttc.publish("test","Hello") time.sleep(10)# sleep for 10 seconds before next call ```
I would suggest: ``` import paho.mqtt.client as mqtt # mosquitto.py is deprecated import time mqttc = mqtt.Client("ioana") mqttc.connect("127.0.0.1", 1883, 60) #mqttc.subscribe("test/", 2) # <- pointless unless you include a subscribe callback mqttc.loop_start() while True: mqttc.publish("test","Hello") time.sleep(10)# sleep for 10 seconds before next call ```
62,287,967
I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and `scrapy`. `My question is that is there any way to scrape a website without using any library?` If there is a way to scrape a website without using any 3rd party library like `beautifulsoup` and `scrapy`. `It can use builtin libraries` Please suggest me a blog, article or tutorial so that I can learn
2020/06/09
[ "https://Stackoverflow.com/questions/62287967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Instead of using `scrapy` you can use `urllib`. Instead of `beautifulsoup` you can use `regex`. But `scrapy` and `beautifulsoup` do your life easier. `Scrapy`, not easy library so you can use `requests` or `urllib`.
i think the best, popular and easy to learn and use libraries in python web scraping are requests, lxml and BeautifulSoup which has the latest version is bs4 in summary ‘Requests’ lets us make HTML requests to the website’s server for retrieving the data on its page. Getting the HTML content of a web page is the first and foremost step of web scraping. Let’s take a look at the advantages and disadvantages of the Requests Python library **Advantages:** * Simple * Basic/Digest Authentication * International Domains and URLs * Chunked Requests * HTTP(S) Proxy Support **Disadvantages:** * Retrieves only static content of a page * Can’t be used for parsing HTML * Can’t handle websites made purely with JavaScript We know the requests library cannot parse the HTML retrieved from a web page. Therefore, we require lxml, a high performance, blazingly fast, production-quality HTML, and XML parsing Python library. Let’s take a look at the advantages and disadvantages of the lxml Python library. **Advantages:** * Faster than most of the parser out there * Light-weight * Uses element trees * Pythonic API **Disadvantages:** * Does not work well with poorly designed HTML * The official documentation is not very beginner-friendly BeautifulSoup is perhaps the most widely used Python library for web scraping. It creates a parse tree for parsing HTML and XML documents. Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. One major advantage of the Beautiful Soup library is that it works very well with poorly designed HTML and has a lot of functions. The combination of Beautiful Soup and Requests is quite common in the industry. **Advantages:** * Requires a few lines of code * Great documentation * Easy to learn for beginners * Robust * Automatic encoding detection **Disadvantages:** * Slower than lxml If you want to learn how to scrape web pages using Beautiful Soup, this tutorial is for you: [turtorial](https://www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/?utm_source=blog&utm_medium=5-popular-python-libraries-web-scraping) by the way there so many libraries you can try like Scrapy, Selenium Library for Web Scraping, regex and urllib
62,287,967
I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and `scrapy`. `My question is that is there any way to scrape a website without using any library?` If there is a way to scrape a website without using any 3rd party library like `beautifulsoup` and `scrapy`. `It can use builtin libraries` Please suggest me a blog, article or tutorial so that I can learn
2020/06/09
[ "https://Stackoverflow.com/questions/62287967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Instead of using `scrapy` you can use `urllib`. Instead of `beautifulsoup` you can use `regex`. But `scrapy` and `beautifulsoup` do your life easier. `Scrapy`, not easy library so you can use `requests` or `urllib`.
I think it's not possible to scrap websites without using any library. You can refer bellow the blog to learn more about web scraping using python. here explain how anyone can scrap websites using python in an easy manner. <https://spurqlabs.com/how-to-do-web-scraping-crawling-using-python-with-selenium/>
62,287,967
I have just started python. I am trying to web scrape a website to fetch the price and title from it. I have gone through multiple tutorial and blog, the most common libraries are beautiful soup and `scrapy`. `My question is that is there any way to scrape a website without using any library?` If there is a way to scrape a website without using any 3rd party library like `beautifulsoup` and `scrapy`. `It can use builtin libraries` Please suggest me a blog, article or tutorial so that I can learn
2020/06/09
[ "https://Stackoverflow.com/questions/62287967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
i think the best, popular and easy to learn and use libraries in python web scraping are requests, lxml and BeautifulSoup which has the latest version is bs4 in summary ‘Requests’ lets us make HTML requests to the website’s server for retrieving the data on its page. Getting the HTML content of a web page is the first and foremost step of web scraping. Let’s take a look at the advantages and disadvantages of the Requests Python library **Advantages:** * Simple * Basic/Digest Authentication * International Domains and URLs * Chunked Requests * HTTP(S) Proxy Support **Disadvantages:** * Retrieves only static content of a page * Can’t be used for parsing HTML * Can’t handle websites made purely with JavaScript We know the requests library cannot parse the HTML retrieved from a web page. Therefore, we require lxml, a high performance, blazingly fast, production-quality HTML, and XML parsing Python library. Let’s take a look at the advantages and disadvantages of the lxml Python library. **Advantages:** * Faster than most of the parser out there * Light-weight * Uses element trees * Pythonic API **Disadvantages:** * Does not work well with poorly designed HTML * The official documentation is not very beginner-friendly BeautifulSoup is perhaps the most widely used Python library for web scraping. It creates a parse tree for parsing HTML and XML documents. Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. One major advantage of the Beautiful Soup library is that it works very well with poorly designed HTML and has a lot of functions. The combination of Beautiful Soup and Requests is quite common in the industry. **Advantages:** * Requires a few lines of code * Great documentation * Easy to learn for beginners * Robust * Automatic encoding detection **Disadvantages:** * Slower than lxml If you want to learn how to scrape web pages using Beautiful Soup, this tutorial is for you: [turtorial](https://www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/?utm_source=blog&utm_medium=5-popular-python-libraries-web-scraping) by the way there so many libraries you can try like Scrapy, Selenium Library for Web Scraping, regex and urllib
I think it's not possible to scrap websites without using any library. You can refer bellow the blog to learn more about web scraping using python. here explain how anyone can scrap websites using python in an easy manner. <https://spurqlabs.com/how-to-do-web-scraping-crawling-using-python-with-selenium/>
73,071,481
**edit** using utf-16 seems to get me closer in the right direction, but I have csv values that include commas such as "one example value is a description, which is long and can include commas, and quotes" So with my current code: ``` filepath="csv_input/frups.csv" rows = [] with open(filepath, encoding='utf-16') as f: for line in f: print('line=',line) formatted_line=line.strip().split(",") print('formatted_line=',formatted_line) rows.append(formatted_line) print('') ``` Lines get formatted incorrectly: ``` line= "FRUPS" "11111112" "Paahou 11111112, 11111112,11111112" "Bar, Achal" "Iagress" "Unassigned" "Normal" "GaWu , Suaair center will not be able to repair 3 couch part 11111112, 11111112,11111112 . Pleasa to repair . formatted_line= ['"FRUPS"\t"11111112"\t"Parts not able to repair in Suzhou 11111112', ' 11111112', '11111112"\t"Baaaaaar', ' Acaaaal"\t"In Progress"\t"Unassigned"\t"Normal"\t"Got coaow Wu ', ' Suar cat 11111112', ' 11111112', '11111112. Pleasa to repair .'] line= 11111112 formatted_line= ['11111112'] ``` So in this example, the `line` is separated by long spaces, but breaking up by commas is not as reliable for reading data line by line correctly --- I am trying to read a csv line by line in python but each solution leads to a different error. 1. Using pandas: ``` filepath="csv_input/frups.csv" data = pd.read_csv(filepath, encoding='utf-16') for thing in data: print(thing) print('') ``` Fails to read\_csv the file with an error `Error tokenizing data. C error: Expected 7 fields in line 16, saw 8` 2. Using csv\_reader ``` # open file in read mode with open(filepath, 'r') as read_obj: # pass the file object to reader() to get the reader object csv_reader = reader(read_obj) # Iterate over each row in the csv using reader object for row in csv_reader: # row variable is a list that represents a row in csv print(row) ``` Fails with error at `for row in csv_reader` line with `line contains NUL` I've tried to figure out what these `NUL` characters our but trying to investigate using code leads to different errors: ``` data = open(filepath, 'rb').read() print(data.find('\x00')) error: argument should be integer or bytes-like object, not 'str' ``` 3. another read solution trying to strip certain characters ``` with open(filepath,'rb') as f: contents = f.read() contents = contents.rstrip("\n").decode("utf-16") contents = contents.split("\r\n") ``` error: `TypeError: a bytes-like object is required, not 'str'` It seems like my csv has some weird characters that cause python to error out. I can open and view my csv just fine in excel, how can I read my csv line by line? Such as ``` row[0]=['col1','col2','col3'] row[1]=['val1','val2','val3'] etc... ```
2022/07/21
[ "https://Stackoverflow.com/questions/73071481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18283635/" ]
No token expiration date is there for security reasons. If someone steals a token which has no expiration date that token will be able to be used forever. This can be extremely dangerous. Especially if the token is valuable. If a token has expired, the token should be refreshed and then you can request again.
I would say your frontend should manage valid token state properly. Good auth libs have config where you can define when before token expiration is token refreshed. So it should be configured in that way that token won't be never expired on the backend side.
11,203,167
I'm building a site in django that interfaces with a large program written in R, and I would like to have a button on the site that runs the R program. I have that working, using `subprocess.call()`, but, as expected, the server does not continue rendering the view until `subprocess.call()` returns. As this program could take several hours to run, that's not really an option. Is there any way to run the R program and and keep executing the python code? I've searched around, and looked into `subprocess.Popen()`, but I couldn't get that to work. Here's the generic code I'm using in the view: ``` if 'button' in request.POST: subprocess.call('R CMD BATCH /path/to/script.R', shell=True) return HttpResponseRedirect('') ``` Hopefully I've just overlooked something simple. Thank you.
2012/06/26
[ "https://Stackoverflow.com/questions/11203167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1134853/" ]
``` subprocess.Popen(['R', 'CMD', 'BATCH', '/path/to/script.R']) ``` The process will be started asynchronously. Example: ``` $ cat 1.py import time import subprocess print time.time() subprocess.Popen(['sleep', '1000']) print time.time() $ python 1.py 1340698384.08 1340698384.08 ``` You must note that the child process will run even after the main process stops.
You may use a wrapper for subprocess.call(), that wrapper would have its own thread within which it will call subprocess.call() method.
58,455,611
Currently I’m working on a corpus/dataset. It’s in xml format as you can see the picture below. I’m facing a problem. I want to access all **‘ne’** elements one by one as shown in below picture. Then I want to access the **text of the ‘W’ elements** which are inside the ‘ne’ elements. Then I want to **concatenate** thy symbols **‘SDi’ and ‘EDi’** with the text of these ‘W’ elements. ‘i’ can take any positive whole number starting from 1. In the case of ‘SDi’ I need only the **text of first ‘W’** element that is inside the ‘ne’ element. In the case of ‘EDi’ I need only the **text of last ‘W’ element** that is inside the ‘ne’ element. Currently I don't get anything as output after running the code. I think this is because of the fact that the element 'W' is never accessed. Moreover, i think that element 'W' is not accessed because it is a grandchild of element 'ne' therefore it can't be accessed directly rather it may be possible with the help its father node. Note1: The number and names of sub elements inside ‘ne’ elements are not same. Note2: Only those things are explained here which needed. You may find some other details in the coding/picture but ignore them. I'm using Spyder (python 3.6) Any help would be appreciated. A picture from the XML file I'm working on is given below: [![enter image description here](https://i.stack.imgur.com/70UyY.png)](https://i.stack.imgur.com/70UyY.png) Text version of XML file: [Click here](https://drive.google.com/file/d/1PWvqpr758yb87OCtKao77TJWzBirLy1D/view?usp=sharing) Sample/Expected output image (below): [![enter image description here](https://i.stack.imgur.com/IgTLj.png)](https://i.stack.imgur.com/IgTLj.png) Coding I've done so far: ``` for i in range(len(List_of_root_nodes)): true_false = True current = List_of_root_nodes[i] start_ID = current.PDante_ID #print('start:', start_ID) # For Testing end_ID = None number = str(i+1) # This number will serve as i used with SD and ED that is (SDi and EDi) discourse_starting_symbol = "SD" + number discourse_ending_symbol = "ED" + number while true_false: if current.right_child is None: end_ID = current.PDante_ID #print('end:', end_ID) # For Testing true_false = False else: current = current.right_child # Finding 'ne' element with id='start_ID' ne_text = None ne_id = None for ne in myroot.iter('ne'): ne_id = ne.get('id') # If ne_id matches with start_ID means the place where SDi is to be placed is found if ne_id == start_ID: for w in ne.iter('W'): ne_text = str(w.text) boundary_and_text = " " + str(discourse_starting_symbol) + " " + ne_text w.text = boundary_and_text break # If ne_id matches with end_ID means the place where EDi is to be placed is found # Some changes Required here: Here the 'EDi' will need to be placed after the last 'W' element. # So last 'W' element needs to be accessed if ne_id == end_ID: for w in ne.iter('W'): ne_text = str(w.text) boundary_and_text = ne_text + " " + str(discourse_ending_symbol) + " " w.text = boundary_and_text break ```
2019/10/18
[ "https://Stackoverflow.com/questions/58455611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5067040/" ]
The expression `let rec c_write = "printf(\" %d \");\n"` is not a function. It is a value of type `string` which is bound to a variable named `c_write`. So you're not using any I/O functions in your code. When entered in the interactive toplevel, this value is printed by the interpreter evaluation loop for user convenience. The same as when a Python interpreter will print for you the value that you've just entered. The representation, chosen by the OCaml toplevel interpreter, in general, has nothing to do with the representation which is used to store a value in a file or to print it. Moreover, in OCaml, there is no canonical representations. If you want to write a function that prints a C printf statement then this is how it will look like in OCaml ``` let print_printf () = print_endline {|printf("%d");|} ``` In the example above, I've used `{||}` to denote a sting literal instead of more common `""`, since in this literal there is no need to escape special characters and they are interpreted literally (i.e., the don't have any special meaning). You can achieve the same result using the regular `""` quotes for denoting it ``` let print_printf () = print_endline "printf(\"%d\");" ``` Here is an example of the toplevel interaction using these definitions: ``` # let print_printf () = print_endline {|printf("%d");|};; val print_printf : unit -> unit = <fun> # print_printf ();; printf("%d"); - : unit = () # let print_printf () = print_endline "printf(\"%d\");";; val print_printf : unit -> unit = <fun> # print_printf ();; printf("%d"); - : unit = () ``` If you will put this code in a file, compile, and execute and redirect into a C file it will be a well-formed C file (modulo the absence of the function body).
Since you are somehow using the toplevel printer for printing, and that you somehow needs a very specific format, you need to install a custom printer. The following would work: ``` # #install_printer Format.pp_print_string;; # " This \" is not escaped " ;; - : string = This " is not escaped ``` However, it seems very likely that this is not really the problem that you are trying to solve.
1,460,559
I'm using Django's `render_to_response` to write data out to an html page, but I'd also like that render\_ to \_response call to load a python dictionary into a javascript associative array. What's the best way to do this?
2009/09/22
[ "https://Stackoverflow.com/questions/1460559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72106/" ]
Convert it to JSON and include, in your template.html, inside a `<script>` tag, something like ``` var my_associative_array = {{ json_data }} ``` after having JSON-encoded your Python dict into a string and put it in the context using key `json_data`.
What does that mean exactly? If you mean you think data in the template is in JavaScript terms, it isn't: You can use python objects in the template directly. If you mean, how do I embed a JSON literal from a Python dictionary or list into my template: Encode it with simplejson, which is included with Django. But, you often don't want to do this for a couple reasons. If you include this dynamic data in the template, you can't cache it as easily. Shouldn't this be another view that is generating a JS file you're including? Or maybe an AJAX call to grab the data once the page is live? Take the pick for what best fits you situation.
1,460,559
I'm using Django's `render_to_response` to write data out to an html page, but I'd also like that render\_ to \_response call to load a python dictionary into a javascript associative array. What's the best way to do this?
2009/09/22
[ "https://Stackoverflow.com/questions/1460559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72106/" ]
Vinay Sajip is close however you add to add the safe filter to avoid django from auto escaping the json data, so this would work (there are other ways to stop the auto escaping but this is the easiest one): ``` var my_associative_array = {{ json_data|safe }} ```
What does that mean exactly? If you mean you think data in the template is in JavaScript terms, it isn't: You can use python objects in the template directly. If you mean, how do I embed a JSON literal from a Python dictionary or list into my template: Encode it with simplejson, which is included with Django. But, you often don't want to do this for a couple reasons. If you include this dynamic data in the template, you can't cache it as easily. Shouldn't this be another view that is generating a JS file you're including? Or maybe an AJAX call to grab the data once the page is live? Take the pick for what best fits you situation.
1,460,559
I'm using Django's `render_to_response` to write data out to an html page, but I'd also like that render\_ to \_response call to load a python dictionary into a javascript associative array. What's the best way to do this?
2009/09/22
[ "https://Stackoverflow.com/questions/1460559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72106/" ]
Vinay Sajip is close however you add to add the safe filter to avoid django from auto escaping the json data, so this would work (there are other ways to stop the auto escaping but this is the easiest one): ``` var my_associative_array = {{ json_data|safe }} ```
Convert it to JSON and include, in your template.html, inside a `<script>` tag, something like ``` var my_associative_array = {{ json_data }} ``` after having JSON-encoded your Python dict into a string and put it in the context using key `json_data`.
20,658,451
I've opened Aptana Studio 3 (Ubuntu 10.04) just like I did it hundreds times before (last time was yesterday). But this time I see EMPTY workspace. No projects. No error messages. Nothing. Screen attached. I have not changed anything since the last time I used Aptana Studio (yesterday). I have not switched workspace or nothing like this. I've always had one workspace. I'm also using pydev extention - all my projects are python/django if that matters. It happened to me AGAIN, but last time it happened on my laptopt where I wanted to format disk and re-install the system anyway so I ignored it and simply re-installed everything. Now it happened on my PC where I have a lot of important projects. BTW, all my projects were not in default location (ie. workspace folder). I added them from other locations and workspace folder was actually empty. I don't know if this might have something to do with the issue. Any ideas how to quickly fix this? ![Aptana Studio 3 Destroyed My Workspace](https://i.stack.imgur.com/KSIuM.png)
2013/12/18
[ "https://Stackoverflow.com/questions/20658451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/367181/" ]
I had this problem and after freaking out I looked around and found File -> Switch Workspace and choosing my workspace loaded everything as normal.
I solved the problem by manually adding the projects back to workspace. Wasn't that bad. I still don't know why they disappeared.
63,442,415
I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size. However, I need to understand the class written in python so I can figure out how to override it. But I did not find any python documentation that shows what the code looks like for QLabel. There is just documentation for c++. Hence, I wanted to know where I can get the python code for all of PyQt5 if that exists? If not, how can I change the font size of all QLabels used in my code?
2020/08/16
[ "https://Stackoverflow.com/questions/63442415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12946401/" ]
Qt Stylesheets -------------- This is probably the easiest way to do in your situation, you are really trying to apply a specific "style" to all your QLabels. You can apply a style to your whole application, or a specific window, and this will affect all children that match the selectors. So in your case, to apply to *all widgets* in your application you can do the following to set the font size of all `QLabel` instances: ``` app = QApplication([]) app.setStyleSheet('.QLabel { font-size: 14pt;}') ``` **Note:** Be sure to set the stylesheet *before* attaching your widgets to its parent, otherwise you would need to manually trigger a style refresh. ### Also... * The `.QLabel` selector will only apply to `QLabel` class instances, and not to classes that inherit `QLabel`. To apply to both QLabel and inherited classes, use `QLabel {...}` instead of `.QLabel {...}` in the stylesheet. Some documentation to help you beyond that: * Qt stylesheet documentation: <https://doc.qt.io/qt-5/stylesheet.html> * Qt stylesheet syntax: <https://doc.qt.io/qt-5/stylesheet-syntax.html> * Qt stylesheet reference: <https://doc.qt.io/qt-5/stylesheet-reference.html> * PyQt documentation: <https://doc.qt.io/qtforpython/api.html>
Completing Adrien's answer, you can use `QFont` class and perform `.setFont()` method for every button. ```py my_font = QFont("Times New Roman", 12) my_button.setFont(my_font) ``` Using this class you can also change some font parameters, see <https://doc.qt.io/qt-5/qfont.html> Yeah, documentation for C++ is okay to read because all methods & classes from C++ are implemented in Python. UPD: `QWidget` class also has `setFont` method so you can set font size on `centralwidget` as well as using stylesheets.
63,442,415
I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size. However, I need to understand the class written in python so I can figure out how to override it. But I did not find any python documentation that shows what the code looks like for QLabel. There is just documentation for c++. Hence, I wanted to know where I can get the python code for all of PyQt5 if that exists? If not, how can I change the font size of all QLabels used in my code?
2020/08/16
[ "https://Stackoverflow.com/questions/63442415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12946401/" ]
To change the font of all QLabels then there are several options: * Use Qt StyleSheet ```css app.setStyleSheet("QLabel{font-size: 18pt;}") ``` * Use [`QApplication::setFont()`](https://doc.qt.io/qt-5/qapplication.html#setFont) ```py custom_font = QFont() custom_font.setWeight(18); QApplication.setFont(custom_font, "QLabel") ```
Qt Stylesheets -------------- This is probably the easiest way to do in your situation, you are really trying to apply a specific "style" to all your QLabels. You can apply a style to your whole application, or a specific window, and this will affect all children that match the selectors. So in your case, to apply to *all widgets* in your application you can do the following to set the font size of all `QLabel` instances: ``` app = QApplication([]) app.setStyleSheet('.QLabel { font-size: 14pt;}') ``` **Note:** Be sure to set the stylesheet *before* attaching your widgets to its parent, otherwise you would need to manually trigger a style refresh. ### Also... * The `.QLabel` selector will only apply to `QLabel` class instances, and not to classes that inherit `QLabel`. To apply to both QLabel and inherited classes, use `QLabel {...}` instead of `.QLabel {...}` in the stylesheet. Some documentation to help you beyond that: * Qt stylesheet documentation: <https://doc.qt.io/qt-5/stylesheet.html> * Qt stylesheet syntax: <https://doc.qt.io/qt-5/stylesheet-syntax.html> * Qt stylesheet reference: <https://doc.qt.io/qt-5/stylesheet-reference.html> * PyQt documentation: <https://doc.qt.io/qtforpython/api.html>
63,442,415
I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size. However, I need to understand the class written in python so I can figure out how to override it. But I did not find any python documentation that shows what the code looks like for QLabel. There is just documentation for c++. Hence, I wanted to know where I can get the python code for all of PyQt5 if that exists? If not, how can I change the font size of all QLabels used in my code?
2020/08/16
[ "https://Stackoverflow.com/questions/63442415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12946401/" ]
While the provided answers should have already given you enough suggestions, I'd like to add some insight. Are there python sources for Qt? ================================ First of all, you cannot find "the class written in python", because (luckily) there's none. PyQt is a [*binding*](https://en.wikipedia.org/wiki/Language_binding): it is an interface to the actual Qt library, which is written in C++. As you might already know, while Python is pretty fast on nowadays computers, it's [not *that* fast](https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/gpp-python3.html), so using a binding is a very good compromise: it allows the simple syntax Python provides, and gives all speed provided by C++ compiled libraries under the hood. You can find the source code for Qt widgets [here](https://github.com/qt/qtbase/tree/dev/src/widgets) (official mirror), or [here](https://code.woboq.org/qt5/qtbase/src/widgets/). How to override the default font? ================================= Well, this depends on how you're going to manage your project. Generally speaking, you can set the default font [size] for a specific widget, for its *child* widgets, for the top level window or even for the whole application. And there are at least two ways to do it. 1. use `setFont()`: it sets the default font for the *target*; you can get the current default font using `something.font()`, then use [`font.setPointSize()`](https://doc.qt.io/qt-5/qfont.html#setPointSize) (or [`setPointSizeF()`](https://doc.qt.io/qt-5/qfont.html#setPointSizeF) for float values, if the font allows it) and then call `setFont(font)` on the target. 2. use [`font[-*]`](https://doc.qt.io/qt-5/stylesheet-reference.html#font) in the target `setStyleSheet()`; Target? ------- The target might be the widget itself, one of its parents or even the [`QApplication.instance()`](https://doc.qt.io/qt-5/qcoreapplication.html#instance). You can use both `setFont()` or `setStyleSheet()` on any of them: ``` font = self.font() font.setPointSize(24) # set the font for the widget: self.pushButton.setFont(someFont) # set the font for the top level window (and any of its children): self.window().setFont(someFont) # set the font for *any* widget created in this QApplication: QApplication.instance().setFont(someFont) # the same as... self.pushButton.setStyleSheet(''' font-size: 24px; ''') # etc... ``` Also, consider setting the [`Qt.AA_UseStyleSheetPropagationInWidgetStyles`](https://doc.qt.io/qt-5/qt.html#ApplicationAttribute-enum) attribute for the application instance. Setting and inheritance ----------------------- By default, Qt uses [font propagation](https://www.qt.io/blog/2008/11/16/font-and-palette-propagation-in-qt) (as much as palette propagation) for both `setFont` and `setStyleSheet`, *but* whenever a style sheet is set, it takes precedence, even if it's set on *any* of the parent widgets (up to the top level window *OR* the QApplication instance). Whenever stylesheets are applied, there are various possibilities, based on [CSS Selectors](https://doc.qt.io/qt-5/stylesheet-syntax.html#selector-types): * `'font-size: 24px;'`: no selector, the current widget and any of its child will use the specified font size; * `'QClass { font-size: 24px; }'`: classes and subclasses selector, any widget (including the current instance) and its children of the same class/subclass will use the specified font size: * `'QClass[property="value"] {...}'`: property selector, as the above, but only if the [`property`](https://doc.qt.io/qt-5/qobject.html#property) matches the value; note that values are *always* quoted, and bool values are always lower case; * `'.QClass {...}'`: classes selector, but *not* subclasses: if you're using a subclass of QLabel and the stylesheet is set for `.QLabel`, that stylesheet won't be applied; * `'QClass#objectName {...}'`: apply only for widgets for which [`objectName()`](https://doc.qt.io/qt-5/qobject.html#objectName-prop) matches; * `'QParentClass QClass {...}`': apply for widget of class QClass that are children of `QParentClass` * `'QParentClass > QClass {...}`': apply for widget of class QClass that are *direct* children of `QParentClass` Note that both `setFont` and `setStyleSheet` support propagation, but `setStyle` only works on children when set to the QApplication instance: if you use [`widget.setStyle()`](https://doc.qt.io/qt-5/qwidget.html#setStyle) it won't have effect on any of the widget's children. Finally, remember: * whenever a widget gets reparented, it receives the font, palette and stylesheet of its parent, in "cascading" mode (the closest parent has precedence); * stylesheets have precedence on both palette and font, whenever any of the related properties are set, and palette/font properties are *not* compatible with stylesheets (or, at least, they behave in unexpected ways);
Qt Stylesheets -------------- This is probably the easiest way to do in your situation, you are really trying to apply a specific "style" to all your QLabels. You can apply a style to your whole application, or a specific window, and this will affect all children that match the selectors. So in your case, to apply to *all widgets* in your application you can do the following to set the font size of all `QLabel` instances: ``` app = QApplication([]) app.setStyleSheet('.QLabel { font-size: 14pt;}') ``` **Note:** Be sure to set the stylesheet *before* attaching your widgets to its parent, otherwise you would need to manually trigger a style refresh. ### Also... * The `.QLabel` selector will only apply to `QLabel` class instances, and not to classes that inherit `QLabel`. To apply to both QLabel and inherited classes, use `QLabel {...}` instead of `.QLabel {...}` in the stylesheet. Some documentation to help you beyond that: * Qt stylesheet documentation: <https://doc.qt.io/qt-5/stylesheet.html> * Qt stylesheet syntax: <https://doc.qt.io/qt-5/stylesheet-syntax.html> * Qt stylesheet reference: <https://doc.qt.io/qt-5/stylesheet-reference.html> * PyQt documentation: <https://doc.qt.io/qtforpython/api.html>
63,442,415
I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size. However, I need to understand the class written in python so I can figure out how to override it. But I did not find any python documentation that shows what the code looks like for QLabel. There is just documentation for c++. Hence, I wanted to know where I can get the python code for all of PyQt5 if that exists? If not, how can I change the font size of all QLabels used in my code?
2020/08/16
[ "https://Stackoverflow.com/questions/63442415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12946401/" ]
To change the font of all QLabels then there are several options: * Use Qt StyleSheet ```css app.setStyleSheet("QLabel{font-size: 18pt;}") ``` * Use [`QApplication::setFont()`](https://doc.qt.io/qt-5/qapplication.html#setFont) ```py custom_font = QFont() custom_font.setWeight(18); QApplication.setFont(custom_font, "QLabel") ```
Completing Adrien's answer, you can use `QFont` class and perform `.setFont()` method for every button. ```py my_font = QFont("Times New Roman", 12) my_button.setFont(my_font) ``` Using this class you can also change some font parameters, see <https://doc.qt.io/qt-5/qfont.html> Yeah, documentation for C++ is okay to read because all methods & classes from C++ are implemented in Python. UPD: `QWidget` class also has `setFont` method so you can set font size on `centralwidget` as well as using stylesheets.
63,442,415
I had written a gui using PyQt5 and recently I wanted to increase the font size of all my QLabels to a particular size. I could go through the entire code and individually and change the qfont. But that is not efficient and I thought I could just override the class and set all QLabel font sizes to the desired size. However, I need to understand the class written in python so I can figure out how to override it. But I did not find any python documentation that shows what the code looks like for QLabel. There is just documentation for c++. Hence, I wanted to know where I can get the python code for all of PyQt5 if that exists? If not, how can I change the font size of all QLabels used in my code?
2020/08/16
[ "https://Stackoverflow.com/questions/63442415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12946401/" ]
While the provided answers should have already given you enough suggestions, I'd like to add some insight. Are there python sources for Qt? ================================ First of all, you cannot find "the class written in python", because (luckily) there's none. PyQt is a [*binding*](https://en.wikipedia.org/wiki/Language_binding): it is an interface to the actual Qt library, which is written in C++. As you might already know, while Python is pretty fast on nowadays computers, it's [not *that* fast](https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/gpp-python3.html), so using a binding is a very good compromise: it allows the simple syntax Python provides, and gives all speed provided by C++ compiled libraries under the hood. You can find the source code for Qt widgets [here](https://github.com/qt/qtbase/tree/dev/src/widgets) (official mirror), or [here](https://code.woboq.org/qt5/qtbase/src/widgets/). How to override the default font? ================================= Well, this depends on how you're going to manage your project. Generally speaking, you can set the default font [size] for a specific widget, for its *child* widgets, for the top level window or even for the whole application. And there are at least two ways to do it. 1. use `setFont()`: it sets the default font for the *target*; you can get the current default font using `something.font()`, then use [`font.setPointSize()`](https://doc.qt.io/qt-5/qfont.html#setPointSize) (or [`setPointSizeF()`](https://doc.qt.io/qt-5/qfont.html#setPointSizeF) for float values, if the font allows it) and then call `setFont(font)` on the target. 2. use [`font[-*]`](https://doc.qt.io/qt-5/stylesheet-reference.html#font) in the target `setStyleSheet()`; Target? ------- The target might be the widget itself, one of its parents or even the [`QApplication.instance()`](https://doc.qt.io/qt-5/qcoreapplication.html#instance). You can use both `setFont()` or `setStyleSheet()` on any of them: ``` font = self.font() font.setPointSize(24) # set the font for the widget: self.pushButton.setFont(someFont) # set the font for the top level window (and any of its children): self.window().setFont(someFont) # set the font for *any* widget created in this QApplication: QApplication.instance().setFont(someFont) # the same as... self.pushButton.setStyleSheet(''' font-size: 24px; ''') # etc... ``` Also, consider setting the [`Qt.AA_UseStyleSheetPropagationInWidgetStyles`](https://doc.qt.io/qt-5/qt.html#ApplicationAttribute-enum) attribute for the application instance. Setting and inheritance ----------------------- By default, Qt uses [font propagation](https://www.qt.io/blog/2008/11/16/font-and-palette-propagation-in-qt) (as much as palette propagation) for both `setFont` and `setStyleSheet`, *but* whenever a style sheet is set, it takes precedence, even if it's set on *any* of the parent widgets (up to the top level window *OR* the QApplication instance). Whenever stylesheets are applied, there are various possibilities, based on [CSS Selectors](https://doc.qt.io/qt-5/stylesheet-syntax.html#selector-types): * `'font-size: 24px;'`: no selector, the current widget and any of its child will use the specified font size; * `'QClass { font-size: 24px; }'`: classes and subclasses selector, any widget (including the current instance) and its children of the same class/subclass will use the specified font size: * `'QClass[property="value"] {...}'`: property selector, as the above, but only if the [`property`](https://doc.qt.io/qt-5/qobject.html#property) matches the value; note that values are *always* quoted, and bool values are always lower case; * `'.QClass {...}'`: classes selector, but *not* subclasses: if you're using a subclass of QLabel and the stylesheet is set for `.QLabel`, that stylesheet won't be applied; * `'QClass#objectName {...}'`: apply only for widgets for which [`objectName()`](https://doc.qt.io/qt-5/qobject.html#objectName-prop) matches; * `'QParentClass QClass {...}`': apply for widget of class QClass that are children of `QParentClass` * `'QParentClass > QClass {...}`': apply for widget of class QClass that are *direct* children of `QParentClass` Note that both `setFont` and `setStyleSheet` support propagation, but `setStyle` only works on children when set to the QApplication instance: if you use [`widget.setStyle()`](https://doc.qt.io/qt-5/qwidget.html#setStyle) it won't have effect on any of the widget's children. Finally, remember: * whenever a widget gets reparented, it receives the font, palette and stylesheet of its parent, in "cascading" mode (the closest parent has precedence); * stylesheets have precedence on both palette and font, whenever any of the related properties are set, and palette/font properties are *not* compatible with stylesheets (or, at least, they behave in unexpected ways);
Completing Adrien's answer, you can use `QFont` class and perform `.setFont()` method for every button. ```py my_font = QFont("Times New Roman", 12) my_button.setFont(my_font) ``` Using this class you can also change some font parameters, see <https://doc.qt.io/qt-5/qfont.html> Yeah, documentation for C++ is okay to read because all methods & classes from C++ are implemented in Python. UPD: `QWidget` class also has `setFont` method so you can set font size on `centralwidget` as well as using stylesheets.
18,048,232
I get satchmo to try, but I have a great problem at first try, and I don't understand whats wrong. When I making `$ python clonesatchmo.py` into clear django project, it trows an error: ``` $ python clonesatchmo.py Creating the Satchmo Application Customizing the files Performing initial data synching Traceback (most recent call last): File "manage.py", line 18, in <module> from django.core.management import execute_manager ImportError: cannot import name execute_manager Traceback (most recent call last): File "manage.py", line 18, in <module> from django.core.management import execute_manager ImportError: cannot import name execute_manager Error: Can not copy the static files. Error: Can not syncdb. ``` AND creates a store folder. trying smth like this is working!!: ``` $ python manage.py shell >>> import os, sys >>> print sys.executable /some/path/to/python >>> os.system('bash') $ /some/path/to/python manage.py validate # this is NOT fail on "from django.core.management import execute_manager" ``` I have Django 1.6 and Satchmo 0.9.3, python 2.7.5 (I do not use virtualenv)
2013/08/04
[ "https://Stackoverflow.com/questions/18048232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768419/" ]
Replace the contents of manage.py with the following (from a new django 1.6 project). ``` #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "<app>.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) ```
`execute_manager` was put on the deprecation path as part of the project layout refactor in Django 1.4 <https://docs.djangoproject.com/en/1.4/releases/1.4/#django-core-management-execute-manager>. Per the deprecation policy that means that the code for `execute_manager` has been completely removed in 1.6. If you are seeing this import error then the version of Satchmo you are using has not been updated to be compatible with Django 1.6.
58,176,203
In python, I have gotten quite used to container objects having truthy behavior when they are populated, and falsey behavior when they are not: ```py # list a = [] not a True a.append(1) not a False # deque from collections import deque d = deque() not d True d.append(1) not d False # and so on ``` However, [queue.Queue](https://docs.python.org/3/library/queue.html#queue.Queue) does not have this behavior. To me, this seems odd and a contradiction against almost any other container data type that I can think of. Furthermore, the method `empty` on queue seem to go against coding conventions that avoid race conditions on any other object (checking if a file exists, checking if a list is empty, etc). For example, we would generally say the following is bad practice: ```py _queue = [] if not len(_queue): # do something ``` And should be replaced with ```py _queue = [] if not _queue: # do something ``` or to handle an `IndexError`, which we might still argue would be better with the `if not _queue` statement: ```py try: x = _queue.pop() except IndexError as e: logger.exception(e) # do something else ``` Yet, `Queue` requires someone to do one of the following: ```py _queue = queue.Queue() if _queue.empty(): # do something # though this smells like a race condition # or handle an exception try: _queue.get(timeout=5) except Empty as e: # do something else # maybe logger.exception(e) ``` Is there documentation somewhere that might point to *why* this design choice was made? It seems odd, especially when [the source code](https://github.com/python/cpython/blob/master/Lib/queue.py) shows that it was built on top of `collections.deque` (noted that Queue does *not* inherit from `deque`)
2019/09/30
[ "https://Stackoverflow.com/questions/58176203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867968/" ]
According to the definition of the [truth value testing](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) procedure, the behavior is expected: > > Any object can be tested for truth value, for use in an if or while > condition or as operand of the Boolean operations below. > > > By default, an object is considered true unless its class defines > either a `__bool__()` method that returns False or a `__len__()` method > that returns zero, when called with the object. > > > As Queue does not neither implements `__bool__()` nor `__len__()` then it's truth value is `True`. As to why does Queue does not implement `__len__()` a clue can be found in the comments of the qsize function: > > '''Return the approximate size of the queue (not reliable!).''' > > > The same can be said of the `__bool__()` function.
I'm going to leave the accepted answer as is, but as far as I can tell, the reason is that `if _queue: # do something` *would* be a race condition, since `Queue` is designed to be passed between threads and therefore possesses dubious state as far as tasks go. From the source: ```py class Queue: ~snip~ def qsize(self): '''Return the approximate size of the queue (not reliable!).''' with self.mutex: return self._qsize() def empty(self): '''Return True if the queue is empty, False otherwise (not reliable!). This method is likely to be removed at some point. Use qsize() == 0 as a direct substitute, but be aware that either approach risks a race condition where a queue can grow before the result of empty() or qsize() can be used. To create code that needs to wait for all queued tasks to be completed, the preferred technique is to use the join() method. ''' with self.mutex: return not self._qsize() ~snip ``` Must have missed this helpful docstring when I was originally looking. The `qsize` bool is not tied to the state of the queue once it's evaluated. So the user is doing processing against a queue based on an already out-of-date state. Like checking the existence of a file, it's more pythonic to just handle the exception: ```py try: task = _queue.get(timeout=4) except Empty as e: # do something ``` since the exception/success against `get` *is* the state of the queue. Likewise, we would not do: ```py if os.exists(file): with open(file) as fh: # do processing ``` Instead, we would do: ```py try: with open(file) as fh: # do processing except FileNotFoundError as e: # do something else ``` I suppose the intentional leaving-out of the `__bool__` method by the author is to steer the developer *away* from leaning against such a paradigm, and treating the queue like you would any other object that might be of questionable state.
39,367,963
I did python script: ``` from string import punctuation from collections import Counter import urllib from stripogram import html2text myurl = urllib.urlopen("https://www.google.co.in/?gfe_rd=cr&ei=v-PPV5aYHs6L8Qfwwrlg#q=samsung%20j7") html_string = myurl.read() text = html2text( html_string ) file = open("/home/nextremer/Final_CF/contentBased/contentCount/hi.txt", "w") file.write(text) file.close() ``` Using this script I didn't get perfect output only some HTML code. - I want save all webpage text content in a text file. - I used urllib2 or bs4 but I didn't get results. - I don't want output as a html structure. - I want all text data from webpage
2016/09/07
[ "https://Stackoverflow.com/questions/39367963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6708233/" ]
What do you mean with "webpage text"? It seems you don't want the full HTML-File. If you just want the text you see in your browser, that is not so easily solvable, as the parsing of a HTML-document can be very complex, especially with JavaScript-rich pages. That starts with assessing if a String between "<" and ">" is a regular tag and includes analyzing the CSS-Properties changed by JavaScript-behavior. That is why people write very big and complex rendering-Engines for Webpage-Browsers.
``` import urllib urllib.urlretrieve("http://www.example.com/test.html", "test.txt") ```
39,367,963
I did python script: ``` from string import punctuation from collections import Counter import urllib from stripogram import html2text myurl = urllib.urlopen("https://www.google.co.in/?gfe_rd=cr&ei=v-PPV5aYHs6L8Qfwwrlg#q=samsung%20j7") html_string = myurl.read() text = html2text( html_string ) file = open("/home/nextremer/Final_CF/contentBased/contentCount/hi.txt", "w") file.write(text) file.close() ``` Using this script I didn't get perfect output only some HTML code. - I want save all webpage text content in a text file. - I used urllib2 or bs4 but I didn't get results. - I don't want output as a html structure. - I want all text data from webpage
2016/09/07
[ "https://Stackoverflow.com/questions/39367963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6708233/" ]
You dont need to write any hard algorithms to extract data from search result. Google has a API to do this. Here is an example: <https://github.com/google/google-api-python-client/blob/master/samples/customsearch/main.py> But to use it, first you must to register in google for API Key. All information you can find here: <https://developers.google.com/api-client-library/python/start/get_started>
``` import urllib urllib.urlretrieve("http://www.example.com/test.html", "test.txt") ```
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
While `.get()` is a nice idiom, it's slower than `if/else` (and slower than `try/except` if presence of the key in the dictionary can be expected most of the time): ``` >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10") 0.07691968797894333 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="try:\n a=d[2]\nexcept KeyError:\n a=10") 0.4583777282275605 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="a=d.get(1, 10)") 0.17784020746671558 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="a=d.get(2, 10)") 0.17952161730158878 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="if 1 in d:\n a=d[1]\nelse:\n a=10") 0.10071221458065338 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="if 2 in d:\n a=d[2]\nelse:\n a=10") 0.06966537335119938 ```
(this is a late answer) An alternative is to subclass the `dict` class and implement the [`__missing__()`](https://docs.python.org/3/reference/datamodel.html?highlight=__missing__#object.__missing__) method, like this: ``` class ConnectionDetails(dict): def __missing__(self, key): if key == 'host': return "localhost" raise KeyError(key) ``` Examples: ``` >>> connection_details = ConnectionDetails(port=80) >>> connection_details['host'] 'localhost' >>> connection_details['port'] 80 >>> connection_details['password'] Traceback (most recent call last): File "python", line 1, in <module> File "python", line 6, in __missing__ KeyError: 'password' ```
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
Like this: ``` host = connectionDetails.get('host', someDefaultValue) ```
You can use a lamba function for this as a one-liner. Make a new object `connectionDetails2` which is accessed like a function... ``` connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT" ``` Now use ``` connectionDetails2(k) ``` instead of ``` connectionDetails[k] ``` which returns the dictionary value if `k` is in the keys, otherwise it returns `"DEFAULT"`
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
This is not exactly the question asked for but there is a method in python dictionaries: `dict.setdefault` ```py host = connectionDetails.setdefault('host',someDefaultValue) ``` However this method sets the value of `connectionDetails['host']` to `someDefaultValue` if key `host` is not already defined, unlike what the question asked.
You can use a lamba function for this as a one-liner. Make a new object `connectionDetails2` which is accessed like a function... ``` connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT" ``` Now use ``` connectionDetails2(k) ``` instead of ``` connectionDetails[k] ``` which returns the dictionary value if `k` is in the keys, otherwise it returns `"DEFAULT"`
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
Like this: ``` host = connectionDetails.get('host', someDefaultValue) ```
Testing @Tim Pietzcker's suspicion about the situation in PyPy (5.2.0-alpha0) for Python 3.3.5, I find that indeed both `.get()` and the `if`/`else` way perform similar. Actually it seems that in the if/else case there is even only a single lookup if the condition and the assignment involve the same key (compare with the last case where there is two lookups). ``` >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10") 0.011889292989508249 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="try:\n a=d[2]\nexcept KeyError:\n a=10") 0.07310474599944428 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="a=d.get(1, 10)") 0.010391917996457778 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="a=d.get(2, 10)") 0.009348208011942916 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="if 1 in d:\n a=d[1]\nelse:\n a=10") 0.011475925013655797 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="if 2 in d:\n a=d[2]\nelse:\n a=10") 0.009605801998986863 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="if 2 in d:\n a=d[2]\nelse:\n a=d[1]") 0.017342638995614834 ```
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
While `.get()` is a nice idiom, it's slower than `if/else` (and slower than `try/except` if presence of the key in the dictionary can be expected most of the time): ``` >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10") 0.07691968797894333 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="try:\n a=d[2]\nexcept KeyError:\n a=10") 0.4583777282275605 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="a=d.get(1, 10)") 0.17784020746671558 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="a=d.get(2, 10)") 0.17952161730158878 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="if 1 in d:\n a=d[1]\nelse:\n a=10") 0.10071221458065338 >>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", ... stmt="if 2 in d:\n a=d[2]\nelse:\n a=10") 0.06966537335119938 ```
Testing @Tim Pietzcker's suspicion about the situation in PyPy (5.2.0-alpha0) for Python 3.3.5, I find that indeed both `.get()` and the `if`/`else` way perform similar. Actually it seems that in the if/else case there is even only a single lookup if the condition and the assignment involve the same key (compare with the last case where there is two lookups). ``` >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10") 0.011889292989508249 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="try:\n a=d[2]\nexcept KeyError:\n a=10") 0.07310474599944428 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="a=d.get(1, 10)") 0.010391917996457778 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="a=d.get(2, 10)") 0.009348208011942916 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="if 1 in d:\n a=d[1]\nelse:\n a=10") 0.011475925013655797 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="if 2 in d:\n a=d[2]\nelse:\n a=10") 0.009605801998986863 >>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", .... stmt="if 2 in d:\n a=d[2]\nelse:\n a=d[1]") 0.017342638995614834 ```
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
You can also use the [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) like so: ``` from collections import defaultdict a = defaultdict(lambda: "default", key="some_value") a["blabla"] => "default" a["key"] => "some_value" ``` You can pass any ordinary function instead of lambda: ``` from collections import defaultdict def a(): return 4 b = defaultdict(a, key="some_value") b['absent'] => 4 b['key'] => "some_value" ```
You can use `dict.get()` for default values. ``` d = {"a" :1, "b" :2} x = d.get("a",5) y = d.get("c",6) # This will give # x = 1, y = 6 # as the result ``` Since "a" is in the keys, `x = d.get("a",5)` will return associated value `1`. Since "c" is not in the keys, `y = d.get("c",6)` will return the default value `6`.
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
You can also use the [`defaultdict`](https://docs.python.org/2/library/collections.html#collections.defaultdict) like so: ``` from collections import defaultdict a = defaultdict(lambda: "default", key="some_value") a["blabla"] => "default" a["key"] => "some_value" ``` You can pass any ordinary function instead of lambda: ``` from collections import defaultdict def a(): return 4 b = defaultdict(a, key="some_value") b['absent'] => 4 b['key'] => "some_value" ```
You can use a lamba function for this as a one-liner. Make a new object `connectionDetails2` which is accessed like a function... ``` connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT" ``` Now use ``` connectionDetails2(k) ``` instead of ``` connectionDetails[k] ``` which returns the dictionary value if `k` is in the keys, otherwise it returns `"DEFAULT"`
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
Like this: ``` host = connectionDetails.get('host', someDefaultValue) ```
I am sure that all these answers are ok but it shows that there is no 'nice' way of doing this. I use dictionaries instead of case statements all the time and to add a default clause I just call the following function: ``` def choose(choise, choises, default): """Choose a choice from the choises given """ return choises[choise] if choise in choises else default ``` That way I can use normal dictionaries without special default clauses etc.
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
For multiple different defaults try this: ``` connectionDetails = { "host": "www.example.com" } defaults = { "host": "127.0.0.1", "port": 8080 } completeDetails = {} completeDetails.update(defaults) completeDetails.update(connectionDetails) completeDetails["host"] # ==> "www.example.com" completeDetails["port"] # ==> 8080 ```
I am sure that all these answers are ok but it shows that there is no 'nice' way of doing this. I use dictionaries instead of case statements all the time and to add a default clause I just call the following function: ``` def choose(choise, choises, default): """Choose a choice from the choises given """ return choises[choise] if choise in choises else default ``` That way I can use normal dictionaries without special default clauses etc.
9,358,983
Assuming `connectionDetails` is a Python dictionary, what's the best, most elegant, most "pythonic" way of refactoring code like this? ``` if "host" in connectionDetails: host = connectionDetails["host"] else: host = someDefaultValue ```
2012/02/20
[ "https://Stackoverflow.com/questions/9358983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940208/" ]
Like this: ``` host = connectionDetails.get('host', someDefaultValue) ```
For multiple different defaults try this: ``` connectionDetails = { "host": "www.example.com" } defaults = { "host": "127.0.0.1", "port": 8080 } completeDetails = {} completeDetails.update(defaults) completeDetails.update(connectionDetails) completeDetails["host"] # ==> "www.example.com" completeDetails["port"] # ==> 8080 ```
15,728,081
I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database. The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; that's the server process stay in a loop, listening for incoming packet. Any suggestion would be high value and appreciate. Many thanks in advance.
2013/03/31
[ "https://Stackoverflow.com/questions/15728081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929999/" ]
In case you feel that Celery is a bit oversized for your needs you could also define a [custom management command](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) that lives forever and waits for your incoming packet.
I suggest you to use Celery which works with Django and has support for long running tasks among other features. <http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html> <http://docs.celeryproject.org/en/latest/getting-started/introduction.html>
15,728,081
I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database. The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; that's the server process stay in a loop, listening for incoming packet. Any suggestion would be high value and appreciate. Many thanks in advance.
2013/03/31
[ "https://Stackoverflow.com/questions/15728081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929999/" ]
I suggest you to use Celery which works with Django and has support for long running tasks among other features. <http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html> <http://docs.celeryproject.org/en/latest/getting-started/introduction.html>
<https://github.com/lukedupin/django_posix_spawn> Using management commands in conjunction with this allows you to run django tasks that don't block your website.
15,728,081
I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database. The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; that's the server process stay in a loop, listening for incoming packet. Any suggestion would be high value and appreciate. Many thanks in advance.
2013/03/31
[ "https://Stackoverflow.com/questions/15728081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929999/" ]
I suggest you to use Celery which works with Django and has support for long running tasks among other features. <http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html> <http://docs.celeryproject.org/en/latest/getting-started/introduction.html>
If you need a loop that is "django-aware" and already using celery for async tasks then [celery-eternal](http://celery-eternal.readthedocs.io) might be a good fit. Only caveat is that you must use redis as the celery results backend.
15,728,081
I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database. The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; that's the server process stay in a loop, listening for incoming packet. Any suggestion would be high value and appreciate. Many thanks in advance.
2013/03/31
[ "https://Stackoverflow.com/questions/15728081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929999/" ]
In case you feel that Celery is a bit oversized for your needs you could also define a [custom management command](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) that lives forever and waits for your incoming packet.
<https://github.com/lukedupin/django_posix_spawn> Using management commands in conjunction with this allows you to run django tasks that don't block your website.
15,728,081
I'm doing monitoring work with django. The program required to have a looping-forever sitting in background to process receiving data and update to database. The job could be worked by writing a python script, and run in background with, for example, supervisord. However, I prefer the solution with django itself; that's the server process stay in a loop, listening for incoming packet. Any suggestion would be high value and appreciate. Many thanks in advance.
2013/03/31
[ "https://Stackoverflow.com/questions/15728081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929999/" ]
In case you feel that Celery is a bit oversized for your needs you could also define a [custom management command](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/) that lives forever and waits for your incoming packet.
If you need a loop that is "django-aware" and already using celery for async tasks then [celery-eternal](http://celery-eternal.readthedocs.io) might be a good fit. Only caveat is that you must use redis as the celery results backend.
61,256,730
I'm writing a python code that converts a binary to decimal. ``` def bin_dec (binary): binary_list = list(str(binary)) **for bit in binary_list: if int(bit) > 1 or int(bit) < 0: print('Invalid Binary') print('') exit()** total = 0 argument = 0 binary_length = len(str(binary)) exponent = binary_length - 1 while exponent >= 0: total += (int(binary_list[argument]) * (2**exponent)) argument += 1 exponent -= 1 print(total) print('') ``` When I test the code with neagtive binary numbers I don't see the output "Invalid Binary" Instead I see an integer error ``` >>> bin_dec(-10) Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> bin_dec(-10) File "E:/Bronx Science/Sophomore/Computer Science_Python/Edwin Chen_Lab 8_Diamond and Squares.py", **line 27, in bin_dec if int(bit) > 1 or int(bit) < 0:** ValueError: invalid literal for int() with base 10: '-' ```
2020/04/16
[ "https://Stackoverflow.com/questions/61256730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13332906/" ]
``` $agent = $this->request->getUserAgent(); if ($agent->isBrowser()) { if($this->input->cookie('country')) { $countryId = $this->input->cookie('country'); }else{ redirect(base_url()); } } ```
HTTP 302 response code means that the URL of requested resource has been changed temporarily. Further changes in the URL might be made in the future. Therefore, this same URI should be used by the client in future requests.[You can check this out to learn more](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302) Since you are actually redirecting Non-authenticated users (A category bots belong to), i think the error code is correct. What you can do however, is to add the page to robots.txt file so the page does not get indexed at all.
25,844,794
While executing below code, I am getting error as mentioned. I downloaded the required package from <http://www.cs.unm.edu/~mccune/prover9/download/> and configure. But still same issue. I am getting this error: ``` >>> import nltk >>> dt = nltk.DiscourseTester(['A student dances', 'Every student is a person']) >>> dt.readings() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/nltk/inference/discourse.py", line 351, in readings self._construct_threads() File "/usr/local/lib/python2.7/dist-packages/nltk/inference/discourse.py", line 297, in _construct_threads consistency_checked = self._check_consistency(self._threads) File "/usr/local/lib/python2.7/dist-packages/nltk/inference/discourse.py", line 393, in _check_consistency modelfound = mb.build_model() File "/usr/local/lib/python2.7/dist-packages/nltk/inference/api.py", line 333, in build_model verbose) File "/usr/local/lib/python2.7/dist-packages/nltk/inference/mace.py", line 202, in _build_model verbose=verbose) File "/usr/local/lib/python2.7/dist-packages/nltk/inference/mace.py", line 215, in _call_mace4 self._mace4_bin = self._find_binary('mace4', verbose) File "/usr/local/lib/python2.7/dist-packages/nltk/inference/prover9.py", line 166, in _find_binary verbose=verbose) File "/usr/local/lib/python2.7/dist-packages/nltk/internals.py", line 544, in find_binary binary_names, url, verbose)) File "/usr/local/lib/python2.7/dist-packages/nltk/internals.py", line 538, in find_binary_iter url, verbose): File "/usr/local/lib/python2.7/dist-packages/nltk/internals.py", line 517, in find_file_iter raise LookupError('\n\n%s\n%s\n%s' % (div, msg, div)) LookupError: =========================================================================== NLTK was unable to find the mace4 file! Use software specific configuration paramaters or set the PROVER9HOME environment variable. Searched in: - /usr/local/bin/prover9 - /usr/local/bin/prover9/bin - /usr/local/bin - /usr/bin - /usr/local/prover9 - /usr/local/share/prover9 ``` While configuring the LADR-2009-11 through `make all`, ended process with ``` .o utilities.o provers.o foffer.o ../ladr/libladr.a search.o: In function `search': search.c:(.text+0x6e54): undefined reference to `round' ../ladr/libladr.a(avltree.o): In function `avl_item_at_position': avltree.c:(.text+0x7cb): undefined reference to `ceil' collect2: error: ld returned 1 exit status make[1]: *** [prover9] Error 1 make[1]: Leaving directory `/root/Desktop/karim/software/LADR-2009-11A/provers.src' make: *** [all] Error 2 ```
2014/09/15
[ "https://Stackoverflow.com/questions/25844794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2518644/" ]
Try following code: ``` .mini1 { width: 100%; height: 6.7%; margin-top: -2%; background-image: url('../images/footer1.jpg'); z-index: 10; background-size: 100% 100%; } ``` Please see to it that, image path is correct. Go in console to check for any errors.
Well here is a working JSfiddle: <http://jsfiddle.net/knftvt6v/4/> I believe it is your file path that's causing the error, can you make a JS fiddle ``` .mini1 { width: 100%; height: 2em; margin-top: -2%; background: url('http://www.serenitybaumer.com/main_images/footer.jpg'); z-index: 10; color:white; text-align:center; } ``` I added this block of code in which worked fine
62,221,721
I have created GuI in Visual Studio 2019. [![enter image description here](https://i.stack.imgur.com/g21cN.png)](https://i.stack.imgur.com/g21cN.png) There user will enter username and password and that i have to pass to python script. That when user will click on login button, python script will be triggered and output will be displayed. My Tried python code is: ``` import paramiko import time ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: hostname = input("Enter host IP address: ") username = input("Enter SSH Username: ") password = input("Enter SSH Password: ") port = 22 ssh.connect(hostname, port, username, password, look_for_keys=False) print("ssh login successfully") #stdin,stdout,stderr = ssh.exec_command('show version') #output = stdout.readlines() #print(output) Device_access = ssh.invoke_shell() Device_access.send(b'environment no more \n') Device_access.send(b'show version\n') time.sleep(2) output = Device_access.recv(65000) print (output.decode('ascii')) except: print("error in connection due to wrong input entered") ``` But in this i am not getting how to link with input enter to Gui c# with python script. Please let me know how i can do. Thanks in advance!
2020/06/05
[ "https://Stackoverflow.com/questions/62221721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11699581/" ]
You could use arguments to call your Python Script. Change the python script: ``` import paramiko import time import sys # Used to get arguments ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: hostname = sys.argv[1] # Skip 0th arg, since it is just the filename username = sys.argv[2] password = sys.argv[3] port = 22 ssh.connect(hostname, port, username, password, look_for_keys=False) print("ssh login successfully") #stdin,stdout,stderr = ssh.exec_command('show version') #output = stdout.readlines() #print(output) Device_access = ssh.invoke_shell() Device_access.send(b'environment no more \n') Device_access.send(b'show version\n') time.sleep(2) output = Device_access.recv(65000) print (output.decode('ascii')) except: print("error in connection due to wrong input entered") ``` And change your C# code which calls the Script to something like this: ``` Process pythonScript = new Process(); pythonScript.StartInfo.FileName = "Your python script"; pythonScript.StartInfo.Arguments = $"{YouHostnameVar} {YouUsernameVar} {YourPasswordVar}"; // Start the script with the credentials as arguments pythonScript.Start(); ```
There are multiple approaches to incorporating a Python script with .NET C# code ================================================================================ I will try and give a basic overview, along with my suggestion, but ultimately, it will be up to you to figure out what works best. IronPython ---------- IronPython is an actual separate interpreter to translate Python code into the .NET Common Language Runtime (CLR). It works well for simple Python2 scripts that are not reliant on certain libraries. Python.NET ---------- Python.NET uses the normal Python interpreter. It simply provides a way to interface between Python scripts and .NET code. System Diagnostics (My Suggestion) ---------------------------------- The System Diagnostics C# tool allows you to run Python scripts as a system process. Not that this only runs the Python script. In order to transfer information between the Python script and the C# code, you will need some kind of shared file. I recommend setting up a folder where you save information used by both the C# and Python programs. For a simple implementation of System Diagnostics, along with notes on the particular way System Diagnostics is being called, check out this: <https://www.dotnetlovers.com/article/216/executing-python-script-from-c-sharp> EDIT Based on Paul Sütterlin Answer ----------------------------------- As opposed to using a file to share information, Paul correctly points out that you can pass information as arguments. He also points out the simple process tool in C#, which is easier to set up than System Diagnostics. I recommend you read the article I linked to see which solution best suits you. System diagnostics gives you more options, but they do have to be configured.
1,104,762
How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case. Correct ouptut but strangely indented: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` Bad output, but looks better in code: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` --- Wow, lots of fast answers. Thanks!
2009/07/09
[ "https://Stackoverflow.com/questions/1104762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23002/" ]
Adjacent strings are concatenated at compile time: ``` if True: print ("this is the first line of a very long string" " this is the second line") ``` Output: ``` this is the first line of a very long string this is the second line ```
You can use a trailing backslash to join separate strings like this: ``` if True: print "long test long test long test long test long " \ "test long test long test long test long test long test" ```
1,104,762
How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case. Correct ouptut but strangely indented: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` Bad output, but looks better in code: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` --- Wow, lots of fast answers. Thanks!
2009/07/09
[ "https://Stackoverflow.com/questions/1104762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23002/" ]
Adjacent strings are concatenated at compile time: ``` if True: print ("this is the first line of a very long string" " this is the second line") ``` Output: ``` this is the first line of a very long string this is the second line ```
``` if True: print "long test long test long test long test long"\ "test long test long test long test long test long test" ```
1,104,762
How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case. Correct ouptut but strangely indented: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` Bad output, but looks better in code: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` --- Wow, lots of fast answers. Thanks!
2009/07/09
[ "https://Stackoverflow.com/questions/1104762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23002/" ]
Adjacent strings are concatenated at compile time: ``` if True: print ("this is the first line of a very long string" " this is the second line") ``` Output: ``` this is the first line of a very long string this is the second line ```
``` if True: print "long test long test long test "+ "long test long test long test "+ "long test long test long test " ``` And so on.
1,104,762
How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case. Correct ouptut but strangely indented: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` Bad output, but looks better in code: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` --- Wow, lots of fast answers. Thanks!
2009/07/09
[ "https://Stackoverflow.com/questions/1104762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23002/" ]
Adjacent strings are concatenated at compile time: ``` if True: print ("this is the first line of a very long string" " this is the second line") ``` Output: ``` this is the first line of a very long string this is the second line ```
Why isn't anyone recommending triple quotes? ``` print """ blah blah blah ..............""" ```
1,104,762
How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case. Correct ouptut but strangely indented: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` Bad output, but looks better in code: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` --- Wow, lots of fast answers. Thanks!
2009/07/09
[ "https://Stackoverflow.com/questions/1104762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23002/" ]
``` if True: print "long test long test long test long test long"\ "test long test long test long test long test long test" ```
You can use a trailing backslash to join separate strings like this: ``` if True: print "long test long test long test long test long " \ "test long test long test long test long test long test" ```
1,104,762
How can I break a long one liner string in my code and keep the string indented with the rest of the code? [PEP 8](http://www.python.org/dev/peps/pep-0008/ "PEP-8") doesn't have any example for this case. Correct ouptut but strangely indented: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` Bad output, but looks better in code: ``` if True: print "long test long test long test long test long \ test long test long test long test long test long test" >>> long test long test long test long test long test long test long test long test long test long test ``` --- Wow, lots of fast answers. Thanks!
2009/07/09
[ "https://Stackoverflow.com/questions/1104762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23002/" ]
You can use a trailing backslash to join separate strings like this: ``` if True: print "long test long test long test long test long " \ "test long test long test long test long test long test" ```
``` if True: print "long test long test long test "+ "long test long test long test "+ "long test long test long test " ``` And so on.