qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
```
but not in Python 3.2:
```none
$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
File "test_zip_file_py3k.py", line 8, in <module>
for row in csv.DictReader(items_file):
File "/somedir/python3.2/csv.py", line 109, in __next__
self.fieldnames
File "/somedir/python3.2/csv.py", line 96, in fieldnames
self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)
```
The `csv` module in Python 3 wants to see a text file, but `zipfile.ZipFile.open` returns a `zipfile.ZipExtFile` that is always treated as binary data.
How does one make this work in Python 3? | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | I just noticed that [Lennart's answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786) didn't work with Python **3.1**, but it **does** work with [Python **3.2**](http://www.python.org/download/releases/3.2/). They've enhanced [`zipfile.ZipExtFile`](http://docs.python.org/py3k/library/zipfile.html#zipfile.ZipFile.open) in Python 3.2 (see [release notes](http://docs.python.org/dev/whatsnew/3.2.html#gzip-and-zipfile)). These changes appear to make `zipfile.ZipExtFile` work nicely with [`io.TextWrapper`](http://docs.python.org/py3k/library/io.html#io.TextIOWrapper).
Incidentally, it works in Python 3.1, if you uncomment the hacky lines below to monkey-patch `zipfile.ZipExtFile`, not that I would recommend this sort of hackery. I include it only to illustrate the essence of what was done in Python 3.2 to make things work nicely.
```
$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
# items_file.readable = lambda: True
# items_file.writable = lambda: False
# items_file.seekable = lambda: False
# items_file.read1 = items_file.read
items_file = io.TextIOWrapper(items_file)
for idx, row in enumerate(csv.DictReader(items_file)):
print('Processing row {0} -- row = {1}'.format(idx, row))
```
If I had to support py3k < 3.2, then I would go with the solution in [my other answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5639578#5639578).
**Update for 3.6+**
Starting w/3.6, support for `mode='U'` was removed[^1](https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.open):
>
> *Changed in version 3.6:* Removed support of `mode='U'`. Use io.TextIOWrapper for reading compressed text files in universal newlines mode.
>
>
>
Starting w/3.8, a [Path object](https://docs.python.org/3/library/zipfile.html#zipfile.Path) was added which gives us an `open()` method that we can call like the built-in `open()` function (passing `newline=''` in the case of our CSV) and we get back an io.TextIOWrapper object the csv readers accept. See Yuri's answer, [here](https://stackoverflow.com/a/70583472). | And if you just like to read a file into a string:
```
with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt') as myfile:
eggs = myfile.read().decode('UTF-8'))
``` |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
```
but not in Python 3.2:
```none
$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
File "test_zip_file_py3k.py", line 8, in <module>
for row in csv.DictReader(items_file):
File "/somedir/python3.2/csv.py", line 109, in __next__
self.fieldnames
File "/somedir/python3.2/csv.py", line 96, in fieldnames
self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)
```
The `csv` module in Python 3 wants to see a text file, but `zipfile.ZipFile.open` returns a `zipfile.ZipExtFile` that is always treated as binary data.
How does one make this work in Python 3? | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | I just noticed that [Lennart's answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5631786#5631786) didn't work with Python **3.1**, but it **does** work with [Python **3.2**](http://www.python.org/download/releases/3.2/). They've enhanced [`zipfile.ZipExtFile`](http://docs.python.org/py3k/library/zipfile.html#zipfile.ZipFile.open) in Python 3.2 (see [release notes](http://docs.python.org/dev/whatsnew/3.2.html#gzip-and-zipfile)). These changes appear to make `zipfile.ZipExtFile` work nicely with [`io.TextWrapper`](http://docs.python.org/py3k/library/io.html#io.TextIOWrapper).
Incidentally, it works in Python 3.1, if you uncomment the hacky lines below to monkey-patch `zipfile.ZipExtFile`, not that I would recommend this sort of hackery. I include it only to illustrate the essence of what was done in Python 3.2 to make things work nicely.
```
$ cat test_zip_file_py3k.py
import csv, io, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
# items_file.readable = lambda: True
# items_file.writable = lambda: False
# items_file.seekable = lambda: False
# items_file.read1 = items_file.read
items_file = io.TextIOWrapper(items_file)
for idx, row in enumerate(csv.DictReader(items_file)):
print('Processing row {0} -- row = {1}'.format(idx, row))
```
If I had to support py3k < 3.2, then I would go with the solution in [my other answer](https://stackoverflow.com/questions/5627954/py3k-how-do-you-read-a-file-inside-a-zip-file-as-text-not-bytes/5639578#5639578).
**Update for 3.6+**
Starting w/3.6, support for `mode='U'` was removed[^1](https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.open):
>
> *Changed in version 3.6:* Removed support of `mode='U'`. Use io.TextIOWrapper for reading compressed text files in universal newlines mode.
>
>
>
Starting w/3.8, a [Path object](https://docs.python.org/3/library/zipfile.html#zipfile.Path) was added which gives us an `open()` method that we can call like the built-in `open()` function (passing `newline=''` in the case of our CSV) and we get back an io.TextIOWrapper object the csv readers accept. See Yuri's answer, [here](https://stackoverflow.com/a/70583472). | Starting with Python 3.8, the zipfile module has the [Path object](https://docs.python.org/3.8/library/zipfile.html#path-objects), which we can use with its open() method to get an io.TextIOWrapper object, which can be passed to the csv readers:
```py
import csv, sys, zipfile
# Give a string path to the ZIP archive, and
# the archived file to read from
items_zipf = zipfile.Path(sys.argv[1], at='items.csv')
# Then use the open method, like you'd usually
# use the built-in open()
items_f = items_zipf.open(newline='')
# Pass the TextIO-like file to your reader as normal
for row in csv.DictReader(items_f):
print(row)
``` |
5,627,954 | A simple program for reading a CSV file inside a ZIP archive:
```py
import csv, sys, zipfile
zip_file = zipfile.ZipFile(sys.argv[1])
items_file = zip_file.open('items.csv', 'rU')
for row in csv.DictReader(items_file):
pass
```
works in Python 2.7:
```none
$ python2.7 test_zip_file_py3k.py ~/data.zip
$
```
but not in Python 3.2:
```none
$ python3.2 test_zip_file_py3k.py ~/data.zip
Traceback (most recent call last):
File "test_zip_file_py3k.py", line 8, in <module>
for row in csv.DictReader(items_file):
File "/somedir/python3.2/csv.py", line 109, in __next__
self.fieldnames
File "/somedir/python3.2/csv.py", line 96, in fieldnames
self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file
in text mode?)
```
The `csv` module in Python 3 wants to see a text file, but `zipfile.ZipFile.open` returns a `zipfile.ZipExtFile` that is always treated as binary data.
How does one make this work in Python 3? | 2011/04/11 | [
"https://Stackoverflow.com/questions/5627954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/638434/"
] | And if you just like to read a file into a string:
```
with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt') as myfile:
eggs = myfile.read().decode('UTF-8'))
``` | Starting with Python 3.8, the zipfile module has the [Path object](https://docs.python.org/3.8/library/zipfile.html#path-objects), which we can use with its open() method to get an io.TextIOWrapper object, which can be passed to the csv readers:
```py
import csv, sys, zipfile
# Give a string path to the ZIP archive, and
# the archived file to read from
items_zipf = zipfile.Path(sys.argv[1], at='items.csv')
# Then use the open method, like you'd usually
# use the built-in open()
items_f = items_zipf.open(newline='')
# Pass the TextIO-like file to your reader as normal
for row in csv.DictReader(items_f):
print(row)
``` |
55,633,118 | I would like to create an application running from CLI in windows like the awscli program.
It should be built with python script and when running that it showld perform soma action like
```
samplepgm login -u akhil -p raju
```
Like this, Could you guide me in creating this kind of cli application in Windows with python. | 2019/04/11 | [
"https://Stackoverflow.com/questions/55633118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1556933/"
] | Check out `argparse` for something basic:
<https://docs.python.org/3/library/argparse.html>
For a better library check out `Click`:
<https://click.palletsprojects.com/en/7.x/>
Others:
* <https://pypi.org/project/argh/>
* <http://docopt.org/> | I have implemented this using [Pyinstaller](https://pyinstaller.readthedocs.io/en/stable/) which will build an exe file of the python files. Will work with all versions of Python
First you need to create your python cli script for the task, then build the exe using
`pyinstaller --onefile -c -F -n Cli-latest action.py`
If you need to get inputs from users then you can do a infinite loop which will request for `input`
(Try `input("My Dev:-$ "`) |
54,435,024 | I have a 50 years data. I need to choose the combination of 30 years out of it such that the values corresponding to them reach a particular threshold value but the possible number of combination for `50C30` is coming out to be `47129212243960`.
How to calculate it efficiently?
```
Prs_100
Yrs
2012 425.189729
2013 256.382494
2014 363.309507
2015 578.728535
2016 309.311562
2017 476.388839
2018 441.479570
2019 342.267756
2020 388.133403
2021 405.007245
2022 316.108551
2023 392.193322
2024 296.545395
2025 467.388190
2026 644.588971
2027 301.086631
2028 478.492618
2029 435.868944
2030 467.464995
2031 323.465049
2032 391.201598
2033 548.911349
2034 381.252838
2035 451.175339
2036 281.921215
2037 403.840004
2038 460.514250
2039 409.134409
2040 312.182576
2041 320.246886
2042 290.163454
2043 381.432168
2044 259.228592
2045 393.841815
2046 342.999972
2047 337.491898
2048 486.139010
2049 318.278012
2050 385.919542
2051 309.472316
2052 307.756455
2053 338.596315
2054 322.508536
2055 385.428138
2056 339.379743
2057 420.428529
2058 417.143175
2059 361.643381
2060 459.861622
2061 374.359335
```
I need only that 30 years combination whose `Prs_100` mean value reaches upto a certain threshold , I can then break from calculating further outcomes.On searching SO , I found a particular approach using an `apriori` algorithm but couldn't really figure out the values of support in it.
I have used the combinations method of python
```
list(combinations(dftest.index,30))
```
but it was not working in this case.
Expected Outcome-
Let's say I found a 30 years set whose `Prs_100` mean value is more than 460 , then I'll save that 30 years output as a result and it will be my desired outcome too.
How to do it ? | 2019/01/30 | [
"https://Stackoverflow.com/questions/54435024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5617580/"
] | This is `vendor.js` is working fine:
```
require('datatables.net');
require('datatables.net-bs4');
window.JSZip = require('jszip');
require('datatables.net-buttons');
require('datatables.net-buttons/js/buttons.flash.js');
require('datatables.net-buttons/js/buttons.html5.js');
``` | If you are not using Bootstrap, you should use this:
```
var table = $('#example').DataTable( {
buttons: [
'copy', 'excel', 'pdf'
] } );
table.buttons().container()
.appendTo( $('<#elementWhereYouNeddToShowThem>', table.table().container() ) );
``` |
53,529,807 | I am trying to balance my dataset, But I am struggling in finding the right way to do it. Let me set the problem. I have a multiclass dataset with the following class weights:
```
class weight
2.0 0.700578
4.0 0.163401
3.0 0.126727
1.0 0.009294
```
As you can see the dataset is pretty unbalanced. What I would like to do is to obtain a balanced dataset in which each class is represented with the same weight.
There are a lot of questions regarding but:
* [Scikit-learn balanced subsampling](https://stackoverflow.com/questions/23455728/scikit-learn-balanced-subsampling): this subsamples can be overlapping, which for my approach is wrong. Moreover, I would like to get that using sklearn or packages that are well tested.
* [How to perform undersampling (the right way) with python scikit-learn?](https://stackoverflow.com/questions/34831676/how-to-perform-undersampling-the-right-way-with-python-scikit-learn): here they suggest to use an unbalanced dataset with a balance class weight vector, however, I need to have this balance dataset, is not a matter of which model and which weights.
* <https://github.com/scikit-learn-contrib/imbalanced-learn>: a lot of question refers to this package. Below an example on how I am trying to use it.
Here the example:
```
from imblearn.ensemble import EasyEnsembleClassifier
eec = EasyEnsembleClassifier(random_state=42, sampling_strategy='not minority', n_estimators=2)
eec.fit(data_for, label_all.loc[data_for.index,'LABEL_O_majority'])
new_data = eec.estimators_samples_
```
However, the returned indexes are all the indexes of the initial data and they are repeated `n_estimators` times.
Here the result:
```
[array([ 0, 1, 2, ..., 1196, 1197, 1198]),
array([ 0, 1, 2, ..., 1196, 1197, 1198])]
```
Finally, a lot of techniques use oversampling but would like to not use them. Only for class `1` I can tolerate oversampling, as it is very predictable.
I am wondering if really sklearn, or this contrib package do not have a function that does this. | 2018/11/28 | [
"https://Stackoverflow.com/questions/53529807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6394941/"
] | Try something like this …
```
### Exporting SQL Server table to JSON
Clear-Host
#--Establishing connection to SQL Server --#
$InstanceName = "."
$connectionString = "Server=$InstanceName;Database=msdb;Integrated Security=True;"
#--Main Query --#
$query = "SELECT * FROM sysjobs"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$result = $command.ExecuteReader()
$table = new-object "System.Data.DataTable"
$table.Load($result)
#--Exporting data to the screen --#
$table | select $table.Columns.ColumnName | ConvertTo-Json
$connection.Close()
# Results
{
"job_id": "5126aca3-1003-481c-ab36-60b45a7ee757",
"originating_server_id": 0,
"name": "syspolicy_purge_history",
"enabled": 1,
"description": "No description available.",
"start_step_id": 1,
"category_id": 0,
"owner_sid": [
1
],
"notify_level_eventlog": 0,
"notify_level_email": 0,
"notify_level_netsend": 0,
"notify_level_page": 0,
"notify_email_operator_id": 0,
"notify_netsend_operator_id": 0,
"notify_page_operator_id": 0,
"delete_level": 0,
"date_created": "\/Date(1542859767703)\/",
"date_modified": "\/Date(1542859767870)\/",
"version_number": 5
}
``` | The "rub" here is that the SQL command `FOR JSON AUTO` even with execute scalar, will truncate JSON output, and outputting to a variable with `VARCHAR(max)` will still truncate. Using SQL 2016 LocalDB bundled with Visual Studio if that matters. |
53,529,807 | I am trying to balance my dataset, But I am struggling in finding the right way to do it. Let me set the problem. I have a multiclass dataset with the following class weights:
```
class weight
2.0 0.700578
4.0 0.163401
3.0 0.126727
1.0 0.009294
```
As you can see the dataset is pretty unbalanced. What I would like to do is to obtain a balanced dataset in which each class is represented with the same weight.
There are a lot of questions regarding but:
* [Scikit-learn balanced subsampling](https://stackoverflow.com/questions/23455728/scikit-learn-balanced-subsampling): this subsamples can be overlapping, which for my approach is wrong. Moreover, I would like to get that using sklearn or packages that are well tested.
* [How to perform undersampling (the right way) with python scikit-learn?](https://stackoverflow.com/questions/34831676/how-to-perform-undersampling-the-right-way-with-python-scikit-learn): here they suggest to use an unbalanced dataset with a balance class weight vector, however, I need to have this balance dataset, is not a matter of which model and which weights.
* <https://github.com/scikit-learn-contrib/imbalanced-learn>: a lot of question refers to this package. Below an example on how I am trying to use it.
Here the example:
```
from imblearn.ensemble import EasyEnsembleClassifier
eec = EasyEnsembleClassifier(random_state=42, sampling_strategy='not minority', n_estimators=2)
eec.fit(data_for, label_all.loc[data_for.index,'LABEL_O_majority'])
new_data = eec.estimators_samples_
```
However, the returned indexes are all the indexes of the initial data and they are repeated `n_estimators` times.
Here the result:
```
[array([ 0, 1, 2, ..., 1196, 1197, 1198]),
array([ 0, 1, 2, ..., 1196, 1197, 1198])]
```
Finally, a lot of techniques use oversampling but would like to not use them. Only for class `1` I can tolerate oversampling, as it is very predictable.
I am wondering if really sklearn, or this contrib package do not have a function that does this. | 2018/11/28 | [
"https://Stackoverflow.com/questions/53529807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6394941/"
] | If you are using sql server express 2016 or later you should be able to do it on the database side using FOR JSON clause. Try something like
```
$instance = "localhost\SQLEXPRESS"
$connectionString = "Server=$Instance; Database=myDB;Integrated Security=True;"
$query = "Select * from myTable FOR JSON AUTO"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $query
$command.ExecuteScalar() | Out-File "file.json"
``` | The "rub" here is that the SQL command `FOR JSON AUTO` even with execute scalar, will truncate JSON output, and outputting to a variable with `VARCHAR(max)` will still truncate. Using SQL 2016 LocalDB bundled with Visual Studio if that matters. |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | Just a Simplified Version--
```
n,m = input().split()
n = int(n)
m = int(m)
#printing first half
for i in range(n//2):
t = int((2*i)+1)
print(('.|.'*t).center(m, '-'))
#printing middle line
print('WELCOME'.center(m,'-'))
#printing last half
for i in reversed(range(n//2)):
t = int((2*i)+1)
print(('.|.'*t).center(m, '-'))
``` | I was curious to look if there was a better solution to this hackerrank problem than mine so I landed up here.
### My solution with a single `for` loop which successfully passed all the test cases:
```
# Enter your code here. Read input from STDIN. Print output to
if __name__ == "__main__":
row_num, column_num = map(int, input().split())
num_list = []
# take user input N and M as stated in the problem: https://www.hackerrank.com/challenges/designer-door-mat
# where N are the number of rows and M are the number of coulmns
# For this explanation we assume N(row_num)=7, M(column_num)=21 for simplicity,
# the code below works on all the test cases provided by hackerrank and has cleared the submission
# this for loop is for iterating through the number of rows: 0th row to (n-1)th row
for i in range(0, row_num):
# steps to be done at each row
if i < row_num//2:
# BEFORE REACHING THE MIDDLE OF THE DOOR MAT
# we need to generate a pattern of ".|." aligned with '-' in the following manner:
# steps below will generate ".|." pattern 1, 3, 5 times
# On i=0, times = 2*(0+1)-1 = 1 => ---------.|.---------
# On i=1, times = 2*(1+1)-1 = 3 => ------.|..|..|.------
# On i=2, times = 2*(2+1)-1 = 5 => ---.|..|..|..|..|.---
times = 2*(i+1)-1
# record these numbers since we need to do the reverse when we reach the middle of the "door mat"
num_list.append(times)
# recall the assignment on Text Alignment: https://www.hackerrank.com/challenges/text-alignment/problem
# since that idea will be used below - at least this is how I look.
# Essentially, this part of code helps to eliminate the need of a for loop for iterating through each columns to generate '-'
# which would otherwise have to be used to print '-' surrounding the pattern .|. in each row
# instead we can use the column number "M" from the user input to determine how much alignment is to be done
print(('.|.'*times).center(column_num, '-'))
elif i == (row_num//2):
# UPON REACHING EXACTLY IN THE MIDDLE OF THE DOOR MAT
# once middle of the row is reached, all we need to print is "WELCOME" aligned with '-' : -------WELCOME-------
print('WELCOME'.center(column_num, '-'))
else:
# AFTER CROSSING THE MIDDLE OF THE DOOR MAT
# as soon as we cross the middle of the row, we need to print the same pattern as done above but this time in reverse order
# thankfully we have already stored the generated numbers in a list which is num_list = [1, 3, 5]
# all we need to do is just fetch them one by one in reverse order
# which is what is done by: num_list[(row_num-1)-i]
# row_num = 7, i = 4, num_list[(7-1)-4] --> num_list[2] --> 5 => ---.|..|..|..|..|.---
# row_num = 7, i = 5, num_list[(7-1)-5] --> num_list[1] --> 3 => ------.|..|..|.------
# row_num = 7, i = 6, num_list[(7-1)-6] --> num_list[0] --> 1 => ---------.|.---------
print(('.|.'*num_list[(row_num-1)-i]).center(column_num, '-'))
# DONE!
``` |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | I think the most concise answer in python3 would be the following:
```
N, M = map(int,input().split())
for i in range(1,N,2):
print((i * ".|.").center(M, "-"))
print("WELCOME".center(M,"-"))
for i in range(N-2,-1,-2):
print((i * ".|.").center(M, "-"))
``` | ```py
n, m = map(int, input().split())
str1 = ".|."
half_thickness = n-2
for i in range(1,half_thickness+1,2):
print((str1*i).center(m,"-"))
print("WELCOME".center(m,"-"))
for i in reversed(range(1,half_thickness+1,2)):
print((str1*i).center(m,"-"))
``` |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | This solution uses list comprehension. There is a tutorial on this [here](https://www.datacamp.com/community/tutorials/python-list-comprehension)
```py
# Using list comprehension
n, m = map(int, input().split())
pattern = [('.|.'*(2 * i + 1)).center(m,'-') for i in range(n//2)]
print('\n'.join(pattern + ['WELCOME'.center(m, '-')] + pattern[::-1]))
``` | I was curious to look if there was a better solution to this hackerrank problem than mine so I landed up here.
### My solution with a single `for` loop which successfully passed all the test cases:
```
# Enter your code here. Read input from STDIN. Print output to
if __name__ == "__main__":
row_num, column_num = map(int, input().split())
num_list = []
# take user input N and M as stated in the problem: https://www.hackerrank.com/challenges/designer-door-mat
# where N are the number of rows and M are the number of coulmns
# For this explanation we assume N(row_num)=7, M(column_num)=21 for simplicity,
# the code below works on all the test cases provided by hackerrank and has cleared the submission
# this for loop is for iterating through the number of rows: 0th row to (n-1)th row
for i in range(0, row_num):
# steps to be done at each row
if i < row_num//2:
# BEFORE REACHING THE MIDDLE OF THE DOOR MAT
# we need to generate a pattern of ".|." aligned with '-' in the following manner:
# steps below will generate ".|." pattern 1, 3, 5 times
# On i=0, times = 2*(0+1)-1 = 1 => ---------.|.---------
# On i=1, times = 2*(1+1)-1 = 3 => ------.|..|..|.------
# On i=2, times = 2*(2+1)-1 = 5 => ---.|..|..|..|..|.---
times = 2*(i+1)-1
# record these numbers since we need to do the reverse when we reach the middle of the "door mat"
num_list.append(times)
# recall the assignment on Text Alignment: https://www.hackerrank.com/challenges/text-alignment/problem
# since that idea will be used below - at least this is how I look.
# Essentially, this part of code helps to eliminate the need of a for loop for iterating through each columns to generate '-'
# which would otherwise have to be used to print '-' surrounding the pattern .|. in each row
# instead we can use the column number "M" from the user input to determine how much alignment is to be done
print(('.|.'*times).center(column_num, '-'))
elif i == (row_num//2):
# UPON REACHING EXACTLY IN THE MIDDLE OF THE DOOR MAT
# once middle of the row is reached, all we need to print is "WELCOME" aligned with '-' : -------WELCOME-------
print('WELCOME'.center(column_num, '-'))
else:
# AFTER CROSSING THE MIDDLE OF THE DOOR MAT
# as soon as we cross the middle of the row, we need to print the same pattern as done above but this time in reverse order
# thankfully we have already stored the generated numbers in a list which is num_list = [1, 3, 5]
# all we need to do is just fetch them one by one in reverse order
# which is what is done by: num_list[(row_num-1)-i]
# row_num = 7, i = 4, num_list[(7-1)-4] --> num_list[2] --> 5 => ---.|..|..|..|..|.---
# row_num = 7, i = 5, num_list[(7-1)-5] --> num_list[1] --> 3 => ------.|..|..|.------
# row_num = 7, i = 6, num_list[(7-1)-6] --> num_list[0] --> 1 => ---------.|.---------
print(('.|.'*num_list[(row_num-1)-i]).center(column_num, '-'))
# DONE!
``` |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | I think the most concise answer in python3 would be the following:
```
N, M = map(int,input().split())
for i in range(1,N,2):
print((i * ".|.").center(M, "-"))
print("WELCOME".center(M,"-"))
for i in range(N-2,-1,-2):
print((i * ".|.").center(M, "-"))
``` | I was curious to look if there was a better solution to this hackerrank problem than mine so I landed up here.
### My solution with a single `for` loop which successfully passed all the test cases:
```
# Enter your code here. Read input from STDIN. Print output to
if __name__ == "__main__":
row_num, column_num = map(int, input().split())
num_list = []
# take user input N and M as stated in the problem: https://www.hackerrank.com/challenges/designer-door-mat
# where N are the number of rows and M are the number of coulmns
# For this explanation we assume N(row_num)=7, M(column_num)=21 for simplicity,
# the code below works on all the test cases provided by hackerrank and has cleared the submission
# this for loop is for iterating through the number of rows: 0th row to (n-1)th row
for i in range(0, row_num):
# steps to be done at each row
if i < row_num//2:
# BEFORE REACHING THE MIDDLE OF THE DOOR MAT
# we need to generate a pattern of ".|." aligned with '-' in the following manner:
# steps below will generate ".|." pattern 1, 3, 5 times
# On i=0, times = 2*(0+1)-1 = 1 => ---------.|.---------
# On i=1, times = 2*(1+1)-1 = 3 => ------.|..|..|.------
# On i=2, times = 2*(2+1)-1 = 5 => ---.|..|..|..|..|.---
times = 2*(i+1)-1
# record these numbers since we need to do the reverse when we reach the middle of the "door mat"
num_list.append(times)
# recall the assignment on Text Alignment: https://www.hackerrank.com/challenges/text-alignment/problem
# since that idea will be used below - at least this is how I look.
# Essentially, this part of code helps to eliminate the need of a for loop for iterating through each columns to generate '-'
# which would otherwise have to be used to print '-' surrounding the pattern .|. in each row
# instead we can use the column number "M" from the user input to determine how much alignment is to be done
print(('.|.'*times).center(column_num, '-'))
elif i == (row_num//2):
# UPON REACHING EXACTLY IN THE MIDDLE OF THE DOOR MAT
# once middle of the row is reached, all we need to print is "WELCOME" aligned with '-' : -------WELCOME-------
print('WELCOME'.center(column_num, '-'))
else:
# AFTER CROSSING THE MIDDLE OF THE DOOR MAT
# as soon as we cross the middle of the row, we need to print the same pattern as done above but this time in reverse order
# thankfully we have already stored the generated numbers in a list which is num_list = [1, 3, 5]
# all we need to do is just fetch them one by one in reverse order
# which is what is done by: num_list[(row_num-1)-i]
# row_num = 7, i = 4, num_list[(7-1)-4] --> num_list[2] --> 5 => ---.|..|..|..|..|.---
# row_num = 7, i = 5, num_list[(7-1)-5] --> num_list[1] --> 3 => ------.|..|..|.------
# row_num = 7, i = 6, num_list[(7-1)-6] --> num_list[0] --> 1 => ---------.|.---------
print(('.|.'*num_list[(row_num-1)-i]).center(column_num, '-'))
# DONE!
``` |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | Just a Simplified Version--
```
n,m = input().split()
n = int(n)
m = int(m)
#printing first half
for i in range(n//2):
t = int((2*i)+1)
print(('.|.'*t).center(m, '-'))
#printing middle line
print('WELCOME'.center(m,'-'))
#printing last half
for i in reversed(range(n//2)):
t = int((2*i)+1)
print(('.|.'*t).center(m, '-'))
``` | ```
N, M = map(int, input().split())
d = ".|."
for i in range(N//2):
print((d*i).rjust(M//2-1,'-') + d + (d*i).ljust(M//2-1,'-'))
print("WELCOME".center(M,'-'))
for j in range(N//2+2,N+1):
print((d*(N-j)).rjust(M//2-1,'-') + d + (d*(N-j)).ljust(M//2-1,'-'))
``` |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | I think the most concise answer in python3 would be the following:
```
N, M = map(int,input().split())
for i in range(1,N,2):
print((i * ".|.").center(M, "-"))
print("WELCOME".center(M,"-"))
for i in range(N-2,-1,-2):
print((i * ".|.").center(M, "-"))
``` | every seems to missing the first hint . the input should be from stdin and out put should read to stdout . |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | ```py
n, m = map(int, input().split())
str1 = ".|."
half_thickness = n-2
for i in range(1,half_thickness+1,2):
print((str1*i).center(m,"-"))
print("WELCOME".center(m,"-"))
for i in reversed(range(1,half_thickness+1,2)):
print((str1*i).center(m,"-"))
``` | ```
# Enter your code here. Read input from STDIN. Print output to STDOUT
length, breadth = map(int, input().split())
def out(n,string):
for i in range(n):
print ("{}".format(string), end='')
def print_out(hyphen_count,polka_count):
out(hyphen_count, '-')
out(polka_count, '.|.')
out(hyphen_count, '-')
print ('')
hyphen_count = (breadth - 3) // 2
polka_count = 1
for i in range(length):
if i < (length // 2):
print_out(hyphen_count,polka_count)
hyphen_count = hyphen_count - 3
polka_count = polka_count + 2
elif i == (length // 2 + 1):
out((breadth - 7)//2, '-')
print ("WELCOME", end='')
out((breadth - 7)//2, '-')
print ('')
hyphen_count = hyphen_count + 3
polka_count = polka_count - 2
elif (length // 2) < i < length:
print_out(hyphen_count,polka_count)
hyphen_count = hyphen_count + 3
polka_count = polka_count - 2
print_out(hyphen_count,polka_count)
``` |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | every seems to missing the first hint . the input should be from stdin and out put should read to stdout . | I was curious to look if there was a better solution to this hackerrank problem than mine so I landed up here.
### My solution with a single `for` loop which successfully passed all the test cases:
```
# Enter your code here. Read input from STDIN. Print output to
if __name__ == "__main__":
row_num, column_num = map(int, input().split())
num_list = []
# take user input N and M as stated in the problem: https://www.hackerrank.com/challenges/designer-door-mat
# where N are the number of rows and M are the number of coulmns
# For this explanation we assume N(row_num)=7, M(column_num)=21 for simplicity,
# the code below works on all the test cases provided by hackerrank and has cleared the submission
# this for loop is for iterating through the number of rows: 0th row to (n-1)th row
for i in range(0, row_num):
# steps to be done at each row
if i < row_num//2:
# BEFORE REACHING THE MIDDLE OF THE DOOR MAT
# we need to generate a pattern of ".|." aligned with '-' in the following manner:
# steps below will generate ".|." pattern 1, 3, 5 times
# On i=0, times = 2*(0+1)-1 = 1 => ---------.|.---------
# On i=1, times = 2*(1+1)-1 = 3 => ------.|..|..|.------
# On i=2, times = 2*(2+1)-1 = 5 => ---.|..|..|..|..|.---
times = 2*(i+1)-1
# record these numbers since we need to do the reverse when we reach the middle of the "door mat"
num_list.append(times)
# recall the assignment on Text Alignment: https://www.hackerrank.com/challenges/text-alignment/problem
# since that idea will be used below - at least this is how I look.
# Essentially, this part of code helps to eliminate the need of a for loop for iterating through each columns to generate '-'
# which would otherwise have to be used to print '-' surrounding the pattern .|. in each row
# instead we can use the column number "M" from the user input to determine how much alignment is to be done
print(('.|.'*times).center(column_num, '-'))
elif i == (row_num//2):
# UPON REACHING EXACTLY IN THE MIDDLE OF THE DOOR MAT
# once middle of the row is reached, all we need to print is "WELCOME" aligned with '-' : -------WELCOME-------
print('WELCOME'.center(column_num, '-'))
else:
# AFTER CROSSING THE MIDDLE OF THE DOOR MAT
# as soon as we cross the middle of the row, we need to print the same pattern as done above but this time in reverse order
# thankfully we have already stored the generated numbers in a list which is num_list = [1, 3, 5]
# all we need to do is just fetch them one by one in reverse order
# which is what is done by: num_list[(row_num-1)-i]
# row_num = 7, i = 4, num_list[(7-1)-4] --> num_list[2] --> 5 => ---.|..|..|..|..|.---
# row_num = 7, i = 5, num_list[(7-1)-5] --> num_list[1] --> 3 => ------.|..|..|.------
# row_num = 7, i = 6, num_list[(7-1)-6] --> num_list[0] --> 1 => ---------.|.---------
print(('.|.'*num_list[(row_num-1)-i]).center(column_num, '-'))
# DONE!
``` |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | Just a Simplified Version--
```
n,m = input().split()
n = int(n)
m = int(m)
#printing first half
for i in range(n//2):
t = int((2*i)+1)
print(('.|.'*t).center(m, '-'))
#printing middle line
print('WELCOME'.center(m,'-'))
#printing last half
for i in reversed(range(n//2)):
t = int((2*i)+1)
print(('.|.'*t).center(m, '-'))
``` | ```
# Enter your code here. Read input from STDIN. Print output to STDOUT
length, breadth = map(int, input().split())
def out(n,string):
for i in range(n):
print ("{}".format(string), end='')
def print_out(hyphen_count,polka_count):
out(hyphen_count, '-')
out(polka_count, '.|.')
out(hyphen_count, '-')
print ('')
hyphen_count = (breadth - 3) // 2
polka_count = 1
for i in range(length):
if i < (length // 2):
print_out(hyphen_count,polka_count)
hyphen_count = hyphen_count - 3
polka_count = polka_count + 2
elif i == (length // 2 + 1):
out((breadth - 7)//2, '-')
print ("WELCOME", end='')
out((breadth - 7)//2, '-')
print ('')
hyphen_count = hyphen_count + 3
polka_count = polka_count - 2
elif (length // 2) < i < length:
print_out(hyphen_count,polka_count)
hyphen_count = hyphen_count + 3
polka_count = polka_count - 2
print_out(hyphen_count,polka_count)
``` |
62,537,194 | I am trying to solve a problem in HackerRank and stuck in this.
Help me to write python code for this question
Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications:
Mat size must be X. ( is an odd natural number, and is times .)
The design should have 'WELCOME' written in the center.
The design pattern should only use |, . and - characters.
Sample Designs
```
Size: 7 x 21
---------.|.---------
------.|..|..|.------
---.|..|..|..|..|.---
-------WELCOME-------
---.|..|..|..|..|.---
------.|..|..|.------
---------.|.---------
``` | 2020/06/23 | [
"https://Stackoverflow.com/questions/62537194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13766802/"
] | every seems to missing the first hint . the input should be from stdin and out put should read to stdout . | ```
if you do not want to use any align keyword then. It is complicate to understand but diff. approch.
n, m = map(int,input().split())
i = m
i = int(i-3)
f = 1
for j in range(-i,n-3,6):
j = abs(j)
if j > 0:
j = int(j/2)
print(('-'*j)+('.|.'*f)+('-'*j))
f = f+2
else:
f = f-2
break
wel = int(m-7)
wel = int(wel/2)
print(('-'*wel)+'WELCOME'+('-'*wel))
for j in range(3,i,3):
j = abs(j)
if f > 0:
print(('-'*j)+('.|.'*f)+('-'*j))
f = f-2
else:
break
``` |
73,726,556 | is there a way to launch a script running on python3 via a python2 script.
To explain briefly I need to start the python3 script when starting the python2 script.
Python3 script is a video stream server (using Flask) and have to run simultaneously from the python2 script (not python3 script first and then python2 script).
The ideal would be to get a function in the python2 script which "open a cmd window and write" it in : python3 script\_python3.py | 2022/09/15 | [
"https://Stackoverflow.com/questions/73726556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19869727/"
] | Simply you can use;
```
const requestedTime=document.querySelector(".entry-date")?.value;
```
"." uses for class names, if you have "example" class you should define it as ".example"
"?" called as Optional chaining that means if there is no object like that return "undefined" not an error
".value" uses for getting value (if there is one more object has same class it'll return error.) | There is no `getElementByClassName` method, only `getElementsByClassName`. So you would have to change your code to `.getElementsByClassName(...)[0]`.
```js
var children=document.getElementsByClassName("entry-date published")[0].textContent
console.log(children);
```
```html
<time class="updated" datetime="2022-09-14T00:54:04+05:30" itemprop="dateModified">14th September 2022</time>
<time class="entry-date published" datetime="2022-02-09T18:35:52+05:30" itemprop="datePublished">9th February 2022</time></span> <span class="byline">
``` |
73,726,556 | is there a way to launch a script running on python3 via a python2 script.
To explain briefly I need to start the python3 script when starting the python2 script.
Python3 script is a video stream server (using Flask) and have to run simultaneously from the python2 script (not python3 script first and then python2 script).
The ideal would be to get a function in the python2 script which "open a cmd window and write" it in : python3 script\_python3.py | 2022/09/15 | [
"https://Stackoverflow.com/questions/73726556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19869727/"
] | Simply you can use;
```
const requestedTime=document.querySelector(".entry-date")?.value;
```
"." uses for class names, if you have "example" class you should define it as ".example"
"?" called as Optional chaining that means if there is no object like that return "undefined" not an error
".value" uses for getting value (if there is one more object has same class it'll return error.) | There are two issues.
1. First there is a type in `getElementByClassName` it should be `getElementsByClassName` with `s`.
2. `getElementsByClassName` will return `HTMLCollection` which is `array-like`, I suggest you to use `querySelector` instead because you want to select just one element.
```js
var text = document.querySelector(".entry-date.published").textContent;
alert(text)
```
```html
<time class="updated" datetime="2022-09-14T00:54:04+05:30" itemprop="dateModified">14th September 2022</time>
<time class="entry-date published" datetime="2022-02-09T18:35:52+05:30" itemprop="datePublished">9th February 2022</time></span> <span class="byline">
``` |
73,726,556 | is there a way to launch a script running on python3 via a python2 script.
To explain briefly I need to start the python3 script when starting the python2 script.
Python3 script is a video stream server (using Flask) and have to run simultaneously from the python2 script (not python3 script first and then python2 script).
The ideal would be to get a function in the python2 script which "open a cmd window and write" it in : python3 script\_python3.py | 2022/09/15 | [
"https://Stackoverflow.com/questions/73726556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19869727/"
] | Simply you can use;
```
const requestedTime=document.querySelector(".entry-date")?.value;
```
"." uses for class names, if you have "example" class you should define it as ".example"
"?" called as Optional chaining that means if there is no object like that return "undefined" not an error
".value" uses for getting value (if there is one more object has same class it'll return error.) | To get a **2nd** child, you can use `:nth-child(2)`. So your code would be something like this:
```js
document.write(document.querySelector("time:nth-child(2)").textContent);
```
Learn more about CSS selectors on **[CSS Diner](https://flukeout.github.io/)** |
17,846,964 | I used qt Designer to generate my code. I want to have my 5 text boxes to pass 5 arguments to a python function(the function is not in this code) when the run button is released. I'm not really sure how to do this, I'm very new to pyqt.
```
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
self.runText = ""
self.scriptText = ""
self.changeText = ""
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(580, 200)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.Run = QtGui.QPushButton(self.centralwidget)
self.Run.setGeometry(QtCore.QRect(250, 150, 75, 23))
self.Run.setObjectName(_fromUtf8("Run"))
self.Script = QtGui.QLabel(self.centralwidget)
self.Script.setGeometry(QtCore.QRect(70, 10, 46, 13))
self.Script.setObjectName(_fromUtf8("Script"))
self.Hosts = QtGui.QLabel(self.centralwidget)
self.Hosts.setGeometry(QtCore.QRect(270, 10, 46, 13))
self.Hosts.setObjectName(_fromUtf8("Hosts"))
self.CHange = QtGui.QLabel(self.centralwidget)
self.CHange.setGeometry(QtCore.QRect(470, 10, 46, 13))
self.CHange.setObjectName(_fromUtf8("CHange"))
self.ScriptLine = QtGui.QLineEdit(self.centralwidget)
self.ScriptLine.setGeometry(QtCore.QRect(30, 30, 113, 20))
self.ScriptLine.setObjectName(_fromUtf8("ScriptLine"))
self.HostLine = QtGui.QLineEdit(self.centralwidget)
self.HostLine.setGeometry(QtCore.QRect(230, 30, 113, 20))
self.HostLine.setObjectName(_fromUtf8("HostLine"))
self.ChangeLine = QtGui.QLineEdit(self.centralwidget)
self.ChangeLine.setGeometry(QtCore.QRect(430, 30, 113, 20))
self.ChangeLine.setText(_fromUtf8(""))
self.ChangeLine.setObjectName(_fromUtf8("ChangeLine"))
self.Cla = QtGui.QLabel(self.centralwidget)
self.Cla.setGeometry(QtCore.QRect(260, 80, 211, 16))
self.Cla.setText(_fromUtf8(""))
self.Cla.setObjectName(_fromUtf8("Cla"))
self.Sla = QtGui.QLabel(self.centralwidget)
self.Sla.setGeometry(QtCore.QRect(260, 100, 211, 16))
self.Sla.setText(_fromUtf8(""))
self.Sla.setObjectName(_fromUtf8("Sla"))
self.Hla = QtGui.QLabel(self.centralwidget)
self.Hla.setGeometry(QtCore.QRect(260, 120, 201, 16))
self.Hla.setText(_fromUtf8(""))
self.Hla.setObjectName(_fromUtf8("Hla"))
self.Cla_2 = QtGui.QLabel(self.centralwidget)
self.Cla_2.setGeometry(QtCore.QRect(250, 60, 111, 16))
self.Cla_2.setObjectName(_fromUtf8("Cla_2"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(210, 100, 46, 13))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(210, 120, 46, 13))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setGeometry(QtCore.QRect(200, 80, 46, 13))
self.label_3.setObjectName(_fromUtf8("label_3"))
self.lineEdit = QtGui.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(30, 80, 113, 20))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.lineEdit_2 = QtGui.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(430, 80, 113, 20))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Wingdings 2"))
font.setPointSize(1)
self.lineEdit_2.setFont(font)
self.lineEdit_2.setAutoFillBackground(False)
self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
self.label_4 = QtGui.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(60, 60, 81, 16))
self.label_4.setObjectName(_fromUtf8("label_4"))
self.label_5 = QtGui.QLabel(self.centralwidget)
self.label_5.setGeometry(QtCore.QRect(460, 60, 46, 13))
self.label_5.setObjectName(_fromUtf8("label_5"))
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.ScriptLine, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.Sla.setText)
QtCore.QObject.connect(self.HostLine, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.Hla.setText)
QtCore.QObject.connect(self.ChangeLine, QtCore.SIGNAL(_fromUtf8("textChanged(QString)")), self.Cla.setText)
QtCore.QObject.connect(self.Run, QtCore.SIGNAL(_fromUtf8("released()")), self.ScriptLine.clear)
QtCore.QObject.connect(self.Run, QtCore.SIGNAL(_fromUtf8("released()")), self.HostLine.clear)
QtCore.QObject.connect(self.Run, QtCore.SIGNAL(_fromUtf8("released()")), self.ChangeLine.clear)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.Run.setText(_translate("MainWindow", "Run", None))
self.Script.setText(_translate("MainWindow", "Script", None))
self.Hosts.setText(_translate("MainWindow", "Hosts", None))
self.CHange.setText(_translate("MainWindow", "Change", None))
self.ScriptLine.setPlaceholderText(_translate("MainWindow", "Enter script file name", None))
self.HostLine.setPlaceholderText(_translate("MainWindow", "Enter Host file name", None))
self.ChangeLine.setPlaceholderText(_translate("MainWindow", "Enter Change file name", None))
self.Cla_2.setText(_translate("MainWindow", "Files to be used:", None))
self.label.setText(_translate("MainWindow", "Script:", None))
self.label_2.setText(_translate("MainWindow", "Hosts:", None))
self.label_3.setText(_translate("MainWindow", "Change:", None))
self.label_4.setText(_translate("MainWindow", "User Name", None))
self.label_5.setText(_translate("MainWindow", "Password", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
``` | 2013/07/25 | [
"https://Stackoverflow.com/questions/17846964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2616664/"
] | It's because you're doing [array dereferencing](http://schlueters.de/blog/archives/138-Features-in-PHP-trunk-Array-dereferencing.html) which is only available in PHP as of version 5.4. You have it locally but your webhost does not. That's why you should always make sure your development environment matches your production environment. | It because you're using something called array dereferencing which basically means that you can access a value from an array returned by a function direct. this is only supported in php>=5.4
To solve your issue, do something like this:
```
function pem2der($pem_data) {
$exploded = explode('-----', $pem_data);
$retStr = base64_decode(trim($exploded[2]));
return $retStr;
}
``` |
21,495,524 | How to read only the first line of ping results using python? On reading ping results with python returns multiple lines. So I like to know how to read and save just the 1st line of output? The code should not only work for ping but should work for tools like "ifstat" too, which again returns multiple line results. | 2014/02/01 | [
"https://Stackoverflow.com/questions/21495524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259921/"
] | Run the command using subprocess.check\_output, and return the first of splitlines():
```
import subprocess
subprocess.check_output(['ping', '-c1', '192.168.0.1']).splitlines()[0]
```
Andreas | You can use [`subprocess.check_output`](http://docs.python.org/2/library/subprocess.html#subprocess.check_output) and [`str.splitlines`](http://docs.python.org/2/library/stdtypes.html#str.splitlines). Here [`subprocess.check_output`](http://docs.python.org/2/library/subprocess.html#subprocess.check_output) runs the command and returns the output in a string, and the you can get the first line using `str.splitlines()[0]`.
```
>>> import subprocess
>>> out = subprocess.check_output('ping google.com -c 1', shell=True)
>>> out.splitlines()[0]
'PING google.com (173.194.36.78) 56(84) bytes of data.'
```
Note that running a untrusted command with `shell=True` can be dangerous. So, a better way would be:
```
>>> import shlex
>>> command = shlex.split('ping google.com -c 1')
>>> out = subprocess.check_output(command)
>>> out.splitlines()[0]
'PING google.com (173.194.36.65) 56(84) bytes of data.'
``` |
21,495,524 | How to read only the first line of ping results using python? On reading ping results with python returns multiple lines. So I like to know how to read and save just the 1st line of output? The code should not only work for ping but should work for tools like "ifstat" too, which again returns multiple line results. | 2014/02/01 | [
"https://Stackoverflow.com/questions/21495524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3259921/"
] | Run the command using subprocess.check\_output, and return the first of splitlines():
```
import subprocess
subprocess.check_output(['ping', '-c1', '192.168.0.1']).splitlines()[0]
```
Andreas | IF you have got output in str variable ping\_result, do split and access first in the array <http://docs.python.org/2/library/stdtypes.html#str.split>. Something like this:
first\_line = ping\_result.split('\n')[0] |
52,745,705 | so I'm trying to create an AI just for fun, but I've run into a problem. Currently when you say `Hi` it will say `Hi` back. If you say something it doesn't know, like `Hello`, it will ask you to define it, and then add it to a dictionary variable `knowledge`. Then whenever you say `Hello`, it translates it into `Hi` and will say `Hi`.
But, I want it to loop through what you've defined as `hi` and say a random thing that means `hi`. So if you tell it `Hello`, `What's Up`, and `Greetings` all mean hi, it will work to say any of them and it will return `Hi`. But how would I make it say either `Hi`, `Hello`, `What's Up`, or `Greetings` once it knows them? (just examples)
I have tried this:
```
def sayHello():
for index, item in enumerate(knowledge):
if knowledge[item] == 'HI':
print(knowledge[index] + "! I'm Orion!")
```
However I get this error:
```
Traceback (most recent call last):
File "python", line 28, in <module>
File "python", line 12, in sayHello
KeyError: 0
``` | 2018/10/10 | [
"https://Stackoverflow.com/questions/52745705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10481614/"
] | Firs thing you need is your initial dictionary with only `hi`. Then we say something to our friend. We check all the values, if our phrase is not in there, we ask for the phrase to be defined. We create a new key with that definition along with a default empty list. We then append the phase to that list. Else, we search which value list our phrase lies in and select a random word from that list.
```
from random import choice
knowledge = {'hi': ['hi']}
while True:
new = input('Say something to HAL: ')
check = list(*knowledge.values())
if new.lower() not in check:
key = input('Define {} for me: '.format(new))
knowledge.setdefault(key.lower(), [])
knowledge[key].append(new.lower())
else:
for k, v in knowledge.items():
if new.lower() in v:
print(choice(v).title())
```
>
>
> ```
> Say something to HAL: hi
> Hi
> Say something to HAL: hey
> Define hey for me: hi
> Say something to HAL: hey
> Hey
> Say something to HAL: hey
> Hi
>
> ```
>
> | You could do something like this:
```
knowledge = {"hi": ["hi"]}
```
And when your AI learns that `new_word` means the same as `"hi"`:
```
knowledge["hi"].append(new_word)
```
So now, if you now say hi to your AI (this uses the random module):
```
print(random.choice(knowledge["hi"]))
``` |
57,655,112 | I want to remove some unwanted tags/images from various repositories of azure container registry. I want to do all these programmatically. For example, what I need is:
* Authenticate with ACR
* List all repositories
* List all tags of each repository
* Remove unwanted images with particular tags.
Normally these operations can be done using Azure CLI and `az acr` commands. Maybe I can create a PowerShell script with `az acr` commands to accomplish this.
But can I do this with python? Is there something like Graph API to do these operations?
I found this API for ACR but allows to only delete entire registry. It doesn't allow repository-specific operations:
<https://learn.microsoft.com/en-us/rest/api/containerregistry/>
I tried with docker registry API:
<https://docs.docker.com/registry/spec/api/>
```
#!/bin/bash
export registry="myregistry.azurecr.io"
export user="myusername"
export password="mypassword"
export operation="/v2/_catalog"
export credentials=$(echo -n "$user:$password" | base64 -w 0)
export catalog=$(curl -s -H "Authorization: Basic $credentials" https://$registry$operation)
echo "Catalog"
echo $catalog
```
But an error is returned all the time:
```
{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":[{"Type":"registry","Name":"catalog","Action":"*"}]}]}
```
How can I properly authenticate with ACR before using Docker registry API? | 2019/08/26 | [
"https://Stackoverflow.com/questions/57655112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10259516/"
] | Would this work?
```py
>>> for header in soup.find_all('h3'):
... if header.get_text() == '64-bit deb for Ubuntu/Debian':
... header.find_next_sibling()
...
<table align="center" border="1" width="600">
:
</table>
``` | bs4 4.7.1 + you can use `:contains` with adjacent sibling (+) combinator. No need for a loop.
```
from bs4 import BeautifulSoup as bs
html = '''<h3>Windows 64-bit</h3>
<table width="600" border="1" align="center">
:
</table>
:
<h3>64-bit deb for Ubuntu/Debian</h3>
<table width="600" border="1" align="center">
:'''
soup = bs(html, 'lxml')
table = soup.select_one('h3:contains("64-bit deb for Ubuntu/Debian") + table')
``` |
62,376,571 | I want to read an array of integers from single line where size of array is given in python3.
Like read this to list.
```
5 //size
1 2 3 4 5 //input in one line
```
**while i have tried this**
```
arr = list(map(int, input().split()))
```
but dont succeed how to give size.
**Please help**
I am new to python 3 | 2020/06/14 | [
"https://Stackoverflow.com/questions/62376571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12206760/"
] | Since, the framework itself has exposed a method to do something which can be done through vanilla javascript, it certainly has added advantages. One of the scenario I can think of is using React.forwardRef which can be used for:
* Forwarding refs to DOM components
* Forwarding refs in higher-order-components
As explained in the React docs itself:
```
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
``` | you don't need react or angular to do any web development, angular and react give us a wrapper which will try to give us optimize reusable component,
all the component we are developing using react can be done by web-component but older browser don't support this.
**i am listing some of benefit of using ref in React**
1. this will be helpful for if you are using server side rendering, Be careful when you use Web API(s) since they won’t work on server-side Ex, document, Window, localStorage
2. you can easily listen to changes in state of object, you don't have
to maintain or query the DOM again and again and the framework will
do this for you. |
21,617,416 | I just started working with python + splinter
<http://splinter.cobrateam.info/docs/tutorial.html>
Unfortunately I can't get the example to work.
I cannot tell if:
```
browser.find_by_name('btnG')
```
is finding anything.
Second, I try to click the button with
button = browser.find\_by\_name('btnG').first
button.click()
This does not throw an error but NOTHING HAPPENS.
I tried again with the tutorial:
<http://f.souza.cc/2011/05/splinter-python-tool-for-acceptance.html>
and I got stuck again with the CLICK.
I am using python 2.7.3, and the latest stuff from splinter/selenium today.
How can I troublehsoot this problem (is anyone else having a problem)? | 2014/02/07 | [
"https://Stackoverflow.com/questions/21617416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1639926/"
] | When all else fails update firefox.
I upgraded my Jan 9, 2014 version and things could click! | The name of the button in my (Chromium) browser as of now is `'btnK'`. |
46,415,102 | I am running a nodejs server on port 8080, so my server can only process one request at a time.
I can see that if i send multiple requests in one single shot, new requests are queued and executed sequentially one after another.
What I am trying to find is, how do i run multiple instances/threads of this process. Example like gunicorn for python servers. Is there something similar, instead of running the nodejs server on multiple ports for each instance.
I have placed nginx infront of the node process. Is that sufficient and recommended method.
```
worker_processes auto;
worker_rlimit_nofile 1100;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
pid /var/run/nginx.pid;
http {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
server {
listen 80;
server_name localhost;
access_log /dev/null;
error_log /dev/null;
location / {
proxy_pass http://localhost:8080;
}
}
}
``` | 2017/09/25 | [
"https://Stackoverflow.com/questions/46415102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7999545/"
] | **First off, make sure your node.js process is ONLY using asynchronous I/O.** If it's not compute intensive and using asynchronous I/O, it should be able to have many different requests "in-flight" at the same time. The design of node.js is particularly good at this if your code is designed properly. If you show us the crux of what it is doing on one of these requests, we can advise more specifically on whether your server code is designed properly for best throughput.
**Second, instrument and measure, measure, measure.** Understand where your bottlenecks are in your existing node.js server and what is causing the delay or sequencing you see. Sometimes there are ways to dramatically fix/improve your bottlenecks before you start adding lots more clusters or servers.
**Third, use the [node.js cluster module](https://nodejs.org/api/cluster.html).** This will create one master node.js process that automatically balances between several child processes. You generally want to creates a cluster child for each actual CPU you have in your server computer since that will get you the most use out of your CPU.
**Fourth, if you need to scale to the point of multiple actual server computers, then you would use either a load balancer or reverse proxy such as nginx to share the load among multiple hosts.** If you had a quad core CPUs in your server, you could run a cluster with four node.js processes on it on each server computer and then use nginx to balance among the several server boxes you had.
Note that adding multiple hosts that are load balanced by nginx is the last option here, not the first option. | Like @poke said, you would use a reverse proxy and/or a load balancer in front.
But if you want a software to run multiple instances of node, with balancing and other stuffs, you should check pm2
<http://pm2.keymetrics.io/> |
46,415,102 | I am running a nodejs server on port 8080, so my server can only process one request at a time.
I can see that if i send multiple requests in one single shot, new requests are queued and executed sequentially one after another.
What I am trying to find is, how do i run multiple instances/threads of this process. Example like gunicorn for python servers. Is there something similar, instead of running the nodejs server on multiple ports for each instance.
I have placed nginx infront of the node process. Is that sufficient and recommended method.
```
worker_processes auto;
worker_rlimit_nofile 1100;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
pid /var/run/nginx.pid;
http {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
server {
listen 80;
server_name localhost;
access_log /dev/null;
error_log /dev/null;
location / {
proxy_pass http://localhost:8080;
}
}
}
``` | 2017/09/25 | [
"https://Stackoverflow.com/questions/46415102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7999545/"
] | Like @poke said, you would use a reverse proxy and/or a load balancer in front.
But if you want a software to run multiple instances of node, with balancing and other stuffs, you should check pm2
<http://pm2.keymetrics.io/> | Just a point to be added here over @sheplu, the `pm2` module uses the node cluster module under the hood. But even then, pm2 is a very good choice, as it provides various other abstractions other than node cluster.
More info on it here: <https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/> |
46,415,102 | I am running a nodejs server on port 8080, so my server can only process one request at a time.
I can see that if i send multiple requests in one single shot, new requests are queued and executed sequentially one after another.
What I am trying to find is, how do i run multiple instances/threads of this process. Example like gunicorn for python servers. Is there something similar, instead of running the nodejs server on multiple ports for each instance.
I have placed nginx infront of the node process. Is that sufficient and recommended method.
```
worker_processes auto;
worker_rlimit_nofile 1100;
events {
worker_connections 1024;
multi_accept on;
use epoll;
}
pid /var/run/nginx.pid;
http {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
server {
listen 80;
server_name localhost;
access_log /dev/null;
error_log /dev/null;
location / {
proxy_pass http://localhost:8080;
}
}
}
``` | 2017/09/25 | [
"https://Stackoverflow.com/questions/46415102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7999545/"
] | **First off, make sure your node.js process is ONLY using asynchronous I/O.** If it's not compute intensive and using asynchronous I/O, it should be able to have many different requests "in-flight" at the same time. The design of node.js is particularly good at this if your code is designed properly. If you show us the crux of what it is doing on one of these requests, we can advise more specifically on whether your server code is designed properly for best throughput.
**Second, instrument and measure, measure, measure.** Understand where your bottlenecks are in your existing node.js server and what is causing the delay or sequencing you see. Sometimes there are ways to dramatically fix/improve your bottlenecks before you start adding lots more clusters or servers.
**Third, use the [node.js cluster module](https://nodejs.org/api/cluster.html).** This will create one master node.js process that automatically balances between several child processes. You generally want to creates a cluster child for each actual CPU you have in your server computer since that will get you the most use out of your CPU.
**Fourth, if you need to scale to the point of multiple actual server computers, then you would use either a load balancer or reverse proxy such as nginx to share the load among multiple hosts.** If you had a quad core CPUs in your server, you could run a cluster with four node.js processes on it on each server computer and then use nginx to balance among the several server boxes you had.
Note that adding multiple hosts that are load balanced by nginx is the last option here, not the first option. | Just a point to be added here over @sheplu, the `pm2` module uses the node cluster module under the hood. But even then, pm2 is a very good choice, as it provides various other abstractions other than node cluster.
More info on it here: <https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/> |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | You get this error when the browser asks you to accept the certificate from a website. You can set to ignore these errors by default in order avoid these errors.
For Chrome, you need to add ***--ignore-certificate-errors*** and
***--ignore-ssl-errors*** ChromeOptions() argument:
```
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
```
For the Firefox, you need to set ***accept\_untrusted\_certs*** FirefoxProfile() option to True:
```
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
driver = webdriver.Firefox(firefox_profile=profile)
```
For the Internet Explorer, you need to set ***acceptSslCerts*** desired capability:
```
capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
capabilities['acceptSslCerts'] = True
driver = webdriver.Ie(capabilities=capabilities)
``` | I was facing the same problem. The problem was I did set `webdriver.chrome.driver` system property to chrome.exe. But one should download `chromedriver.exe` and set the file path as a value to `webdriver.chrome.driver` system property.
Once this is set, everything started working fine. |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | You get this error when the browser asks you to accept the certificate from a website. You can set to ignore these errors by default in order avoid these errors.
For Chrome, you need to add ***--ignore-certificate-errors*** and
***--ignore-ssl-errors*** ChromeOptions() argument:
```
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
```
For the Firefox, you need to set ***accept\_untrusted\_certs*** FirefoxProfile() option to True:
```
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
driver = webdriver.Firefox(firefox_profile=profile)
```
For the Internet Explorer, you need to set ***acceptSslCerts*** desired capability:
```
capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
capabilities['acceptSslCerts'] = True
driver = webdriver.Ie(capabilities=capabilities)
``` | For me it got resolved after writing code as below in chrome options, change from above answer was to include spki-list.
```
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors-spki-list')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
``` |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | You get this error when the browser asks you to accept the certificate from a website. You can set to ignore these errors by default in order avoid these errors.
For Chrome, you need to add ***--ignore-certificate-errors*** and
***--ignore-ssl-errors*** ChromeOptions() argument:
```
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
```
For the Firefox, you need to set ***accept\_untrusted\_certs*** FirefoxProfile() option to True:
```
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
driver = webdriver.Firefox(firefox_profile=profile)
```
For the Internet Explorer, you need to set ***acceptSslCerts*** desired capability:
```
capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
capabilities['acceptSslCerts'] = True
driver = webdriver.Ie(capabilities=capabilities)
``` | This error message...
```
[ERROR:ssl_client_socket_openssl.cc(855)] handshake failed; returned -1, SSL error code 1, net_error -100
```
...implies that the **handshake failed** between *ChromeDriver* and *Chrome Browser* failed at some point.
Root Cause Analysis
-------------------
This error is generated due to [net::SSLClientSocketImpl::DoHandshake](https://code.woboq.org/data/symbol.html?root=../qt5/&ref=_ZN3net19SSLClientSocketImpl11DoHandshakeEv) and [net::SSLClientSocketImpl](https://code.woboq.org/data/symbol.html?root=../qt5/&ref=net::SSLClientSocketImpl) implemented in [ssl\_client\_socket\_impl.cc
net::SSLClientSocketImpl::DoHandshake](https://code.woboq.org/qt5/qtwebengine/src/3rdparty/chromium/net/socket/ssl_client_socket_impl.cc.html) as follows:
```
int SSLClientSocketImpl::DoHandshake() {
crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
int rv = SSL_do_handshake(ssl_.get());
int net_error = OK;
if (rv <= 0) {
int ssl_error = SSL_get_error(ssl_.get(), rv);
if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
// The server supports channel ID. Stop to look one up before returning to
// the handshake.
next_handshake_state_ = STATE_CHANNEL_ID_LOOKUP;
return OK;
}
if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP &&
!ssl_config_.send_client_cert) {
return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
}
if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
DCHECK(ssl_config_.client_private_key);
DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
}
OpenSSLErrorInfo error_info;
net_error = MapLastOpenSSLError(ssl_error, err_tracer, &error_info);
if (net_error == ERR_IO_PENDING) {
// If not done, stay in this state
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
}
LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
<< ssl_error << ", net_error " << net_error;
net_log_.AddEvent(
NetLogEventType::SSL_HANDSHAKE_ERROR,
CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
}
next_handshake_state_ = STATE_HANDSHAKE_COMPLETE;
return net_error;
}
```
As per [ERROR:ssl\_client\_socket\_openssl.cc handshake failed](https://bugs.chromium.org/p/chromium/issues/detail?id=395271) the main issue is the **failure** of **handshake** when *ChromeDriver* handshakes with **SSL pages** in *Chrome*. Though *Chromium* team conducts test for *SSL handshake* through `net_unittests`, `content_tests`, and `browser_tests` but were not **exhaustive**. Some usecases are left out relying on the upstream tests.
Conclusion
----------
This error won't **interupt** the **execution** of your *Test Suite* and you can ignore this issue for the time being till it is fixed by the *Chromium Team*. |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | You get this error when the browser asks you to accept the certificate from a website. You can set to ignore these errors by default in order avoid these errors.
For Chrome, you need to add ***--ignore-certificate-errors*** and
***--ignore-ssl-errors*** ChromeOptions() argument:
```
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
```
For the Firefox, you need to set ***accept\_untrusted\_certs*** FirefoxProfile() option to True:
```
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
driver = webdriver.Firefox(firefox_profile=profile)
```
For the Internet Explorer, you need to set ***acceptSslCerts*** desired capability:
```
capabilities = webdriver.DesiredCapabilities().INTERNETEXPLORER
capabilities['acceptSslCerts'] = True
driver = webdriver.Ie(capabilities=capabilities)
``` | ssl error means that the certificate is wrong and you should not allow execution or communication with a web address that is using a wrong ssl certificate. allow means that you accept the communication with a bogus or thief address and what ever comes when you communicate with them.
So it is not browser problem or something that you should fix by reprogramming your browser to allow failed ssl certificates. |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | For me it got resolved after writing code as below in chrome options, change from above answer was to include spki-list.
```
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors-spki-list')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
``` | I was facing the same problem. The problem was I did set `webdriver.chrome.driver` system property to chrome.exe. But one should download `chromedriver.exe` and set the file path as a value to `webdriver.chrome.driver` system property.
Once this is set, everything started working fine. |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | This error message...
```
[ERROR:ssl_client_socket_openssl.cc(855)] handshake failed; returned -1, SSL error code 1, net_error -100
```
...implies that the **handshake failed** between *ChromeDriver* and *Chrome Browser* failed at some point.
Root Cause Analysis
-------------------
This error is generated due to [net::SSLClientSocketImpl::DoHandshake](https://code.woboq.org/data/symbol.html?root=../qt5/&ref=_ZN3net19SSLClientSocketImpl11DoHandshakeEv) and [net::SSLClientSocketImpl](https://code.woboq.org/data/symbol.html?root=../qt5/&ref=net::SSLClientSocketImpl) implemented in [ssl\_client\_socket\_impl.cc
net::SSLClientSocketImpl::DoHandshake](https://code.woboq.org/qt5/qtwebengine/src/3rdparty/chromium/net/socket/ssl_client_socket_impl.cc.html) as follows:
```
int SSLClientSocketImpl::DoHandshake() {
crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
int rv = SSL_do_handshake(ssl_.get());
int net_error = OK;
if (rv <= 0) {
int ssl_error = SSL_get_error(ssl_.get(), rv);
if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
// The server supports channel ID. Stop to look one up before returning to
// the handshake.
next_handshake_state_ = STATE_CHANNEL_ID_LOOKUP;
return OK;
}
if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP &&
!ssl_config_.send_client_cert) {
return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
}
if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
DCHECK(ssl_config_.client_private_key);
DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
}
OpenSSLErrorInfo error_info;
net_error = MapLastOpenSSLError(ssl_error, err_tracer, &error_info);
if (net_error == ERR_IO_PENDING) {
// If not done, stay in this state
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
}
LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
<< ssl_error << ", net_error " << net_error;
net_log_.AddEvent(
NetLogEventType::SSL_HANDSHAKE_ERROR,
CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
}
next_handshake_state_ = STATE_HANDSHAKE_COMPLETE;
return net_error;
}
```
As per [ERROR:ssl\_client\_socket\_openssl.cc handshake failed](https://bugs.chromium.org/p/chromium/issues/detail?id=395271) the main issue is the **failure** of **handshake** when *ChromeDriver* handshakes with **SSL pages** in *Chrome*. Though *Chromium* team conducts test for *SSL handshake* through `net_unittests`, `content_tests`, and `browser_tests` but were not **exhaustive**. Some usecases are left out relying on the upstream tests.
Conclusion
----------
This error won't **interupt** the **execution** of your *Test Suite* and you can ignore this issue for the time being till it is fixed by the *Chromium Team*. | I was facing the same problem. The problem was I did set `webdriver.chrome.driver` system property to chrome.exe. But one should download `chromedriver.exe` and set the file path as a value to `webdriver.chrome.driver` system property.
Once this is set, everything started working fine. |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | I was facing the same problem. The problem was I did set `webdriver.chrome.driver` system property to chrome.exe. But one should download `chromedriver.exe` and set the file path as a value to `webdriver.chrome.driver` system property.
Once this is set, everything started working fine. | ssl error means that the certificate is wrong and you should not allow execution or communication with a web address that is using a wrong ssl certificate. allow means that you accept the communication with a bogus or thief address and what ever comes when you communicate with them.
So it is not browser problem or something that you should fix by reprogramming your browser to allow failed ssl certificates. |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | This error message...
```
[ERROR:ssl_client_socket_openssl.cc(855)] handshake failed; returned -1, SSL error code 1, net_error -100
```
...implies that the **handshake failed** between *ChromeDriver* and *Chrome Browser* failed at some point.
Root Cause Analysis
-------------------
This error is generated due to [net::SSLClientSocketImpl::DoHandshake](https://code.woboq.org/data/symbol.html?root=../qt5/&ref=_ZN3net19SSLClientSocketImpl11DoHandshakeEv) and [net::SSLClientSocketImpl](https://code.woboq.org/data/symbol.html?root=../qt5/&ref=net::SSLClientSocketImpl) implemented in [ssl\_client\_socket\_impl.cc
net::SSLClientSocketImpl::DoHandshake](https://code.woboq.org/qt5/qtwebengine/src/3rdparty/chromium/net/socket/ssl_client_socket_impl.cc.html) as follows:
```
int SSLClientSocketImpl::DoHandshake() {
crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
int rv = SSL_do_handshake(ssl_.get());
int net_error = OK;
if (rv <= 0) {
int ssl_error = SSL_get_error(ssl_.get(), rv);
if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
// The server supports channel ID. Stop to look one up before returning to
// the handshake.
next_handshake_state_ = STATE_CHANNEL_ID_LOOKUP;
return OK;
}
if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP &&
!ssl_config_.send_client_cert) {
return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
}
if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
DCHECK(ssl_config_.client_private_key);
DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
}
OpenSSLErrorInfo error_info;
net_error = MapLastOpenSSLError(ssl_error, err_tracer, &error_info);
if (net_error == ERR_IO_PENDING) {
// If not done, stay in this state
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
}
LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
<< ssl_error << ", net_error " << net_error;
net_log_.AddEvent(
NetLogEventType::SSL_HANDSHAKE_ERROR,
CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
}
next_handshake_state_ = STATE_HANDSHAKE_COMPLETE;
return net_error;
}
```
As per [ERROR:ssl\_client\_socket\_openssl.cc handshake failed](https://bugs.chromium.org/p/chromium/issues/detail?id=395271) the main issue is the **failure** of **handshake** when *ChromeDriver* handshakes with **SSL pages** in *Chrome*. Though *Chromium* team conducts test for *SSL handshake* through `net_unittests`, `content_tests`, and `browser_tests` but were not **exhaustive**. Some usecases are left out relying on the upstream tests.
Conclusion
----------
This error won't **interupt** the **execution** of your *Test Suite* and you can ignore this issue for the time being till it is fixed by the *Chromium Team*. | For me it got resolved after writing code as below in chrome options, change from above answer was to include spki-list.
```
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors-spki-list')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
``` |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | For me it got resolved after writing code as below in chrome options, change from above answer was to include spki-list.
```
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors-spki-list')
options.add_argument('--ignore-ssl-errors')
driver = webdriver.Chrome(chrome_options=options)
``` | ssl error means that the certificate is wrong and you should not allow execution or communication with a web address that is using a wrong ssl certificate. allow means that you accept the communication with a bogus or thief address and what ever comes when you communicate with them.
So it is not browser problem or something that you should fix by reprogramming your browser to allow failed ssl certificates. |
37,883,759 | When running my python selenium script with Chrome driver I get about three of the below error messages every time a page loads even though everything works fine. Is there a way to suppress these messages?
>
> [24412:18772:0617/090708:ERROR:ssl\_client\_socket\_openssl.cc(1158)]
> handshake failed; returned -1, SSL error code 1, net\_error -100
>
>
> | 2016/06/17 | [
"https://Stackoverflow.com/questions/37883759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998220/"
] | This error message...
```
[ERROR:ssl_client_socket_openssl.cc(855)] handshake failed; returned -1, SSL error code 1, net_error -100
```
...implies that the **handshake failed** between *ChromeDriver* and *Chrome Browser* failed at some point.
Root Cause Analysis
-------------------
This error is generated due to [net::SSLClientSocketImpl::DoHandshake](https://code.woboq.org/data/symbol.html?root=../qt5/&ref=_ZN3net19SSLClientSocketImpl11DoHandshakeEv) and [net::SSLClientSocketImpl](https://code.woboq.org/data/symbol.html?root=../qt5/&ref=net::SSLClientSocketImpl) implemented in [ssl\_client\_socket\_impl.cc
net::SSLClientSocketImpl::DoHandshake](https://code.woboq.org/qt5/qtwebengine/src/3rdparty/chromium/net/socket/ssl_client_socket_impl.cc.html) as follows:
```
int SSLClientSocketImpl::DoHandshake() {
crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE);
int rv = SSL_do_handshake(ssl_.get());
int net_error = OK;
if (rv <= 0) {
int ssl_error = SSL_get_error(ssl_.get(), rv);
if (ssl_error == SSL_ERROR_WANT_CHANNEL_ID_LOOKUP) {
// The server supports channel ID. Stop to look one up before returning to
// the handshake.
next_handshake_state_ = STATE_CHANNEL_ID_LOOKUP;
return OK;
}
if (ssl_error == SSL_ERROR_WANT_X509_LOOKUP &&
!ssl_config_.send_client_cert) {
return ERR_SSL_CLIENT_AUTH_CERT_NEEDED;
}
if (ssl_error == SSL_ERROR_WANT_PRIVATE_KEY_OPERATION) {
DCHECK(ssl_config_.client_private_key);
DCHECK_NE(kSSLClientSocketNoPendingResult, signature_result_);
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
}
OpenSSLErrorInfo error_info;
net_error = MapLastOpenSSLError(ssl_error, err_tracer, &error_info);
if (net_error == ERR_IO_PENDING) {
// If not done, stay in this state
next_handshake_state_ = STATE_HANDSHAKE;
return ERR_IO_PENDING;
}
LOG(ERROR) << "handshake failed; returned " << rv << ", SSL error code "
<< ssl_error << ", net_error " << net_error;
net_log_.AddEvent(
NetLogEventType::SSL_HANDSHAKE_ERROR,
CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info));
}
next_handshake_state_ = STATE_HANDSHAKE_COMPLETE;
return net_error;
}
```
As per [ERROR:ssl\_client\_socket\_openssl.cc handshake failed](https://bugs.chromium.org/p/chromium/issues/detail?id=395271) the main issue is the **failure** of **handshake** when *ChromeDriver* handshakes with **SSL pages** in *Chrome*. Though *Chromium* team conducts test for *SSL handshake* through `net_unittests`, `content_tests`, and `browser_tests` but were not **exhaustive**. Some usecases are left out relying on the upstream tests.
Conclusion
----------
This error won't **interupt** the **execution** of your *Test Suite* and you can ignore this issue for the time being till it is fixed by the *Chromium Team*. | ssl error means that the certificate is wrong and you should not allow execution or communication with a web address that is using a wrong ssl certificate. allow means that you accept the communication with a bogus or thief address and what ever comes when you communicate with them.
So it is not browser problem or something that you should fix by reprogramming your browser to allow failed ssl certificates. |
29,159,657 | I am a beginner in python. I want to know if there is any in-built function or other way so I can achieve below in python 2.7:
Find all **-letter** in list and sublist and replace it with **['not',letter]**
Eg: Find all items in below list starting with - and replace them with ['not',letter]
```
Input : ['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']]
Output : ['and', ['or', ['not','S'], 'Q'], ['or', ['not','S'], 'R'], ['or', ['or', ['not','Q'], ['not','R']], ['not','S']]]
```
Can anyone suggest how to do it in python.
Thanks | 2015/03/20 | [
"https://Stackoverflow.com/questions/29159657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960970/"
] | Try a bit of recursion:
```
def change(lol):
for index,item in enumerate(lol):
if isinstance(item, list):
change(item)
elif item.startswith('-'):
lol[index] = ['not',item.split('-')[1]]
return lol
```
In action:
```
In [24]: change(['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']])
Out[24]:
['and',
['or', ['not', 'S'], 'Q'],
['or', ['not', 'S'], 'R'],
['or', ['or', ['not', 'Q'], ['not', 'R']], ['not', 'S']]]
``` | You need to use a recursive function.The `isinstance(item, str)` simply checks to see if an item is string.
```
def dumb_replace(lst):
for ind, item in enumerate(lst):
if isinstance(item, str):
if item.startswith('-'):
lst[ind] = ['not', 'letter']
else:
dumb_replace(item)
```
And:
```
dumb_replace(Input)
```
Gives:
```
['and', ['or', ['not', 'letter'], 'Q'], ['or', ['not', 'letter'], 'R'], ['or', ['or', ['not', 'letter'], ['not', 'letter']], ['not', 'letter']]]
``` |
29,159,657 | I am a beginner in python. I want to know if there is any in-built function or other way so I can achieve below in python 2.7:
Find all **-letter** in list and sublist and replace it with **['not',letter]**
Eg: Find all items in below list starting with - and replace them with ['not',letter]
```
Input : ['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']]
Output : ['and', ['or', ['not','S'], 'Q'], ['or', ['not','S'], 'R'], ['or', ['or', ['not','Q'], ['not','R']], ['not','S']]]
```
Can anyone suggest how to do it in python.
Thanks | 2015/03/20 | [
"https://Stackoverflow.com/questions/29159657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960970/"
] | Try a bit of recursion:
```
def change(lol):
for index,item in enumerate(lol):
if isinstance(item, list):
change(item)
elif item.startswith('-'):
lol[index] = ['not',item.split('-')[1]]
return lol
```
In action:
```
In [24]: change(['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']])
Out[24]:
['and',
['or', ['not', 'S'], 'Q'],
['or', ['not', 'S'], 'R'],
['or', ['or', ['not', 'Q'], ['not', 'R']], ['not', 'S']]]
``` | Based on a recipe found [here](http://arstechnica.com/civis/viewtopic.php?f=20&t=1120489):
```
def nested_list_replacer(seq, val = '-S', sub = ['not', 'letter']):
def top_kill(s):
for i in s:
if isinstance(i, str):
if i == val:
i = sub
yield i
else:
yield type(i)(top_kill(i))
return type(seq)(top_kill(seq))
l = ['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']]
print(nested_list_replacer(l, '-S'))
print(nested_list_replacer(l, '-Q'))
```
Gives:
```
['and', ['or', ['not', 'letter'], 'Q'], ['or', ['not', 'letter'], 'R'], ['or', ['or', '-Q', '-R'], ['not', 'letter']]]
['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', ['not', 'letter'], '-R'], '-S']]
``` |
29,159,657 | I am a beginner in python. I want to know if there is any in-built function or other way so I can achieve below in python 2.7:
Find all **-letter** in list and sublist and replace it with **['not',letter]**
Eg: Find all items in below list starting with - and replace them with ['not',letter]
```
Input : ['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']]
Output : ['and', ['or', ['not','S'], 'Q'], ['or', ['not','S'], 'R'], ['or', ['or', ['not','Q'], ['not','R']], ['not','S']]]
```
Can anyone suggest how to do it in python.
Thanks | 2015/03/20 | [
"https://Stackoverflow.com/questions/29159657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960970/"
] | You need to use a recursive function.The `isinstance(item, str)` simply checks to see if an item is string.
```
def dumb_replace(lst):
for ind, item in enumerate(lst):
if isinstance(item, str):
if item.startswith('-'):
lst[ind] = ['not', 'letter']
else:
dumb_replace(item)
```
And:
```
dumb_replace(Input)
```
Gives:
```
['and', ['or', ['not', 'letter'], 'Q'], ['or', ['not', 'letter'], 'R'], ['or', ['or', ['not', 'letter'], ['not', 'letter']], ['not', 'letter']]]
``` | Based on a recipe found [here](http://arstechnica.com/civis/viewtopic.php?f=20&t=1120489):
```
def nested_list_replacer(seq, val = '-S', sub = ['not', 'letter']):
def top_kill(s):
for i in s:
if isinstance(i, str):
if i == val:
i = sub
yield i
else:
yield type(i)(top_kill(i))
return type(seq)(top_kill(seq))
l = ['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', '-Q', '-R'], '-S']]
print(nested_list_replacer(l, '-S'))
print(nested_list_replacer(l, '-Q'))
```
Gives:
```
['and', ['or', ['not', 'letter'], 'Q'], ['or', ['not', 'letter'], 'R'], ['or', ['or', '-Q', '-R'], ['not', 'letter']]]
['and', ['or', '-S', 'Q'], ['or', '-S', 'R'], ['or', ['or', ['not', 'letter'], '-R'], '-S']]
``` |
14,286,200 | I'm building a website using pyramid, and I want to fetch some data from other websites. Because there may be 50+ calls of `urlopen`, I wanted to use gevent to speed things up.
Here's what I've got so far using gevent:
```
import urllib2
from gevent import monkey; monkey.patch_all()
from gevent import pool
gpool = gevent.pool.Pool()
def load_page(url):
response = urllib2.urlopen(url)
html = response.read()
response.close()
return html
def load_pages(urls):
return gpool.map(load_page, urls)
```
Running `pserve development.ini --reload` gives:
`NotImplementedError: gevent is only usable from a single thread`.
I've read that I need to monkey patch before anything else, but I'm not sure where the right place is for that. Also, is this a pserve-specific issue? Will I need to re-solve this problem when I move to [mod\_wsgi](http://docs.pylonsproject.org/projects/pyramid/en/latest/tutorials/modwsgi/index.html)? Or is there a way to handle this use-case (just urlopen) without gevent? I've seen suggestions for [requests](http://docs.python-requests.org/en/latest/) but I couldn't find an example of fetching multiple pages in the docs.
### Update 1:
I also tried eventlet from [this SO question](https://stackoverflow.com/a/2361129/312364) (almost directly copied from this eventlet [example](http://eventlet.net/doc/design_patterns.html#client-pattern)):
```
import eventlet
from eventlet.green import urllib2
def fetch(url):
return urllib2.urlopen(url).read()
def fetch_multiple(urls):
pool = eventlet.GreenPool()
return pool.imap(fetch, urls)
```
However when I call `fetch_multiple`, I'm getting `TypeError: request() got an unexpected keyword argument 'return_response'`
### Update 2:
The `TypeError` from the previous update was likely from earlier attempts to monkeypatch with gevent and not properly restarting pserve. Once I restarted everything, it works properly. Lesson learned. | 2013/01/11 | [
"https://Stackoverflow.com/questions/14286200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | There are multiple ways to do what you want:
* Create a dedicated `gevent` thread, and explicitly dispatch all of your URL-opening jobs to that thread, which will then do the gevented `urlopen` requests.
* Use threads instead of greenlets. Running 50 threads isn't going to tax any modern OS.
* Use a thread pool and a queue. There's usually not much advantage to doing 50 downloads at the same time instead of, say, 8 at a time (as your browser probably does).
* Use a different async framework instead of `gevent`, one that doesn't work by magically greenletifying your code.
* Use a library that has its own non-magic async support, like `pycurl`.
* Instead of mixing and matching incompatible frameworks, build the server around `gevent` too, or find some other framework that works for both your web-serving and your web-client needs.
You could simulate the last one without changing frameworks by loading `gevent` first, and have it monkeypatch your threads, forcing your existing threaded server framework to become a `gevent` server. But this may not work, or mostly work but occasionally fail, or work but be much slower… Really, using a framework designed to be `gevent`-friendly (or at least greenlet-friendly) is a much better idea, if that's the way you want to go.
You mentioned that others had recommended `requests`. The reason you can't find the documentation is that the built-in async code in `requests` was removed. See, [an older version](http://docs.python-requests.org/en/v0.10.6/user/advanced/#asynchronous-requests) for how it was used. It's now available as a separate library, [`grequests`](https://github.com/kennethreitz/grequests). However, it works by implicitly wrapping `requests` with `gevent`, so it will have exactly the same issues as doing so yourself.
(There are other reasons to use `requests` instead of `urllib2`, and if you want to `gevent` it it's easier to use `grequests` than to do it yourself.) | I've had similar problems with gevent when trying to deploy a web application. The thing you could do that would take the least hassle is to use a WSGI deployment that runs on gevent; examples include gUnicorn, uWSGI, or one of gevent's built-in WSGI servers. Pyramid should have a way of using an alternate deployment. If large portions of your code rely on gevent, it's easier to just use a server that runs on gevent as well.
So, basically the last bullet on the above answer. |
11,267,347 | I have been [compiling diagrams](https://stackoverflow.com/questions/11253303/how-does-the-java-runtime-environment-compare-with-the-net-framework-in-terms-o) (pun intended) in hope of understanding the different implementations of common programming languages. I understand whether code is compiled or interpreted depends on the implementation of the code, and is not an aspect of the programming language itself.
I am interested in comparing Python interpretation with direct compilation (ex of C++)
[](https://i.stack.imgur.com/YEkNm.png)
and the virtual machine model (ex Java or C#)
[](https://i.stack.imgur.com/sxsw2.png)
In light of these two diagrams above, could you please help me develop a similar flowchart of how the .py file is converted to .pyc, uses the standard libraries (I gather they are called modules) and then actually run. Many programmers on SO indicate that python as a scripting language is not executed by the CPU but rather the interpreter, but that sounds quite impossible because ultimately hardware must be doing the computation. | 2012/06/29 | [
"https://Stackoverflow.com/questions/11267347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1405543/"
] | For the reference implementation of python:
(.py) -> python (checks for .pyc) -> (.pyc) -> python (execution dynamically loads modules)
There are [other implementations](http://wiki.python.org/moin/PythonImplementations). Most notable are:
* [jython](http://www.jython.org/) which compiles (.py) to (.class) and follows the java pattern from there
* [pypy](http://pypy.org/) which employs a [JIT](http://en.wikipedia.org/wiki/Just-in-time_compilation) as it compiles (.py). the chain from there could vary (pypy could be run in cpython, jython or .net environments) | Python is technically a scripted language but it is also compiled, python source is taken from its source file and fed into the interpreter which often compiles the source to bytecode either internally and then throws it away or externally and saves it like a .pyc
Yes python is a single virtual machine that then sits ontop of the actual hardware but all python bytecode is, is a series of instructions for the pvm (python virtual machine) much like assembler for the actual CPU. |
11,267,347 | I have been [compiling diagrams](https://stackoverflow.com/questions/11253303/how-does-the-java-runtime-environment-compare-with-the-net-framework-in-terms-o) (pun intended) in hope of understanding the different implementations of common programming languages. I understand whether code is compiled or interpreted depends on the implementation of the code, and is not an aspect of the programming language itself.
I am interested in comparing Python interpretation with direct compilation (ex of C++)
[](https://i.stack.imgur.com/YEkNm.png)
and the virtual machine model (ex Java or C#)
[](https://i.stack.imgur.com/sxsw2.png)
In light of these two diagrams above, could you please help me develop a similar flowchart of how the .py file is converted to .pyc, uses the standard libraries (I gather they are called modules) and then actually run. Many programmers on SO indicate that python as a scripting language is not executed by the CPU but rather the interpreter, but that sounds quite impossible because ultimately hardware must be doing the computation. | 2012/06/29 | [
"https://Stackoverflow.com/questions/11267347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1405543/"
] | First off, this is an implementation detail. I am limiting my answer to CPython and PyPy because I am familiar with them. Answers for Jython, IronPython, and other implementations will differ - probably radically.
Python is closer to the "virtual machine model". Python code is, contrary to the statements of some too-loud-for-their-level-of-knowledge people and despite everyone (including me) conflating it in casual discussion, never interpreted. It is *always* compiled to bytecode (again, on CPython and PyPy) when it is loaded. If it was loaded because a module was imported and was loaded from a .py file, a .pyc file may be created to cache the compilation output. This step is not mandatory; you can turn it off via various means, and program execution is not affected the tiniest bit (except that the next process to load the module has to do it again). However, the compilation to bytecode is not avoidable, the bytecode is generated in memory if it is not loaded from disk.
This bytecode (the exact details of which are an implementation detail and differ between versions) is then executed, at module level, which entails building function objects, class objects, and the like. These objects simply reuse (hold a pointer to) the bytecode which is already in memory. This is unlike C++ and Java, where code and classes are set in stone during/after compilation. During execution, `import` statements may be encountered. I lack the space, time and understanding to describe the import machinery, but the short story is:
* If it was already imported once, you get that module object (another runtime construct for a thing static languages only have at compile time). A couple of builtin modules (well, all of them in PyPy, for reasons beyond the scope of this question) are already imported before any Python code runs, simply because they are so tightly integrated with the core of the interpreter and so fundamental. `sys` is such a module. Some Python code may also run beforehand, especially when you start the interactive interpreter (look up `site.py`).
* Otherwise, the module is located. The rules for this are not our concern. In the end, these rules arrive at either a Python file or a dynamically-linked piece of machine code (.DLL on Windows, though Python modules specifically use the extension .pyd but that's just a name; on unix the equivalent .so is used).
+ The module is first loaded into memory (loaded dynamically, or parsed and compiled to bytecode).
+ Then, the module is initialized. Extension modules have a special function for that which is called. Python modules are simply run, from top to bottom. In well-behaved modules this just sets up global data, defines functions and classes, and imports dependencies. Of course, anything else can also happen. The resulting module object is cached (remember step one) and returned.
All of this applies to standard library modules as well as third party modules. That's also why you can get a confusing error message if you call a script of yours just like a standard library module which you import in that script (it imports itself, albeit without crashing due to caching - one of many things I glossed over).
How the bytecode is executed (the last part of your question) differs. CPython simply interprets it, but as you correctly note, that doesn't mean it magically doesn't use the CPU. Instead, there is a large ugly loop which detects what bytecode instruction shall be executed next, and then jumps to some native code which carries out the semantics of that instruction. PyPy is more interesting; it starts off interpreting but records some stats along the way. When it decides it's worth doing so, it starts recording what the interpreter does in detail, and generates some highly optimized native code. The interpreter is still used for other parts of the Python code. Note that it's the same with many JVMs and possibly .NET, but the diagram you cite glosses over that. | Python is technically a scripted language but it is also compiled, python source is taken from its source file and fed into the interpreter which often compiles the source to bytecode either internally and then throws it away or externally and saves it like a .pyc
Yes python is a single virtual machine that then sits ontop of the actual hardware but all python bytecode is, is a series of instructions for the pvm (python virtual machine) much like assembler for the actual CPU. |
11,267,347 | I have been [compiling diagrams](https://stackoverflow.com/questions/11253303/how-does-the-java-runtime-environment-compare-with-the-net-framework-in-terms-o) (pun intended) in hope of understanding the different implementations of common programming languages. I understand whether code is compiled or interpreted depends on the implementation of the code, and is not an aspect of the programming language itself.
I am interested in comparing Python interpretation with direct compilation (ex of C++)
[](https://i.stack.imgur.com/YEkNm.png)
and the virtual machine model (ex Java or C#)
[](https://i.stack.imgur.com/sxsw2.png)
In light of these two diagrams above, could you please help me develop a similar flowchart of how the .py file is converted to .pyc, uses the standard libraries (I gather they are called modules) and then actually run. Many programmers on SO indicate that python as a scripting language is not executed by the CPU but rather the interpreter, but that sounds quite impossible because ultimately hardware must be doing the computation. | 2012/06/29 | [
"https://Stackoverflow.com/questions/11267347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1405543/"
] | First off, this is an implementation detail. I am limiting my answer to CPython and PyPy because I am familiar with them. Answers for Jython, IronPython, and other implementations will differ - probably radically.
Python is closer to the "virtual machine model". Python code is, contrary to the statements of some too-loud-for-their-level-of-knowledge people and despite everyone (including me) conflating it in casual discussion, never interpreted. It is *always* compiled to bytecode (again, on CPython and PyPy) when it is loaded. If it was loaded because a module was imported and was loaded from a .py file, a .pyc file may be created to cache the compilation output. This step is not mandatory; you can turn it off via various means, and program execution is not affected the tiniest bit (except that the next process to load the module has to do it again). However, the compilation to bytecode is not avoidable, the bytecode is generated in memory if it is not loaded from disk.
This bytecode (the exact details of which are an implementation detail and differ between versions) is then executed, at module level, which entails building function objects, class objects, and the like. These objects simply reuse (hold a pointer to) the bytecode which is already in memory. This is unlike C++ and Java, where code and classes are set in stone during/after compilation. During execution, `import` statements may be encountered. I lack the space, time and understanding to describe the import machinery, but the short story is:
* If it was already imported once, you get that module object (another runtime construct for a thing static languages only have at compile time). A couple of builtin modules (well, all of them in PyPy, for reasons beyond the scope of this question) are already imported before any Python code runs, simply because they are so tightly integrated with the core of the interpreter and so fundamental. `sys` is such a module. Some Python code may also run beforehand, especially when you start the interactive interpreter (look up `site.py`).
* Otherwise, the module is located. The rules for this are not our concern. In the end, these rules arrive at either a Python file or a dynamically-linked piece of machine code (.DLL on Windows, though Python modules specifically use the extension .pyd but that's just a name; on unix the equivalent .so is used).
+ The module is first loaded into memory (loaded dynamically, or parsed and compiled to bytecode).
+ Then, the module is initialized. Extension modules have a special function for that which is called. Python modules are simply run, from top to bottom. In well-behaved modules this just sets up global data, defines functions and classes, and imports dependencies. Of course, anything else can also happen. The resulting module object is cached (remember step one) and returned.
All of this applies to standard library modules as well as third party modules. That's also why you can get a confusing error message if you call a script of yours just like a standard library module which you import in that script (it imports itself, albeit without crashing due to caching - one of many things I glossed over).
How the bytecode is executed (the last part of your question) differs. CPython simply interprets it, but as you correctly note, that doesn't mean it magically doesn't use the CPU. Instead, there is a large ugly loop which detects what bytecode instruction shall be executed next, and then jumps to some native code which carries out the semantics of that instruction. PyPy is more interesting; it starts off interpreting but records some stats along the way. When it decides it's worth doing so, it starts recording what the interpreter does in detail, and generates some highly optimized native code. The interpreter is still used for other parts of the Python code. Note that it's the same with many JVMs and possibly .NET, but the diagram you cite glosses over that. | For the reference implementation of python:
(.py) -> python (checks for .pyc) -> (.pyc) -> python (execution dynamically loads modules)
There are [other implementations](http://wiki.python.org/moin/PythonImplementations). Most notable are:
* [jython](http://www.jython.org/) which compiles (.py) to (.class) and follows the java pattern from there
* [pypy](http://pypy.org/) which employs a [JIT](http://en.wikipedia.org/wiki/Just-in-time_compilation) as it compiles (.py). the chain from there could vary (pypy could be run in cpython, jython or .net environments) |
57,395,610 | I'm creating a REST-API for my Django-App. I have a function, that returns a list of dictionaries, that I would like to serialize and return with the rest-api.
The list (nodes\_of\_graph) looks like this:
[{'id': 50, position: {'x': 99.0, 'y': 234.0}, 'locked': True}, {'id': 62, position: {'x': 27.0, 'y': 162.0}, 'locked': True}, {'id': 64, position: {'x': 27.0, 'y': 162.0}, 'locked': True}]
Since I'm a rookie to python, django and the Restframwork, I have no clue how to attempt this. Is anybody here, who knows how to tackle that?
somehow all my attempts to serialize this list have failed. I've tried with
```py
class Graph_Node_Serializer(serializers.ListSerializer):
class Nodes:
fields = (
'id',
'position',
'locked',
)
def nodes_for_graph(request, id):
serializer = Graph_Node_Serializer(nodes_of_graph)
return Response(serializer.data)
```
The result I hope for is an response of the django-rest-framwork, containing the data in the list of dictionaries. | 2019/08/07 | [
"https://Stackoverflow.com/questions/57395610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11895645/"
] | You can register shortcut events on the page (such as MainPage).
```cs
public MainPage()
{
this.InitializeComponent();
Window.Current.Dispatcher.AcceleratorKeyActivated += AccelertorKeyActivedHandle;
}
private async void AccelertorKeyActivedHandle(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
if (args.EventType.ToString().Contains("Down"))
{
var ctrl = Window.Current.CoreWindow.GetKeyState(Windows.System.VirtualKey.Control);
if (ctrl.HasFlag(CoreVirtualKeyStates.Down))
{
if (args.VirtualKey == Windows.System.VirtualKey.Number1)
{
// add the content in textbox
}
}
}
}
```
This registration method is global registration, you can run related functions when the trigger condition is met.
Best regards. | Try writing a function in your code which is triggered when a specific set of keys are pressed together.
For example, if you want to print an emoji when the user presses "Ctrl + 1",
write a function or a piece of code which is triggered when Ctrl and 1 are pressed
together and appends the text in the multiline-textbox with the emoji at the cursor
position.
I hope this will help. |
54,040,018 | I have a requirement of testing OSPF v2 and OSPF v3 routing protocols against their respective RFCs. Scapy module for python seems interesting solution to craft OSPF packets, but are there any open source OSPF libraries over scapy that one could use to create the test cases. Would appreciate any pointers in this direction. | 2019/01/04 | [
"https://Stackoverflow.com/questions/54040018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6192859/"
] | You should use the usual `tput` program for producing the correct escape sequences for the actual terminal, rather than hard-coding specific strings (that look ugly in an Emacs compilation buffer, for example):
```
printf-bold-1:
@printf "normal text - `tput bold`bold text`tput sgr0`"
.PHONY: printf-bold-1
```
Of course, you may store the result into a Make variable, to reduce the number of subshells:
```
bold := $(shell tput bold)
sgr0 := $(shell tput sgr0)
printf-bold-1:
@printf 'normal text - $(bold)bold text$(sgr0)'
.PHONY: printf-bold-1
``` | Ok, I got it. I should have used `\033` instead of `\e` or `\x1b` :
```
printf-bold-1:
@printf "normal text - \033[1mbold text\033[0m"
```
Or, as suggested in the comments, use simple quotes instead of double quotes :
```
printf-bold-1:
@printf 'normal text - \e[1mbold text\e[0m'
```
`make printf-bold-1` now produces :
>
> normal text - **bold text**
>
>
> |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | In C, that would have been more or less legal.
In C++, functions typically shouldn't do that. You should try to use [RAII](http://en.wikipedia.org/wiki/RAII) to guarantee memory doesn't get leaked.
And now you might say "how would it leak memory, I call `delete[]` just there!", but what if an exception is thrown at the `// ...` lines?
Depending on what exactly the functions are meant to do, you have several options to consider. One obvious one is to replace the array with a vector:
```
std::vector<char> f();
std::vector<char> data = f();
int data_length = data.size();
// ...
//delete[] data;
```
and now we no longer need to explicitly delete, because the vector is allocated on the stack, and its destructor is called when it goes out of scope.
I should mention, in response to comments, that the above implies a *copy* of the vector, which could potentially be expensive. Most compilers will, if the `f` function is not too complex, optimize that copy away so this will be fine. (and if the function isn't called too often, the overhead won't matter *anyway*). But if that doesn't happen, you could instead pass an empty array to the `f` function by reference, and have `f` store its data in that instead of returning a new vector.
If the performance of returning a copy is unacceptable, another alternative would be to decouple the choice of container entirely, and use iterators instead:
```
// definition of f
template <typename iter>
void f(iter out);
// use of f
std::vector<char> vec;
f(std::back_inserter(vec));
```
Now the usual iterator operations can be used (`*out` to reference or write to the current element, and `++out` to move the iterator forward to the next element) -- and more importantly, all the standard algorithms will now work. You could use `std::copy` to copy the data to the iterator, for example. This is the approach usually chosen by the standard library (ie. it is a good idea;)) when a function has to return a sequence of data.
Another option would be to make your own object taking responsibility for the allocation/deallocation:
```
struct f { // simplified for the sake of example. In the real world, it should be given a proper copy constructor + assignment operator, or they should be made inaccessible to avoid copying the object
f(){
// do whatever the f function was originally meant to do here
size = ???
data = new char[size];
}
~f() { delete[] data; }
int size;
char* data;
};
f data;
int data_length = data.size;
// ...
//delete[] data;
```
And again we no longer need to explicitly delete because the allocation is managed by an object on the stack. The latter is obviously more work, and there's more room for errors, so if the standard vector class (or other standard library components) do the job, prefer them. This example is only if you need something customized to your situation.
The general rule of thumb in C++ is that "if you're writing a `delete` or `delete[]` outside a RAII object, you're doing it wrong. If you're writing a `new` or `new[] outside a RAII object, you're doing it wrong, unless the result is immediately passed to a smart pointer" | Use RAII (Resource Acquisition Is Initialization) design pattern.
<http://en.wikipedia.org/wiki/RAII>
[Understanding the meaning of the term and the concept - RAII (Resource Acquisition is Initialization)](https://stackoverflow.com/questions/712639/please-help-us-non-c-developers-understand-what-raii-is) |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | Your function should not return a naked pointer to some memory. The pointer, after all, can be copied. Then you have the ownership problem: Who actually owns the memory and should delete it? You also have the problem that a naked pointer might point to a single object on the stack, on the heap, or to a static object. It could also point to an array at these places. Given that all you return is a pointer, how are users supposed to know?
What you should do instead is to return an object that manages its resource in an appropriate way. (Look up RAII.) Give the fact that the resource in this case is an array of `char`, either a `std::string` or a `std::vector` seem to be best:
```
int f(std::vector<char>& buffer);
std::vector<char> buffer;
int result = f(buffer);
``` | If all `f()` does with the buffer is to return it (and its length), let it just return the length, and have the caller `new` it. If `f()` also does something with the buffer, then do as polyglot suggeted.
Of course, there may be a better design for the problem you want to solve, but for us to suggest anything would require that you provide more context. |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | In 'proper' C++ you would return an object that contains the memory allocation somewhere inside of it. Something like a std::vector. | The proper style is probably not to use a char\* but a std::vector or a std::string depending on what you are using char\* for.
About the problem of passing a parameter to be modified, instead of passing a pointer, pass a reference. In your case:
```
int f(char*&);
```
and if you follow the first advice:
```
int f(std::string&);
```
or
```
int f(std::vector<char>&);
``` |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | In C, that would have been more or less legal.
In C++, functions typically shouldn't do that. You should try to use [RAII](http://en.wikipedia.org/wiki/RAII) to guarantee memory doesn't get leaked.
And now you might say "how would it leak memory, I call `delete[]` just there!", but what if an exception is thrown at the `// ...` lines?
Depending on what exactly the functions are meant to do, you have several options to consider. One obvious one is to replace the array with a vector:
```
std::vector<char> f();
std::vector<char> data = f();
int data_length = data.size();
// ...
//delete[] data;
```
and now we no longer need to explicitly delete, because the vector is allocated on the stack, and its destructor is called when it goes out of scope.
I should mention, in response to comments, that the above implies a *copy* of the vector, which could potentially be expensive. Most compilers will, if the `f` function is not too complex, optimize that copy away so this will be fine. (and if the function isn't called too often, the overhead won't matter *anyway*). But if that doesn't happen, you could instead pass an empty array to the `f` function by reference, and have `f` store its data in that instead of returning a new vector.
If the performance of returning a copy is unacceptable, another alternative would be to decouple the choice of container entirely, and use iterators instead:
```
// definition of f
template <typename iter>
void f(iter out);
// use of f
std::vector<char> vec;
f(std::back_inserter(vec));
```
Now the usual iterator operations can be used (`*out` to reference or write to the current element, and `++out` to move the iterator forward to the next element) -- and more importantly, all the standard algorithms will now work. You could use `std::copy` to copy the data to the iterator, for example. This is the approach usually chosen by the standard library (ie. it is a good idea;)) when a function has to return a sequence of data.
Another option would be to make your own object taking responsibility for the allocation/deallocation:
```
struct f { // simplified for the sake of example. In the real world, it should be given a proper copy constructor + assignment operator, or they should be made inaccessible to avoid copying the object
f(){
// do whatever the f function was originally meant to do here
size = ???
data = new char[size];
}
~f() { delete[] data; }
int size;
char* data;
};
f data;
int data_length = data.size;
// ...
//delete[] data;
```
And again we no longer need to explicitly delete because the allocation is managed by an object on the stack. The latter is obviously more work, and there's more room for errors, so if the standard vector class (or other standard library components) do the job, prefer them. This example is only if you need something customized to your situation.
The general rule of thumb in C++ is that "if you're writing a `delete` or `delete[]` outside a RAII object, you're doing it wrong. If you're writing a `new` or `new[] outside a RAII object, you're doing it wrong, unless the result is immediately passed to a smart pointer" | Just return the pointer:
```
char * f() {
return new char[100];
}
```
Having said that, you probably do not need to mess with explicit allocation like this - instead of arrays of char, use `std::string` or `std::vector<char>` instead. |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | Your function should not return a naked pointer to some memory. The pointer, after all, can be copied. Then you have the ownership problem: Who actually owns the memory and should delete it? You also have the problem that a naked pointer might point to a single object on the stack, on the heap, or to a static object. It could also point to an array at these places. Given that all you return is a pointer, how are users supposed to know?
What you should do instead is to return an object that manages its resource in an appropriate way. (Look up RAII.) Give the fact that the resource in this case is an array of `char`, either a `std::string` or a `std::vector` seem to be best:
```
int f(std::vector<char>& buffer);
std::vector<char> buffer;
int result = f(buffer);
``` | I guess you are trying to allocate a one dimensional array. If so, you don't need to pass a pointer to pointer.
```
int f(char* &buffer)
```
should be sufficient. And the usage scenario would be:
```
char* data;
int data_length = f(data);
// ...
delete[] data;
``` |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | Use RAII (Resource Acquisition Is Initialization) design pattern.
<http://en.wikipedia.org/wiki/RAII>
[Understanding the meaning of the term and the concept - RAII (Resource Acquisition is Initialization)](https://stackoverflow.com/questions/712639/please-help-us-non-c-developers-understand-what-raii-is) | Actually, the smart thing to do would be to put that pointer in a class. That way you have better control over its destruction, and the interface is much less confusing to the user.
```
class Cookie {
public:
Cookie () : pointer (new char[100]) {};
~Cookie () {
delete[] pointer;
}
private:
char * pointer;
// Prevent copying. Otherwise we have to make these "smart" to prevent
// destruction issues.
Cookie(const Cookie&);
Cookie& operator=(const Cookie&);
};
``` |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | Your function should not return a naked pointer to some memory. The pointer, after all, can be copied. Then you have the ownership problem: Who actually owns the memory and should delete it? You also have the problem that a naked pointer might point to a single object on the stack, on the heap, or to a static object. It could also point to an array at these places. Given that all you return is a pointer, how are users supposed to know?
What you should do instead is to return an object that manages its resource in an appropriate way. (Look up RAII.) Give the fact that the resource in this case is an array of `char`, either a `std::string` or a `std::vector` seem to be best:
```
int f(std::vector<char>& buffer);
std::vector<char> buffer;
int result = f(buffer);
``` | The proper style is probably not to use a char\* but a std::vector or a std::string depending on what you are using char\* for.
About the problem of passing a parameter to be modified, instead of passing a pointer, pass a reference. In your case:
```
int f(char*&);
```
and if you follow the first advice:
```
int f(std::string&);
```
or
```
int f(std::vector<char>&);
``` |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | In 'proper' C++ you would return an object that contains the memory allocation somewhere inside of it. Something like a std::vector. | Actually, the smart thing to do would be to put that pointer in a class. That way you have better control over its destruction, and the interface is much less confusing to the user.
```
class Cookie {
public:
Cookie () : pointer (new char[100]) {};
~Cookie () {
delete[] pointer;
}
private:
char * pointer;
// Prevent copying. Otherwise we have to make these "smart" to prevent
// destruction issues.
Cookie(const Cookie&);
Cookie& operator=(const Cookie&);
};
``` |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | Your function should not return a naked pointer to some memory. The pointer, after all, can be copied. Then you have the ownership problem: Who actually owns the memory and should delete it? You also have the problem that a naked pointer might point to a single object on the stack, on the heap, or to a static object. It could also point to an array at these places. Given that all you return is a pointer, how are users supposed to know?
What you should do instead is to return an object that manages its resource in an appropriate way. (Look up RAII.) Give the fact that the resource in this case is an array of `char`, either a `std::string` or a `std::vector` seem to be best:
```
int f(std::vector<char>& buffer);
std::vector<char> buffer;
int result = f(buffer);
``` | Just return the pointer:
```
char * f() {
return new char[100];
}
```
Having said that, you probably do not need to mess with explicit allocation like this - instead of arrays of char, use `std::string` or `std::vector<char>` instead. |
1,171,926 | I'm trying to program a pyramid like score system for an ARG game and have come up with a problem. When users get into the game they start a new "pyramid" but if one start the game with a referer code from another player they become a child of this user and then kick points up the ladder.
The issue here is not the point calculation, I've gotten that right with some good help from you guys, but if a user gets more point that it parent, they should switch places in the ladder. So that a users parent becomes it's child and so on.
The python code I have now doesnt work proper, and I dont really know why.
```
def verify_parents(user):
"""
This is a recursive function that checks to see if any of the parents
should bump up because they got more points than its parent.
"""
from rottenetter.accounts.models import get_score
try:
parent = user.parent
except:
return False
else:
# If this players score is greater than its parent
if get_score(user) > get_score(parent):
# change parent
user.parent = parent.parent
user.save()
# change parent's parent to current profile
parent.parent = user
parent.save()
verify_parents(parent)
```
In my mind this should work, if a user has a parent, check to see if the user got more points than its parent, if so, set the users parent to be the parents parent, and set the parents parent to be the user, and then they have switched places. And after that, call the same function with the parent as a target so that it can check it self, and then continue up the ladder.
But this doesnt always work, in some cases people aren't bumbed to the right position of some reason.
Edit:
When one users steps up or down a step in the ladder, it's childs move with him so they still relate to the same parent, unless they to get more points and step up. So it should be unecessary to anything with the parents shouldn't it? | 2009/07/23 | [
"https://Stackoverflow.com/questions/1171926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42546/"
] | The proper style is probably not to use a char\* but a std::vector or a std::string depending on what you are using char\* for.
About the problem of passing a parameter to be modified, instead of passing a pointer, pass a reference. In your case:
```
int f(char*&);
```
and if you follow the first advice:
```
int f(std::string&);
```
or
```
int f(std::vector<char>&);
``` | I guess you are trying to allocate a one dimensional array. If so, you don't need to pass a pointer to pointer.
```
int f(char* &buffer)
```
should be sufficient. And the usage scenario would be:
```
char* data;
int data_length = f(data);
// ...
delete[] data;
``` |
52,019,077 | ```
from bs4 import BeautifulSoup
import requests
url = "https://www.104.com.tw/job/?jobno=5mjva&jobsource=joblist_b_relevance"
r = requests.get(url)
r.encoding = "utf-8"
print(r.text)
```
I want to reach the content in div ("class=content")(p)
but when I print the r.text out there's a big part disappear.
But I also found if I open a text file and write it in, it would be just right in the notebook
```
doc = open("file104.txt", "w", encoding="utf-8")
doc.write(r.text)
doc.close()
```
I guess it might be the encoding problem? But it is still not working after I encoded in utf-8.
Sorry everbody!
===========================================================================
I finally found the problem which comes from the Ipython IDLE, everthing would be fine if I run the code in powershell, I should try this earlier....
But still wanna know why cause this problem! | 2018/08/25 | [
"https://Stackoverflow.com/questions/52019077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10273637/"
] | in your table you could have a field for count. When use login and login is wrong, add + 1 to your count. When user login successfuly, reset the count. If count meet +3, reset the code. | i understand from your question that you need the logic on how to make the random\_code expired after inserting from interacted users on your website 3 times ,assuming that , as long as the code is not expired he will be able to do his inserts and you may load it on your page .
i would do that through database queries .
**Please follow this instruction listed below**
**instructions :**
while your php page generate the random code , you may store it in database table with a auto reference key , for instance ,
assuming that you have randomly generated a code as below :
"Some random code here"
the above code which was generated by your php page have load it from mysql table called Random\_Generated\_Code , i would go to edit this table and add new field in it and call it generated\_Code\_Reference\_Key ( could be auto serial number ) to avoid any duplication as well make additional field called Expire\_Flag which we are going to use later.
so once your page have loaded the above example code , you should retrieve the generated\_Code\_Reference\_Key along with it and keep it in hidden variable on your page
it should be loaded on the page based on expire\_Flag value as a condition
select generated\_code from Random\_Generated\_Code where expire\_flag = ""
now once the user try to insert that generated code , in each time he insert it define another table in your database lets call it ( inserted\_Codes\_by\_users) and store in it the username of whoever is doing that on your website as well you have to store the generated\_Code\_Reference\_Key which we are storing in hidden variable as mentioned earlier to indicate which code was used while inserting.
now during page load or any event you want you can find expired code by make select statement from the inserted\_Codes\_by\_users table
select count(generated\_Code\_Reference\_Key) as The\_Code\_Used\_Qty from inserted\_Codes\_by\_users where username = username\_of\_that\_user
so you can get how many times this user have inserted this specific generated\_random\_Code
retrieve result of the query in a variable and to make sense lets call it The\_Code\_Used\_Qty and make if condition on page load event or any event you like
if The\_Code\_Used\_Qty = 3 then
fire update statement to first table which loaded that random generated code
and update the expire\_flag field for that code (Expired) based on reference\_key
update Random\_Generated\_Code set expire\_Flag = "expired" where generated\_Code\_Reference\_Key = "generated\_Code\_Reference\_Key" << the one u stored in hidden variable
end if
so now that will get you directly to the point of why we are loading random\_generated\_code table first time with that condition expire\_flag = ""
as it will only retrieve the codes which is not expired .
hopefully this will help you to achieve what you want .
good luck and let me know if you need any help or if you face any confusion while reading my answer.
Good luck . |
25,165,500 | I'm trying to get zipline working with non-US, intraday data, that I've loaded into a pandas DataFrame:
```
BARC HSBA LLOY STAN
Date
2014-07-01 08:30:00 321.250 894.55 112.105 1777.25
2014-07-01 08:32:00 321.150 894.70 112.095 1777.00
2014-07-01 08:34:00 321.075 894.80 112.140 1776.50
2014-07-01 08:36:00 321.725 894.80 112.255 1777.00
2014-07-01 08:38:00 321.675 894.70 112.290 1777.00
```
I've followed moving-averages tutorial [here](http://nbviewer.ipython.org/github/quantopian/zipline/blob/master/docs/tutorial.ipynb), replacing "AAPL" with my own symbol code, and the historical calls with "1m" data instead of "1d".
Then I do the final call using `algo_obj.run(DataFrameSource(mydf))`, where `mydf` is the dataframe above.
However there are all sorts of problems arising related to [TradingEnvironment](https://github.com/quantopian/zipline/blob/master/zipline/finance/trading.py). According to the source code:
```
# This module maintains a global variable, environment, which is
# subsequently referenced directly by zipline financial
# components. To set the environment, you can set the property on
# the module directly:
# from zipline.finance import trading
# trading.environment = TradingEnvironment()
#
# or if you want to switch the environment for a limited context
# you can use a TradingEnvironment in a with clause:
# lse = TradingEnvironment(bm_index="^FTSE", exchange_tz="Europe/London")
# with lse:
# the code here will have lse as the global trading.environment
# algo.run(start, end)
```
However, using the context doesn't seem to fully work. I still get errors, for example stating that my timestamps are before the market open (and indeed, looking at `trading.environment.open_and_close` the times are for the US market.
**My question is, has anybody managed to use zipline with non-US, intra-day data?** Could you point me to a resource and ideally example code on how to do this?
n.b. I've seen there are some [tests](https://github.com/quantopian/zipline/blob/master/tests/test_tradingcalendar.py) on github that seem related to the trading calendars (tradincalendar\_lse.py, tradingcalendar\_tse.py , etc) - but this appears to only handle data at the daily level. I would need to fix:
* open/close times
* reference data for the benchmark
* and probably more ... | 2014/08/06 | [
"https://Stackoverflow.com/questions/25165500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2196034/"
] | I've got this working after fiddling around with the tutorial notebook. Code sample below. It's using the DF `mid`, as described in the original question. A few points bear mentioning:
1. **Trading Calendar** I create one manually and assign to `trading.environment`, by using non\_working\_days in *tradingcalendar\_lse.py*. Alternatively you could create one that fits your data exactly (however could be a problem for out-of-sample data). There are two fields that you need to define: `trading_days` and `open_and_closes`.
2. **sim\_params** There is a problem with the default start/end values because they aren't timezone aware. So you *must* create a sim\_params object and pass start/end parameters with a timezone.
3. Also, `run()` must be called with the argument overwrite\_sim\_params=False as `calculate_first_open`/`close` raise timestamp errors.
I should mention that it's also possible to pass pandas Panel data, with fields open,high,low,close,price and volume in the minor\_axis. But in this case, the former fields are mandatory - otherwise errors are raised.
Note that this code only produces a *daily* summary of the performance. I'm sure there must be a way to get the result at a minute resolution (I thought this was set by `emission_rate`, but apparently it's not). If anybody knows please comment and I'll update the code.
Also, not sure what the api call is to call 'analyze' (i.e. when using `%%zipline` magic in IPython, as in the tutorial, the `analyze()` method gets automatically called. How do I do this manually?)
```py
import pytz
from datetime import datetime
from zipline.algorithm import TradingAlgorithm
from zipline.utils import tradingcalendar
from zipline.utils import tradingcalendar_lse
from zipline.finance.trading import TradingEnvironment
from zipline.api import order_target, record, symbol, history, add_history
from zipline.finance import trading
def initialize(context):
# Register 2 histories that track daily prices,
# one with a 100 window and one with a 300 day window
add_history(10, '1m', 'price')
add_history(30, '1m', 'price')
context.i = 0
def handle_data(context, data):
# Skip first 30 mins to get full windows
context.i += 1
if context.i < 30:
return
# Compute averages
# history() has to be called with the same params
# from above and returns a pandas dataframe.
short_mavg = history(10, '1m', 'price').mean()
long_mavg = history(30, '1m', 'price').mean()
sym = symbol('BARC')
# Trading logic
if short_mavg[sym] > long_mavg[sym]:
# order_target orders as many shares as needed to
# achieve the desired number of shares.
order_target(sym, 100)
elif short_mavg[sym] < long_mavg[sym]:
order_target(sym, 0)
# Save values for later inspection
record(BARC=data[sym].price,
short_mavg=short_mavg[sym],
long_mavg=long_mavg[sym])
def analyze(context,perf) :
perf["pnl"].plot(title="Strategy P&L")
# Create algorithm object passing in initialize and
# handle_data functions
# This is needed to handle the correct calendar. Assume that market data has the right index for tradeable days.
# Passing in env_trading_calendar=tradingcalendar_lse doesn't appear to work, as it doesn't implement open_and_closes
from zipline.utils import tradingcalendar_lse
trading.environment = TradingEnvironment(bm_symbol='^FTSE', exchange_tz='Europe/London')
#trading.environment.trading_days = mid.index.normalize().unique()
trading.environment.trading_days = pd.date_range(start=mid.index.normalize()[0],
end=mid.index.normalize()[-1],
freq=pd.tseries.offsets.CDay(holidays=tradingcalendar_lse.non_trading_days))
trading.environment.open_and_closes = pd.DataFrame(index=trading.environment.trading_days,columns=["market_open","market_close"])
trading.environment.open_and_closes.market_open = (trading.environment.open_and_closes.index + pd.to_timedelta(60*7,unit="T")).to_pydatetime()
trading.environment.open_and_closes.market_close = (trading.environment.open_and_closes.index + pd.to_timedelta(60*15+30,unit="T")).to_pydatetime()
from zipline.utils.factory import create_simulation_parameters
sim_params = create_simulation_parameters(
start = pd.to_datetime("2014-07-01 08:30:00").tz_localize("Europe/London").tz_convert("UTC"), #Bug in code doesn't set tz if these are not specified (finance/trading.py:SimulationParameters.calculate_first_open[close])
end = pd.to_datetime("2014-07-24 16:30:00").tz_localize("Europe/London").tz_convert("UTC"),
data_frequency = "minute",
emission_rate = "minute",
sids = ["BARC"])
algo_obj = TradingAlgorithm(initialize=initialize,
handle_data=handle_data,
sim_params=sim_params)
# Run algorithm
perf_manual = algo_obj.run(mid,overwrite_sim_params=False) # overwrite == True calls calculate_first_open[close] (see above)
``` | @Luciano
You can add `analyze(None, perf_manual)`at the end of your code for automatically running the analyze process. |
54,119,766 | I am using python2.7
I have a json i pull that is always changing when i request it.
I need to pull out `Animal_Target_DisplayNam`e under Term7 Under Relation6 in my dict.
The problem is sometimes the object Relation6 is in another part of the Json, it could be leveled deeper or in another order.
I am trying to create code that can just export the values of the key `Animal_Target_DisplayName` but nothing is working. It wont even loop down the nested dict.
Now this can work if i just pull it out using something like `['view']['Term0'][0]['Relation6']` but remember the JSON is never returned in the same structure.
Code i am using to get the values of the key `Animal_Target_DisplayName` but it doesnt seem to loop through my dict and find all the values with that key.
```
array = []
for d in dict.values():
row = d['Animal_Target_DisplayName']
array.append(row)
```
JSON Below:
```
dict = {
"view":{
"Term0":[
{
"Id":"b0987b91-af12-4fe3-a56f-152ac7a4d84d",
"DisplayName":"Dog",
"FullName":"Dog",
"AssetType1":[
{
"AssetType_Id":"00000000-0000-0000-0000-000000031131",
}
]
},
{
"Id":"ee74a59d-fb74-4052-97ba-9752154f015d",
"DisplayName":"Dog2",
"FullName":"Dog",
"AssetType1":[
{
"AssetType_Id":"00000000-0000-0000-0000-000000031131",
}
]
},
{
"Id":"eb548eae-da6f-41e8-80ea-7e9984f56af6",
"DisplayName":"Dog3",
"FullName":"Dog3",
"AssetType1":[
{
"AssetType_Id":"00000000-0000-0000-0000-000000031131",
}
]
},
{
"Id":"cfac6dd4-0efa-4417-a2bf-0333204f8a42",
"DisplayName":"Animal Set",
"FullName":"Animal Set",
"AssetType1":[
{
"AssetType_Id":"00000000-0000-0000-0001-000400000001",
}
],
"StringAttribute2":[
{
"StringAttribute_00000000-0000-0000-0000-000000003114_Id":"00a701a8-be4c-4b76-a6e5-3b0a4085bcc8",
"StringAttribute_00000000-0000-0000-0000-000000003114_Value":"Desc"
}
],
"StringAttribute3":[
{
"StringAttribute_00000000-0000-0000-0000-000000000262_Id":"a81adfb4-7528-4673-8c95-953888f3b43a",
"StringAttribute_00000000-0000-0000-0000-000000000262_Value":"meow"
}
],
"BooleanAttribute4":[
{
"BooleanAttribute_00000000-0000-0000-0001-000500000001_Id":"932c5f97-c03f-4a1a-a0c5-a518f5edef5e",
"BooleanAttribute_00000000-0000-0000-0001-000500000001_Value":"true"
}
],
"SingleValueListAttribute5":[
{
"SingleValueListAttribute_00000000-0000-0000-0001-000500000031_Id":"ef51dedd-6f25-4408-99a6-5a6cfa13e198",
"SingleValueListAttribute_00000000-0000-0000-0001-000500000031_Value":"Blah"
}
],
"Relation6":[
{
"Animal_Id":"2715ca09-3ced-4b74-a418-cef4a95dddf1",
"Term7":[
{
"Animal_Target_Id":"88fd0090-4ea8-4ae6-b7f0-1b13e5cf3d74",
"Animal_Target_DisplayName":"Animaltheater",
"Animal_Target_FullName":"Animaltheater"
}
]
},
{
"Animal_Id":"6068fe78-fc8e-4542-9aee-7b4b68760dcd",
"Term7":[
{
"Animal_Target_Id":"4e87a614-2a8b-46c0-90f3-8a0cf9bda66c",
"Animal_Target_DisplayName":"Animaltitle",
"Animal_Target_FullName":"Animaltitle"
}
]
},
{
"Animal_Id":"754ec0e6-19b6-4b6b-8ba1-573393268257",
"Term7":[
{
"Animal_Target_Id":"a8986ed5-3ec8-44f3-954c-71cacb280ace",
"Animal_Target_DisplayName":"Animalcustomer",
"Animal_Target_FullName":"Animalcustomer"
}
]
},
{
"Animal_Id":"86b3ffd1-4d54-4a98-b25b-369060651bd6",
"Term7":[
{
"Animal_Target_Id":"89d02067-ebe8-4b87-9a1f-a6a0bdd40ec4",
"Animal_Target_DisplayName":"Animalfact_transaction",
"Animal_Target_FullName":"Animalfact_transaction"
}
]
},
{
"Animal_Id":"ea2e1b76-f8bc-46d9-8ebc-44ffdd60f213",
"Term7":[
{
"Animal_Target_Id":"e398cd32-1e73-46bd-8b8f-d039986d6de0",
"Animal_Target_DisplayName":"Animalfact_transaction",
"Animal_Target_FullName":"Animalfact_transaction"
}
]
}
],
"Relation10":[
{
"TargetRelation_b8b178ff-e957-47db-a4e7-6e5b789d6f03_Id":"aff80bd0-a282-4cf5-bdcc-2bad35ddec1d",
"Term11":[
{
"AnimalId":"3ac22167-eb91-469a-9d94-315aa301f55a",
"AnimalDisplayName":"Animal",
"AnimalFullName":"Animal"
}
]
}
],
"Tag12":[
{
"Tag_Id":"75968ea6-4c9f-43c9-80f7-dfc41b24ec8f",
"Tag_Name":"AnimalAnimaltitle"
},
{
"Tag_Id":"b1adbc00-aeef-415b-82b6-a3159145c60d",
"Tag_Name":"Animal2"
},
{
"Tag_Id":"5f78e4dc-2b37-41e0-a0d3-cec773af2397",
"Tag_Name":"AnimalDisplayName"
}
]
}
]
}
}
```
The output i am trying to get is a list of all the values from key `Animal_Target_DisplayName` like this `['Animaltheater','Animaltitle', 'Animalcustomer', 'Animalfact_transaction', 'Animalfact_transaction']` but we need to remember the nested structure of this json always changes but the keys for it are always the same. | 2019/01/09 | [
"https://Stackoverflow.com/questions/54119766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6856433/"
] | I guess your only option is running through the entire dict and get the values of `Animal_Target_DisplayName` key, I propose the following recursive solution:
```py
def run_json(dict_):
animal_target_sons = []
if type(dict_) is list:
for element in dict_:
animal_target_sons.append(run_json(element))
elif type(dict_) is dict:
for key in dict_:
if key=="Animal_Target_DisplayName":
animal_target_sons.append([dict_[key]])
else:
animal_target_sons.append(run_json(dict_[key]))
return [x for sublist in animal_target_sons for x in sublist]
run_json(dict_)
```
Then calling `run_json` returns a list with what you want. By the way, I recommend you to rename your json from `dict` to, for example `dict_`, since `dict` is a reserved word of Python for the dictionary type. | Since you're getting JSON, why not make use of the json module? That will do the parsing for you and allow you to use dictionary functions+features to get the information you need.
```
#!/usr/bin/python2.7
from __future__ import print_function
import json
# _somehow_ get your JSON in as a string. I'm calling it "jstr" for this
# example.
# Use the module to parse it
jdict = json.loads(jstr)
# our dict has keys...
# view -> Term0 -> keys-we're-interested-in
templist = jdict["view"]["Term0"]
results = {}
for _el in range(len(templist)):
if templist[_el]["FullName"] == "Animal Set":
# this is the one we're interested in - and it's another list
moretemp = templist[_el]["Relation6"]
for _k in range(len(moretemp)):
term7 = moretemp[_k]["Term7"][0]
displayName = term7["Animal_Target_DisplayName"]
fullName = term7["Animal_Target_FullName"]
results[fullName] = displayName
print("{0}".format(results))
```
Then you can dump the `results` dict plain, or with pretty-printing:
```
>>> print(json.dumps(results, indent=4))
{
"Animaltitle2": "Animaltitle2",
"Animalcustomer3": "Animalcustomer3",
"Animalfact_transaction4": "Animalfact_transaction4",
"Animaltheater1": "Animaltheater1"
}
``` |
64,311,719 | I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element.
My script is as follows:
```
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)
lhip = '13.14.15.16'
user = 'username'
paswd = 'password'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--lh_ip', type=str, metavar='', default=lhip, help='Public IP of VM' )
parser.add_argument('-u', '--usr', type=str, metavar='', default=user, help='Username for VM')
parser.add_argument('-p', '--pwd', type=str, metavar='', default=paswd, help='Password for VM')
args = parser.parse_args()
lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
if driver.title == 'Privacy error':
driver.find_element_by_id('details-button').click()
driver.find_element_by_id('proceed-link').click()
except:
pass
driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
if driver.find_element_by_tag_name('span'):
print('Login Failed')
except:
print('Login Successful')
driver.close()
```
The python script works fine on my system when used without the chrome\_options. However upon adding them to run in headless mode, it fails with the following output:
```
[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
driver.find_element_by_id('username').send_keys(args.usr)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
(Session info: headless chrome=85.0.4183.121)
```
Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked.
Also why is it saying "css selector" when I have only used id for username? | 2020/10/12 | [
"https://Stackoverflow.com/questions/64311719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9953181/"
] | If the script is working perfectly fine without headless mode, probably there is issue with the window size. Along with specifying --no-sandbox option, try changing the window size passed to the webdriver
chrome\_options.add\_argument('--window-size=1920,1080')
This window size worked in my case.
Even if this dosen't work you might need to add wait timers as answered before as rendering in headless mode works in a different way as compared to a browser in UI mode.
Ref for rendering in headless mode - <https://www.toolsqa.com/selenium-webdriver/selenium-headless-browser-testing/> | I would refactor code in a way to wait until elements will be present on a web page:
```
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID, 'username'))).send_keys(args.usr)
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID,'password'))).send_keys(args.pwd)
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID, 'login-btn'))).click()
```
Generally usage of `WebDriverWait` in combination with some condition should be preferred to implicit waits or `time.sleep()`. [Here](https://stackoverflow.com/a/28067495/2792888) is explained in details why.
Other thing to double check are whether elements have the IDs used for search and that these elements aren't located within an iframe. |
64,311,719 | I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element.
My script is as follows:
```
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)
lhip = '13.14.15.16'
user = 'username'
paswd = 'password'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--lh_ip', type=str, metavar='', default=lhip, help='Public IP of VM' )
parser.add_argument('-u', '--usr', type=str, metavar='', default=user, help='Username for VM')
parser.add_argument('-p', '--pwd', type=str, metavar='', default=paswd, help='Password for VM')
args = parser.parse_args()
lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
if driver.title == 'Privacy error':
driver.find_element_by_id('details-button').click()
driver.find_element_by_id('proceed-link').click()
except:
pass
driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
if driver.find_element_by_tag_name('span'):
print('Login Failed')
except:
print('Login Successful')
driver.close()
```
The python script works fine on my system when used without the chrome\_options. However upon adding them to run in headless mode, it fails with the following output:
```
[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
driver.find_element_by_id('username').send_keys(args.usr)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
(Session info: headless chrome=85.0.4183.121)
```
Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked.
Also why is it saying "css selector" when I have only used id for username? | 2020/10/12 | [
"https://Stackoverflow.com/questions/64311719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9953181/"
] | I had the same issue, it was initially working, though after an update from a website that we were using Selenium on, it stopped working in headless mode, though kept on working in non headless. After 2 days of researching the deepest and darkest depths of the web and a lot of trial and error, finally found what the issue was.
I tried all the methods outlined on the web and more, though nothing worked until I found this.
In headless chrome mode, the user agent is something like this:
Mozilla/5.0 (X11; Linux x86\_64) AppleWebKit/537.36 (KHTML, like Gecko) **HeadlessChrome**/60.0.3112.50 Safari/537.36
The service provider updated their code to identify the HeadlessChrome part and would cause the tab to crash and in turn, destroying the Selenium user session.
Which lead to the issue firing above in one of the exceptions.
To solve this, I used a plugin called fake\_headers (<https://github.com/diwu1989/Fake-Headers>):
```
from fake_headers import Headers
header = Headers(
browser="chrome", # Generate only Chrome UA
os="win", # Generate only Windows platform
headers=False # generate misc headers
)
customUserAgent = header.generate()['User-Agent']
options.add_argument(f"user-agent={customUserAgent}")
```
Though this was only half the solution as I only wanted Windows and Chrome headers and the fake\_headers module has not not include the latest Chrome browsers and has a lot of older versions of Chrome in the list as can be seen in this file <https://github.com/diwu1989/Fake-Headers/blob/master/fake_headers/browsers.py>. The particular site I was running Selenium had certain features that only worked on newer versions of Chrome, so when an older version of Chrome was passed through the user-agent header, the certain features on the site would actually stop working. So I needed to update the browsers.py file in the fake\_headers module to include only the versions of Chrome that I wanted to include. So I deleted all the older versions of Chrome and created a select list of versions (each one individually tested to work on the site in question and deleted the ones that did not). Which ended up with the following list, which I could expand on though have not for the time being.
```
chrome_ver = [
'90.0.4430', '84.0.4147', '85.0.4183', '85.0.4183', '87.0.4280', '86.0.4240', '88.0.4324', '89.0.4389', '92.0.4515', '91.0.4472', '93.0.4577', '93.0.4577'
]
```
Hope this helps spare someone two days of stress and messing around.
Some more useful info on headless chrome detectability:
<https://intoli.com/blog/making-chrome-headless-undetectable/> | I would refactor code in a way to wait until elements will be present on a web page:
```
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID, 'username'))).send_keys(args.usr)
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID,'password'))).send_keys(args.pwd)
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID, 'login-btn'))).click()
```
Generally usage of `WebDriverWait` in combination with some condition should be preferred to implicit waits or `time.sleep()`. [Here](https://stackoverflow.com/a/28067495/2792888) is explained in details why.
Other thing to double check are whether elements have the IDs used for search and that these elements aren't located within an iframe. |
64,311,719 | I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element.
My script is as follows:
```
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)
lhip = '13.14.15.16'
user = 'username'
paswd = 'password'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--lh_ip', type=str, metavar='', default=lhip, help='Public IP of VM' )
parser.add_argument('-u', '--usr', type=str, metavar='', default=user, help='Username for VM')
parser.add_argument('-p', '--pwd', type=str, metavar='', default=paswd, help='Password for VM')
args = parser.parse_args()
lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
if driver.title == 'Privacy error':
driver.find_element_by_id('details-button').click()
driver.find_element_by_id('proceed-link').click()
except:
pass
driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
if driver.find_element_by_tag_name('span'):
print('Login Failed')
except:
print('Login Successful')
driver.close()
```
The python script works fine on my system when used without the chrome\_options. However upon adding them to run in headless mode, it fails with the following output:
```
[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
driver.find_element_by_id('username').send_keys(args.usr)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
(Session info: headless chrome=85.0.4183.121)
```
Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked.
Also why is it saying "css selector" when I have only used id for username? | 2020/10/12 | [
"https://Stackoverflow.com/questions/64311719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9953181/"
] | I came across similar situations too. And I've tried a lot of solutions online such as specifying the resolution, but nothing worked until this:
```
self.chrome_options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"')
```
So it seems that you need to add UA to chrome options so that the selenium driver wouldn't crash in headless mode. | I would refactor code in a way to wait until elements will be present on a web page:
```
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID, 'username'))).send_keys(args.usr)
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID,'password'))).send_keys(args.pwd)
WebDriverWait(wd, 10).until(EC.presence_of_element_located((By.ID, 'login-btn'))).click()
```
Generally usage of `WebDriverWait` in combination with some condition should be preferred to implicit waits or `time.sleep()`. [Here](https://stackoverflow.com/a/28067495/2792888) is explained in details why.
Other thing to double check are whether elements have the IDs used for search and that these elements aren't located within an iframe. |
64,311,719 | I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element.
My script is as follows:
```
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)
lhip = '13.14.15.16'
user = 'username'
paswd = 'password'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--lh_ip', type=str, metavar='', default=lhip, help='Public IP of VM' )
parser.add_argument('-u', '--usr', type=str, metavar='', default=user, help='Username for VM')
parser.add_argument('-p', '--pwd', type=str, metavar='', default=paswd, help='Password for VM')
args = parser.parse_args()
lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
if driver.title == 'Privacy error':
driver.find_element_by_id('details-button').click()
driver.find_element_by_id('proceed-link').click()
except:
pass
driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
if driver.find_element_by_tag_name('span'):
print('Login Failed')
except:
print('Login Successful')
driver.close()
```
The python script works fine on my system when used without the chrome\_options. However upon adding them to run in headless mode, it fails with the following output:
```
[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
driver.find_element_by_id('username').send_keys(args.usr)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
(Session info: headless chrome=85.0.4183.121)
```
Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked.
Also why is it saying "css selector" when I have only used id for username? | 2020/10/12 | [
"https://Stackoverflow.com/questions/64311719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9953181/"
] | If the script is working perfectly fine without headless mode, probably there is issue with the window size. Along with specifying --no-sandbox option, try changing the window size passed to the webdriver
chrome\_options.add\_argument('--window-size=1920,1080')
This window size worked in my case.
Even if this dosen't work you might need to add wait timers as answered before as rendering in headless mode works in a different way as compared to a browser in UI mode.
Ref for rendering in headless mode - <https://www.toolsqa.com/selenium-webdriver/selenium-headless-browser-testing/> | I came across similar situations too. And I've tried a lot of solutions online such as specifying the resolution, but nothing worked until this:
```
self.chrome_options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"')
```
So it seems that you need to add UA to chrome options so that the selenium driver wouldn't crash in headless mode. |
64,311,719 | I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element.
My script is as follows:
```
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)
lhip = '13.14.15.16'
user = 'username'
paswd = 'password'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--lh_ip', type=str, metavar='', default=lhip, help='Public IP of VM' )
parser.add_argument('-u', '--usr', type=str, metavar='', default=user, help='Username for VM')
parser.add_argument('-p', '--pwd', type=str, metavar='', default=paswd, help='Password for VM')
args = parser.parse_args()
lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
if driver.title == 'Privacy error':
driver.find_element_by_id('details-button').click()
driver.find_element_by_id('proceed-link').click()
except:
pass
driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
if driver.find_element_by_tag_name('span'):
print('Login Failed')
except:
print('Login Successful')
driver.close()
```
The python script works fine on my system when used without the chrome\_options. However upon adding them to run in headless mode, it fails with the following output:
```
[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
driver.find_element_by_id('username').send_keys(args.usr)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
(Session info: headless chrome=85.0.4183.121)
```
Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked.
Also why is it saying "css selector" when I have only used id for username? | 2020/10/12 | [
"https://Stackoverflow.com/questions/64311719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9953181/"
] | If the script is working perfectly fine without headless mode, probably there is issue with the window size. Along with specifying --no-sandbox option, try changing the window size passed to the webdriver
chrome\_options.add\_argument('--window-size=1920,1080')
This window size worked in my case.
Even if this dosen't work you might need to add wait timers as answered before as rendering in headless mode works in a different way as compared to a browser in UI mode.
Ref for rendering in headless mode - <https://www.toolsqa.com/selenium-webdriver/selenium-headless-browser-testing/> | chrome\_options.add\_argument('--window-size=1920,1080')
this worked for me
thanks |
64,311,719 | I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element.
My script is as follows:
```
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)
lhip = '13.14.15.16'
user = 'username'
paswd = 'password'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--lh_ip', type=str, metavar='', default=lhip, help='Public IP of VM' )
parser.add_argument('-u', '--usr', type=str, metavar='', default=user, help='Username for VM')
parser.add_argument('-p', '--pwd', type=str, metavar='', default=paswd, help='Password for VM')
args = parser.parse_args()
lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
if driver.title == 'Privacy error':
driver.find_element_by_id('details-button').click()
driver.find_element_by_id('proceed-link').click()
except:
pass
driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
if driver.find_element_by_tag_name('span'):
print('Login Failed')
except:
print('Login Successful')
driver.close()
```
The python script works fine on my system when used without the chrome\_options. However upon adding them to run in headless mode, it fails with the following output:
```
[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
driver.find_element_by_id('username').send_keys(args.usr)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
(Session info: headless chrome=85.0.4183.121)
```
Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked.
Also why is it saying "css selector" when I have only used id for username? | 2020/10/12 | [
"https://Stackoverflow.com/questions/64311719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9953181/"
] | I had the same issue, it was initially working, though after an update from a website that we were using Selenium on, it stopped working in headless mode, though kept on working in non headless. After 2 days of researching the deepest and darkest depths of the web and a lot of trial and error, finally found what the issue was.
I tried all the methods outlined on the web and more, though nothing worked until I found this.
In headless chrome mode, the user agent is something like this:
Mozilla/5.0 (X11; Linux x86\_64) AppleWebKit/537.36 (KHTML, like Gecko) **HeadlessChrome**/60.0.3112.50 Safari/537.36
The service provider updated their code to identify the HeadlessChrome part and would cause the tab to crash and in turn, destroying the Selenium user session.
Which lead to the issue firing above in one of the exceptions.
To solve this, I used a plugin called fake\_headers (<https://github.com/diwu1989/Fake-Headers>):
```
from fake_headers import Headers
header = Headers(
browser="chrome", # Generate only Chrome UA
os="win", # Generate only Windows platform
headers=False # generate misc headers
)
customUserAgent = header.generate()['User-Agent']
options.add_argument(f"user-agent={customUserAgent}")
```
Though this was only half the solution as I only wanted Windows and Chrome headers and the fake\_headers module has not not include the latest Chrome browsers and has a lot of older versions of Chrome in the list as can be seen in this file <https://github.com/diwu1989/Fake-Headers/blob/master/fake_headers/browsers.py>. The particular site I was running Selenium had certain features that only worked on newer versions of Chrome, so when an older version of Chrome was passed through the user-agent header, the certain features on the site would actually stop working. So I needed to update the browsers.py file in the fake\_headers module to include only the versions of Chrome that I wanted to include. So I deleted all the older versions of Chrome and created a select list of versions (each one individually tested to work on the site in question and deleted the ones that did not). Which ended up with the following list, which I could expand on though have not for the time being.
```
chrome_ver = [
'90.0.4430', '84.0.4147', '85.0.4183', '85.0.4183', '87.0.4280', '86.0.4240', '88.0.4324', '89.0.4389', '92.0.4515', '91.0.4472', '93.0.4577', '93.0.4577'
]
```
Hope this helps spare someone two days of stress and messing around.
Some more useful info on headless chrome detectability:
<https://intoli.com/blog/making-chrome-headless-undetectable/> | I came across similar situations too. And I've tried a lot of solutions online such as specifying the resolution, but nothing worked until this:
```
self.chrome_options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"')
```
So it seems that you need to add UA to chrome options so that the selenium driver wouldn't crash in headless mode. |
64,311,719 | I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element.
My script is as follows:
```
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)
lhip = '13.14.15.16'
user = 'username'
paswd = 'password'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--lh_ip', type=str, metavar='', default=lhip, help='Public IP of VM' )
parser.add_argument('-u', '--usr', type=str, metavar='', default=user, help='Username for VM')
parser.add_argument('-p', '--pwd', type=str, metavar='', default=paswd, help='Password for VM')
args = parser.parse_args()
lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
if driver.title == 'Privacy error':
driver.find_element_by_id('details-button').click()
driver.find_element_by_id('proceed-link').click()
except:
pass
driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
if driver.find_element_by_tag_name('span'):
print('Login Failed')
except:
print('Login Successful')
driver.close()
```
The python script works fine on my system when used without the chrome\_options. However upon adding them to run in headless mode, it fails with the following output:
```
[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
driver.find_element_by_id('username').send_keys(args.usr)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
(Session info: headless chrome=85.0.4183.121)
```
Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked.
Also why is it saying "css selector" when I have only used id for username? | 2020/10/12 | [
"https://Stackoverflow.com/questions/64311719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9953181/"
] | I had the same issue, it was initially working, though after an update from a website that we were using Selenium on, it stopped working in headless mode, though kept on working in non headless. After 2 days of researching the deepest and darkest depths of the web and a lot of trial and error, finally found what the issue was.
I tried all the methods outlined on the web and more, though nothing worked until I found this.
In headless chrome mode, the user agent is something like this:
Mozilla/5.0 (X11; Linux x86\_64) AppleWebKit/537.36 (KHTML, like Gecko) **HeadlessChrome**/60.0.3112.50 Safari/537.36
The service provider updated their code to identify the HeadlessChrome part and would cause the tab to crash and in turn, destroying the Selenium user session.
Which lead to the issue firing above in one of the exceptions.
To solve this, I used a plugin called fake\_headers (<https://github.com/diwu1989/Fake-Headers>):
```
from fake_headers import Headers
header = Headers(
browser="chrome", # Generate only Chrome UA
os="win", # Generate only Windows platform
headers=False # generate misc headers
)
customUserAgent = header.generate()['User-Agent']
options.add_argument(f"user-agent={customUserAgent}")
```
Though this was only half the solution as I only wanted Windows and Chrome headers and the fake\_headers module has not not include the latest Chrome browsers and has a lot of older versions of Chrome in the list as can be seen in this file <https://github.com/diwu1989/Fake-Headers/blob/master/fake_headers/browsers.py>. The particular site I was running Selenium had certain features that only worked on newer versions of Chrome, so when an older version of Chrome was passed through the user-agent header, the certain features on the site would actually stop working. So I needed to update the browsers.py file in the fake\_headers module to include only the versions of Chrome that I wanted to include. So I deleted all the older versions of Chrome and created a select list of versions (each one individually tested to work on the site in question and deleted the ones that did not). Which ended up with the following list, which I could expand on though have not for the time being.
```
chrome_ver = [
'90.0.4430', '84.0.4147', '85.0.4183', '85.0.4183', '87.0.4280', '86.0.4240', '88.0.4324', '89.0.4389', '92.0.4515', '91.0.4472', '93.0.4577', '93.0.4577'
]
```
Hope this helps spare someone two days of stress and messing around.
Some more useful info on headless chrome detectability:
<https://intoli.com/blog/making-chrome-headless-undetectable/> | chrome\_options.add\_argument('--window-size=1920,1080')
this worked for me
thanks |
64,311,719 | I just started learning Selenium and need to verify a login web-page using a jenkins machine in the cloud, which doesn't have a GUI. I managed to run the script successfully on my system which has a UI. However when I modified the script to run headless, it fails saying unable to locate element.
My script is as follows:
```
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import time
import argparse
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--window-size=1120, 550')
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--allow-running-insecure-content')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=chrome_options)
driver.implicitly_wait(5)
lhip = '13.14.15.16'
user = 'username'
paswd = 'password'
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--lh_ip', type=str, metavar='', default=lhip, help='Public IP of VM' )
parser.add_argument('-u', '--usr', type=str, metavar='', default=user, help='Username for VM')
parser.add_argument('-p', '--pwd', type=str, metavar='', default=paswd, help='Password for VM')
args = parser.parse_args()
lh_url = 'https://' + args.lh_ip + '/login/'
driver.get(lh_url)
try:
if driver.title == 'Privacy error':
driver.find_element_by_id('details-button').click()
driver.find_element_by_id('proceed-link').click()
except:
pass
driver.find_element_by_id('username').send_keys(args.usr)
driver.find_element_by_id('password').send_keys(args.pwd)
driver.find_element_by_id('login-btn').click()
driver.implicitly_wait(10)
try:
if driver.find_element_by_tag_name('span'):
print('Login Failed')
except:
print('Login Successful')
driver.close()
```
The python script works fine on my system when used without the chrome\_options. However upon adding them to run in headless mode, it fails with the following output:
```
[WDM] - Current google-chrome version is 85.0.4183
[WDM] - Get LATEST driver version for 85.0.4183
[WDM] - Driver [/home/ramesh/.wdm/drivers/chromedriver/linux64/85.0.4183.87/chromedriver] found in cache
Traceback (most recent call last):
File "/home/ramesh/practice_python/test_headless.py", line 44, in <module>
driver.find_element_by_id('username').send_keys(args.usr)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/home/ramesh/.local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="username"]"}
(Session info: headless chrome=85.0.4183.121)
```
Since I have about one day's learning of Selenium, I may be doing something rather silly, so would be very grateful if someone showed me what I've done wrong. I've googled a lot and tried many things but none worked.
Also why is it saying "css selector" when I have only used id for username? | 2020/10/12 | [
"https://Stackoverflow.com/questions/64311719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9953181/"
] | I came across similar situations too. And I've tried a lot of solutions online such as specifying the resolution, but nothing worked until this:
```
self.chrome_options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"')
```
So it seems that you need to add UA to chrome options so that the selenium driver wouldn't crash in headless mode. | chrome\_options.add\_argument('--window-size=1920,1080')
this worked for me
thanks |
15,642,581 | I've installed numpy and when I go to install Matplotlib it fails. Regardless of the method I use to install it. Below are the errors I receive.
```
gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -O2 -
DNDEBUG -g -O3 -DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -
I/usr/local/include -I/usr/include -I/usr/X11/include -I/opt/local/include -
I/usr/local/include -I/usr/include -I. -
I/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/include -I. -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/_png.cpp -o build/temp.macosx-10.6-intel-2.7/src/_png.o
src/_png.cpp:23:20: error: png.h: No such file or directory
src/_png.cpp:66: error: variable or field ‘write_png_data’ declared void
src/_png.cpp:66: error: ‘png_structp’ was not declared in this scope
src/_png.cpp:66: error: ‘png_bytep’ was not declared in this scope
src/_png.cpp:66: error: ‘png_size_t’ was not declared in this scope
src/_png.cpp:23:20: error: png.h: No such file or directory
src/_png.cpp:66: error: variable or field ‘write_png_data’ declared void
src/_png.cpp:66: error: ‘png_structp’ was not declared in this scope
src/_png.cpp:66: error: ‘png_bytep’ was not declared in this scope
src/_png.cpp:66: error: ‘png_size_t’ was not declared in this scope
lipo: can't figure out the architecture type of:
/var/folders/c9/xzv35t2n3ld9lgjrtl0vd0xr0000gn/T//ccwRj4ny.out
error: command 'gcc-4.2' failed with exit status 1
----------------------------------------
Command /Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -
c "import setuptools;__file__='/var/folders/c9/xzv35t2n3ld9lgjrtl0vd0xr0000gn/T/pip-
build/matplotlib/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'),
__file__, 'exec'))" install --record /var/folders/c9/xzv35t2n3ld9lgjrtl0vd0xr0000gn/T/pip-
udXluz-record/install-record.txt --single-version-externally-managed failed with error
code 1 in /var/folders/c9/xzv35t2n3ld9lgjrtl0vd0xr0000gn/T/pip-build/matplotlib
Storing complete log
``` | 2013/03/26 | [
"https://Stackoverflow.com/questions/15642581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1238230/"
] | ```
public static void Display_Grid(DataGrid d, List<string> S1)
{
ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
DataColumn cl = new DataColumn("Item Number", typeof(string));
cl.MaxLength = 200;
dt.Columns.Add(cl);
int i = 0;
foreach (string s in S1)
{
DataRow rw = dt.NewRow();
rw["Item Number"] = S1[i];
i++;
}
d.ItemsSource = ds.Tables[0].AsDataView();
}
``` | add new row in datagrid using observablecollection ItemCollection
```
itemmodel model=new itemmodel ();
model.name='Rahul';
ItemCollection.add(model);
``` |
60,358,982 | I am getting an **Internal Server Error** and not sure if i need to change something in wsgi.
The app was working fine while tested on virtual environment on port 8000.
I followed all the steps using the tutorial <https://www.youtube.com/watch?v=Sa_kQheCnds>
the apache error log shows the following :
```
[Sun Feb 23 02:13:47.329729 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] mod_wsgi (pid=2544): Target WSGI script '/home/recprydjango/rec$
[Sun Feb 23 02:13:47.329817 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] mod_wsgi (pid=2544): Exception occurred processing WSGI script $
[Sun Feb 23 02:13:47.330088 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] Traceback (most recent call last):
[Sun Feb 23 02:13:47.330125 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] File "/home/recprydjango/recipe/app/wsgi.py", line 12, in <mo$
[Sun Feb 23 02:13:47.330130 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] from django.core.wsgi import get_wsgi_application
[Sun Feb 23 02:13:47.330148 2020] [wsgi:error] [pid 2544:tid 140477402474240] [remote xx.xx.xx.xx:59870] ModuleNotFoundError: No module named 'django'
```
I have the following structure
```
(venv) recprydjango@recpry-django:~/recipe$ tree
.
├── app
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── ...
│ │ └── wsgi.cpython-37.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── manage.py
├── media
│ └── images
│ ├── chocolatecake.png
│ └── ...
├── recipe
│ ├── admin.py
│ ├── apps.py
│ ├── forms.py
│ ├── __init__.py
│ ├── models.py
│ ├── __pycache__
│ │ ├── ...
│ │ └── views.cpython-37.pyc
│ ├── tests.py
│ └── views.py
├── requirements.txt
├── static
│ ├── admin
│ │ ├── css/...
│ │ ├── fonts/...
│ │ ├── img/...
│ │ └── js/...
│ └── smart-selects/...
├── templates
│ └── home.html
└── venv
├── bin
│ ├── activate
│ ├── activate.csh
│ ├── activate.fish
│ ├── easy_install
│ ├── easy_install-3.6
│ ├── pip
│ ├── pip3
│ ├── pip3.6
│ ├── python -> python3
│ └── python3 -> /usr/bin/python3
├── include
├── lib
│ └── python3.6
│ └── site-packages
```
settings.py
```
import os
import json
with open('/etc/config.json') as config_file:
config = json.load(config_file)
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['xx.xx.xx.xx']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#--- ADDED APP recipe HERE !!!!
'recipe',
#--- ADDED Smart_Selects HERE !!
'smart_selects',
#Bootstap
'crispy_forms',
'widget_tweaks',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
# --- TEMPLATE DIRECTORY
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
#--- ADDED THIS SECTION TO UPLOAD PHOTOS !!!! ---
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
#------------------------------------------------
#--- ADDED THIS SECTION FOR SMART SELECTS !!! ---
USE_DJANGO_JQUERY = True
#------------------------------------------------
CRISPY_TEMPLATE_PACK = 'bootstrap4'
```
wsgi.py
```
"""
WSGI config for app project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
import sys
sys.path.insert(0, '/home/recprydjango/recipe/')
sys.path.insert(0, '/home/recprydjango/recipe/app/')
sys.path.insert(0, '/home/recprydjango/recipe/recipe/')
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings')
application = get_wsgi_application()
```
apache conf
```
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
#ServerName www.example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
Alias /static /home/recprydjango/recipe/static
<Directory /home/recprydjango/recipe/static>
Require all granted
</Directory>
Alias /media /home/recprydjango/recipe/media
<Directory /home/recprydjango/recipe/media>
Require all granted
</Directory>
<Directory /home/recprydjango/recipe/app>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/recprydjango/recipe/app/wsgi.py
WSGIDaemonProcess django_app python-path=/home/recprydjango/recipe python-home=/home/recprydjango/recipe/venv
WSGIProcessGroup django_app
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
``` | 2020/02/23 | [
"https://Stackoverflow.com/questions/60358982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10881955/"
] | UPD: Now I'm sure the reason of such behavior is "AdBlock Plus" Chrome Extension (ID: cfhdojbkjhnklbpkdaibdccddilifddb).
I think the refresh started to happen after the extension's update. When I open DevTools in Chrome Incognito mode AdBlock is disabled and I get no refresh, also there's no refresh on another PC I use with no AdBlock. | I have found that some extensions cause page refreshes, such as "Awesome Color Picker" |
54,390,224 | My question is why can I not use a relative path to specify a bash script to run?
I have a ansible file structure following [best practice](https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html#directory-layout).
My directory structure for this role is:
```
.
├── files
│ └── install-watchman.bash
└── tasks
└── main.yml
```
and the main.yml includes this:
```
- name: install Watchman
shell: "{{ role_path }}/files/install-watchman.bash"
- name: copy from files dir to target home dir
copy:
src: files/install-watchman.bash
dest: /home/vagrant/install-watchman.bash
owner: vagrant
group: vagrant
mode: 0744
- name: install Watchman
shell: files/install-watchman.bash
```
I would expect all three commands to work, but in practice the third one fails:
```
TASK [nodejs : install Watchman] ***********************************************
changed: [machine1]
TASK [nodejs : copy from files dir to target home dir] ********
changed: [machine1]
TASK [nodejs : install Watchman] ***********************************************
fatal: [machine1]: FAILED! => {"changed": true, "cmd": "files/install-watchman.bash", "delta": "0:00:00.002997", "end": "2019-01-27 16:01:50.093530", "msg": "non-zero return code", "rc": 127, "start": "2019-01-27 16:01:50.090533", "stderr": "/bin/sh: 1: files/install-watchman.bash: not found", "stderr_lines": ["/bin/sh: 1: files/install-watchman.bash: not found"], "stdout": "", "stdout_lines": []}
to retry, use: --limit @/vagrant/ansible/site.retry
```
(If it helps, this is the version info for ansible:)
```
vagrant@ubuntu-xenial:~$ ansible --version
ansible 2.7.6
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/vagrant/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/dist-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609]
``` | 2019/01/27 | [
"https://Stackoverflow.com/questions/54390224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10055448/"
] | I put together a test of this to see: <https://github.com/farrellit/ansible-demonstrations/tree/master/shell-cwd>
It has convinced me that the short answer is probably, *ansible roles' `shell` tasks will by default have the working directory of the playbook that include that role*.
It basically comes down to a role like this ( the rest of that dir is tooling to make it run):
```
- shell: pwd
register: shellout
- debug: var=shellout.stdout
- shell: pwd
args:
chdir: "{{role_path}}"
register: shellout2
- debug: var=shellout2.stdout
```
This has shown:
```
PLAY [localhost] ***********************************************************************************************************************************************************************************************************************
TASK [shelldir : command] **************************************************************************************************************************************************************************************************************
changed: [127.0.0.1]
TASK [shelldir : debug] ****************************************************************************************************************************************************************************************************************
ok: [127.0.0.1] => {
"shellout.stdout": "/code"
}
TASK [shelldir : command] **************************************************************************************************************************************************************************************************************
changed: [127.0.0.1]
TASK [shelldir : debug] ****************************************************************************************************************************************************************************************************************
ok: [127.0.0.1] => {
"shellout2.stdout": "/code/roles/shelldir"
}
PLAY RECAP *****************************************************************************************************************************************************************************************************************************
127.0.0.1 : ok=4 changed=2 unreachable=0 failed=0
```
That the current working directory for roles is not `role_path`. In my case it is the role of the playbook that invoked the task. It might be something else in the case of an included playbook or tasks file from a different directory (I'll leave that as an exercise for you, if you care). I set that execution to run from `/tmp`, so I don't think it would matter the current working directory of the shell that ran `ansible-playbook`. | Shell will execute the command on the remote. You have copied the script to `/home/vagrant/install-watchman.bash` on your remote. Therefore you have to use that location for executing on the remote as well.
```
- name: install Watchman
shell: /home/vagrant/install-watchman.bash
```
a relative path will work as well, if your ansible user is the user "vagrant"
```
- name: install Watchman
shell: install-watchman.bash
```
Side note:
I would recommend to use `command` instead of `shell` whenever possible: [shell vs command Module](https://blog.confirm.ch/ansible-modules-shell-vs-command/) |
68,759,605 | >
> {"name": "Sara", "grade": "1", "school": "Buckeye", "teacher": "Ms. Black", "sci": {"gr": "A", "perc": "93"}, "math": {"gr": "B+", "perc": "88"}, "eng": {"gr": "A-", "perc": "91"}}
>
>
>
I have the json file above (named test) and I am trying to turn it into a dataframe in python using pandas. The pd.read\_json(test.csv) command returns two lines 'gr' and 'perc' instead of one. Is there a way to make one row and the nested columns be gr.sci, gr.math, gr.eng, perc.sci, perc.math, perc.eng? | 2021/08/12 | [
"https://Stackoverflow.com/questions/68759605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10256905/"
] | Try with `pd.json_normalize()`, as follows:
```
df = pd.json_normalize(test)
```
**Result:**
```
print(df)
name grade school teacher sci.gr sci.perc math.gr math.perc eng.gr eng.perc
0 Sara 1 Buckeye Ms. Black A 93 B+ 88 A- 91
``` | Use `pd.json_normalize` after convert json file to python data structure:
```
import pandas as pd
import json
data = json.load('data.json')
df = pd.json_normalize(data)
```
```
>>> df
name grade school teacher sci.gr sci.perc math.gr math.perc eng.gr eng.perc
0 Sara 1 Buckeye Ms. Black A 93 B+ 88 A- 91
``` |
64,609,700 | I have a script that imports another script, like this:
```
from mp_utils import *
login_response = login(...)
r = incomingConfig(...)
```
and mp\_utils.py is like this:
```
import requests
import logging
from requests.exceptions import HTTPError
def login( ... ):
...
def incomingConfig( ... ):
...
```
When running it, `login` works fine, but `incomingConfig` fails with:
```
Message: 'module' object has no attribute 'incomingConfig'
Exception: None
```
No idea why, any ideas?
funny thing is if import with python cli interactive, it works fine.
Many thanks! | 2020/10/30 | [
"https://Stackoverflow.com/questions/64609700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2115947/"
] | `from x import *` imports everything so that you don't have to name the module before you call a function. Try removing `mp_utils` from your function calls. | It is importing all the functions correctly, when you import using `from` then you don't have to prefix `mp_utils` to call the functions, just you can call it by their name. To call `mp_utils` prefixed, use `import mp_utils` instead. |
64,609,700 | I have a script that imports another script, like this:
```
from mp_utils import *
login_response = login(...)
r = incomingConfig(...)
```
and mp\_utils.py is like this:
```
import requests
import logging
from requests.exceptions import HTTPError
def login( ... ):
...
def incomingConfig( ... ):
...
```
When running it, `login` works fine, but `incomingConfig` fails with:
```
Message: 'module' object has no attribute 'incomingConfig'
Exception: None
```
No idea why, any ideas?
funny thing is if import with python cli interactive, it works fine.
Many thanks! | 2020/10/30 | [
"https://Stackoverflow.com/questions/64609700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2115947/"
] | `from x import *` imports everything so that you don't have to name the module before you call a function. Try removing `mp_utils` from your function calls. | You don't need to reference mp.utils before calling incomingConfig.
By using a \* import, it means you already added all the functions into the the current namespace. So you should be able to just make the call using `r = incomingConfig(...)`
If you want to make the call your way, you'd have to import it as
`import mp_utils`
Than later you can make the call.
`r = mp_utils.incomingConfig(...)` |
5,082,697 | I have created with the "extra" clause a concatenated field out of three text fields in a model - and I expect to be able to do this: q.filter(concatenated\_\_icontains="y") but it gives me an error. What alternatives are there?
```
>>> q = Patient.objects.extra(select={'concatenated': "mrn||' '||first_name||' '||last_name"})
>>> q.filter(concatenated__icontains="y")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 561, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/lib/python2.7/site-packages/django/db/models/query.py", line 579, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1170, in add_q
can_reuse=used_aliases, force_having=force_having)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1058, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1237, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'concatenated' into field. Choices are: first_name, id, last_name, mrn, specimen
``` | 2011/02/22 | [
"https://Stackoverflow.com/questions/5082697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/443404/"
] | If you need something beyond this,
```
Patient.objects.filter(first_name__icointains='y' | last_name__icontains='y' | mrn__icontains='y')
```
you might have to resort to raw SQL.
Of course, you can add in your `extra` either before or after the filter above. | My final solution based on Prasad's answer:
```
from django.db.models import Q
searchterm='y'
Patient.objects.filter(Q(mrn__icontains=searchterm) | Q(first_name__icontains=searchterm) | Q(last_name__icontains=searchterm))
``` |
54,434,766 | I have to define Instance variable, This Instance Variable is accessed in different Instance methods. Hence I am setting up Instance Variable under constructor. I see best of Initializing instance variables under constructor.
Is it a Good practice to use if else condition under constructor to define instance variable. Is there any other pythonic way to achieve this in standard coding practice.
```
class Test:
def __init__(self, EmpName, Team):
self.EmpName = EmpName
self.Team = Team
if Team == "Dev":
self.Manager = "Bob"
elif Team == "QA":
self.Manager = "Kim"
elif Team == "Admin":
self.Manager == "Jeff"
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54434766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10966964/"
] | The relationship between teams and managers is very straightforward data; I would not like having it as code. Thus, a lookup dictionary would be my choice.
```
class Test:
TEAM_MANAGERS = {
"Dev": "Bob",
"QA": "Kim",
"Admin": "Jeff",
}
def __init__(self, emp_name, team):
self.emp_name = emp_name
self.team = team
try:
self.manager = TEAM_MANAGERS[team]
except KeyError:
raise ArgumentError("Unknown team")
``` | There is nothing wrong with using `if-else` inside the `__init__()` method.
Based upon the condition you want the specific variable to be initialized, this is appropriate. |
54,434,766 | I have to define Instance variable, This Instance Variable is accessed in different Instance methods. Hence I am setting up Instance Variable under constructor. I see best of Initializing instance variables under constructor.
Is it a Good practice to use if else condition under constructor to define instance variable. Is there any other pythonic way to achieve this in standard coding practice.
```
class Test:
def __init__(self, EmpName, Team):
self.EmpName = EmpName
self.Team = Team
if Team == "Dev":
self.Manager = "Bob"
elif Team == "QA":
self.Manager = "Kim"
elif Team == "Admin":
self.Manager == "Jeff"
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54434766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10966964/"
] | It's very bad coding practice to mix data and structure like this in general for object oriented programming and Python is no exception. There's a number of ways to solve this:
* you could just passing in the team manager; but it appears that's the step you want to automate
* you could link the Employee to a team instance, something like:
Something like:
```
class Team:
def __init__(self, name, manager):
self.name = name
self.manager = manager
class Employee:
def __init__(self, name, team):
self.name = name
self.team = team
team_dev = Team("Dev", "Bob")
team_qa = Team("QA", "Kim")
employee_1 = Employee("Jack", team_dev)
print(f'{employee_1.name} is on {employee_1.team.name} as managed by {employee_1.team.manager}')
```
Note that variables should not be CamelCase, but class names should.
An even nicer solution might be to have the manager of a team be an employee themselves. Of course, then you need the team when you create the employee and the employee when you create the team, so it may need to be None initially:
```
class Team:
def __init__(self, name, manager=None):
self.name = name
self.manager = manager
class Employee:
def __init__(self, name, team):
self.name = name
self.team = team
team_dev = Team("Dev")
team_dev.manager = Employee("Bob", team_dev)
team_qa = Team("QA")
team_qa.manager = Employee("Kim", team_qa)
employee_1 = Employee("Jack", team_dev)
print(f'{employee_1.name} is on {employee_1.team.name} as managed by {employee_1.team.manager.name}')
``` | There is nothing wrong with using `if-else` inside the `__init__()` method.
Based upon the condition you want the specific variable to be initialized, this is appropriate. |
54,434,766 | I have to define Instance variable, This Instance Variable is accessed in different Instance methods. Hence I am setting up Instance Variable under constructor. I see best of Initializing instance variables under constructor.
Is it a Good practice to use if else condition under constructor to define instance variable. Is there any other pythonic way to achieve this in standard coding practice.
```
class Test:
def __init__(self, EmpName, Team):
self.EmpName = EmpName
self.Team = Team
if Team == "Dev":
self.Manager = "Bob"
elif Team == "QA":
self.Manager = "Kim"
elif Team == "Admin":
self.Manager == "Jeff"
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54434766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10966964/"
] | The relationship between teams and managers is very straightforward data; I would not like having it as code. Thus, a lookup dictionary would be my choice.
```
class Test:
TEAM_MANAGERS = {
"Dev": "Bob",
"QA": "Kim",
"Admin": "Jeff",
}
def __init__(self, emp_name, team):
self.emp_name = emp_name
self.team = team
try:
self.manager = TEAM_MANAGERS[team]
except KeyError:
raise ArgumentError("Unknown team")
``` | It's very bad coding practice to mix data and structure like this in general for object oriented programming and Python is no exception. There's a number of ways to solve this:
* you could just passing in the team manager; but it appears that's the step you want to automate
* you could link the Employee to a team instance, something like:
Something like:
```
class Team:
def __init__(self, name, manager):
self.name = name
self.manager = manager
class Employee:
def __init__(self, name, team):
self.name = name
self.team = team
team_dev = Team("Dev", "Bob")
team_qa = Team("QA", "Kim")
employee_1 = Employee("Jack", team_dev)
print(f'{employee_1.name} is on {employee_1.team.name} as managed by {employee_1.team.manager}')
```
Note that variables should not be CamelCase, but class names should.
An even nicer solution might be to have the manager of a team be an employee themselves. Of course, then you need the team when you create the employee and the employee when you create the team, so it may need to be None initially:
```
class Team:
def __init__(self, name, manager=None):
self.name = name
self.manager = manager
class Employee:
def __init__(self, name, team):
self.name = name
self.team = team
team_dev = Team("Dev")
team_dev.manager = Employee("Bob", team_dev)
team_qa = Team("QA")
team_qa.manager = Employee("Kim", team_qa)
employee_1 = Employee("Jack", team_dev)
print(f'{employee_1.name} is on {employee_1.team.name} as managed by {employee_1.team.manager.name}')
``` |
54,434,766 | I have to define Instance variable, This Instance Variable is accessed in different Instance methods. Hence I am setting up Instance Variable under constructor. I see best of Initializing instance variables under constructor.
Is it a Good practice to use if else condition under constructor to define instance variable. Is there any other pythonic way to achieve this in standard coding practice.
```
class Test:
def __init__(self, EmpName, Team):
self.EmpName = EmpName
self.Team = Team
if Team == "Dev":
self.Manager = "Bob"
elif Team == "QA":
self.Manager = "Kim"
elif Team == "Admin":
self.Manager == "Jeff"
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54434766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10966964/"
] | The relationship between teams and managers is very straightforward data; I would not like having it as code. Thus, a lookup dictionary would be my choice.
```
class Test:
TEAM_MANAGERS = {
"Dev": "Bob",
"QA": "Kim",
"Admin": "Jeff",
}
def __init__(self, emp_name, team):
self.emp_name = emp_name
self.team = team
try:
self.manager = TEAM_MANAGERS[team]
except KeyError:
raise ArgumentError("Unknown team")
``` | ```
class Test():
def __init__(self,EmpName = "",Team = ""):
self.EmpName = EmpName
self.Team = Team
self.Manager = Manager
if self.Team == "Dev":
self.Manager = "Bob"
elif self.Team == "Dev":
self.Manager = "Kim"
elif self.Team == "Admin":
self.manager = "Jeff"
else:
self.manager = ""
def get_manager(self):
return self.Manager
obj = Test("DemoEmp","Dev")
print (obj.get_manager())
``` |
54,434,766 | I have to define Instance variable, This Instance Variable is accessed in different Instance methods. Hence I am setting up Instance Variable under constructor. I see best of Initializing instance variables under constructor.
Is it a Good practice to use if else condition under constructor to define instance variable. Is there any other pythonic way to achieve this in standard coding practice.
```
class Test:
def __init__(self, EmpName, Team):
self.EmpName = EmpName
self.Team = Team
if Team == "Dev":
self.Manager = "Bob"
elif Team == "QA":
self.Manager = "Kim"
elif Team == "Admin":
self.Manager == "Jeff"
``` | 2019/01/30 | [
"https://Stackoverflow.com/questions/54434766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10966964/"
] | It's very bad coding practice to mix data and structure like this in general for object oriented programming and Python is no exception. There's a number of ways to solve this:
* you could just passing in the team manager; but it appears that's the step you want to automate
* you could link the Employee to a team instance, something like:
Something like:
```
class Team:
def __init__(self, name, manager):
self.name = name
self.manager = manager
class Employee:
def __init__(self, name, team):
self.name = name
self.team = team
team_dev = Team("Dev", "Bob")
team_qa = Team("QA", "Kim")
employee_1 = Employee("Jack", team_dev)
print(f'{employee_1.name} is on {employee_1.team.name} as managed by {employee_1.team.manager}')
```
Note that variables should not be CamelCase, but class names should.
An even nicer solution might be to have the manager of a team be an employee themselves. Of course, then you need the team when you create the employee and the employee when you create the team, so it may need to be None initially:
```
class Team:
def __init__(self, name, manager=None):
self.name = name
self.manager = manager
class Employee:
def __init__(self, name, team):
self.name = name
self.team = team
team_dev = Team("Dev")
team_dev.manager = Employee("Bob", team_dev)
team_qa = Team("QA")
team_qa.manager = Employee("Kim", team_qa)
employee_1 = Employee("Jack", team_dev)
print(f'{employee_1.name} is on {employee_1.team.name} as managed by {employee_1.team.manager.name}')
``` | ```
class Test():
def __init__(self,EmpName = "",Team = ""):
self.EmpName = EmpName
self.Team = Team
self.Manager = Manager
if self.Team == "Dev":
self.Manager = "Bob"
elif self.Team == "Dev":
self.Manager = "Kim"
elif self.Team == "Admin":
self.manager = "Jeff"
else:
self.manager = ""
def get_manager(self):
return self.Manager
obj = Test("DemoEmp","Dev")
print (obj.get_manager())
``` |
17,297,230 | I am new to python and have tried searching for help prior to posting.
I have binary file that contains a number of values I need to parse. Each value has a hex header of two bytes and a third byte that gives a size of the data in that record to parse. The following is an example:
```
\x76\x12\x0A\x08\x00\x00\x00\x00\x00\x00\x00\x00
```
The `\x76\x12` is the record marker and `\x0A` is the number of bytes to be read next.
This data always has the two byte marker and a third byte size. However the data to be parsed is variable and the record marker increments as follows: `\x76\x12` and `\x77\x12` and so on until `\x79\x12` where is starts again.
This is just example data for the use of this posting.
Many Thanks for any help or pointers. | 2013/06/25 | [
"https://Stackoverflow.com/questions/17297230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2519943/"
] | Is something like this what you want?
```
>>> b = b'\x76\x12\x0A\x08\x00\x00\x00\x00\x00\x00\x00\x00'
>>> from StringIO import StringIO
>>> io = StringIO(b)
>>> io.seek(0)
>>> io.read(2) #read 2 bytes, maybe validate?
'v\x12'
>>> import struct
>>> nbytes = struct.unpack('B',io.read(1))
>>> print nbytes
(10,)
>>> data = io.read(nbytes[0])
>>> data
'\x08\x00\x00\x00\x00\x00\x00\x00\x00'
``` | This will treat the data as a raw string (to ignore '\' escape character and split into a list
```
a = r"\x76\x12\x0A\x08\x00\x00\x00\x00\x00\x00\x00\x00".split('\\')
print a
```
output: ['', 'x76', 'x12', 'x0A', 'x08', 'x00', 'x00', 'x00', 'x00', 'x00', 'x00', 'x00', 'x00']
You can then iterate through the values you are interested in and convert them to decimal if required:
```
for i in range(len(a[4:])): # cutting off records before index 4 here
print int(str(a[i+4][1:]),16)
``` |
68,840,058 | I would like to show the data of a hdf5 file in the ImageView() class from pyqtgraph. The bare code of displaying the plot for ImageView() is:
```
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
# Interpret image data as row-major instead of col-major
pg.setConfigOptions(leftButtonPan = False, imageAxisOrder='row-major')
app = QtGui.QApplication([])
## Create window with ImageView widget
win = QtGui.QMainWindow()
win.resize(800,800)
imv = pg.ImageView()
win.setCentralWidget(imv)
win.show()
win.setWindowTitle('pyqtgraph example: ImageView')
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
```
There is however also a hdf5 example in the pyqtgraph example set. I'm unfortunately not able to get it to work. I made some alterations to the example to make it work for my needs but I'm getting an error. Here is first the code:
```
import numpy as np
import h5py
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
pg.mkQApp()
plt = pg.plot()
plt.setWindowTitle('pyqtgraph example: HDF5 big data')
plt.enableAutoRange(False, False)
plt.setXRange(0, 500)
class HDF5Plot(pg.ImageItem):
def __init__(self, *args, **kwds):
self.hdf5 = None
self.limit = 10000 # maximum number of samples to be plotted
pg.ImageItem.__init__(self, *args, **kwds)
def setHDF5(self, data):
self.hdf5 = data
self.updateHDF5Plot()
def viewRangeChanged(self):
self.updateHDF5Plot()
def updateHDF5Plot(self):
if self.hdf5 is None:
self.setData([])
return
vb = self.getViewBox()
if vb is None:
return # no ViewBox yet
# Determine what data range must be read from HDF5
xrange = vb.viewRange()[0]
start = max(0, int(xrange[0]) - 1)
stop = min(len(self.hdf5), int(xrange[1] + 2))
# Decide by how much we should downsample
ds = int((stop - start) / self.limit) + 1
if ds == 1:
# Small enough to display with no intervention.
visible = self.hdf5[start:stop]
scale = 1
else:
# Here convert data into a down-sampled array suitable for visualizing.
# Must do this piecewise to limit memory usage.
samples = 1 + ((stop - start) // ds)
visible = np.zeros(samples * 2, dtype=self.hdf5.dtype)
sourcePtr = start
targetPtr = 0
# read data in chunks of ~1M samples
chunkSize = (1000000 // ds) * ds
while sourcePtr < stop - 1:
chunk = self.hdf5[sourcePtr:min(stop, sourcePtr + chunkSize)]
sourcePtr += len(chunk)
# reshape chunk to be integral multiple of ds
chunk = chunk[:(len(chunk) // ds) * ds].reshape(len(chunk) // ds, ds)
# compute max and min
chunkMax = chunk.max(axis=1)
chunkMin = chunk.min(axis=1)
# interleave min and max into plot data to preserve envelope shape
visible[targetPtr:targetPtr + chunk.shape[0] * 2:2] = chunkMin
visible[1 + targetPtr:1 + targetPtr + chunk.shape[0] * 2:2] = chunkMax
targetPtr += chunk.shape[0] * 2
visible = visible[:targetPtr]
scale = ds * 0.5
self.setData(visible) # update the plot
self.setPos(start, 0) # shift to match starting index
self.resetTransform()
self.scale(scale, 1) # scale to match downsampling
f = h5py.File('test.hdf5', 'r')
curve = HDF5Plot()
curve.setHDF5(f['data'])
plt.addItem(curve)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
```
And here is the error:
```
Traceback (most recent call last):
File "pyqtg.py", line 206, in <module>
curve.setHDF5(f['data'])
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "/home/anaconda3/envs/img/lib/python3.8/site-packages/h5py-3.3.0-py3.8-linux-x86_64.egg/h5py/_hl/group.py", line 305, in __getitem__
oid = h5o.open(self.id, self._e(name), lapl=self._lapl)
File "h5py/_objects.pyx", line 54, in h5py._objects.with_phil.wrapper
File "h5py/_objects.pyx", line 55, in h5py._objects.with_phil.wrapper
File "h5py/h5o.pyx", line 190, in h5py.h5o.open
KeyError: "Unable to open object (object 'data' doesn't exist)"
```
The problem is that I don't know what/how the hdf5 file looks so I am unsure how to replace 'data' with the correct term or if it is completely different in and of itself. Any help is greatly appreciated.
**Edit 1:**
I got the examples from running `python -m pyqtgraph.examples`. Once the GUI pops up down the list you'll see "HDF5 Big Data". My code stems from that example. And from the examples the third one from the top, ImageView, is the code I would like to use to show the HDF5 file.
**Edit 2:**
Here is the result of running the second part of the code kcw78:
<http://pastie.org/p/3scRyUm1ZFVJNMwTHQHCBv>
**Edit 3:**
So I ran the code above but made a small change with the help from kcw78. I changed:
```
f = h5py.File('test.hdf5', 'r')
curve = HDF5Plot()
curve.setHDF5(f['data'])
plt.addItem(curve)
```
to:
```
with h5py.File('test.hdf5', 'r') as h5f:
curve = HDF5Plot()
curve.setHDF5(h5f['aggea'])
plt.addItem(curve)
```
And got the errors:
```
Traceback (most recent call last):
File "/home/anaconda3/envs/img/lib/python3.8/site-packages/pyqtgraph/graphicsItems/GraphicsObject.py", line 23, in itemChange
self.parentChanged()
File "/home/anaconda3/envs/img/lib/python3.8/site-packages/pyqtgraph/graphicsItems/GraphicsItem.py", line 458, in parentChanged
self._updateView()
File "/home/anaconda3/envs/img/lib/python3.8/site-packages/pyqtgraph/graphicsItems/GraphicsItem.py", line 514, in _updateView
self.viewRangeChanged()
File "pyqtg.py", line 25, in viewRangeChanged
self.updateHDF5Plot()
File "pyqtg.py", line 77, in updateHDF5Plot
self.setData(visible) # update the plot
TypeError: setData(self, int, Any): argument 1 has unexpected type 'numpy.ndarray'
Traceback (most recent call last):
File "/home/anaconda3/envs/img/lib/python3.8/site-packages/pyqtgraph/graphicsItems/GraphicsObject.py", line 23, in itemChange
self.parentChanged()
File "/home/anaconda3/envs/img/lib/python3.8/site-packages/pyqtgraph/graphicsItems/GraphicsItem.py", line 458, in parentChanged
self._updateView()
File "/home/anaconda3/envs/img/lib/python3.8/site-packages/pyqtgraph/graphicsItems/GraphicsItem.py", line 514, in _updateView
self.viewRangeChanged()
File "pyqtg.py", line 25, in viewRangeChanged
self.updateHDF5Plot()
File "pyqtg.py", line 77, in updateHDF5Plot
self.setData(visible) # update the plot
TypeError: setData(self, int, Any): argument 1 has unexpected type 'numpy.ndarray'
Traceback (most recent call last):
File "pyqtg.py", line 25, in viewRangeChanged
self.updateHDF5Plot()
File "pyqtg.py", line 77, in updateHDF5Plot
self.setData(visible) # update the plot
TypeError: setData(self, int, Any): argument 1 has unexpected type 'numpy.ndarray'
```
**Edit 4:**
Here is a photo of the results: <https://imgur.com/a/tVHNdx9>. I get the same empty results from both creating a 2d hdf5 file and using my 2d data file.
```
with h5py.File('mytest.hdf5', 'r') as h5fr, \
h5py.File('test_1d.hdf5', 'w') as h5fw:
arr = h5fr['aggea'][:].reshape(-1,)
h5fw.create_dataset('data', data=arr)
print(h5fw['data'].shape, h5fw['data'].dtype)
```
**Edit 5: The code that runs and plots**
```
import sys, os
import numpy as np
import h5py
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
pg.mkQApp()
plt = pg.plot()
plt.setWindowTitle('pyqtgraph example: HDF5 big data')
plt.enableAutoRange(False, False)
plt.setXRange(0, 500)
class HDF5Plot(pg.PlotCurveItem):
def __init__(self, *args, **kwds):
self.hdf5 = None
self.limit = 10000 # maximum number of samples to be plotted
pg.PlotCurveItem.__init__(self, *args, **kwds)
def setHDF5(self, data):
self.hdf5 = data
self.updateHDF5Plot()
def viewRangeChanged(self):
self.updateHDF5Plot()
def updateHDF5Plot(self):
if self.hdf5 is None:
self.setData([])
return
vb = self.getViewBox()
if vb is None:
return # no ViewBox yet
# Determine what data range must be read from HDF5
xrange = vb.viewRange()[0]
start = max(0, int(xrange[0]) - 1)
stop = min(len(self.hdf5), int(xrange[1] + 2))
# Decide by how much we should downsample
ds = int((stop - start) / self.limit) + 1
if ds == 1:
# Small enough to display with no intervention.
visible = self.hdf5[start:stop]
scale = 1
else:
# Here convert data into a down-sampled array suitable for visualizing.
# Must do this piecewise to limit memory usage.
samples = 1 + ((stop - start) // ds)
visible = np.zeros(samples * 2, dtype=self.hdf5.dtype)
sourcePtr = start
targetPtr = 0
# read data in chunks of ~1M samples
chunkSize = (1000000 // ds) * ds
while sourcePtr < stop - 1:
chunk = self.hdf5[sourcePtr:min(stop, sourcePtr + chunkSize)]
sourcePtr += len(chunk)
# reshape chunk to be integral multiple of ds
chunk = chunk[:(len(chunk) // ds) * ds].reshape(len(chunk) // ds, ds)
# compute max and min
chunkMax = chunk.max(axis=1)
chunkMin = chunk.min(axis=1)
# interleave min and max into plot data to preserve envelope shape
visible[targetPtr:targetPtr + chunk.shape[0] * 2:2] = chunkMin
visible[1 + targetPtr:1 + targetPtr + chunk.shape[0] * 2:2] = chunkMax
targetPtr += chunk.shape[0] * 2
visible = visible[:targetPtr]
scale = ds * 0.5
self.setData(visible) # update the plot
self.setPos(start, 0) # shift to match starting index
self.resetTransform()
self.scale(scale, 1) # scale to match downsampling
with h5py.File('mytest.hdf5', 'r') as h5fr, \
h5py.File('test_1d.hdf5', 'w') as h5fw:
arr = h5fr['aggea'][:].reshape(-1,)
h5fw.create_dataset('data', data=arr)
curve = HDF5Plot()
curve.setHDF5(h5fw['data'])
plt.addItem(curve)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
```
**Edit 6:**
What worked in the end:
```
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import h5py
import pyqtgraph as pg
import matplotlib.pyplot as plt
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
win.resize(800,800)
imv = pg.ImageView()
win.setCentralWidget(imv)
win.show()
win.setWindowTitle('pyqtgraph example: ImageView')
with h5py.File('test.hdf5', 'r') as h5fr:
data = h5fr.get('aggea')[()] #this gets the values. You can also use hf.get('dataset_name').value as this gives insight what `[()]` is doing, though it's deprecated
imv.setImage(data)
# hf = h5py.File('test.hdf5', 'r')
# n1 = np.array(hf['/pathtodata'][:])
# print(n1.shape)
## Set a custom color map
colors = [
(0, 0, 0),
(45, 5, 61),
(84, 42, 55),
(150, 87, 60),
(208, 171, 141),
(255, 255, 255)
]
cmap = pg.ColorMap(pos=np.linspace(0.0, 1.0, 6), color=colors)
imv.setColorMap(cmap)
## Start Qt event loop unless running in interactive mode.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
``` | 2021/08/18 | [
"https://Stackoverflow.com/questions/68840058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8313547/"
] | This should help with the second part.
```r
df %>%
group_by(species, native_region, intro_region) %>%
filter(all(c(1,0) %in% invasive)) %>%
filter(., invasive == 0) %>%
anti_join(df, .)
# A tibble: 11 × 4
species native_region invasive intro_region
<chr> <dbl> <dbl> <dbl>
1 Abies 4 1 8
2 Abies 4 1 3
3 Abies 4 1 4
4 Abies 3 1 5
5 Abrus 2 0 3
6 Abrus 2 0 6
7 Abrus 2 1 7
8 Acacia 4 1 5
9 Acacia 5 0 7
10 Acacia 6 1 7
11 Acacia 8 1 7
'''
``` | Figured out the first part:
```r
df %>% select(species, native_region) -> x
df %>% group_by(species) %>% anti_join(., x, by = c("species", "intro_region" = "native_region"))
# A tibble: 9 x 4
# Groups: species [3]
species native_region invasive intro_region
<chr> <dbl> <dbl> <dbl>
1 Abies 4 1 8
2 Abies 3 1 5
3 Abrus 2 0 3
4 Abrus 2 0 6
5 Abrus 2 1 7
6 Acacia 5 0 7
7 Acacia 6 1 7
8 Acacia 8 0 7
9 Acacia 8 1 7
```
Boom.
I'll still take suggestions on the second part. Thanks to everyone. |
17,786,203 | Consider the array `a= [1, 2, 3, 1, 2, 3]`. Now suppose I want to remove all the 2s in this array in python. So I apply `a.remove(2)`. However the result which comes out is `[1, 3, 1, 2, 3]`, i.e the only first 2 is removed. How can I remove all the 2s which appear in an array? In general, given an array and an element p, how can I remove all the elements of the array which are equal to p?
Edit:- I think I should mention this, this question has been inspired from a Brilliant computer science problem. | 2013/07/22 | [
"https://Stackoverflow.com/questions/17786203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2517072/"
] | Use a list comprehension to build a replacement list, where all elements are *not* equal to `p`:
```
a = [i for i in a if i != p]
```
Note that in Python, the datatype is called a `list`, not an array. | You can use [`filter()`](http://docs.python.org/2/library/functions.html#filter).
```
>>> a= [1, 2, 3, 1, 2, 3]
>>> filter(lambda x: x != 2, a)
[1, 3, 1, 3]
```
In a function :
```
>>> def removeAll(inList, num):
return filter(lambda elem: elem != num, inList)
>>> removeAll(a, 2)
[1, 3, 1, 3]
``` |
9,845,354 | I'm having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains.
So far I have this, which I can run through CDM, and state a file to open. I've messed around with regular expressions, still can't figure out how to count individual characters. Any ideas? sorry if I explained this badly.
```
import sys
import re
filename = raw_input()
count = 0
datafile=open(filename, 'r')
``` | 2012/03/23 | [
"https://Stackoverflow.com/questions/9845354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1289022/"
] | The Counter type is useful for counting items. It was added in python 2.7:
```
import collections
counts = collections.Counter()
for line in datafile:
# remove the EOL and iterate over each character
#if you desire the counts to be case insensitive, replace line.rstrip() with line.rstrip().lower()
for c in line.rstrip():
# Missing items default to 0, so there is no special code for new characters
counts[c] += 1
```
To see the results:
```
results = [(key, value) for key, value in counts.items() if key.isalpha()]
print results
``` | If you want to use regular expressions, you can do as follows:
```
pattern = re.compile('[^a-zA-Z]+') # pattern for everything but letters
only_letters = pattern.sub(text, '') # delete everything else
count = len(only_letters) # total number of letters
```
For counting the number of distinct characters, use Counter as already adviced. |
9,845,354 | I'm having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains.
So far I have this, which I can run through CDM, and state a file to open. I've messed around with regular expressions, still can't figure out how to count individual characters. Any ideas? sorry if I explained this badly.
```
import sys
import re
filename = raw_input()
count = 0
datafile=open(filename, 'r')
``` | 2012/03/23 | [
"https://Stackoverflow.com/questions/9845354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1289022/"
] | The Counter type is useful for counting items. It was added in python 2.7:
```
import collections
counts = collections.Counter()
for line in datafile:
# remove the EOL and iterate over each character
#if you desire the counts to be case insensitive, replace line.rstrip() with line.rstrip().lower()
for c in line.rstrip():
# Missing items default to 0, so there is no special code for new characters
counts[c] += 1
```
To see the results:
```
results = [(key, value) for key, value in counts.items() if key.isalpha()]
print results
``` | Regular expressions are useful if you want to find complex patterns in a string. Because you want to count (as opposed to find) simple (just single alphabetic characters) “patterns”, regular expressions are not the tool of choice here.
If I understand correctly what you are trying, the most transparent way to solve this is to iterate over all lines, and to iterate over all characters in that line, and if that character is alphabetic, add 1 to a corresponding dictionary entry. In code:
```
filename=raw_input()
found = {}
with open(filename) as file:
for line in file:
for character in line:
if character in "abcdefghijklmnopqrstuvxyz":
# Checking `in (explicit string)` is not quick, but transparent.
# You can use something like `character.isalpha()` if you want it to
# automatically depend on your locale.
found[character] = found.get(character, 0)+1
# If there is no dictionary entry for character yet, assume default 0
# If you need e.g. small and capital letters counted together,
# "Normalize" them to one particular type, for example using
# found[character.upper()] = found.get(character, 0)+1
```
After this loop has run through the file, the dictionary `found` will contain the number of occurences for each character. |
9,845,354 | I'm having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains.
So far I have this, which I can run through CDM, and state a file to open. I've messed around with regular expressions, still can't figure out how to count individual characters. Any ideas? sorry if I explained this badly.
```
import sys
import re
filename = raw_input()
count = 0
datafile=open(filename, 'r')
``` | 2012/03/23 | [
"https://Stackoverflow.com/questions/9845354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1289022/"
] | I'd stay away from regexes. They'll be slow and ugly. Instead, read the entire file into a string, and use the built-in string method `count` to count the characters.
To put it together for you:
```
filename = raw_input()
datafile=open(filename, 'r')
data = datafile.read()
datafile.close() # Don't forget to close the file!
counts = {} # make sure counts is an empty dictionary
data = data.lower() # convert data to lowercase
for k in range(97, 123): # letters a to z are ASCII codes 97 to 122
character = chr(k) # get the ASCII character from the number
counts[character] = data.count(character)
```
Then, you have a dictionary `counts` containing all the counts. For example, `counts['a']` gives you the number of `a`s in the file. Or, for the entire list of counts, do `counts.items()`. | If you want to use regular expressions, you can do as follows:
```
pattern = re.compile('[^a-zA-Z]+') # pattern for everything but letters
only_letters = pattern.sub(text, '') # delete everything else
count = len(only_letters) # total number of letters
```
For counting the number of distinct characters, use Counter as already adviced. |
9,845,354 | I'm having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains.
So far I have this, which I can run through CDM, and state a file to open. I've messed around with regular expressions, still can't figure out how to count individual characters. Any ideas? sorry if I explained this badly.
```
import sys
import re
filename = raw_input()
count = 0
datafile=open(filename, 'r')
``` | 2012/03/23 | [
"https://Stackoverflow.com/questions/9845354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1289022/"
] | If the file is small enough to be read all at once, it's very easy indeed:
```
from collections import Counter
filename = raw_input()
with open(filename) as f:
data = f.read()
counter = Counter(data.lower())
print('\n'.join(str((ch, counter[ch])) for ch in counter if ch.isalpha()))
``` | If you want to use regular expressions, you can do as follows:
```
pattern = re.compile('[^a-zA-Z]+') # pattern for everything but letters
only_letters = pattern.sub(text, '') # delete everything else
count = len(only_letters) # total number of letters
```
For counting the number of distinct characters, use Counter as already adviced. |
9,845,354 | I'm having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains.
So far I have this, which I can run through CDM, and state a file to open. I've messed around with regular expressions, still can't figure out how to count individual characters. Any ideas? sorry if I explained this badly.
```
import sys
import re
filename = raw_input()
count = 0
datafile=open(filename, 'r')
``` | 2012/03/23 | [
"https://Stackoverflow.com/questions/9845354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1289022/"
] | I'd stay away from regexes. They'll be slow and ugly. Instead, read the entire file into a string, and use the built-in string method `count` to count the characters.
To put it together for you:
```
filename = raw_input()
datafile=open(filename, 'r')
data = datafile.read()
datafile.close() # Don't forget to close the file!
counts = {} # make sure counts is an empty dictionary
data = data.lower() # convert data to lowercase
for k in range(97, 123): # letters a to z are ASCII codes 97 to 122
character = chr(k) # get the ASCII character from the number
counts[character] = data.count(character)
```
Then, you have a dictionary `counts` containing all the counts. For example, `counts['a']` gives you the number of `a`s in the file. Or, for the entire list of counts, do `counts.items()`. | Regular expressions are useful if you want to find complex patterns in a string. Because you want to count (as opposed to find) simple (just single alphabetic characters) “patterns”, regular expressions are not the tool of choice here.
If I understand correctly what you are trying, the most transparent way to solve this is to iterate over all lines, and to iterate over all characters in that line, and if that character is alphabetic, add 1 to a corresponding dictionary entry. In code:
```
filename=raw_input()
found = {}
with open(filename) as file:
for line in file:
for character in line:
if character in "abcdefghijklmnopqrstuvxyz":
# Checking `in (explicit string)` is not quick, but transparent.
# You can use something like `character.isalpha()` if you want it to
# automatically depend on your locale.
found[character] = found.get(character, 0)+1
# If there is no dictionary entry for character yet, assume default 0
# If you need e.g. small and capital letters counted together,
# "Normalize" them to one particular type, for example using
# found[character.upper()] = found.get(character, 0)+1
```
After this loop has run through the file, the dictionary `found` will contain the number of occurences for each character. |
9,845,354 | I'm having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains.
So far I have this, which I can run through CDM, and state a file to open. I've messed around with regular expressions, still can't figure out how to count individual characters. Any ideas? sorry if I explained this badly.
```
import sys
import re
filename = raw_input()
count = 0
datafile=open(filename, 'r')
``` | 2012/03/23 | [
"https://Stackoverflow.com/questions/9845354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1289022/"
] | If the file is small enough to be read all at once, it's very easy indeed:
```
from collections import Counter
filename = raw_input()
with open(filename) as f:
data = f.read()
counter = Counter(data.lower())
print('\n'.join(str((ch, counter[ch])) for ch in counter if ch.isalpha()))
``` | Regular expressions are useful if you want to find complex patterns in a string. Because you want to count (as opposed to find) simple (just single alphabetic characters) “patterns”, regular expressions are not the tool of choice here.
If I understand correctly what you are trying, the most transparent way to solve this is to iterate over all lines, and to iterate over all characters in that line, and if that character is alphabetic, add 1 to a corresponding dictionary entry. In code:
```
filename=raw_input()
found = {}
with open(filename) as file:
for line in file:
for character in line:
if character in "abcdefghijklmnopqrstuvxyz":
# Checking `in (explicit string)` is not quick, but transparent.
# You can use something like `character.isalpha()` if you want it to
# automatically depend on your locale.
found[character] = found.get(character, 0)+1
# If there is no dictionary entry for character yet, assume default 0
# If you need e.g. small and capital letters counted together,
# "Normalize" them to one particular type, for example using
# found[character.upper()] = found.get(character, 0)+1
```
After this loop has run through the file, the dictionary `found` will contain the number of occurences for each character. |
57,045,356 | This is a problem given in ***HackWithInfy2019*** in hackerrank.
I am stuck with this problem since yesterday.
Question:
---------
You are given array of N integers.You have to find a pair **(i,j)**
which **maximizes** the value of **GCD(`a[i],a[j]`)+(`j - i`)**
and 1<=i< j<=n
Constraints are:
----------------
2<= **N** <= 10^5
1<= **a[i]** <= 10^5
I've tried this problem using python | 2019/07/15 | [
"https://Stackoverflow.com/questions/57045356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11669081/"
] | Here is an approach that could work:
```
result = 0
min_i = array[1 ... 100000] initialized to 0
for j in [1, 2, ..., n]
for d in divisors of a[j]
let i = min_i[d]
if i > 0
result = max(result, d + j - i)
else
min_i[d] = j
```
Here, `min_i[d]` for each `d` is the smallest `i` such that `a[i] % d == 0`. We use this in the inner loop to, for each `d`, find the first element in the array whose GCD with `a[j]` is at least `d`. When `j` is one of the possible values for which `gcd(a[i], a[j]) + j - i` is maximal, when the inner loop runs with `d` equal to the required GCD, `result` will be set to the correct answer.
The maximum possible number of divisors for a natural number less than or equal to 100,000 is 128 (see [here](https://codeforces.com/blog/entry/14463)). Therefore the inner loop runs at most 128 \* 100,000 = 12.8 million times. I imagine this could pass with some optimizations (although maybe not in Python).
(To iterate over divisors, use a sieve to precompute the smallest nontrivial divisor for each integer from 1 to 100000.) | Here is one way of doing it.
Create a mutable class `MinMax` for storing the min. and max. index.
Create a `Map<Integer, MinMax>` for storing the min. and max. index for a particular divisor.
For each value in `a`, find all divisors for `a[i]`, and update the map accordingly, such that the `MinMax` object stores the min. and max. `i` of the number with that particular divisor.
When done, iterate the map and find the entry with largest result of calculating `key + value.max - value.min`.
The min. and max. values of that entry is your answer. |
44,794,782 | I am in the process of downloading data from firebase, exporting it into a json. After this I am trying to upload it into bigquery but I need to remove the new line feed for big query to accept it.
```
{ "ConnectionTime": 730669.644775033,
"objectId": "eHFvTUNqTR",
"CustomName": "Relay Controller",
"FirmwareRevision": "FW V1.96",
"DeviceID": "F1E4746E-DCEC-495B-AC75-1DFD66527561",
"PeripheralType": 9,
"updatedAt": "2016-12-13T15:50:41.626Z",
"Model": "DF Bluno",
"HardwareRevision": "HW V1.7",
"Serial": "0123456789",
"createdAt": "2016-12-13T15:50:41.626Z",
"Manufacturer": "DFRobot"}
{
"ConnectionTime": 702937.7616419792,
"objectId": "uYuT3zgyez",
"CustomName": "Relay Controller",
"FirmwareRevision": "FW V1.96",
"DeviceID": "F1E4746E-DCEC-495B-AC75-1DFD66527561",
"PeripheralType": 9,
"updatedAt": "2016-12-13T08:08:29.829Z",
"Model": "DF Bluno",
"HardwareRevision": "HW V1.7",
"Serial": "0123456789",
"createdAt": "2016-12-13T08:08:29.829Z",
"Manufacturer": "DFRobot"}
```
This is how I need it but can not figure out how to do this besides manually doing it.
```
{"ConnectionTime": 730669.644775033,"objectId": "eHFvTUNqTR","CustomName": "Relay Controller","FirmwareRevision": "FW V1.96","DeviceID": "F1E4746E-DCEC-495B-AC75-1DFD66527561","PeripheralType": 9,"updatedAt": "2016-12-13T15:50:41.626Z","Model": "DF Bluno","HardwareRevision": "HW V1.7","Serial": "0123456789","createdAt": "2016-12-13T15:50:41.626Z","Manufacturer": "DFRobot"}
{"ConnectionTime": 702937.7616419792, "objectId": "uYuT3zgyez", "CustomName": "Relay Controller", "FirmwareRevision": "FW V1.96", "DeviceID": "F1E4746E-DCEC-495B-AC75-1DFD66527561", "PeripheralType": 9, "updatedAt": "2016-12-13T08:08:29.829Z", "Model": "DF Bluno", "HardwareRevision": "HW V1.7", "Serial": "0123456789", "createdAt": "2016-12-13T08:08:29.829Z", "Manufacturer": "DFRobot"}
```
I am using python to load the json, read it and then write a new one but can not figure out the right code. Thank you!
here is the outline for my python code
```
import json
with open('nospacetest.json', 'r') as f:
data_json=json.load(f)
#b= the file after code for no line breaks is added
with open('testnoline.json', 'w') as outfile:
json.dump=(b, outfile)
``` | 2017/06/28 | [
"https://Stackoverflow.com/questions/44794782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8192249/"
] | Reading between the lines, I think the input format might be a single JSON array, and the desired output is newline-separated JSON representations of the elements of that array. If so, this is probably all that's needed:
```
with open('testnoline.json', 'w') as outfile:
for obj in data_json:
outfile.write(json.dumps(obj) + "\n")
``` | You only need to make sure that `indent=None` when you [`dump`](https://docs.python.org/2/library/json.html#basic-usage) you data to json:
```
with open('testnoline.json', 'w') as outfile:
json.dump(data_json, outfile, indent=None)
```
Quoting from the doc:
>
> If `indent` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. `None` (the default) selects the most compact representation.
>
>
> |
42,281,484 | I am attempting to measure the period of time from when a user submits a PHP form to when they submit again. The form's action is the same page so effectively it's just a refresh. Moreover, the user may input the same data again. I need it so that it begins counting before the page refreshes as the result must be as accurate as possible. I have already tried a number of methods but none of which resulted in any success. I have simplified the following code:
**HTML Form**
```
<form method="GET" action="index.php">
<input id="motion_image" type="image" value="1" name="x" src="img/btn1.png">
<input id="motion_image" type="image" value="2" name="x" src="img/btn2.png">
</form>
```
Ultimately, I need to have a PHP or JavaScript variable of how long it took a user to press either one of these two buttons to when they again press either one of them. It is important that the counter begins before the refresh as the variable needs to be as accurate as possible. Furthermore, it needs to be responsive so that after say 5 seconds it triggers an event (e.g. a JavaScript alert). I did not feel it was necessary to include my previous attempts as they were all unsuccessful and I believe there is probably a better way. I have full access to the server the site is being hosted on so running a python sub script and exchanging variables using JSON or any other similar solutions are entirely possible.
Apologies for any mistakes and my general lack of stack overflow skills :)
Thanks | 2017/02/16 | [
"https://Stackoverflow.com/questions/42281484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You could try a simple extension. Here's an example:
```
extension UIImageView {
func render(with radius: CGFloat) {
// add the shadow to the base view
self.backgroundColor = UIColor.clear
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 10)
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 10
// add a border view for corners
let borderView = UIView()
borderView.frame = self.bounds
borderView.layer.cornerRadius = radius
borderView.layer.masksToBounds = true
self.addSubview(borderView)
// add the image for clipping
let subImageView = UIImageView()
subImageView.image = self.image
subImageView.frame = borderView.bounds
borderView.addSubview(subImageView)
//for performance
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 10).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
}
}
```
Usage:
```
myImageView.image = image
myImageView.render(with: 10)
```
Obviously you can add as many parameters as you want to the extension, set defaults, break it into separate methods, etc.
Result:
[](https://i.stack.imgur.com/LNoqh.png) | You can just add the image in and give it a few attributes to make it round.
When you have the UImage selected click on the attributes tab and click on the '+' and type in
```
layer.cornerRadius
```
And change it to a number instead of a string. All number 1-50 work. If you want a perfect circle then type in 50. |
42,281,484 | I am attempting to measure the period of time from when a user submits a PHP form to when they submit again. The form's action is the same page so effectively it's just a refresh. Moreover, the user may input the same data again. I need it so that it begins counting before the page refreshes as the result must be as accurate as possible. I have already tried a number of methods but none of which resulted in any success. I have simplified the following code:
**HTML Form**
```
<form method="GET" action="index.php">
<input id="motion_image" type="image" value="1" name="x" src="img/btn1.png">
<input id="motion_image" type="image" value="2" name="x" src="img/btn2.png">
</form>
```
Ultimately, I need to have a PHP or JavaScript variable of how long it took a user to press either one of these two buttons to when they again press either one of them. It is important that the counter begins before the refresh as the variable needs to be as accurate as possible. Furthermore, it needs to be responsive so that after say 5 seconds it triggers an event (e.g. a JavaScript alert). I did not feel it was necessary to include my previous attempts as they were all unsuccessful and I believe there is probably a better way. I have full access to the server the site is being hosted on so running a python sub script and exchanging variables using JSON or any other similar solutions are entirely possible.
Apologies for any mistakes and my general lack of stack overflow skills :)
Thanks | 2017/02/16 | [
"https://Stackoverflow.com/questions/42281484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You could try a simple extension. Here's an example:
```
extension UIImageView {
func render(with radius: CGFloat) {
// add the shadow to the base view
self.backgroundColor = UIColor.clear
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 10)
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 10
// add a border view for corners
let borderView = UIView()
borderView.frame = self.bounds
borderView.layer.cornerRadius = radius
borderView.layer.masksToBounds = true
self.addSubview(borderView)
// add the image for clipping
let subImageView = UIImageView()
subImageView.image = self.image
subImageView.frame = borderView.bounds
borderView.addSubview(subImageView)
//for performance
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 10).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
}
}
```
Usage:
```
myImageView.image = image
myImageView.render(with: 10)
```
Obviously you can add as many parameters as you want to the extension, set defaults, break it into separate methods, etc.
Result:
[](https://i.stack.imgur.com/LNoqh.png) | You have to do the following below `super.layoutSubviews()`:
```
self.clipToBound = true
```
What is ClipToBound?
clipsToBounds property
>
> A Boolean value that determines whether subviews are confined to the
> bounds of the view.
>
>
> Discussion Setting this value to YES causes subviews to be clipped to
> the bounds of the receiver. If set to NO, subviews whose frames extend
> beyond the visible bounds of the receiver are not clipped. The default
> value is NO.
>
>
> |
42,281,484 | I am attempting to measure the period of time from when a user submits a PHP form to when they submit again. The form's action is the same page so effectively it's just a refresh. Moreover, the user may input the same data again. I need it so that it begins counting before the page refreshes as the result must be as accurate as possible. I have already tried a number of methods but none of which resulted in any success. I have simplified the following code:
**HTML Form**
```
<form method="GET" action="index.php">
<input id="motion_image" type="image" value="1" name="x" src="img/btn1.png">
<input id="motion_image" type="image" value="2" name="x" src="img/btn2.png">
</form>
```
Ultimately, I need to have a PHP or JavaScript variable of how long it took a user to press either one of these two buttons to when they again press either one of them. It is important that the counter begins before the refresh as the variable needs to be as accurate as possible. Furthermore, it needs to be responsive so that after say 5 seconds it triggers an event (e.g. a JavaScript alert). I did not feel it was necessary to include my previous attempts as they were all unsuccessful and I believe there is probably a better way. I have full access to the server the site is being hosted on so running a python sub script and exchanging variables using JSON or any other similar solutions are entirely possible.
Apologies for any mistakes and my general lack of stack overflow skills :)
Thanks | 2017/02/16 | [
"https://Stackoverflow.com/questions/42281484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You could try a simple extension. Here's an example:
```
extension UIImageView {
func render(with radius: CGFloat) {
// add the shadow to the base view
self.backgroundColor = UIColor.clear
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 10)
self.layer.shadowOpacity = 0.3
self.layer.shadowRadius = 10
// add a border view for corners
let borderView = UIView()
borderView.frame = self.bounds
borderView.layer.cornerRadius = radius
borderView.layer.masksToBounds = true
self.addSubview(borderView)
// add the image for clipping
let subImageView = UIImageView()
subImageView.image = self.image
subImageView.frame = borderView.bounds
borderView.addSubview(subImageView)
//for performance
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 10).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
}
}
```
Usage:
```
myImageView.image = image
myImageView.render(with: 10)
```
Obviously you can add as many parameters as you want to the extension, set defaults, break it into separate methods, etc.
Result:
[](https://i.stack.imgur.com/LNoqh.png) | You could try to remove the :
```
let imgLayer = CAShapeLayer()
let myImage = image.cgImage
```
And replace the code with:
```
Image.frame = bounds
Image.masksToBounds = true
Image.contents = myImage
Image.path = UIBezierPath(roundedRect: bounds, cornerRadius: 14).cgPath
Image.cornerRadius = 14
```
Xcode might not be liking the alias that you giving the image.
Then you also need to write in the brackets for the UIView
```
Layer.addsublayer(Image)
``` |
37,083,591 | I've been creating a studying program for learning japanese using python and tried condensing and randomizing it butnow it doesnt do the input,i have analyzed it multiple times and cant find any reason here is what i have for it so far,any suggestions would be appreciate
```
import sys
import random
start = input("Are you ready to practice Japanese Lesson 1? ")
if start.lower() =="yes":
print("Ok Let's Begin")
questiontimer = 0
while questiontimer<10:
questiontimer = (int(questiontimer) + 1)
WordList = ["konnichiwa"]
rand_word = random.choice(WordList)
if rand_word == "konnichiwa":
answer = input("Question "+ questiontimer +":Say hello In japanese.")
if rand_word == answer.lower():
print("Correct!")
elif randword!= answer.lower():
print("Incorrect, the answer is Konnichiwa")
```
this is as condensed as i could get it to reproduce the problem after
```
print("Ok Let's Begin")
```
it is supposed to pick a random string from the list then ask for input based on which word it is right now it has only one string in the list but still does not print what is in the input or allow input for the answer | 2016/05/07 | [
"https://Stackoverflow.com/questions/37083591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6302586/"
] | You can encrypt your parameters string and then send it as a message
>
> Encrypted URL form:
>
>
>
```
myAppName://encrypted_query
```
Now when you get a call in your app, you should fetch the `encryptedt_data` out of the URL and should decrypt it before actually doing anything.
>
> Decrypted URL form:
>
>
>
```
myAppName://someQuery?blablabla=123
```
In my believe this is the best and easiest way to get this done. For encryption/decryption best practice check this, [AES Encryption for an NSString on the iPhone](https://stackoverflow.com/questions/1400246/aes-encryption-for-an-nsstring-on-the-iphone) and [this](https://github.com/dev5tec/FBEncryptor).
As long as you're not concern about the security, you can always use reduced size of encryption string to make a URL smaller. That option is given in Github library. | >
> So the best way to go about this is to insert the URL scheme `myAppName://someQuery?blablabla=123` and that should in turn fire the `openURL` command and open that specific view.
>
>
>
I'm assuming you're using a web view and that's why you want to handle things this way. But are you aware of the `WKScriptMessageHandler` protocol in the new `WKWebView` class?
If you embed `onclick='window.webkit.messageHandlers.yourHandlerName.postMessage(yourUserData)'` on the web side, and setup one or more script message handlers through the `WKUserContentController` of your `WKWebView`, their `-userContentController:didReceiveScriptMessage:` methods will be called with `yourUserData` as the message body. |
33,362,977 | i got a program which needs to send a byte array via a serial communication. And I got no clue how one can make such a thing in python.
I found a c/c++/java function which creates the needed byte array:
```
byte[] floatArrayToByteArray(float[] input)
{
int len = 4*input.length;
int index=0;
byte[] b = new byte[4];
byte[] out = new byte[len];
ByteBuffer buf = ByteBuffer.wrap(b);
for(int i=0;i<input.length;i++)
{
buf.position(0);
buf.putFloat(input[i]);
for(int j=0;j<4;j++) out[j+i*4]=b[3-j];
}
return out;
}
```
but how can I translate that to python code.
edit: the serial data is send to a device. where I can not change the firmware.
thanks | 2015/10/27 | [
"https://Stackoverflow.com/questions/33362977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2206668/"
] | Put your data to array (here are [0,1,2] ), and send with: serial.write(). I assume you've properly opened serial port.
```
>> import array
>> tmp = array.array('B', [0x00, 0x01, 0x02]).tostring()
>> ser.write(tmp.encode())
```
Ansvered using: [Binary data with pyserial(python serial port)](https://stackoverflow.com/questions/472977/binary-data-with-pyserialpython-serial-port)
and this:[pySerial write() won't take my string](https://stackoverflow.com/questions/22275079/pyserial-write-wont-take-my-string) | It depends on if you are sending a signed or unsigned and other parameters. There is a bunch of documentation on this. This is an example I have used in the past.
```
x1= 0x04
x2 = 0x03
x3 = 0x02
x4 = x1+ x2+x3
input_array = [x1, x2, x3, x4]
write_bytes = struct.pack('<' + 'B' * len(input_array), *input_array)
ser.write(write_bytes)
```
To understand why I used 'B' and '<' you have to refer to pyserial documentation.
<https://docs.python.org/2/library/struct.html> |
35,877,007 | I need a cron job to work on a file named like this:
```
20160307_20160308_xxx_yyy.csv
(yesterday_today_xxx_yyy.csv)
```
And my cron job looks like this:
```
53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date -d "yesterday" +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron.log 2>&1
```
Today's date is getting calculated properly but I am unable to get yesterday's date working. The error is:
```
IOError: [Errno 2] No such file or directory: 'tmp/_20160308_xxx_yyy.csv'
```
Please help! | 2016/03/08 | [
"https://Stackoverflow.com/questions/35877007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351197/"
] | I found the answer to my own question.
I needed to use this to get yesterday's date:
```
53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date -v-1d +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron.log 2>&1
```
Hope it helps somebody! | This version worked for me. Maybe it can be helpful for someone:
```
53 11 * * * /path/to/python /path/to/python/script /path/to/file/$(date --date '-1 day' +"\%Y\%m\%d")_$(date +"\%Y\%m\%d")_xxx_yyy.csv >> /path/to/logfile/cron.log 2>&1
``` |
50,305,112 | I am trying to install pandas in my company computer.
I tried to do
```
pip install pandas
```
but operation retries and then timesout.
then I downloaded the package:
pandas-0.22.0-cp27-cp27m-win\_amd64.whl
and install:
```
pip install pandas-0.22.0-cp27-cp27m-win_amd64
```
But I get the following error:
>
>
> ```
> Retrying (Retry(total=4, connect=None, read=None, redirect=None,
> status=None)) after connection broken by
> 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection
> object at 0x0000000003F16320>, 'Connection to pypi.python.org timed
> out. (connect timeout=15)')': /simple/pytz/
> Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by
> 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection
> object at 0x0000000003F16C50>, 'Connection to pypi.python.org timed
> out. (connect timeout=15)')': /simple/pytz/
> Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by
> 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection
> object at 0x0000000003F16C18>, 'Connection to pypi.python.org timed
> out. (connect timeout=15)')': /simple/pytz/
> Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by
> 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection
> object at 0x0000000003F16780>, 'Connection to pypi.python.org timed
> out. (connect timeout=15)')': /simple/pytz/
> Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by
> 'ConnectTimeoutError(<pip._vendor.urllib3.connection.VerifiedHTTPSConnection
> object at 0x0000000003F16898>, 'Connection to pypi.python.org timed
> out. (connect timeout=15)')': /simple/pytz/
> Could not find a version that satisfies the requirement pytz>=2011k (from pandas==0.22.0) (from versions: )
> No matching distribution found for pytz>=2011k (from pandas==0.22.0)
>
> ```
>
>
I did the same with package: `pandas-0.22.0-cp27-cp27m-win_amd64.whl`
I also tried to use proxies:
```
pip --proxy=IND\namit.kewat:xl123456@192.168.180.150:8880 install numpy
```
But I am unable to get pandas.
when I tried to access the site : <https://pypi.org/project/pandas/#files> I can access it without any problem on explorer | 2018/05/12 | [
"https://Stackoverflow.com/questions/50305112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4570833/"
] | This works for me:
```
pip --default-timeout=1000 install pandas
``` | In my case, my network was configured to use IPV6 by default, so I changed it to work with IPV4 only.
You can do that in the Network connections section in the control panel:
`'Control Panel\All Control Panel Items\Network Connections'`
[](https://i.stack.imgur.com/agR8k.png)
Than disable the IPV6 option:
[](https://i.stack.imgur.com/CN9fw.png) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.