qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
620,954
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .
2009/03/07
[ "https://Stackoverflow.com/questions/620954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
Other than pygments? <http://pygments.org/>
If you're using gtk+, there's a binding of gtksourceview for Python in [gnome-python-extras](http://ftp.gnome.org/pub/GNOME/sources/gnome-python-extras/2.25/). It seems to work well in my experience. The downside: the documentation is less than perfect. There's also a binding of [QScintilla](http://www.riverbankcomputing.co.uk/software/qscintilla/intro) for Python if PyQt is your thing.
620,954
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .
2009/03/07
[ "https://Stackoverflow.com/questions/620954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
Other than pygments? <http://pygments.org/>
You can use [StyledTextCtrl](http://www.wxpython.org/docs/api/wx.stc.StyledTextCtrl-class.html) in [wxPython](http://www.wxpython.org). Check out the official demo for an example (The *demo code* tab for any demo).
620,954
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .
2009/03/07
[ "https://Stackoverflow.com/questions/620954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
Other than pygments? <http://pygments.org/>
You say "in a GUI app" but don't mention the toolkit. If you are using PyQt, and need a read-only widget, you can use QWebKit which has a whole HTML widget in it based on WebKit, so it supports pretty much anything, from flash to the ACID2 test. If you want a read-write widget, Qt's QTextEdit supports syntax highlighting, and I wrote an adapter to let pygments worj with it: <http://lateral.netmanagers.com.ar/weblog/2009/09/21.html#BB831> I am sure something similar can be done with other toolkits, but I don't know how.
620,954
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .
2009/03/07
[ "https://Stackoverflow.com/questions/620954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
If you're using gtk+, there's a binding of gtksourceview for Python in [gnome-python-extras](http://ftp.gnome.org/pub/GNOME/sources/gnome-python-extras/2.25/). It seems to work well in my experience. The downside: the documentation is less than perfect. There's also a binding of [QScintilla](http://www.riverbankcomputing.co.uk/software/qscintilla/intro) for Python if PyQt is your thing.
You can use [StyledTextCtrl](http://www.wxpython.org/docs/api/wx.stc.StyledTextCtrl-class.html) in [wxPython](http://www.wxpython.org). Check out the official demo for an example (The *demo code* tab for any demo).
620,954
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .
2009/03/07
[ "https://Stackoverflow.com/questions/620954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
If you're using gtk+, there's a binding of gtksourceview for Python in [gnome-python-extras](http://ftp.gnome.org/pub/GNOME/sources/gnome-python-extras/2.25/). It seems to work well in my experience. The downside: the documentation is less than perfect. There's also a binding of [QScintilla](http://www.riverbankcomputing.co.uk/software/qscintilla/intro) for Python if PyQt is your thing.
You say "in a GUI app" but don't mention the toolkit. If you are using PyQt, and need a read-only widget, you can use QWebKit which has a whole HTML widget in it based on WebKit, so it supports pretty much anything, from flash to the ACID2 test. If you want a read-write widget, Qt's QTextEdit supports syntax highlighting, and I wrote an adapter to let pygments worj with it: <http://lateral.netmanagers.com.ar/weblog/2009/09/21.html#BB831> I am sure something similar can be done with other toolkits, but I don't know how.
620,954
Are there any easy to use python components that could be used in a GUI? It would be great to have something like JSyntaxPane for Python. I would like to know of python-only versions ( not interested in jython ) .
2009/03/07
[ "https://Stackoverflow.com/questions/620954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
You can use [StyledTextCtrl](http://www.wxpython.org/docs/api/wx.stc.StyledTextCtrl-class.html) in [wxPython](http://www.wxpython.org). Check out the official demo for an example (The *demo code* tab for any demo).
You say "in a GUI app" but don't mention the toolkit. If you are using PyQt, and need a read-only widget, you can use QWebKit which has a whole HTML widget in it based on WebKit, so it supports pretty much anything, from flash to the ACID2 test. If you want a read-write widget, Qt's QTextEdit supports syntax highlighting, and I wrote an adapter to let pygments worj with it: <http://lateral.netmanagers.com.ar/weblog/2009/09/21.html#BB831> I am sure something similar can be done with other toolkits, but I don't know how.
60,396,222
I know there are questions like that but I still wanted to ask this because I couldn't solve, so there is my code: ``` #! python3 import os my_path = 'E:\\Movies' for folder in os.listdir(my_path): size = os.path.getsize(folder) print(f'size of the {folder} is: {size} ') ``` And I got this error: ``` Traceback (most recent call last): File "c:/Users/ataba/OneDrive/Masaüstü/Programming/python/findingfiles.py", line 7, in <module> size = os.path.getsize(folder) File "C:\Program Files\Python37\lib\genericpath.py", line 50, in getsize return os.stat(filename).st_size FileNotFoundError: [WinError 2] The system cannot find the file specified: 'FordvFerrari1080p' ``` When I write `print(folder)` instead of getting their size it shows the folders so I don't think the program can't find them.
2020/02/25
[ "https://Stackoverflow.com/questions/60396222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10577122/" ]
Temporary tables are created using the server's collation by default. It looks like your server's collation is `SQL_Latin1_General_CP1_CI_AS` and the database's (actually, the column's) `Hebrew_CI_AS` or vice versa. You can overcome this by using `collate database_default` in the temporary table's column definitions, eg : ``` create #x ( ID int PRIMARY KEY, Company_Code nvarchar(20) COLLATE database_default, Cust nvarchar(20) COLLATE database_default, ... ) ``` This will create the columns using the current database's collation, not the server's.
In your temp table definition #x,add COLLATE DATABASE\_DEFAULT to the String columns, like ``` custName nvarchar(xx) COLLATE DATABASE_DEFAULT NOT NULL ```
29,723,590
I'm trying to set up Python to run on my local apache server on a mac. On `httpd.conf`, I've ``` <VirtualHost *:80> DocumentRoot "/Users/ptamzz/Sites/python/sandbox.ptamzz.com" <Directory "/Users/pritams/Sites/python/sandbox.ptamzz.com"> Options Indexes FollowSymLinks MultiViews ExecCGI AddHandler cgi-script .py Require all granted </Directory> DirectoryIndex index.py ServerName sandbox.ptamzz.com ErrorLog "/var/log/apache2/error-log" CustomLog "/var/log/apache2/access-log" common </VirtualHost> ``` On my document root, I've my `index.py` file as ``` #!/usr/bin/python print "Content-type: text/html" print "<html><body>Pritam's Page</body></html>" ``` But when I load the page on my browser, the python codes are returned as it is. ![Screenshot](https://i.stack.imgur.com/QxQ6s.png) What all am I missing?
2015/04/18
[ "https://Stackoverflow.com/questions/29723590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383393/" ]
**Executing python in Apache ( cgi )** System : OSX yosmite 10.10.3 , Default apache **uncommented in http config** ``` LoadModule cgi_module libexec/apache2/mod_cgi.so ``` **virtual hosts entry** ``` <VirtualHost *:80> # Hook virtual host domain name into physical location. ServerName python.localhost DocumentRoot "/Users/sj/Sites/python" # Log errors to a custom log file. ErrorLog "/private/var/log/apache2/pythonlocal.log" # Add python file extensions as CGI script handlers. AddHandler cgi-script .py # Be sure to add ** ExecCGI ** as an option in the document # directory so Apache has permissions to run CGI scripts. <Directory "/Users/sj/Sites/python"> Options Indexes MultiViews FollowSymLinks ExecCGI AddHandler cgi-script .cgi AllowOverride All Order allow,deny Allow from all </Directory> </VirtualHost> ``` **index.py file** ``` #!/usr/bin/env python print "Content-type: text/html" print print "<html><body>Test Page</body></html>" ``` file was made executable using ``` chmod a+x index.py ``` **restarted apache and output** ![python in apache](https://i.stack.imgur.com/JUXFt.png)
For later Versions of Apache (2.4) the answer of Sojan V Jose is mostly still applying, except that I got an authorization failure, that can be resolved by replacing: ``` Order allow,deny Allow from all ``` with: ``` Require all granted ```
70,125,767
I am a student, new to python. I am trying to code a program that will tell if a user input number is fibonacci or not. ``` num=int(input("Enter the number you want to check\n")) temp=1 k=0 a=0 summ=0 while summ<=num: summ=temp+k temp=summ k=temp if summ==num: a=a+1 print("Yes. {} is a fibonnaci number".format(num)) break if a==0: print("No. {} is NOT a fibonacci number".format(num)) #The program is working for only numbers upto 2. ```
2021/11/26
[ "https://Stackoverflow.com/questions/70125767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17517066/" ]
You don't need quite so many variables. A Fibonacci integer sequence can be generated with the single assignment ``` a, b = b, a + b # Short for # temp = a # a = b # b = temp + b ``` Repeated applications sets `a` to the numbers in the pattern in sequence. The choice of initial values for `a` and `b` determine which exact sequence you get. The Fibonacci numbers are generated when `a = 0` and `b = 1` are used. ``` a = 0 b = 1 a, b = 1, 0 + 1 # 0, 1 a, b = 1, 1 + 1 # 1, 2 a, b = 2, 1 + 2 # 2, 3 a, b = 3, 2 + 3 # 3, 5 # etc ``` (As another example, the Lucas numbers are generated if you start with `a = 2` and `b = 1`.) All you need to do is return `True` if `n == a` at each step, iterating until `n > a`. If `n` wasn't one of the `a` values generated by the loop, you'll return `False`. ``` n = int(input(...)) a = 0 b = 1 while a <= n: if n == a: return True a, b = b, a + b return False ```
I'd suggest something like this: ``` fib_terms = [0, 1] # first two fibonacci terms user_input= int(input('Enter the number you want to check\n')) # Add new fibonacci terms until the user_input is reached while fib_terms[-1] <= user_input: fib_terms.append(fib_terms[-1] + fib_terms[-2]) if user_input in fib_terms: print(f'Yes. {user_input} is a fibonacci number.') else: print(f'No. {user_input} is NOT a fibonacci number.') ```
70,125,767
I am a student, new to python. I am trying to code a program that will tell if a user input number is fibonacci or not. ``` num=int(input("Enter the number you want to check\n")) temp=1 k=0 a=0 summ=0 while summ<=num: summ=temp+k temp=summ k=temp if summ==num: a=a+1 print("Yes. {} is a fibonnaci number".format(num)) break if a==0: print("No. {} is NOT a fibonacci number".format(num)) #The program is working for only numbers upto 2. ```
2021/11/26
[ "https://Stackoverflow.com/questions/70125767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17517066/" ]
You don't need quite so many variables. A Fibonacci integer sequence can be generated with the single assignment ``` a, b = b, a + b # Short for # temp = a # a = b # b = temp + b ``` Repeated applications sets `a` to the numbers in the pattern in sequence. The choice of initial values for `a` and `b` determine which exact sequence you get. The Fibonacci numbers are generated when `a = 0` and `b = 1` are used. ``` a = 0 b = 1 a, b = 1, 0 + 1 # 0, 1 a, b = 1, 1 + 1 # 1, 2 a, b = 2, 1 + 2 # 2, 3 a, b = 3, 2 + 3 # 3, 5 # etc ``` (As another example, the Lucas numbers are generated if you start with `a = 2` and `b = 1`.) All you need to do is return `True` if `n == a` at each step, iterating until `n > a`. If `n` wasn't one of the `a` values generated by the loop, you'll return `False`. ``` n = int(input(...)) a = 0 b = 1 while a <= n: if n == a: return True a, b = b, a + b return False ```
welcome to the python community. In Your code `temp` means the previous number and `k` means the previous number of `temp`. The problem is that you change the `temp` before you assign the next value to `k`. To solve that you just have to sawp the lines 8 and 9. In the new order you first assign the value of `temp` to `k` then `summ` to `temp`. That's it! I suggest you to do it by a list in this way: `fib[i] = fib[i-1] + fib[i-2]` It will improve the clarity of your code.
70,125,767
I am a student, new to python. I am trying to code a program that will tell if a user input number is fibonacci or not. ``` num=int(input("Enter the number you want to check\n")) temp=1 k=0 a=0 summ=0 while summ<=num: summ=temp+k temp=summ k=temp if summ==num: a=a+1 print("Yes. {} is a fibonnaci number".format(num)) break if a==0: print("No. {} is NOT a fibonacci number".format(num)) #The program is working for only numbers upto 2. ```
2021/11/26
[ "https://Stackoverflow.com/questions/70125767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17517066/" ]
You don't need quite so many variables. A Fibonacci integer sequence can be generated with the single assignment ``` a, b = b, a + b # Short for # temp = a # a = b # b = temp + b ``` Repeated applications sets `a` to the numbers in the pattern in sequence. The choice of initial values for `a` and `b` determine which exact sequence you get. The Fibonacci numbers are generated when `a = 0` and `b = 1` are used. ``` a = 0 b = 1 a, b = 1, 0 + 1 # 0, 1 a, b = 1, 1 + 1 # 1, 2 a, b = 2, 1 + 2 # 2, 3 a, b = 3, 2 + 3 # 3, 5 # etc ``` (As another example, the Lucas numbers are generated if you start with `a = 2` and `b = 1`.) All you need to do is return `True` if `n == a` at each step, iterating until `n > a`. If `n` wasn't one of the `a` values generated by the loop, you'll return `False`. ``` n = int(input(...)) a = 0 b = 1 while a <= n: if n == a: return True a, b = b, a + b return False ```
Check this: ``` def fibonacci_list(limit): u_n_1 = 1 u_n_2 = 1 u_n = 1 out_list = [u_n] while u_n <= limit: out_list.append(u_n) u_n = u_n_1 + u_n_2 u_n_2 = u_n_1 u_n_1 = u_n return out_list def is_fibonacci_number(n): if n in fibonacci_list(n): return True return False def main(): n = int(input('Enter a number:')) if is_fibonacci_number(n): print(str(n) + ' is a fibonacci number ') else: print(str(n) + ' is not a fibonacci number ') if __name__ == '__main__': main() ```
70,125,767
I am a student, new to python. I am trying to code a program that will tell if a user input number is fibonacci or not. ``` num=int(input("Enter the number you want to check\n")) temp=1 k=0 a=0 summ=0 while summ<=num: summ=temp+k temp=summ k=temp if summ==num: a=a+1 print("Yes. {} is a fibonnaci number".format(num)) break if a==0: print("No. {} is NOT a fibonacci number".format(num)) #The program is working for only numbers upto 2. ```
2021/11/26
[ "https://Stackoverflow.com/questions/70125767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17517066/" ]
You don't need quite so many variables. A Fibonacci integer sequence can be generated with the single assignment ``` a, b = b, a + b # Short for # temp = a # a = b # b = temp + b ``` Repeated applications sets `a` to the numbers in the pattern in sequence. The choice of initial values for `a` and `b` determine which exact sequence you get. The Fibonacci numbers are generated when `a = 0` and `b = 1` are used. ``` a = 0 b = 1 a, b = 1, 0 + 1 # 0, 1 a, b = 1, 1 + 1 # 1, 2 a, b = 2, 1 + 2 # 2, 3 a, b = 3, 2 + 3 # 3, 5 # etc ``` (As another example, the Lucas numbers are generated if you start with `a = 2` and `b = 1`.) All you need to do is return `True` if `n == a` at each step, iterating until `n > a`. If `n` wasn't one of the `a` values generated by the loop, you'll return `False`. ``` n = int(input(...)) a = 0 b = 1 while a <= n: if n == a: return True a, b = b, a + b return False ```
``` bool checkfibonacci(int n) { int a = 0; int b = 1; if (n == a || n == b) return true; int c = a + b; while(c <= n) { if(c == n) return true; a = b; b = c; c = a + b; } return false; } ``` Something like this will do it.
46,035,788
I'm trying to use python to search through a directory of files and open every single file in search of a string. We're talking about less than 1000 files with 1, 2, 3 line each, so opening them all only takes a few seconds. Well, I think that I've made it, but there's a problem: the string that I'm search for is "**exit 0**". ``` #!/usr/bin/env python import glob scriptsdir = "/dummydir/*.ksh" string = "exit 0" files = glob.glob(scriptsdir) teste = 0 for script in files: f=open(script,"r") for line in f: if string in line: teste = teste + 1 f.close() print teste ``` This sucks because the code is working: like this, the "teste" value at the end refers to number of .ksh files on the directory, but if change the string to **exit 1**, the value of the "teste" in the end is 0. I'm literally searching for an "**exit 0**" string that exists in some of those files. Is it possible to do it? I've tested it and if I change the string value to something that exists, the count is done right. Any help? Thank you,
2017/09/04
[ "https://Stackoverflow.com/questions/46035788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6834568/" ]
Because the start of your pattern match the empty string: ``` /|google... ``` That means: nothing OR google ...
This pattern is invalid: ``` |google|robot|bot|spider|crawler|curl|Facebot|facebook|archiver|^$ ^ | +--- this character (an alternator) effectively renders the regex useless ``` This means that the regex could in theory match anything because the left part is empty. Moreover, `^$` on the right of the last alternator also means an empty string match. [Debuggex Demo](https://www.debuggex.com/r/4q2m9j1y71bNaA8x)
40,981,908
I'm new to AWS Lambda and pretty new to Python. I wanted to write a python lambda that uses the AWS API. boto is the most popular python module to do this so I wanted to include it. Looking at examples online I put `import boto3` at the top of my Lambda and it just worked- I was able to use boto in my Lambda. How does AWS know about boto? It's a community module. Are there a list of supported modules for Lambdas? Does AWS cache its own copy of community modules?
2016/12/05
[ "https://Stackoverflow.com/questions/40981908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1028270/" ]
[The documentation](http://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html) seems to suggest `boto3` is provided by default on AWS Lambda: > > AWS Lambda includes the AWS SDK for Python (Boto 3), so you don't need to include it in your deployment package. However, if you want to use a version of Boto3 other than the one included by default, you can include it in your deployment package. > > > As far as I know, you will need to manually install any other dependencies in your deployment package, as shown in the linked documentation, using: ``` pip install foobar -t <project path> ```
AWS Lambda includes the AWS SDK for Python (Boto 3), so you don't need to include it in your deployment package. This link will give you a little more in-depth info on Lambda environment <https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/> And this too <https://alestic.com/2014/12/aws-lambda-persistence/>
40,981,908
I'm new to AWS Lambda and pretty new to Python. I wanted to write a python lambda that uses the AWS API. boto is the most popular python module to do this so I wanted to include it. Looking at examples online I put `import boto3` at the top of my Lambda and it just worked- I was able to use boto in my Lambda. How does AWS know about boto? It's a community module. Are there a list of supported modules for Lambdas? Does AWS cache its own copy of community modules?
2016/12/05
[ "https://Stackoverflow.com/questions/40981908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1028270/" ]
AWS Lambda's Python environment comes pre-installed with `boto3`. Any other libraries you want need to be part of the zip you upload. You can install them locally with `pip install whatever -t mysrcfolder`.
AWS Lambda includes the AWS SDK for Python (Boto 3), so you don't need to include it in your deployment package. This link will give you a little more in-depth info on Lambda environment <https://aws.amazon.com/blogs/compute/container-reuse-in-lambda/> And this too <https://alestic.com/2014/12/aws-lambda-persistence/>
26,278,386
I have a list or array (what is the correct term in python?) of objects. What is the most efficient way to get all objects matching a condition? I could iterate over the list and check each element, but that doesn't seem very efficient. ``` objects = [] for object in list: if object.value == "123": objects.add(object) ```
2014/10/09
[ "https://Stackoverflow.com/questions/26278386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1474934/" ]
This is the simplest way: ``` objects = [x for x in someList if x.value == 123] ``` If you're looking for a *faster* solution, you have to tell us more about your objects and how the source list is built. For example, if the property in question is unique among the objects, you can have better performance using `dict` instead of `list`. Another option is to keep the list sorted and use `bisect` instead of the linear search. Do note however, that these optimization efforts start making sense when the list grows really big, if you have less than ~500 elements, just use a comprehension and stop worrying.
You can use `filter` ``` objects = filter(lambda i: i.value == '123', l) ``` *Note to self* Apparently the ["filter vs list comp"](https://stackoverflow.com/questions/3013449/list-filtering-list-comprehension-vs-lambda-filter) debate starts flame wars.
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
Invisible reCAPTCHA =================== Implementing Google's new Invisible reCAPTCHA is very similar to how we add v2 to our site. You may add it as its own container like normal, or the new method of adding it to the form submit button. I hope this guide will help you along the correct path. Standalone CAPTCHA Container ---------------------------- Implementing recaptcha requires a few things: ``` - Sitekey - Class - Callback - Bind ``` This will be your final goal. ``` <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"> </div> ``` When using the standalone method, you must have data-bind set to the ID of your submit button. If you do not have this set, your captcha will not be invisible. A callback must also be used to submit the form. An invisible captcha will cancel all events from the submit button, so you need the callback to actually pass the submission on. ``` <script> function submitForm() { var form = document.getElementById("ContactForm"); if (validate_form(form)) { form.submit(); } else { grecaptcha.reset(); } } </script> ``` Notice in the example callback that there is also custom form validation. It is very important that you reset the reCAPTCHA when the validation fails, otherwise you will not be able to re-submit the form until the CAPTCHA expires. Invisible CAPTCHA Button ------------------------ A lot of this is the same as with the standalone CAPTCHA above, but instead of having a container, everything is placed on the submit button. This will be your goal. ``` <button class="g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit"> Submit</button> ``` There's something new here, data-badge. This is a div that gets inserted into the DOM that contains the inputs required for reCAPTCHA to function. It has three possible values: bottomleft, bottomright, inline. Inline will make it display directly above the submit button, and allow you to control how you would like it to be styled. On to your question ------------------- ``` <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"></div> <input type="submit" name="login" class="loginmodal-submit" id="recaptcha-submit" value="Login"> </form> ``` Or ``` <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button class="loginmodal-submit g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit" value="Login">Submit</button> </form> ``` I hope this helps you and future coders. I'll keep this up-to-date as the technology evolves.
If you're looking for a fully customizable general solution which will even work with multiple forms on the same page, I'll explicitly render the reCaptcha widget by using the **render=explicit** and **onload=aFunctionCallback** parameters. Here is a simple example: ```html <!DOCTYPE html> <html> <body> <form action="" method="post"> <input type="text" name="first-name-1"> <br /> <input type="text" name="last-name-1"> <br /> <div class="recaptcha-holder"></div> <input type="submit" value="Submit"> </form> <br /><br /> <form action="" method="post"> <input type="text" name="first-name-2"> <br /> <input type="text" name="last-name-2"> <br /> <div class="recaptcha-holder"></div> <input type="submit" value="Submit"> </form> <script type="text/javascript"> var renderGoogleInvisibleRecaptcha = function() { for (var i = 0; i < document.forms.length; ++i) { var form = document.forms[i]; var holder = form.querySelector('.recaptcha-holder'); if (null === holder){ continue; } (function(frm){ var holderId = grecaptcha.render(holder,{ 'sitekey': 'CHANGE_ME_WITH_YOUR_SITE_KEY', 'size': 'invisible', 'badge' : 'bottomright', // possible values: bottomright, bottomleft, inline 'callback' : function (recaptchaToken) { HTMLFormElement.prototype.submit.call(frm); } }); frm.onsubmit = function (evt){ evt.preventDefault(); grecaptcha.execute(holderId); }; })(form); } }; </script> <script src="https://www.google.com/recaptcha/api.js?onload=renderGoogleInvisibleRecaptcha&render=explicit" async defer></script> </body> </html> ``` As you can see, I am adding an empty div element into a form. In order to identify which forms should be protected using reCaptcha, I'll add a class name to this element. In our example I am using 'recaptcha-holder' class name. The callback function iterates through all the existing forms and if it finds our injected element with the 'recaptcha-holder' class name, it will render the reCaptcha widget. I've been using this solution on my Invisible reCaptcha for WordPress plugin. If somebody wants to see how this works, the plugin is available for download on WordPress directory: <https://wordpress.org/plugins/invisible-recaptcha/> Hope this helps!
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
Invisible reCAPTCHA =================== Implementing Google's new Invisible reCAPTCHA is very similar to how we add v2 to our site. You may add it as its own container like normal, or the new method of adding it to the form submit button. I hope this guide will help you along the correct path. Standalone CAPTCHA Container ---------------------------- Implementing recaptcha requires a few things: ``` - Sitekey - Class - Callback - Bind ``` This will be your final goal. ``` <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"> </div> ``` When using the standalone method, you must have data-bind set to the ID of your submit button. If you do not have this set, your captcha will not be invisible. A callback must also be used to submit the form. An invisible captcha will cancel all events from the submit button, so you need the callback to actually pass the submission on. ``` <script> function submitForm() { var form = document.getElementById("ContactForm"); if (validate_form(form)) { form.submit(); } else { grecaptcha.reset(); } } </script> ``` Notice in the example callback that there is also custom form validation. It is very important that you reset the reCAPTCHA when the validation fails, otherwise you will not be able to re-submit the form until the CAPTCHA expires. Invisible CAPTCHA Button ------------------------ A lot of this is the same as with the standalone CAPTCHA above, but instead of having a container, everything is placed on the submit button. This will be your goal. ``` <button class="g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit"> Submit</button> ``` There's something new here, data-badge. This is a div that gets inserted into the DOM that contains the inputs required for reCAPTCHA to function. It has three possible values: bottomleft, bottomright, inline. Inline will make it display directly above the submit button, and allow you to control how you would like it to be styled. On to your question ------------------- ``` <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"></div> <input type="submit" name="login" class="loginmodal-submit" id="recaptcha-submit" value="Login"> </form> ``` Or ``` <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button class="loginmodal-submit g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit" value="Login">Submit</button> </form> ``` I hope this helps you and future coders. I'll keep this up-to-date as the technology evolves.
1. Login with your google account 2. Visit the google recaptcha link. 3. Then follow the link to code integration, follow the code for both client and serverside validation. <https://developers.google.com/recaptcha/docs/invisible> 4. Increase or decrease the security level once after creating the recaptcha, go to the advance settings here, <https://www.google.com/recaptcha/admin#list>
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
Invisible reCAPTCHA =================== Implementing Google's new Invisible reCAPTCHA is very similar to how we add v2 to our site. You may add it as its own container like normal, or the new method of adding it to the form submit button. I hope this guide will help you along the correct path. Standalone CAPTCHA Container ---------------------------- Implementing recaptcha requires a few things: ``` - Sitekey - Class - Callback - Bind ``` This will be your final goal. ``` <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"> </div> ``` When using the standalone method, you must have data-bind set to the ID of your submit button. If you do not have this set, your captcha will not be invisible. A callback must also be used to submit the form. An invisible captcha will cancel all events from the submit button, so you need the callback to actually pass the submission on. ``` <script> function submitForm() { var form = document.getElementById("ContactForm"); if (validate_form(form)) { form.submit(); } else { grecaptcha.reset(); } } </script> ``` Notice in the example callback that there is also custom form validation. It is very important that you reset the reCAPTCHA when the validation fails, otherwise you will not be able to re-submit the form until the CAPTCHA expires. Invisible CAPTCHA Button ------------------------ A lot of this is the same as with the standalone CAPTCHA above, but instead of having a container, everything is placed on the submit button. This will be your goal. ``` <button class="g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit"> Submit</button> ``` There's something new here, data-badge. This is a div that gets inserted into the DOM that contains the inputs required for reCAPTCHA to function. It has three possible values: bottomleft, bottomright, inline. Inline will make it display directly above the submit button, and allow you to control how you would like it to be styled. On to your question ------------------- ``` <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"></div> <input type="submit" name="login" class="loginmodal-submit" id="recaptcha-submit" value="Login"> </form> ``` Or ``` <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button class="loginmodal-submit g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit" value="Login">Submit</button> </form> ``` I hope this helps you and future coders. I'll keep this up-to-date as the technology evolves.
Here is how to implement a client + server side **(php)** Invisible reCaptcha functionality: * Client Side ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>reCaptcha</title> <!--api link--> <script src="https://www.google.com/recaptcha/api.js" async defer></script> <!--call back function--> <script> function onSubmit(token) { document.getElementById('reCaptchaForm').submit(); } </script> </head> <body> <div class="container"> <form id="reCaptchaForm" action="signup.php" method="POST"> <input type="text" placeholder="type anything"> <!--Invisible reCaptcha configuration--> <button class="g-recaptcha" data-sitekey="<your site key>" data-callback='onSubmit'>Submit</button> <br/> </form> </div> </body> </html> ``` * Server Side validation: Create a **signup.php** file ```html <?php //only run when form is submitted if(isset($_POST['g-recaptcha-response'])) { $secretKey = '<your secret key>'; $response = $_POST['g-recaptcha-response']; $remoteIp = $_SERVER['REMOTE_ADDR']; $reCaptchaValidationUrl = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$remoteIp"); $result = json_decode($reCaptchaValidationUrl, TRUE); //get response along side with all results print_r($result); if($result['success'] == 1) { //True - What happens when user is verified $userMessage = '<div>Success: you\'ve made it :)</div>'; } else { //False - What happens when user is not verified $userMessage = '<div>Fail: please try again :(</div>'; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>reCAPTCHA Response</title> </head> <body> <?php if(!empty($userMessage)) { echo $userMessage; } ?> </body> </html> ```
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
Invisible reCAPTCHA =================== Implementing Google's new Invisible reCAPTCHA is very similar to how we add v2 to our site. You may add it as its own container like normal, or the new method of adding it to the form submit button. I hope this guide will help you along the correct path. Standalone CAPTCHA Container ---------------------------- Implementing recaptcha requires a few things: ``` - Sitekey - Class - Callback - Bind ``` This will be your final goal. ``` <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"> </div> ``` When using the standalone method, you must have data-bind set to the ID of your submit button. If you do not have this set, your captcha will not be invisible. A callback must also be used to submit the form. An invisible captcha will cancel all events from the submit button, so you need the callback to actually pass the submission on. ``` <script> function submitForm() { var form = document.getElementById("ContactForm"); if (validate_form(form)) { form.submit(); } else { grecaptcha.reset(); } } </script> ``` Notice in the example callback that there is also custom form validation. It is very important that you reset the reCAPTCHA when the validation fails, otherwise you will not be able to re-submit the form until the CAPTCHA expires. Invisible CAPTCHA Button ------------------------ A lot of this is the same as with the standalone CAPTCHA above, but instead of having a container, everything is placed on the submit button. This will be your goal. ``` <button class="g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit"> Submit</button> ``` There's something new here, data-badge. This is a div that gets inserted into the DOM that contains the inputs required for reCAPTCHA to function. It has three possible values: bottomleft, bottomright, inline. Inline will make it display directly above the submit button, and allow you to control how you would like it to be styled. On to your question ------------------- ``` <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <div class="g-recaptcha" data-sitekey="<sitekey>" data-bind="recaptcha-submit" data-callback="submitForm"></div> <input type="submit" name="login" class="loginmodal-submit" id="recaptcha-submit" value="Login"> </form> ``` Or ``` <form action="test.php" method="POST" id="theForm"> <script> function submitForm() { document.getElementById("theForm").submit(); } </script> <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button class="loginmodal-submit g-recaptcha" data-sitekey="<sitekey>" data-callback="submitForm" data-badge="inline" type="submit" value="Login">Submit</button> </form> ``` I hope this helps you and future coders. I'll keep this up-to-date as the technology evolves.
Here is a **working** example: ``` <html lang="en"> <head> <meta charset="UTF-8"> <title>ReCAPTCHA Example</title> </head> <body> <div class="container"> <form method="post" action="/contact/" id="contact-form"> <h3 class="title-divider"> <span>Contact Us</span> </h3> <input type="text" name="name"> <div class="captcha"><!-- BEGIN: ReCAPTCHA implementation example. --> <div id="recaptcha-demo" class="g-recaptcha" data-sitekey="YOUR_RECAPTCHA_SITE_KEY" data-callback="onSuccess" data-bind="form-submit"></div> <script> var onSuccess = function (response) { var errorDivs = document.getElementsByClassName("recaptcha-error"); if (errorDivs.length) { errorDivs[0].className = ""; } var errorMsgs = document.getElementsByClassName("recaptcha-error-message"); if (errorMsgs.length) { errorMsgs[0].parentNode.removeChild(errorMsgs[0]); } document.getElementById("contact-form").submit(); };</script><!-- END: ReCAPTCHA implementation example. --> </div> <button id="form-submit" type="submit">Submit</button> </form> <script src="https://www.google.com/recaptcha/api.js" async defer></script> </div> </body> </html> ``` Do not forget to change **YOUR\_RECAPTCHA\_SITE\_KEY** to your Google ReCAPTCHA site key. Next step is to actually validate the data. It is done by making a POST request to the endpoint <https://www.google.com/recaptcha/api/siteverify>, containing your Secret key and the data from the reCAPTCHA, which is identified by **g-recaptcha-response**. There are a lot of different ways it could be done depending on your CMS/Framework. You might have noticed the reCaptcha badge in the lower right corner of the screen. This exists to let users know that a form is protected by reCaptcha now that the verification checkbox has been removed. It’s possible to hide this badge however by configuring it to be inline, and then modifying it with CSS. ``` <style> .grecaptcha-badge {display: none;} </style> ``` *Please note that because Google collects user information to enable reCaptcha functionality, their terms of service require you to alert users to its use.* If you hide the badge you can add an informational paragraph somewhere on the page instead.
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
If you're looking for a fully customizable general solution which will even work with multiple forms on the same page, I'll explicitly render the reCaptcha widget by using the **render=explicit** and **onload=aFunctionCallback** parameters. Here is a simple example: ```html <!DOCTYPE html> <html> <body> <form action="" method="post"> <input type="text" name="first-name-1"> <br /> <input type="text" name="last-name-1"> <br /> <div class="recaptcha-holder"></div> <input type="submit" value="Submit"> </form> <br /><br /> <form action="" method="post"> <input type="text" name="first-name-2"> <br /> <input type="text" name="last-name-2"> <br /> <div class="recaptcha-holder"></div> <input type="submit" value="Submit"> </form> <script type="text/javascript"> var renderGoogleInvisibleRecaptcha = function() { for (var i = 0; i < document.forms.length; ++i) { var form = document.forms[i]; var holder = form.querySelector('.recaptcha-holder'); if (null === holder){ continue; } (function(frm){ var holderId = grecaptcha.render(holder,{ 'sitekey': 'CHANGE_ME_WITH_YOUR_SITE_KEY', 'size': 'invisible', 'badge' : 'bottomright', // possible values: bottomright, bottomleft, inline 'callback' : function (recaptchaToken) { HTMLFormElement.prototype.submit.call(frm); } }); frm.onsubmit = function (evt){ evt.preventDefault(); grecaptcha.execute(holderId); }; })(form); } }; </script> <script src="https://www.google.com/recaptcha/api.js?onload=renderGoogleInvisibleRecaptcha&render=explicit" async defer></script> </body> </html> ``` As you can see, I am adding an empty div element into a form. In order to identify which forms should be protected using reCaptcha, I'll add a class name to this element. In our example I am using 'recaptcha-holder' class name. The callback function iterates through all the existing forms and if it finds our injected element with the 'recaptcha-holder' class name, it will render the reCaptcha widget. I've been using this solution on my Invisible reCaptcha for WordPress plugin. If somebody wants to see how this works, the plugin is available for download on WordPress directory: <https://wordpress.org/plugins/invisible-recaptcha/> Hope this helps!
1. Login with your google account 2. Visit the google recaptcha link. 3. Then follow the link to code integration, follow the code for both client and serverside validation. <https://developers.google.com/recaptcha/docs/invisible> 4. Increase or decrease the security level once after creating the recaptcha, go to the advance settings here, <https://www.google.com/recaptcha/admin#list>
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
If you're looking for a fully customizable general solution which will even work with multiple forms on the same page, I'll explicitly render the reCaptcha widget by using the **render=explicit** and **onload=aFunctionCallback** parameters. Here is a simple example: ```html <!DOCTYPE html> <html> <body> <form action="" method="post"> <input type="text" name="first-name-1"> <br /> <input type="text" name="last-name-1"> <br /> <div class="recaptcha-holder"></div> <input type="submit" value="Submit"> </form> <br /><br /> <form action="" method="post"> <input type="text" name="first-name-2"> <br /> <input type="text" name="last-name-2"> <br /> <div class="recaptcha-holder"></div> <input type="submit" value="Submit"> </form> <script type="text/javascript"> var renderGoogleInvisibleRecaptcha = function() { for (var i = 0; i < document.forms.length; ++i) { var form = document.forms[i]; var holder = form.querySelector('.recaptcha-holder'); if (null === holder){ continue; } (function(frm){ var holderId = grecaptcha.render(holder,{ 'sitekey': 'CHANGE_ME_WITH_YOUR_SITE_KEY', 'size': 'invisible', 'badge' : 'bottomright', // possible values: bottomright, bottomleft, inline 'callback' : function (recaptchaToken) { HTMLFormElement.prototype.submit.call(frm); } }); frm.onsubmit = function (evt){ evt.preventDefault(); grecaptcha.execute(holderId); }; })(form); } }; </script> <script src="https://www.google.com/recaptcha/api.js?onload=renderGoogleInvisibleRecaptcha&render=explicit" async defer></script> </body> </html> ``` As you can see, I am adding an empty div element into a form. In order to identify which forms should be protected using reCaptcha, I'll add a class name to this element. In our example I am using 'recaptcha-holder' class name. The callback function iterates through all the existing forms and if it finds our injected element with the 'recaptcha-holder' class name, it will render the reCaptcha widget. I've been using this solution on my Invisible reCaptcha for WordPress plugin. If somebody wants to see how this works, the plugin is available for download on WordPress directory: <https://wordpress.org/plugins/invisible-recaptcha/> Hope this helps!
Here is a **working** example: ``` <html lang="en"> <head> <meta charset="UTF-8"> <title>ReCAPTCHA Example</title> </head> <body> <div class="container"> <form method="post" action="/contact/" id="contact-form"> <h3 class="title-divider"> <span>Contact Us</span> </h3> <input type="text" name="name"> <div class="captcha"><!-- BEGIN: ReCAPTCHA implementation example. --> <div id="recaptcha-demo" class="g-recaptcha" data-sitekey="YOUR_RECAPTCHA_SITE_KEY" data-callback="onSuccess" data-bind="form-submit"></div> <script> var onSuccess = function (response) { var errorDivs = document.getElementsByClassName("recaptcha-error"); if (errorDivs.length) { errorDivs[0].className = ""; } var errorMsgs = document.getElementsByClassName("recaptcha-error-message"); if (errorMsgs.length) { errorMsgs[0].parentNode.removeChild(errorMsgs[0]); } document.getElementById("contact-form").submit(); };</script><!-- END: ReCAPTCHA implementation example. --> </div> <button id="form-submit" type="submit">Submit</button> </form> <script src="https://www.google.com/recaptcha/api.js" async defer></script> </div> </body> </html> ``` Do not forget to change **YOUR\_RECAPTCHA\_SITE\_KEY** to your Google ReCAPTCHA site key. Next step is to actually validate the data. It is done by making a POST request to the endpoint <https://www.google.com/recaptcha/api/siteverify>, containing your Secret key and the data from the reCAPTCHA, which is identified by **g-recaptcha-response**. There are a lot of different ways it could be done depending on your CMS/Framework. You might have noticed the reCaptcha badge in the lower right corner of the screen. This exists to let users know that a form is protected by reCaptcha now that the verification checkbox has been removed. It’s possible to hide this badge however by configuring it to be inline, and then modifying it with CSS. ``` <style> .grecaptcha-badge {display: none;} </style> ``` *Please note that because Google collects user information to enable reCaptcha functionality, their terms of service require you to alert users to its use.* If you hide the badge you can add an informational paragraph somewhere on the page instead.
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
Here is how to implement a client + server side **(php)** Invisible reCaptcha functionality: * Client Side ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>reCaptcha</title> <!--api link--> <script src="https://www.google.com/recaptcha/api.js" async defer></script> <!--call back function--> <script> function onSubmit(token) { document.getElementById('reCaptchaForm').submit(); } </script> </head> <body> <div class="container"> <form id="reCaptchaForm" action="signup.php" method="POST"> <input type="text" placeholder="type anything"> <!--Invisible reCaptcha configuration--> <button class="g-recaptcha" data-sitekey="<your site key>" data-callback='onSubmit'>Submit</button> <br/> </form> </div> </body> </html> ``` * Server Side validation: Create a **signup.php** file ```html <?php //only run when form is submitted if(isset($_POST['g-recaptcha-response'])) { $secretKey = '<your secret key>'; $response = $_POST['g-recaptcha-response']; $remoteIp = $_SERVER['REMOTE_ADDR']; $reCaptchaValidationUrl = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$remoteIp"); $result = json_decode($reCaptchaValidationUrl, TRUE); //get response along side with all results print_r($result); if($result['success'] == 1) { //True - What happens when user is verified $userMessage = '<div>Success: you\'ve made it :)</div>'; } else { //False - What happens when user is not verified $userMessage = '<div>Fail: please try again :(</div>'; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>reCAPTCHA Response</title> </head> <body> <?php if(!empty($userMessage)) { echo $userMessage; } ?> </body> </html> ```
1. Login with your google account 2. Visit the google recaptcha link. 3. Then follow the link to code integration, follow the code for both client and serverside validation. <https://developers.google.com/recaptcha/docs/invisible> 4. Increase or decrease the security level once after creating the recaptcha, go to the advance settings here, <https://www.google.com/recaptcha/admin#list>
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
Here is a **working** example: ``` <html lang="en"> <head> <meta charset="UTF-8"> <title>ReCAPTCHA Example</title> </head> <body> <div class="container"> <form method="post" action="/contact/" id="contact-form"> <h3 class="title-divider"> <span>Contact Us</span> </h3> <input type="text" name="name"> <div class="captcha"><!-- BEGIN: ReCAPTCHA implementation example. --> <div id="recaptcha-demo" class="g-recaptcha" data-sitekey="YOUR_RECAPTCHA_SITE_KEY" data-callback="onSuccess" data-bind="form-submit"></div> <script> var onSuccess = function (response) { var errorDivs = document.getElementsByClassName("recaptcha-error"); if (errorDivs.length) { errorDivs[0].className = ""; } var errorMsgs = document.getElementsByClassName("recaptcha-error-message"); if (errorMsgs.length) { errorMsgs[0].parentNode.removeChild(errorMsgs[0]); } document.getElementById("contact-form").submit(); };</script><!-- END: ReCAPTCHA implementation example. --> </div> <button id="form-submit" type="submit">Submit</button> </form> <script src="https://www.google.com/recaptcha/api.js" async defer></script> </div> </body> </html> ``` Do not forget to change **YOUR\_RECAPTCHA\_SITE\_KEY** to your Google ReCAPTCHA site key. Next step is to actually validate the data. It is done by making a POST request to the endpoint <https://www.google.com/recaptcha/api/siteverify>, containing your Secret key and the data from the reCAPTCHA, which is identified by **g-recaptcha-response**. There are a lot of different ways it could be done depending on your CMS/Framework. You might have noticed the reCaptcha badge in the lower right corner of the screen. This exists to let users know that a form is protected by reCaptcha now that the verification checkbox has been removed. It’s possible to hide this badge however by configuring it to be inline, and then modifying it with CSS. ``` <style> .grecaptcha-badge {display: none;} </style> ``` *Please note that because Google collects user information to enable reCaptcha functionality, their terms of service require you to alert users to its use.* If you hide the badge you can add an informational paragraph somewhere on the page instead.
1. Login with your google account 2. Visit the google recaptcha link. 3. Then follow the link to code integration, follow the code for both client and serverside validation. <https://developers.google.com/recaptcha/docs/invisible> 4. Increase or decrease the security level once after creating the recaptcha, go to the advance settings here, <https://www.google.com/recaptcha/admin#list>
41,079,379
I have to program a task in python 3.4 that requires the following: - The program ask the user to enter a data model that is made by several submodels in a form of string like the following: ``` # the program ask : please input the submodel1 # user will input: A = a*x + b*y*exp(3*c/d*x) # then the program ask : -> please input the submodel2 # user will input: B = e*x + f*y*exp(3*h/d*x) # then the program ask : -> please input the main model: # user will input: Y = A*x - exp(B**2/y) ``` then the program take these models (strings) and performs some operations on them like curve fitting of the main model to existing data and plot results with showing parameters values. the idea here is to give the user the freedom of choosing the model at runtime without needing to program it as a function inside the app. my problem here resides in converting or interpreting the string as a python function that returns value. I explored solution like the eval() function but I am looking to a solution that is like in the MatLab ``` func = sym('string') func = matlabfunction(func) ``` which creates an anonymous function that you can deal with it easily hope I made myself clear, if any further clarification needed please let me know, the solution should be compatible with python 3.4 Thanks in advance
2016/12/10
[ "https://Stackoverflow.com/questions/41079379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4434914/" ]
Here is how to implement a client + server side **(php)** Invisible reCaptcha functionality: * Client Side ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>reCaptcha</title> <!--api link--> <script src="https://www.google.com/recaptcha/api.js" async defer></script> <!--call back function--> <script> function onSubmit(token) { document.getElementById('reCaptchaForm').submit(); } </script> </head> <body> <div class="container"> <form id="reCaptchaForm" action="signup.php" method="POST"> <input type="text" placeholder="type anything"> <!--Invisible reCaptcha configuration--> <button class="g-recaptcha" data-sitekey="<your site key>" data-callback='onSubmit'>Submit</button> <br/> </form> </div> </body> </html> ``` * Server Side validation: Create a **signup.php** file ```html <?php //only run when form is submitted if(isset($_POST['g-recaptcha-response'])) { $secretKey = '<your secret key>'; $response = $_POST['g-recaptcha-response']; $remoteIp = $_SERVER['REMOTE_ADDR']; $reCaptchaValidationUrl = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$response&remoteip=$remoteIp"); $result = json_decode($reCaptchaValidationUrl, TRUE); //get response along side with all results print_r($result); if($result['success'] == 1) { //True - What happens when user is verified $userMessage = '<div>Success: you\'ve made it :)</div>'; } else { //False - What happens when user is not verified $userMessage = '<div>Fail: please try again :(</div>'; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>reCAPTCHA Response</title> </head> <body> <?php if(!empty($userMessage)) { echo $userMessage; } ?> </body> </html> ```
Here is a **working** example: ``` <html lang="en"> <head> <meta charset="UTF-8"> <title>ReCAPTCHA Example</title> </head> <body> <div class="container"> <form method="post" action="/contact/" id="contact-form"> <h3 class="title-divider"> <span>Contact Us</span> </h3> <input type="text" name="name"> <div class="captcha"><!-- BEGIN: ReCAPTCHA implementation example. --> <div id="recaptcha-demo" class="g-recaptcha" data-sitekey="YOUR_RECAPTCHA_SITE_KEY" data-callback="onSuccess" data-bind="form-submit"></div> <script> var onSuccess = function (response) { var errorDivs = document.getElementsByClassName("recaptcha-error"); if (errorDivs.length) { errorDivs[0].className = ""; } var errorMsgs = document.getElementsByClassName("recaptcha-error-message"); if (errorMsgs.length) { errorMsgs[0].parentNode.removeChild(errorMsgs[0]); } document.getElementById("contact-form").submit(); };</script><!-- END: ReCAPTCHA implementation example. --> </div> <button id="form-submit" type="submit">Submit</button> </form> <script src="https://www.google.com/recaptcha/api.js" async defer></script> </div> </body> </html> ``` Do not forget to change **YOUR\_RECAPTCHA\_SITE\_KEY** to your Google ReCAPTCHA site key. Next step is to actually validate the data. It is done by making a POST request to the endpoint <https://www.google.com/recaptcha/api/siteverify>, containing your Secret key and the data from the reCAPTCHA, which is identified by **g-recaptcha-response**. There are a lot of different ways it could be done depending on your CMS/Framework. You might have noticed the reCaptcha badge in the lower right corner of the screen. This exists to let users know that a form is protected by reCaptcha now that the verification checkbox has been removed. It’s possible to hide this badge however by configuring it to be inline, and then modifying it with CSS. ``` <style> .grecaptcha-badge {display: none;} </style> ``` *Please note that because Google collects user information to enable reCaptcha functionality, their terms of service require you to alert users to its use.* If you hide the badge you can add an informational paragraph somewhere on the page instead.
7,378,431
How to add data to a relationship with multiple foreign keys in Django? I'm building a simulation written in python and would like to use django's orm to store (intermediate and final) results in a database. Therefore I am not concerned with urls and views. The problem I am having is the instantiation of an object with multiple ForeinKeys. This object is supposed to represent the relationship between an agent and a time step. Here is the code: I'm using the following models ``` from django.db import models import random from django.contrib.admin.util import related_name # Create your models here. class Agent(models.Model): agent = int def __init__(self, agent, *args, **kwargs): models.Model.__init__(self, *args, **kwargs) self.agent = agent def __str__(self): return str(self.agent) class Step(models.Model): step = int def __init__(self, step, *args, **kwargs): models.Model.__init__(self, *args, **kwargs) self.step = step def __str__(self): return str(self.step) class StepAgentData(models.Model): def __init__(self, step, agent, *args, **kwargs): models.Model.__init__(self, *args, **kwargs) self.step = step #This does not work self.agent = agent step = models.ForeignKey(Step, related_name='time_step') agent = models.ForeignKey(Agent, related_name='associated_agent') data = float def __unicode__(self): return str("Step %s \t Agent %s ", (self.step,self.agent)) ``` Running the following script ``` from DBStructureTest.App.models import Step, Agent, StepAgentData if __name__ == '__main__': s = Step(1) s.save() a = Agent(2) a.save() sad = StepAgentData(s,a) sad.save() print "finished" ``` results in the following error message when self.step = step is executed in the constructor of the StepAgentData (see comment in the code of the StepAgentData model) ``` > File > "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", > line 367, in __set__ > val = getattr(value, self.field.rel.get_related_field().attname) > File > "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", > line 773, in get_related_field > data = self.to._meta.get_field_by_name(self.field_name) File > "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", > line 307, in get_field_by_name > cache = self.init_name_map() File > "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", > line 337, in init_name_map > for f, model in self.get_all_related_m2m_objects_with_model(): > File > "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", > line 414, in get_all_related_m2m_objects_with_model > cache = self._fill_related_many_to_many_cache() File > "/usr/local/lib/python2.7/dist-packages/django/db/models/options.py", > line 428, in _fill_related_many_to_many_cache > for klass in get_models(): File > "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", > line 167, in get_models > self._populate() File > "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", > line 61, in _populate > self.load_app(app_name, True) File > "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", > line 76, in load_app > app_module = import_module(app_name) File > "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", > line 35, in import_module > __import__(name) ImportError: No module named App ``` The folder structure is the following: ``` |-DBStructureTest |-App |-__init__.py |-Main.py |-models.py |-test.py |-views.py |-__init__.py |-manage.py |-settings.py |-urls.py ``` What am I doing wrong? Help is very much appreciated. EDIT: In the /App directory I get the following after doing 'import models' ` > > > > > > > > > > > > import models > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "models.py", line 1, in > > > from django.db import models > > > File "/usr/local/lib/python2.7/dist-packages/django/db/**init**.py", line 14, in > > > if not settings.DATABASES: > > > File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 276, in **getattr** > > > self.\_setup() > > > File "/usr/local/lib/python2.7/dist-packages/django/conf/**init**.py", line 40, in \_setup > > > raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT\_VARIABLE) > > > ImportError: Settings cannot be imported, because environment variable DJANGO\_SETTINGS\_MODULE is undefined. > > > ' > > > > > > > > > > > > > > > > > >
2011/09/11
[ "https://Stackoverflow.com/questions/7378431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/939186/" ]
Try using [PAM](http://en.wikipedia.org/wiki/Pluggable_Authentication_Modules) via [Python PAM](http://atlee.ca/software/pam/) or similar
That should be possible by having your script read the `/etc/passwd` and `/etc/shadow` files, which contain details about usernames and passwords on a Linux system. Do note that the script will have to have read access to the files, which depending on the situation may or may not be possible. Here are two good articles explaining the format of those files, which should tell you everything you need to know in order to have your script read and understand them: * [Understanding /etc/passwd File Format](http://www.cyberciti.biz/faq/understanding-etcpasswd-file-format/) * [Understanding /etc/shadow File Format](http://www.cyberciti.biz/faq/understanding-etcshadow-file/) By the way, when it talks about *encrypted password*, it means that it has been encrypted using the DES algorithm. You'll probably need to use [pyDes](http://twhiteman.netfirms.com/des.html) or another python implementation of the DES algorithm in order for your script to create an encrypted password that it can compare to the one in `/etc/shadow`.
3,495,290
relatively long-time PHP user here. I could install XAMPP in my sleep at this point to the point where I can get a PHP script running in the browser at "localhost", but in my searches to find a similar path using Python, I've run out of Googling ideas. I've discovered the mod\_python Apache mod, but then I also discovered that it's been discontinued. I'd greatly prefer to do my Python learning in a browser as opposed to the command prompt, so if anybody could point me along the proper path, I'd be very grateful. Thanks!
2010/08/16
[ "https://Stackoverflow.com/questions/3495290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/385950/" ]
well mod\_python has been retired. So in order to host python apps you want `mod_wsgi` <http://code.google.com/p/modwsgi/> But python isn't really like php(as in you mix it with html to get output, if I understand your question correctly). In learning python, using the command line/repl will probably be much more useful/straight forward I would think. If you are looking for python as primarily web development you should look into django (<http://www.djangoproject.com/>) as that might be closer to what you are looking for..
Most Python webframeworks have a built-in minimal development server: * [Flask](http://flask.pocoo.org/docs/quickstart/) * [Turbogears](http://turbogears.org/2.0/docs/main/QuickStart.html#run-the-server) * [Django](http://docs.djangoproject.com/en/dev/ref/django-admin/#runserver-port-or-ipaddr-port) * [Pylons](http://pylonshq.com/docs/en/1.0/gettingstarted/#running-the-application) * [web.py](http://webpy.org/tutorial3.en#start) * [web2py](http://web2py.com/book/default/chapter/03) But don't be afraid of the command line. Python has a great interactive console (just run `python`) and there's an even better one: [IPython](http://ipython.scipy.org/moin/).
3,495,290
relatively long-time PHP user here. I could install XAMPP in my sleep at this point to the point where I can get a PHP script running in the browser at "localhost", but in my searches to find a similar path using Python, I've run out of Googling ideas. I've discovered the mod\_python Apache mod, but then I also discovered that it's been discontinued. I'd greatly prefer to do my Python learning in a browser as opposed to the command prompt, so if anybody could point me along the proper path, I'd be very grateful. Thanks!
2010/08/16
[ "https://Stackoverflow.com/questions/3495290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/385950/" ]
well mod\_python has been retired. So in order to host python apps you want `mod_wsgi` <http://code.google.com/p/modwsgi/> But python isn't really like php(as in you mix it with html to get output, if I understand your question correctly). In learning python, using the command line/repl will probably be much more useful/straight forward I would think. If you are looking for python as primarily web development you should look into django (<http://www.djangoproject.com/>) as that might be closer to what you are looking for..
Many options, here are a couple: * [mod\_wsgi](http://code.google.com/p/modwsgi/) is an Apache module that is suitable for production environments * [SimpleHTTPServer](http://docs.python.org/library/simplehttpserver.html) ships with Python and is easy to use * frameworks like [Django](http://www.djangoproject.com/) or [Twisted](http://twistedmatrix.com/trac/)
40,879,188
np.where lets you pick values to assign for a boolean type query, e.g. ``` test = [0,1,2] np.where(test==0,'True','False') print test ['True','False','False'] ``` Which is basically an 'if' statement. Is there a pythonic way of having an 'if, else if, else' kind of statement (with different cases) for a numpy array? This is my workaround: ``` color = [0,1,2] color = np.where(color==0,'red',color) color = np.where(color==1,'blue',color) color = np.where(color==2,'green',color) print color ['red','blue','green'] ``` But I wonder if there's a better way of doing this.
2016/11/30
[ "https://Stackoverflow.com/questions/40879188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5531108/" ]
`np.choose` is something of a multielement `where`: ``` In [97]: np.choose([0,1,1,2,0,1],['red','green','blue']) Out[97]: array(['red', 'green', 'green', 'blue', 'red', 'green'], dtype='<U5') In [113]: np.choose([0,1,2],[0,np.array([1,2,3])[:,None], np.arange(10,13)]) Out[113]: array([[ 0, 1, 12], [ 0, 2, 12], [ 0, 3, 12]]) ``` In the more complex cases it helps to have a good handle on broadcasting. There are limits, for example no more than 32 choices. It's not used nearly as much as `np.where`. And sometimes you just want to apply `where` or boolean masking multiple times: ``` In [115]: x Out[115]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [116]: x[x<4] += 10 In [117]: x Out[117]: array([[10, 11, 12, 13], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [118]: x[x>8] -=3 In [119]: x Out[119]: array([[ 7, 8, 9, 10], [ 4, 5, 6, 7], [ 8, 6, 7, 8]]) In [120]: x[(4<x)&(x<8)] *=2 In [121]: x Out[121]: array([[14, 8, 9, 10], [ 4, 10, 12, 14], [ 8, 12, 14, 8]]) ```
One of the more Pythonic ways to do this would be to use a list comprehension, like this: ``` >>> color = [0,1,2] >>> ['red' if c == 0 else 'blue' if c == 1 else 'green' for c in color] ['red', 'blue', 'green'] ``` It's fairly intuitive if you read it. For a given item in the list `color`, the value in the new list will be `'red'` if the color is `0`, `'blue'` if it's `1`, and `'green'` otherwise. I don't know if I would take the `if` `else`s in a list comprehension further than three, though. A `for` loop would be appropriate there. Or you could use a dictionary, which might be more "Pythonic," and would be much more scalable: ``` >>> color_dict = {0: 'red', 1: 'blue', 2: 'green'} >>> [color_dict[number] for number in color] ['red', 'blue', 'green'] ```
40,879,188
np.where lets you pick values to assign for a boolean type query, e.g. ``` test = [0,1,2] np.where(test==0,'True','False') print test ['True','False','False'] ``` Which is basically an 'if' statement. Is there a pythonic way of having an 'if, else if, else' kind of statement (with different cases) for a numpy array? This is my workaround: ``` color = [0,1,2] color = np.where(color==0,'red',color) color = np.where(color==1,'blue',color) color = np.where(color==2,'green',color) print color ['red','blue','green'] ``` But I wonder if there's a better way of doing this.
2016/11/30
[ "https://Stackoverflow.com/questions/40879188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5531108/" ]
[numpy.select()](https://numpy.org/doc/stable/reference/generated/numpy.select.html) is what you want here. It is the numpy version of case when. Syntax: ``` import numpy as np color = np.array([0,1,2]) condlist = [color == 1, color == 2, color == 3] choicelist = ['red', 'blue', 'green'] np.select(condlist, choicelist, default='unknown') ``` returns: ``` array(['unknown', 'red', 'blue'], dtype='<U7') ```
One of the more Pythonic ways to do this would be to use a list comprehension, like this: ``` >>> color = [0,1,2] >>> ['red' if c == 0 else 'blue' if c == 1 else 'green' for c in color] ['red', 'blue', 'green'] ``` It's fairly intuitive if you read it. For a given item in the list `color`, the value in the new list will be `'red'` if the color is `0`, `'blue'` if it's `1`, and `'green'` otherwise. I don't know if I would take the `if` `else`s in a list comprehension further than three, though. A `for` loop would be appropriate there. Or you could use a dictionary, which might be more "Pythonic," and would be much more scalable: ``` >>> color_dict = {0: 'red', 1: 'blue', 2: 'green'} >>> [color_dict[number] for number in color] ['red', 'blue', 'green'] ```
40,879,188
np.where lets you pick values to assign for a boolean type query, e.g. ``` test = [0,1,2] np.where(test==0,'True','False') print test ['True','False','False'] ``` Which is basically an 'if' statement. Is there a pythonic way of having an 'if, else if, else' kind of statement (with different cases) for a numpy array? This is my workaround: ``` color = [0,1,2] color = np.where(color==0,'red',color) color = np.where(color==1,'blue',color) color = np.where(color==2,'green',color) print color ['red','blue','green'] ``` But I wonder if there's a better way of doing this.
2016/11/30
[ "https://Stackoverflow.com/questions/40879188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5531108/" ]
[numpy.select()](https://numpy.org/doc/stable/reference/generated/numpy.select.html) is what you want here. It is the numpy version of case when. Syntax: ``` import numpy as np color = np.array([0,1,2]) condlist = [color == 1, color == 2, color == 3] choicelist = ['red', 'blue', 'green'] np.select(condlist, choicelist, default='unknown') ``` returns: ``` array(['unknown', 'red', 'blue'], dtype='<U7') ```
`np.choose` is something of a multielement `where`: ``` In [97]: np.choose([0,1,1,2,0,1],['red','green','blue']) Out[97]: array(['red', 'green', 'green', 'blue', 'red', 'green'], dtype='<U5') In [113]: np.choose([0,1,2],[0,np.array([1,2,3])[:,None], np.arange(10,13)]) Out[113]: array([[ 0, 1, 12], [ 0, 2, 12], [ 0, 3, 12]]) ``` In the more complex cases it helps to have a good handle on broadcasting. There are limits, for example no more than 32 choices. It's not used nearly as much as `np.where`. And sometimes you just want to apply `where` or boolean masking multiple times: ``` In [115]: x Out[115]: array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [116]: x[x<4] += 10 In [117]: x Out[117]: array([[10, 11, 12, 13], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) In [118]: x[x>8] -=3 In [119]: x Out[119]: array([[ 7, 8, 9, 10], [ 4, 5, 6, 7], [ 8, 6, 7, 8]]) In [120]: x[(4<x)&(x<8)] *=2 In [121]: x Out[121]: array([[14, 8, 9, 10], [ 4, 10, 12, 14], [ 8, 12, 14, 8]]) ```
24,606,931
I have tried for hours to install `FiPy` I've installed Pip and many other things to get it to work. Pip successfull installed many of the things I needed but I cannot get it to work for PySparse or FiPy. Why I try, to install PySparse I get an error: ``` $ pip install pysparse Downloading/unpacking pysparse Could not find a version that satisfies the requirement pysparse (from versions: 1.1.1-dev, 1.2-dev, 1.2-dev202, 1.2-dev203, 1.2-dev213, 1.3-dev) Cleaning up... No distributions matching the version for pysparse Storing debug log for failure in /Users/Emily/.pip/pip.log ``` and when I try to install `FiPy` I get this error: ``` $ pip install fipy Downloading/unpacking fipy Downloading FiPy-3.1.tar.gz (5.7MB): 5.7MB downloaded Running setup.py (path:/private/var/folders/jt/gzhjdv8s1xb_v2b52lmr8bx00000gn/T/pip_build_Emily/fipy/setup.py) egg_info for package fipy Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/var/folders/jt/gzhjdv8s1xb_v2b52lmr8bx00000gn/T/pip_build_Emily/fipy/setup.py", line 44, in <module> import ez_setup ImportError: No module named ez_setup Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 17, in <module> File "/private/var/folders/jt/gzhjdv8s1xb_v2b52lmr8bx00000gn/T/pip_build_Emily/fipy/setup.py", line 44, in <module> import ez_setup ImportError: No module named ez_setup ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in /private/var/folders/jt/gzhjdv8s1xb_v2b52lmr8bx00000gn/T/pip_build_Emily/fipy Storing debug log for failure in /Users/Emily/.pip/pip.log ``` Can you please help? Please be specific because I am having a lot of trouble.
2014/07/07
[ "https://Stackoverflow.com/questions/24606931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3811717/" ]
I've just encountered the same problems you did, and here are my work-arounds: Pysparse: pip doesn't find the pysparse distribution in PyPI because it appears to not be a stable version (see e.g. [Could not find a version that satisfies the requirement pytz](https://stackoverflow.com/questions/18230956/could-not-find-a-version-that-satisfies-the-requirement-pytz) for reference). To get around this you could use, as the link suggests, ``` pip install --pre pysparse ``` However, that didn't work for me--the installation failed. So I downloaded and installed pysparse manually from <http://pysparse.sourceforge.net/index.html> FiPY: The error says "no module named ez\_setup". If you install the python ez\_setup module using pip the installation of FiPY should now work. FiPY seems to be working for me now. Good luck!
PySparse is not a strict requirement for FiPy. FiPy needs one of PySparse, Scipy or Trilinos as a linear solver and Scipy is probably the easiest to install. To check that FiPy has access to a linear solver, you can run the tests, ``` $ python -c "import fipy; fipy.test()" ``` It should be evident from the test output if FiPy does not have a solver library available.
55,016,775
I need help making a mirrored right triangle like below ``` 1 21 321 4321 54321 654321 ``` I can print a regular right triangle with the code below ``` print("Pattern A") for i in range(8): for j in range(1,i): print(j, end="") print("") ``` Which prints ``` 1 12 123 1234 12345 123456 ``` But I can't seem to find a way to mirror it. I tried to look online on how to do it but I can't seem to find any results for python and only examples for Java.
2019/03/06
[ "https://Stackoverflow.com/questions/55016775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11157933/" ]
Here is one using the new f-string formatting system: ``` def test(x): s = "" for i in range(1,x+1): s = str(i) + s print(f'{s:>{x}}') test(6) ```
Something like this works. I loop over the amount of lines, add the whitespace needed for that line and print the numbers. ``` def test(x): for i in range(1,x+1): print((x-i)*(" ") + "".join(str(j+1) for j in range(i))) test(6) ```
44,690,174
How to convert a column that has been read as a string into a column of arrays? i.e. convert from below schema ``` scala> test.printSchema root |-- a: long (nullable = true) |-- b: string (nullable = true) +---+---+ | a| b| +---+---+ | 1|2,3| +---+---+ | 2|4,5| +---+---+ ``` To: ``` scala> test1.printSchema root |-- a: long (nullable = true) |-- b: array (nullable = true) | |-- element: long (containsNull = true) +---+-----+ | a| b | +---+-----+ | 1|[2,3]| +---+-----+ | 2|[4,5]| +---+-----+ ``` Please share both scala and python implementation if possible. On a related note, how do I take care of it while reading from the file itself? I have data with ~450 columns and few of them I want to specify in this format. Currently I am reading in pyspark as below: ``` df = spark.read.format('com.databricks.spark.csv').options( header='true', inferschema='true', delimiter='|').load(input_file) ``` Thanks.
2017/06/22
[ "https://Stackoverflow.com/questions/44690174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4531806/" ]
There are various method, The best way to do is using `split` function and cast to `array<long>` ``` data.withColumn("b", split(col("b"), ",").cast("array<long>")) ``` You can also create simple udf to convert the values ``` val tolong = udf((value : String) => value.split(",").map(_.toLong)) data.withColumn("newB", tolong(data("b"))).show ``` Hope this helps!
Using a [UDF](https://jaceklaskowski.gitbooks.io/mastering-apache-spark/spark-sql-udfs.html) would give you exact required schema. Like this: ``` val toArray = udf((b: String) => b.split(",").map(_.toLong)) val test1 = test.withColumn("b", toArray(col("b"))) ``` It would give you schema as follows: ``` scala> test1.printSchema root |-- a: long (nullable = true) |-- b: array (nullable = true) | |-- element: long (containsNull = true) +---+-----+ | a| b | +---+-----+ | 1|[2,3]| +---+-----+ | 2|[4,5]| +---+-----+ ``` As far as applying schema on file read itself is concerned, I think that is a tough task. So, for now you can apply transformation after creating `DataFrameReader` of `test`. I hope this helps!
44,690,174
How to convert a column that has been read as a string into a column of arrays? i.e. convert from below schema ``` scala> test.printSchema root |-- a: long (nullable = true) |-- b: string (nullable = true) +---+---+ | a| b| +---+---+ | 1|2,3| +---+---+ | 2|4,5| +---+---+ ``` To: ``` scala> test1.printSchema root |-- a: long (nullable = true) |-- b: array (nullable = true) | |-- element: long (containsNull = true) +---+-----+ | a| b | +---+-----+ | 1|[2,3]| +---+-----+ | 2|[4,5]| +---+-----+ ``` Please share both scala and python implementation if possible. On a related note, how do I take care of it while reading from the file itself? I have data with ~450 columns and few of them I want to specify in this format. Currently I am reading in pyspark as below: ``` df = spark.read.format('com.databricks.spark.csv').options( header='true', inferschema='true', delimiter='|').load(input_file) ``` Thanks.
2017/06/22
[ "https://Stackoverflow.com/questions/44690174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4531806/" ]
There are various method, The best way to do is using `split` function and cast to `array<long>` ``` data.withColumn("b", split(col("b"), ",").cast("array<long>")) ``` You can also create simple udf to convert the values ``` val tolong = udf((value : String) => value.split(",").map(_.toLong)) data.withColumn("newB", tolong(data("b"))).show ``` Hope this helps!
In python (pyspark) it would be: ``` from pyspark.sql.types import * from pyspark.sql.functions import col, split test = test.withColumn( "b", split(col("b"), ",\s*").cast("array<int>").alias("ev") ) ```
29,989,024
Im trying to use a [specific gamma corrected grayscale implementation](http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0029740) - Gleam to convert an images pixels to grayscale. How can i do this manually with PIL python? ``` def tau_gamma_correct(pixel_channel): pixel_channel = pixel_channel**(1/2.2) return pixel_channel #@param: rgb #@result: returns grayscale value def gleam(rgb): #convert rgb tuple to list rgblist = list(rgb) #gamma correct each rgb channel rgblist[0] = tau_gamma_correct(rgblist[0]) rgblist[1] = tau_gamma_correct(rgblist[1]) rgblist[2] = tau_gamma_correct(rgblist[2]) grayscale = 1/3*(rgblist[0] + rgblist[1] + rgblist[2]) return grayscale # get a glob list of jpg filenames files = glob.glob('*.jpg') for file in files: file = open(file) filename = file.name image = Image.open(file) pix = image.load() width, height = image.size #print(width,height) for x in range(0, width): for y in range(0, height): rgb = pix[x,y] #print(rgb) # calc new pixel value and set to pixel image.mode = 'L' pix[x,y] = gleam(rgb) image.save(filename + 'gray.gleam'+'.jpg') file.close() ``` `SystemError: new style getargs format but argument is not a tuple` It is still expecting the rgb tuple i think.
2015/05/01
[ "https://Stackoverflow.com/questions/29989024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/688830/" ]
I found that i could just build another image: ``` import sys import os import glob import numpy from PIL import Image def tau_gamma_correct(pixel_channel): pixel_channel = pixel_channel**(1/2.2) return pixel_channel #@param: rgb #@result: returns grayscale value def gleam(rgb): #convert rgb tuple to list rgblist = list(rgb) #gamma correct each rgb channel rgblist[0] = tau_gamma_correct(rgblist[0]) print('gleamed red ' + str(rgblist[0])) rgblist[1] = tau_gamma_correct(rgblist[1]) print('gleamed green ' + str(rgblist[1])) rgblist[2] = tau_gamma_correct(rgblist[2]) print('gleamed blue ' + str(rgblist[0])) grayscale = (rgblist[0] + rgblist[1] + rgblist[2])/3 print('grayscale '+ str(grayscale)) return grayscale # get a glob list of jpg filenames files = glob.glob('*.jpg') for file in files: file = open(file) filename = file.name image = Image.open(file) pix = image.load() width, height = image.size new_image = Image.new('L', image.size) #pixelmatrix = [width][height] pixelmatrix = numpy.zeros((width, height)) #print(width,height) for x in range(0, width): for y in range(0, height): rgb = pix[x,y] print('current pixel value: '+str(rgb)) # calc new pixel value and set to pixel #print(gleam(rgb)) gray = gleam(rgb) print('changing to pixel value: '+str(gray)) pixelmatrix[x,y] = gray new_image.save(filename + 'gray.gleam'+'.jpg') new_image.putdata(pixelmatrix) file.close() ```
Seeing the `SystemError: new style getargs format but argument is not a tuple` error it seems that you need to return a tuple, which is represented as : ``` sample_tuple = (1, 2, 3, 4) ``` So we edit the `gleam()` function as: ``` def gleam(rgb): #convert rgb tuple to list rgblist = list(rgb) #gamma correct each rgb channel rgblist[0] = tau_gamma_correct(rgblist[0]) rgblist[1] = tau_gamma_correct(rgblist[1]) rgblist[2] = tau_gamma_correct(rgblist[2]) grayscale = 1/3*(rgblist[0] + rgblist[1] + rgblist[2]) return (grayscale, ) ``` Keep in mind that while returning a single element tuple you need to represent as : ``` sample_tuple = (1, ) ``` This is due to the fact that `(4) == 4` but `(4, ) != 4`
29,989,024
Im trying to use a [specific gamma corrected grayscale implementation](http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0029740) - Gleam to convert an images pixels to grayscale. How can i do this manually with PIL python? ``` def tau_gamma_correct(pixel_channel): pixel_channel = pixel_channel**(1/2.2) return pixel_channel #@param: rgb #@result: returns grayscale value def gleam(rgb): #convert rgb tuple to list rgblist = list(rgb) #gamma correct each rgb channel rgblist[0] = tau_gamma_correct(rgblist[0]) rgblist[1] = tau_gamma_correct(rgblist[1]) rgblist[2] = tau_gamma_correct(rgblist[2]) grayscale = 1/3*(rgblist[0] + rgblist[1] + rgblist[2]) return grayscale # get a glob list of jpg filenames files = glob.glob('*.jpg') for file in files: file = open(file) filename = file.name image = Image.open(file) pix = image.load() width, height = image.size #print(width,height) for x in range(0, width): for y in range(0, height): rgb = pix[x,y] #print(rgb) # calc new pixel value and set to pixel image.mode = 'L' pix[x,y] = gleam(rgb) image.save(filename + 'gray.gleam'+'.jpg') file.close() ``` `SystemError: new style getargs format but argument is not a tuple` It is still expecting the rgb tuple i think.
2015/05/01
[ "https://Stackoverflow.com/questions/29989024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/688830/" ]
The problem is that `image.mode = 'L'` doesn't actually change the type of the image, it just changes the attribute so it's no longer accurate. To change the mode of the image you need to make a new copy with [`image.convert('L')`](http://effbot.org/imagingbook/image.htm#tag-Image.Image.convert). Once you have an image in grayscale mode, it won't require a tuple for a pixel value anymore.
Seeing the `SystemError: new style getargs format but argument is not a tuple` error it seems that you need to return a tuple, which is represented as : ``` sample_tuple = (1, 2, 3, 4) ``` So we edit the `gleam()` function as: ``` def gleam(rgb): #convert rgb tuple to list rgblist = list(rgb) #gamma correct each rgb channel rgblist[0] = tau_gamma_correct(rgblist[0]) rgblist[1] = tau_gamma_correct(rgblist[1]) rgblist[2] = tau_gamma_correct(rgblist[2]) grayscale = 1/3*(rgblist[0] + rgblist[1] + rgblist[2]) return (grayscale, ) ``` Keep in mind that while returning a single element tuple you need to represent as : ``` sample_tuple = (1, ) ``` This is due to the fact that `(4) == 4` but `(4, ) != 4`
29,989,024
Im trying to use a [specific gamma corrected grayscale implementation](http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0029740) - Gleam to convert an images pixels to grayscale. How can i do this manually with PIL python? ``` def tau_gamma_correct(pixel_channel): pixel_channel = pixel_channel**(1/2.2) return pixel_channel #@param: rgb #@result: returns grayscale value def gleam(rgb): #convert rgb tuple to list rgblist = list(rgb) #gamma correct each rgb channel rgblist[0] = tau_gamma_correct(rgblist[0]) rgblist[1] = tau_gamma_correct(rgblist[1]) rgblist[2] = tau_gamma_correct(rgblist[2]) grayscale = 1/3*(rgblist[0] + rgblist[1] + rgblist[2]) return grayscale # get a glob list of jpg filenames files = glob.glob('*.jpg') for file in files: file = open(file) filename = file.name image = Image.open(file) pix = image.load() width, height = image.size #print(width,height) for x in range(0, width): for y in range(0, height): rgb = pix[x,y] #print(rgb) # calc new pixel value and set to pixel image.mode = 'L' pix[x,y] = gleam(rgb) image.save(filename + 'gray.gleam'+'.jpg') file.close() ``` `SystemError: new style getargs format but argument is not a tuple` It is still expecting the rgb tuple i think.
2015/05/01
[ "https://Stackoverflow.com/questions/29989024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/688830/" ]
I found that i could just build another image: ``` import sys import os import glob import numpy from PIL import Image def tau_gamma_correct(pixel_channel): pixel_channel = pixel_channel**(1/2.2) return pixel_channel #@param: rgb #@result: returns grayscale value def gleam(rgb): #convert rgb tuple to list rgblist = list(rgb) #gamma correct each rgb channel rgblist[0] = tau_gamma_correct(rgblist[0]) print('gleamed red ' + str(rgblist[0])) rgblist[1] = tau_gamma_correct(rgblist[1]) print('gleamed green ' + str(rgblist[1])) rgblist[2] = tau_gamma_correct(rgblist[2]) print('gleamed blue ' + str(rgblist[0])) grayscale = (rgblist[0] + rgblist[1] + rgblist[2])/3 print('grayscale '+ str(grayscale)) return grayscale # get a glob list of jpg filenames files = glob.glob('*.jpg') for file in files: file = open(file) filename = file.name image = Image.open(file) pix = image.load() width, height = image.size new_image = Image.new('L', image.size) #pixelmatrix = [width][height] pixelmatrix = numpy.zeros((width, height)) #print(width,height) for x in range(0, width): for y in range(0, height): rgb = pix[x,y] print('current pixel value: '+str(rgb)) # calc new pixel value and set to pixel #print(gleam(rgb)) gray = gleam(rgb) print('changing to pixel value: '+str(gray)) pixelmatrix[x,y] = gray new_image.save(filename + 'gray.gleam'+'.jpg') new_image.putdata(pixelmatrix) file.close() ```
The problem is that `image.mode = 'L'` doesn't actually change the type of the image, it just changes the attribute so it's no longer accurate. To change the mode of the image you need to make a new copy with [`image.convert('L')`](http://effbot.org/imagingbook/image.htm#tag-Image.Image.convert). Once you have an image in grayscale mode, it won't require a tuple for a pixel value anymore.
66,312,791
i have a python script to download and save a MP3 and i would like to add code to cut out 5 seconds from the beginning of the MP3. ``` def download(): ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': 'c:/MP3/%(title)s.%(ext)s', 'cookiefile': 'cookies.txt', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([inpYTLinkSong.get()]) ``` I found some code for command line to cut x seconds: `ffmpeg -ss 00:00:15.00 -i "OUTPUT-OF-FIRST URL" -t 00:00:10.00 -c copy out.mp4` So i think i have to get the -ss part into the postprocessor part in my script, something like: ``` 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', 'ss':'00:00:05.00' }], ``` But of course its not working with 'ss' or 'duration' (found in ffmpeg docu). So any ideas what i have to put there instead of 'ss'?
2021/02/22
[ "https://Stackoverflow.com/questions/66312791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11675699/" ]
I don't think you can directly limit the width of the `Textfield`, it will take the max width of its parent element. But you can put it in a parent element with fixable width: ```py v.Row( children = [ v.Html( tag = 'div', style_ = 'width: 500px', children = [ v.TextField(type = "number") ] ), v.Html( tag = 'H1', children = ['Some text here'] ) ] ) ```
Here is the best I have so far, based on Christoph's answer: I added v.Spacer, and converted the second part to a v.Col (might be worth also including the first part to a v.Col ?) ``` import ipyvuetify as v v.Row( children = [ v.Html( tag = 'div', style_ = 'width: 50px', children = [ v.TextField(type = "number") ] ), v.Spacer(), v.Col( sm=3, tag = 'H1', children = ['Some text here'] ) ] ) ``` [![enter image description here](https://i.stack.imgur.com/J2Kx3.png)](https://i.stack.imgur.com/J2Kx3.png)
66,312,791
i have a python script to download and save a MP3 and i would like to add code to cut out 5 seconds from the beginning of the MP3. ``` def download(): ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': 'c:/MP3/%(title)s.%(ext)s', 'cookiefile': 'cookies.txt', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([inpYTLinkSong.get()]) ``` I found some code for command line to cut x seconds: `ffmpeg -ss 00:00:15.00 -i "OUTPUT-OF-FIRST URL" -t 00:00:10.00 -c copy out.mp4` So i think i have to get the -ss part into the postprocessor part in my script, something like: ``` 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', 'ss':'00:00:05.00' }], ``` But of course its not working with 'ss' or 'duration' (found in ffmpeg docu). So any ideas what i have to put there instead of 'ss'?
2021/02/22
[ "https://Stackoverflow.com/questions/66312791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11675699/" ]
Adding a `max-width:50px` to the TextField style works. ```py import ipyvuetify as v text_field_widget = v.TextField( style_ = "max-width:50px", v_model=None, type="number") #Textfield should be an one digit number... row = v.Row(class_ = 'mx-2',children=[text_field_widget, v.Html(tag='H1',children=['Some text here'])]) row ``` [![enter image description here](https://i.stack.imgur.com/FOTWw.png)](https://i.stack.imgur.com/FOTWw.png)
I don't think you can directly limit the width of the `Textfield`, it will take the max width of its parent element. But you can put it in a parent element with fixable width: ```py v.Row( children = [ v.Html( tag = 'div', style_ = 'width: 500px', children = [ v.TextField(type = "number") ] ), v.Html( tag = 'H1', children = ['Some text here'] ) ] ) ```
66,312,791
i have a python script to download and save a MP3 and i would like to add code to cut out 5 seconds from the beginning of the MP3. ``` def download(): ydl_opts = { 'format': 'bestaudio/best', 'outtmpl': 'c:/MP3/%(title)s.%(ext)s', 'cookiefile': 'cookies.txt', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([inpYTLinkSong.get()]) ``` I found some code for command line to cut x seconds: `ffmpeg -ss 00:00:15.00 -i "OUTPUT-OF-FIRST URL" -t 00:00:10.00 -c copy out.mp4` So i think i have to get the -ss part into the postprocessor part in my script, something like: ``` 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', 'ss':'00:00:05.00' }], ``` But of course its not working with 'ss' or 'duration' (found in ffmpeg docu). So any ideas what i have to put there instead of 'ss'?
2021/02/22
[ "https://Stackoverflow.com/questions/66312791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11675699/" ]
Adding a `max-width:50px` to the TextField style works. ```py import ipyvuetify as v text_field_widget = v.TextField( style_ = "max-width:50px", v_model=None, type="number") #Textfield should be an one digit number... row = v.Row(class_ = 'mx-2',children=[text_field_widget, v.Html(tag='H1',children=['Some text here'])]) row ``` [![enter image description here](https://i.stack.imgur.com/FOTWw.png)](https://i.stack.imgur.com/FOTWw.png)
Here is the best I have so far, based on Christoph's answer: I added v.Spacer, and converted the second part to a v.Col (might be worth also including the first part to a v.Col ?) ``` import ipyvuetify as v v.Row( children = [ v.Html( tag = 'div', style_ = 'width: 50px', children = [ v.TextField(type = "number") ] ), v.Spacer(), v.Col( sm=3, tag = 'H1', children = ['Some text here'] ) ] ) ``` [![enter image description here](https://i.stack.imgur.com/J2Kx3.png)](https://i.stack.imgur.com/J2Kx3.png)
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
``` f=[1,1] for i in range(8): s=len(f) f.append(f[s-1]+f[s-2]) #sum of last two elements print(f) ``` or use -1 and -2 as index for two last element.
Script ``` f=[1,1] for i in range(2,8): print(i) f.append(f[i-1]+f[i-2]) print(f) ``` Output ``` 2 [1, 1, 2] 3 [1, 1, 2, 3] 4 [1, 1, 2, 3, 5] 5 [1, 1, 2, 3, 5, 8] 6 [1, 1, 2, 3, 5, 8, 13] 7 [1, 1, 2, 3, 5, 8, 13, 21] ``` Issue is `i` starts from 0, `f[-1], f[-2]` returns 0. start using range from 2 and 8 represents first 8 fibonacci numbers. removing debug print Script ``` f=[1,1] for i in range(2,8): f.append(f[i-1]+f[i-2]) print(f) ```
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
``` f=[1,1] for i in range(8): s=len(f) f.append(f[s-1]+f[s-2]) #sum of last two elements print(f) ``` or use -1 and -2 as index for two last element.
You should be aware that the [`range`](https://docs.python.org/3.6/library/functions.html#func-range) function starts at 0 if you don't explicitly specify a starting point. In your case, it should be: `for i in range(2, 8)`. Output: ``` [1, 1, 2, 3, 5, 8, 13, 21] ``` Also, in Python, you can use negative index in an array to count from the right instead of the left, this is why you had this weird result.
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
``` f=[1,1] for i in range(8): f.append(f[i]+f[i+1]) print(f) ``` **RESULT** ``` [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] ```
Script ``` f=[1,1] for i in range(2,8): print(i) f.append(f[i-1]+f[i-2]) print(f) ``` Output ``` 2 [1, 1, 2] 3 [1, 1, 2, 3] 4 [1, 1, 2, 3, 5] 5 [1, 1, 2, 3, 5, 8] 6 [1, 1, 2, 3, 5, 8, 13] 7 [1, 1, 2, 3, 5, 8, 13, 21] ``` Issue is `i` starts from 0, `f[-1], f[-2]` returns 0. start using range from 2 and 8 represents first 8 fibonacci numbers. removing debug print Script ``` f=[1,1] for i in range(2,8): f.append(f[i-1]+f[i-2]) print(f) ```
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
``` f=[1,1] for i in range(8): s=len(f) f.append(f[s-1]+f[s-2]) #sum of last two elements print(f) ``` or use -1 and -2 as index for two last element.
Adding to pjs' answer: When `i = 0`, you are adding `f[-1]` and `f[-2]`, where an index of `-1` gives you the last element in the list and so on. To fix that, as other answers have already pointed out, you need to set the correct starting point for `range()`.
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
Python's `range` starts at 0, you need to start with generating element 2. By starting at 0, you get negative indices for the first couple of calculations, which access from the end of the list. To fix this, change the loop to `for i in range(2, 8)`. To clarify what seems to be a source of confusion, by starting the `range` at zero and using negative indexing you end up with the following terms being summed and appended to the list: ``` f[2] = f[0-1] + f[0-2] = f[-1] + f[-2] (= f[1] + f[0]) = 1 + 1 = 2 # looking good f[3] = f[1-1] + f[1-2] = f[0] + f[-1] (= f[0] + f[2]) = 1 + 2 = 3 # looking good f[4] = f[2-1] + f[2-2] = f[1] + f[0] = 1 + 1 = 2 # oops! f[5] = f[3-1] + f[3-2] = f[2] + f[1] = 2 + 1 = 3 ``` From that point on the numbers are on track, but offset from the proper indexing by 2.
Script ``` f=[1,1] for i in range(2,8): print(i) f.append(f[i-1]+f[i-2]) print(f) ``` Output ``` 2 [1, 1, 2] 3 [1, 1, 2, 3] 4 [1, 1, 2, 3, 5] 5 [1, 1, 2, 3, 5, 8] 6 [1, 1, 2, 3, 5, 8, 13] 7 [1, 1, 2, 3, 5, 8, 13, 21] ``` Issue is `i` starts from 0, `f[-1], f[-2]` returns 0. start using range from 2 and 8 represents first 8 fibonacci numbers. removing debug print Script ``` f=[1,1] for i in range(2,8): f.append(f[i-1]+f[i-2]) print(f) ```
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
``` f=[1,1] for i in range(8): f.append(f[i]+f[i+1]) print(f) ``` **RESULT** ``` [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] ```
You should be aware that the [`range`](https://docs.python.org/3.6/library/functions.html#func-range) function starts at 0 if you don't explicitly specify a starting point. In your case, it should be: `for i in range(2, 8)`. Output: ``` [1, 1, 2, 3, 5, 8, 13, 21] ``` Also, in Python, you can use negative index in an array to count from the right instead of the left, this is why you had this weird result.
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
``` f=[1,1] for i in range(8): f.append(f[i]+f[i+1]) print(f) ``` **RESULT** ``` [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] ```
``` f=[1,1] for i in range(8): s=len(f) f.append(f[s-1]+f[s-2]) #sum of last two elements print(f) ``` or use -1 and -2 as index for two last element.
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
Python's `range` starts at 0, you need to start with generating element 2. By starting at 0, you get negative indices for the first couple of calculations, which access from the end of the list. To fix this, change the loop to `for i in range(2, 8)`. To clarify what seems to be a source of confusion, by starting the `range` at zero and using negative indexing you end up with the following terms being summed and appended to the list: ``` f[2] = f[0-1] + f[0-2] = f[-1] + f[-2] (= f[1] + f[0]) = 1 + 1 = 2 # looking good f[3] = f[1-1] + f[1-2] = f[0] + f[-1] (= f[0] + f[2]) = 1 + 2 = 3 # looking good f[4] = f[2-1] + f[2-2] = f[1] + f[0] = 1 + 1 = 2 # oops! f[5] = f[3-1] + f[3-2] = f[2] + f[1] = 2 + 1 = 3 ``` From that point on the numbers are on track, but offset from the proper indexing by 2.
Adding to pjs' answer: When `i = 0`, you are adding `f[-1]` and `f[-2]`, where an index of `-1` gives you the last element in the list and so on. To fix that, as other answers have already pointed out, you need to set the correct starting point for `range()`.
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
``` f=[1,1] for i in range(8): f.append(f[i]+f[i+1]) print(f) ``` **RESULT** ``` [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] ```
Adding to pjs' answer: When `i = 0`, you are adding `f[-1]` and `f[-2]`, where an index of `-1` gives you the last element in the list and so on. To fix that, as other answers have already pointed out, you need to set the correct starting point for `range()`.
44,141,117
I am trying to print fibonacci series using lists in python. This is my code ``` f=[1,1] for i in range(8): f.append(f[i-1]+f[i-2]) print(f) ``` output is ``` [1, 1, 2, 3, 2, 3, 5, 5, 5, 8] ``` I am not getting the bug here!
2017/05/23
[ "https://Stackoverflow.com/questions/44141117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054946/" ]
Python's `range` starts at 0, you need to start with generating element 2. By starting at 0, you get negative indices for the first couple of calculations, which access from the end of the list. To fix this, change the loop to `for i in range(2, 8)`. To clarify what seems to be a source of confusion, by starting the `range` at zero and using negative indexing you end up with the following terms being summed and appended to the list: ``` f[2] = f[0-1] + f[0-2] = f[-1] + f[-2] (= f[1] + f[0]) = 1 + 1 = 2 # looking good f[3] = f[1-1] + f[1-2] = f[0] + f[-1] (= f[0] + f[2]) = 1 + 2 = 3 # looking good f[4] = f[2-1] + f[2-2] = f[1] + f[0] = 1 + 1 = 2 # oops! f[5] = f[3-1] + f[3-2] = f[2] + f[1] = 2 + 1 = 3 ``` From that point on the numbers are on track, but offset from the proper indexing by 2.
``` f=[1,1] for i in range(8): s=len(f) f.append(f[s-1]+f[s-2]) #sum of last two elements print(f) ``` or use -1 and -2 as index for two last element.
21,395,069
I am running ubuntu 13.10 with the latest pip. I have a whole set of SSL certs for my corporate proxy installed as per: <https://askubuntu.com/questions/73287/how-do-i-install-a-root-certificate> now. Firefox no longer complains about unrecognised certs but I still get: ``` Could not fetch URL http://pypi.python.org/simple/: There was a problem confirming the ssl certificate: [Errno 1] _ssl.c:509: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` with pip? I have tried adding settings to $HOME/.pip/pip.conf ``` [global] cert = /etc/ssl/certs/mycorporatecert.pem ``` as well Thanks
2014/01/28
[ "https://Stackoverflow.com/questions/21395069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1687633/" ]
I guess you would have to use `pip`'s `--cert` option. ``` --cert <path> Path to alternate CA bundle. ``` There's no indication in the documentation that you can use the `cert=` option in the `pip.conf` configuration file. See: <https://pip.pypa.io/en/stable/reference/pip/?highlight=proxy#cmdoption-cert>
try updating your proxy variables as shown here for http\_proxy and https\_proxy <https://askubuntu.com/questions/228530/updating-http-proxy-environment-variable> you should need the cert (or declared global cert as you have it above) as well as the proxy. the alternative to setting the variables would be to use it from the command line like [user:passwd@]proxy.server:port ``` pip install --proxy http://proxy.company.com:80 <package> ```
21,395,069
I am running ubuntu 13.10 with the latest pip. I have a whole set of SSL certs for my corporate proxy installed as per: <https://askubuntu.com/questions/73287/how-do-i-install-a-root-certificate> now. Firefox no longer complains about unrecognised certs but I still get: ``` Could not fetch URL http://pypi.python.org/simple/: There was a problem confirming the ssl certificate: [Errno 1] _ssl.c:509: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` with pip? I have tried adding settings to $HOME/.pip/pip.conf ``` [global] cert = /etc/ssl/certs/mycorporatecert.pem ``` as well Thanks
2014/01/28
[ "https://Stackoverflow.com/questions/21395069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1687633/" ]
I guess you would have to use `pip`'s `--cert` option. ``` --cert <path> Path to alternate CA bundle. ``` There's no indication in the documentation that you can use the `cert=` option in the `pip.conf` configuration file. See: <https://pip.pypa.io/en/stable/reference/pip/?highlight=proxy#cmdoption-cert>
Despite what the documentation might say placing `cert = PATH_TO_CERTIFICATE_FILE` in the `pip.conf` or `pip.ini` did indeed work for me, at least for native Windows Python 2.7.13 with pip 9.0.1. BTW: on windows the configuration file is in `%APPDATA%\pip\pip.ini` and might have to be created manually (including the `pip` directory).
21,395,069
I am running ubuntu 13.10 with the latest pip. I have a whole set of SSL certs for my corporate proxy installed as per: <https://askubuntu.com/questions/73287/how-do-i-install-a-root-certificate> now. Firefox no longer complains about unrecognised certs but I still get: ``` Could not fetch URL http://pypi.python.org/simple/: There was a problem confirming the ssl certificate: [Errno 1] _ssl.c:509: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` with pip? I have tried adding settings to $HOME/.pip/pip.conf ``` [global] cert = /etc/ssl/certs/mycorporatecert.pem ``` as well Thanks
2014/01/28
[ "https://Stackoverflow.com/questions/21395069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1687633/" ]
I don't know if this has always been the case, but I've found I also need to set the REQUESTS\_CA\_BUNDLE environment variable, presumably as pip uses requests and doesn't pass all the config through to it.
try updating your proxy variables as shown here for http\_proxy and https\_proxy <https://askubuntu.com/questions/228530/updating-http-proxy-environment-variable> you should need the cert (or declared global cert as you have it above) as well as the proxy. the alternative to setting the variables would be to use it from the command line like [user:passwd@]proxy.server:port ``` pip install --proxy http://proxy.company.com:80 <package> ```
21,395,069
I am running ubuntu 13.10 with the latest pip. I have a whole set of SSL certs for my corporate proxy installed as per: <https://askubuntu.com/questions/73287/how-do-i-install-a-root-certificate> now. Firefox no longer complains about unrecognised certs but I still get: ``` Could not fetch URL http://pypi.python.org/simple/: There was a problem confirming the ssl certificate: [Errno 1] _ssl.c:509: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed ``` with pip? I have tried adding settings to $HOME/.pip/pip.conf ``` [global] cert = /etc/ssl/certs/mycorporatecert.pem ``` as well Thanks
2014/01/28
[ "https://Stackoverflow.com/questions/21395069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1687633/" ]
I don't know if this has always been the case, but I've found I also need to set the REQUESTS\_CA\_BUNDLE environment variable, presumably as pip uses requests and doesn't pass all the config through to it.
Despite what the documentation might say placing `cert = PATH_TO_CERTIFICATE_FILE` in the `pip.conf` or `pip.ini` did indeed work for me, at least for native Windows Python 2.7.13 with pip 9.0.1. BTW: on windows the configuration file is in `%APPDATA%\pip\pip.ini` and might have to be created manually (including the `pip` directory).
70,622,248
My question is an extension to this: [Python Accessing Values in A List of Dictionaries](https://stackoverflow.com/questions/17117912/python-accessing-values-in-a-list-of-dictionaries) I want to only return values from dictionaries if another given value exists in that dictionary. In the case of the example given in the linked question, say I only want to return 'Name' values if the 'Age' value in the dictionary is '17'. This should output ```py 'Suzy' ``` only.
2022/01/07
[ "https://Stackoverflow.com/questions/70622248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3465940/" ]
The reason for your error is that the conditional operator (`c ? t : f`) takes precedence over the lambda declaration (`=>`). [source](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/#operator-precedence) Wrapping the conditional operator in `{}` brackets should solve your problem: ```cs CreateMap<CompanyClient, MyDto>() .ForMember( dto => dto.PaymentTerms, opt => opt.MapFrom(companyClient => { companyClient.Company.PaymentTerms != null ? companyClient.Company.PaymentTerms.Value : null })) ```
If someone has this error and the answers above do not help, try the following. <https://stackoverflow.com/a/60379426/13434418> Preview (Conditional mapping with different source types) ``` //Cannot convert lambda expression to type x.MapFrom(src => src.CommunityId.HasValue ? src.Community : src.Account) //OK x.MapFrom(src => src.CommunityId.HasValue ? (object)src.Community : src.Account) ```
70,622,248
My question is an extension to this: [Python Accessing Values in A List of Dictionaries](https://stackoverflow.com/questions/17117912/python-accessing-values-in-a-list-of-dictionaries) I want to only return values from dictionaries if another given value exists in that dictionary. In the case of the example given in the linked question, say I only want to return 'Name' values if the 'Age' value in the dictionary is '17'. This should output ```py 'Suzy' ``` only.
2022/01/07
[ "https://Stackoverflow.com/questions/70622248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3465940/" ]
I found that we can get rid of this stupid message by just casting the non-null result to the output type. So where ``` .ForMember( dst => dst.VisitReportFileId, opt => opt.MapFrom(src => src.VisitReportFile == null ? null : src.VisitReportFile.Id.Key)); ``` Gives me a > > Cannot convert lambda expression to type 'IValueResolver<Activity, ActivityDTO, object>' because it is not a delegate type > > > I can fix it by casting the "else" result to `Guid?`: ``` .ForMember( dst => dst.VisitReportFileId, opt => opt.MapFrom(src => src.VisitReportFile == null ? null : (Guid?)src.VisitReportFile.Id.Key)); ```
If someone has this error and the answers above do not help, try the following. <https://stackoverflow.com/a/60379426/13434418> Preview (Conditional mapping with different source types) ``` //Cannot convert lambda expression to type x.MapFrom(src => src.CommunityId.HasValue ? src.Community : src.Account) //OK x.MapFrom(src => src.CommunityId.HasValue ? (object)src.Community : src.Account) ```
63,583,084
According to this [FAQ page](https://faq.whatsapp.com/iphone/how-to-link-to-whatsapp-from-a-different-app) of Whatsapp on **How to link to WhatsApp from a different app** Using the URL `whatsapp://send?phone=XXXXXXXXXXXXX&text=Hello` can be used to open the Whatsapp app on a Windows PC and perform a custom action. It does work when it is opened in a browser. The URL opens Whatsapp installed and composes the message(*parameter:*`text`) for the given contact(*parameter:*`phone`) I want to open the Whatsapp application directly using python script without the intervention of browser in between I have tried using `request` and `urlib`, but they don't consider it as a valid schema for URL as it does not have a `http://` or `https://` instead it has `whatsapp://`. ``` requests.exceptions.InvalidSchema: No connection adapters were found for 'whatsapp://send' ``` Is there a library in python that would open the associated applications directly based on the URL. **P.S.** I know the page is for Iphone but the link works perfectly on windows browser. Just need to know if that can be used. Working with `Python 3.7.9` on **Windows 10**
2020/08/25
[ "https://Stackoverflow.com/questions/63583084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/603633/" ]
You can use cmd exe to do such a job. Just try ``` import subprocess subprocess.Popen(["cmd", "/C", "start whatsapp://send?phone=XXXXXXXXXXXXX&text=Hello"], shell=True) ``` edit: if you want to pass '&'(ampersand) in cmd shell you need to use escape char '^' for it. please try that one ``` subprocess.Popen(["cmd", "/C", "start whatsapp://send?phone=XXXXXXXXXXXXX^&text=Hello"], shell=True) ```
Using this command start whatsapp://send?phone=XXXXXXXXXXXXX^&text=Hello not working after updated to new WhatsApp Desktop App (UWP) for windows. you have other idea for send text message to destination user.
50,546,892
i've seen some people write their shebang line with a space after env. Eg. ``` #!/usr/bin/env python ``` Is this a typo? I don't ever use a space. I use ``` #!/usr/bin/env/python ``` Can someone please clarify this?
2018/05/26
[ "https://Stackoverflow.com/questions/50546892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9536653/" ]
No it isn't a typo! The one you are using will not work on all os's. E.G. in my Ubuntu Linux implementation 'env' is a program in /usr/bin not a directory so #!/usr/bin/env/python won't work.
Not using a space isn't a typo, but leads to portability issues when executing the same file on different machines. The purpose of the shebang line (`#!/usr....`) is to indicate what interpreter is to be used when executing the code in the file. According to [Wikipedia](https://en.wikipedia.org/wiki/Shebang_%28Unix%29#Syntax): > > The form of a shebang interpreter directive is as follows: > > > `#!interpreter [optional-arg]` > > > in which interpreter is an absolute path to an executable program. The optional argument is a string representing a single argument. > > > The example you provided, `#!/usr/bin/env python`, actually indicates to the shell that the interpreter to be used when executing the file is the first python interpreter that exists in the user's path. The shebang line is written this way to [ensure portability](https://en.wikipedia.org/wiki/Shebang_(Unix)#Portability): > > Shebangs must specify absolute paths (or paths relative to current working directory) to system executables; this can cause problems on systems that have a non-standard file system layout. Even when systems have fairly standard paths, it is quite possible for variants of the same operating system to have different locations for the desired interpreter. Python, for example, might be in /usr/bin/python, /usr/local/bin/python, or even something like /home/username/bin/python if installed by an ordinary user. > > > Because of this it is sometimes required to edit the shebang line after copying a script from one computer to another because the path that was coded into the script may not apply on a new machine, depending on the consistency in past convention of placement of the interpreter. For this reason and because POSIX does not standardize path names, POSIX does not standardize the feature. > > > Often, the program /usr/bin/env can be used to circumvent this limitation by introducing a level of indirection. #! is followed by /usr/bin/env, followed by the desired command without full path, as in this example: > > > `#!/usr/bin/env sh` > > >
57,864,579
I have a dataset of 8500 rows of text. I want to apply a function `pre_process` on each of these rows. When I do it serially, it takes about 42 mins on my computer: ``` import pandas as pd import time import re ### constructing a sample dataframe of 10 rows to demonstrate df = pd.DataFrame(columns=['text']) df.text = ["The Rock is destined to be the 21st Century 's new `` Conan '' and that he 's going to make a splash even greater than Arnold Schwarzenegger , Jean-Claud Van Damme or Steven Segal .", "The gorgeously elaborate continuation of `` The Lord of the Rings '' trilogy is so huge that a column of words can not adequately describe co-writer/director Peter Jackson 's expanded vision of J.R.R. Tolkien 's Middle-earth .", 'Singer/composer Bryan Adams contributes a slew of songs -- a few potential hits , a few more simply intrusive to the story -- but the whole package certainly captures the intended , er , spirit of the piece .', "You 'd think by now America would have had enough of plucky British eccentrics with hearts of gold .", 'Yet the act is still charming here .', "Whether or not you 're enlightened by any of Derrida 's lectures on `` the other '' and `` the self , '' Derrida is an undeniably fascinating and playful fellow .", 'Just the labour involved in creating the layered richness of the imagery in this chiaroscuro of madness and light is astonishing .', 'Part of the charm of Satin Rouge is that it avoids the obvious with humour and lightness .', "a screenplay more ingeniously constructed than `` Memento ''", "`` Extreme Ops '' exceeds expectations ."] def pre_process(text): ''' function to pre-process and clean text ''' stop_words = ['in', 'of', 'at', 'a', 'the'] # lowercase text=str(text).lower() # remove special characters except spaces, apostrophes and dots text=re.sub(r"[^a-zA-Z0-9.']+", ' ', text) # remove stopwords text=[word for word in text.split(' ') if word not in stop_words] return ' '.join(text) t = time.time() for i in range(len(df)): df.text[i] = pre_process(df.text[i]) print('Time taken for pre-processing the data = {} mins'.format((time.time()-t)/60)) >>> Time taken for pre-processing the data = 41.95724259614944 mins ``` So, I want to make use of multiprocessing for this task. I took help from [here](https://stackoverflow.com/questions/48934807/how-to-convert-a-for-loop-into-parallel-processing-in-python) and wrote the following code: ``` import pandas as pd import multiprocessing as mp pool = mp.Pool(mp.cpu_count()) def func(text): return pre_process(text) t = time.time() results = pool.map(func, [df.text[i] for i in range(len(df))]) print('Time taken for pre-processing the data = {} mins'.format((time.time()-t)/60)) pool.close() ``` But the code just keeps on running, and doesn't stop. How can I get it to work?
2019/09/10
[ "https://Stackoverflow.com/questions/57864579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5305512/" ]
Try following : ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Serialization; namespace ConsoleApplication131 { class Program { const string FILENAME = @"c:\temp\test.xml"; static void Main(string[] args) { XmlReader reader = XmlReader.Create(FILENAME); XmlSerializer serializer = new XmlSerializer(typeof(Envelope)); Envelope envelope = (Envelope)serializer.Deserialize(reader); } } [XmlRoot(ElementName = "Envelope", Namespace = "http://www.w3.org/2003/05/soap-envelope")] public class Envelope { [XmlElement(ElementName = "Header", Namespace = "http://www.w3.org/2003/05/soap-envelope")] public Header header { get; set; } [XmlElement(ElementName = "Body", Namespace = "http://www.w3.org/2003/05/soap-envelope")] public Body body { get; set; } } [XmlRoot(ElementName = "Header", Namespace = "http://www.w3.org/2003/05/soap-envelope")] public class Header { [XmlElement(ElementName = "Action", Namespace = "http://www.w3.org/2005/08/addressing")] public Action action { get; set; } } [XmlRoot(ElementName = "Action", Namespace = "http://www.w3.org/2005/08/addressing")] public class Action { [XmlAttribute(AttributeName = "mustUnderstand", Namespace = "http://www.w3.org/2003/05/soap-envelope")] public int mustUnderstand { get; set;} [XmlText] public string value { get;set;} } [XmlRoot(ElementName = "Body", Namespace = "")] public class Body { [XmlElement(ElementName = "BatchResponse", Namespace = "https://example.com/operations")] public BatchResponse batchResponse { get; set; } } [XmlRoot(ElementName = "BatchResponse", Namespace = "https://example.com/operations")] public class BatchResponse { [XmlElement(ElementName = "BatchResult", Namespace = "https://example.com/operations")] public BatchResult batchResult { get; set; } } [XmlRoot(ElementName = "BatchResult", Namespace = "https://example.com/operations")] public class BatchResult { [XmlElement(ElementName = "FailureMessages", Namespace = "https://example.com/responses")] public string failureMessages { get; set; } [XmlElement(ElementName = "FailureType", Namespace = "https://example.com/responses")] public string failureType { get; set; } [XmlElement(ElementName = "ProcessedSuccessfully", Namespace = "https://example.com/responses")] public Boolean processedSuccessfully { get; set; } [XmlElement(ElementName = "SessionId", Namespace = "https://example.com/responses")] public string sessionId { get; set; } [XmlElement(ElementName = "TotalPages", Namespace = "https://example.com/responses")] public int totalPages { get; set; } } } ```
you can use `local-name()` to ignore the namespace in xpath ``` //*[local-name()='Envelope']/*[local-name()='Body']/*[local-name()='BatchResponse'] ```
51,311,741
how can i create a spoofed UDP packet using python sockets,without using scapy library. i have created the socket like this ``` sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP sock.sendto(bytes('', "utf-8"), ('192.168.1.9', 7043))# 192.168.1.9dest 7043 dest port ```
2018/07/12
[ "https://Stackoverflow.com/questions/51311741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6584777/" ]
This is one of the first results for google searches like "spoofing udp packet python" so I am going to expand @Cukic0d's answer using scapy. Using the scapy CLI tool (some Linux distributions package it separately to the scapy Python library ): ```py pkt = IP(dst="1.1.1.1")/UDP(sport=13338, dport=13337)/"fm12abcd" send(pkt) ``` This sends a UDP Packet to the IP `1.1.1.1` with the source port `13338`, destination port `13337` and the content `fm12abcd`. If you need to a certain interface for some reason (like sending over a VPN that isn't your default route) you can use `send(pkt, iface='tun0')` to specify it. One difference to @Cukic0d's answer is that this solution is more flexible by sending a layer 3 packet with `send` instead of a layer 2 packet with `sendp`. So it isn't necessary to prepend the correct Ethernet header with `Ether()` which can cause issues in some scenarios, e.g.: ``` WARNING: Could not get the source MAC: Unsupported address family (-2) for interface [tun0] WARNING: Mac address to reach destination not found. Using broadcast. ```
I think you mean changing the source and destination addresses from the IP layer (on which the UDP layer is based). To do so, you will need to use raw sockets. (SOCK\_RAW), meaning that you have to build everything starting from the Ethernet layer to the UDP layer. Honestly, without scapy, that’s a lot of hard work. If you wanted to use scapy, it would take 2 lines: ``` pkt = Ether()/IP(src=“...”, dst=“...”)/UDP()/... sendp(pkt) ``` I really advice you to use scapy. The code itself is quite small so I don’t see a reason not to use it. It’s defiantly the easiest in python
20,078,739
I have a list of objects that I need to sort according to a [key function](https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions "Key functions"). The problem is that some of the elements in my list can go "out-of-date" while the list is being sorted. When the key function is called on such an expired item, it fails with an exception. Ideally, what I would like is a way of sorting my list with a key function such that when an error occurs upon calling the key function on an element, this element is excluded from the sort result. My problem can be reconstructed using the following example: Suppose I have two classes, `Good` and `Bad`: ``` class Good(object): def __init__(self, x): self.x = x def __repr__(self): return 'Good(%r)' % self.x class Bad(object): @property def x(self): raise RuntimeError() def __repr__(self): return 'Bad' ``` I want to sort instances of these classes according to their `x` property. Eg.: ``` >>> sorted([Good(5), Good(3), Good(7)], key=lambda obj: obj.x) [Good(3), Good(5), Good(7)] ``` Now, when there is a `Bad` in my list, the sorting fails: ``` >>> sorted([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ... RuntimeError ``` I am looking for a magical function `func` that sorts a list according to a key function, but simply ignores elements for which the key function raised an error: ``` >>> func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) [Good(3), Good(5)] ``` What is the most Pythonic way of achieving this?
2013/11/19
[ "https://Stackoverflow.com/questions/20078739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839209/" ]
Every sorting algorithm I know doesn't throw out some values because they're outdated or something. The task of sorting algorithm is to **sort** the list, and sort it fast, everything else is extraneous, specific task. So, I would write this magical function myself. It would do the sorting in two steps: first it would filter the list, leaving only `Good` values, and then sort the resulting list.
Since the result of the key function can change over time, and most sorting implementations probably assume a deterministic key function, it's probably best to only execute the key function once per object, to ensure a well-ordered and crash-free final list. ``` def func(seq, **kargs): key = kargs["key"] stored_values = {} for item in seq: try: value = key(item) stored_values[item] = value except RuntimeError: pass return sorted(stored_values.iterkeys(), key=lambda item: stored_values[item]) print func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ``` Result: ``` [Good(3), Good(5)] ```
20,078,739
I have a list of objects that I need to sort according to a [key function](https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions "Key functions"). The problem is that some of the elements in my list can go "out-of-date" while the list is being sorted. When the key function is called on such an expired item, it fails with an exception. Ideally, what I would like is a way of sorting my list with a key function such that when an error occurs upon calling the key function on an element, this element is excluded from the sort result. My problem can be reconstructed using the following example: Suppose I have two classes, `Good` and `Bad`: ``` class Good(object): def __init__(self, x): self.x = x def __repr__(self): return 'Good(%r)' % self.x class Bad(object): @property def x(self): raise RuntimeError() def __repr__(self): return 'Bad' ``` I want to sort instances of these classes according to their `x` property. Eg.: ``` >>> sorted([Good(5), Good(3), Good(7)], key=lambda obj: obj.x) [Good(3), Good(5), Good(7)] ``` Now, when there is a `Bad` in my list, the sorting fails: ``` >>> sorted([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ... RuntimeError ``` I am looking for a magical function `func` that sorts a list according to a key function, but simply ignores elements for which the key function raised an error: ``` >>> func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) [Good(3), Good(5)] ``` What is the most Pythonic way of achieving this?
2013/11/19
[ "https://Stackoverflow.com/questions/20078739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839209/" ]
Every sorting algorithm I know doesn't throw out some values because they're outdated or something. The task of sorting algorithm is to **sort** the list, and sort it fast, everything else is extraneous, specific task. So, I would write this magical function myself. It would do the sorting in two steps: first it would filter the list, leaving only `Good` values, and then sort the resulting list.
If the list items can go from Good to Bad while sorting, then there is nothing you can do. The `key`s are evaluated only once before sorting, so any change in the key will be invisible to the sort function: ``` >>> from random import randrange >>> values = [randrange(100) for i in range(10)] >>> values [54, 72, 91, 73, 55, 68, 21, 25, 18, 95] >>> def k(x): ... print x ... return x ... >>> values.sort(key=k) 54 72 91 73 55 68 21 25 18 95 ``` (If the key were evaluated many times during the sort, you would see the numbers printed many times).
20,078,739
I have a list of objects that I need to sort according to a [key function](https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions "Key functions"). The problem is that some of the elements in my list can go "out-of-date" while the list is being sorted. When the key function is called on such an expired item, it fails with an exception. Ideally, what I would like is a way of sorting my list with a key function such that when an error occurs upon calling the key function on an element, this element is excluded from the sort result. My problem can be reconstructed using the following example: Suppose I have two classes, `Good` and `Bad`: ``` class Good(object): def __init__(self, x): self.x = x def __repr__(self): return 'Good(%r)' % self.x class Bad(object): @property def x(self): raise RuntimeError() def __repr__(self): return 'Bad' ``` I want to sort instances of these classes according to their `x` property. Eg.: ``` >>> sorted([Good(5), Good(3), Good(7)], key=lambda obj: obj.x) [Good(3), Good(5), Good(7)] ``` Now, when there is a `Bad` in my list, the sorting fails: ``` >>> sorted([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ... RuntimeError ``` I am looking for a magical function `func` that sorts a list according to a key function, but simply ignores elements for which the key function raised an error: ``` >>> func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) [Good(3), Good(5)] ``` What is the most Pythonic way of achieving this?
2013/11/19
[ "https://Stackoverflow.com/questions/20078739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839209/" ]
I did this once with a mergesort. Mergesort makes it relatively simple to eliminate no-longer-useful values. The project I did it in is at <http://stromberg.dnsalias.org/~dstromberg/equivalence-classes.html#python-3e> . Feel free to raid it for ideas, or lift code out of it; it's Free as in speech (GPLv2 or later, at your option). The sort in that code should almost do what you want, except it'll sort a list with duplicates to a list of lists, where each sublist has equal values. That part may or may not be useful to you. I've got a more straightforward mergesort (it doesn't do the duplicate buckets thing, but it doesn't deal with dropping no-longer-good values either) at <http://stromberg.dnsalias.org/svn/sorts/compare/trunk/> . The file is .m4, but don't let that fool you - it's really pure python or cython autogenerated from the same .m4 file.
Since the result of the key function can change over time, and most sorting implementations probably assume a deterministic key function, it's probably best to only execute the key function once per object, to ensure a well-ordered and crash-free final list. ``` def func(seq, **kargs): key = kargs["key"] stored_values = {} for item in seq: try: value = key(item) stored_values[item] = value except RuntimeError: pass return sorted(stored_values.iterkeys(), key=lambda item: stored_values[item]) print func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ``` Result: ``` [Good(3), Good(5)] ```
20,078,739
I have a list of objects that I need to sort according to a [key function](https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions "Key functions"). The problem is that some of the elements in my list can go "out-of-date" while the list is being sorted. When the key function is called on such an expired item, it fails with an exception. Ideally, what I would like is a way of sorting my list with a key function such that when an error occurs upon calling the key function on an element, this element is excluded from the sort result. My problem can be reconstructed using the following example: Suppose I have two classes, `Good` and `Bad`: ``` class Good(object): def __init__(self, x): self.x = x def __repr__(self): return 'Good(%r)' % self.x class Bad(object): @property def x(self): raise RuntimeError() def __repr__(self): return 'Bad' ``` I want to sort instances of these classes according to their `x` property. Eg.: ``` >>> sorted([Good(5), Good(3), Good(7)], key=lambda obj: obj.x) [Good(3), Good(5), Good(7)] ``` Now, when there is a `Bad` in my list, the sorting fails: ``` >>> sorted([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ... RuntimeError ``` I am looking for a magical function `func` that sorts a list according to a key function, but simply ignores elements for which the key function raised an error: ``` >>> func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) [Good(3), Good(5)] ``` What is the most Pythonic way of achieving this?
2013/11/19
[ "https://Stackoverflow.com/questions/20078739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839209/" ]
I did this once with a mergesort. Mergesort makes it relatively simple to eliminate no-longer-useful values. The project I did it in is at <http://stromberg.dnsalias.org/~dstromberg/equivalence-classes.html#python-3e> . Feel free to raid it for ideas, or lift code out of it; it's Free as in speech (GPLv2 or later, at your option). The sort in that code should almost do what you want, except it'll sort a list with duplicates to a list of lists, where each sublist has equal values. That part may or may not be useful to you. I've got a more straightforward mergesort (it doesn't do the duplicate buckets thing, but it doesn't deal with dropping no-longer-good values either) at <http://stromberg.dnsalias.org/svn/sorts/compare/trunk/> . The file is .m4, but don't let that fool you - it's really pure python or cython autogenerated from the same .m4 file.
If the list items can go from Good to Bad while sorting, then there is nothing you can do. The `key`s are evaluated only once before sorting, so any change in the key will be invisible to the sort function: ``` >>> from random import randrange >>> values = [randrange(100) for i in range(10)] >>> values [54, 72, 91, 73, 55, 68, 21, 25, 18, 95] >>> def k(x): ... print x ... return x ... >>> values.sort(key=k) 54 72 91 73 55 68 21 25 18 95 ``` (If the key were evaluated many times during the sort, you would see the numbers printed many times).
20,078,739
I have a list of objects that I need to sort according to a [key function](https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions "Key functions"). The problem is that some of the elements in my list can go "out-of-date" while the list is being sorted. When the key function is called on such an expired item, it fails with an exception. Ideally, what I would like is a way of sorting my list with a key function such that when an error occurs upon calling the key function on an element, this element is excluded from the sort result. My problem can be reconstructed using the following example: Suppose I have two classes, `Good` and `Bad`: ``` class Good(object): def __init__(self, x): self.x = x def __repr__(self): return 'Good(%r)' % self.x class Bad(object): @property def x(self): raise RuntimeError() def __repr__(self): return 'Bad' ``` I want to sort instances of these classes according to their `x` property. Eg.: ``` >>> sorted([Good(5), Good(3), Good(7)], key=lambda obj: obj.x) [Good(3), Good(5), Good(7)] ``` Now, when there is a `Bad` in my list, the sorting fails: ``` >>> sorted([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ... RuntimeError ``` I am looking for a magical function `func` that sorts a list according to a key function, but simply ignores elements for which the key function raised an error: ``` >>> func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) [Good(3), Good(5)] ``` What is the most Pythonic way of achieving this?
2013/11/19
[ "https://Stackoverflow.com/questions/20078739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1839209/" ]
Since the result of the key function can change over time, and most sorting implementations probably assume a deterministic key function, it's probably best to only execute the key function once per object, to ensure a well-ordered and crash-free final list. ``` def func(seq, **kargs): key = kargs["key"] stored_values = {} for item in seq: try: value = key(item) stored_values[item] = value except RuntimeError: pass return sorted(stored_values.iterkeys(), key=lambda item: stored_values[item]) print func([Good(5), Good(3), Bad()], key=lambda obj: obj.x) ``` Result: ``` [Good(3), Good(5)] ```
If the list items can go from Good to Bad while sorting, then there is nothing you can do. The `key`s are evaluated only once before sorting, so any change in the key will be invisible to the sort function: ``` >>> from random import randrange >>> values = [randrange(100) for i in range(10)] >>> values [54, 72, 91, 73, 55, 68, 21, 25, 18, 95] >>> def k(x): ... print x ... return x ... >>> values.sort(key=k) 54 72 91 73 55 68 21 25 18 95 ``` (If the key were evaluated many times during the sort, you would see the numbers printed many times).
14,104,128
I'm trying to define "variables" in an openoffice document, and I must be doing something wrong because when I try to display the value of the variable using a field, I only get an empty string. Here's the code I'm using (using the Python UNO bridge). The interesting bit is the second function. ```python import time import subprocess import logging import os import sys import uno from com.sun.star.text.SetVariableType import STRING def get_uno_model(): # helper function to connect to OOo. Only interesting # if you want to reproduce the issue locally, # don't spend time on this one try: model = XSCRIPTCONTEXT.getDocument() except NameError: pass # we are not running in a macro # get the uno component context from the PyUNO runtime localContext = uno.getComponentContext() # create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", localContext ) # connect to the running office try: ctx = resolver.resolve("uno:socket,host=localhost,port=2002;" "urp;StarOffice.ComponentContext") except: cmd = ['soffice', '--writer', '-accept=socket,host=localhost,port=2002;urp;'] popen = subprocess.Popen(cmd) time.sleep(1) ctx = resolver.resolve("uno:socket,host=localhost,port=2002;" "urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager # get the central desktop object desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) # access the current writer document model = desktop.getCurrentComponent() return model def build_variable(model, name, value): # find or create a TextFieldMaster with the correct name master_prefix = u"com.sun.star.text.fieldmaster.SetExpression" variable_names = set([_name.split('.')[-1] for _name in model.TextFieldMasters.ElementNames if _name.startswith(master_prefix)]) master_name = u'%s.%s' % (master_prefix, name) if name not in variable_names: master = model.createInstance(master_prefix) master.Name = name else: master = model.TextFieldMasters.getByName(master_name) # create the SetExpression field field = model.createInstance(u'com.sun.star.text.textfield.SetExpression') field.attachTextFieldMaster(master) field.IsVisible = True field.IsInput = False field.SubType = STRING field.Content = value return field model = get_uno_model() # local function to connect to OpenOffice text = model.Text field = build_variable(model, u'Toto', 'nice variable') text.insertTextContent(text.getEnd(), field, False) ``` This code works somehow (unless I removed too much), but if I manually insert a field to display the value of Toto I don't get the 'nice variable' string that I expect, and the field which is inserted has no value
2012/12/31
[ "https://Stackoverflow.com/questions/14104128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281368/" ]
Use the updater property: <http://jsfiddle.net/ZUhFy/10/> ``` .typeahead({ source: namelist, updater: function(item) { $('#log').append(item + '<br>'); return item; } }); ``` > > updater returns selected item The method used to return selected item. > Accepts a single argument, the item and has the scope of the typeahead > instance. <http://twitter.github.com/bootstrap/javascript.html#typeahead> > > >
try ``` $('#findname').on('keyup', function() {...}); ```
14,104,128
I'm trying to define "variables" in an openoffice document, and I must be doing something wrong because when I try to display the value of the variable using a field, I only get an empty string. Here's the code I'm using (using the Python UNO bridge). The interesting bit is the second function. ```python import time import subprocess import logging import os import sys import uno from com.sun.star.text.SetVariableType import STRING def get_uno_model(): # helper function to connect to OOo. Only interesting # if you want to reproduce the issue locally, # don't spend time on this one try: model = XSCRIPTCONTEXT.getDocument() except NameError: pass # we are not running in a macro # get the uno component context from the PyUNO runtime localContext = uno.getComponentContext() # create the UnoUrlResolver resolver = localContext.ServiceManager.createInstanceWithContext( "com.sun.star.bridge.UnoUrlResolver", localContext ) # connect to the running office try: ctx = resolver.resolve("uno:socket,host=localhost,port=2002;" "urp;StarOffice.ComponentContext") except: cmd = ['soffice', '--writer', '-accept=socket,host=localhost,port=2002;urp;'] popen = subprocess.Popen(cmd) time.sleep(1) ctx = resolver.resolve("uno:socket,host=localhost,port=2002;" "urp;StarOffice.ComponentContext") smgr = ctx.ServiceManager # get the central desktop object desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx) # access the current writer document model = desktop.getCurrentComponent() return model def build_variable(model, name, value): # find or create a TextFieldMaster with the correct name master_prefix = u"com.sun.star.text.fieldmaster.SetExpression" variable_names = set([_name.split('.')[-1] for _name in model.TextFieldMasters.ElementNames if _name.startswith(master_prefix)]) master_name = u'%s.%s' % (master_prefix, name) if name not in variable_names: master = model.createInstance(master_prefix) master.Name = name else: master = model.TextFieldMasters.getByName(master_name) # create the SetExpression field field = model.createInstance(u'com.sun.star.text.textfield.SetExpression') field.attachTextFieldMaster(master) field.IsVisible = True field.IsInput = False field.SubType = STRING field.Content = value return field model = get_uno_model() # local function to connect to OpenOffice text = model.Text field = build_variable(model, u'Toto', 'nice variable') text.insertTextContent(text.getEnd(), field, False) ``` This code works somehow (unless I removed too much), but if I manually insert a field to display the value of Toto I don't get the 'nice variable' string that I expect, and the field which is inserted has no value
2012/12/31
[ "https://Stackoverflow.com/questions/14104128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/281368/" ]
Use the updater property: <http://jsfiddle.net/ZUhFy/10/> ``` .typeahead({ source: namelist, updater: function(item) { $('#log').append(item + '<br>'); return item; } }); ``` > > updater returns selected item The method used to return selected item. > Accepts a single argument, the item and has the scope of the typeahead > instance. <http://twitter.github.com/bootstrap/javascript.html#typeahead> > > >
### Try using the `keyup` ``` .on('keyup', function(){...}) ```
69,503,139
My path is all messed up, javac and python commands not found, I even uninstalled and reinstalled java. I would throw in random stuff from the internet into my terminal whenever my code wouldn't work and have subsequently ruined my path, I've even added stuff to my bash\_profile and I don't know how to reset it or fix it. very frustrated. sorry I'm a noob echo $PATH gives this: ``` Khalids-MacBook-Air:~ khalidhamid$ echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ``` ~/.bash\_profile gives this: ``` Khalids-MacBook-Air:~ khalidhamid$ ~/.bash_profile -bash: /Users/khalidhamid/.bash_profile: Permission denied ``` javac Student.java gives this: ``` Khalids-MacBook-Air:java khalidhamid$ javac Student.java javac: file not found: Student.java Usage: javac <options> <source files> use -help for a list of possible options ```
2021/10/09
[ "https://Stackoverflow.com/questions/69503139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17110677/" ]
In SQL Server Management Studio you can remove the shortcut CTRL+E to execute a query. Go to Tools > Options in the menu, then go to Environment > Keyboard > Keyboard in the tree on the left. Then select `Query.Execute` in the right table. Select the shortcut `CTRL+E (SQL Query Editor)` then click Remove which removes the shortcut. You will then no longer be able to execute the query when clicking CTRL+E. [![enter image description here](https://i.stack.imgur.com/oia8j.png)](https://i.stack.imgur.com/oia8j.png)
To prevent executing an entire script file from start to end, and only allow running selected snippets, this would work: ``` WHILE 1=1 PRINT 'NOT ALLOWED, press the STOP button' PRINT 'After WHILE, will not show unless executed manually' GO PRINT 'After GO, will not show unless executed manually' ``` Because the server goes into *very busy loop*, it may not immediately stop when you click the STOP button, but it will stop in the end. For sake of completeness, here is the **STOP** button: > > [![enter image description here](https://i.stack.imgur.com/w6VPv.png)](https://i.stack.imgur.com/w6VPv.png) > > >
69,503,139
My path is all messed up, javac and python commands not found, I even uninstalled and reinstalled java. I would throw in random stuff from the internet into my terminal whenever my code wouldn't work and have subsequently ruined my path, I've even added stuff to my bash\_profile and I don't know how to reset it or fix it. very frustrated. sorry I'm a noob echo $PATH gives this: ``` Khalids-MacBook-Air:~ khalidhamid$ echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ``` ~/.bash\_profile gives this: ``` Khalids-MacBook-Air:~ khalidhamid$ ~/.bash_profile -bash: /Users/khalidhamid/.bash_profile: Permission denied ``` javac Student.java gives this: ``` Khalids-MacBook-Air:java khalidhamid$ javac Student.java javac: file not found: Student.java Usage: javac <options> <source files> use -help for a list of possible options ```
2021/10/09
[ "https://Stackoverflow.com/questions/69503139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17110677/" ]
Add `set noexec on;` at the top of your script. That will prevent running *any* statements in the file.
In SQL Server Management Studio you can remove the shortcut CTRL+E to execute a query. Go to Tools > Options in the menu, then go to Environment > Keyboard > Keyboard in the tree on the left. Then select `Query.Execute` in the right table. Select the shortcut `CTRL+E (SQL Query Editor)` then click Remove which removes the shortcut. You will then no longer be able to execute the query when clicking CTRL+E. [![enter image description here](https://i.stack.imgur.com/oia8j.png)](https://i.stack.imgur.com/oia8j.png)
69,503,139
My path is all messed up, javac and python commands not found, I even uninstalled and reinstalled java. I would throw in random stuff from the internet into my terminal whenever my code wouldn't work and have subsequently ruined my path, I've even added stuff to my bash\_profile and I don't know how to reset it or fix it. very frustrated. sorry I'm a noob echo $PATH gives this: ``` Khalids-MacBook-Air:~ khalidhamid$ echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin ``` ~/.bash\_profile gives this: ``` Khalids-MacBook-Air:~ khalidhamid$ ~/.bash_profile -bash: /Users/khalidhamid/.bash_profile: Permission denied ``` javac Student.java gives this: ``` Khalids-MacBook-Air:java khalidhamid$ javac Student.java javac: file not found: Student.java Usage: javac <options> <source files> use -help for a list of possible options ```
2021/10/09
[ "https://Stackoverflow.com/questions/69503139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17110677/" ]
Add `set noexec on;` at the top of your script. That will prevent running *any* statements in the file.
To prevent executing an entire script file from start to end, and only allow running selected snippets, this would work: ``` WHILE 1=1 PRINT 'NOT ALLOWED, press the STOP button' PRINT 'After WHILE, will not show unless executed manually' GO PRINT 'After GO, will not show unless executed manually' ``` Because the server goes into *very busy loop*, it may not immediately stop when you click the STOP button, but it will stop in the end. For sake of completeness, here is the **STOP** button: > > [![enter image description here](https://i.stack.imgur.com/w6VPv.png)](https://i.stack.imgur.com/w6VPv.png) > > >
66,345,760
I'm trying to play a `.mp3` file. My code : ``` import os os.system("start C:\Users\User\Desktop\Wakeup.mp3") ``` But, it gives an error like this: ``` File "C:/Users/User/PycharmProjects/pythonProject/Test.py", line 2 os.system("start C:\Users\User\Desktop\Wakeup.mp3") ^ SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 8-9: truncated \UXXXXXXXX escape ``` with other variants for playing a sound, I'm getting the same error Thanks for attention
2021/02/24
[ "https://Stackoverflow.com/questions/66345760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15272617/" ]
You did not escape the backslash character. try this: ``` os.system("start C:\\Users\\User\\Desktop\\Wakeup.mp3") ``` **Option 2** Use forward slash instead: ``` os.system("start C:/Users/User/Desktop/Wakeup.mp3") ``` **Option 3** Use "raw" string: ``` os.system(r"start C:\Users\User\Desktop\Wakeup.mp3") ```
If you want to play sound. You can do something like this. ``` from playsound import playsound playsound("path/name.mp3") ``` Hope this helps ... :D
5,639,049
I found in the [documentation of pygraph](http://dl.dropbox.com/u/1823095/python-graph/docs/pygraph.classes.graph.graph-class.html) how to change the [attributes of the nodes and the edges](http://www.graphviz.org/doc/info/attrs.html), but I found no help on how to change the attributes of the graphs. I tried without luck: ``` gr = graph() gr.__setattr__('aspect',2) ``` What do you recommend? Thanks! [update] I also tried: ``` gr = graph() gr.__setattr__('rotate',90) gr.rotate = 90 gr.color = 'red' setattr(gr,'bgcolor','red') ``` [update 2] Example code from the website with the different ideas to change the attributes: ``` #!/usr/bin/env python # Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com> # License: MIT (see COPYING file) # Import graphviz import sys sys.path.append('..') sys.path.append('/usr/lib/graphviz/python/') sys.path.append('/usr/lib64/graphviz/python/') import gv # Import pygraph from pygraph.classes.graph import graph from pygraph.classes.digraph import digraph from pygraph.algorithms.searching import breadth_first_search from pygraph.readwrite.dot import write # Graph creation gr = graph() gr.__setattr__('rotate',90) gr.rotate = 90 gr.color = 'red' setattr(gr,'bgcolor','red') # Add nodes and edges gr.add_nodes(["Portugal","Spain","France","Germany","Belgium","Netherlands","Italy"]) gr.add_nodes(["Switzerland","Austria","Denmark","Poland","Czech Republic","Slovakia","Hungary"]) gr.add_nodes(["England","Ireland","Scotland","Wales"]) gr.add_edge(("Portugal", "Spain")) gr.add_edge(("Spain","France")) gr.add_edge(("France","Belgium")) gr.add_edge(("France","Germany")) gr.add_edge(("France","Italy")) gr.add_edge(("Belgium","Netherlands")) gr.add_edge(("Germany","Belgium")) gr.add_edge(("Germany","Netherlands")) gr.add_edge(("England","Wales")) gr.add_edge(("England","Scotland")) gr.add_edge(("Scotland","Wales")) gr.add_edge(("Switzerland","Austria")) gr.add_edge(("Switzerland","Germany")) gr.add_edge(("Switzerland","France")) gr.add_edge(("Switzerland","Italy")) gr.add_edge(("Austria","Germany")) gr.add_edge(("Austria","Italy")) gr.add_edge(("Austria","Czech Republic")) gr.add_edge(("Austria","Slovakia")) gr.add_edge(("Austria","Hungary")) gr.add_edge(("Denmark","Germany")) gr.add_edge(("Poland","Czech Republic")) gr.add_edge(("Poland","Slovakia")) gr.add_edge(("Poland","Germany")) gr.add_edge(("Czech Republic","Slovakia")) gr.add_edge(("Czech Republic","Germany")) gr.add_edge(("Slovakia","Hungary")) # Draw as PNG dot = write(gr) gvv = gv.readstring(dot) gv.layout(gvv,'dot') gv.render(gvv,'png','europe.png') ```
2011/04/12
[ "https://Stackoverflow.com/questions/5639049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380038/" ]
So, doing more research on my own, I found that [pygraphviz](http://networkx.lanl.gov/pygraphviz/index.html) is offering what I need. Here is the `pygraph` example using `pygraphviz` and accepting attributes. It is also shorter, as you don't have to specify the nodes if all of them are connected via edges. ``` #!/usr/bin/env python # Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com> # License: MIT (see COPYING file) # Import pygraphviz import pygraphviz as pgv # Graph creation and setting of attributes gr = pgv.AGraph(rotate='90',bgcolor='lightgray') # Add nodes and edges gr.add_edge(("Portugal", "Spain")) gr.add_edge(("Spain","France")) gr.add_edge(("France","Belgium")) gr.add_edge(("France","Germany")) gr.add_edge(("France","Italy")) gr.add_edge(("Belgium","Netherlands")) gr.add_edge(("Germany","Belgium")) gr.add_edge(("Germany","Netherlands")) gr.add_edge(("England","Wales")) gr.add_edge(("England","Scotland")) gr.add_edge(("Scotland","Wales")) gr.add_edge(("Switzerland","Austria")) gr.add_edge(("Switzerland","Germany")) gr.add_edge(("Switzerland","France")) gr.add_edge(("Switzerland","Italy")) gr.add_edge(("Austria","Germany")) gr.add_edge(("Austria","Italy")) gr.add_edge(("Austria","Czech Republic")) gr.add_edge(("Austria","Slovakia")) gr.add_edge(("Austria","Hungary")) gr.add_edge(("Denmark","Germany")) gr.add_edge(("Poland","Czech Republic")) gr.add_edge(("Poland","Slovakia")) gr.add_edge(("Poland","Germany")) gr.add_edge(("Czech Republic","Slovakia")) gr.add_edge(("Czech Republic","Germany")) gr.add_edge(("Slovakia","Hungary")) # Draw as PNG gr.layout(prog='dot') gr.draw('europe.png') ```
I don't know about pygraph, but I think the way you set attributes in python was: ``` setattr(object, attr, value) setattr(gr, 'aspect', 2) ``` I mean, you have tried gr.aspect = 2, right?
5,639,049
I found in the [documentation of pygraph](http://dl.dropbox.com/u/1823095/python-graph/docs/pygraph.classes.graph.graph-class.html) how to change the [attributes of the nodes and the edges](http://www.graphviz.org/doc/info/attrs.html), but I found no help on how to change the attributes of the graphs. I tried without luck: ``` gr = graph() gr.__setattr__('aspect',2) ``` What do you recommend? Thanks! [update] I also tried: ``` gr = graph() gr.__setattr__('rotate',90) gr.rotate = 90 gr.color = 'red' setattr(gr,'bgcolor','red') ``` [update 2] Example code from the website with the different ideas to change the attributes: ``` #!/usr/bin/env python # Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com> # License: MIT (see COPYING file) # Import graphviz import sys sys.path.append('..') sys.path.append('/usr/lib/graphviz/python/') sys.path.append('/usr/lib64/graphviz/python/') import gv # Import pygraph from pygraph.classes.graph import graph from pygraph.classes.digraph import digraph from pygraph.algorithms.searching import breadth_first_search from pygraph.readwrite.dot import write # Graph creation gr = graph() gr.__setattr__('rotate',90) gr.rotate = 90 gr.color = 'red' setattr(gr,'bgcolor','red') # Add nodes and edges gr.add_nodes(["Portugal","Spain","France","Germany","Belgium","Netherlands","Italy"]) gr.add_nodes(["Switzerland","Austria","Denmark","Poland","Czech Republic","Slovakia","Hungary"]) gr.add_nodes(["England","Ireland","Scotland","Wales"]) gr.add_edge(("Portugal", "Spain")) gr.add_edge(("Spain","France")) gr.add_edge(("France","Belgium")) gr.add_edge(("France","Germany")) gr.add_edge(("France","Italy")) gr.add_edge(("Belgium","Netherlands")) gr.add_edge(("Germany","Belgium")) gr.add_edge(("Germany","Netherlands")) gr.add_edge(("England","Wales")) gr.add_edge(("England","Scotland")) gr.add_edge(("Scotland","Wales")) gr.add_edge(("Switzerland","Austria")) gr.add_edge(("Switzerland","Germany")) gr.add_edge(("Switzerland","France")) gr.add_edge(("Switzerland","Italy")) gr.add_edge(("Austria","Germany")) gr.add_edge(("Austria","Italy")) gr.add_edge(("Austria","Czech Republic")) gr.add_edge(("Austria","Slovakia")) gr.add_edge(("Austria","Hungary")) gr.add_edge(("Denmark","Germany")) gr.add_edge(("Poland","Czech Republic")) gr.add_edge(("Poland","Slovakia")) gr.add_edge(("Poland","Germany")) gr.add_edge(("Czech Republic","Slovakia")) gr.add_edge(("Czech Republic","Germany")) gr.add_edge(("Slovakia","Hungary")) # Draw as PNG dot = write(gr) gvv = gv.readstring(dot) gv.layout(gvv,'dot') gv.render(gvv,'png','europe.png') ```
2011/04/12
[ "https://Stackoverflow.com/questions/5639049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380038/" ]
Apparently you can use `gv.setv()` to set attributes on a graph. ``` import gv g = gv.digraph('19261920') gv.setv(g, 'overlap', 'compress') ``` I found `gv.setv()` by examining the `gv.py` interface definition file at `/usr/include/graphviz/gv.i` Searching the interwebz for `"import gv" overlap setv` led me to [this old post](http://lists.research.att.com/pipermail/graphviz-interest/2007q4/003660.html) which demonstrates use of `gv.setv()`. And I found this [PDF gv\_python man page](http://www.graphviz.org/pdf/gv.3python.pdf) which contains more documentation on `setv`. That's quite a lot of sleuthing for such a simple thing, eh?
I don't know about pygraph, but I think the way you set attributes in python was: ``` setattr(object, attr, value) setattr(gr, 'aspect', 2) ``` I mean, you have tried gr.aspect = 2, right?
5,639,049
I found in the [documentation of pygraph](http://dl.dropbox.com/u/1823095/python-graph/docs/pygraph.classes.graph.graph-class.html) how to change the [attributes of the nodes and the edges](http://www.graphviz.org/doc/info/attrs.html), but I found no help on how to change the attributes of the graphs. I tried without luck: ``` gr = graph() gr.__setattr__('aspect',2) ``` What do you recommend? Thanks! [update] I also tried: ``` gr = graph() gr.__setattr__('rotate',90) gr.rotate = 90 gr.color = 'red' setattr(gr,'bgcolor','red') ``` [update 2] Example code from the website with the different ideas to change the attributes: ``` #!/usr/bin/env python # Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com> # License: MIT (see COPYING file) # Import graphviz import sys sys.path.append('..') sys.path.append('/usr/lib/graphviz/python/') sys.path.append('/usr/lib64/graphviz/python/') import gv # Import pygraph from pygraph.classes.graph import graph from pygraph.classes.digraph import digraph from pygraph.algorithms.searching import breadth_first_search from pygraph.readwrite.dot import write # Graph creation gr = graph() gr.__setattr__('rotate',90) gr.rotate = 90 gr.color = 'red' setattr(gr,'bgcolor','red') # Add nodes and edges gr.add_nodes(["Portugal","Spain","France","Germany","Belgium","Netherlands","Italy"]) gr.add_nodes(["Switzerland","Austria","Denmark","Poland","Czech Republic","Slovakia","Hungary"]) gr.add_nodes(["England","Ireland","Scotland","Wales"]) gr.add_edge(("Portugal", "Spain")) gr.add_edge(("Spain","France")) gr.add_edge(("France","Belgium")) gr.add_edge(("France","Germany")) gr.add_edge(("France","Italy")) gr.add_edge(("Belgium","Netherlands")) gr.add_edge(("Germany","Belgium")) gr.add_edge(("Germany","Netherlands")) gr.add_edge(("England","Wales")) gr.add_edge(("England","Scotland")) gr.add_edge(("Scotland","Wales")) gr.add_edge(("Switzerland","Austria")) gr.add_edge(("Switzerland","Germany")) gr.add_edge(("Switzerland","France")) gr.add_edge(("Switzerland","Italy")) gr.add_edge(("Austria","Germany")) gr.add_edge(("Austria","Italy")) gr.add_edge(("Austria","Czech Republic")) gr.add_edge(("Austria","Slovakia")) gr.add_edge(("Austria","Hungary")) gr.add_edge(("Denmark","Germany")) gr.add_edge(("Poland","Czech Republic")) gr.add_edge(("Poland","Slovakia")) gr.add_edge(("Poland","Germany")) gr.add_edge(("Czech Republic","Slovakia")) gr.add_edge(("Czech Republic","Germany")) gr.add_edge(("Slovakia","Hungary")) # Draw as PNG dot = write(gr) gvv = gv.readstring(dot) gv.layout(gvv,'dot') gv.render(gvv,'png','europe.png') ```
2011/04/12
[ "https://Stackoverflow.com/questions/5639049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380038/" ]
So, doing more research on my own, I found that [pygraphviz](http://networkx.lanl.gov/pygraphviz/index.html) is offering what I need. Here is the `pygraph` example using `pygraphviz` and accepting attributes. It is also shorter, as you don't have to specify the nodes if all of them are connected via edges. ``` #!/usr/bin/env python # Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com> # License: MIT (see COPYING file) # Import pygraphviz import pygraphviz as pgv # Graph creation and setting of attributes gr = pgv.AGraph(rotate='90',bgcolor='lightgray') # Add nodes and edges gr.add_edge(("Portugal", "Spain")) gr.add_edge(("Spain","France")) gr.add_edge(("France","Belgium")) gr.add_edge(("France","Germany")) gr.add_edge(("France","Italy")) gr.add_edge(("Belgium","Netherlands")) gr.add_edge(("Germany","Belgium")) gr.add_edge(("Germany","Netherlands")) gr.add_edge(("England","Wales")) gr.add_edge(("England","Scotland")) gr.add_edge(("Scotland","Wales")) gr.add_edge(("Switzerland","Austria")) gr.add_edge(("Switzerland","Germany")) gr.add_edge(("Switzerland","France")) gr.add_edge(("Switzerland","Italy")) gr.add_edge(("Austria","Germany")) gr.add_edge(("Austria","Italy")) gr.add_edge(("Austria","Czech Republic")) gr.add_edge(("Austria","Slovakia")) gr.add_edge(("Austria","Hungary")) gr.add_edge(("Denmark","Germany")) gr.add_edge(("Poland","Czech Republic")) gr.add_edge(("Poland","Slovakia")) gr.add_edge(("Poland","Germany")) gr.add_edge(("Czech Republic","Slovakia")) gr.add_edge(("Czech Republic","Germany")) gr.add_edge(("Slovakia","Hungary")) # Draw as PNG gr.layout(prog='dot') gr.draw('europe.png') ```
Try the following ``` import pydot dot = write(gr) dotG = pydot.graph_from_dot_data(dot) params = { 'rotate': 10, 'color': 'red'} dotG.set_graph_defaults(**params) dot = dotG.to_string() ```
5,639,049
I found in the [documentation of pygraph](http://dl.dropbox.com/u/1823095/python-graph/docs/pygraph.classes.graph.graph-class.html) how to change the [attributes of the nodes and the edges](http://www.graphviz.org/doc/info/attrs.html), but I found no help on how to change the attributes of the graphs. I tried without luck: ``` gr = graph() gr.__setattr__('aspect',2) ``` What do you recommend? Thanks! [update] I also tried: ``` gr = graph() gr.__setattr__('rotate',90) gr.rotate = 90 gr.color = 'red' setattr(gr,'bgcolor','red') ``` [update 2] Example code from the website with the different ideas to change the attributes: ``` #!/usr/bin/env python # Copyright (c) 2007-2008 Pedro Matiello <pmatiello@gmail.com> # License: MIT (see COPYING file) # Import graphviz import sys sys.path.append('..') sys.path.append('/usr/lib/graphviz/python/') sys.path.append('/usr/lib64/graphviz/python/') import gv # Import pygraph from pygraph.classes.graph import graph from pygraph.classes.digraph import digraph from pygraph.algorithms.searching import breadth_first_search from pygraph.readwrite.dot import write # Graph creation gr = graph() gr.__setattr__('rotate',90) gr.rotate = 90 gr.color = 'red' setattr(gr,'bgcolor','red') # Add nodes and edges gr.add_nodes(["Portugal","Spain","France","Germany","Belgium","Netherlands","Italy"]) gr.add_nodes(["Switzerland","Austria","Denmark","Poland","Czech Republic","Slovakia","Hungary"]) gr.add_nodes(["England","Ireland","Scotland","Wales"]) gr.add_edge(("Portugal", "Spain")) gr.add_edge(("Spain","France")) gr.add_edge(("France","Belgium")) gr.add_edge(("France","Germany")) gr.add_edge(("France","Italy")) gr.add_edge(("Belgium","Netherlands")) gr.add_edge(("Germany","Belgium")) gr.add_edge(("Germany","Netherlands")) gr.add_edge(("England","Wales")) gr.add_edge(("England","Scotland")) gr.add_edge(("Scotland","Wales")) gr.add_edge(("Switzerland","Austria")) gr.add_edge(("Switzerland","Germany")) gr.add_edge(("Switzerland","France")) gr.add_edge(("Switzerland","Italy")) gr.add_edge(("Austria","Germany")) gr.add_edge(("Austria","Italy")) gr.add_edge(("Austria","Czech Republic")) gr.add_edge(("Austria","Slovakia")) gr.add_edge(("Austria","Hungary")) gr.add_edge(("Denmark","Germany")) gr.add_edge(("Poland","Czech Republic")) gr.add_edge(("Poland","Slovakia")) gr.add_edge(("Poland","Germany")) gr.add_edge(("Czech Republic","Slovakia")) gr.add_edge(("Czech Republic","Germany")) gr.add_edge(("Slovakia","Hungary")) # Draw as PNG dot = write(gr) gvv = gv.readstring(dot) gv.layout(gvv,'dot') gv.render(gvv,'png','europe.png') ```
2011/04/12
[ "https://Stackoverflow.com/questions/5639049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380038/" ]
Apparently you can use `gv.setv()` to set attributes on a graph. ``` import gv g = gv.digraph('19261920') gv.setv(g, 'overlap', 'compress') ``` I found `gv.setv()` by examining the `gv.py` interface definition file at `/usr/include/graphviz/gv.i` Searching the interwebz for `"import gv" overlap setv` led me to [this old post](http://lists.research.att.com/pipermail/graphviz-interest/2007q4/003660.html) which demonstrates use of `gv.setv()`. And I found this [PDF gv\_python man page](http://www.graphviz.org/pdf/gv.3python.pdf) which contains more documentation on `setv`. That's quite a lot of sleuthing for such a simple thing, eh?
Try the following ``` import pydot dot = write(gr) dotG = pydot.graph_from_dot_data(dot) params = { 'rotate': 10, 'color': 'red'} dotG.set_graph_defaults(**params) dot = dotG.to_string() ```
64,866,304
I'm trying to set up a new cygwin installation and install python through cygwin. I've done so, and the setup completed, but when I try to run `python3.8` I get a fatal python error: ```sh $ python3.8 Python path configuration: PYTHONHOME = 'C:\Users\cmhac\AppData\Local\Programs\Python\Python38' PYTHONPATH = 'C:\Users\cmhac\AppData\Local\Programs\Python\Python38' program name = 'python3.8' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3.8.exe' sys.base_prefix = 'C' sys.base_exec_prefix = '\\Users\\cmhac\\AppData\\Local\\Programs\\Python\\Python38' sys.executable = '/usr/bin/python3.8.exe' sys.prefix = 'C' sys.exec_prefix = '\\Users\\cmhac\\AppData\\Local\\Programs\\Python\\Python38' sys.path = [ 'C', '\\Users\\cmhac\\AppData\\Local\\Programs\\Python\\Python38', 'C/lib/python38.zip', 'C/lib/python3.8', '\\Users\\cmhac\\AppData\\Local\\Programs\\Python\\Python38/lib/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x0000000800000010 (most recent call first): <no Python frame> ``` How do I even begin fixing this? The python38.exe file is there, and everything seems fine. Never had this error with any other python installation.
2020/11/16
[ "https://Stackoverflow.com/questions/64866304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11831775/" ]
I saw this exact error: Fatal Python error: init\_fs\_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' If you set these two env variables to nil, the problem should disappear: set PYTHONHOME= set PYTHONPATH=
Go to your wsgi.py file under your project and do something similar to: ``` import os import sys from django.core.wsgi import get_wsgi_application sys.path.append('path/to/yourprojectenv/lib/python3.8/site-packages') ``` Restart your server and try again.
44,434,185
I am trying to create a python program that will take data from multiple excel sheets and I am kinda stuck at the moment: ``` import xlrd import xlwt workbook1 = xlrd.open_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx', on_demand = True) worksheet = workbook1.sheet_by_index('Sheet1') sheet.cell(5, 5).value ``` This is my code currently this produces a error ``` Traceback (most recent call last): File "H:\python things\Datapull2.py", line 4, in <module> worksheet = workbook1.sheet_by_index('Sheet1') File "C:\Users\gomcrai\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 432, in sheet_by_index return self._sheet_list[sheetx] or self.get_sheet(sheetx) TypeError: list indices must be integers or slices, not str ``` I just wanna take the information from the cell(s) I've marked and drop them into a newly created excel sheet. If anyone could help me please let me know. Side note: I know these things would probably be easier in VB but I am practicing python.
2017/06/08
[ "https://Stackoverflow.com/questions/44434185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8131036/" ]
The answer's well documented in Marshmallows [api reference](http://marshmallow.readthedocs.io/en/latest/api_reference.html#module-marshmallow.fields). I need to use `dump_to` : ``` class ApiSchema(Schema): class Meta: strict = True time = fields.Number(dump_to='_time') id = fields.String(dump_to='_id') ```
You can override the [`dump`](https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.Schema.dump) method to *prepend* underscores to selected fields before returning the serialised object: ``` class ApiSchema(Schema): class Meta: strict = True time = fields.Number() id = fields.String() def dump(self, *args, **kwargs): special = kwargs.pop('special', None) _partial = super(ApiSchema, self).dump(*args, **kwargs) if special is not None and all(f in _partial for f in special): for field in special: _partial['_{}'.format(field)] = _partial.pop(field) return _partial ``` --- ``` api_schema = ApiSchema(...) result = api_schema.dump(obj, special=('id', 'time')) ``` You can also use the [`post_dump`](http://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.decorators.post_dump) decorator on a separate custom method without having to override `dump`, but then, you may have to hardcode the fields to-be-modified as part of the class, which may be inflexible depending on your use case.
44,434,185
I am trying to create a python program that will take data from multiple excel sheets and I am kinda stuck at the moment: ``` import xlrd import xlwt workbook1 = xlrd.open_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx', on_demand = True) worksheet = workbook1.sheet_by_index('Sheet1') sheet.cell(5, 5).value ``` This is my code currently this produces a error ``` Traceback (most recent call last): File "H:\python things\Datapull2.py", line 4, in <module> worksheet = workbook1.sheet_by_index('Sheet1') File "C:\Users\gomcrai\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 432, in sheet_by_index return self._sheet_list[sheetx] or self.get_sheet(sheetx) TypeError: list indices must be integers or slices, not str ``` I just wanna take the information from the cell(s) I've marked and drop them into a newly created excel sheet. If anyone could help me please let me know. Side note: I know these things would probably be easier in VB but I am practicing python.
2017/06/08
[ "https://Stackoverflow.com/questions/44434185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8131036/" ]
<https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#specifying-attribute-names> Even though the docs are for version 2, this seems to still work as of 3.5.1. The stable version 3 docs will not have this example. ``` class ApiSchema(Schema): class Meta: strict = True _time = fields.Number(attribute="time") _id = fields.String(attribute="id") ```
You can override the [`dump`](https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.Schema.dump) method to *prepend* underscores to selected fields before returning the serialised object: ``` class ApiSchema(Schema): class Meta: strict = True time = fields.Number() id = fields.String() def dump(self, *args, **kwargs): special = kwargs.pop('special', None) _partial = super(ApiSchema, self).dump(*args, **kwargs) if special is not None and all(f in _partial for f in special): for field in special: _partial['_{}'.format(field)] = _partial.pop(field) return _partial ``` --- ``` api_schema = ApiSchema(...) result = api_schema.dump(obj, special=('id', 'time')) ``` You can also use the [`post_dump`](http://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.decorators.post_dump) decorator on a separate custom method without having to override `dump`, but then, you may have to hardcode the fields to-be-modified as part of the class, which may be inflexible depending on your use case.
44,434,185
I am trying to create a python program that will take data from multiple excel sheets and I am kinda stuck at the moment: ``` import xlrd import xlwt workbook1 = xlrd.open_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx', on_demand = True) worksheet = workbook1.sheet_by_index('Sheet1') sheet.cell(5, 5).value ``` This is my code currently this produces a error ``` Traceback (most recent call last): File "H:\python things\Datapull2.py", line 4, in <module> worksheet = workbook1.sheet_by_index('Sheet1') File "C:\Users\gomcrai\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 432, in sheet_by_index return self._sheet_list[sheetx] or self.get_sheet(sheetx) TypeError: list indices must be integers or slices, not str ``` I just wanna take the information from the cell(s) I've marked and drop them into a newly created excel sheet. If anyone could help me please let me know. Side note: I know these things would probably be easier in VB but I am practicing python.
2017/06/08
[ "https://Stackoverflow.com/questions/44434185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8131036/" ]
The accepted answer (using `attribute`) didn't work for me, possibly [because](https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.fields.Field): > > Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use data\_key instead. > > > However `data_key` worked nicely: ``` class ApiSchema(Schema): class Meta: strict = True _time = fields.Number(data_key="time") _id = fields.String(data_key="id") ```
You can override the [`dump`](https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.Schema.dump) method to *prepend* underscores to selected fields before returning the serialised object: ``` class ApiSchema(Schema): class Meta: strict = True time = fields.Number() id = fields.String() def dump(self, *args, **kwargs): special = kwargs.pop('special', None) _partial = super(ApiSchema, self).dump(*args, **kwargs) if special is not None and all(f in _partial for f in special): for field in special: _partial['_{}'.format(field)] = _partial.pop(field) return _partial ``` --- ``` api_schema = ApiSchema(...) result = api_schema.dump(obj, special=('id', 'time')) ``` You can also use the [`post_dump`](http://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.decorators.post_dump) decorator on a separate custom method without having to override `dump`, but then, you may have to hardcode the fields to-be-modified as part of the class, which may be inflexible depending on your use case.
44,434,185
I am trying to create a python program that will take data from multiple excel sheets and I am kinda stuck at the moment: ``` import xlrd import xlwt workbook1 = xlrd.open_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx', on_demand = True) worksheet = workbook1.sheet_by_index('Sheet1') sheet.cell(5, 5).value ``` This is my code currently this produces a error ``` Traceback (most recent call last): File "H:\python things\Datapull2.py", line 4, in <module> worksheet = workbook1.sheet_by_index('Sheet1') File "C:\Users\gomcrai\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 432, in sheet_by_index return self._sheet_list[sheetx] or self.get_sheet(sheetx) TypeError: list indices must be integers or slices, not str ``` I just wanna take the information from the cell(s) I've marked and drop them into a newly created excel sheet. If anyone could help me please let me know. Side note: I know these things would probably be easier in VB but I am practicing python.
2017/06/08
[ "https://Stackoverflow.com/questions/44434185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8131036/" ]
<https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#specifying-attribute-names> Even though the docs are for version 2, this seems to still work as of 3.5.1. The stable version 3 docs will not have this example. ``` class ApiSchema(Schema): class Meta: strict = True _time = fields.Number(attribute="time") _id = fields.String(attribute="id") ```
The answer's well documented in Marshmallows [api reference](http://marshmallow.readthedocs.io/en/latest/api_reference.html#module-marshmallow.fields). I need to use `dump_to` : ``` class ApiSchema(Schema): class Meta: strict = True time = fields.Number(dump_to='_time') id = fields.String(dump_to='_id') ```
44,434,185
I am trying to create a python program that will take data from multiple excel sheets and I am kinda stuck at the moment: ``` import xlrd import xlwt workbook1 = xlrd.open_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx', on_demand = True) worksheet = workbook1.sheet_by_index('Sheet1') sheet.cell(5, 5).value ``` This is my code currently this produces a error ``` Traceback (most recent call last): File "H:\python things\Datapull2.py", line 4, in <module> worksheet = workbook1.sheet_by_index('Sheet1') File "C:\Users\gomcrai\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 432, in sheet_by_index return self._sheet_list[sheetx] or self.get_sheet(sheetx) TypeError: list indices must be integers or slices, not str ``` I just wanna take the information from the cell(s) I've marked and drop them into a newly created excel sheet. If anyone could help me please let me know. Side note: I know these things would probably be easier in VB but I am practicing python.
2017/06/08
[ "https://Stackoverflow.com/questions/44434185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8131036/" ]
The accepted answer (using `attribute`) didn't work for me, possibly [because](https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.fields.Field): > > Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use data\_key instead. > > > However `data_key` worked nicely: ``` class ApiSchema(Schema): class Meta: strict = True _time = fields.Number(data_key="time") _id = fields.String(data_key="id") ```
The answer's well documented in Marshmallows [api reference](http://marshmallow.readthedocs.io/en/latest/api_reference.html#module-marshmallow.fields). I need to use `dump_to` : ``` class ApiSchema(Schema): class Meta: strict = True time = fields.Number(dump_to='_time') id = fields.String(dump_to='_id') ```
44,434,185
I am trying to create a python program that will take data from multiple excel sheets and I am kinda stuck at the moment: ``` import xlrd import xlwt workbook1 = xlrd.open_workbook('Z:\Public\Safety\SafetyDataPullProject\TestFile.xlsx', on_demand = True) worksheet = workbook1.sheet_by_index('Sheet1') sheet.cell(5, 5).value ``` This is my code currently this produces a error ``` Traceback (most recent call last): File "H:\python things\Datapull2.py", line 4, in <module> worksheet = workbook1.sheet_by_index('Sheet1') File "C:\Users\gomcrai\AppData\Local\Programs\Python\Python36-32\lib\site-packages\xlrd\book.py", line 432, in sheet_by_index return self._sheet_list[sheetx] or self.get_sheet(sheetx) TypeError: list indices must be integers or slices, not str ``` I just wanna take the information from the cell(s) I've marked and drop them into a newly created excel sheet. If anyone could help me please let me know. Side note: I know these things would probably be easier in VB but I am practicing python.
2017/06/08
[ "https://Stackoverflow.com/questions/44434185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8131036/" ]
<https://marshmallow.readthedocs.io/en/2.x-line/quickstart.html#specifying-attribute-names> Even though the docs are for version 2, this seems to still work as of 3.5.1. The stable version 3 docs will not have this example. ``` class ApiSchema(Schema): class Meta: strict = True _time = fields.Number(attribute="time") _id = fields.String(attribute="id") ```
The accepted answer (using `attribute`) didn't work for me, possibly [because](https://marshmallow.readthedocs.io/en/latest/api_reference.html#marshmallow.fields.Field): > > Note: This should only be used for very specific use cases such as outputting multiple fields for a single attribute. In most cases, you should use data\_key instead. > > > However `data_key` worked nicely: ``` class ApiSchema(Schema): class Meta: strict = True _time = fields.Number(data_key="time") _id = fields.String(data_key="id") ```
15,627,307
I am trying to figure out the best way to convert from epoch seconds (since NTP epoch 1900-01-01 00:00) to a datetime string (MM/DD/YY,hh:mm:ss) without any libraries/modules/external functions, as they are not available on an embedded device. My first thought was to look at the [Python datetime module source code](http://svn.python.org/projects/python/trunk/Modules/datetimemodule.c), however that was not very useful to me. My initial attempt in Python uses a conversion of days since 0001-01-01 to date using `getDateFromJulianDay` adapted to Python from [C++ source](http://qt.gitorious.org/qt/qt/blobs/4.7/src/corelib/tools/qdatetime.cpp#line132), combined with modulo operations to obtain time. It works, but is there a better way? ``` def getDateFromJulianDay(julianDay): # Gregorian calendar starting from October 15, 1582 # This algorithm is from: # Henry F. Fliegel and Thomas C. van Flandern. 1968. # Letters to the editor: # a machine algorithm for processing calendar dates. # Commun. ACM 11, 10 (October 1968), 657-. DOI=10.1145/364096.364097 # http://doi.acm.org/10.1145/364096.364097 ell = julianDay + 68569; n = (4 * ell) / 146097; ell = ell - (146097 * n + 3) / 4; i = (4000 * (ell + 1)) / 1461001; ell = ell - (1461 * i) / 4 + 31; j = (80 * ell) / 2447; d = ell - (2447 * j) / 80; ell = j / 11; m = j + 2 - (12 * ell); y = 100 * (n - 49) + i + ell; return y,m,d # NTP response (integer portion) for Monday, March 25, 2013 at 6:40:43 PM sec_since_1900 = 3573225643 # 2415021 is the number of days between 0001-01-01 and 1900-01-01, # the start of the NTP epoch (year,month,day) = getDateFromJulianDay(2415021 + sec_since_1900/60/60/24) seconds_into_day = sec_since_1900 % 86400 (hour, sec_past_hour) = divmod(seconds_into_day,3600) (min, sec) = divmod(sec_past_hour,60) print 'year:',year,'month:',month,'day:',day print 'hour:',hour,'min:',min,'sec:',sec ``` Why I'm doing this: I am getting the current time from an NTP server, and taking this time at face value for updating a hardware real time clock (RTC) that only accepts the date, time and time zone: MM/DD/YY,hh:mm:ss,±zz. I plan to implement true NTP capabilities at a later date. A discussion of time synchronization methods is best left elsewhere, such as [this question](https://stackoverflow.com/questions/5642946/small-footprint-clock-synchronization-without-ntp). Notes: * My embedded device is a Telit GC-864 cellular modem that runs Python 1.5.2+ and only has limited operators (mostly just C operators), no modules, and some of the expected built-in Python types. The exact capabilities are [here](http://www.telit.com/module/infopool/download.php?id=617), if you're interested. I write Python for this device as if I'm writing C code - not very Pythonic, I know. * I realize NTP is best used only for a time offset, however with limited options, I'm using NTP as an absolute time source (I could add the check for the NTP rollover in 2036 to enable another 136 years of operation). * The GC-864-V2 device with up-to-date firmware does have NTP capability, but the GC-864 I need to use is stuck on a previous release of firmware.
2013/03/26
[ "https://Stackoverflow.com/questions/15627307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2209295/" ]
The `getDateFromJulianDay` function originally proposed is too computationally intensive for effective use on an embedded device, containing many multiplication and division operations on large `long` variables or, as originally written in C++, [`longlong` variables](http://qt.gitorious.org/qt/qt/blobs/4.7/src/corelib/tools/qdatetime.cpp#line140). I think I hunted down an efficient epoch to date algorithm for an embedded device. After fruitless Googling, I found myself back on Stack Overflow, and found the question [Converting epoch time to “real” date/time](https://stackoverflow.com/questions/1692184/converting-epoch-time-to-real-date-time), asking about self-written epoch time to date implementation and provides a suitable algorithm. This [answer](https://stackoverflow.com/a/1692210/2209295) to the question references the [gmtime.c source code](http://www.raspberryginger.com/jbailey/minix/html/gmtime_8c-source.html), and provided the source in C I needed to write a Python conversion algorithm: ``` /* * gmtime - convert the calendar time into broken down time */ /* $Header: /opt/proj/minix/cvsroot/src/lib/ansi/gmtime.c,v 1.1.1.1 2005/04/21 14:56:05 beng Exp $ */ #include <time.h> #include <limits.h> #include "loc_time.h" struct tm * gmtime(register const time_t *timer) { static struct tm br_time; register struct tm *timep = &br_time; time_t time = *timer; register unsigned long dayclock, dayno; int year = EPOCH_YR; dayclock = (unsigned long)time % SECS_DAY; dayno = (unsigned long)time / SECS_DAY; timep->tm_sec = dayclock % 60; timep->tm_min = (dayclock % 3600) / 60; timep->tm_hour = dayclock / 3600; timep->tm_wday = (dayno + 4) % 7; /* day 0 was a thursday */ while (dayno >= YEARSIZE(year)) { dayno -= YEARSIZE(year); year++; } timep->tm_year = year - YEAR0; timep->tm_yday = dayno; timep->tm_mon = 0; while (dayno >= _ytab[LEAPYEAR(year)][timep->tm_mon]) { dayno -= _ytab[LEAPYEAR(year)][timep->tm_mon]; timep->tm_mon++; } timep->tm_mday = dayno + 1; timep->tm_isdst = 0; return timep; } ``` Additionally, the [analysis](https://stackoverflow.com/a/3136466/2209295) of the question [Why is gmtime implemented this way?](https://stackoverflow.com/questions/3136341/why-is-gmtime-implemented-this-way) helped affirm that the `gmtime` function is fairly efficient. Using the [raspberryginger.com minix Doxygen documentation site](http://www.raspberryginger.com/jbailey/minix/html/), I was able to find the C macros and constants that were included in [gmtime.c](http://www.raspberryginger.com/jbailey/minix/html/gmtime_8c-source.html) from [loc\_time.h](http://www.raspberryginger.com/jbailey/minix/html/loc__time_8h-source.html). The relevant code snippet: ``` #define YEAR0 1900 /* the first year */ #define EPOCH_YR 1970 /* EPOCH = Jan 1 1970 00:00:00 */ #define SECS_DAY (24L * 60L * 60L) #define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400))) #define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365) #define FIRSTSUNDAY(timp) (((timp)->tm_yday - (timp)->tm_wday + 420) % 7) #define FIRSTDAYOF(timp) (((timp)->tm_wday - (timp)->tm_yday + 420) % 7) #define TIME_MAX ULONG_MAX #define ABB_LEN 3 extern const int _ytab[2][10]; ``` And the `extern const int _ytab` was defined in [misc.c](http://www.raspberryginger.com/jbailey/minix/html/lib_2ansi_2misc_8c-source.html#l00082): ``` const int _ytab[2][12] = { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; ``` Some other things I found: * The [gmtime.c File Reference](http://www.raspberryginger.com/jbailey/minix/html/gmtime_8c.html) was very helpful for finding dependencies. * The `gmtime` function starts indexing the Month, Day of Week, and Day of Year at the number zero, (maximal ranges of 0-11, 0-6, 0-365, respectively), whereas the Day of Month starts at the number 1, (1-31), see the [IBM `gmtime()` reference](http://publib.boulder.ibm.com/infocenter/zvm/v6r1/index.jsp?topic=/com.ibm.zvm.v610.edclv/gmtime.htm). --- I re-wrote the `gmtime` function for Python 1.5.2+: ```py def is_leap_year(year): return ( not ((year) % 4) and ( ((year) % 100) or (not((year) % 400)) ) ) def year_size(year): if is_leap_year(year): return 366 else: return 365 def ntp_time_to_date(ntp_time): year = 1900 # EPOCH_YR for NTP ytab = [ [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ] (dayno,dayclock) = divmod(ntp_time, 86400L) dayno = int(dayno) # Calculate time of day from seconds on the day's clock. (hour, sec_past_hour) = divmod(dayclock,3600) hour = int(hour) (min, sec) = divmod(int(sec_past_hour),60) while (dayno >= year_size(year)): dayno = dayno - year_size(year) year = year + 1 month = 1 # NOTE: month range is (1-12) while (dayno >= ytab[is_leap_year(year)][month]): dayno = dayno - ytab[is_leap_year(year)][month] month = month + 1 day = dayno + 1 return (year, month, day, hour, min, sec) ``` Modifications I made re-factoring the C++ `gmtime` function to my Python function `ntp_time_to_date(ntp_time)`: * Changed epoch from UNIX epoch of 1970 to NTP epoch of 1900 ([the prime epoch for NTP](http://www.eecis.udel.edu/~mills/y2k.html#era)). * Slightly streamlined time of day calculation. + Comparing time of day calculation of `gmtime` to `ntp_time_to_date`: - Both `(dayclock % 3600) / 60` and `dayclock / 3600` occur behind the scenes in `divmod(dayclock,3600)` and `divmod(sec_past_hour,60)`. - Only real difference is that `divmod(sec_past_hour,60)` avoids modulo of `dayclock` (0-86399) by 60 via `dayclock % 60`, and instead does modulo of `sec_past_hour` (0-3599) by 60 within `divmod(sec_past_hour,60)`. * Removed variables and code I did not need, for example, day of week. * Changed indexing of Month to start at 1, so Month range is (1-12) instead of (0-11) * Type cast variables away from `long` as soon as values were less than 65535 to greatly decrease code execution time. + The requires long variables are: - `ntp_time`, seconds since 1900 (0-4294967295) - `dayclock`, seconds into day (0-86399) + The largest of the rest of the variables is the calculated year within the date. --- The Python `ntp_time_to_date` function (with its dependencies) runs successfully on the Telit GC-864 on an embedded version of Python 1.5.2+, as well as on Python 2.7.3, but of course use the datetime library if you can.
TL;DR ===== If you are using a Telit GC-864, the Python interpreter seemingly inserts some sort of delay in-between each line of code execution. For a Telit GC-864, the function in my question `getDateFromJulianDay(julianDay)` is faster than the function in my answer, `ntp_time_to_date(ntp_time)`. More Detail =========== The number of code *lines* dominates execution time on a GC-864 more than the *complexity* of the code - weird, I know. The function `getDateFromJulianDay(julianDay)` in my question has a handful of complex operations, maybe 15 lines of code. The function in my answer `ntp_time_to_date(ntp_time)` has simpler computation complexity, but the `while` loops cause 100+ lines of code execution: * One loop counts from 1900 to the current year * Another loop counts from month 1 to the current month Test Results ============ Timing test results running on an actual GC-864 (note: **not** a GC-864-V2) using the same NTP time input for each trial (each function outputs "3/25/2013 18:40"). Timing was performed using printf statement debugging, and a serial terminal on a computer would time stamp each line sent by the GC-864. `getDateFromJulianDay(julianDay)` Trials: * 0.3802 seconds * 0.3370 seconds * 0.3370 seconds * Average: 0.3514 seconds `ntp_time_to_date(ntp_time)` Trials: * 0.8899 seconds * 0.9072 seconds * 0.8986 seconds * Average: 0.8986 seconds The variability partially stems from the GC-864 cell modem servicing cellular network tasks periodically. For completeness, the optimization of typecasting the `long` variables to `int` as quickly as possible in `ntp_time_to_date(ntp_time)` has a fairly significant effect. Without this optimization: * 2.3155 seconds * 1.5034 seconds * 1.5293 seconds * 2.0995 seconds * 2.0909 seconds * Average: 1.9255 seconds Doing anything computationally involved on a Telit GC-864 running .pyo files in Python 1.5.2+ is not a great idea. Using the GC-864-V2, which has a built-in NTP capability is a possible solution for someone who comes across this issue. Moreover, newer machine-to-machine (M2M) aka internet of things (IoT) cell phone modems are much more capable. If you have a similar issue with the GC-864, **consider using a newer and more modern cell phone modem**.
46,367,625
I am trying to detect language of the string with langdetect package. But it does not work. ``` from langdetect import detect word_string = "Books are for reading" print(detect(word_string)) ``` If I use code above I get error `ImportError: cannot import name detect` When I replace detect with \* ``` from langdetect import * word_string = "Books are for reading" print(detect(word_string)) ``` I get error: `NameError: name 'detect' is not defined` So my question is how can I solve these problems ? **So the problem was that my langdetect package and python file was with the same name.... Thank you for your answers.**
2017/09/22
[ "https://Stackoverflow.com/questions/46367625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152972/" ]
Try installing it first by writing :-> `!pip install langdetect` on terminal and then `import langdetect`
You can not import it because it is probably not there. See if the name is correct. Seeing other questions here on SO I assume you mean detect\_langs.
46,367,625
I am trying to detect language of the string with langdetect package. But it does not work. ``` from langdetect import detect word_string = "Books are for reading" print(detect(word_string)) ``` If I use code above I get error `ImportError: cannot import name detect` When I replace detect with \* ``` from langdetect import * word_string = "Books are for reading" print(detect(word_string)) ``` I get error: `NameError: name 'detect' is not defined` So my question is how can I solve these problems ? **So the problem was that my langdetect package and python file was with the same name.... Thank you for your answers.**
2017/09/22
[ "https://Stackoverflow.com/questions/46367625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6152972/" ]
Try installing it first by writing :-> `!pip install langdetect` on terminal and then `import langdetect`
Your error indicates the Python interpreter couldn't find the `module` you are importing in it's `sys.path`. Add to your code ``` import os sys.path.append('absolute_path to your module.py file') ``` and try again. Another option is to add your **[PYTHONPATH](https://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH)** environment variable the folder containing your module. Try `import langdetect` after validating it's path is in your `sys.path` variable; if this commands succeeds it means you loaded the module successfully. Now you need to address the detect function as `langdetect.detect` because it resides in the `langdetect` namespace. If it doesn't find it - it's not there.
39,370,879
I have a dataframe df\_energy2 ``` df_energy2.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 29974 entries, 0 to 29973 Data columns (total 4 columns): TIMESTAMP 29974 non-null datetime64[ns] P_ACT_KW 29974 non-null int64 PERIODE_TARIF 29974 non-null object P_SOUSCR 29974 non-null int64 dtypes: datetime64[ns](1), int64(2), object(1) memory usage: 936.8+ KB ``` with this structure : ``` df_energy2.head() TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR 2016-01-01 00:00:00 116 HC 250 2016-01-01 00:10:00 121 HC 250 ``` Is there any python function which can extract hour from `TIMESTAMP`? Kind regards
2016/09/07
[ "https://Stackoverflow.com/questions/39370879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2278337/" ]
I think you need [`dt.hour`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.hour.html): ``` print (df.TIMESTAMP.dt.hour) 0 0 1 0 Name: TIMESTAMP, dtype: int64 df['hours'] = df.TIMESTAMP.dt.hour print (df) TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR hours 0 2016-01-01 00:00:00 116 HC 250 0 1 2016-01-01 00:10:00 121 HC 250 0 ```
Given your data: > > > ``` > df_energy2.head() > > TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR > 2016-01-01 00:00:00 116 HC 250 > 2016-01-01 00:10:00 121 HC 250 > > ``` > > You have timestamp as the index. For extracting hours from timestamp where you have it as the index of the dataframe: ``` hours = df_energy2.index.hour ``` --- **Edit**: Yes, jezrael you're right. Putting what he has stated: pandas dataframe has a property for this i.e. `dt` : ``` <dataframe>.<ts_column>.dt.hour ``` Example in your context - the column with date is `TIMESTAMP` ``` df.TIMESTAMP.dt.hour ``` --- A similar question - [Pandas, dataframe with a datetime64 column, querying by hour](https://stackoverflow.com/questions/21624217/pandas-dataframe-with-a-datetime64-column-querying-by-hour)
16,027,942
I've written a high level motor controller in Python, and have got to a point where I want to go a little lower level to get some speed, so I'm interested in coding those bits in C. I don't have much experience with C, but the math I'm working on is pretty straightforward, so I'm sure I can implement with a minimal amount of banging my head against the wall. What I'm not sure about is how best to invoke this compiled C program in order to pipe it's outputs back into my high-level python controller. I've used a little bit of ctypes, but only to pull some functions from a manufacfturer-supplied DLL...not sure if that is an appropriate path to go down in this case. Any thoughts?
2013/04/16
[ "https://Stackoverflow.com/questions/16027942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481457/" ]
You can take a look at this tutorial [here](http://csl.name/C-functions-from-Python/). Also, a more reliable example on the official python website, [here](http://docs.python.org/2/extending/extending.html#a-simple-example). For example, `sum.h` function ``` int sum(int a, int b) ``` A file named, `module.c`, ``` #include <Python.h> #include "sum.h" static PyObject* mod_sum(PyObject *self, PyObject *args) { int a; int b; int s; if (!PyArg_ParseTuple(args,"ii",&a,&b)) return NULL; s = sum(a,b); return Py_BuildValue("i",s); } static PyMethodDef ModMethods[] = { {"sum", mod_sum, METH_VARARGS, "Description.."}, {NULL,NULL,0,NULL} }; PyMODINIT_FUNC initmod(void) { PyObject *m; m = Py_InitModule("module",ModMethods); if (m == NULL) return; } ``` Python ``` import module s = module.sum(3,5) ```
Another option: try [numba](http://numba.pydata.org/). It gives you C-like speed for free: just import numba and @autojit your functions, for a wonderful speed increase. Won't work if you have complicated data types, but if you're looping and jumping around array indices, it might be just what you're looking for.
16,027,942
I've written a high level motor controller in Python, and have got to a point where I want to go a little lower level to get some speed, so I'm interested in coding those bits in C. I don't have much experience with C, but the math I'm working on is pretty straightforward, so I'm sure I can implement with a minimal amount of banging my head against the wall. What I'm not sure about is how best to invoke this compiled C program in order to pipe it's outputs back into my high-level python controller. I've used a little bit of ctypes, but only to pull some functions from a manufacfturer-supplied DLL...not sure if that is an appropriate path to go down in this case. Any thoughts?
2013/04/16
[ "https://Stackoverflow.com/questions/16027942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481457/" ]
You can take a look at this tutorial [here](http://csl.name/C-functions-from-Python/). Also, a more reliable example on the official python website, [here](http://docs.python.org/2/extending/extending.html#a-simple-example). For example, `sum.h` function ``` int sum(int a, int b) ``` A file named, `module.c`, ``` #include <Python.h> #include "sum.h" static PyObject* mod_sum(PyObject *self, PyObject *args) { int a; int b; int s; if (!PyArg_ParseTuple(args,"ii",&a,&b)) return NULL; s = sum(a,b); return Py_BuildValue("i",s); } static PyMethodDef ModMethods[] = { {"sum", mod_sum, METH_VARARGS, "Description.."}, {NULL,NULL,0,NULL} }; PyMODINIT_FUNC initmod(void) { PyObject *m; m = Py_InitModule("module",ModMethods); if (m == NULL) return; } ``` Python ``` import module s = module.sum(3,5) ```
you can use SWIG, it is very simple to use
16,027,942
I've written a high level motor controller in Python, and have got to a point where I want to go a little lower level to get some speed, so I'm interested in coding those bits in C. I don't have much experience with C, but the math I'm working on is pretty straightforward, so I'm sure I can implement with a minimal amount of banging my head against the wall. What I'm not sure about is how best to invoke this compiled C program in order to pipe it's outputs back into my high-level python controller. I've used a little bit of ctypes, but only to pull some functions from a manufacfturer-supplied DLL...not sure if that is an appropriate path to go down in this case. Any thoughts?
2013/04/16
[ "https://Stackoverflow.com/questions/16027942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481457/" ]
You can take a look at this tutorial [here](http://csl.name/C-functions-from-Python/). Also, a more reliable example on the official python website, [here](http://docs.python.org/2/extending/extending.html#a-simple-example). For example, `sum.h` function ``` int sum(int a, int b) ``` A file named, `module.c`, ``` #include <Python.h> #include "sum.h" static PyObject* mod_sum(PyObject *self, PyObject *args) { int a; int b; int s; if (!PyArg_ParseTuple(args,"ii",&a,&b)) return NULL; s = sum(a,b); return Py_BuildValue("i",s); } static PyMethodDef ModMethods[] = { {"sum", mod_sum, METH_VARARGS, "Description.."}, {NULL,NULL,0,NULL} }; PyMODINIT_FUNC initmod(void) { PyObject *m; m = Py_InitModule("module",ModMethods); if (m == NULL) return; } ``` Python ``` import module s = module.sum(3,5) ```
You can use Cython for setting the necessary c types and compile your python syntax code.
21,119,958
I am trying to negate the value returned by one function. Consider the code to be ``` def greater(a,b): return a>b check = negate(greater) assert check(8,9) ``` OR ``` def equal(a,b): return a==b check = negate(equal) assert check("python","java") ``` How should I define the ***NEGATE*** function???
2014/01/14
[ "https://Stackoverflow.com/questions/21119958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3181773/" ]
Like this: ``` def negate(func): def result(*args): return not func(*args) return result ``` This is a function which creates a function which returns the result of invoking the original function and `not`ing it's return value, and then returning that function.
Use the `not` operator in a decorator: ``` from functools import wraps def negate(func): @wraps(func) def wrapper(*args, **kw): return not func(*args, **kw) return wrapper ``` The above decorator returns a wrapper function that applies `not` to the return value of the wrapped function. The [`@functools.wraps()` decorator](http://docs.python.org/2/library/functools.html#functools.wraps) in the above example is optional but makes sure the wrapper gains the docstring and other introspectable attributes from the original function, making it behave more closely like the wrapped function. Demo: ``` >>> from functools import wraps >>> def negate(func): ... @wraps(func) ... def wrapper(*args, **kw): ... return not func(*args, **kw) ... return wrapper ... >>> def greater(a,b): ... return a>b ... >>> check = negate(greater) >>> check(8, 9) True ```
21,119,958
I am trying to negate the value returned by one function. Consider the code to be ``` def greater(a,b): return a>b check = negate(greater) assert check(8,9) ``` OR ``` def equal(a,b): return a==b check = negate(equal) assert check("python","java") ``` How should I define the ***NEGATE*** function???
2014/01/14
[ "https://Stackoverflow.com/questions/21119958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3181773/" ]
Use a function-style [decorator](http://docs.python.org/2/glossary.html#term-decorator): ``` def negate(func): def inner(*args, **kwargs): val = func(*args, **kwargs) return not val return inner ``` **Demo:** ``` >>> greater(10, 20) False >>> negate(greater)(10, 20) True ``` To preserve things like `docstring` and other attributes of the function being passed to `negate` you can use [`functools.wraps`](http://docs.python.org/2/library/functools.html#functools.wraps). ``` from functools import wraps def negate(func): @wraps(func) def inner(*args, **kwargs): val = func(*args, **kwargs) return not val return inner ```
Use the `not` operator in a decorator: ``` from functools import wraps def negate(func): @wraps(func) def wrapper(*args, **kw): return not func(*args, **kw) return wrapper ``` The above decorator returns a wrapper function that applies `not` to the return value of the wrapped function. The [`@functools.wraps()` decorator](http://docs.python.org/2/library/functools.html#functools.wraps) in the above example is optional but makes sure the wrapper gains the docstring and other introspectable attributes from the original function, making it behave more closely like the wrapped function. Demo: ``` >>> from functools import wraps >>> def negate(func): ... @wraps(func) ... def wrapper(*args, **kw): ... return not func(*args, **kw) ... return wrapper ... >>> def greater(a,b): ... return a>b ... >>> check = negate(greater) >>> check(8, 9) True ```
21,119,958
I am trying to negate the value returned by one function. Consider the code to be ``` def greater(a,b): return a>b check = negate(greater) assert check(8,9) ``` OR ``` def equal(a,b): return a==b check = negate(equal) assert check("python","java") ``` How should I define the ***NEGATE*** function???
2014/01/14
[ "https://Stackoverflow.com/questions/21119958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3181773/" ]
Like this: ``` def negate(func): def result(*args): return not func(*args) return result ``` This is a function which creates a function which returns the result of invoking the original function and `not`ing it's return value, and then returning that function.
Use a function-style [decorator](http://docs.python.org/2/glossary.html#term-decorator): ``` def negate(func): def inner(*args, **kwargs): val = func(*args, **kwargs) return not val return inner ``` **Demo:** ``` >>> greater(10, 20) False >>> negate(greater)(10, 20) True ``` To preserve things like `docstring` and other attributes of the function being passed to `negate` you can use [`functools.wraps`](http://docs.python.org/2/library/functools.html#functools.wraps). ``` from functools import wraps def negate(func): @wraps(func) def inner(*args, **kwargs): val = func(*args, **kwargs) return not val return inner ```
14,749,379
Because *programming* is one of my favorite hobbies I started a small project in python. I'm trying to make a nutritional calculator for daily routine, see the code below: ``` # Name: nutri.py # Author: pyn my_dict = {'chicken':(40, 50, 10), 'pork':(50, 30, 20) } foods = raw_input("Enter your food: ") #explode / split the user input foods_list = foods.split(',') #returns a list separated by comma print foods_list ``` What I want to do: 1. Get user input and store it in a variable 2. Search the dictionary based on user input and return the asociated values if the keys / foods exists 3. Sum these values in different nutritional chunks and return them, something like: You ate x protein, y carbs and z fat etc. Any ideas are welcome.
2013/02/07
[ "https://Stackoverflow.com/questions/14749379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2050432/" ]
You could use the sibling selector. As long as div's share the same parent, you can still affect them with hover [DEMO](http://jsfiddle.net/8LFWR/) Vital Code: ``` #gestaltung_cd:hover ~ #mainhexa1, #gestaltung_illu:hover ~ #mainhexa2, #gestaltung_klassisch:hover ~ #mainhexa3 { display: block; } ```
Here's an example of how to do the first one and you'd just do the same for the other two with the relevant IDs. ``` $("#gestaltung_cd").hover( function () { $("#mainhexa1").show(); }, function () { $("#mainhexa1").hide(); } ); ```
14,749,379
Because *programming* is one of my favorite hobbies I started a small project in python. I'm trying to make a nutritional calculator for daily routine, see the code below: ``` # Name: nutri.py # Author: pyn my_dict = {'chicken':(40, 50, 10), 'pork':(50, 30, 20) } foods = raw_input("Enter your food: ") #explode / split the user input foods_list = foods.split(',') #returns a list separated by comma print foods_list ``` What I want to do: 1. Get user input and store it in a variable 2. Search the dictionary based on user input and return the asociated values if the keys / foods exists 3. Sum these values in different nutritional chunks and return them, something like: You ate x protein, y carbs and z fat etc. Any ideas are welcome.
2013/02/07
[ "https://Stackoverflow.com/questions/14749379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2050432/" ]
using jQuerys hover function, like this: ``` $('#gestaltung_cd').hover(function() { $('#mainhexa1').toggle(); }); ``` (if you don't want to hide the div on blur, then change toggle() to show())
Just for the record ... You can do the effect you want only with CSS and HTML ( without javascript ), but you have to place your elements to follow each other and use `+` selector in CSS. Something like : HTML ``` <div id="gestaltung_cd"></div> <div id="mainhexa1"></div> <div id="gestaltung_illu"></div> <div id="mainhexa2"></div> <div id="gestaltung_klassisch"></div> <div id="mainhexa3"></div> ``` CSS ``` div#gestaltung_cd:hover + div#mainhexa1 { display:block; } div#gestaltung_illu:hover + div#mainhexa2 { display:block; } div#gestaltung_klassisch:hover + div#mainhexa3 { display:block; } ``` you can check out the demo <http://tinkerbin.com/KP17XUgq>
14,749,379
Because *programming* is one of my favorite hobbies I started a small project in python. I'm trying to make a nutritional calculator for daily routine, see the code below: ``` # Name: nutri.py # Author: pyn my_dict = {'chicken':(40, 50, 10), 'pork':(50, 30, 20) } foods = raw_input("Enter your food: ") #explode / split the user input foods_list = foods.split(',') #returns a list separated by comma print foods_list ``` What I want to do: 1. Get user input and store it in a variable 2. Search the dictionary based on user input and return the asociated values if the keys / foods exists 3. Sum these values in different nutritional chunks and return them, something like: You ate x protein, y carbs and z fat etc. Any ideas are welcome.
2013/02/07
[ "https://Stackoverflow.com/questions/14749379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2050432/" ]
You could use the sibling selector. As long as div's share the same parent, you can still affect them with hover [DEMO](http://jsfiddle.net/8LFWR/) Vital Code: ``` #gestaltung_cd:hover ~ #mainhexa1, #gestaltung_illu:hover ~ #mainhexa2, #gestaltung_klassisch:hover ~ #mainhexa3 { display: block; } ```
I'd suggest you add an attribute to the first three divs that specifies which div to show on hover: ``` <div id="gestaltung_cd" data-maindiv="mainhexa1"></div> <div id="gestaltung_illu" data-maindiv="mainhexa2"></div> <div id="gestaltung_klassisch" data-maindiv="mainhexa3"></div> ``` That way you can handle the show/hide on hover with a single use of the [`.hover()`](http://api.jquery.com/hover/) method: ``` $("div[data-maindiv]").hover(function() { $("#" + $(this).attr("data-maindiv") ).show(); }, function() { $("#" + $(this).attr("data-maindiv") ).hide(); }); ``` Demo: <http://jsfiddle.net/GFMQR/>
14,749,379
Because *programming* is one of my favorite hobbies I started a small project in python. I'm trying to make a nutritional calculator for daily routine, see the code below: ``` # Name: nutri.py # Author: pyn my_dict = {'chicken':(40, 50, 10), 'pork':(50, 30, 20) } foods = raw_input("Enter your food: ") #explode / split the user input foods_list = foods.split(',') #returns a list separated by comma print foods_list ``` What I want to do: 1. Get user input and store it in a variable 2. Search the dictionary based on user input and return the asociated values if the keys / foods exists 3. Sum these values in different nutritional chunks and return them, something like: You ate x protein, y carbs and z fat etc. Any ideas are welcome.
2013/02/07
[ "https://Stackoverflow.com/questions/14749379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2050432/" ]
Using jQuery's [hover](http://api.jquery.com/hover/) function : ``` var divs = { cd: 'mainhexa1', illu: 'mainhexa2', klassisch: 'mainhexa3' }; $('[id^=gestaltung]').hover(function(){ // selects all elements whose id starts with gestaltung $('#'+divs[this.id.slice('gestaltung_'.length)]).toggle(); }); ``` Note that it might be easier to have some relation between the opener and opening elements, like a class or another attribute (as in nnnnnn's answer).
If you wrap each block of divs in a container you can match them up by index, which will make the code work regardless of how many divs there are. Something like this: ``` <div class="gesaltung-container"> <div id="gestaltung_cd">gestaltung_cd</div> <div id="gestaltung_illu">gestaltung_illu</div> <div id="gestaltung_klassisch">gestaltung_klassisch</div> </div> <div class="mainhexa-container"> <div id="mainhexa1">mainhexa1</div> <div id="mainhexa2">mainhexa2</div> <div id="mainhexa3">mainhexa3</div> </div> ``` ```js $('.gesaltung-container div').hover( function () { $('.mainhexa-container div').eq($(this).index()).show(); }, function () { $('.mainhexa-container div').eq($(this).index()).hide(); } ); ``` [**Example fiddle**](http://jsfiddle.net/RoryMcCrossan/4tAZS/)
14,749,379
Because *programming* is one of my favorite hobbies I started a small project in python. I'm trying to make a nutritional calculator for daily routine, see the code below: ``` # Name: nutri.py # Author: pyn my_dict = {'chicken':(40, 50, 10), 'pork':(50, 30, 20) } foods = raw_input("Enter your food: ") #explode / split the user input foods_list = foods.split(',') #returns a list separated by comma print foods_list ``` What I want to do: 1. Get user input and store it in a variable 2. Search the dictionary based on user input and return the asociated values if the keys / foods exists 3. Sum these values in different nutritional chunks and return them, something like: You ate x protein, y carbs and z fat etc. Any ideas are welcome.
2013/02/07
[ "https://Stackoverflow.com/questions/14749379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2050432/" ]
You could use the sibling selector. As long as div's share the same parent, you can still affect them with hover [DEMO](http://jsfiddle.net/8LFWR/) Vital Code: ``` #gestaltung_cd:hover ~ #mainhexa1, #gestaltung_illu:hover ~ #mainhexa2, #gestaltung_klassisch:hover ~ #mainhexa3 { display: block; } ```
``` $("#gestaltung_cd").hover(function({ $("#mainhexa1").css({ "visibility": "visible" }); }, function() { //Your hover out function }); ```
14,749,379
Because *programming* is one of my favorite hobbies I started a small project in python. I'm trying to make a nutritional calculator for daily routine, see the code below: ``` # Name: nutri.py # Author: pyn my_dict = {'chicken':(40, 50, 10), 'pork':(50, 30, 20) } foods = raw_input("Enter your food: ") #explode / split the user input foods_list = foods.split(',') #returns a list separated by comma print foods_list ``` What I want to do: 1. Get user input and store it in a variable 2. Search the dictionary based on user input and return the asociated values if the keys / foods exists 3. Sum these values in different nutritional chunks and return them, something like: You ate x protein, y carbs and z fat etc. Any ideas are welcome.
2013/02/07
[ "https://Stackoverflow.com/questions/14749379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2050432/" ]
Using jQuery's [hover](http://api.jquery.com/hover/) function : ``` var divs = { cd: 'mainhexa1', illu: 'mainhexa2', klassisch: 'mainhexa3' }; $('[id^=gestaltung]').hover(function(){ // selects all elements whose id starts with gestaltung $('#'+divs[this.id.slice('gestaltung_'.length)]).toggle(); }); ``` Note that it might be easier to have some relation between the opener and opening elements, like a class or another attribute (as in nnnnnn's answer).
Here's an example of how to do the first one and you'd just do the same for the other two with the relevant IDs. ``` $("#gestaltung_cd").hover( function () { $("#mainhexa1").show(); }, function () { $("#mainhexa1").hide(); } ); ```
14,749,379
Because *programming* is one of my favorite hobbies I started a small project in python. I'm trying to make a nutritional calculator for daily routine, see the code below: ``` # Name: nutri.py # Author: pyn my_dict = {'chicken':(40, 50, 10), 'pork':(50, 30, 20) } foods = raw_input("Enter your food: ") #explode / split the user input foods_list = foods.split(',') #returns a list separated by comma print foods_list ``` What I want to do: 1. Get user input and store it in a variable 2. Search the dictionary based on user input and return the asociated values if the keys / foods exists 3. Sum these values in different nutritional chunks and return them, something like: You ate x protein, y carbs and z fat etc. Any ideas are welcome.
2013/02/07
[ "https://Stackoverflow.com/questions/14749379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2050432/" ]
using jQuerys hover function, like this: ``` $('#gestaltung_cd').hover(function() { $('#mainhexa1').toggle(); }); ``` (if you don't want to hide the div on blur, then change toggle() to show())
If you wrap each block of divs in a container you can match them up by index, which will make the code work regardless of how many divs there are. Something like this: ``` <div class="gesaltung-container"> <div id="gestaltung_cd">gestaltung_cd</div> <div id="gestaltung_illu">gestaltung_illu</div> <div id="gestaltung_klassisch">gestaltung_klassisch</div> </div> <div class="mainhexa-container"> <div id="mainhexa1">mainhexa1</div> <div id="mainhexa2">mainhexa2</div> <div id="mainhexa3">mainhexa3</div> </div> ``` ```js $('.gesaltung-container div').hover( function () { $('.mainhexa-container div').eq($(this).index()).show(); }, function () { $('.mainhexa-container div').eq($(this).index()).hide(); } ); ``` [**Example fiddle**](http://jsfiddle.net/RoryMcCrossan/4tAZS/)