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 |
|---|---|---|---|---|---|
13,455,143 | Having a class
```
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
```
Both methods (`Func1` and `Func2`) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address `z`.
The result of ... | 2012/11/19 | [
"https://Stackoverflow.com/questions/13455143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572616/"
] | I would say that the proper way to get access to the variable is simply:
```
a_instance.z #instance variable 'z'
A.z #class variable 'z'
```
No need for `Func1` and `Func2` here.
---
As a side note, if you *must* write `Func2`, it seems like a `classmethod` might be appropriate:
```
@classmethod
def Fu... | I would usually use `self.z`, because in case there are subclasses with different values for `z` it will choose the "right" one. The only reason not to do that is if you know you will always want the `A` version notwithstanding.
Accessing via self or via a classmethod (see mgilson's answer) also facilitates the creati... |
13,455,143 | Having a class
```
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
```
Both methods (`Func1` and `Func2`) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address `z`.
The result of ... | 2012/11/19 | [
"https://Stackoverflow.com/questions/13455143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572616/"
] | I would say that the proper way to get access to the variable is simply:
```
a_instance.z #instance variable 'z'
A.z #class variable 'z'
```
No need for `Func1` and `Func2` here.
---
As a side note, if you *must* write `Func2`, it seems like a `classmethod` might be appropriate:
```
@classmethod
def Fu... | If you don't care about value clobbering and things like that, you're fine with `self.z`. Otherwise, `A.z` will undoubtedly evaluate to the class variable. Beware, though, about what would happen if a subclass `B` redefines `z` but **not** `Func2`:
```
class B(A):
z = 7
b = B()
b.Func2() # Returns 0, not 7
```
... |
13,455,143 | Having a class
```
class A(object):
z = 0
def Func1(self):
return self.z
def Func2(self):
return A.z
```
Both methods (`Func1` and `Func2`) give the same result and are only included in this artificial example to illustrate the two possible methods of how to address `z`.
The result of ... | 2012/11/19 | [
"https://Stackoverflow.com/questions/13455143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572616/"
] | I would usually use `self.z`, because in case there are subclasses with different values for `z` it will choose the "right" one. The only reason not to do that is if you know you will always want the `A` version notwithstanding.
Accessing via self or via a classmethod (see mgilson's answer) also facilitates the creati... | If you don't care about value clobbering and things like that, you're fine with `self.z`. Otherwise, `A.z` will undoubtedly evaluate to the class variable. Beware, though, about what would happen if a subclass `B` redefines `z` but **not** `Func2`:
```
class B(A):
z = 7
b = B()
b.Func2() # Returns 0, not 7
```
... |
64,996,663 | I was testing this function on some sample text file to make sure it is working as expected.
```
#include <stdio.h>
#include <time.h>
#define BUF 100
int main(){
FILE *fp = fopen("my_huge_file.txt","r");
char str[BUF];
int count=0;
while( (fgets(str, BUF, fp)) != NULL ){
... | 2020/11/25 | [
"https://Stackoverflow.com/questions/64996663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549160/"
] | This issue is because your pipeline agent does not have Java 11 pre-installed in it.
You have two options to solve this issue.
**Option 1:** Change the pipeline agent to an agent which does have Java 11 pre-installed.
If you are using Microsoft-hosted pipeline agents, you can use this link to check which all agents ... | Perhaps the JDK running in your pipeline is, say, version 8. In that case, the Java compiler that is executed doesn't understand what version 11 means. Perhaps your local environment is using Java 11 where this problem would therefore not happen. |
64,996,663 | I was testing this function on some sample text file to make sure it is working as expected.
```
#include <stdio.h>
#include <time.h>
#define BUF 100
int main(){
FILE *fp = fopen("my_huge_file.txt","r");
char str[BUF];
int count=0;
while( (fgets(str, BUF, fp)) != NULL ){
... | 2020/11/25 | [
"https://Stackoverflow.com/questions/64996663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549160/"
] | This issue is because your pipeline agent does not have Java 11 pre-installed in it.
You have two options to solve this issue.
**Option 1:** Change the pipeline agent to an agent which does have Java 11 pre-installed.
If you are using Microsoft-hosted pipeline agents, you can use this link to check which all agents ... | I had the same problem. You need to specify the jdk version in the pipeline .yaml-file:
>
> To build with Maven, add the following snippet to your
> azure-pipelines.yml file. Change values, such as the path to your
> pom.xml file, to match your project configuration. See the Maven task
> for more about these options.... |
64,996,663 | I was testing this function on some sample text file to make sure it is working as expected.
```
#include <stdio.h>
#include <time.h>
#define BUF 100
int main(){
FILE *fp = fopen("my_huge_file.txt","r");
char str[BUF];
int count=0;
while( (fgets(str, BUF, fp)) != NULL ){
... | 2020/11/25 | [
"https://Stackoverflow.com/questions/64996663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12549160/"
] | This issue is because your pipeline agent does not have Java 11 pre-installed in it.
You have two options to solve this issue.
**Option 1:** Change the pipeline agent to an agent which does have Java 11 pre-installed.
If you are using Microsoft-hosted pipeline agents, you can use this link to check which all agents ... | I solved this problem by adding a new file **system.properties** and the content added to the file is **java.runtime.version=11**.
```
java.runtime.version=11
``` |
58,167,766 | I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*? | 2019/09/30 | [
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] | It just means when the match is “” or an empty string, that it is included in the list of results. | If a subject is an empty string then fullmatch() evaluates to True for any regex that can find a ... The overall regex match is not included in the tuple, unless you place the entire ... appear in the regular expression, as raw strings do not offer a means to escape it. |
58,167,766 | I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*? | 2019/09/30 | [
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] | This happen when you use groups that matches empty string , example:
```
print(re.findall(r'(\w)(\d?)(\w)', "bc"))
```
OUPUT:
```
[('b', '', 'c')]
```
Here group `(\d?)` matches `''` and is included in the result. | It just means when the match is “” or an empty string, that it is included in the list of results. |
58,167,766 | I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*? | 2019/09/30 | [
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] | This happen when you use groups that matches empty string , example:
```
print(re.findall(r'(\w)(\d?)(\w)', "bc"))
```
OUPUT:
```
[('b', '', 'c')]
```
Here group `(\d?)` matches `''` and is included in the result. | If a subject is an empty string then fullmatch() evaluates to True for any regex that can find a ... The overall regex match is not included in the tuple, unless you place the entire ... appear in the regular expression, as raw strings do not offer a means to escape it. |
58,167,766 | I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*? | 2019/09/30 | [
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] | Zero-length matches, or empty matches.
A Regular Expression is made of boundaries definitions, or anchors, for instance the operator `^`. Once the anchor is hit, you have a match, which can be "empty", that is immediately followed by another anchor. | If a subject is an empty string then fullmatch() evaluates to True for any regex that can find a ... The overall regex match is not included in the tuple, unless you place the entire ... appear in the regular expression, as raw strings do not offer a means to escape it. |
58,167,766 | I am referring to the documentation of the [`re.findall`](https://docs.python.org/3/library/re.html#re.findall) function:
What is the meaning of *"Empty matches are included in the result."*? | 2019/09/30 | [
"https://Stackoverflow.com/questions/58167766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1779091/"
] | This happen when you use groups that matches empty string , example:
```
print(re.findall(r'(\w)(\d?)(\w)', "bc"))
```
OUPUT:
```
[('b', '', 'c')]
```
Here group `(\d?)` matches `''` and is included in the result. | Zero-length matches, or empty matches.
A Regular Expression is made of boundaries definitions, or anchors, for instance the operator `^`. Once the anchor is hit, you have a match, which can be "empty", that is immediately followed by another anchor. |
62,684,468 | I'm working on an automated web scraper for a Restaurant website, but I'm having an issue. The said website uses Cloudflare's anti-bot security, which I would like to bypass, not the Under-Attack-Mode but a captcha test that only triggers when it detects a non-American IP or a bot. I'm trying to bypass it as Cloudflare... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62684468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7032457/"
] | This really piqued my interests. The `requests` solution that I was able to get working.
Solution
--------
Finally narrow down the problem. When you use requests it uses urllib3 connection pool. There seems to be some inconsistency between a regular urllib3 connection and a connection pool. A working solution:
```py... | After some debugging, and thanks to the answers of @TuanGeek, we've found out the issue with the requests library seems to come from a DNS issue on requests' part when dealing with cloudflare, a simple fix to this issue is connecting directly to the host IP as such:
```
import requests
from collections import OrderedD... |
52,608,420 | I am using a language I made with a similar syntax to python, and I wanted to use python syntax highlighting for my language as well.
The only problem is that my language uses curly brackets rather then : and indents.
So some times when I type return for example it highlights the return in red.
Is there any way I ca... | 2018/10/02 | [
"https://Stackoverflow.com/questions/52608420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6516763/"
] | I'm surprised that someone is still using jQuery Mobile but I think I have most of the code you need.
Several years ago I wrote an article covering a complex jQuery Mobile authorization tutorial: <https://www.gajotres.net/complex-jquery-mobile-authorization-example/>
The main idea is to post your authorization inform... | I'm not sure what your php file looks like as you have not provided the code...
But here is a mockup example of the front-end js and html.
Place js in between head tags.
```
<script type="text/javascript">
$(document).ready(function () {
$("#insert").click(function () {
var email = $("#email... |
58,100,383 | I have been experimenting to create a docker image with python3.6 based on amazonlinux.
So far, I have not been very successful. I use
```
docker run -it amazonlinux
```
to start an interactive docker terminal. Inside the terminal, I run "yum install python36" and see the following error message. Note that I copied... | 2019/09/25 | [
"https://Stackoverflow.com/questions/58100383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1947254/"
] | You can check this [Dockerfile](https://github.com/RealSalmon/docker-amazonlinux-python/blob/master/Dockerfile) based on amazon Linux and having python version is `PYTHON_VERSION=3.6.4`.
Or you can work with your existing one like
```
ARG PYTHON_VERSION=3.6.4
ARG BOTO3_VERSION=1.6.3
ARG BOTOCORE_VERSION=1.9.3
ARG APP... | I too had similiar issue for docker.
yum install docker
Loaded plugins: ovl, priorities
amzn2-core | 3.7 kB 00:00:00
No package docker available.
Error: Nothing to do
instead yum I used amazon-linux-extras, it worked
amazon-linux-extras install docker
================================== |
58,100,383 | I have been experimenting to create a docker image with python3.6 based on amazonlinux.
So far, I have not been very successful. I use
```
docker run -it amazonlinux
```
to start an interactive docker terminal. Inside the terminal, I run "yum install python36" and see the following error message. Note that I copied... | 2019/09/25 | [
"https://Stackoverflow.com/questions/58100383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1947254/"
] | There is now a far easier answer to this question thanks to aws 'extras'. Now this will work:
```
amazon-linux-extras install python3
``` | I too had similiar issue for docker.
yum install docker
Loaded plugins: ovl, priorities
amzn2-core | 3.7 kB 00:00:00
No package docker available.
Error: Nothing to do
instead yum I used amazon-linux-extras, it worked
amazon-linux-extras install docker
================================== |
53,296,469 | below is the python code
```
def load_scan(path):
print(path)
slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)]
slices.sort(key = lambda x: int(x.InstanceNumber))
try:
slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
except:
slice_thickness = np... | 2018/11/14 | [
"https://Stackoverflow.com/questions/53296469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207817/"
] | Find where filereader.py is. You can see the directory from the traceback itself.
Replace `raise StopIteration` with `return` and you are set to go.
Your filereader.py directory will look like this : `/usr/local/lib/python3.7/site-packages/dicom/filereader.py` | I believe dicom is no longer supported, Use [pydicom](https://pypi.org/project/pydicom/) instead of dicom. |
24,255,734 | I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(eleme... | 2014/06/17 | [
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] | You could use `itertools.islice`:
```
for element in itertools.islice(my_list, 0, 3):
do_stuff(element)
```
Of course, if it actually *is* a list, then you could just use a regular slice:
```
for element in my_list[:3]:
do_stuff(element)
```
Regular slices on normal sequences are "forgiving" in that if yo... | ```
for element in my_list[:3]:
do_stuff(element)
``` |
24,255,734 | I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(eleme... | 2014/06/17 | [
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] | You could use `itertools.islice`:
```
for element in itertools.islice(my_list, 0, 3):
do_stuff(element)
```
Of course, if it actually *is* a list, then you could just use a regular slice:
```
for element in my_list[:3]:
do_stuff(element)
```
Regular slices on normal sequences are "forgiving" in that if yo... | @mhawke's answer is perfect if it's actually a `list` or something else that supports the slice interface.
For a more general iterable type, try the ever-handy [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate):
```
for ii, element in enumerate(my_list):
if ii>=3:
break
do_stuff... |
24,255,734 | I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(eleme... | 2014/06/17 | [
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] | Slice the list:
```
for element in my_list[:3]:
do_stuff(element)
```
[Documentation](https://docs.python.org/2/reference/expressions.html#slicings) says that there won't be any errors if the list doesn't have elements on those indices, thus you can safely use that on lists containing less than 3 elements. List ... | ```
for element in my_list[:3]:
do_stuff(element)
``` |
24,255,734 | I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(eleme... | 2014/06/17 | [
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] | Slice the list:
```
for element in my_list[:3]:
do_stuff(element)
```
[Documentation](https://docs.python.org/2/reference/expressions.html#slicings) says that there won't be any errors if the list doesn't have elements on those indices, thus you can safely use that on lists containing less than 3 elements. List ... | @mhawke's answer is perfect if it's actually a `list` or something else that supports the slice interface.
For a more general iterable type, try the ever-handy [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate):
```
for ii, element in enumerate(my_list):
if ii>=3:
break
do_stuff... |
24,255,734 | I have a list of dicts that can be anywhere from 0 to 100 elements long. I want to look through the first three elements only, and I don't want to throw an error if there are less than three elements in the list. How do I do this cleanly in python?
psuedocode:
```
for element in my_list (max of 3):
do_stuff(eleme... | 2014/06/17 | [
"https://Stackoverflow.com/questions/24255734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672601/"
] | ```
for element in my_list[:3]:
do_stuff(element)
``` | @mhawke's answer is perfect if it's actually a `list` or something else that supports the slice interface.
For a more general iterable type, try the ever-handy [`enumerate`](https://docs.python.org/2/library/functions.html#enumerate):
```
for ii, element in enumerate(my_list):
if ii>=3:
break
do_stuff... |
69,979,902 | I am doing this assignment for a python course but I am nowhere near the solution.
Let's say if I enter x = 4, this is what I am supposed to get:
```
"pyramid(0) =>" [ ]
"pyramid(1) =>" [ [1] ]
"pyramid(2) =>" [ [1], [1, 1] ]
"pyramid(3) =>" [ [1], [1, 1], [1, 1, 1] ]
```
I believe t... | 2021/11/15 | [
"https://Stackoverflow.com/questions/69979902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15572613/"
] | You can do:
```
def pyramid(n):
result = []
for i in range(n):
result.append([1] * (i+1))
return result
>>> pyramid(0)
[]
>>> pyramid(1)
[[1]]
>>> pyramid(2)
[[1], [1, 1]]
``` | I tried to come up with words to guide you to this solution, but it just wasn't possible. You need a 'for' loop to count to 4, and you need `[1]*i` to create a list with a certain number of 1s.
```
x = 4
list1 = []
print("pyramid(0) =>", list1)
for i in range(x):
list1.append( [1] * i )
print("pyramid(%d) =>" ... |
69,979,902 | I am doing this assignment for a python course but I am nowhere near the solution.
Let's say if I enter x = 4, this is what I am supposed to get:
```
"pyramid(0) =>" [ ]
"pyramid(1) =>" [ [1] ]
"pyramid(2) =>" [ [1], [1, 1] ]
"pyramid(3) =>" [ [1], [1, 1], [1, 1, 1] ]
```
I believe t... | 2021/11/15 | [
"https://Stackoverflow.com/questions/69979902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15572613/"
] | You can do:
```
def pyramid(n):
result = []
for i in range(n):
result.append([1] * (i+1))
return result
>>> pyramid(0)
[]
>>> pyramid(1)
[[1]]
>>> pyramid(2)
[[1], [1, 1]]
``` | As @mkrieger1 stated, you need more lists. Create the sublist in you for loop, then add to that sublist instead of adding to `list`. Then you can add the sublist to `list1`. This can keep your structure intact.
```py
x = 4
list1 = []
line = 0
while line < x:
one = line + 1
sublist = [] # create the sublist to... |
44,311,287 | I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. Any help on this would be greatly appreciated.
```
# -*- coding: utf-8 -*-
import paramiko
import... | 2017/06/01 | [
"https://Stackoverflow.com/questions/44311287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055089/"
] | If this were my project, I would convert the code to a function and then create a keyword library that includes that function.
For example, you could create a file named CustomLibrary.py with a function defined like this:
```
def verify_model(model):
prompt = "#"
datetime = datetime.now()
ssh_pre = param... | To call Python code from Robot Framework, you need to use the same syntax as a Robot Framework Library, but once you do, it's very simple. Here's an example, in a file called CustomLibrary.py located in the same folder as the test:
```
from robot.libraries.BuiltIn import BuiltIn
# Do any other imports you want here.
... |
44,311,287 | I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. Any help on this would be greatly appreciated.
```
# -*- coding: utf-8 -*-
import paramiko
import... | 2017/06/01 | [
"https://Stackoverflow.com/questions/44311287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055089/"
] | If this were my project, I would convert the code to a function and then create a keyword library that includes that function.
For example, you could create a file named CustomLibrary.py with a function defined like this:
```
def verify_model(model):
prompt = "#"
datetime = datetime.now()
ssh_pre = param... | The easiest way is importing a `.py` file into your testsuite using relative path approach, like `./my_lib.py` (assume that your python file is in the same folder with your TC file)
In your `.py` file, simply define a function, for example:
```
def get_date(date_string, date_format='%Y-%m-%d'):
return datetime.st... |
44,311,287 | I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. Any help on this would be greatly appreciated.
```
# -*- coding: utf-8 -*-
import paramiko
import... | 2017/06/01 | [
"https://Stackoverflow.com/questions/44311287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8055089/"
] | To call Python code from Robot Framework, you need to use the same syntax as a Robot Framework Library, but once you do, it's very simple. Here's an example, in a file called CustomLibrary.py located in the same folder as the test:
```
from robot.libraries.BuiltIn import BuiltIn
# Do any other imports you want here.
... | The easiest way is importing a `.py` file into your testsuite using relative path approach, like `./my_lib.py` (assume that your python file is in the same folder with your TC file)
In your `.py` file, simply define a function, for example:
```
def get_date(date_string, date_format='%Y-%m-%d'):
return datetime.st... |
46,418,397 | This may appear like a very trivial question but I have just started learning python classes and objects. I have a code like below.
```
class Point(object):
def __init__(self,x,y):
self.x = float(x)
self.y = float(y)
def __str__(self):
return '('+str(self.x)+','+str(self.y)+... | 2017/09/26 | [
"https://Stackoverflow.com/questions/46418397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8629294/"
] | I would use Repeat to add one element and implement the interpolation as a new lambda layer. I don't think there's an existing layer for this in keras. | Surprisingly there is no existing layer/function in keras that does such an interpolation of a tensor (as pointed out by xtof54). So, I implemented it using a lambda layer, and it worked fine.
```
def resize_like(input_tensor, ref_tensor): # resizes input tensor wrt. ref_tensor
H, W = ref_tensor.get_shape(... |
66,742,855 | I am working in selenium with python.
I used the code that worked, one hour ago, but now it returns me that
```
no such element: Unable to lacate element:...
```
The same code worked maximum one hour ago.
Where is the problem? I checked the source code, but it still the same
Here is my code:
```
import selenium
f... | 2021/03/22 | [
"https://Stackoverflow.com/questions/66742855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15446325/"
] | You could also use a capture group without a global flag to match for only a single match, and match all lines that do not start with 10 hyphens using a negative lookahead.
```
^(?:(?!----------).*\n)+(?=----------$)
```
[regex demo](https://regex101.com/r/h0BlCk/1)
Or you can match as least as possible lines, unti... | You may try matching on the following pattern, with DOT ALL mode enabled:
```regex
^.*?(?=----------|$)
```
[Demo
----](https://regex101.com/r/mvZxBD/1)
This will match all content up to, but including, the first set of dashes. Note that for inputs not having any dash separators, it would return all content.
If yo... |
64,812,794 | The following code appears when I am running a cell on Google Colab:
```
NameError Traceback (most recent call last)
<ipython-input-36-5f325bc0550d in <module>()
4
5 TAGGER_PATH = "crf_nlu.tagger" # path to the tagger- it will save/access the model from here
----> 6 ct = ... | 2020/11/12 | [
"https://Stackoverflow.com/questions/64812794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14597269/"
] | I just sorted it out. For the google colab, I had to add the following line:
>
> pip install sklearn-pycrfsuite
>
>
> | Use:
>
> pip install python-crfsuite
>
>
>
Scikit-crfsuite provides API similar to scikit-learn library. |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | You can execute your file by using this:
```
python /Users/luca/Documents/python/gameover.py
```
You can also run the file by moving to the path of the file you want to run and typing:
```
python gameover.py
``` | Let's say your script is called `my_script.py` and you have put it in your Downloads folder.
There are many ways of installing Python, but [Homebrew](https://brew.sh/) is the easiest.
0. Open [Terminal.app](https://en.wikipedia.org/wiki/Terminal_(macOS)) (press ⌘+Space and type "Terminal" and press the [Enter key](ht... |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | If you are working with Ubuntu, sometimes you need to run as `sudo`:
For Python2:
```
sudo python gameover.py
```
For Python3:
```
sudo python3 gameover.py
``` | Open the directory where you have saved your python program
```
cd desktop/home/file.....
```
type the command
```
python3 filename.py
``` |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial:
<http://docs.python-guide.org/en/latest/starting/install3/osx/>.
To run the program you can then copy and paste in this code:
```
python /Users/luca/Documents/python/gameover.py
```
Or you can go t... | First of all, you need to move to the location of the file you are trying to execute, so in a Terminal:
```
cd ~/Documents/python
```
Now, you should be able to execute your file:
```
python gameover.py
``` |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | You need [*python*](http://www.python.org/) installed on your system. Then you can run this in the terminal in the correct directory:
```
python gameover.py
``` | Open the directory where you have saved your python program
```
cd desktop/home/file.....
```
type the command
```
python3 filename.py
``` |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | If you are working with Ubuntu, sometimes you need to run as `sudo`:
For Python2:
```
sudo python gameover.py
```
For Python3:
```
sudo python3 gameover.py
``` | For OS Monterrey
```
/usr/local/bin/python3
```
or o Open the search bar on your mac and enter python a window will open with the address of the directory copy the directory and paste it into the terminal
enjoy |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial:
<http://docs.python-guide.org/en/latest/starting/install3/osx/>.
To run the program you can then copy and paste in this code:
```
python /Users/luca/Documents/python/gameover.py
```
Or you can go t... | For OS Monterrey
```
/usr/local/bin/python3
```
or o Open the search bar on your mac and enter python a window will open with the address of the directory copy the directory and paste it into the terminal
enjoy |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial:
<http://docs.python-guide.org/en/latest/starting/install3/osx/>.
To run the program you can then copy and paste in this code:
```
python /Users/luca/Documents/python/gameover.py
```
Or you can go t... | Open the directory where you have saved your python program
```
cd desktop/home/file.....
```
type the command
```
python3 filename.py
``` |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | First of all, you need to move to the location of the file you are trying to execute, so in a Terminal:
```
cd ~/Documents/python
```
Now, you should be able to execute your file:
```
python gameover.py
``` | Open the directory where you have saved your python program
```
cd desktop/home/file.....
```
type the command
```
python3 filename.py
``` |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | You can execute your file by using this:
```
python /Users/luca/Documents/python/gameover.py
```
You can also run the file by moving to the path of the file you want to run and typing:
```
python gameover.py
``` | This Depends on what version of python is installed on you system. See below.
If You have Python 2.\* version you have to run this command
```
python gameover.py
```
But if you have Python 3.\* version you have to run this command
```
python3 gameover.py
```
Because for MAC with Python version 3.\* you will get ... |
21,492,214 | I want to run a Python script in Terminal, but I don't know how? I already have a saved file called gameover.py in the directory "/User/luca/Documents/python". | 2014/01/31 | [
"https://Stackoverflow.com/questions/21492214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3255415/"
] | This Depends on what version of python is installed on you system. See below.
If You have Python 2.\* version you have to run this command
```
python gameover.py
```
But if you have Python 3.\* version you have to run this command
```
python3 gameover.py
```
Because for MAC with Python version 3.\* you will get ... | If you are working with Ubuntu, sometimes you need to run as `sudo`:
For Python2:
```
sudo python gameover.py
```
For Python3:
```
sudo python3 gameover.py
``` |
42,165,925 | I have .txt file that has 6 lines on it.
```
Line 1 name
Line 2 eamil address
line 4 phone number
line 5 sensor name
line 6 link .
```
I want to read those 6 lines in python and forward an email to the email address listed in the second line. I have a script that does this . But I don't know how to do this from... | 2017/02/10 | [
"https://Stackoverflow.com/questions/42165925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7449247/"
] | ```
with open("filename", "r") as f:
for l in f:
// do your processing, maybe keep track of how many lines you see since you need to do something different on each line
``` | Have a look at this question: [How do I read a text file into a string variable in Python](https://stackoverflow.com/q/8369219/2519977)
It shows you how to read a file line per line into an array.
So you can do:
```
with open('data.txt', 'r') as myfile:
data=myfile.read().replace('\n', '')
```
`data[1]` woul... |
42,165,925 | I have .txt file that has 6 lines on it.
```
Line 1 name
Line 2 eamil address
line 4 phone number
line 5 sensor name
line 6 link .
```
I want to read those 6 lines in python and forward an email to the email address listed in the second line. I have a script that does this . But I don't know how to do this from... | 2017/02/10 | [
"https://Stackoverflow.com/questions/42165925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7449247/"
] | You said email lies in the second line of the file?
you can manipulate txt files by line using the readline() function.
usage example:
text file:
```
John Smith
[email protected]
line3
1-800-smth-here
sensorname
link
file = open(“testfile.txt”, “r”)
client_email = file.readline(1)
print client_email
```
would resu... | Have a look at this question: [How do I read a text file into a string variable in Python](https://stackoverflow.com/q/8369219/2519977)
It shows you how to read a file line per line into an array.
So you can do:
```
with open('data.txt', 'r') as myfile:
data=myfile.read().replace('\n', '')
```
`data[1]` woul... |
65,912,670 | I have .csv file with only 2 columns. ("left" and "right")
The file size is less than 200 MB
I use the following code on **dev server** and it works as expected:
```
import pandas as pd
df = pd.read_csv('en_bigram.csv')
st = df[df["right"] == "some_text"]["left"]
st[st.str.startswith("My")].to_list()
```
"pandas" mo... | 2021/01/27 | [
"https://Stackoverflow.com/questions/65912670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/139150/"
] | I ran the following experiments on my machine (Intel 9th Gen i7) with a test data file of ~535 MB:
### Pandas version
```py
# import measurement dependencies
import time
import psutil
p = psutil.Process()
start = time.process_time()
import pandas as pd
df = pd.read_csv('test.csv')
st = df[df["right"] == "some_text... | >
> Is there any overhead (like memory/ cpu) in using pandas in production? Can the 4 lines pandas code written using python's built in modules like csv in 4 or 5 lines?
>
>
>
I'm going to say go with pandas. Once you start slicing and dicing large datasets, numpy arrays are much more efficient than python lists. |
67,172,207 | I've seen a couple of questions similar to this but none in python. Basically, I want to check if certain words are in a list. Though the words I want to compare might have a ',' which I want to ignore. I have tried this, though it does not ignore the ','.
```py
x = ['hello','there,','person']
y = ['there','person']
s... | 2021/04/20 | [
"https://Stackoverflow.com/questions/67172207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] | Check out this code use `any function` along with `map` to map containing conditon.
```
x = ['hello','there,','person']
y = ['there','person'] # or take this for more intuation ['there','person','bro']
similar = [words for words in y if any(map(lambda i: i.count(words), x))]
print(similar)
```
**OUTPUT:**
```
['the... | Just compare the strings without any comma:
```py
similar = [words for words in x if words.replace(',', '') in y ]
```
**Output**:
```py
>>similar
['there,', 'person']
``` |
67,172,207 | I've seen a couple of questions similar to this but none in python. Basically, I want to check if certain words are in a list. Though the words I want to compare might have a ',' which I want to ignore. I have tried this, though it does not ignore the ','.
```py
x = ['hello','there,','person']
y = ['there','person']
s... | 2021/04/20 | [
"https://Stackoverflow.com/questions/67172207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] | Just compare the strings without any comma:
```py
similar = [words for words in x if words.replace(',', '') in y ]
```
**Output**:
```py
>>similar
['there,', 'person']
``` | The other two answers so far require a quadratic time complexity of *O(n x m)*, where *n* and *m* are the lengths of `x` and `y`, respectively.
For a solution that requires just a linear time complexity of *O(n + m)*, you can normalize the strings in `x` to ones without commas and store them as a set, so that you can ... |
67,172,207 | I've seen a couple of questions similar to this but none in python. Basically, I want to check if certain words are in a list. Though the words I want to compare might have a ',' which I want to ignore. I have tried this, though it does not ignore the ','.
```py
x = ['hello','there,','person']
y = ['there','person']
s... | 2021/04/20 | [
"https://Stackoverflow.com/questions/67172207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14222251/"
] | Check out this code use `any function` along with `map` to map containing conditon.
```
x = ['hello','there,','person']
y = ['there','person'] # or take this for more intuation ['there','person','bro']
similar = [words for words in y if any(map(lambda i: i.count(words), x))]
print(similar)
```
**OUTPUT:**
```
['the... | The other two answers so far require a quadratic time complexity of *O(n x m)*, where *n* and *m* are the lengths of `x` and `y`, respectively.
For a solution that requires just a linear time complexity of *O(n + m)*, you can normalize the strings in `x` to ones without commas and store them as a set, so that you can ... |
24,807,434 | I've run into a problem with having imports in `__init__.py` and using `import as` with absolute imports in modules of the package.
My project has a subpackage and in its `__init__.py` I "lift" one of the classes from a module to the subpackage level with `from import as` statement. The module imports other modules fr... | 2014/07/17 | [
"https://Stackoverflow.com/questions/24807434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227133/"
] | You incorrectly assume that one cannot have an alias with `from ... import`, as `from ... import ... as` has been there since Python 2.0. The `import ... as` is the obscure syntax that not many know about, but which you use by accident in your code.
[PEP 0221](http://legacy.python.org/dev/peps/pep-0221/) claims that t... | Your project structure regarding the way you call modules, must be like this:
```
pkg/
├── __init__.py
├── subpkg
│ ├── __init__.py
│ ├── one.py
│ └── two.py
tst.py
```
Define your **two.py** like this:
```
class TWO:
def functionTwo(self):
print("2")
```
Define your **one.py** like this :
```
... |
24,807,434 | I've run into a problem with having imports in `__init__.py` and using `import as` with absolute imports in modules of the package.
My project has a subpackage and in its `__init__.py` I "lift" one of the classes from a module to the subpackage level with `from import as` statement. The module imports other modules fr... | 2014/07/17 | [
"https://Stackoverflow.com/questions/24807434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227133/"
] | You incorrectly assume that one cannot have an alias with `from ... import`, as `from ... import ... as` has been there since Python 2.0. The `import ... as` is the obscure syntax that not many know about, but which you use by accident in your code.
[PEP 0221](http://legacy.python.org/dev/peps/pep-0221/) claims that t... | Here is a theory on what's going on.
When you use the `as` reserved word, for instance:
```
import pkg.subpkg.two_longname as two
```
Python must to completely initialize and resolve all dependences that has to do with `pkg.subpkg`. But there is a problem, to completely load `subpkg` you need to completely load `on... |
24,807,434 | I've run into a problem with having imports in `__init__.py` and using `import as` with absolute imports in modules of the package.
My project has a subpackage and in its `__init__.py` I "lift" one of the classes from a module to the subpackage level with `from import as` statement. The module imports other modules fr... | 2014/07/17 | [
"https://Stackoverflow.com/questions/24807434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3227133/"
] | You incorrectly assume that one cannot have an alias with `from ... import`, as `from ... import ... as` has been there since Python 2.0. The `import ... as` is the obscure syntax that not many know about, but which you use by accident in your code.
[PEP 0221](http://legacy.python.org/dev/peps/pep-0221/) claims that t... | As the accepted answer states this is an issue with Python's behavior.
I've filed a bug: <http://bugs.python.org/issue30024>
The fix by Serhiy Storchaka was merged and expected in Python 3.7 |
73,404,980 | I need to include a directory containing a python script and binaries that need to be executed by the script based on the parsed arguments in the JavaFX application.
The project is modular and built using Maven (although the modular part is not such an important piece of information).
When built using the maven run c... | 2022/08/18 | [
"https://Stackoverflow.com/questions/73404980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19794251/"
] | Problems
========
The `src/main/resources` directory only exists in your project sources. It does not exist in the build output, and it definitely does not exist in your deployment location. In other words, using:
```java
var pyPath = Paths.get("src/main/resources/script/main.py").toAbsolutePath().toString();
```
W... | I managed to create the artifacts using the [Java Packager](https://github.com/fvarrui/JavaPackager) plugin for Maven which made the deployment a much easier task. |
19,795,357 | I need to run some python files over and over with different settings and different file names.
Here is an example of a task I need to do. This is for Linux, but I need to do the same thing in Windows. Is there a way to use python to be the caller and run other python scripts which are already set to work on STD I/O? ... | 2013/11/05 | [
"https://Stackoverflow.com/questions/19795357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] | Don't think you can work around using `require`, but you can specifically check for `MODULE_NOT_FOUND` errors:
```
function moduleExists(mod) {
try {
require(mod);
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND')
return false;
throw e;
};
return true;
}
``` | I'm showing with the "swig" module. There might be better ways, but this works for me.
```
var swig;
try {
swig = require('swig');
} catch (err) {
console.log(" [FAIL]\t Cannot load swig.\n\t Have you tried installing it? npm install swig");
}
if (swig != undefined) {
console.log(" [ OK ]\t Module: swig"... |
19,795,357 | I need to run some python files over and over with different settings and different file names.
Here is an example of a task I need to do. This is for Linux, but I need to do the same thing in Windows. Is there a way to use python to be the caller and run other python scripts which are already set to work on STD I/O? ... | 2013/11/05 | [
"https://Stackoverflow.com/questions/19795357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] | The best way is to use [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve), since it does not actually run any code contained in the module.
>
> Use the internal `require()` machinery to look up the location of a module, but rather than loading the module, just return the resolved filena... | I'm showing with the "swig" module. There might be better ways, but this works for me.
```
var swig;
try {
swig = require('swig');
} catch (err) {
console.log(" [FAIL]\t Cannot load swig.\n\t Have you tried installing it? npm install swig");
}
if (swig != undefined) {
console.log(" [ OK ]\t Module: swig"... |
19,795,357 | I need to run some python files over and over with different settings and different file names.
Here is an example of a task I need to do. This is for Linux, but I need to do the same thing in Windows. Is there a way to use python to be the caller and run other python scripts which are already set to work on STD I/O? ... | 2013/11/05 | [
"https://Stackoverflow.com/questions/19795357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1018733/"
] | The best way is to use [`require.resolve()`](http://nodejs.org/api/globals.html#globals_require_resolve), since it does not actually run any code contained in the module.
>
> Use the internal `require()` machinery to look up the location of a module, but rather than loading the module, just return the resolved filena... | Don't think you can work around using `require`, but you can specifically check for `MODULE_NOT_FOUND` errors:
```
function moduleExists(mod) {
try {
require(mod);
} catch(e) {
if (e.code === 'MODULE_NOT_FOUND')
return false;
throw e;
};
return true;
}
``` |
55,602,574 | I am attempting to programmatically put data into a locally running DynamoDB Container by triggering a Python lambda expression.
I'm trying to follow the template provided here: <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Python.03.html>
I am using the amazon/dynamodb-local you ca... | 2019/04/09 | [
"https://Stackoverflow.com/questions/55602574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740463/"
] | As per [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Parameters) suggests, the `monthIndex` would start at 0, rather than 1. So you need to manually subtract 1.
```
data.forEach((item) => {
item.date.pop()
item.date[1]--
item.date = new Date(...item.dat... | The month is represented by a value from 0 to 11, 4 is the fifth month, it corresponds to May, you just need to decrease it by 1. |
60,654,425 | I am making a lot of plots and saving them to a file, it all works, but during the compilation I get the following message:
```
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much... | 2020/03/12 | [
"https://Stackoverflow.com/questions/60654425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11085398/"
] | Replace `fig.close()` with `plt.close(fig)`, [`close`](https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html) is a function defined directly in the module. | Try this, matplotlib.pyplot.close(fig) , for more information refer this website
<https://matplotlib.org/2.1.0/api/_as_gen/matplotlib.pyplot.close.html> |
14,082,909 | I'm creating a simple script for blender and i need a little help with get some data from file i've created before via python.
That file got structure like below:
```
name first morph
values -1.0000 1.0000
data 35 0.026703 0.115768 -0.068769
data 36 -0.049349 0.015188 -0.029470
data 37 -0.042880 -0.045805 -0.039931
d... | 2012/12/29 | [
"https://Stackoverflow.com/questions/14082909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1936580/"
] | ```
names = []
values = []
data = []
with open('yourfile') as lines:
for line in lines:
first, rest = line.split(' ', 1)
if first == 'name':
names.append(rest)
elif first == 'values':
floats = map(float, rest.split())
values.append(tuple(floats))
... | Here is a simple python "for line in" solution... you can just call `processed.py`...
```
fp = open("data1.txt", "r")
data = fp.readlines()
fp1 = open("processed.py", "w")
fp1.write("names = []\nvalues=[]\ndata=[]\n")
for line in data:
s = ""
if "name" in line:
s = "names.append('" + line[5:].strip(... |
33,936,017 | I learn how to remove items from a list while iterating from [here](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) by:
```
somelist = [x for x in somelist if determine(x)]
```
Further, how do I remove a specific index from a list while iterating? For instance,
```
li... | 2015/11/26 | [
"https://Stackoverflow.com/questions/33936017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3067748/"
] | Basically your attempt is not supported according to any documentation. In general you should not modify a container while iterating unless the documentation explicitly says that you can. It doesn't help if it "seems to work" since you then just exploiting some behavior in the version of the implementation you're using... | You can produce the same thing using list comprehension:
```
somelist = [i for idx, i in enumerate(lists) if i[0] != lists[idx][0]]
``` |
13,033,820 | I have a question about while loops in python.
I want to make a program that performs a while loop in a certain time.I want to add the extra feature that while the program us running,a certain variable can be changed by pressing a random key.
```
from time import sleep
import time
i=0
a=0
while i<10:
... | 2012/10/23 | [
"https://Stackoverflow.com/questions/13033820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1714419/"
] | This might be happening because you render the *header*, *menu* and *body* inside a `<table>`. At least the *body* seems to be missing the row and cell tags (`<tr><td>...</td></tr>`). Therefore there are no rows and cells in your table which can lead to all sorts of rendering problems.
It would probably help if you di... | This looks to be nothing to do with the MVC side of what you are doing - that looks perfectly fine.
The issue will be with your HTML. I would suggest having a look at the site using one of the browser developer tools (e.g. in Chrome or IE open your site and press F12) - you can use the features of these to examine ho... |
59,407,592 | Below code has a call to a method called **lago**.
```
#!/usr/bin/env python
#
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
#
import sys
class InstallTest():
"""Ru Ovirt System Tests"""
def run_command_checking_exit_code(command):
""" Runs a command"""
print("Com... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59407592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12342391/"
] | Try this :
```js
var value1="4111111111111111"
var pattern = new RegExp('^4[0-9]{12}(?:[0-9]{3})?$}');
var result=pattern.test(value1);
console.log(result);
```
This will return either `True` or `False` | If you pattern is somthimg like that: `4111111111111111` or `4111111111111111`
then use this code:
```
const str="^4[0-9]{12}([0-9]{3})?$";
'4111111111111'.match(str)
'4111111111111111'.match(str)
``` |
56,750,400 | Is there any library implementation for the `label2idx()` function in python?
I wish to extract superpixels from the label representation to the format exactly returned by the `label2idx()` function.
label2idx function: <https://in.mathworks.com/help/images/ref/label2idx.html> | 2019/06/25 | [
"https://Stackoverflow.com/questions/56750400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9215748/"
] | Given an array of labels `label_arr` containing all labels from `1` to `max(label_arr)`, you can do:
```
def label2idx(label_arr):
return [
np.where(label_arr.ravel() == i)[0]
for i in range(1, np.max(label_arr) + 1)]
```
---
If you want to relax the requirement of all labels being contained you... | MATLAB's [`label2idx`](https://www.mathworks.com/help/images/ref/label2idx.html) outputs the flattened indices (column-major ordered) given the labeled image.
We can use `scikit-image's` built-in [`regionprops`](https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.regionprops) to get those indice... |
37,662,732 | I'm looking for an XPATH to extract 'sets' as separate sequences. It has to be interpreted by python `lxml` (which is a wrapper around `libxml2`).
For example, given the following:
```
<root>
<sub1>
<sub2>
<Container>
<item>1 - My laptop has exploded again</item>
... | 2016/06/06 | [
"https://Stackoverflow.com/questions/37662732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204634/"
] | 1. Evaluate this XPath expression:
`count(/*/*/*)`
This finds the number of `<sub2>` elements (equivalent and more readable, but longer, is:
```
count(/*/sub1/sub2))
```
2. For each `$n` in 1 to `count(/*/*/*)` evaluate the following XPath expression:
`/*/*/*[$n]/*/item/text()`
Again, this is equivalent to the l... | ```
from lxml import etree
doc=etree.parse("data.xml");
v = doc.findall('sub1/sub2/Container')
finalResult = list()
for vv in v:
sequence = list()
for item in vv.findall('item'):
sequence.append(item.text)
finalResult.append(sequence)
print finalResult
```
And this is the result:
```
[['1 - My l... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.h... | Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | One solution is to use `./manage.py dumpdata -o data.json` instead of `./manage.py dumpdata > data.json`.
Another solution is to use [Python's UTF-8 mode](https://docs.python.org/3/using/cmdline.html?highlight=utf%20mode#id5), run:
```
python -Xutf8 ./manage.py dumpdata > data.json
``` | To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.h... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.h... | If you have multiple Python environments, before applying workarounds, it's worth checking that you issue `python manage.py` against the correct environment. That was my case where I met the same error: the database was created under containerized environment on Linux, with a higher Python version, but Django and other... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | To save `json` data in django the [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper) is used:
>
> The default encoding is now `locale.getpreferredencoding(False)` (...)
>
>
>
In documentation of `locale.getpreferredencoding` fuction we can [read](https://docs.python.org/3/library/locale.h... | On windows the way i solved mine was
Add to your settings
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
run this on shell only on windows
```
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
```
I actually did this it worked
```
py... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | One solution is to use `./manage.py dumpdata -o data.json` instead of `./manage.py dumpdata > data.json`.
Another solution is to use [Python's UTF-8 mode](https://docs.python.org/3/using/cmdline.html?highlight=utf%20mode#id5), run:
```
python -Xutf8 ./manage.py dumpdata > data.json
``` | Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.... | If you have multiple Python environments, before applying workarounds, it's worth checking that you issue `python manage.py` against the correct environment. That was my case where I met the same error: the database was created under containerized environment on Linux, with a higher Python version, but Django and other... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | Here is the solution from djangoproject.com
You go to Settings there's a "Use Unicode UTF-8 for worldwide language support", box in "Language" - "Administrative Language Settings" - "Change system locale" - "Region Settings".
If we apply that, and reboot, then we get a sensible, modern, default encoding from Python.... | On windows the way i solved mine was
Add to your settings
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
run this on shell only on windows
```
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
```
I actually did this it worked
```
py... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | One solution is to use `./manage.py dumpdata -o data.json` instead of `./manage.py dumpdata > data.json`.
Another solution is to use [Python's UTF-8 mode](https://docs.python.org/3/using/cmdline.html?highlight=utf%20mode#id5), run:
```
python -Xutf8 ./manage.py dumpdata > data.json
``` | If you have multiple Python environments, before applying workarounds, it's worth checking that you issue `python manage.py` against the correct environment. That was my case where I met the same error: the database was created under containerized environment on Linux, with a higher Python version, but Django and other... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | One solution is to use `./manage.py dumpdata -o data.json` instead of `./manage.py dumpdata > data.json`.
Another solution is to use [Python's UTF-8 mode](https://docs.python.org/3/using/cmdline.html?highlight=utf%20mode#id5), run:
```
python -Xutf8 ./manage.py dumpdata > data.json
``` | On windows the way i solved mine was
Add to your settings
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
run this on shell only on windows
```
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
```
I actually did this it worked
```
py... |
64,457,733 | I'm trying to dump my entire DB to a json. When I run `python manage.py dumpdata > data.json` I get an error:
```
(env) PS C:\dev\watch_something> python manage.py dumpdata > data.json
CommandError: Unable to serialize database: 'charmap' codec can't encode character '\u0130' in position 1: character maps to <undefine... | 2020/10/21 | [
"https://Stackoverflow.com/questions/64457733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8168198/"
] | On windows the way i solved mine was
Add to your settings
```
import _locale
_locale._getdefaultlocale = (lambda *args: ['en_US', 'utf8'])
```
run this on shell only on windows
```
python -Xutf8 manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json
```
I actually did this it worked
```
py... | If you have multiple Python environments, before applying workarounds, it's worth checking that you issue `python manage.py` against the correct environment. That was my case where I met the same error: the database was created under containerized environment on Linux, with a higher Python version, but Django and other... |
56,460,723 | I am working with Django and currently try to move my local dev. to Docker. I managed to run my web server. However, what I didn't to yet was `npm install`. That's where I got stuck and I couldn't find documentation or good examples. Anyone who has done that before?
**Dockerfile**:
```
# Pull base image
FROM python:3... | 2019/06/05 | [
"https://Stackoverflow.com/questions/56460723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10419791/"
] | It is simple, you should just follow this instruction:
```
npm install
//or
yarn install
```
This will install all node\_modules, when it is not found in the current directory, it will search for the **node\_modules** on directory up.
Hope this answers your question. | In the Dockerfile just add:
RUN npm install
This will look if there is a package.json in the current directory and if it does, it will install all dependencies. |
12,091,009 | I'm trying to get this [nodetime](http://nodetime.com/docs) running, but seems there's some prblems I can't figur out. I did exactly as the guide say, So i supposed to get following:
>
> After your start your application, a link of the form https://nodetime.com/[session\_id] will be printed to the console, where the ... | 2012/08/23 | [
"https://Stackoverflow.com/questions/12091009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326868/"
] | No. You cannot embed an Apps Script web app in an external site. You can only do it on a Google Site. | Yes it is possible I have installed google comments and google follower on my tumblr blog. |
44,093,441 | In C++, how are the local class variables declared? I'm new to C++ but have some python experience. I'm wondering if C++ classes have a way of identifying their local variables, for example, in python your class' local variables are marked with a self. so they would be like:
```
self.variable_name
```
Does C++ have ... | 2017/05/21 | [
"https://Stackoverflow.com/questions/44093441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8034222/"
] | That's pretty close! Within the class, however, one would mention the class variables simply using their own name, therefore as `variable` as opposed to `class.variable`.
(Also, note that your functions need to have a semicolon following them, and by convention these functions tend to be defined under the class itsel... | When you read Effective C++ (written by Scott Meyers), member variables are init when ctor initializer. After ctor, all assignment is assignment, not init. You can write ctor like this.
```
Circle(double value, bool isTrueFalse, <More Variables>) : class.variable(value), class.othervariable(isTrueFalse), ..<More Varia... |
63,147,540 | This is my first time using Python and I'm tasked with the following: print a list of cities from this JSON: <http://jsonplaceholder.typicode.com/users>
I'm trying to print out a list that should read:
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
etc.
This is the code I have so far:
```
import json
import reque... | 2020/07/29 | [
"https://Stackoverflow.com/questions/63147540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13488080/"
] | As `users` is a list, it should be:
```
print(users[0]['address']['city'])
```
This is how you can access nested properties in JSON response.
You can also loop over the users and print their city in the same format.
```
for user in users:
print(user['address']['city'])
``` | You can get city name with user['address']['city']
and use loop to get all city names
like this
```
for user in users:
print(user['address']['city'])
```
output :
```
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
Roscoeview
South Christy
Howemouth
Aliyaview
Bartholomebury
Lebsackbury
[Program finished]
``... |
63,147,540 | This is my first time using Python and I'm tasked with the following: print a list of cities from this JSON: <http://jsonplaceholder.typicode.com/users>
I'm trying to print out a list that should read:
Gwenborough
Wisokyburgh
McKenziehaven
South Elvis
etc.
This is the code I have so far:
```
import json
import reque... | 2020/07/29 | [
"https://Stackoverflow.com/questions/63147540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13488080/"
] | As `users` is a list, it should be:
```
print(users[0]['address']['city'])
```
This is how you can access nested properties in JSON response.
You can also loop over the users and print their city in the same format.
```
for user in users:
print(user['address']['city'])
``` | ```
first of all i get this, why your loading(response.text) , instead requests package has a built in .json() method which is what you want to access nested data . so you could do something like this
response = requests.get("https://jsonplaceholder.typicode.com/users")
data = response.json()
... |
7,196,148 | I know there is not much on stackoverflow on dojango, but I thought I'd ask anyway.
Dojango describes RegexField as follows:
```
class RegexField(DojoFieldMixin, fields.RegexField):
widget = widgets.ValidationTextInput
js_regex = None # we additionally have to define a custom javascript regexp, because the py... | 2011/08/25 | [
"https://Stackoverflow.com/questions/7196148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563247/"
] | After three days of beavering away I fould that you need to send `regex` and `js_regex`, though `regex` is not used:
```
post_code = RegexField(
regex='',
required = True,
widget=ValidationTextInput(
attrs={
'invalid': 'Post Code in incorrect format',
'regExp': '[A-Z]{1,2}\d... | The error is related to `super().__init__` call. If `fields.RegexField` is standard Django `RegexField`, then it requires `regex` keyword argument, as documented. Since you don't pass it, you get `TypeError`. If it's supposed to be the same as `js_regex`, then pass it along in the super call.
```
def __init__(self, js... |
46,327,700 | I have this `list` in `python` which can have `n` elements. Now what I am trying to do is show `4` elements from this `list` at a time with an added option 'next' to show next set of 4 elements. So if my list is something like this:
```
['room 11','room 22','room 33','room 44','room 55','room 65','room 77']
```
then... | 2017/09/20 | [
"https://Stackoverflow.com/questions/46327700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2966197/"
] | This will help you
```
room_list_num = 0
room_list_slot = 0
def room_try():
room_list = ['room 11','room 22','room 33','room 44','room 55','room 66','room 77','room 88','room 99','room 110','room 111','room 112']
inner_list_str = ["%d. Room number: %s" % ((i%4)+1, x)
for i, x in enumerat... | You can do something like this:
```
def room_try():
room_list_num = 0
room_list_slot = 0
room_list = ['room 11', 'room 22', 'room 33', 'room 44', 'room 55', 'room 66', 'room 77', 'room 88', 'room 99', 'room 110', 'room 111', 'room 112']
inner_list_str = ["%d. Room number: %s" % (i, x)
... |
53,823,349 | I have a set of values that I'd like to plot the gaussian kernel density estimation of, however there are two problems that I'm having:
1. I only have the values of bars not the values themselves
2. I am plotting onto a categorical axis
Here's the plot I've generated so far:
[ instead, but then it wouldn't be a KDE distribution.
Not all hope is l... | I have stated my reservations to applying a KDE to OP's categorical data in my comments above. Basically, as the phylogenetic distance between species does not obey the triangle inequality, there cannot be a valid kernel that could be used for kernel density estimation. However, there are other density estimation metho... |
53,823,349 | I have a set of values that I'd like to plot the gaussian kernel density estimation of, however there are two problems that I'm having:
1. I only have the values of bars not the values themselves
2. I am plotting onto a categorical axis
Here's the plot I've generated so far:
[ instead, but then it wouldn't be a KDE distribution.
Not all hope is l... | THE EASY WAY
============
For now, I am skipping any philosophical argument about the validity of using Kernel density in such settings. Will come around that later.
An **easy way** to do this is using scikit-learn `KernelDensity`:
```
import numpy as np
import pandas as pd
from sklearn.neighbors import KernelDensit... |
57,094,939 | I am wrote a serializer for the User model in Django with DRF:
the model:
```py
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.db import models
from django.utils.translation import ugettext
class BaseModel(models.Model):
# all models sho... | 2019/07/18 | [
"https://Stackoverflow.com/questions/57094939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1907902/"
] | I hope this will solve the issue,
```
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = models.User
fields = ['email', 'username', 'password']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
**return models.User.objects.c... | You can create your own user manager by overriding `BaseUserManager` and use `set_password()` method there. There is a full example in django's [documentation](https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#a-full-example). So your `models.py` will be:
```py
# models.py
from django.db import models
fr... |
33,493,861 | I wrote script which create animation (movie) from fits files. One file has size 2.8 MB and the no. of files is 9000.
Here is code
```
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import os
import pyfits
import glob
import re
Writ... | 2015/11/03 | [
"https://Stackoverflow.com/questions/33493861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2952470/"
] | I would recommend you to use `ffmpeg`. With the command `image2pipe` you don't have to load all the images into your RAM but rather one by one (i think) into a pipe.
In addition to that, `ffmpeg` allows you to manipulate the video (framerate, codec, format, etc...).
<https://ffmpeg.org/ffmpeg.html> | You might be better off creating your animation with FuncAnimation instead of ArtistAnimation, as explained in [ArtistAnimation vs FuncAnimation matplotlib animation matplotlib.animation](https://stackoverflow.com/questions/22158395/artistanimation-vs-funcanimation-matplotlib-animation-matplotlib-animation) FuncAnimati... |
50,438,762 | The code below is a basic square drawing using Turtle in python.
Running the code the first time works. But running the code again activates a Turtle window that is non-responsive and subsequently crashes every time.
The error message includes `raise Terminator` and `Terminator`
Restarting kernel in Spyder (Python 3... | 2018/05/20 | [
"https://Stackoverflow.com/questions/50438762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9655448/"
] | I realize this will seem wholly unsatisfactory, but I have found that creating the turtle with:
```
try:
tess = turtle.Turtle()
except:
tess = turtle.Turtle()
```
works (that is, eliminates the "working every other time" piece. I also start with
```
wn = turtle.Screen()
```
and end with
```
from sys i... | The module uses a class variable \_RUNNING which remains true between executions when running in spyder instead of running it as a self contained script. I have requested for the module to be updated.
Meanwhile, work around/working example beyond what DukeEgr93 has proposed
1)
```
import importlib
import turtle
imp... |
50,192,322 | this is my code the I am currently writing for a robot in my university project. This code works, however the loop will constantly print statements every second and I would like it to only print when I change the input condition (break the if condition), so it wouldn't keep on printing. Is there anyway to fix this? Tha... | 2018/05/05 | [
"https://Stackoverflow.com/questions/50192322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9746251/"
] | Keep track of the last category - something like that.
```
previous_category = 0
while True:
#some stuff
if 0.01 < joystick.get_axis(1) <= 0.25:
if previous_category != 1:
print ('moving backward with 25% speed')
previous_category = 1
# performing some actions
elif... | You can accomplish this with a global integer that stores the last value printed. Something like this:
```
_last_count = None
def condprint(count):
global _last_count
if count != _last_count:
print('Waiting for joystick '+str(count))
_last_count = count
``` |
63,043,387 | I have three arrays, such that:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = np.array([1, 2, 3, 4, 5])
Value_Arr = np.array([0.1, 0.6, 0.3, 0.8, 0.2])
```
I want to create a new array which has the dimensions of Data, but where each element is from Values, using the index positi... | 2020/07/22 | [
"https://Stackoverflow.com/questions/63043387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868191/"
] | Since `ID_Arr` is sorted, we can directly use [`np.searchsorted`](https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html) and index `Value_Arr` with the result:
```
Value_Arr[np.searchsorted(ID_Arr, Data_Arr)]
array([0.1, 0.1, 0.1, 0.6, 0.6, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.8, 0.8,
0.2, 0.2, 0.... | Looks like you want:
```
out = Value_Arr[ID_Arr[Data_Arr - 1] - 1]
```
Note that the `- 1` are due to the fact that Python/Numpy is `0`-based index. |
63,043,387 | I have three arrays, such that:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = np.array([1, 2, 3, 4, 5])
Value_Arr = np.array([0.1, 0.6, 0.3, 0.8, 0.2])
```
I want to create a new array which has the dimensions of Data, but where each element is from Values, using the index positi... | 2020/07/22 | [
"https://Stackoverflow.com/questions/63043387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868191/"
] | Based off approaches from [`this post`](https://stackoverflow.com/a/62658135/), here are the adaptations.
### Approach #1
```
# https://stackoverflow.com/a/62658135/ @Divakar
a,b,invalid_specifier = ID_Arr, Data_Arr, 0
sidx = a.argsort()
idx = np.searchsorted(a,b,sorter=sidx)
# Remove out of bounds indices as the... | Looks like you want:
```
out = Value_Arr[ID_Arr[Data_Arr - 1] - 1]
```
Note that the `- 1` are due to the fact that Python/Numpy is `0`-based index. |
63,043,387 | I have three arrays, such that:
```
Data_Arr = np.array([1, 1, 1, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5])
ID_Arr = np.array([1, 2, 3, 4, 5])
Value_Arr = np.array([0.1, 0.6, 0.3, 0.8, 0.2])
```
I want to create a new array which has the dimensions of Data, but where each element is from Values, using the index positi... | 2020/07/22 | [
"https://Stackoverflow.com/questions/63043387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2868191/"
] | Since `ID_Arr` is sorted, we can directly use [`np.searchsorted`](https://numpy.org/doc/stable/reference/generated/numpy.searchsorted.html) and index `Value_Arr` with the result:
```
Value_Arr[np.searchsorted(ID_Arr, Data_Arr)]
array([0.1, 0.1, 0.1, 0.6, 0.6, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.8, 0.8,
0.2, 0.2, 0.... | Based off approaches from [`this post`](https://stackoverflow.com/a/62658135/), here are the adaptations.
### Approach #1
```
# https://stackoverflow.com/a/62658135/ @Divakar
a,b,invalid_specifier = ID_Arr, Data_Arr, 0
sidx = a.argsort()
idx = np.searchsorted(a,b,sorter=sidx)
# Remove out of bounds indices as the... |
33,761,993 | Here's what I'm doing, I'm web crawling for my personal use on a website to copy the text and put the chapters of a book on text format and then transform it with another program to pdf automatically to put it in my cloud. Everything is fine until this happens: special characters are not copying correctly, for example ... | 2015/11/17 | [
"https://Stackoverflow.com/questions/33761993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431636/"
] | The easiest way to fix this problem that I found is adding `encoding= "utf-8"` in the open function:
```
with open('file.txt','w',encoding='utf-8') as file :
file.write('ñoño')
``` | The only error I can spot is,
```
str(texta).encode("utf-8")
```
In it, you are forcing a conversion to str and encoding it. It should be replaced with,
```
texta.encode("utf-8")
```
**EDIT:**
The error stems in the server not giving the correct encoding for the page. So `requests` assumes a `'ISO-8859-1'`. As n... |
33,761,993 | Here's what I'm doing, I'm web crawling for my personal use on a website to copy the text and put the chapters of a book on text format and then transform it with another program to pdf automatically to put it in my cloud. Everything is fine until this happens: special characters are not copying correctly, for example ... | 2015/11/17 | [
"https://Stackoverflow.com/questions/33761993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431636/"
] | The easiest way to fix this problem that I found is adding `encoding= "utf-8"` in the open function:
```
with open('file.txt','w',encoding='utf-8') as file :
file.write('ñoño')
``` | For some reason, you (wrongly) have utf8 encoded data in a Python3 string. The real cause of that is probably that `requests.content` is already a unicode string, so you should not decode it, but use it directly:
```
url = 'http://www.wuxiaworld.com/atg-index/atg-chapter-' + str(x) + "/"
source = requests.get(... |
10,080,944 | I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. ... | 2012/04/09 | [
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Here's a regular expression to do that:
```
findData = re.compile('(?<=<pre>).+?(?=[\d\s]*</pre>)', re.S)
# ...
result = findData.search(data).group(0).strip()
```
[Here's a demo.](http://codepad.org/M71yUzqw) | Quazi, this calls out for a regex, specifically `<pre>(.+?)(?:\d+\s+){3}` with the DOTALL flag enabled.
You can find out about how to use regex in Python at <http://docs.python.org/library/re.html> and if you do a lot of this sort of string extraction, you'll be very glad you did. Going over my provided regex piece-by... |
10,080,944 | I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. ... | 2012/04/09 | [
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Quazi, this calls out for a regex, specifically `<pre>(.+?)(?:\d+\s+){3}` with the DOTALL flag enabled.
You can find out about how to use regex in Python at <http://docs.python.org/library/re.html> and if you do a lot of this sort of string extraction, you'll be very glad you did. Going over my provided regex piece-by... | Other people have offered up regex solutions, which are good but may behave unexpectedly at times.
If the pages are exactly as shown in your example, that is:
* No other HTML tags are present - only the `<html>` and `<pre>` tags
* The number of lines is always consistent
* The spacing between lines is always consiste... |
10,080,944 | I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. ... | 2012/04/09 | [
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Here's a regular expression to do that:
```
findData = re.compile('(?<=<pre>).+?(?=[\d\s]*</pre>)', re.S)
# ...
result = findData.search(data).group(0).strip()
```
[Here's a demo.](http://codepad.org/M71yUzqw) | I'd probably use lxml or BeautifulSoup. IMO, regex's are heavily overused, especially for parsing up HTML. |
10,080,944 | I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. ... | 2012/04/09 | [
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | Here's a regular expression to do that:
```
findData = re.compile('(?<=<pre>).+?(?=[\d\s]*</pre>)', re.S)
# ...
result = findData.search(data).group(0).strip()
```
[Here's a demo.](http://codepad.org/M71yUzqw) | Other people have offered up regex solutions, which are good but may behave unexpectedly at times.
If the pages are exactly as shown in your example, that is:
* No other HTML tags are present - only the `<html>` and `<pre>` tags
* The number of lines is always consistent
* The spacing between lines is always consiste... |
10,080,944 | I have a weird parsing problem with python. I need to parse the following text.
Here I need only the section between(not including) "pre" tag and column of numbers (starting with 205 4 164). I have several pages in this format.
```
<html>
<pre>
A Short Study of Notation Efficiency
CACM August, 1960
Smith Jr., H. ... | 2012/04/09 | [
"https://Stackoverflow.com/questions/10080944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776614/"
] | I'd probably use lxml or BeautifulSoup. IMO, regex's are heavily overused, especially for parsing up HTML. | Other people have offered up regex solutions, which are good but may behave unexpectedly at times.
If the pages are exactly as shown in your example, that is:
* No other HTML tags are present - only the `<html>` and `<pre>` tags
* The number of lines is always consistent
* The spacing between lines is always consiste... |
61,511,948 | I am coding a Discord bot in a library for python, discord.py.
I don't need help with that but with scraping some info from the site.
```py
@commands.command(aliases=["rubyuserinfo"])
async def rubyinfo(self, ctx, input):
HEADERS = {
'User-Agent' : 'Magic Browser'
}
url = ... | 2020/04/29 | [
"https://Stackoverflow.com/questions/61511948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11251803/"
] | *How about the following, using .select() method*
```
from bs4 import BeautifulSoup
html = '<p class="margin-none font-color">Hey! My name is KOMKO190 :) </p>'
soup = BeautifulSoup(html, features="lxml")
element = soup.select('p.margin-none')[0]
print(element.text)
```
*Prints out*
>
>
> ```
> Hey! My name is ... | ```
from bs4 import BeautifulSoup as bs
url = 'https://rubyrealms.com/user/username/'
session = requests.Session()
request = session.get(url=url)
if request.status_code == 200:
soup = bs(request.text, 'lxml')
print(soup.find('p', class_='margin-none font-color').text)
else:
print(request.status_code)
```... |
61,511,948 | I am coding a Discord bot in a library for python, discord.py.
I don't need help with that but with scraping some info from the site.
```py
@commands.command(aliases=["rubyuserinfo"])
async def rubyinfo(self, ctx, input):
HEADERS = {
'User-Agent' : 'Magic Browser'
}
url = ... | 2020/04/29 | [
"https://Stackoverflow.com/questions/61511948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11251803/"
] | Change your XPath expression for a relative one :
```
from lxml import html
import requests
page = requests.get('https://www.rubyrealms.com/user/KOMKO190/')
tree = html.fromstring(page.content)
stuff = tree.xpath('normalize-space(//h3[.="Bio"]/following-sibling::p/text())')
print (stuff)
```
Output :
```
Hey! My na... | *How about the following, using .select() method*
```
from bs4 import BeautifulSoup
html = '<p class="margin-none font-color">Hey! My name is KOMKO190 :) </p>'
soup = BeautifulSoup(html, features="lxml")
element = soup.select('p.margin-none')[0]
print(element.text)
```
*Prints out*
>
>
> ```
> Hey! My name is ... |
61,511,948 | I am coding a Discord bot in a library for python, discord.py.
I don't need help with that but with scraping some info from the site.
```py
@commands.command(aliases=["rubyuserinfo"])
async def rubyinfo(self, ctx, input):
HEADERS = {
'User-Agent' : 'Magic Browser'
}
url = ... | 2020/04/29 | [
"https://Stackoverflow.com/questions/61511948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11251803/"
] | Change your XPath expression for a relative one :
```
from lxml import html
import requests
page = requests.get('https://www.rubyrealms.com/user/KOMKO190/')
tree = html.fromstring(page.content)
stuff = tree.xpath('normalize-space(//h3[.="Bio"]/following-sibling::p/text())')
print (stuff)
```
Output :
```
Hey! My na... | ```
from bs4 import BeautifulSoup as bs
url = 'https://rubyrealms.com/user/username/'
session = requests.Session()
request = session.get(url=url)
if request.status_code == 200:
soup = bs(request.text, 'lxml')
print(soup.find('p', class_='margin-none font-color').text)
else:
print(request.status_code)
```... |
48,136,092 | I installed the python module tabula-py which is apparently based on the Java version of tabula. When I try to run it I get an error saying that the wrong version of Java is installed, but when I check in system perferences on MacOS it says I've got the latest version (Version 8 update 151). On the github page it menti... | 2018/01/07 | [
"https://Stackoverflow.com/questions/48136092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6670570/"
] | This answer on the github issues page fixed the problem. <https://github.com/chezou/tabula-py/issues/54>
```
sudo mv /usr/bin/java /usr/bin/java-1.6
sudo ln -s /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java
``` | Probably You installed java in mutiple locations.
Typ in terminal
$ wich java
To check where is this java 6 located. Then maybe You will fiund out how to uninstall it from this location. |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex =... | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
... | Your algorithm is almost correct but
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]` in this line you made the mistake.
It shouldn't be `compare_index`, it should be `element`. Please check the correct algorithm below
```
my_list = [64, 25, 12, 11, 32]
def selec... |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex =... | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
... | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
min... |
68,992,767 | I'm trying to implement selection sort in python using a list. But the implementation part is correct and is as per my algorithm but it is not resulting in correct output. Adding my code:
```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex =... | 2021/08/31 | [
"https://Stackoverflow.com/questions/68992767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12116796/"
] | ```
my_list = [64, 25, 12, 11, 32]
def selection_sort(element_list):
for element in range(len(element_list)):
mindex = element
for compare_index in range(element+1, len(element_list)):
if element_list[mindex] > element_list[compare_index]:
mindex = compare_index
... | I think the problem lies in the line
`element_list[compare_index], element_list[mindex] = element_list[mindex], element_list[compare_index]`
Here I believe you want to exchange the position of the bigger and the smaller number in the array, but the problem is that you are exchanging the positions of the elements with... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.