qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
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 $ ``...
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.ZipExt...
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 $ ``...
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.ZipExt...
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, ...
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 $ ``...
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, ...
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 ...
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.p...
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 ...
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 unb...
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....
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 unb...
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...
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...
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(('.|.'...
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 ...
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...
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...
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'.cen...
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 ...
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...
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 ...
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...
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(('.|.'...
``` 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...
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...
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_co...
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...
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 ...
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...
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(('.|.'...
``` # 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_co...
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...
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 = ...
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 scr...
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...
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-14...
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 scr...
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...
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....
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 scr...
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...
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...
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 product...
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); ...
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 com...
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` an...
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 searc...
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 opera...
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"> :''' so...
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 py...
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 expl...
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**...
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 butt...
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. Examp...
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...
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. Examp...
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. Examp...
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...
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 e...
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(...
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 e...
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(...
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 e...
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(...
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 [...
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 e...
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(...
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 some...
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 e...
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 e...
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 [...
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 e...
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 some...
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 e...
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 [...
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 e...
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 some...
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 e...
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 [...
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 some...
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...
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', '-...
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: ...
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...
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', '-...
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...
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...
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: ...
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...
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...
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 ...
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. ...
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 depen...
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 follo...
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...
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 depen...
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-l...
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...
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 depen...
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-l...
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 follo...
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}, 'loc...
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 ...
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-textb...
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 direct...
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 ``` ...
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` ...
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 poi...
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 ...
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 poi...
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. I...
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 re...
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 poi...
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...
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 poi...
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 ...
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 poi...
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. I...
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 poi...
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 * poi...
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 poi...
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. I...
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...
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 poi...
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 * poi...
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 poi...
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. I...
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 poi...
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...
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 a...
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...
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 ...
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\_ls...
@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 cre...
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(...
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...
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...
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'...
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.I...
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...
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 is...
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.I...
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...
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 ...
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.I...
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...
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'...
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 ...
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...
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'...
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...
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 is...
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 ...
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...
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 is...
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...
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 ...
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/...
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) { ...
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...
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 us...
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-wat...
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...
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 wel...
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\_jso...
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 9...
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( ... ): ... ``` ...
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( ... ): ... ``` ...
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 m...
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...
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....
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): se...
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....
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 inst...
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....
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): se...
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 inst...
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....
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): se...
``` 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": ...
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....
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 inst...
``` 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": ...
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\x0...
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 ...
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 ...
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, imageAxis...
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 Ab...
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 ...
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...
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 wi...
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...
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 ...
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 wi...
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...
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 th...
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 wi...
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...
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 ...
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 wi...
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 ...
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 wi...
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...
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 th...
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 wi...
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 th...
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<=...
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 s...
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...
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", "F...
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(...
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 JS...
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 ac...
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, hei...
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 ac...
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, hei...
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 > ...
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 ac...
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, hei...
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 n...
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...
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: > > ...
> > 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 `WKScriptMess...
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...
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...
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....
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...
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: > >...
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'` [![enter image description here](https://i.stack.imgur.com/agR8k.png)](https://i...