Unnamed: 0
int64 0
1.91M
| id
int64 337
73.8M
| title
stringlengths 10
150
| question
stringlengths 21
64.2k
| answer
stringlengths 19
59.4k
| tags
stringlengths 5
112
| score
int64 -10
17.3k
|
---|---|---|---|---|---|---|
1,903,300 | 7,664,767 |
Achieve AVRCP using Pybluez in Linux
|
<p>I want to make my PC as AVRCP bluetooth controller (CT) and handle a device which supports AVRCP bluetooth profile This has to be done using python scripting. Can I achieve this from pyBluez. If yes can some one give me some pointer of how to achieve this.</p>
<p>Thanks in Advance</p>
|
<p>I'm also exploring this area. Further to the links provided by Radu, I've found <a href="https://trac.ctdo.de/ctdo/browser/btctl/src/pyavrcp" rel="nofollow">https://trac.ctdo.de/ctdo/browser/btctl/src/pyavrcp</a> which appears to implement the controller (CT) side of AVRCP, as well as the target (player).</p>
|
python|bluetooth|avrcp
| 1 |
1,903,301 | 52,309,212 |
Can I keep a list of references, that auto update in the list?
|
<p>In its essence, I do this:</p>
<pre><code>a = True
b = False
ls = [a, b]
a = False
print(ls)
> [True, False]
</code></pre>
<p>And what happens is that whatever happens to <code>a</code> is decoupled from the list after the first inclusion. Is there any way to update <code>a</code> and also have the list updating itself, in a clean way?</p>
<p>Of course I could simply do <code>ls[0] = False</code> and be done. But in a large project, with many moving parts, I'd like to avoid non-descriptive bracket indexing.</p>
<p>I assume I could do some messy construct of an instantiated class, and then iterate over the attributes, but that sounds like messy business. Or is it?</p>
|
<p>If you want to avoid indexing and have easy to read attributes then you could just use a class that has class attributes:</p>
<pre><code>class Data:
a = True
</code></pre>
<p>and keep multiple references to it:</p>
<pre><code>data = Data
data2 = Data # or similarly data2 = data
data.a = False
print(data2.a)
# False
</code></pre>
<p>Note that if you instantiate the class you'll need to keep a reference to the instance rather than the class as the original class won't be updated anymore:</p>
<pre><code>data = Data()
data2 = data
data.a = 123
print(data2.a)
# 123
# original class remains unchanged
print(Data().a)
# True
</code></pre>
<p>From Python 3.7 you can use a <a href="https://docs.python.org/3/library/dataclasses.html" rel="nofollow noreferrer">dataclass</a>, which makes instantiation with custom data simpler:</p>
<pre><code>from dataclasses import dataclass
@dataclass
class Data:
a = True
data = Data(a=False)
data2 = data
print(data2.a)
# False
</code></pre>
<p>Finally, if you do care about variable states then there's a good chance you'll be working within a class anyway, in which case you could use a property:</p>
<pre><code>class SomeClass:
def __init__(self):
self.a = False
self.b = True
@property
def ls(self):
return self.a, self.b
some_class = SomeClass()
some_class.a = True
print(some_class.ls)
# True, True
</code></pre>
|
python
| 5 |
1,903,302 | 72,578,256 |
Surprising Performance Results
|
<p>I am surprised by the results of this small performance test (Project Euler #1):</p>
<pre><code>c: 233168 in 134 ms
java: 233168 in 46 ms
py: 233168 in 12 ms
</code></pre>
<p>I have attached the full code examples below as well as the execution shell script.</p>
<p>Does anyone have any idea as to why the c solution is so much slower than both the Java and Python solutions?</p>
<p><strong>C</strong></p>
<pre><code>#include <stdio.h>
int main() {
int i, sum = 0;
for (i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
printf("%d\n", sum);
}
</code></pre>
<p><strong>Java</strong></p>
<pre><code>class Main {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
System.out.println(sum);
}
}
</code></pre>
<p><strong>Python</strong></p>
<pre><code>total = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
total += i
print(total)
</code></pre>
<p><strong>Run.sh</strong> - (slightly redacted for brevity)</p>
<pre><code>milliseconds() {
gdate +%s%3N
}
exec_c() {
$build_cache/a.out
}
exec_py() {
python $build_cache/main.py
}
exec_java() {
java -classpath $build_cache Main
}
time_func() {
start_time=$(milliseconds)
output=$($1)
end_time=$(milliseconds)
delta_time=$((end_time - start_time))
echo "$output in $delta_time ms"
}
run() {
filename=$1
extension=${filename##*.}
case "$extension" in
"c")
cc $filename -o $build_cache/a.out
if [ $? -ne 0 ]; then
exit 1
fi
time_func exec_c
;;
"py")
cp $filename $build_cache/main.py
time_func exec_py
;;
"java")
javac -d $build_cache $filename 2>&1
if [ $? -ne 0 ]; then
exit 1
fi
time_func exec_java
;;
*)
echo "unsupported filetype"
exit 1
;;
esac
}
</code></pre>
|
<p>Upon taking everyone's advice and moving the test to a true benchmarking tool, the surprising result (C being slowest) has disappeared.</p>
<p>Therefore, the failure must have been in the execution harness. However, it is interesting that the previous harness favored C and Java more than the Python solution...</p>
<pre><code>$ hyperfine "./.build/a.out" "./.build/main.py" "java -classpath ./.build Main"
Benchmark 1: ./.build/a.out
Time (mean ± σ): 0.2 ms ± 0.1 ms [User: 0.0 ms, System: 0.1 ms]
Range (min … max): 0.0 ms … 1.9 ms 746 runs
Benchmark 2: ./.build/main.py
Time (mean ± σ): 24.6 ms ± 56.9 ms [User: 6.9 ms, System: 2.3 ms]
Range (min … max): 8.3 ms … 214.1 ms 13 runs
Benchmark 3: java -classpath ./.build Main
Time (mean ± σ): 41.2 ms ± 0.6 ms [User: 39.2 ms, System: 8.2 ms]
Range (min … max): 40.3 ms … 44.6 ms 64 runs
Summary
'./.build/a.out' ran
143.25 ± 350.93 times faster than './.build/main.py'
239.24 ± 195.07 times faster than 'java -classpath ./.build Main'
</code></pre>
|
python|java|c|performance|optimization
| 2 |
1,903,303 | 16,182,703 |
why is easy_install using python 2.6 for zeromq binding installation?
|
<pre><code>sudo easy_install pyzmq
Searching for pyzmq
Best match: pyzmq 13.0.2
Processing pyzmq-13.0.2-py2.6-macosx-10.8-intel.egg
pyzmq 13.0.2 is already the active version in easy-install.pth
Using /Library/Python/2.6/site-packages/pyzmq-13.0.2-py2.6-macosx-10.8-intel.egg
Processing dependencies for pyzmq
Finished processing dependencies for pyzmq
</code></pre>
<p>now I have to run my python programs with zeromq like this </p>
<pre><code>python2.6 program.py
</code></pre>
<p>My default python is python 2.7.
How to install the pyzmq module with python 2.7?</p>
|
<p>probably because the <code>easy_install</code> on your path is for Python 2.6.</p>
<p>Check the output of</p>
<pre><code>which easy_install
head -n 1 $(which easy_install)
</code></pre>
<p>And you will probably have your answer. You may need to install or reinstall setuptools / distribute for Python 2.7, or just make sure the Python 2.7 easy_install is ahead of the 2.6 one on your PATH. You can try</p>
<pre><code>which -a easy_install
</code></pre>
<p>to see where multiple easy_installs are on your PATH.</p>
|
python|zeromq
| 0 |
1,903,304 | 31,908,956 |
Numpy conditional multiply data in array (if true multiply A, false multiply B)
|
<p>Say I have a large array of value 0~255. I wanted every element in this array that is higher than 100 got multiplied by 1.2, otherwise, got multiplied by 0.8.</p>
<p>It sounded simple but I could not find anyway other than iterate through all the variable and multiply it one by one.</p>
|
<p>If <code>arr</code> is your array, then this should work:</p>
<pre><code>arr[arr > 100] *= 1.2
arr[arr <= 100] *= 0.8
</code></pre>
<p><strong>Update:</strong> As pointed out in the comments, this could have the undesired effect of the first step affecting what is done in the second step, so we should instead do something like</p>
<pre class="lang-py prettyprint-override"><code># first get the indexes we of the elements we want to change
gt_idx = arr > 100
le_idx = arr <= 100
# then update the array
arr[gt_idx] *= 1.2
arr[le_idx] *= 0.8
</code></pre>
|
python|arrays|numpy
| 7 |
1,903,305 | 9,835,205 |
How can I replace a character with different patterns (HTML tags) in Python?
|
<p>I have a string like:</p>
<pre><code>hello #this# is #some text string# text text
</code></pre>
<p>I want change it to:</p>
<pre><code>hello <sometag>this</sometag> is <sometag>some text string</sometag> text text
</code></pre>
<p>That is, replace the first <code>#</code> with an HTML tag and the second <code>#</code> with the closing tag, and so on. I am using Python; any body knows any regular expression or something other method?</p>
|
<p>If you want to HTML bold everything separated by hashes surrounded by whitespace, you can do this:</p>
<pre><code>import regex
regex = re.compile('(\s?)#(.*?)#(\s+)')
str = 'hello #this# is #some text string# text text'
str = re.sub(regex, '\\1<b>\\2</b>\\3', str)
</code></pre>
<p>If you want to match without space around the hashes, you change the relevant line to these:</p>
<pre><code>regex = re.compile('#(.*?)#')
re.sub(regex, '<b>\\1</b>', str)
</code></pre>
<p>BUT this will only match paired hashes. In your example, it would result to <code>'<b>text</b>text text<b>text</b>text#text text'</code></p>
|
python|regex
| 1 |
1,903,306 | 26,295,482 |
Confused about variable scope using matplotlib -- axis object
|
<p>I have no idea why the following code works. If I comment out the ax assignment in main, it ceases to work. How does ax get in scope of the function? This is python version 2.7.2.</p>
<p>After a little more research, I've found that functions defined in this same code module see all variables in the <strong>main</strong> block. I had no idea python worked this way! Every variable in the <strong>main</strong> block is visible to all functions in the same source file. This does not strike me as desirable! It seems to violate what functions are about. I suppose this exception is made for <strong>main</strong> code blocks, but I would not have guessed it. </p>
<p>How do I prevent functions defined in this code module from seeing all variables in the <strong>main</strong> block?</p>
<pre><code>import pylab as plt
def f():
ax.plot([1],[2]) # How is this ever defined?
return
if (__name__ == "__main__"):
fig = plt.figure()
plt.clf()
ax = plt.subplot(111,polar=True) # If I comment this out, then ax is not defined error in function call
plt.hold(True)
f()
</code></pre>
|
<p>"This does not strike me as desirable! It seems to violate what functions are about."</p>
<p>You should then simply avoid having global variables in your code. Note that the main block you're referring to, is the global namespace (of that module/script). There is an if-statement, but that doesn't mean the "main" block is suddenly a special function.</p>
<p>What you can do is this (which is often considered better anyway):</p>
<pre><code>import pylab as plt
def f():
ax.plot([1],[2]) # This is now never defined
return
def main():
fig = plt.figure()
plt.clf()
ax = plt.subplot(111,polar=True) # ax is now local to the main() function only.
plt.hold(True)
f()
if __name__ == "__main__": # No parentheses for an if-statement; very un-Pythonic
main()
</code></pre>
<p>Now, this will cause an error every time, because <code>ax</code> is defined only inside <code>main()</code>, and not in the global (module) namespace.</p>
|
python|matplotlib
| 2 |
1,903,307 | 63,270,999 |
Azure VM Run PowerShell Script doesn't Output
|
<p>I'm attempting to run a python script inside of my Windows 10 Azure VM. I've managed to connect to the VM and run the script from an Automation runbook but nothing from the powershell script seems to be outputted after the runbook completes.</p>
<p>My python script stored at <code>C:\Users\username\Desktop\test.py</code>:</p>
<pre><code>print("Hello World.")
</code></pre>
<p>My powershell script stored at <code>C:\Users\username\Desktop\test.ps1</code>:</p>
<pre><code>Write-Output "Starting Script..."
C:\Users\username\Python\python.exe C:\Users\username\Desktop\test.py
Write-Output "Shutting Down..."
</code></pre>
<p>My Azure runbook named VMRunTest:</p>
<pre><code>$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
$rgname ="ParcelTracking"
$vmname ="ParcelTracking-Scraper"
$ScriptToRun = "C:\Users\username\Desktop\test.ps1"
Out-File -InputObject $ScriptToRun -FilePath ScriptToRun.ps1
Invoke-AzureRmVMRunCommand -ResourceGroupName $rgname -Name $vmname -CommandId 'RunPowerShellScript' -ScriptPath ScriptToRun.ps1
Remove-Item -Path ScriptToRun.ps1
</code></pre>
<p>Per the <a href="https://docs.microsoft.com/en-us/azure/virtual-machines/windows/run-command#:%7E:text=Run%20Command%20can%20run%20scripts,script%20within%20a%20virtual%20machine." rel="nofollow noreferrer">documentation</a> it also requires that I open the output port on the VM to allow the <code>443</code> port with the <code>AzureCloud</code> tag. In the <a href="https://i.stack.imgur.com/WMGc2.png" rel="nofollow noreferrer">following image</a> you what my setting are for that.</p>
<p>When I execute the Azure Runbook, I get no errors, warnings, and no exceptions. This is the output that follows:</p>
<pre><code>Logging in to Azure...
Environments
------------
{[AzureChinaCloud, AzureChinaCloud], [AzureCloud, AzureCloud], [AzureGermanCloud, AzureGermanCloud], [AzureUSGovernme...
Value : {Microsoft.Azure.Management.Compute.Models.InstanceViewStatus,
Microsoft.Azure.Management.Compute.Models.InstanceViewStatus}
Name :
StartTime :
EndTime :
Status : Succeeded
Error :
Output :
Capacity : 0
Count : 0
Item :
</code></pre>
<p>So, it appears to have been successful, however I don't see any mention of the <code>Hello World.</code> statement or either output statements from the powershell script. So, I can only assume that the python script is not executing. I also know this from trying this process on a python script that should take roughly ~15minutes to run and it comes back as completed within 1 minute.</p>
<p>I think I'm close, just missing a few minor details somewhere. Any help would be greatly appreciated.</p>
|
<p>I can reproduce your issue, actually it works.</p>
<p>Change the line</p>
<pre><code>Invoke-AzureRmVMRunCommand -ResourceGroupName $rgname -Name $vmname -CommandId 'RunPowerShellScript' -ScriptPath ScriptToRun.ps1
</code></pre>
<p>to</p>
<pre><code>$run = Invoke-AzureRmVMRunCommand -ResourceGroupName $rgname -Name $vmname -CommandId 'RunPowerShellScript' -ScriptPath ScriptToRun.ps1
Write-Output $run.Value[0]
</code></pre>
<p>Then you will be able to see the output(in my vm, I didn't install python, for a quick test, I just use powershell, in your case, it should also work).</p>
<p><a href="https://i.stack.imgur.com/fOPLG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fOPLG.png" alt="enter image description here" /></a></p>
|
python|azure|powershell|azure-runbook|azure-vm
| 0 |
1,903,308 | 32,190,009 |
behavior of len() with arange()
|
<p>With this dataframe, dff:</p>
<pre><code> A B
0 0 a
1 1 a
2 2 b
3 3 b
4 4 b
5 5 b
6 6 c
7 7 c
</code></pre>
<p>I understand how <code>len(dff) == 8</code></p>
<p>However, I don't understand the answer from:</p>
<pre><code>dff['counts'] = np.arange(len(dff))
</code></pre>
<p>which is </p>
<pre><code> A B counts
0 0 a 0
1 1 a 1
2 2 b 2
3 3 b 3
4 4 b 4
5 5 b 5
6 6 c 6
7 7 c 7
</code></pre>
<p>Shouldn't <code>dff['counts']</code> be 8 for every row? What is going on under the hood?</p>
|
<p>You seem to misunderstand what <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html" rel="nofollow"><code>np.arange</code></a> does:</p>
<pre><code>In [32]:
np.arange(8)
Out[32]:
array([0, 1, 2, 3, 4, 5, 6, 7])
</code></pre>
<p>Here the length of your df is being used to set the <code>stop</code> param:</p>
<p>From the docs:</p>
<pre><code>numpy.arange([start, ]stop, [step, ]dtype=None)
Return evenly spaced values within a given interval.
Values are generated within the half-open interval [start, stop) (in other words, the interval including start but excluding stop). For integer arguments the function is equivalent to the Python built-in range function, but returns an ndarray rather than a list.
When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.
Parameters:
start : number, optional
Start of interval. The interval includes this value. The default start value is 0.
stop : number
End of interval. The interval does not include this value, except in some cases where step is not an integer and floating point round-off affects the length of out.
step : number, optional
Spacing between values. For any output out, this is the distance between two adjacent values, out[i+1] - out[i]. The default step size is 1. If step is specified, start must also be given.
dtype : dtype
The type of the output array. If dtype is not given, infer the data type from the other input arguments.
Returns:
arange : ndarray
Array of evenly spaced values.
For floating point arguments, the length of the result is ceil((stop - start)/step). Because of floating point overflow, this rule may result in the last element of out being greater than stop.
</code></pre>
<p>if you wanted to set every row to the same value you could do just </p>
<pre><code>In [34]:
dff['counts'] = len(dff)
dff
Out[34]:
A B counts
0 0 a 8
1 1 a 8
2 2 b 8
3 3 b 8
4 4 b 8
5 5 b 8
6 6 c 8
7 7 c 8
</code></pre>
|
python|pandas
| 2 |
1,903,309 | 32,154,209 |
AngularJS is not loading
|
<p>Hi people I have a html file named responsive.html. I want to use angularJS here. my resposive.html looks like this</p>
<pre><code><html ng-app="a">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="static/js/angular.min.js"></script>
<script src="static/js/app.js"></script>
<script src="../../dist/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</head>
<title> Helooqw</title>
<body ng-controller="aA">
{{ name }}
</body>
</html>
</code></pre>
<p>and my app.js</p>
<pre><code>var app = angular.module('a', []);
app.controller('aA', ['$scope', function($scope){
$scope.name = 'Gentle lah';
}])
</code></pre>
<p>But when I load the page, i dont able to see the name there. Please help on this issue. Thanks in advance.
Attached is my directory:</p>
<p><a href="https://i.stack.imgur.com/OgXMe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OgXMe.png" alt="enter image description here"></a></p>
|
<p>Added verbatim because its using django.</p>
<pre><code><html ng-app="a">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="static/js/angular.min.js"></script>
<script src="static/js/app.js"></script>
</head>
<title> Heloow</title>
<body ng-controller="aA">
{% verbatim %}
{{ name }}
{% endverbatim %}
</body>
</html>
</code></pre>
|
python|html|angularjs|django|angularjs-controller
| 0 |
1,903,310 | 28,027,566 |
How do I display the results of basic shell commands in a Django 1.4 website?
|
<p>Currently have built static web pages with Django and was just wondering how would I go about displaying the results of a basic shell command, such as 'ls -l' on one of these web pages.</p>
<p>Would it be possible to specifically assign a certain div to display the results?</p>
|
<p>Use the <code>os</code> module to execute the command:</p>
<pre><code>import os
from django.shortcuts import render
def command_view(request):
output = os.popen('ls -l').read()
return render(request, 'command.html', {'output': output})
</code></pre>
<p>And put the result of the command into the <code><pre></code> tag:</p>
<pre><code><pre>{{ output }}</pre>
</code></pre>
|
python|django|shell
| 6 |
1,903,311 | 28,282,997 |
Decode french in python
|
<p>I need to parse french string ("Vidéo") from UTF-8 file.
But I get <code>'Vid\xc3\xa9o'</code> instead of desired sting.</p>
<p>I tried decode('utf-8') but it will fail with following result: </p>
<pre><code>'Vid\xe9o'
</code></pre>
<p>How to fix this encoding issue?</p>
|
<p><code>'\xe9'</code> is the correct representation of the unicode 'é'. <code>\x</code> is the string escape sequence for a hexadecimal character and 'e9' is the hexadecimal value of the character 'é'. If you write the value of the string <code>'Vid\xe9o'</code> to a file and open it with a program which supports displaying unicode characters, it should show up as 'Vidéo'.</p>
|
python|utf-8
| 3 |
1,903,312 | 44,118,193 |
How to Spawn additional Rectangles in Pygame?
|
<p>I'm creating a simple game and I got stuck on a problem.</p>
<p>The game goes like this:
"White square" eats "Green Squares"</p>
<p><strong>Question:</strong><br>
How can I spawn "New Red squares" and remain on screen each time the "White square" eats a "Green square" ? </p>
<p>Here is the code:</p>
<pre><code>import pygame, sys
from random import randint
from pygame.locals import*
pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Square-it")
clock = pygame.time.Clock()
"Green Square"
green_x = randint(10, 780)
green_y = randint(10, 580)
green_width = 15
green_height = 15
green_color = pygame.Color("green")
green = pygame.Rect(green_x, green_y, green_width, green_height)
"Red Square"
red_x = randint(20, 780)
red_y = randint(20, 580)
red_width = 10
red_height = 10
red_color = pygame.Color("red")
red = pygame.Rect(red_x, red_y, red_width, red_height)
"White Square"
white_x = 400
white_y = 300
white_width = 10
white_height = 10
white_color = pygame.Color("white")
white = pygame.Rect(white_x, white_y, white_width, white_height)
while True:
clock.tick(60)
gameDisplay.fill((0, 20, 5))
gameDisplay.fill(white_color, white)
gameDisplay.fill(green_color, green)
gameDisplay.fill(red_color, red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
'''When White eats Green, Green regenerates'''
if white.colliderect(green):
green = pygame.Rect(randint(10, 780), randint(10, 580), green_width, green_height)
'''White Square Movement'''
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
white.left = white.left - 10
if keys[K_RIGHT]:
white.right = white.right + 10
if keys[K_UP]:
white.top = white.top - 10
if keys[K_DOWN]:
white.bottom = white.bottom + 10
</code></pre>
|
<p>You should first create an array to store all your red rectangle instances</p>
<pre><code>red_square_list = []
</code></pre>
<p>When your white rectangle collide the green rectangle, you should extract x,y position of the green rectangle and create an instance of red rectangle at this position.</p>
<p>To do it, I would recommend to work with classes but first you can create a function to create a red rectangle:</p>
<pre><code>def create_red_square(x, y)
red_width = 10
red_height = 10
red_color = pygame.Color("red")
red = pygame.Rect(red_x, red_y, red_width, red_height)
return red
</code></pre>
<p>Now, everytime white collides green, you have to extract the green rectangle position and display a red one with the function above :</p>
<pre><code>if white.colliderect(green):
pos_x, pos_y = green.left, green.top
green = pygame.Rect(randint(10, 780), randint(10, 580), green_width, green_height)
red_square_list.append(create_red_square(pos_x, pos_y))
</code></pre>
<p>The last line is only to store the red rectangle if you want to use them later (like you do for green / white rectangle)</p>
<p>I hope it helps,</p>
<p><strong><em>EDIT #1:</em></strong></p>
<p>I made some small mistakes is the previous code, this is a working solution :</p>
<p>`
import pygame, sys
from random import randint
from pygame.locals import*</p>
<pre><code>red_square_list = []
pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Square-it")
clock = pygame.time.Clock()
red_color = pygame.Color("red")
"Green Square"
green_x = randint(10, 780)
green_y = randint(10, 580)
green_width = 15
green_height = 15
green_color = pygame.Color("green")
green = pygame.Rect(green_x, green_y, green_width, green_height)
def create_red_square(x, y):
"""Return one instance of Rect at position x, y"""
red_width = 10
red_height = 10
red = pygame.Rect(x, y, red_width, red_height)
return red
"White Square"
white_x = 400
white_y = 300
white_width = 10
white_height = 10
white_color = pygame.Color("white")
white = pygame.Rect(white_x, white_y, white_width, white_height)
while True:
clock.tick(60)
gameDisplay.fill((0, 20, 5))
gameDisplay.fill(white_color, white)
gameDisplay.fill(green_color, green)
for each in red_square_list: #display all red rect
gameDisplay.fill(red_color, each)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
'''When White eats Green, Green regenerates'''
if white.colliderect(green):
# extract green rect position
pos_left, pos_top = green.left, green.top
# store the new red rectangle in the array
red_square_list.append(create_red_square(pos_left+2, pos_top+2))
# +2 is required as red square are 10x10 and green 15x15
# new rect green
new_left = randint(10, 780)
new_top = randint(10, 580)
green = pygame.Rect(new_left, new_top, green_width, green_height)
'''White Square Movement'''
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
white.left = white.left - 10
if keys[K_RIGHT]:
white.right = white.right + 10
if keys[K_UP]:
white.top = white.top - 10
if keys[K_DOWN]:
white.bottom = white.bottom + 10
</code></pre>
<p>I hope it helps,</p>
|
python|python-3.x|random|pygame
| 0 |
1,903,313 | 33,056,828 |
BeautifulSoup: extract between href and class?
|
<p>I want to store the dates from the following chunk of text:</p>
<pre><code>newsoup = '''<html><body><a href="/president/washington/speeches/speech-3460">Proclamation
of Pardons in Western Pennsylvania (July 10, 1795)</a>, <a class="transcript" href="/president/washington/speeches/speech-3460">Transcript</a>,
<a href="/president/washington/speeches/speech-3939">Seventh Annual Message to Congress (December 8, 1795)</a></body></html>'''
</code></pre>
<p>But, I'm having trouble getting at the text between <code>></code> and <code></a></code>. Once I get <code>Proclamation of Pardons in Western Pennsylvania (July 10, 1795)</code>, I'll be set. I've tried adapting another approach to my specific data, but I end up with an empty object.</p>
<p>I'm trying something like the following, but having little luck:</p>
<pre><code>a = newsoup.findAll('a',attrs={'href'})
print a
</code></pre>
<p>I should have noted that <code>newsoup</code> was already a soup object.</p>
|
<p>Assuming newsoup is a soup object, I think this should work:</p>
<p>(If it is not, you can run <code>newsoup = BeautifulSoup(newsoup)</code> )</p>
<pre><code>a = newsoup.findAll('a')
for x in a:
print x.text
</code></pre>
|
python|python-2.7|web-scraping|beautifulsoup
| 2 |
1,903,314 | 14,354,209 |
Python script on linux and autostart at boot path
|
<p>I've made a script in Python and it works without problems.
Since I've added a configuration file (I've used a parser) it stopped starting at boot (I have it in my rc.local file with its absolute path).</p>
<p>Investigating further I've found out that I need to specify the absolute path of the configuration file in the python script or it isn't working.</p>
<p>I've like it to work checking simply in the folder where the script file sits.</p>
<p>I mean:</p>
<p>if my script.py is in home folder I'd like it to check for its configuration file in the same folder... If it's in /home/user I'd like it to check in /home/user.</p>
<p>How can I achieve this keeping in mind that rc.local is run by root user with some ENV variables that are different from my normal user's?</p>
|
<p>Base the path off the <code>__file__</code> variable:</p>
<pre><code>import os.path
scriptpath = os.path.abspath(os.path.dirname(__file__))
configfile = os.path.join(scriptpath, configfilename)
</code></pre>
|
python|bash
| 5 |
1,903,315 | 34,423,337 |
In Python, Rename a file with the folder's name in batch
|
<p>My overarching goal is to rename a file with the containing folder's name and move the renamed file to a new location. I am a Python beginner.</p>
<p>How I am stuck.
I am looping through the directory and searching for the folder names, but I don't know how to pull the name of the folder out to use as the name for the file.<a href="http://i.stack.imgur.com/I3IQa.jpg" rel="nofollow">This is what my filing system looks like.</a> Within each of the folders is a file VOP.shp that needs to be renamed and moved or copied elsewhere.</p>
<pre><code>#loop through path
#Convert desired name to string
for root, dirnames, filenames in os.walk(path):
for name in dirnames:
if name.endswith("batch"):
</code></pre>
|
<p>You can find all the files with the extension.shp using the following code:</p>
<pre><code>import glob
glob("a_directory_name/*/*VOP.shp")
</code></pre>
|
python-2.7|batch-processing
| 0 |
1,903,316 | 34,758,600 |
Unsuccessful post to asp.net form using Python requests
|
<p>I am attempting to use Python requests to post a value to the "employer" form in the <a href="http://www.myvisajobs.com/Search_Visa_Sponsor.aspx?N=" rel="nofollow">http://www.myvisajobs.com/Search_Visa_Sponsor.aspx?N=</a></p>
<p>This is what I have tried so far in Python:</p>
<pre><code>import requests
url = "http://www.myvisajobs.com/Search_Visa_Sponsor.aspx?N="
data = {"ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$txtCompany":"Microsoft"}
r = requests.post(url,data)
print(r.text)
</code></pre>
<p>Which returns only the original HTML. I am trying to return the resulting HTML. My gut feeling is I am doing something fundamentally wrong, but I am not sure what. </p>
|
<p>There are much more parameters sent in the search POST request than just the <code>ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$txtCompany</code> referring to the company name.</p>
<p>Instead, to make things transparent and easy, I would use <a href="https://github.com/jmcarp/robobrowser" rel="nofollow"><code>RoboBrowser</code></a> that would "auto-fill" other form POST parameters needed. Example working code:</p>
<pre><code>from robobrowser import RoboBrowser
url = "http://www.myvisajobs.com/Search_Visa_Sponsor.aspx?N="
browser = RoboBrowser(history=True)
browser.open(url)
form = browser.get_form(id='aspnetForm')
form['ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$txtCompany'].value = 'Microsoft'
browser.submit_form(form)
results = browser.select('div#ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder1_divContent table tr')[1:]
for result in results:
cells = result.find_all("td")
print(cells[2].get_text(strip=True))
</code></pre>
<p>It prints the company names from the search results:</p>
<pre><code>Microsoft Corporation
Microsoft Operations Puerto Rico, Llc
Microsoft Caribbean, Inc.
Standard Microsystems Corporation
4Microsoft Corporation
Microsoft Business Solutions Corporation
Microsoft C98052orporation
Microsoft Ccrporation
Microsoft Coiporation
Microsoft Copporation
Microsoft Corforation
Microsoft Licensing, GP
Microsoft Way
Microsoftech Inc
Quantitative Micro Software Llc
Webtv Networks Microsoft Sub
Microsoft
FAST, A Microsoft Subsidiary
Microsoft Corporation - Sham
Microsoft Partner Careers (sponsored By Microsoft Dynamics)
Microsoft Iberica
Microsoft Karthi
</code></pre>
|
python|asp.net
| 1 |
1,903,317 | 12,238,005 |
Shuffling list, but keeping some elements frozen
|
<p>I've such a problem:</p>
<p>There is a list of elements of class <code>CAnswer</code> (no need to describe the class), and I need to shuffle it, but with one constraint - some elements of the list have <code>CAnswer.freeze</code> set to <code>True</code>, and those elements must not be shuffled, but remain on their original positions. So, let's say, for a given list:</p>
<pre><code>[a, b, c, d, e, f]
</code></pre>
<p>Where all elements are instances of <code>CAnswer</code>, but <code>c.freeze == True</code>, and for others <code>freeze == False</code>, the possible outcome could be:</p>
<pre><code>[e, a, c, f, b, d]
</code></pre>
<p>So element with index 2 is still on its position.</p>
<p>What is the best algorithm to achieve it?</p>
<p>Thank you in advance :)</p>
|
<p>Another solution:</p>
<pre><code># memorize position of fixed elements
fixed = [(pos, item) for (pos,item) in enumerate(items) if item.freeze]
# shuffle list
random.shuffle(items)
# swap fixed elements back to their original position
for pos, item in fixed:
index = items.index(item)
items[pos], items[index] = items[index], items[pos]
</code></pre>
|
python|python-2.7
| 14 |
1,903,318 | 23,392,544 |
wxPython: Show Frame while doing something in other thread
|
<p>in my GUI with wxPython if have to do some calculations which can take some time. So I want to start them in a seperate Thread and show a window in the GUI that prints that the program is calculating. The main windows should be disabled during this.
So that's my code:</p>
<pre><code>import time
import threading
import wx
def calculate():
# Simulates the calculation
time.sleep(5)
return True
class CalcFrame(wx.Frame):
def __init__(self, parent, id):
wx.Frame.__init__(self, parent=None, id=-1, title="Calculate")
# Normally here are some intctrls, but i dont show them to keep it easy
self.panel = wx.Panel(parent=self, id=-1)
self.createButtons()
def createButtons(self):
button = wx.Button(parent=self.panel, id=-1, label="Calculate")
button.Bind(wx.EVT_BUTTON, self.onCalculate)
def onCalculate(self, event):
calcThread = threading.Thread(target=calculate)
checkThread = threading.Thread(target=self.checkThread, args=(calcThread,))
self.createWaitingFrame()
self.waitingFrame.Show(True)
self.Disable()
calcThread.run()
checkThread.run()
def createWaitingFrame(self):
self.waitingFrame = wx.MiniFrame(parent=self, title="Please wait")
panel = wx.Panel(parent=self.waitingFrame)
waitingText = wx.StaticText(parent=panel, label="Please wait - Calculating", style=wx.ALIGN_CENTER)
def checkThread(self, thread):
while thread.is_alive():
pass
print "Fertig"
self.waitingFrame.Destroy()
self.Enable()
app = wx.PySimpleApp()
frame = CalcFrame(parent=None, id=-1)
frame.Show()
app.MainLoop()
</code></pre>
<p>But my problem is now, that if i press the "Calculate" button, the waitingFrame isnt't shown right, I can't see the text. I also cant move/maximize/minimize the main window.
Can you help me? Thank you in advance :)</p>
|
<p>you should never update the gui in a thread other than the main thread .... Im pretty sure the docs for wxPython mention this in several places .. it is not thread safe and your gui gets in broken states ...</p>
<p>instead I believe you are supposed to do something like</p>
<pre><code>def thread1():
time.sleep(5)
return True
def thread2(t1,gui):
while thread.is_alive():
pass
print "Fertig"
wx.CallAfter(gui.ThreadDone)
class MyFrame(wx.Frame):
def startThread(self):
calcThread = threading.Thread(target=thread1)
checkThread = threading.Thread(target=thread2, args=(calcThread,self))
def ThreadDone(self):
print "Both threads done???"
print "Now modify gui from main thread(here!)"
</code></pre>
|
python|multithreading|wxpython
| 1 |
1,903,319 | 23,177,221 |
libpython2.7.a missing many references
|
<p>I'm trying to compile a <code>cython</code> module with <code>-static</code>, but I am getting a lot of errors about missing references in <code>libpython2.7.a</code>. For example:</p>
<pre><code> /usr/lib/x86_64-linux-gnu/libpython2.7.a(complexobject.o): In function `_Py_c_pow':
(.text.unlikely+0x507): undefined reference to `pow'
</code></pre>
<p>I already have the package <code>build-essential</code> installed, which is one solution I found on Google.</p>
<p>My work flow is:</p>
<pre><code>cython --embed hi.py
gcc hi.c -lpython2.7 -I /usr/include/python2.7 -static
</code></pre>
<p>What am I missing to be able to link this file statically? </p>
<p>EDIT: Added additional linker options
<code>gcc hi.c -lpython2.7 -lm -pthread -lzlib -I /usr/include/python2.7 -static</code></p>
<p>All the references to undefined functions went away, but ld is saying it can't find lzlib so compilation still fails. Without <code>-lzlib</code> I still get some undefined references.</p>
|
<p>As your package manager will show you, the library for zlib is <code>libz.so</code>, hence you must pass <code>-lz</code>.</p>
<p>Added by question owner:
For other's reference all the linker options needed <code>-lpython2.7 -lm -ldl -lutil -lz -pthread</code></p>
|
python|ubuntu|gcc|cython
| 0 |
1,903,320 | 8,160,632 |
Asynchronous interactive Python script
|
<p>I'm trying to write a simple Python script to interface with a chat server. It would poll the server for updates, and allow the user to enter text to send to the server as chat. I can kind of get something hacked together with multithreading, but it looks terrible. Is there a nice, simple way to display updating information on the screen while also accepting user input? I'd prefer to do it without curses.</p>
|
<p>I don't know how to code with ncurses, but here's a solution with wxWidget. It should be roughly similar regarding the design.</p>
<pre><code>"""Asynchronous interactive Python script"""
import random
import threading
import wx
import wx.lib.mixins.listctrl as listmix
LOCK = threading.Lock()
def threadsafe(function):
"""A decorator that makes a function safe against concurrent accesses."""
def _decorated_function(*args, **kwargs):
"""Replacement function."""
with LOCK:
function(*args, **kwargs)
return _decorated_function
class SharedList(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
"""An output list that can print information from both the user and the server.
N.B.: The _print function that actually updates the list content uses the threadsafe decorator.
"""
def __init__(self, parent, pos=wx.DefaultPosition, size=(-1, -1), style=wx.LC_REPORT):
wx.ListCtrl.__init__(self, parent, wx.ID_ANY, pos, size, style)
self.InsertColumn(0, 'Origin', width=75)
self.InsertColumn(1, 'Output')
listmix.ListCtrlAutoWidthMixin.__init__(self)
self.resizeLastColumn(1000)
self._list_index = 0
def user_print(self, text):
"""Print a line as the user"""
self._print("user", text)
def chat_print(self, text):
"""Print a line as the chat server"""
self._print("chat", text)
@threadsafe
def _print(self, origin, text):
"""Generic print function."""
self.InsertStringItem(self._list_index, str(origin))
self.SetStringItem(self._list_index, 1, str(text))
self.EnsureVisible(self.GetItemCount() - 1)
self._list_index = self._list_index + 1
class ServerChecker(threading.Thread):
"""A separate thread that would connect to the IRC chat."""
def __init__(self, shared_list):
threading.Thread.__init__(self)
self._stop_event = threading.Event()
self._shared_list = shared_list
def run(self):
"""Connection to the server, socket, listen, bla bla bla."""
while not self._stop_event.is_set():
self._shared_list.chat_print("bla bla bla")
self._stop_event.wait(random.randint(1, 3))
def stop(self):
"""Stop the thread."""
self._stop_event.set()
class SampleFrame(wx.Frame):
"""The main GUI element."""
def __init__(self):
super(SampleFrame, self).__init__(parent=None, title='DAS Board', size=(600, 400))
self._shared_list = None
self._user_text = None
self._init_ui()
self._thread = ServerChecker(self._shared_list)
self._thread.start()
self.Bind(wx.EVT_CLOSE, self._on_close)
self.Center()
self.Show()
def _init_ui(self):
"""Building and assembling the graphical elements.
Don't pay too much attention, especially if you want to use ncurses instead.
"""
panel = wx.Panel(self)
self._shared_list = SharedList(panel)
main_box_v = wx.BoxSizer(wx.VERTICAL)
main_box_v.Add(self._shared_list, proportion=1, flag=wx.EXPAND|wx.ALL, border=10)
self._user_text = wx.TextCtrl(panel, -1, value="User text to send...",
style=wx.TE_CENTRE)
main_box_v.Add(self._user_text, proportion=0, flag=wx.EXPAND|wx.ALL, border=10)
button = wx.Button(panel, label="Send user text.")
button.Bind(wx.EVT_BUTTON, self._user_send_text)
main_box_v.Add(button, flag=wx.EXPAND|wx.ALL, border=10)
panel.SetSizer(main_box_v)
def _user_send_text(self, event):
"""Button callback"""
self._shared_list.user_print(self._user_text.GetValue())
event.Skip()
def _on_close(self, event):
"""Stop the separate thread, then destroy the GUI."""
event.Skip()
self._thread.stop()
self.Destroy()
APP = wx.App(0)
SampleFrame()
APP.MainLoop()
</code></pre>
|
python|multithreading
| 0 |
1,903,321 | 368,805 |
Python UnicodeDecodeError - Am I misunderstanding encode?
|
<p>Any thoughts on why this isn't working? I really thought 'ignore' would do the right thing.</p>
<pre><code>>>> 'add \x93Monitoring\x93 to list '.encode('latin-1','ignore')
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
UnicodeDecodeError: 'ascii' codec can't decode byte 0x93 in position 4: ordinal not in range(128)
</code></pre>
|
<p>…there's a reason they're called "encodings"…</p>
<p>A little preamble: think of unicode as the norm, or the ideal state. Unicode is just a table of characters. №65 is latin capital A. №937 is greek capital omega. Just that.</p>
<p>In order for a computer to store and-or manipulate Unicode, it has to <em>encode</em> it into bytes. The most straightforward <em>encoding</em> of Unicode is UCS-4; every character occupies 4 bytes, and all ~1000000 characters are available. The 4 bytes contain the number of the character in the Unicode tables as a 4-byte integer. Another very useful encoding is UTF-8, which can encode any Unicode character with one to four bytes. But there also are some limited encodings, like "latin1", which include a very limited range of characters, mostly used by Western countries. Such <em>encodings</em> use only one byte per character.</p>
<p>Basically, Unicode can be <em>encoded</em> with many encodings, and encoded strings can be <em>decoded</em> to Unicode. The thing is, Unicode came quite late, so all of us that grew up using an 8-bit <em>character set</em> learned too late that all this time we worked with <em>encoded</em> strings. The encoding could be ISO8859-1, or windows CP437, or CP850, or, or, or, depending on our system default.</p>
<p>So when, in your source code, you enter the string "add “Monitoring“ to list" (and I think you wanted the string "add “Monitoring” to list", note the second quote), you actually are using a string already <em>encoded</em> according to your system's default codepage (by the byte \x93 I assume you use Windows codepage 1252, “Western”). If you want to get Unicode from that, you need to <em>decode</em> the string from the "cp1252" encoding.</p>
<p>So, what you meant to do, was:</p>
<pre><code>"add \x93Monitoring\x94 to list".decode("cp1252", "ignore")
</code></pre>
<p>It's unfortunate that Python 2.x includes an <code>.encode</code> method for strings too; this is a convenience function for "special" encodings, like the "zip" or "rot13" or "base64" ones, which have nothing to do with Unicode.</p>
<p>Anyway, all you have to remember for your to-and-fro Unicode conversions is:</p>
<ul>
<li>a Unicode string gets <em>encoded</em> to a Python 2.x string (actually, a sequence of bytes)</li>
<li>a Python 2.x string gets <em>decoded</em> to a Unicode string</li>
</ul>
<p>In both cases, you need to specify the <em>encoding</em> that will be used.</p>
<p>I'm not very clear, I'm sleepy, but I sure hope I help.</p>
<p>PS A humorous side note: Mayans didn't have Unicode; ancient Romans, ancient Greeks, ancient Egyptians didn't too. They all had their own "encodings", and had little to no respect for other cultures. All these civilizations crumbled to dust. Think about it people! Make your apps Unicode-aware, for the good of mankind. :)</p>
<p>PS2 Please don't spoil the previous message by saying "But the Chinese…". If you feel inclined or obligated to do so, though, delay it by thinking that the Unicode BMP is populated mostly by chinese ideograms, ergo Chinese is the basis of Unicode. I can go on inventing outrageous lies, as long as people develop Unicode-aware applications. Cheers!</p>
|
python|unicode|ascii|encode
| 214 |
1,903,322 | 160,889 |
Emulation of lex like functionality in Perl or Python
|
<p>Here's the deal. Is there a way to have strings tokenized in a line based on multiple regexes?</p>
<p>One example:</p>
<p>I have to get all href tags, their corresponding text and some other text based on a different regex.
So I have 3 expressions and would like to tokenize the line and extract tokens of text matching every expression.</p>
<p>I have actually done this using flex (not to be confused with Adobe), which is an implementation of the good old lex. lex provides
an elegant way to do this by executing "actions" based on expressions. One can control the way
lex reading a file too (block / line based read).</p>
<p>The problem is that flex actually produces C/ C++ code which actually does the tokenizing job. I have a
make file which wraps all these things.
I was wondering if perl /python can in some way do the same thing. Its just that I would like to do everything
I like in a single programming language itself.</p>
<p>Tokenizing is just one of the things that I want to do as part of my application.</p>
<p>Apart from perl or python can any language (functional also) do this?</p>
<p>I did read about PLY and ANTLR here (<a href="https://stackoverflow.com/questions/34081/parsing-where-can-i-learn-about-it#34085">Parsing, where can I learn about it</a>).</p>
<p>But is there a way to do it naturally in python itself? pardon my ignorance, but are these tools used in any popular products / services?</p>
<p>Thank you.</p>
|
<p>Look at documentation for following modules on <a href="http://www.cpan.org/" rel="nofollow noreferrer">CPAN</a></p>
<p><a href="http://search.cpan.org/search?query=HTML%3A%3ATreeBuilder&mode=all" rel="nofollow noreferrer">HTML::TreeBuilder</a></p>
<p><a href="http://search.cpan.org/author/MSISK/HTML-TableExtract-2.10/lib/HTML/TableExtract.pm" rel="nofollow noreferrer">HTML::TableExtract</a></p>
<p>and</p>
<p><a href="http://search.cpan.org/search?query=parse+recdescent&mode=all" rel="nofollow noreferrer">Parse::RecDescent</a></p>
<p>I've used these modules to process quite large and complex web-pages.</p>
|
python|perl|parsing|lex
| 8 |
1,903,323 | 42,006,500 |
Downgrade Sphinx from version 1.5.2. to version 1.4.9
|
<p>The search functionality in my Sphinx doc has stopped working after upgrading to version 1.5.1. I'm using the sphinx_rtd_theme. How do I downgrade Sphinx to 1.4.9?</p>
|
<p>inorder to install specific version of sphinx .type in terminal :</p>
<p>pip install sphinx==1.4.9</p>
|
python|python-sphinx
| 2 |
1,903,324 | 41,720,533 |
matplotlib.pyplot 2.0.0 shows empty plots during run time
|
<p>Minimum example:</p>
<pre><code>import matplotlib.pyplot as plt
import time
import numpy as np
plt.ion()
def plot(array):
plt.figure()
plt.plot(array)
plt.show()
for i in range(5):
plot(np.linspace(-10.*i, 10*i, num=101))
time.sleep(15)
</code></pre>
<p>This creates 5 plots and then waits 15 seconds until termination. The plot windows appear, but during these 15 seconds you can see the frames of the plot windows, but the content is transparent (you see the content of other windows below; see attached picture).
This happened after an upgrade to matplotlib to version 2.0.0.</p>
<p>I want the plots to be visible before the program terminates and this was possible before (at least in an ipython console of the spyder IDE). What do I have to adjust?</p>
<p><a href="https://i.stack.imgur.com/rS613.png" rel="nofollow noreferrer">Screenshot of transparent plot windows</a></p>
<p>edit:</p>
<p>Python 2.7.12</p>
<p>matplotlib 2.0.0</p>
<p>ipython: 5.1.0</p>
|
<p>If you are using interactive mode, you should use <code>plt.pause</code> instead of <code>time.sleep</code>. The following works for me,</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
plt.ion()
def plot(array):
plt.figure()
plt.plot(array)
plt.show()
for i in range(5):
plot(np.linspace(-10.*i, 10*i, num=101))
plt.pause(15)
</code></pre>
<p>Generally with interactive plots, I find it works more reliably if you specify the figure and axis <code>ax</code> at the beginning, <code>plt.show</code> them and use <code>ax.plots</code> to update it with <code>plt.draw</code> and <code>plt.pause</code> used whenever you need to update the display. For example,</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig, axs = plt.subplots(5,1)
plt.ion()
plt.show()
def plot(ax, array):
ax.plot(array)
plt.draw()
for i in range(5):
plot(axs[i], np.linspace(-10.*i, 10*i, num=101))
plt.pause(15)
</code></pre>
|
python|matplotlib
| 0 |
1,903,325 | 47,477,744 |
Create variable with multiple return of numpy where
|
<p>Hi i am stata user and now iam trying to pass my codes in stata to python/pandas. In this case i want to create a new variables <code>size</code> that assign the value 1 if the number of jobs is between 1 and 9, the value 2 if jobs is between 10 and 49, 3 between 50 and 199 and 4 for bigger than 200 jobs.</p>
<p>And aftewards, if it is possible label them (1:'Micro', 2:'Small', 3:'Median', 4:'Big')</p>
<pre><code>id year entry cohort jobs
1 2009 0 NaN 3
1 2012 1 2012 3
1 2013 0 2012 4
1 2014 0 2012 11
2 2010 1 2010 11
2 2011 0 2010 12
2 2012 0 2010 13
3 2007 0 NaN 38
3 2008 0 NaN 58
3 2012 1 2012 58
3 2013 0 2012 70
4 2007 0 NaN 231
4 2008 0 NaN 241
</code></pre>
<p>I tried using this code but couldnt succed</p>
<p><code>df['size'] = np.where((1 <= df['jobs'] <= 9),'Micro',np.where((10 <= df['jobs'] <= 49),'Small'),np.where((50 <= df['jobs'] <= 200),'Median'),np.where((200 <= df['empleo']),'Big','NaN'))
</code></p>
|
<p>What you are trying to do is called binning use <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html" rel="nofollow noreferrer"><code>pd.cut</code></a> i.e </p>
<pre><code>df['new'] = pd.cut(df['jobs'],bins=[1,10,50,201,np.inf],labels=['micro','small','medium','big'])
</code></pre>
<p>Output: </p>
<pre><code> id year entry cohort jobs new
0 1 2009 0 NaN 3 micro
1 1 2012 1 2012.0 3 micro
2 1 2013 0 2012.0 4 micro
3 1 2014 0 2012.0 11 small
4 2 2010 1 2010.0 11 small
5 2 2011 0 2010.0 12 small
6 2 2012 0 2010.0 13 small
7 3 2007 0 NaN 38 small
8 3 2008 0 NaN 58 medium
9 3 2012 1 2012.0 58 medium
10 3 2013 0 2012.0 70 medium
11 4 2007 0 NaN 231 big
12 4 2008 0 NaN 241 big
</code></pre>
<p>For multiple conditions you have to go for <a href="https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>np.select</code></a> not <code>np.where</code>. Hope that helps.<br>
</p>
<blockquote>
<pre><code>numpy.select(condlist, choicelist, default=0)
</code></pre>
<p>Where condlist is the list of your condtions, and choicelist is the
list of choices if condition is met. default = 0, here you can put
that as np.nan</p>
</blockquote>
<p>Using <code>np.select</code> for doing the same with the help of <code>.between</code> i.e </p>
<pre><code>np.select([df['jobs'].between(1,10),
df['jobs'].between(10,50),
df['jobs'].between(50,200),
df['jobs'].between(200,np.inf)],
['Micro','Small','Median','Big']
,'NaN')
</code></pre>
|
python|python-3.x|pandas|numpy
| 2 |
1,903,326 | 70,905,872 |
Overflowerror when reading from s3 - signed integer is greater than maximum
|
<p>Reading a large file from S3 ( >5GB) into lambda with the following code:</p>
<pre><code>import json
import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
response = s3.get_object(
Bucket="my-bucket",
Key="my-key"
)
text_bytes = response['Body'].read()
...
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
</code></pre>
<p>However I get the following error:</p>
<pre><code>"errorMessage": "signed integer is greater than maximum"
"errorType": "OverflowError"
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 13, in lambda_handler\n text_bytes = response['Body'].read()\n"
" File \"/var/runtime/botocore/response.py\", line 77, in read\n chunk = self._raw_stream.read(amt)\n"
" File \"/var/runtime/urllib3/response.py\", line 515, in read\n data = self._fp.read() if not fp_closed else b\"\"\n"
" File \"/var/lang/lib/python3.8/http/client.py\", line 472, in read\n s = self._safe_read(self.length)\n"
" File \"/var/lang/lib/python3.8/http/client.py\", line 613, in _safe_read\n data = self.fp.read(amt)\n"
" File \"/var/lang/lib/python3.8/socket.py\", line 669, in readinto\n return self._sock.recv_into(b)\n"
" File \"/var/lang/lib/python3.8/ssl.py\", line 1241, in recv_into\n return self.read(nbytes, buffer)\n"
" File \"/var/lang/lib/python3.8/ssl.py\", line 1099, in read\n return self._sslobj.read(len, buffer)\n"
]
</code></pre>
<p>I am using Python 3.8, and I found here an issue with Python 3.8/9 that might be why: <a href="https://bugs.python.org/issue42853" rel="noreferrer">https://bugs.python.org/issue42853</a></p>
<p>Is there any way around this?</p>
|
<p>As mentioned in the bug you linked to, the core issue in Python 3.8 is the bug with reading more than 1gb at a time. You can use a variant of the workaround suggested in the bug to read the file in chunks.</p>
<pre><code>import boto3
s3 = boto3.client('s3')
def lambda_handler(event, context):
response = s3.get_object(
Bucket="-example-bucket-",
Key="path/to/key.dat"
)
buf = bytearray(response['ContentLength'])
view = memoryview(buf)
pos = 0
while True:
chunk = response['Body'].read(67108864)
if len(chunk) == 0:
break
view[pos:pos+len(chunk)] = chunk
pos += len(chunk)
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
</code></pre>
<p>At best, however, you're going to spend a minute or more of each Lambda run just reading from S3. It would be much better if you could store the file in EFS and read it from there in the Lambda, or use another solution like ECS to avoid reading from a remote data source.</p>
|
python|amazon-s3|aws-lambda
| 4 |
1,903,327 | 70,954,812 |
How To Pick A Text From A List, Perform Certain Task With the Text Picked, Then Pick The Next Line Out Text In Selenium Python
|
<p>I have a txt file and I want selenium to iterate through the txt file. It should Pick the First Line, perform certain action, then picks the second line, perform certain actions as well. It should keep doing that until it gets to the 10th line, then rest for 5 minutes. Pick the next 10, rest for 5 minutes, until all the lines are worked on.</p>
<p>But I am stuck on the first line, its picking the last line of the txt file only. Here is my code;</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code># Picks the first Keyword
file = open ('Keywords.txt', "r")
lines = file.readlines()
for line in lines:
Keywordspace = driver.find_element_by_id('keyword')
Keywordspace.send_keys(line.strip())
# Togls on Title ( action to be performed)
checkBoxtitle = driver.find_element_by_xpath("//*[@id='create_article_form']/div[1]/div/div[4]/div[2]/div[2]/div/div/label")
# Scroll to checkbox if its not in screen
driver.execute_script("arguments[0].scrollIntoView();", checkBoxtitle)
driver.execute_script("arguments[0].click();", checkBoxtitle)
#Create With The First Line ( second action to be performed)
create=driver.find_element_by_id('create_button')
create.click()
# Clear First Line
driver.find_element_by_id('keyword').clear()
#Adds Second Keyword
for line in lines:
Keywordspace = driver.find_element_by_id('keyword')
Keywordspace.send_keys(line.strip())</code></pre>
</div>
</div>
</p>
|
<p>This is what I was referring to.
In this way, the all the code under the <code>for</code> loop would be executed for each iteration. Isn't it what you were looking for...</p>
<pre><code>file = open ('Keywords.txt', "r")
lines = file.readlines()
for line in lines:
Keywordspace = driver.find_element_by_id('keyword')
Keywordspace.send_keys(line.strip())
# Togls on Title ( action to be performed)
checkBoxtitle = driver.find_element_by_xpath(
"//*[@id='create_article_form']/div[1]/div/div[4]/div[2]/div[2]/div/div/label")
# Scroll to checkbox if its not in screen
driver.execute_script("arguments[0].scrollIntoView();", checkBoxtitle)
driver.execute_script("arguments[0].click();", checkBoxtitle)
# Create With The First Line ( second action to be performed)
create = driver.find_element_by_id('create_button')
create.click()
# Clear First Line
driver.find_element_by_id('keyword').clear()
</code></pre>
<p>A small test code to check the iterations:</p>
<pre><code>file = open('keywords.txt', 'r')
lines = file.readlines()
for line in lines:
print(line)
print(f'action_1: {line}')
print(f'action_2: {line}')
print(f'action_3: {line}')
file.close()
</code></pre>
<p>Output:</p>
<pre><code>keyword_1
action_1: keyword_1
action_2: keyword_1
action_3: keyword_1
keyword_2
action_1: keyword_2
action_2: keyword_2
action_3: keyword_2
keyword_3
action_1: keyword_3
action_2: keyword_3
action_3: keyword_3
</code></pre>
|
python|selenium
| 0 |
1,903,328 | 33,737,333 |
iterating over class object's attribute list throws python str error
|
<p>What I'm trying to do is serialize some class objects using python. However when I attempt to iterate over a list attribute of a class object i get a str error. I'm not clear on how to fix this. I'm rather new to python.</p>
<blockquote>
<p>AttributeError: 'str' object has no attribute 'serialize'</p>
</blockquote>
<p>The error occurs inside the Family class object inside this function...</p>
<pre><code>for member in self.members:
print member
data["members"].append( member.serialize() ) # ERROR
</code></pre>
<p><strong>The code</strong></p>
<pre><code>import json
# Functions
# ------------------------------------------------------------------------------
def GetProperties(properties):
if properties == "Basic Properties":
return {
"Basic Properties" : [
Property("isMale", False),
Property("isRelated", True),
]
}
elif properties == "Extra Properties":
return {
"Extra Properties" : [
Property("isTall", False),
Property("isAthletic", True),
]
}
# Classes
# ------------------------------------------------------------------------------
class Property:
def __init__(self, key, value):
self.key = key
self.value = value
class Person:
def __init__(self, name, attributes={}):
self.name = name
self.attributes = {}
def serialize(self):
data = {
"classname" : self.__class__.__name__,
"name" : self.name,
"attributes" : {},
}
return data
class Family:
def __init__(self, name, members=[], attributes={}):
self.name = name
self.members = members[:]
self.attributes = {}
def serialize(self):
data = {
"classname" : self.__class__.__name__,
"name" : self.name,
"attributes" : {},
"members" : [],
}
for member in self.members:
print member
data["members"].append( member.serialize() )
return data
# testing Serialization
newPerson = Person( "Joey" )
newPerson.attributes.update( GetProperties( "Basic Properties" ) )
newFamily = Family( "Johnson's" )
newFamily.attributes.update( GetProperties( "Basic Properties" ) )
newFamily.members.append( "newPerson" )
data = newFamily.serialize()
json.dump(data, open("test.json",'w'), indent=4)
</code></pre>
|
<p>Try:</p>
<pre><code>newFamily.members.append( newPerson) # newPerson as the object instantiated in preceding lines
</code></pre>
<p>In your original code, you had:</p>
<pre><code>newFamily.members.append("newPerson") # newPerson as a string literal
</code></pre>
<p>So, passing the string, you are attempting to serialize the string, not the <code>Person</code> object.</p>
|
python|json|serialization
| 1 |
1,903,329 | 33,845,244 |
Python 3.5 - How can I make this code more efficient/shorter?
|
<p>I have a</p>
<pre><code>list = [value, value, value, value, value, value, value, value, value]
</code></pre>
<p>where value takes on values: -1, 0 or 1.</p>
<pre><code>if list[0] + list[1] + list[2] == 3:
alternative1 = True
elif list[0] + list[1] + list[2] == -3:
alternative2 = True
elif list[3] + list[4] + list[5] == 3:
alternative1 = True
elif list[3] + list[4] + list[5] == -3:
alternative2 = True
elif list[6] + list[7] + list[8] == 3:
alternative1 = True
elif list[6] + list[7] + list[8] == -3:
alternative2 = True
elif list[0] + list[3] + list[6] == 3:
alternative1 = True
elif list[0] + list[3] + list[6] == -3:
alternative2 = True
elif list[1] + list[4] + list[7] == 3:
alternative1 = True
elif list[1] + list[4] + list[7] == -3:
alternative2 = True
elif list[2] + list[5] + list[8] == 3:
alternative1 = True
elif list[2] + list[5] + list[8] == -3:
alternative2 = True
elif list[0] + list[4] + list[8] == 3:
alternative1 = True
elif list[0] + list[4] + list[8] == -3:
alternative2 = True
elif list[2] + list[4] + list[6] == 3:
alternative1 = True
elif list[2] + list[4] + list[6] == -3:
alternative2 = True
</code></pre>
<p>So how can I make this code more efficient/shorter? I suppose I could accomplish this with some kind of while-loop or something similar, but I can't get the list-placeholders to match.</p>
|
<p>Some general advice:</p>
<ul>
<li>Code is often <strong>much</strong> more clear and easier to modify when your logic is in data instead of code. Build a data structure that maps situations to actions. Jon Bentley's <em>Programming Pearls</em> covers this in detail.</li>
<li>You can use a dict as a 2-D array: <code>board={}</code> then <code>board[2,2]</code> where the keys are tuples.</li>
<li>Having done that, you can then normalize patterns to handle patterns that are reflections or rotations of each other in the same way. (Not shown below.)</li>
</ul>
<p>To make this more concrete, let us suppose this is standard tic-tac-toe and consider how to detect a win, which seems to be your goal for at least part of this code. We will use the 2-D array, with <code>1, 0, -1</code> meaning <code>X, empty, O</code> as you seem to be doing (though your particular coding might differ).</p>
<pre><code># List of winning combos.
win_runs = [
((0,0), (0,1), (0,2)), # ... rows
((0,0), (1,0), (2,0)), # ... columns
((2,0), (1,1), (0,2)), # ... diagonals
]
# Initialize empty board.
board = {(i,j): 0 for i in range(3) for j in range(3)}
# Set up a win in leftmost column.
board[0,0] = board[1,0] = board[2,0] = -1
# Check if anyone has a win.
for run in win_runs:
values = {board[tup] for tup in run} # values is a set
if len(values) == 1 and 0 not in values:
print('{} wins'.format(values.pop()))
break
else: # executed only if for loop is exhausted
print('no one wins yet')
</code></pre>
|
python|python-3.x|optimization
| 3 |
1,903,330 | 47,082,765 |
how to handle select boxes in django admin with large amount of records
|
<p>my app has grown so that that drop downs in the django admin have 100,000s of options. I can't even open my admin anymore because of its load on the database, not too mention I wouldn't be able to find an option in the select box.</p>
<p>Does django have an autocomplete option?</p>
<p>What is the best option for handling big data in django admin?</p>
|
<p>Django 2.0 has introduced a new feature on the admin site, called <a href="https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields" rel="noreferrer"><code>autocomplete_fields</code></a>, which is helpful for models with foreign keys. It replaces the normal <code><select></code> element with an autocomplete element:</p>
<pre><code> class QuestionAdmin(admin.ModelAdmin):
ordering = ['date_created']
search_fields = ['question_text']
class ChoiceAdmin(admin.ModelAdmin):
autocomplete_fields = ['question']
</code></pre>
<p>Here's a screenshot of the element:</p>
<p><a href="https://i.stack.imgur.com/bKz8J.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bKz8J.png" alt="Screenshot"></a></p>
|
python|django|django-admin|bigdata
| 11 |
1,903,331 | 46,844,177 |
How to build a 2-level dictionary?
|
<p>I'm slowly getting my feet wet in Python but still seem to miss some fundamentals. Especially with lists and dictionaries.</p>
<p>I'm building an importer and there want to check a directory of files for the ones importable for me. Here's a function I'm trying to build for this:</p>
<pre><code>def check_files(directory=os.path.dirname(os.path.realpath(__file__))):
file_number = 0
files = {}
for file in os.listdir(directory):
if os.path.isfile(file):
file_name = os.fsdecode(file)
--> files = {file_number: {'file_name': file_name}}
with open(file_name,'r', encoding='utf-8', errors='ignore') as f:
line = f.readline()
if line == firstline['one']:
--> files = {file_number: {'file_type': 'one'}}
elif line == firstline['two']:
--> files = {file_number: {'file_type': 'two'}}
else:
--> files = {file_number: {'file_type': 'unknown'}}
file_number += 1
return files
</code></pre>
<p>As you can see I'm failing to build the dictionary I was thinking of building to carry some file information and return it.</p>
<p>Regarding the dictionary structure I was thinking about something like this:</p>
<pre><code>files = {
0: {'file_name': 'test1.csv', 'file_type': 'one'},
1: {'file_name': 'test2.csv', 'file_type': 'two'}
}
</code></pre>
<p>My question is: how do I build the dictionary step by step as I get the values and add new dictionaries into it? I read through quite some dictionary explanations for beginners but they mostly don't handle this multi level case at least not building it step by step.</p>
|
<p>Instead of using the literal construc, you should use the assign operator:</p>
<pre><code>base_dict = {} # same that base_dict = dict()
for i in range(10):
base_dict[i] = {'file_name': 'test' + str(i+1) + '.csv', 'file_type': i+1}
</code></pre>
<p>The first line is creating an empty <code>dict</code>.</p>
<p>The loop iterates i=0..9.
Then we assign a new <code>dict</code> to element <code>i</code> of <code>base_dict</code> with <code>base_dict[i] = ...</code>. You use square brackets to both access and modify (including creation) of key-value paris inside a <code>dict</code>.</p>
<p>Your code will be:</p>
<pre><code>def check_files(directory=os.path.dirname(os.path.realpath(__file__))):
files = {}
for file in os.listdir(directory):
if os.path.isfile(file):
i = len(files)
file_name = os.fsdecode(file)
files[i] = {'file_name': file_name}
with open(file_name,'r', encoding='utf-8', errors='ignore') as f:
line = f.readline()
if line == firstline['one']:
files[i]['file_type'] = 'one'
elif line == firstline['two']:
files[i]['file_type'] = 'one'
else:
files[i]['file_type'] = 'unknown'
return files
</code></pre>
<p>As you can see I deleted the manual count you were using and get the number of already existing elements with <code>i = len(files)</code>, then I use square brackets to enter all the info as needed.</p>
<h3>IMPORTANT NOTE</h3>
<p>Your case may be more complex than this, but having a dictionary whos keys are auto-incremented integers makes no sense, that is what <code>list</code>s are for. Your code with lists would look like this:</p>
<pre><code>def check_files(directory=os.path.dirname(os.path.realpath(__file__))):
files = []
for file in os.listdir(directory):
if os.path.isfile(file):
file_name = os.fsdecode(file)
files.append({'file_name': file_name})
with open(file_name,'r', encoding='utf-8', errors='ignore') as f:
line = f.readline()
if line == firstline['one']:
files[-1]['file_type'] = 'one'
elif line == firstline['two']:
files[-1]['file_type'] = 'one'
else:
files[-1]['file_type'] = 'unknown'
return files
</code></pre>
<p>As you can see it is very similar to the code above but it doesn't need to calculate the length every iteration as the builtin method <code>list.append()</code> already inserts the new data in the next position. <code>list</code>s offer you some advantages over <code>dict</code>s in the case of auto-incremented integers as keys.</p>
<p>The output would be:</p>
<p>files = [
{'file_name': 'test1.csv', 'file_type': 'one'},
{'file_name': 'test2.csv', 'file_type': 'two'}
]</p>
<p>Remember that even the output doesn't explicitly writes the numbers, <code>list</code>s allow you to access the data the same way. Additionally, negative integers can be used to access data from the bottom, so when I'm using <code>files[-1]</code>, that means the last element we inserted. That's the reason why I do not need to know which element we are introducing in this example, we just append it at the end and access the last value appended.</p>
|
python|dictionary
| 1 |
1,903,332 | 37,959,641 |
Query MongoDB from Python u' get added while retriving data
|
<p>I am trying to retrieve my data from <code>MongoDB</code> using <code>Python</code> but <code>u</code> get added to its key value.</p>
<p>Here is my program:</p>
<pre><code>from pymongo import MongoClient
import json
import array
Data = MongoClient()
Variable = Data.Abhi
Dataset = []
i = 0
Outcome = Variable.Temp.find()
for Result in Outcome:
Dataset.append(Result)
print Dataset
</code></pre>
<p>Output :</p>
<pre><code>[{u'cuisine': u'Italian', u'borough': u'Manhattan', u'name': u'Vella', u'restaurant_id': u'41704620', u'grades': [{u'grade': u'A', u'score': 11}, {u'grade': u'B', u'score': 17}], u'address': {u'building': u'1480', u'street': u'2 Avenue', u'zipcode': u'10075', u'coord': [-73.9557413, 40.7720266]}, u'_id': ObjectId('576948b163a37b378dc21565')}]
</code></pre>
<p>I have checked using terminal with find() in my database it is showing</p>
<pre><code>{ "_id" : ObjectId("576948b163a37b378dc21565"), "cuisine" : "Italian", "name" : "Vella", "restaurant_id" : "41704620", "grades" : [ { "grade" : "A", "score" : 11 }, { "grade" : "B", "score" : 17 } ], "address" : { "building" : "1480", "street" : "2 Avenue", "zipcode" : "10075", "coord" : [ -73.9557413, 40.7720266 ] }, "borough" : "Manhattan" }
</code></pre>
<p>Please help me where am I making mistake.</p>
<p>Thanks in advance.</p>
|
<p>you can directly access this by using:</p>
<blockquote>
<p>for Result in Outcome:</p>
<p>Result['your key']</p>
</blockquote>
|
python|arrays|json|python-2.7|pymongo
| 0 |
1,903,333 | 61,431,605 |
Merge overlapping sessions, how do I find the end value of the session? [Leetcode Similar to Car Pooling]
|
<p>I have the following code block which figures out the number of overlapping sessions. Given different intervals, the task is to print the maximum number of overlap among these intervals at any time and also to find the overlapped interval. </p>
<pre><code>def overlap(v):
# variable to store the maximum
# count
ans = 0
count = 0
data = []
# storing the x and y
# coordinates in data vector
for i in range(len(v)):
# pushing the x coordinate
data.append([v[i][0], 'x'])
# pushing the y coordinate
data.append([v[i][1], 'y'])
# sorting of ranges
data = sorted(data)
# Traverse the data vector to
# count number of overlaps
for i in range(len(data)):
# if x occur it means a new range
# is added so we increase count
if (data[i][1] == 'x'):
count += 1
# if y occur it means a range
# is ended so we decrease count
if (data[i][1] == 'y'):
count -= 1
# updating the value of ans
# after every traversal
ans = max(ans, count)
# printing the maximum value
print(ans)
# Driver code
v = [[ 1, 2 ], [ 2, 4 ], [ 3, 6 ],[3,8]]
overlap(v)
</code></pre>
<p>This returns <code>3</code>.
But what would be the best way to also return the maximum overlapping interval by modifying my existing approach? In this case which should be <code>[3,4]</code>.</p>
|
<p>You could use the counter object (from collections) to create a list of intersecting sub intervals and count the number of original intervals that intersect with them. Each interval in your list would be intersected with all the sub-intervals found so far in order to accumulate the counts:</p>
<pre><code>v = [[ 1, 2 ], [ 2, 4 ], [ 3, 6 ],[3,8]]
from collections import Counter
overCounts = Counter()
for vStart,vEnd in v:
overlaps = [(max(s,vStart),min(e,vEnd)) for s,e in overCounts
if s<=vEnd and e>=vStart]
overCounts += Counter(overlaps + [(vStart,vEnd)])
interval,count = overCounts.most_common(1)[0]
print(interval,count) # (3,4) 3
</code></pre>
<p>The overlaps list detects intersections with the sub-intervals found so far. <code>s<=vEnd and e>=vStart</code> will return True when interval (s,e) intersects with interval (vStart,vEnd). For those intervals that do intersect we want the start and end of the intersection (sub-interval). The intersection will start at the largest beginning and end at the smallest end. So we take the max() of the start positions with the min() of the end positions to form the sub-interval: <code>(max(s,vStart),min(e,vEnd))</code></p>
<pre><code>vStart vEnd
[--------------------]
[--------------------------]
s e
[-------------]
--max-> <----min-----
</code></pre>
<p><strong>[EDIT]</strong>
To be honest, I like your original approach better than mine. It will respond in O(NLogN) time whereas mine could go up to O(N^2) depending on the data.</p>
<p>In order to capture the sub-interval corresponding to the result in your original approach, you would need to add a variable to keep track of the last starting position encountered and move detection of a higher count inside the 'y' condition. </p>
<p>For example:</p>
<pre><code> lastStart = maxStart = maxEnd = None
# ...
if (data[i][1] == 'x'):
lastStart = data[i][0] # last start of sub-interval
count += 1
if (data[i][1] == 'y'):
if count > ans: # detect a greater overlap
maxStart = lastStart # start of corresponding sub-interval
maxEnd = data[i][0]
ans = count
count -= 1
# ans = max(ans, count) <-- removed
# ...
</code></pre>
<p>You could also implement it using accumulate:</p>
<pre><code>v = [[ 1, 2 ], [ 2, 4 ], [ 3, 6 ],[3,8]]
from itertools import accumulate
edges = sorted((p,e) for i in v for p,e in zip(i,(-1,1)))
counts = accumulate(-e for _,e in edges)
starts = accumulate((p*(e<0) for p,e in edges),max)
count,start,end = max((c+1,s,p) for c,s,(p,e) in zip(counts,starts,edges) if e>0)
print(count,[start,end]) # 3 [3, 4]
</code></pre>
|
python|python-3.x|list
| 2 |
1,903,334 | 27,530,120 |
Express a given sinus as a set of base vectors and vice-versa
|
<p>Say, I have a given sinus:</p>
<pre><code>import numpy as np
import pylab as py
x = np.arange(0, 1000, 1)
y = np.sin(x/40)
py.plot(x, y, color='red')
</code></pre>
<p><img src="https://i.stack.imgur.com/LiYux.png" alt="enter image description here"></p>
<p>...now I want to adjust to it a proper set of vectors, so I would get something like this:</p>
<p><img src="https://i.stack.imgur.com/tgwIM.gif" alt="enter image description here"></p>
<p>How can I achieve something similar to this? Thank you in advance.</p>
|
<p>You have to first sample your signal :
Y(k) = y(k*T) where 1/T is your sample rate frequency.</p>
<p>Then just plot line between each Y(k) and Y(k+1).</p>
<p>Be careful when choosing your frequency (see more Nyquist theorem).</p>
|
python|fft|trigonometry
| -2 |
1,903,335 | 72,382,591 |
cant change elements value in cubic matrix
|
<p>i have a matrix</p>
<pre><code>Matrix = [[[]] * 5 for i in range(5)]
</code></pre>
<p>i'm trying to change the inner element with the following code, but somewhy it changes the whole row instead:</p>
<pre><code>Matrix[0][1].append(1)
</code></pre>
<p>output:</p>
<pre><code>[[[1], [1], [1], [1], [1]], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]
</code></pre>
<p>but i wanted it to work like this:</p>
<pre><code>[[[], [1], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]
</code></pre>
|
<p>You want to use loops inside and outside the list of lists to avoid creating copies.</p>
<pre><code>Matrix = [[[] for _ in range(5)] for i in range(5)]
print(Matrix)
[[[], [1], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []], [[], [], [], [], []]]
</code></pre>
|
python|arrays
| 1 |
1,903,336 | 36,735,863 |
How to verify in selenium if the image is shown on the page?
|
<p>I need to verify if a particular image is shown on page with selenium in python. HTML code looks like this when the image is displayed in a table cell:</p>
<pre><code><td role="gridcell">
<div style="text-align: center">
<img class="grid-center-image" border="0" ng-show="dataItem.device_protected" src="resources/images/icon_supported.png"/>
</div>
</td>
</code></pre>
<p>When the image is not displayed it looks like:</p>
<pre><code><td role="gridcell">
<div style="text-align: center">
<img class="grid-center-image ng-hide" border="0" ng-show="dataItem.device_protected" src="resources/images/icon_supported.png"/>
</div>
</td>
</code></pre>
<p>I do not understand how to approach this? How do I verify if the image is present on the screen?</p>
|
<p>You have to get class attribute of your img tag and then have to check that whether 'ng-hide' is present in it or not. That'll decide the presence of image on screen.</p>
<p>Below is the sample code in python to check visibility of image on screen.</p>
<pre><code>elem = driver.find_element_by_xpath('//your/xpath/to/img/tag')
if 'ng-hide' in elem.get_attribute('class'):
print 'Image is not visible on screen'
else:
print 'Image is visible on screen'
</code></pre>
|
python|selenium-webdriver
| 1 |
1,903,337 | 48,693,804 |
How to match everything within a word
|
<p>Sorry if the title is not clear.</p>
<p>More specifically, using python, I want to match <code>I am (INSERT ANYTHING)ing</code> like <code>I am dancing</code> and <code>I am walking</code> but not <code>I am a student and I like dancing</code> </p>
<p>If I use <code>(?<=I am)(.*)(?=ing)</code> this would match <code>I am a student and I like dancing</code></p>
<p>So namely <code>(INSERT ANYTHING)ing</code> should be one word. Is there anyway to do this?</p>
|
<p>For what you're describing you don't need the lookbehind, just a pattern before "ing" that doesn't have any spaces:</p>
<pre><code>r"I am ([a-zA-Z]+)ing"
</code></pre>
|
python|regex|nlp
| 3 |
1,903,338 | 48,800,899 |
error on preprocessing machine learning
|
<p>I am trying to apply preprocessing on the training data and I also tried rehsape function but that didn't work,I am getting the following errror:</p>
<pre><code>ValueError: Found input variables with inconsistent numbers of samples: [34, 12700]
</code></pre>
<p>Here is my code:</p>
<pre><code>import pandas as pd
import numpy as np
from sklearn import preprocessing,neighbors
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
df=pd.read_csv('train.csv')
df.drop(['ID'],1,inplace=True)
X=np.array(df.drop(['label'],1))
y=np.array(df['label'])
print(X.shape)
X = preprocessing.StandardScaler().fit(X)
X=X.mean_
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
clf = RandomForestRegressor(n_estimators=1900,max_features='log2',max_depth=25)
clf.fit(X_train,y_train)
accuracy=clf.score(X_test,y_test)
print(accuracy)
</code></pre>
|
<p>The issue is with <code>X = preprocessing.StandardScaler().fit(X)</code>
<code>X=X.mean_</code></p>
<p>After this your X will only contain mean of each columns.</p>
<p>To transform the data use following code:</p>
<pre><code>from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)
</code></pre>
<p>For more details refer <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" rel="nofollow noreferrer">scikit-doc</a></p>
|
python-3.x|numpy|machine-learning|scikit-learn
| 1 |
1,903,339 | 4,571,441 |
Recursive expressions with pyparsing
|
<p>I'm trying to figure out how to do a left-associative expression where recursive (not-enclosed in anything) expressions are possible. For example, I'd like to do:</p>
<pre><code>expr + OP + expr
</code></pre>
<p>that parses 2 operations like <code>1 x 2 x 3</code> into <code>(expr OP expr) OP expr</code> result.</p>
<p>If I try to prevent <code>expr</code> parsing from infinite recursion, i can do something like:</p>
<pre><code>expr -> Group(simple_expr + OP + expr)
| simple_expr
</code></pre>
<p>but then I'd get the <code>expr OP (expr OR expr)</code> result.</p>
<p>How do I force left-side binding?</p>
<p>Edit: I know about the <code>operatorPrecedence</code> but when the operator is <code>"IS" + Optional("NOT")</code> or similar, it doesn't seem to match properly.</p>
|
<p>Here is an example parse action that will take the flat lists of tokens and nest them as if parsed left-recursively:</p>
<pre><code>from pyparsing import *
# parse action -maker
def makeLRlike(numterms):
if numterms is None:
# None operator can only by binary op
initlen = 2
incr = 1
else:
initlen = {0:1,1:2,2:3,3:5}[numterms]
incr = {0:1,1:1,2:2,3:4}[numterms]
# define parse action for this number of terms,
# to convert flat list of tokens into nested list
def pa(s,l,t):
t = t[0]
if len(t) > initlen:
ret = ParseResults(t[:initlen])
i = initlen
while i < len(t):
ret = ParseResults([ret] + t[i:i+incr])
i += incr
return ParseResults([ret])
return pa
# setup a simple grammar for 4-function arithmetic
varname = oneOf(list(alphas))
integer = Word(nums)
operand = integer | varname
# ordinary opPrec definition
arith1 = operatorPrecedence(operand,
[
(None, 2, opAssoc.LEFT),
(oneOf("* /"), 2, opAssoc.LEFT),
(oneOf("+ -"), 2, opAssoc.LEFT),
])
# opPrec definition with parseAction makeLRlike
arith2 = operatorPrecedence(operand,
[
(None, 2, opAssoc.LEFT, makeLRlike(None)),
(oneOf("* /"), 2, opAssoc.LEFT, makeLRlike(2)),
(oneOf("+ -"), 2, opAssoc.LEFT, makeLRlike(2)),
])
# parse a few test strings, using both parsers
for arith in (arith1, arith2):
print arith.parseString("A+B+C+D+E")[0]
print arith.parseString("A+B+C*D+E")[0]
print arith.parseString("12AX+34BY+C*5DZ+E")[0]
</code></pre>
<p>Prints:</p>
<p>(normal)</p>
<pre><code>['A', '+', 'B', '+', 'C', '+', 'D', '+', 'E']
['A', '+', 'B', '+', ['C', '*', 'D'], '+', 'E']
[['12', 'A', 'X'], '+', ['34', 'B', 'Y'], '+', ['C', '*', ['5', 'D', 'Z']], '+', 'E']
</code></pre>
<p>(LR-like)</p>
<pre><code>[[[['A', '+', 'B'], '+', 'C'], '+', 'D'], '+', 'E']
[[['A', '+', 'B'], '+', ['C', '*', 'D']], '+', 'E']
[[[[['12', 'A'], 'X'], '+', [['34', 'B'], 'Y']], '+', ['C', '*', [['5', 'D'], 'Z']]], '+', 'E']
</code></pre>
|
python|parsing|pyparsing|associativity
| 8 |
1,903,340 | 51,460,895 |
python: using list slice as target of a for loop
|
<p>I found this code snippet to be very interesting.</p>
<pre><code>a = [0, 1, 2, 3]
for a[-1] in a:
print(a)
</code></pre>
<p>Output is as follows:</p>
<pre><code>[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]
</code></pre>
<p>I am trying to understand why python does that. Is it because python is trying to re-use the index? For loop somehow slices the list?</p>
<p>We can add or delete an element while iterating the list, but when we are trying to access the variable using index, it gives bizarre output.</p>
<p>Can someone help me understand the interaction between for loop and index in the list? Or simply explain this output?</p>
|
<p>It works as expected. (For some interpretation of "expected", at least.)</p>
<p>Re-writing your code to this, to prevent any misinterpretation of what <code>a[-1]</code> is at any point:</p>
<pre><code>a = [a for a in range(0,4)]
for b in a:
print (b)
a[-1] = b
print (a)
</code></pre>
<p>shows us</p>
<pre><code>0
[0, 1, 2, 0]
1
[0, 1, 2, 1]
2
[0, 1, 2, 2]
2
[0, 1, 2, 2]
</code></pre>
<p>which makes it clear that the <code>b</code> <em>assignment</em> to <code>a[-1]</code> is done immediately, changing the list while iterating.</p>
<p>The four loops do the following:</p>
<ol>
<li><code>a[-1]</code> gets set to the first value of the list, <code>0</code>. The result is now <code>[0,1,2,0]</code>.</li>
<li><code>a[-1]</code> gets set to the second value, <code>1</code>. The result is (quite obviously) <code>[0,1,2,1]</code>.</li>
<li><code>a[-1]</code> gets set to <code>2</code> and so the result is <code>[0,1,2,2]</code> – again, only <code>a[-1]</code> gets changed.</li>
<li>Finally, <code>a[-1]</code> gets set to the last value in <code>a</code>, so effectively it does not change and the final result is <code>[0,1,2,2]</code>.</li>
</ol>
|
python|python-3.x|list|for-loop|indexing
| 8 |
1,903,341 | 51,429,286 |
Generating new column of data by aggregating specific columns of dataset
|
<p>My dataset has a few interesting columns that I want to aggregate, and hence create a metric that I can use to do some more analysis. </p>
<p>The algorithm I wrote takes around ~3 seconds to finish, so I was wondering if there is a more efficient way to do this.</p>
<pre><code>def financial_score_calculation(df, dictionary_of_parameters):
for parameter in dictionary_of_parameters:
for i in dictionary_of_parameters[parameter]['target']:
index = df.loc[df[parameter] == i].index
for i in index:
old_score = df.at[i, 'financialliteracyscore']
new_score = old_score + dictionary_of_parameters[parameter]['score']
df.at[i, 'financialliteracyscore'] = new_score
for i in df.index:
old_score = df.at[i, 'financialliteracyscore']
new_score = (old_score/27.0)*100 #converting score to percent value
df.at[i, 'financialliteracyscore'] = new_score
return df
</code></pre>
<p>Here is a truncated version of the dictionary_of_parameters:</p>
<pre><code>dictionary_of_parameters = {
# money management parameters
"SatisfactionLevelCurrentFinances": {'target': [8, 9, 10], 'score': 1},
"WillingnessFinancialRisk": {'target': [8, 9, 10], 'score': 1},
"ConfidenceLevelToEarn2000WithinMonth": {'target': [1], 'score': 1},
"DegreeOfWorryAboutRetirement": {'target': [1], 'score': 1},
"GoodWithYourMoney?": {'target': [7], 'score': 1}
}
</code></pre>
<p>EDIT: generating toy data for df</p>
<pre><code>df = pd.DataFrame(columns = dictionary_of_parameters.keys())
df['financialliteracyscore'] = 0
for i in range(10):
df.loc[i] = dict(zip(df.columns,2*i*np.ones(6)))
</code></pre>
|
<p>Note that in Pandas you can index in ways other than elementwisely with <code>at</code>. In the four-liner below, <code>index</code> is a list which can then be used for indexing with <code>loc</code>.</p>
<pre><code>for parameter in dictionary_of_parameters:
index = df[df[parameter].isin(dictionary_of_parameters[parameter]['target'])].index
df.loc[index,'financialliteracyscore'] += dictionary_of_parameters[parameter]['score']
df['financialliteracyscore'] = df['financialliteracyscore'] /27.0*100
</code></pre>
<p>Here's a reference although I personally never found it useful in my earlier days of programming... <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow noreferrer">https://pandas.pydata.org/pandas-docs/stable/indexing.html</a></p>
|
python|pandas|dataframe
| 0 |
1,903,342 | 64,225,673 |
How to deselect an entire QTableWidget row
|
<p>Given the row index, how can I deselect a single row in a QTableWidget? I don't want to deselect everything using clearSelection()</p>
|
<p>You can use the table <a href="https://doc.qt.io/qt-5/qitemselectionmodel.html" rel="nofollow noreferrer"><code>selectionModel()</code></a> and its <a href="https://doc.qt.io/qt-5/qitemselectionmodel.html#select" rel="nofollow noreferrer"><code>select()</code></a> function, using the <code>Deselect</code> and <code>Rows</code> flags:</p>
<pre><code> def deselectRow(self, row):
if row > self.table.rowCount() - 1:
return
selectionModel = self.table.selectionModel()
selectionModel.select(self.table.model().index(row, 0),
selectionModel.Deselect|selectionModel.Rows)
</code></pre>
|
python|pyqt5|pyside2
| 0 |
1,903,343 | 64,284,097 |
Pandas OLS Random Effects model - weird prediction values
|
<p>I am trying to create a RE-model using Pandas. I only have previous experience in Stata.</p>
<p>My aim is to generate predicted temperatures by regressing the temperature data on a set of dummies. The first set of dummies represents the month of the year while the second dummy represents the station.</p>
<p>I suspect I am doing something wrong the predicted values for id = 1 and month = 1 is zero. When performing the same RE-model in Stata I receive a predicted value of -23.02825. Now, there could of course be some difference in the RE-model between Pandas and Stata that I am unaware of but I suspect that I have somewhat specified the code wrong. Does someone have insights about this?</p>
<p>I am not a experienced poster here on StackOverflow, so if I need to add any additional information, just let me know!</p>
<pre><code>import pandas as pd
import statsmodels.api as sm
from patsy import dmatrices
from linearmodels.panel import RandomEffects
data = pd.read_stata("/Users/user/Desktop/dataset2.dta")
print(data.head())
id value dates month antal year iid
0 1 0 2000-01-01 1.0 62.0 2000-01-01 1
1 1 21 2000-01-02 1.0 62.0 2000-01-01 1
2 1 32 2000-01-03 1.0 62.0 2000-01-01 1
3 1 31 2000-01-04 1.0 62.0 2000-01-01 1
4 1 11 2000-01-05 1.0 62.0 2000-01-01 1
... .. ... ... ... ... ... ...
174903 55 -56 2010-12-27 12.0 31.0 2010-01-01 49
174904 55 -76 2010-12-28 12.0 31.0 2010-01-01 49
174905 55 -93 2010-12-29 12.0 31.0 2010-01-01 49
174906 55 -90 2010-12-30 12.0 31.0 2010-01-01 49
174907 55 10 2010-12-31 12.0 31.0 2010-01-01 49
[174908 rows x 7 columns]
data = data.astype({'iid': 'int16'})
print(data)
data = data.astype({'id': 'int16'})
data = data.astype({'antal': 'int8'})
data = data.astype({'month': 'int8'})
data.dtypes
id int16
value int32
dates datetime64[ns]
month int8
antal int8
year datetime64[ns]
iid int16
dtype: object
d_iid = pd.get_dummies(data.iid, prefix='id', dtype='int8').iloc[:,1:]
data = pd.concat([data, d_iid], axis=1)
d_m = pd.get_dummies(data.month, prefix='m').iloc[:,1:]
data = pd.concat([data, d_m], axis=1)
data = data.set_index(["iid", "dates"])
print(data)
id value month antal year id_2 id_3 id_4 id_5 \
iid dates
1 2000-01-01 1 0 1 62 2000-01-01 0 0 0 0
2000-01-02 1 21 1 62 2000-01-01 0 0 0 0
2000-01-03 1 32 1 62 2000-01-01 0 0 0 0
2000-01-04 1 31 1 62 2000-01-01 0 0 0 0
2000-01-05 1 11 1 62 2000-01-01 0 0 0 0
... .. ... ... ... ... ... ... ... ...
49 2010-12-27 55 -56 12 31 2010-01-01 0 0 0 0
2010-12-28 55 -76 12 31 2010-01-01 0 0 0 0
2010-12-29 55 -93 12 31 2010-01-01 0 0 0 0
2010-12-30 55 -90 12 31 2010-01-01 0 0 0 0
2010-12-31 55 10 12 31 2010-01-01 0 0 0 0
id_6 ... m_3 m_4 m_5 m_6 m_7 m_8 m_9 m_10 m_11 m_12
iid dates ...
1 2000-01-01 0 ... 0 0 0 0 0 0 0 0 0 0
2000-01-02 0 ... 0 0 0 0 0 0 0 0 0 0
2000-01-03 0 ... 0 0 0 0 0 0 0 0 0 0
2000-01-04 0 ... 0 0 0 0 0 0 0 0 0 0
2000-01-05 0 ... 0 0 0 0 0 0 0 0 0 0
... ... ... ... ... ... ... ... ... ... ... ... ...
49 2010-12-27 0 ... 0 0 0 0 0 0 0 0 0 1
2010-12-28 0 ... 0 0 0 0 0 0 0 0 0 1
2010-12-29 0 ... 0 0 0 0 0 0 0 0 0 1
2010-12-30 0 ... 0 0 0 0 0 0 0 0 0 1
2010-12-31 0 ... 0 0 0 0 0 0 0 0 0 1
[174908 rows x 62 columns]
var=data.loc[:, 'id_2':'m_12']
mod = RandomEffects(data.value, var)
re_res = mod.fit()
print(re_res)
RandomEffects Estimation Summary
================================================================================
Dep. Variable: value R-squared: 0.9129
Estimator: RandomEffects R-squared (Between): 0.9993
No. Observations: 174908 R-squared (Within): 0.7416
Date: Fri, Oct 09 2020 R-squared (Overall): 0.9129
Time: 18:15:09 Log-likelihood -8.937e+05
Cov. Estimator: Unadjusted
F-statistic: 3.216e+04
Entities: 47 P-value 0.0000
Avg Obs: 3721.4 Distribution: F(57,174851)
Min Obs: 1096.0
Max Obs: 4018.0 F-statistic (robust): 3.216e+04
P-value 0.0000
Time periods: 4018 Distribution: F(57,174851)
Avg Obs: 43.531
Min Obs: 41.000
Max Obs: 46.000
Parameter Estimates
==============================================================================
Parameter Std. Err. T-stat P-value Lower CI Upper CI
------------------------------------------------------------------------------
id_2 -32.954 0.7098 -46.425 0.0000 -34.345 -31.563
id_3 -71.447 0.9984 -71.562 0.0000 -73.404 -69.491
id_4 -20.982 0.6981 -30.056 0.0000 -22.350 -19.614
id_5 -20.982 0.6981 -30.056 0.0000 -22.350 -19.614
id_6 -17.287 0.7680 -22.511 0.0000 -18.792 -15.782
id_7 -26.455 0.6981 -37.897 0.0000 -27.824 -25.087
id_8 -51.832 0.6981 -74.248 0.0000 -53.200 -50.464
id_9 -51.832 0.6981 -74.248 0.0000 -53.200 -50.464
id_10 -11.651 0.6981 -16.690 0.0000 -13.019 -10.283
id_11 8.3476 0.7003 11.921 0.0000 6.9751 9.7201
id_12 20.876 0.6982 29.902 0.0000 19.508 22.245
id_13 12.719 0.6982 18.218 0.0000 11.351 14.088
id_14 10.063 0.6981 14.415 0.0000 8.6947 11.431
id_15 -137.28 0.6981 -196.66 0.0000 -138.65 -135.92
id_16 23.770 0.6981 34.050 0.0000 22.402 25.138
id_17 38.704 0.6981 55.443 0.0000 37.336 40.073
id_18 48.107 0.9304 51.706 0.0000 46.283 49.930
id_19 112.55 0.6991 161.00 0.0000 111.18 113.92
id_20 111.20 0.6981 159.30 0.0000 109.84 112.57
id_21 107.49 0.6981 153.98 0.0000 106.12 108.86
id_22 112.01 0.9761 114.75 0.0000 110.10 113.92
id_23 22.266 0.6981 31.895 0.0000 20.898 23.634
id_24 -26.090 0.6981 -37.373 0.0000 -27.458 -24.722
id_25 -52.292 0.6982 -74.900 0.0000 -53.660 -50.924
id_26 -86.101 0.6981 -123.34 0.0000 -87.469 -84.733
id_27 73.427 1.2464 58.911 0.0000 70.984 75.869
id_28 30.520 0.6981 43.719 0.0000 29.152 31.888
id_29 50.253 0.6981 71.986 0.0000 48.884 51.621
id_30 50.380 0.6981 72.167 0.0000 49.011 51.748
id_31 69.253 0.6981 99.204 0.0000 67.885 70.622
id_32 36.982 0.6981 52.976 0.0000 35.614 38.350
id_33 68.688 0.6981 98.394 0.0000 67.320 70.056
id_34 5.7040 0.6981 8.1709 0.0000 4.3358 7.0723
id_35 7.8369 0.6981 11.226 0.0000 6.4687 9.2052
id_36 7.8414 0.6981 11.233 0.0000 6.4732 9.2097
id_37 6.1834 0.6981 8.8576 0.0000 4.8151 7.5516
id_38 19.922 0.6981 28.538 0.0000 18.554 21.290
id_39 9.7777 0.6986 13.995 0.0000 8.4084 11.147
id_41 7.0468 0.6981 10.094 0.0000 5.6785 8.4150
id_42 -14.053 0.6981 -20.131 0.0000 -15.421 -12.685
id_43 11.974 0.6981 17.152 0.0000 10.605 13.342
id_44 10.657 0.9111 11.697 0.0000 8.8716 12.443
id_45 23.552 0.6981 33.737 0.0000 22.183 24.920
id_46 9.1107 0.6981 13.051 0.0000 7.7425 10.479
id_48 6.9631 0.6981 9.9745 0.0000 5.5949 8.3314
id_49 4.3713 0.6981 6.2618 0.0000 3.0030 5.7395
m_2 6.2046 0.4627 13.411 0.0000 5.2978 7.1115
m_3 36.329 0.4509 80.562 0.0000 35.445 37.212
m_4 84.415 0.4549 185.57 0.0000 83.524 85.307
m_5 129.82 0.4509 287.93 0.0000 128.94 130.71
m_6 166.63 0.4546 366.52 0.0000 165.74 167.52
m_7 188.15 0.4509 417.30 0.0000 187.26 189.03
m_8 181.04 0.4509 401.55 0.0000 180.16 181.93
m_9 138.76 0.4543 305.42 0.0000 137.87 139.65
m_10 94.589 0.4488 210.78 0.0000 93.709 95.468
m_11 47.314 0.4514 104.81 0.0000 46.429 48.199
m_12 5.9907 0.4483 13.363 0.0000 5.1121 6.8694
==============================================================================
re_res.predict()
fitted_values
iid dates
1 2000-01-01 0.000000
2000-01-02 0.000000
2000-01-03 0.000000
2000-01-04 0.000000
2000-01-05 0.000000
... ... ...
49 2010-12-27 10.362003
2010-12-28 10.362003
2010-12-29 10.362003
2010-12-30 10.362003
2010-12-31 10.362003
174908 rows × 1 columns
</code></pre>
|
<p>So, I found out that Python does not add an intercept (<a href="https://stackoverflow.com/questions/25514220/pandas-statsmodel-ols-predicting-future-values">Pandas/Statsmodel OLS predicting future values</a>).</p>
<p>Thus, the solution:</p>
<pre><code>data['intercept'] = 1
var=data.loc[:,'intercept':'m_12']
</code></pre>
|
python|pandas|statsmodels|linearmodels
| 0 |
1,903,344 | 73,131,997 |
Could anyone explain the print result in Python(sorry my English is poor,so please forgive me for unsuitable speaking)
|
<p>The code are as follows:</p>
<pre><code>str3 = "{{0}}"
print(str3.format("Don't print"))
</code></pre>
<p>And the result is:</p>
<pre><code>{0}
</code></pre>
<p>I don't know why the result is not :</p>
<pre><code>"Don't print"
</code></pre>
|
<p>Do you want <code>Don't print</code> or <code>"Don't print"</code> if it's the first then just with str3 = "{0}" will work</p>
<pre><code>str3 = "{0}"
print(str3.format("Don't print"))
</code></pre>
<p>if is the second way you could use</p>
<pre><code>print(str3.format("\"Don't print\""))
</code></pre>
|
python-3.x|string
| 1 |
1,903,345 | 55,729,515 |
Recursively querying a many-to-many relationship
|
<p>I'm trying to build a family tree in Django and I can't figure out how to reference an object's children, and the children's children of the object's children, and so on. .</p>
<p>This is my model with the function I'm using to try to get the family tree:</p>
<pre><code>class Member(models.Model):
referrals = models.ManyToManyField("self", symmetrical=False)
def tree(self):
refs = {}
for ref in self.referrals.all():
refs[ref] = ref.tree()
return refs
</code></pre>
<p>This seems to work, however, if the children also has children, then it says the following: </p>
<pre><code>maximum recursion depth exceeded while calling a Python object
</code></pre>
<p>Ideally, I want the tree function to return a string object that is a nested list, so I can just place the result in the template, as follows:</p>
<pre><code><ul>
<li>Member A</li>
<li>Member B
<ul>
<li>Member BA</li>
<li>Member BB</li>
</ul>
</li>
<li>Member C</li>
</ul>
</code></pre>
<p>Would appreciate any suggestions, thanks</p>
|
<p>If you build the tree having one of the children pointing to one of the parents, you will create a cycle in your graph, causing your <code>tree</code> function to run infinitely.</p>
<p>Then, you have to avoid to add a <code>referral</code> that has parental relation somehow to the Member you're adding in it.</p>
<p>Also, I would recommend to name the reverse relation for clarity in your code:</p>
<pre><code># Add related name in order to access parents from a member
# like this:
# member.parents instead of members.referrals_set
referrals = models.ManyToManyField("self", symmetrical=False, related_name='parents')
</code></pre>
|
django|python-3.x
| 0 |
1,903,346 | 49,992,587 |
Making an API call with discord.py
|
<p>So I'm trying to do a simple API call with a discord bot to get the prices of games on Steam. I have the API request working but when I try and trigger the bot to check the price for me nothing happens. I don't get an error in the console and the bot doesn't post anything to chat.</p>
<p>I know it's pretty ugly I'll go back and clean it up after I can get it to post.</p>
<pre><code>if message.content.startswith('!pricecheck'):
game = message.content[11:]
gres = requests.get('https://api.steampowered.com/ISteamApps/GetAppList/v2/')
gdata = gres.json()
for i in gdata["applist"]["apps"]:
if (i["name"] == game):
app = (i["appid"])
priceres = requests.get(f"https://store.steampowered.com/api/appdetails/?appids={app}")
priced = priceres.json()
price = (priced[f"{app}"]["data"]["price_overview"].get("final"))
msg = f"{game} is currently{price}".format(message)
await client.send_message(message.channel, msg)
</code></pre>
|
<p>Assuming that the command is called by <code>!pricecheck <game></code>, <code>game = message.content[11:]</code> is including the space. See test case below, where space is replaced with _ so it's easily readable.</p>
<pre><code>>>> test = '!pricecheck_gamename'
>>> print(test[11:])
_gamename
</code></pre>
<p>Because of this, <code>if (i["name"] == game)</code> is never True, so <code>await client.send_message</code> will never execute.</p>
<p>Changing it to <code>message.content[12:]</code> will remove the space.</p>
<hr>
<p><strong>Suggestions</strong></p>
<p>Adding a check to see if a game was found will allow you to see when all your <code>if</code> evaluates to <code>False</code>. It also gives users feedback when the command did not work, possibly because of incorrect usage.</p>
<p>You can also change the <code>requests</code> library to the <a href="https://aiohttp.readthedocs.io/en/stable/" rel="nofollow noreferrer"><code>aiohttp</code></a> library, which is the asynchronous version. <code>requests</code> can be dangerous as it is blocking, meaning that if it takes to long it can cause your code to crash.</p>
<p>Below is an example of how these suggestions can be used with your code.</p>
<pre><code>game_found = False
for i in gdata["applist"]["apps"]:
if (i["name"] == game):
game_found = True
app = (i["appid"])
session = aiohttp.ClientSession()
priceres = await session.get(f"https://store.steampowered.com/api/appdetails/?appids={app}")
priced = await priceres.json()
session.close()
price = (priced[f"{app}"]["data"]["price_overview"].get("final"))
msg = f"{game} is currently{price}".format(message)
await client.send_message(message.channel, msg)
if not game_found:
await client.send_message(message.channel, f"Could not find info on {game}"
</code></pre>
|
python|discord.py
| 1 |
1,903,347 | 64,797,643 |
The slice does not copy the list items, but the link to the list
|
<pre><code>matrix_a = [[5, 0.9, 0.3, 0.2],
[0.2, 8, 0.7, 0.5],
[1, 0.3, 5.5, 0.4],
[0.2, 0.5, 0.7, 6]]
matrix_d = [7,
9,
-5,
6]
def kramer_method(matrix, solution, determinant):
for i in range(4):
temp_matrix = matrix[:]
for t in range(4):
temp_matrix[t][i] = solution[t]
print(temp_matrix)
print(id(temp_matrix) == id(matrix))
return
kramer_method(matrix_a,matrix_d,determinant)
</code></pre>
<p>result:</p>
<pre><code>[[7, 0.9, 0.3, 0.2], [9, 8, 0.7, 0.5], [-5, 0.3, 5.5, 0.4], [6, 0.5, 0.7, 6]]
[[7, 7, 0.3, 0.2], [9, 9, 0.7, 0.5], [-5, -5, 5.5, 0.4], [6, 6, 0.7, 6]]
[[7, 7, 7, 0.2], [9, 9, 9, 0.5], [-5, -5, -5, 0.4], [6, 6, 6, 6]]
[[7, 7, 7, 7], [9, 9, 9, 9], [-5, -5, -5, -5], [6, 6, 6, 6]]
False
</code></pre>
<p>The quetion is: why is the temp_matrix list not taking the original matrix values at the start of the loop?</p>
|
<p>Taking a slice of a list does copy the list. It does what is known as a shallow copy. This means that while <code>temp_matrix</code> is a copy of the original list, it does not copy the elements. So if you did something like <code>temp_matrix.append([1,2,3])</code>, it would not change <code>matrix</code>. Since it does not copy the elements, if you modify one of those <code>temp_matrix[0].append(5)</code>, it would modify both <code>temp_matrix</code> and <code>matrix</code> since it is modifying the lists inside which were not copied.</p>
<p>What you will want to do is use the <a href="https://docs.python.org/3/library/copy.html" rel="nofollow noreferrer">copy</a> module. Specifically, you will want to <code>import copy</code>, and rather than use <code>temp_matrix = matrix[:]</code>, you would use <code>temp_matrix = copy.deepcopy(matrix)</code>. That page about the copy module also explains a bit more about what a deep copy is needed over a shallow copy as you had originally.</p>
|
python|list|loops|copy
| 1 |
1,903,348 | 65,019,151 |
Groupby matching pattern of different groups
|
<p>I have the following dataframe:</p>
<pre><code>df = pd.DataFrame({'ID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
'Info': ['info1', 'info2', 'info3', 'info4', 'info5', 'info6',
'info7', 'info8', 'info9', 'info10', 'info11', 'info12'],
'Category': ['157/120/RGB', '112/54/RGB', '14/280/CMYK', '50/100/RGB',
'150/88/CMYK', '160/100/G', '200/450/CMYK', '65/90/RGB',
'111/111/G', '244/250/RGB', '100/100/CMYK', '144/100/G']})
</code></pre>
<p>I need to get a number of dataframes equal to the number of right-sided Category string patterns, that is <code>RGB</code>, <code>CMYK</code>, <code>G</code>. Is there a way - maybe using regular expressions - to put just this string piece within <code>getgroup</code> method in order to create these groups? For instance:</p>
<pre><code>df_RGB = df.groupby('Category').getgroup('...RGB')
</code></pre>
<p>what should I replace dots with?</p>
|
<p>You can try this with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.get_group.html#pandas.core.groupby.GroupBy.get_group" rel="nofollow noreferrer"><code>GroupBy.get_group</code></a> here.</p>
<pre><code>g = df['Category'].str.extract("/*(\w+)$").squeeze()
keys = g.unique() # if you want to see all the keys
grouped = df.groupby(g)
df_RGB = grouped.get_group('RGB')
ID Info Category
0 1 info1 157/120/RGB
1 2 info2 112/54/RGB
3 4 info4 50/100/RGB
7 8 info8 65/90/RGB
9 10 info10 244/250/RGB
</code></pre>
<ul>
<li>Details about <a href="https://regex101.com/r/waC4Ex/1" rel="nofollow noreferrer">regex pattern used <code>regex101</code></a></li>
</ul>
|
python|pandas|dataframe|regular-language
| 3 |
1,903,349 | 72,026,123 |
How to conditionally remove first N rows of a dataframe out of 2 dataframes
|
<p>I have 2 dataframes as following:</p>
<pre><code>d = {'col1': [1, 2, 3, 4], 'col2': ["2010-01-01", "2011-01-01", "2012-01-01", "2013-01-01"]}
df = pd.DataFrame(data=d)
df
col1 col2
0 1 2010-01-01
1 2 2011-01-01
2 3 2012-01-01
3 4 2013-01-01
</code></pre>
<p>The other dataframe may look like the following:</p>
<pre><code>d2 = {'col1': [11, 22, 33, 44], 'col1': ["2011-01-01", "2011-05-01", "2012-02-01", "2012-06-01"]}
df2 = pd.DataFrame(data=d2)
df2
col1 col2
0 11 2011-01-01
1 22 2011-05-01
2 33 2012-02-01
3 44 2012-06-01
</code></pre>
<p>In both dataframes, <strong>col2</strong> includes dates (in String format, not as a date object) and these dates are placed in ascending order.</p>
<p>In my use case, both of these dataframes are supposed to start with the same value in <strong>col2</strong>.</p>
<p>The first col2 value of <strong>df</strong> is <strong>"2010-01-01"</strong>.
The first col2 value of <strong>df2</strong> is <strong>"2011-01-01"</strong>.
In this particular example, since <strong>"2010-01-01"</strong> does not exist in <strong>df2</strong> and <strong>"2011-01-01"</strong> is the second row item of col2 in <strong>df</strong> dataframe, the first row of <strong>df</strong> needs to be removed so that both dataframes start with the same date String value in <strong>col2</strong>. So, df is supposed to look as following after the change:</p>
<pre><code> col1 col2
1 2 2011-01-01
2 3 2012-01-01
3 4 2013-01-01
</code></pre>
<p>(Please note that the index is not reset after the change.)</p>
<p>But, this could have been the opposite and we could need to remove row(s) from df2 instead to be able to make these dataframes start with the same value in col2.</p>
<p>And in some cases, we may need to remove multiple rows, not only 1, from the dataframe where we need to remove the rows in case we do not find the match in the second row.</p>
<p>Corner case handling:
The logic should also handle such cases (without throwing errors) where it is not possible to make these 2 dataframes start with the same col2 value, in case there is no match. In that case, all rows from both dataframes are supposed to be removed.</p>
<p>Is there an elegant way of developing this logic without writing too many lines of code?</p>
|
<p>First get minimal <code>datetime</code> in both DataFrames and then filter all rows after this row in both <code>DataFrame</code>s (because is possible some rows are removed from <code>df1</code> or <code>df2</code>) by compare values by <code>both</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.cummax.html" rel="nofollow noreferrer"><code>Series.cummax</code></a>. If no match both DataFrames are empty.</p>
<pre><code>both = df.merge(df2, on='col2')['col2'].min()
df = df[df['col2'].eq(both).cummax()]
print (df)
col1 col2
1 2 2011-01-01
2 3 2012-01-01
3 4 2013-01-01
df2 = df2[df2['col2'].eq(both).cummax()]
print (df2)
col1 col2
0 11 2011-01-01
1 22 2011-05-01
2 33 2012-02-01
3 44 2013-01-01
</code></pre>
<hr />
<pre><code>#no match df2.col2 in df.col2
d2 = {'col1': [11, 22, 33, 44], 'col2': ["2011-01-21", "2011-05-01",
"2012-02-01", "2003-01-01"]}
df2 = pd.DataFrame(data=d2)
both = df.merge(df2, on='col2')['col2'].min()
df = df[df['col2'].eq(both).cummax()]
print (df)
Empty DataFrame
Columns: [col1, col2]
Index: []
df2 = df2[df2['col2'].eq(both).cummax()]
print (df2)
Empty DataFrame
Columns: [col1, col2]
Index: []
</code></pre>
|
python|python-3.x|pandas|dataframe
| 1 |
1,903,350 | 72,128,440 |
Sorting by two values and keeping the two highest values
|
<p>I have a problem. I want to create a chart. I want to show the difference between buyer <code>b</code> and seller <code>s</code>. But I want to show only the first 2 countries. Is there an option where I can filter for <code>b</code> and <code>s</code> and get the highest 2?</p>
<p>Dataframe</p>
<pre class="lang-py prettyprint-override"><code> count country part
0 50 DE b
1 20 CN b
2 30 CN s
3 100 BG s
4 3 PL b
5 40 BG b
6 5 RU s
</code></pre>
<p>Code</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
d = {'count': [50, 20, 30, 100, 3, 40, 5],
'country': ['DE', 'CN', 'CN', 'BG', 'PL', 'BG', 'RU'],
'part': ['b', 'b', 's', 's', 'b', 'b', 's']
}
df = pd.DataFrame(data=d)
df_consignee_countries['party'] = 'consignee'
df_orders_countries['party'] = 'buyer'
df_party = pd.concat([df_consignee_countries, df_orders_countries], join="outer")
ax = sns.barplot(x="country", y="count", hue='part', data=df_party, palette='GnBu')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
for p in ax.patches:
ax.annotate(format(p.get_height(), '.1f'),
(p.get_x() + p.get_width() / 2., p.get_height()),
ha = 'center', va = 'center',
xytext = (0, 9),
textcoords = 'offset points')
</code></pre>
<p>What I want</p>
<pre class="lang-py prettyprint-override"><code> count country part
0 50 DE b
2 30 CN s
3 100 BG s
5 40 BG b
</code></pre>
|
<p>You first need to sort your values and then take 2 rows per group:</p>
<pre><code>>>> df.sort_values('count', ascending=False).groupby('part').head(2)
count country part
3 100 BG s
0 50 DE b
5 40 BG b
2 30 CN s
</code></pre>
|
python|pandas|dataframe|seaborn
| 3 |
1,903,351 | 62,486,262 |
response selector is breaking the content into two different values
|
<p>I'm trying to scrape titles of the article from this page - <a href="https://onlinelibrary.wiley.com/doi/full/10.1111/pcmr.12547" rel="nofollow noreferrer">https://onlinelibrary.wiley.com/doi/full/10.1111/pcmr.12547</a></p>
<p>In "scrapy shell" if I run this
<code>response.css("h2.article-section__title::text").extract() </code> I'm getting the following output -</p>
<pre><code>[' Efficacy of small MC1R‐selective ',
'‐MSH analogs as sunless tanning agents that reduce UV‐induced DNA damage\n ',
.....
</code></pre>
<p>This is happening because, in HTML, the article is using an additional italics tag in the title.</p>
<pre><code><h2 class="article-section__title section__title section1" id="pcmr12547-sec-0002-title"> Efficacy of small MC1R‐selective <i>α </i>‐MSH analogs as sunless tanning agents that reduce UV‐induced DNA damage
</h2>
</code></pre>
<p>I can try to fix this it with a python code, which will combine the values until it receives '\n' at the end. But is there any way to fix it through scrapy or any other cleaner way?</p>
<p>A way in which the scrapy will scrape the value along with the HTML tags(if any) in it or, better ignore the tags but will get the text within the tag?</p>
|
<p>You can extract the whole HMTL element with:</p>
<pre class="lang-py prettyprint-override"><code>html_title = response.css(".article-section__title").get()
</code></pre>
<p>Then you can turn the result into plain text with something like <a href="https://pypi.org/project/html-text/" rel="nofollow noreferrer">html-text</a>:</p>
<pre><code>title = html_text.extract_text(html_title)
</code></pre>
|
python-3.x|scrapy|scrapy-shell
| 1 |
1,903,352 | 67,478,497 |
Creating a text file filled with custom formatted text
|
<p>I am trying to create a password list that has all the combinations in the following format:</p>
<p>3 characters 2 numbers 3 characters</p>
<p>example: <code>aaa00aaa</code> <code>bbb11bbb</code></p>
<p>I have created a code that does it with smaller arrays of characters however when I try to use all characters in the ASCII system the code gives out a memory error.</p>
<pre><code>import string
numbers = ["0","1","2","3","4","5","6","7","8","9"]
characters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
characterCombs = []
numbCombs = []
allCombs = []
for el1 in characters:
for el2 in characters:
for el3 in characters:
characterCombs.append(el1+el2+el3)
for n1 in numbers:
for n2 in numbers:
numbCombs.append(n1 + n2)
for ch1 in characterCombs:
for no in numbCombs:
for ch2 in characterCombs:
allCombs.append(ch1+no+ch2)
for i in allCombs:
f.write(i+"\n")
f.close()
</code></pre>
<p>is there a way to optimize this code or should I change my approach and find different ways to combine all these characters?</p>
|
<p>You can use python <code>itertools</code> module to generate combinations.</p>
<pre class="lang-py prettyprint-override"><code>from itertools import permutations
numbers = ["0","1","2","3","4","5","6","7","8","9"]
characters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
for a in permutations(characters, 3):
for b in permutations(numbers, 2):
for c in permutations(characters, 3):
print("".join(a + b + c))
</code></pre>
<p>This is going to take quite a lot of time though ...</p>
<hr />
<p>Also, you don't need to keep a list of all the generated passwords. You can write the passwords in your file inside the for-loops as you generate them.</p>
<hr />
<p>EDIT:</p>
<p>As @Andreas mentioned below, it should be indeed all the permutations (not combinations). I updated the code.</p>
|
python|python-3.x|passwords|combinations
| 0 |
1,903,353 | 67,354,696 |
How to capture all output from a shell script execution to a log file
|
<p>I have a shell script <code>worker.sh</code> which in turn calls various python scripts <code>Script1.py</code>, <code>Script2.py</code> etc like this <code>python3 Script2.py > shell.log</code>. There are also various print statements within the shell script and the python script to know what is happening and which statement is being executed.</p>
<pre><code>echo "Begin execution of Python Script" > shell.log
python3 Script2.py > shell.log
echo "End of execution" > shell.log
</code></pre>
<p>Is this the normal approach to log everything happening including the errors in both shell and python scripts or is there a better way of doing this instead of piping each <code>echo</code> statement to log file. I wanted to capture everything happening(errors as well) since the execution of shell script, including any <code>echo</code> statements in shell and <code>print</code> statements in python script.</p>
<p>Edit: The main shell script will be called via Apache NiFi.</p>
|
<p>What if you remove all '>'s from your script, and then rather logged the output of the whole script to shell.log?</p>
<p>worker.sh:</p>
<pre><code>echo "Begin execution of Python Script"
python3 script.py
echo "End of execution"
</code></pre>
<p>Run it</p>
<p><code>sh worker.sh > shell.log</code></p>
<p>Which would then write</p>
<pre><code>Begin execution of Python Script
Hello from Python!
End of execution
</code></pre>
<p>in shell.log.</p>
|
python|shell
| 1 |
1,903,354 | 63,370,246 |
pandas dataframe-python check if string exists in another column ignoring upper/lower case
|
<p>I have the same dataframe as i asked in (<a href="https://stackoverflow.com/q/62603123/13666184">pandas dataframe check if column contains string that exists in another column</a>)</p>
<pre><code>Name Description
Am Owner of Am
BQ Employee at bq
JW Employee somewhere
</code></pre>
<p>I want to check if the name is also a part of the description, and if so keep the row. If it's not, delete the row. In this case, it will delete the 3rd row (JW Employee somewhere)</p>
<p>I am using</p>
<pre><code>df[df.apply(lambda x: x['Name'] in x['Description'], axis = 1)]
</code></pre>
<p>In this case, it is also deleting the row of BQ because in the description "bq" is in lowercase. In there anyway to use to same syntax but with taking into consideration case sensitivity ?</p>
|
<p>Use <code>.lower()</code> to make it case-agnostic:</p>
<pre><code>df[df.apply(lambda x: x['Name'].lower() in x['Description'].lower(), axis=1)]
</code></pre>
<p>Note that this will consider <code>"am"</code> as a match on <code>"amy"</code>. You may wish to use word boundaries to prevent this:</p>
<pre><code>>>> def filter(x):
... return bool(re.search(rf"(?i)\b{x['Name']}\b", x["Description"]))
...
>>> df[df.apply(filter, axis=1)]
Name Description
0 Am Owner of Am
1 BQ Employee at bq
</code></pre>
<p>Or <code>split</code> which handles regex special characters better:</p>
<pre><code>df[df.apply(lambda x: x["Name"].lower() in x["Description"].lower().split(), axis=1)]
</code></pre>
|
python|pandas|dataframe
| 4 |
1,903,355 | 62,088,720 |
Display images from sqlite3 database to a column in QTableWidget with Python
|
<p>After looking at various examples here and elswhere, I have not been able to show images in 'mydb.db' which is my SQlite3 database to my table QTableWidget in python. Here is my code </p>
<pre><code>def fetch_all_learner_data(self):
connection= sqlite3.connect("mydb.db")
query = "SELECT NAME,ADM,CLASS,STREAM,CATEGORY,GENDER,COUNTY,PARENT,PARENT_CONTACT,PHOTO FROM learner_data"
result = connection.execute(query)
self.classes_table.setRowCount(0)
for row_number,row_data in enumerate(result):
self.classes_table.insertRow(row_number)
for column_number,data in enumerate(row_data):
self.classes_table.setItem(row_number,column_number,QTableWidgetItem(str(data)))
connection.commit()
connection.close()
</code></pre>
<p>This is what end up getting on the image column in the qtable and which have also really slowed my system.</p>
<p><a href="https://i.stack.imgur.com/so7Vs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/so7Vs.png" alt="What displays in the qtable"></a></p>
<p>How can I solve this?</p>
|
<p>You have to build a QIcon based on the data using a QPixmap:</p>
<pre><code>def fetch_all_learner_data(self):
connection = sqlite3.connect("mydb.db")
query = "SELECT NAME,ADM,CLASS,STREAM,CATEGORY,GENDER,COUNTY,PARENT,PARENT_CONTACT,PHOTO FROM learner_data"
result = connection.execute(query)
self.classes_table.setRowCount(0)
for row_number, row_data in enumerate(result):
self.classes_table.insertRow(row_number)
for column_number, data in enumerate(row_data):
it = QTableWidgetItem()
if column_number == 9:
pixmap = QPixmap()
pixmap.loadFromData(data)
it.setIcon(QIcon(pixmap))
else:
it.setText(str(data))
self.classes_table.setItem(row_number, column_number, it)
connection.commit()
connection.close()
</code></pre>
|
python|sqlite|pyqt5
| 3 |
1,903,356 | 59,022,199 |
Getting a number of items created in a particular year in Pandas
|
<p>I am writing a function that returns a number of items created in a particular year in a pandas data frame where the search is made in a column ['çreation'] that has a format 2015-05-11 :</p>
<pre class="lang-py prettyprint-override"><code>def do_get_citations_per_year(data, year):
result = tuple()
citations = list()
for index, row in my_ocan.iterrows():
my_ocan['creation'] = pd.DatetimeIndex(my_ocan['creation']).year
#print(my_ocan['creation'])
if row['creation'] == year:
citations.append(row['creation'])
len_citations = len(citations)
result=(len_citations)
return result
</code></pre>
<p>When I run my function <code>print(my_ocan.get_citations_per_year(2015))</code> I get 0, but there are items created in 2015. </p>
<p>What's the problem? </p>
<p>Thank you and have an awesome day!</p>
|
<p>Try:</p>
<pre class="lang-py prettyprint-override"><code>def do_get_citations_per_year(data, year):
result = tuple()
citations = list()
my_ocan['creation'] = pd.DatetimeIndex(my_ocan['creation']).year
for index, row in my_ocan.iterrows():
#print(my_ocan['creation'])
if row['creation'] == year:
citations.append(row['creation'])
len_citations = len(citations)
result=(len_citations)
return result
</code></pre>
<p>Alternatively I suppose this would give you, what you are looking for:</p>
<pre class="lang-py prettyprint-override"><code>def do_get_citations_per_year(data, year):
result = tuple()
my_ocan['creation'] = pd.DatetimeIndex(my_ocan['creation']).year
len_citations = len(my_ocan.loc[my_ocan["creation"]==year, "creation"])
result=(len_citations)
return result
</code></pre>
<p>(You don't have to iterate through all the pandas rows, just use <code>.loc[<condition>, <colimns_to_return>]</code>)</p>
|
python|python-3.x|pandas
| 0 |
1,903,357 | 72,405,003 |
Dataframe transformation based on repeating cell values based on column values
|
<p>Having a dataframe like this:</p>
<p><a href="https://i.stack.imgur.com/A7tGH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A7tGH.png" alt="enter image description here" /></a></p>
<p>I would like to know what would be the most efficient way to transform it into this othe one:</p>
<p><a href="https://i.stack.imgur.com/eXGak.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eXGak.png" alt="enter image description here" /></a></p>
<p>I tried to generate all the combinations between <strong>Time</strong> column and <strong>days</strong> and then manually create the <strong>Value</strong> column by checking the given <strong>Day-Time</strong> cell, but Im sure it must be a more efficient way</p>
|
<p><strong>IF the original index is not important for you</strong>,
You could also use the <code>.melt()</code> method which has the advantage of grouping the days so you have the values for 1 day after another:</p>
<pre><code>df1 = df.melt(id_vars='Time', var_name='Day', value_name='Value')
</code></pre>
<p>Result:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>Time</th>
<th>Day</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>6am-2pm</td>
<td>Day1</td>
<td>15.4</td>
</tr>
<tr>
<td>1</td>
<td>2pm-10pm</td>
<td>Day1</td>
<td>15.0</td>
</tr>
<tr>
<td>2</td>
<td>10pm-6am</td>
<td>Day1</td>
<td>14.0</td>
</tr>
<tr>
<td>3</td>
<td>6am-2pm</td>
<td>Day2</td>
<td>13.4</td>
</tr>
<tr>
<td>4</td>
<td>2pm-10pm</td>
<td>Day2</td>
<td>2.1</td>
</tr>
<tr>
<td>5</td>
<td>10pm-6am</td>
<td>Day2</td>
<td>22.0</td>
</tr>
<tr>
<td>6</td>
<td>6am-2pm</td>
<td>Day3</td>
<td>45.0</td>
</tr>
<tr>
<td>7</td>
<td>2pm-10pm</td>
<td>Day3</td>
<td>3.4</td>
</tr>
<tr>
<td>8</td>
<td>10pm-6am</td>
<td>Day3</td>
<td>35.0</td>
</tr>
</tbody>
</table>
</div>
<p>You could even rearrange the columns index like this to make it more readable in my own opinion:</p>
<pre><code>df1 = df1.reindex(columns=['Day','Time','Value'])
</code></pre>
<p>Result:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>index</th>
<th>Day</th>
<th>Time</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>Day1</td>
<td>6am-2pm</td>
<td>15.4</td>
</tr>
<tr>
<td>1</td>
<td>Day1</td>
<td>2pm-10pm</td>
<td>15.0</td>
</tr>
<tr>
<td>2</td>
<td>Day1</td>
<td>10pm-6am</td>
<td>14.0</td>
</tr>
<tr>
<td>3</td>
<td>Day2</td>
<td>6am-2pm</td>
<td>13.4</td>
</tr>
<tr>
<td>4</td>
<td>Day2</td>
<td>2pm-10pm</td>
<td>2.1</td>
</tr>
<tr>
<td>5</td>
<td>Day2</td>
<td>10pm-6am</td>
<td>22.0</td>
</tr>
<tr>
<td>6</td>
<td>Day3</td>
<td>6am-2pm</td>
<td>45.0</td>
</tr>
<tr>
<td>7</td>
<td>Day3</td>
<td>2pm-10pm</td>
<td>3.4</td>
</tr>
<tr>
<td>8</td>
<td>Day3</td>
<td>10pm-6am</td>
<td>35.0</td>
</tr>
</tbody>
</table>
</div>
|
python-3.x|pandas|dataframe
| 2 |
1,903,358 | 35,222,726 |
generate temporary file to replace real file
|
<p>I need to generate a temporary file to replace a system file with new contents.</p>
<p>I have the code, and it works, but I was thinking if there is some module that automatically does that, along the lines of:</p>
<pre><code>with tempfile.NamedTemporaryFileFor('/etc/systemfile', delete=False) as fp:
...
</code></pre>
<p>This would create a temporary file with the same permissions and owner of the original file and in the same folder. Then I would write my new contents and atomically replace the original systemfile with the new one. Heck, the context manager could do the replacement for me when the file is closed!</p>
<p>My current code is:</p>
<pre><code>with tempfile.NamedTemporaryFile(delete=False, dir='/etc') as fp:
tempfilename = fp.name
fp.write('my new contents')
orig_stat = os.stat('/etc/systemfile')
os.chown(tempfilename, orig_stat.st_uid, orig_stat.st_gid)
os.chmod(tempfilename, orig_stat.st_mode)
os.replace(tempfilename, '/etc/systemfile')
</code></pre>
|
<p>There is no such context manager in tempfile but it's not too difficult to write your own context manager:</p>
<pre><code>class NamedTemporaryFileFor(object):
def __init__(self, orig_path, delete=True, dir=None):
self.orig_path = orig_path
self.named_temp_file = tempfile.NamedTemporaryFile(delete=delete, dir=dir)
def __enter__(self):
self.named_temp_file.__enter__()
return self
def write(self, *args, **kwargs):
return self.named_temp_file.write(*args, **kwargs)
def __exit__(self, exc, value, tb):
orig_stat = os.stat(self.orig_path)
os.chown(self.named_temp_file.name, orig_stat.st_uid, orig_stat.st_gid)
os.chmod(self.named_temp_file.name, orig_stat.st_mode)
self.named_temp_file.__exit__(exc, value, tb)
if __name__ == "__main__":
with NamedTemporaryFileFor(sys.argv[1], delete=False, dir="/etc") as fp:
f.write(b'my new content')
</code></pre>
<p>(Note that I've had to pass a byte string to the <code>write</code> method to make the example work)</p>
|
python-3.x|atomic|temporary-files
| 1 |
1,903,359 | 54,142,430 |
How to install Pycrypto for Python 3.7.2?
|
<p>When installing Pycrypto, a compiler error occurs</p>
<p>I need to install Pycrypto thrue pip install</p>
<pre><code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Isrc/ -Isrc/inc-msvc/ -Id:\gametest\include -IC:\Python37\include -IC:\Python37\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.16.27023\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\cppwinrt" /Tcsrc/winrand.c /Fobuild\temp.win-amd64-3.7\Release\src/winrand.obj
winrand.c
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(27): error C2061: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : Ё¤ҐвЁдЁЄ в®а "intmax_t"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(28): error C2061: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : Ё¤ҐвЁдЁЄ в®а "rem"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(28): error C2059: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ;
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(29): error C2059: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : }
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(31): error C2061: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : Ё¤ҐвЁдЁЄ в®а "imaxdiv_t"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(31): error C2059: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ;
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(41): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(42): error C2146: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ ")" ЇҐаҐ¤ Ё¤ҐвЁдЁЄ в®а®¬ "_Number"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(42): error C2061: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : Ё¤ҐвЁдЁЄ в®а "_Number"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(42): error C2059: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ;
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(43): error C2059: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : )
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(46): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(47): error C2146: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ ")" ЇҐаҐ¤ Ё¤ҐвЁдЁЄ в®а®¬ "_Numerator"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(47): error C2061: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : Ё¤ҐвЁдЁЄ в®а "_Numerator"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(47): error C2059: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ;
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(47): error C2059: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ,
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(49): error C2059: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : )
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(51): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(57): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(64): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(70): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(77): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(83): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(90): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
C:\Program Files (x86)\Windows Kits\10\include\10.0.17763.0\ucrt\inttypes.h(96): error C2143: бЁв ЄбЁзҐбЄ п ®иЁЎЄ : ®вбгвбвўЁҐ "{" ЇҐаҐ¤ "__cdecl"
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2
----------------------------------------
</code></pre>
<pre><code>Command
"d:\gametest\scripts\python.exe -u -c "import setuptools, tokenize;__file__=
'C:\\Users\\John\\AppData\\Local\\Temp\\pip-install-59ujdaeb\\pycrypto
\\setup.py';f=getattr(tokenize, 'open',
open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record
C:\Users\John\AppData\Local\Temp\pip-record-0_6xj1_v\install-record.txt
--single-version-externally-managed --compile --install-headers d:\gametest
\include\site\python3.7\pycrypto" failed with error code 1 in C:\Users
\John\AppData\Local\Temp\pip-install-59ujdaeb\pycrypto\
</code></pre>
<p>Visual Studio installed</p>
|
<p><code>pip install pycryptodome</code> It is a pycrypto fork with new features and it supports wheel. It replaces pycrypto <a href="https://pycryptodome.readthedocs.org/en/latest/src/examples.html" rel="noreferrer">https://pycryptodome.readthedocs.org/en/latest/src/examples.html</a></p>
|
python|python-3.x|pycrypto
| 18 |
1,903,360 | 36,175,385 |
django slugify russian string
|
<p>I am making search for website with multiple languages. It's working fine, but when it comes to Russian, i get problems. Django doesn't process Russian characters. In template i have </p>
<pre><code><input type="text" name="q">
</code></pre>
<p>When i type russian text, like <strong>ванна</strong>,in my view function in <code>request.POST['q']</code> i have that word correctly. Then i need to slugify this, but it just gives me empty string. Also i tried this <a href="https://stackoverflow.com/a/4036665/5607745">answer</a>, but then i get result <strong>vanna</strong>, when i need it to be the same Russian string. Maybe there is some way converting it back? Or any other solution?</p>
|
<p>From <a href="https://docs.djangoproject.com/en/stable/ref/utils/#django.utils.text.slugify" rel="nofollow noreferrer">documentation</a>:</p>
<blockquote>
<p>Converts to ASCII if allow_unicode is False (default). Converts spaces to hyphens. Removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.</p>
</blockquote>
<p>This should work:</p>
<pre><code>slugify("ванна", allow_unicode=True)
</code></pre>
<p>This is only available as of Django 1.9 though.</p>
<p>However, based on <a href="https://github.com/django/django/blob/1.9/django/utils/text.py#L413-L427" rel="nofollow noreferrer">Django 1.9 source code</a>, you can create your own utils function:</p>
<pre><code>from __future__ import unicode_literals
import re
import unicodedata
from django.utils import six
from django.utils.encoding import force_text
from django.utils.functional import allow_lazy
from django.utils.safestring import SafeText, mark_safe
def slugify_unicode(value):
value = force_text(value)
value = unicodedata.normalize('NFKC', value)
value = re.sub('[^\w\s-]', '', value, flags=re.U).strip().lower()
return mark_safe(re.sub('[-\s]+', '-', value, flags=re.U))
slugify_unicode = allow_lazy(slugify_unicode, six.text_type, SafeText)
</code></pre>
|
python|django|cyrillic
| 4 |
1,903,361 | 46,548,157 |
Python os.execve()
|
<p>I'm trying spawn new process with method <code>execve()</code> from <code>os</code> module. I need spawn new process and do some stuff in another directory, but i won't change.</p>
<p>code:</p>
<pre><code>import os
os.execve('/bin/ls', ['/bin/ls'], {'PATH': '/tmp'})
</code></pre>
<p>when i ran this code, i got content of directory where i'm, not from <code>/tmp</code> directory. What i'm doing wrong? I cannot use <code>os.chdir()</code> or change the way how the run command (like use module <code>subprocess</code>)</p>
|
<p>Change your current working directory before calling <code>execve()</code>. The CWD will be inherited by the new process.</p>
<pre><code>import os
os.chdir('/tmp')
os.execve('/bin/ls', ['arg1', 'arg2'], {'PATH': 'is_inherited_anyway'})
</code></pre>
|
python-2.7
| 0 |
1,903,362 | 44,243,237 |
String to array of integer
|
<p>I have a string <code>'[1. 2. 3. 4. 5.]'</code> and I would like to convert to get only the int such that i obtain an array of integer of <code>[1, 2, 3, 4, 5]</code></p>
<p>How do I do that? I tried using <code>map</code> but unsuccessful.</p>
|
<p>Use <code>strip</code> for remove <code>[]</code>, <code>split</code> for convert to <code>list</code> of <code>values</code> which are converted to <code>int</code> in <code>list comprehension</code>:</p>
<pre><code>s = '[1. 2. 3. 4. 5.]'
print ([int(x.strip('.')) for x in s.strip('[]').split()])
[1, 2, 3, 4, 5]
</code></pre>
<p>Similar solution with <code>replace</code> for remove <code>.</code>:</p>
<pre><code>s = '[1. 2. 3. 4. 5.]'
print ([int(x) for x in s.strip('[]').replace('.','').split()])
[1, 2, 3, 4, 5]
</code></pre>
<p>Or with convert to <code>float</code> first and then to <code>int</code>:</p>
<pre><code>s = '[1. 2. 3. 4. 5.]'
print ([int(float(x)) for x in s.strip('[]').split()])
[1, 2, 3, 4, 5]
</code></pre>
<p>Solution with <code>map</code>:</p>
<pre><code>s = '[1. 2. 3. 4. 5.]'
#add list for python 3
print (list(map(int, s.strip('[]').replace('.','').split())))
[1, 2, 3, 4, 5]
</code></pre>
|
arrays|list|python-3.x|integer
| 2 |
1,903,363 | 47,432,006 |
Logging exception filters in python
|
<p>I want to exclude some specific exceptions that are not critical from logging to <a href="https://docs.sentry.io/clients/python/integrations/logging/" rel="nofollow noreferrer">sentry</a> using <a href="https://github.com/getsentry/raven-python" rel="nofollow noreferrer">raven</a> handler.</p>
<p>However, I couldn't find out any way to config the filters for those handlers.</p>
<p>The similar logging feature in Java is <a href="https://logging.apache.org/log4j/2.0/manual/filters.html" rel="nofollow noreferrer">https://logging.apache.org/log4j/2.0/manual/filters.html</a></p>
<p>I want to do something like this</p>
<pre><code>import logging
...
LOGGING = {
'loggers' = {
'django': {
'handlers': ['sentry', 'console'],
'filters': {
'exclude': [ObjectDoesNotExist, ]
},
'level': 'ERROR',
}
}
}
</code></pre>
<p>Do <code>logging</code> package support that? If no, would you mind telling me the best way to achieve that?</p>
<p>Thanks</p>
|
<p>Thanks for @georgexsh advice, I finally end up with this solution.</p>
<pre><code># config.log_filter.py
from logging import Filter
from django.core.exceptions import ObjectDoesNotExist
DEFAULT_EXCLUDE_EXCEPTIONS = [ObjectDoesNotExist, ]
class ExceptionFilter(Filter):
def __init__(self, exclude_exceptions=DEFAULT_EXCLUDE_EXCEPTIONS, **kwargs):
super(ExceptionFilter, self).__init__(**kwargs)
self.EXCLUDE_EXCEPTIONS = exclude_exceptions
def filter(self, record):
if record.exc_info:
etype, _, _ = record.exc_info
for excluded_exception in self.EXCLUDE_EXCEPTIONS:
if issubclass(etype, excluded_exception):
return False
return True
# settings.common.py
...
LOGGING = {
...
'filters': {
'exception_filter': {
'()': 'config.log_filter.ExceptionFilter'
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'filters': ['exception_filter']
}
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
},
...
}
}
logging.config.dictConfig(LOGGING)
</code></pre>
<p>Hope it helps someone those encounter the same problem</p>
|
python
| 5 |
1,903,364 | 69,742,784 |
Box plot are overlapping because of same name
|
<pre><code>for design in list
if len(design) > 12:
df["Name"] = str(design)[:12] + str("...")
fig.add_trace(
go.Box(
x=df["Name"],
y=df[y_variable],
name="",
quartilemethod=quartile_method,
boxpoints=False,
)
</code></pre>
<p>so if i have 2 names in the list
name1 = ABCDEFGHIJKL
name2 = ABCDEFGHIJKLM</p>
<p>after truncation
name1 = ABCDEFGHIJKL
name2 = ABCDEFGHIJKL</p>
<p>so both become same in x.</p>
<p>Overlapping box blot with same x</p>
<p><img src="https://i.stack.imgur.com/njtwj.png" alt="" /></p>
<p>How to overcome this?
I tried using unique identifier but at the same time I want to have same in the x axis</p>
|
<ul>
<li>reusing <a href="https://plotly.com/python/box-plots/#box-plot-with-plotlyexpress" rel="nofollow noreferrer">https://plotly.com/python/box-plots/#box-plot-with-plotlyexpress</a> as basis for re-runnable example</li>
<li>simulated the issue you noted, where x values overlap</li>
<li>resolved, by
<ol>
<li>not truncating x value</li>
<li>resolved by updating <strong>xaxis</strong> ticks so that truncated value is displayed and bar plots are maintained</li>
</ol>
</li>
</ul>
<pre><code>import plotly.express as px
import plotly.graph_objects as go
df = px.data.tips()
df["name"] = df["time"].map({"Dinner": "ABCDEFGHIJKLMNO", "Lunch": "ABCDEFGHIJKLMNOP"})
go.Figure(
[
go.Box(
x=df.loc[df["name"].eq(n), "name"].str[0:12],
y=df.loc[df["name"].eq(n), "total_bill"],
name=n,
boxpoints=False
)
for n in df["name"].unique()
]
).show()
go.Figure(
[
go.Box(
x=df.loc[df["name"].eq(n), "name"],
y=df.loc[df["name"].eq(n), "total_bill"],
name=n,
boxpoints=False
)
for n in df["name"].unique()
]
).update_layout(xaxis=dict(tickmode="array", tickvals=df.loc[:, "name"], ticktext=df.loc[:, "name"].str[0:12]))
</code></pre>
<p><a href="https://i.stack.imgur.com/rkY5j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rkY5j.png" alt="enter image description here" /></a></p>
|
python|plotly|plotly-dash|boxplot
| 1 |
1,903,365 | 72,921,680 |
what difference between nltk tokenizer and RobertaTokenizer?
|
<p>why here we take <code>RobertaTokenizer</code> and why do we perform Word2Vec?</p>
<pre class="lang-py prettyprint-override"><code> def __init__(self, modelpath, tokenizer):
self.model = Word2Vec.load(modelpath)
self.tokenizer = RobertaTokenizer.from_pretrained('microsoft/graphcodebert-base', cache_dir = config["cached_dir"])
</code></pre>
<p>what difference between NLTK tokenizer and <code>RobertaTokenizer</code>?
why we need <code>RobertaTokenizer</code> instead NLTK?
I know the NLTK tokenizer creates a word index of every word in the set and we perform word2vec to get the semantic meaning between words, but I a can not find why <code>RobertaTokenizer</code> is proposed instead tokenizer from NLTK?</p>
|
<p>This question can be answered using a more abstract view. I can rephrase the question like this "when we already have word vectors for every single token, What makes us use Transformers architecture?" the answer, let's assume you have the word <strong>'bank'</strong> in <code>I paid the money straight into my bank</code> and <strong>'bank'</strong> in <code>willows lined the bank</code>. As you may notice the word doesn't have the same meaning and the model should consider the difference. But with a single word vector assigned to the token, it's simply impossible. So there's a need for a model capable of modeling the difference and it is the exact thing that <code>BERT</code>, <code>RoBERTa</code>, <code>DistillBERT</code>, and any other Transformer-based model do!</p>
<p><strong>Update</strong></p>
<p>There are several ways of quantifying or vectorizing text pieces each having its own pros and cons. In some cases, they can be used alongside each other but generally, they are interchangeable and used individually.</p>
<ul>
<li>Bag of Words (simple but ineffective because doesn't care about word similarities)</li>
<li>TF-IDF (simple yet efficient and better than BoW, doesn't consider word similarities)</li>
<li>Word Dense Vectors (efficient, convenient, can't model different senses for a token in different contexts)</li>
<li>Transformers family is known as WordPiece tokenizers (best way till now in terms of efficiency, relatively complex, and high computation consumption)</li>
</ul>
|
python|nlp|nltk
| 0 |
1,903,366 | 55,996,280 |
How to access distinct elements of a tuple inside an array, passed as function argument?
|
<p>I am trying to manipulate distinct elementf of a tuple, which is part of an array.</p>
<p>What I have:</p>
<pre class="lang-py prettyprint-override"><code>def my_function(lis):
for i in lis:
x[i], y[i], z[i] = lis[i]
...
</code></pre>
<p>As in the main I have:</p>
<pre class="lang-py prettyprint-override"><code>my_function([(1,2,3), (4,5,6), (7,8,9), (10,11,12)]):
...
</code></pre>
<p>The result was:</p>
<pre><code>TypeError: list indices must be integers or slices, not tuple
</code></pre>
<p>As mentioned, I am trying to access distinc element of the tuple from the function and manipulate them.</p>
|
<p>Each <code>i</code> <em>is</em> a tuple; you probably want</p>
<pre><code>for i in lis:
x, y, z = i
# use x, y, and z
</code></pre>
<p>or simply</p>
<pre><code>for x, y, z in lis:
# use x, y, and z
</code></pre>
|
python|arrays|function|tuples
| 4 |
1,903,367 | 64,676,618 |
Align Icon in QPushButton
|
<p>Starting the program, the QIcon is aligned on the left (it's standard i guess) with the text right to it.</p>
<p><img src="https://i.stack.imgur.com/fg6Nx.png" alt="looks like this" /></p>
<p>Instead I want the icon to be centered on top with the text below it.</p>
<p>I tried using <code>setStyleSheet</code> with <code>show_all.setStyleSheet("QIcon { vertical-align: top }")</code> and <code>show_all.setStyleSheet("QPushButton { text-align: bottom }")</code>.</p>
<p>How can I achieve this?</p>
|
<p>QPushButton doesn't allow to choose the layout of its icon and label. Also, remember that while Qt features style sheets to style widgets, not all CSS known properties and selectors are available. Furthermore, style sheets only work on <em>widgets</em>, so using the <code>QIcon</code> selector isn't supported, since QIcon is not a QWidget subclass.</p>
<p>The most simple solution is to use a QToolButton and set the <a href="https://doc.qt.io/qt-5/qtoolbutton.html#toolButtonStyle-prop" rel="nofollow noreferrer"><code>toolButtonStyle</code></a> correctly:</p>
<pre><code>self.someButton = QtWidgets.QToolButton()
# ...
self.someButton.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
</code></pre>
<p>The alternative is to subclass the button, provide a customized paint method <em>and</em> reimplement both <code>sizeHint()</code> and <code>paintEvent()</code>; the first is to ensure that the button is able to resize itself whenever required, while the second is to paint the button control (without text!) and then paint both the icon <em>and</em> the text.</p>
<p>Here's a possible implementation:</p>
<pre><code>from PyQt5 import QtCore, QtGui, QtWidgets
class CustomButton(QtWidgets.QPushButton):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._icon = self.icon()
if not self._icon.isNull():
super().setIcon(QtGui.QIcon())
def sizeHint(self):
hint = super().sizeHint()
if not self.text() or self._icon.isNull():
return hint
style = self.style()
opt = QtWidgets.QStyleOptionButton()
self.initStyleOption(opt)
margin = style.pixelMetric(style.PM_ButtonMargin, opt, self)
spacing = style.pixelMetric(style.PM_LayoutVerticalSpacing, opt, self)
# get the possible rect required for the current label
labelRect = self.fontMetrics().boundingRect(
0, 0, 5000, 5000, QtCore.Qt.TextShowMnemonic, self.text())
iconHeight = self.iconSize().height()
height = iconHeight + spacing + labelRect.height() + margin * 2
if height > hint.height():
hint.setHeight(height)
return hint
def setIcon(self, icon):
# setting an icon might change the horizontal hint, so we need to use a
# "local" reference for the actual icon and go on by letting Qt to *think*
# that it doesn't have an icon;
if icon == self._icon:
return
self._icon = icon
self.updateGeometry()
def paintEvent(self, event):
if self._icon.isNull() or not self.text():
super().paintEvent(event)
return
opt = QtWidgets.QStyleOptionButton()
self.initStyleOption(opt)
opt.text = ''
qp = QtWidgets.QStylePainter(self)
# draw the button without any text or icon
qp.drawControl(QtWidgets.QStyle.CE_PushButton, opt)
rect = self.rect()
style = self.style()
margin = style.pixelMetric(style.PM_ButtonMargin, opt, self)
iconSize = self.iconSize()
iconRect = QtCore.QRect((rect.width() - iconSize.width()) / 2, margin,
iconSize.width(), iconSize.height())
if self.underMouse():
state = QtGui.QIcon.Active
elif self.isEnabled():
state = QtGui.QIcon.Normal
else:
state = QtGui.QIcon.Disabled
qp.drawPixmap(iconRect, self._icon.pixmap(iconSize, state))
spacing = style.pixelMetric(style.PM_LayoutVerticalSpacing, opt, self)
labelRect = QtCore.QRect(rect)
labelRect.setTop(iconRect.bottom() + spacing)
qp.drawText(labelRect,
QtCore.Qt.TextShowMnemonic|QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop,
self.text())
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = CustomButton('Alles anzeigen', icon=QtGui.QIcon.fromTheme('document-new'))
w.setIconSize(QtCore.QSize(32, 32))
w.show()
sys.exit(app.exec_())
</code></pre>
|
python|python-3.x|pyqt|pyqt5
| 2 |
1,903,368 | 65,008,647 |
Python animation from file
|
<p>I'm trying to animate some function. My x values are constant (the range doesn't change throughout the animation):</p>
<pre><code>x = np.linspace(0,1,N)
</code></pre>
<p>And I have my y values stored in a file as frames, separated with a new line:</p>
<pre><code>1
2
3
1.2
1.9
2.8
</code></pre>
<p>How can I show all my values from the frame at once and then move to another frame?</p>
|
<p>I start by creating mock data in a file called <code>data.txt</code> with the format you specified:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def your_func(x, a):
return np.sin(x + a)
n_cycles = 4
n_frames = 100
xmin = 0
xmax = n_cycles*2*np.pi
N = 120
x = np.linspace(xmin, xmax, N)
with open('data.txt', 'w') as fout:
for i in range(n_frames):
alpha = 2*np.pi*i/n_frames
y = your_func(x, alpha)
for value in y:
print(f'{value:.3f}', file=fout)
print(file=fout)
</code></pre>
<p>The data file looks like this:</p>
<pre><code>0.000 # First frame
0.210
...
-0.210
-0.000
0.063 # Second frame
0.271
...
-0.148
0.063
...
-0.063 # Frame 100
0.148
...
-0.271
-0.063
</code></pre>
<p>Then I read those data from disk:</p>
<pre class="lang-py prettyprint-override"><code>def read_data(filename):
with open(filename, 'r') as fin:
text = fin.read()
values = [[]]
for line in text.split('\n'):
if line:
values[-1].append(float(line))
else:
values.append([])
return np.array(values[:-2])
y = read_data('data.txt')
</code></pre>
<p>The animation is generated as follows:</p>
<pre class="lang-py prettyprint-override"><code>from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
def plot_background():
line.set_data([], [])
return line,
def animate(i):
line.set_data(x, y[i])
return line,
fig = plt.figure()
ax = plt.axes(xlim=(x[0], x[-1]), ylim=(-1.1, 1.1))
line, = ax.plot([], [], lw=2)
anim = FuncAnimation(fig, animate, init_func=plot_background,
frames=n_frames, interval=10, blit=True)
anim.save(r'animated_function.mp4',
fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/5nDuo.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5nDuo.gif" alt="animation" /></a></p>
<p>For a more detailed explanation, take a look at <a href="https://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/" rel="nofollow noreferrer">this blog</a>.</p>
|
python|matplotlib|animation|plot
| 2 |
1,903,369 | 64,886,945 |
How can I get .Replace() to work from a text file?
|
<p>im trying to replace all the periods, and commas from a text file the .lower works perfectly find only .replace isn't working</p>
<pre><code>def clean_text(text):
for line in text:
line= text.replace(".", "")
line= text.replace(",", "")
line=(text.lower())
print(line)
</code></pre>
|
<pre><code>line= text.replace(".", "")
</code></pre>
<p>That code creates a new variable <code>line</code> which is a copy of <code>text</code> without periods.</p>
<pre><code>line= text.replace(",", "")
</code></pre>
<p>That code erases the previous contents of <code>line</code> and recreates it as a new variable which is a copy of <code>text</code> without commas.</p>
<pre><code>line=(text.lower())
</code></pre>
<p>That code erases the previous contents of <code>line</code> again, and recreates it as a new variable which is a lowercase copy of <code>text</code>.</p>
<p>So, your problem is that you're making variables and then throwing them away, undoing your work.</p>
<p>Perhaps you meant to do this instead:</p>
<pre><code>line= text.replace(".", "")
line= line.replace(",", "")
line=(line.lower())
</code></pre>
<p>Note how the last two statements refer to <code>line</code> instead of <code>text</code>, so the work done by the previous statements is preserved.</p>
|
python|replace
| 3 |
1,903,370 | 63,993,778 |
Deleting all rows in a pandas dataframe below a row with a specific column value
|
<p>I have a Pandas dataframe that has extra data in the last handful of rows. I need to identify the row with a particular column value and delete all rows starting with that row and below.</p>
<p>Example of the dataframe:</p>
<pre><code>Mod Day Initials
1 9/4/18 AV
2 4/20/19 AV
3 7/18/17 AV
4 12/1/13 AV
Program Title Amount
Axis Axis Gig $35
Rex Rex Gig $75
DOM Triple Z $15
</code></pre>
<p>So, I would want to identify where the dataframe has "Title" in the "Day" Column and delete that row and all rows below it.</p>
|
<p>You can use boolean indexing with <code>df.where</code></p>
<pre><code>s = """Mod,Day,Initials
1,9/4/18,AV
2,4/20/19,AV
3,7/18/17,AV
4,12/1/13,AV
Program,Title,Amount
Axis,Axis Gig,$35
Rex,Rex Gig,$75
DOM,Triple Z,$15"""
df = pd.read_csv(StringIO(s))
# select where your col equals 'Title' then fill all other values with nan
# forward fill all nan values after title and the use boolean indexing
new_df = df[df['Day'].where(df['Day'] == 'Title', np.nan).ffill() != 'Title']
Mod Day Initials
0 1 9/4/18 AV
1 2 4/20/19 AV
2 3 7/18/17 AV
3 4 12/1/13 AV
</code></pre>
|
pandas|dataframe|filter
| 0 |
1,903,371 | 53,311,302 |
Flask consul and consul DNS
|
<p>I'm trying to learn playing with flask and consul.</p>
<p>Here is my /etc/consul.d/consul.json</p>
<p>{
"data_dir": "/opt/consul/data",
"server": true,
"bind_addr": "0.0.0.0",
"bootstrap_expect": 1,
"ui": true,
"domain": "bino.inc",
"client_addr": "0.0.0.0",
"node_name": "node01"
}</p>
<p>run with /usr/bin/consul agent -config-dir=/etc/consul.d/</p>
<p>Test with dig @127.0.0.1 -p 8600 node01.node.bino.inc and got
;; ANSWER SECTION:
node01.node.bino.inc. 0 IN A 192.168.1.5</p>
<p>I just make a copy of example from <a href="https://github.com/vsudilov/flask-consulate" rel="nofollow noreferrer">https://github.com/vsudilov/flask-consulate</a>
make a small change to it :</p>
<pre><code># Register Consul service:
consul.register_service(
address='127.0.0.1',
name='webapp',
interval='10s',
tags=['master', ],
port=5000,
httpcheck='http://localhost:5000/healthcheck'
)
</code></pre>
<p>consul.app.run(port=5000, threaded = False, debug=True)</p>
<p>Looks like consul and flask script communicating each other.
flask debug got :</p>
<blockquote>
<p>127.0.0.1 - - [15/Nov/2018 08:38:27] "GET /healthcheck HTTP/1.1" 200 -</p>
</blockquote>
<p>My question is the FQDN of my flask script that consul will generate ?</p>
<p>I tried </p>
<blockquote>
<p>dig @127.0.0.1 -p 8600 webapp.bino.inc</p>
</blockquote>
<p>, and consul debug said : </p>
<blockquote>
<p>2018/11/15 08:41:29 [WARN] dns: QName invalid: webapp.</p>
</blockquote>
<p>Tried with </p>
<blockquote>
<p>dig @127.0.0.1 -p 8600 webserver.bino.inc</p>
</blockquote>
<p>, consul debug said : </p>
<blockquote>
<p>2018/11/15 08:43:37 [WARN] dns: QName invalid: webserver.</p>
</blockquote>
<p>Sincerely
-bino-</p>
|
<p>Querying registered services in Consul via DNS interface requires specific structure of the service FQDN as described in this link for standard lookups (<a href="https://www.consul.io/docs/agent/dns.html#standard-lookup" rel="nofollow noreferrer">Conusl DNS stadard lookup</a>)</p>
<p>FQDN of the service registered with Consul must be in the form:</p>
<pre><code><service>.service[.datacenter].<domain>
</code></pre>
<p>where <code><service></code> is the name of your service registered with Consul, in your case <code>webapp</code> or <code>webserver</code>. The <code><domain></code> is consul domain as defined in your <code>consul.json</code>. <code>[datacenter]</code> is optional, and Consul server will return services for the datacenter to which it belongs. Since you haven't defined it in <code>consul.json</code> it's <code>dc1</code>.</p>
<p>So your <code>dig</code> query should look like this:</p>
<pre><code>dig @127.0.0.1 -p 8600 webapp.service.bino.inc
</code></pre>
<p>or</p>
<pre><code>dig @127.0.0.1 -p 8600 webserver.service.bino.inc
</code></pre>
<p>Optionally you can try adding datacenter to FQDN. Your <code>dig</code> query should look like this, and should return same response as those above as you are running single DC single node Consul cluster:</p>
<pre><code>dig @127.0.0.1 -p 8600 webserver.service.dc1.bino.inc
</code></pre>
<p>I hope this helps solve your problem.</p>
|
python|flask|consul
| 2 |
1,903,372 | 53,319,089 |
How can I pass parameters to a fixture and use this fixture in a test method?
|
<p>I want to pass username, password and email as fixture parameters here:</p>
<pre><code>@pytest.fixture()
def create_user(self):
try:
assert self.rbac.put_user(username, password, email).status_code == 200
yield
except AssertionError:
assert self.rbac.get_user(username).status_code == 200
yield
finally:
assert self.rbac.delete_user(username).status_code == 200
</code></pre>
<p>Later I will use this fixture in my test:</p>
<pre><code>@pytest.mark.usefixtures("create_user")
def test_assign_delete_user_to_group(self):
"""some code"""
</code></pre>
<p>How can I do that? Thanks!</p>
|
<p>Try a factory fixture:</p>
<pre><code>@pytest.fixture()
def user_factory(self, request):
created_users = []
def create_or_get_user(username):
try:
assert self.rbac.put_user(username, password, email).status_code == 200
except AssertionError:
assert self.rbac.get_user(username).status_code == 200
created_users.append(username)
yield create_or_get_user
for username in created_users:
assert self.rbac.delete_user(username).status_code == 200
</code></pre>
<p>Then use it with</p>
<pre><code>def test_assign_delete_user_to_group(self, user_factory):
"""some code"""
u = user_factory('foo')
assert u
</code></pre>
|
python|automation|pytest
| 0 |
1,903,373 | 71,805,671 |
How to copy file from one path to another if path exist only
|
<p>I am searching over internet but not getting</p>
<p>if my source and destination path exist then only copy
source file : abc.csv to destination path</p>
<pre><code>import shutil
shutil.copyfile("/demo/abc.csv" "/dummy/")
</code></pre>
<p>If destination path does not exist it is creating I don't want it to happen</p>
<p>if both path exist then only copy abc.csv from one path to another path</p>
|
<p>My interpretation of this question is that the source is a file and the target is a directory and furthermore that the copy should only be attempted if the source exists (as a plain file) and the target exists (as a directory). If that's the case then:</p>
<pre><code>import os
import shutil
def safe_copy(source_file, target_directory):
if os.path.isfile(source_file) and os.path.isdir(target_directory):
shutil.copyfile(source_file, os.path.join(target_directory, os.path.basename(source_file)))
</code></pre>
<p>Given a source file /home/test.txt and a target directory /foo then if /home/test.txt exists and /foo is an existing directory then the copy will take place (if permitted) resulting in /foo/test.txt either being created or overwritten</p>
|
python|shutil
| 2 |
1,903,374 | 68,482,073 |
Pandas - Keep the first n characters where n is defined in the column N
|
<p>I have a DataFrame from a source where the names are repeated back to back without a delimiter to split upon.</p>
<p>Example:</p>
<pre><code>In [1]
data = {"Names": ["JakeJake", "ThomasThomas", "HarryHarry"],
"Scores": [70, 81, 23]}
df = pd.DataFrame(data)
Out [1]
Names Scores
0 JakeJake 70
1 ThomasThomas 81
2 HarryHarry 23
</code></pre>
<p>I would like a method to keep just the first half of the 'Names' column. My initial thought was to do the following:</p>
<pre><code>In [2]
df["N"] = df["Names"].str.len()//2
df["X"] = df["Names"].str[:df["N"]]
</code></pre>
<p>However this gives the output</p>
<pre><code>Out [2]
Names Scores N X
0 JakeJake 70 4 nan
1 ThomasThomas 81 6 nan
2 HarryHarry 23 5 nan
</code></pre>
<p>The desired output would be</p>
<pre><code>Out [2]
Names Scores N X
0 JakeJake 70 4 Jake
1 ThomasThomas 81 6 Thomas
2 HarryHarry 23 5 Harry
</code></pre>
<p>I'm sure the answer will be something simple but I can't get my head around it. Cheers</p>
|
<p>With a <a href="https://regex101.com/r/QXxYko/1" rel="nofollow noreferrer">regex</a> to extract names and <code>str.len</code> for the lengths:</p>
<pre><code>df["X"] = df.Names.str.extract(r"^(.+)\1$")
df["N"] = df.X.str.len()
</code></pre>
<p>where regex looks for a fullmatch of anything repeated 2 times (<code>\1</code> refers to the first capturing group within the regex).</p>
<pre><code>>>> df
Names Scores X N
0 JakeJake 70 Jake 4
1 ThomasThomas 81 Thomas 6
2 HarryHarry 23 Harry 5
</code></pre>
|
python|pandas|dataframe|split|delimiter
| 2 |
1,903,375 | 68,518,600 |
Add a title to a dataframe
|
<p>I originally had a dataframe <code>df1</code>,</p>
<pre><code> Close
ticker AAPL AMD BIDU GOOGL IXIC
Date
2011-06-01 12.339643 8.370000 132.470001 263.063049 2769.189941
2011-06-02 12.360714 8.240000 138.490005 264.294281 2773.310059
2011-06-03 12.265714 7.970000 133.210007 261.801788 2732.780029
2011-06-06 12.072857 7.800000 126.970001 260.790802 2702.560059
2011-06-07 11.858571 7.710000 124.820000 259.774780 2701.560059
... ... ... ... ... ...
2021-05-24 127.099998 77.440002 188.960007 2361.040039 13661.169922
2021-05-25 126.900002 77.860001 192.770004 2362.870117 13657.169922
2021-05-26 126.849998 78.339996 194.880005 2380.310059 13738.000000
2021-05-27 125.279999 78.419998 194.809998 2362.679932 13736.280273
2021-05-28 124.610001 80.080002 196.270004 2356.850098 13748.740234
</code></pre>
<p>Due to the need for calculation, I changed the columns and created <code>df2</code>, which contains no <code>Close</code>,</p>
<pre><code>ticker AAPL AMD BIDU GOOGL IXIC
Date
2011-08-25 0.760119 0.028203 0.621415 0.036067 0.993046
2011-09-23 0.648490 0.216017 0.267167 0.699657 0.562897
2011-10-21 0.442864 0.326310 0.197121 0.399332 0.048258
2011-11-18 0.333015 0.062089 0.164588 0.373293 0.015258
2011-12-19 0.101208 0.389120 0.218844 0.094759 0.116979
... ... ... ... ... ...
2021-01-12 0.437177 0.012871 0.997870 0.075802 0.137392
2021-02-10 0.064343 0.178901 0.522356 0.625447 0.320007
2021-03-11 0.135033 0.300345 0.630085 0.253857 0.466884
2021-04-09 0.358583 0.484004 0.295894 0.215424 0.454395
2021-05-07 0.124987 0.311816 0.999940 0.232552 0.281189
</code></pre>
<p>And now I am struggling on how to add a name to the dataframe again, say <code>ret</code>, because I would like to plot the histogram of each column, and would like the titles to be something like <code>('ret', 'AAPL')</code>...</p>
<p>This may be a bit stupid and confusing, hopefully I have explained the question clearly. Thanks for any help.</p>
|
<p>you can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.MultiIndex.from_product.html" rel="nofollow noreferrer"><code>pd.MultiIndex.from_product()</code></a> method:</p>
<pre><code>df2=df2.set_index('Date')
#If 'Date' column is not your Index then make it index
df2.columns=pd.MultiIndex.from_product([['ret'],df2.columns])
</code></pre>
|
pandas|dataframe|plot|indexing|rename
| 0 |
1,903,376 | 10,614,066 |
show a drop down list from 2 dimensional tuple
|
<p>I have a list of countries in a file as follows,</p>
<pre><code>COUNTRIES = (
('AF', 'Afghanistan'),
('AX', '\xc5land Islands'),
('AL', 'Albania'),...
</code></pre>
<p>I would like to display only the full names of countries in my drop down list and also save only the full name in the model. </p>
<p>Right now my models.py is</p>
<pre><code>class UserProfiles(models.Model):
location = models.CharField(max_length=60, blank=True, null=True)
</code></pre>
<p>and forms.py is</p>
<pre><code>class UserProfileForm(ModelForm):
location = forms.ChoiceField(choices=COUNTRIES)
</code></pre>
|
<p>Adjust the COUNTRIES list like this</p>
<pre><code>COUNTRIES = [ (long, long) for short, long in COUNTRIES ]
</code></pre>
<p>Then use this in your model</p>
<pre><code>class UserProfiles(models.Model):
location = models.CharField(max_length=60, blank=True, null=True, choices=COUNTRIES)
</code></pre>
<p>The form should be OK as it is</p>
|
python|django
| 0 |
1,903,377 | 5,173,343 |
override Django get_or_create
|
<p>I have a model that I overrode the <code>save</code> method for, so that the <code>save</code> method can be passed in some data and auto-fill-in a field before saving. Here is my model:</p>
<pre><code>class AccountModel(models.Model):
account = models.ForeignKey(Account)
def save(self, request=None, *args, **kwargs):
if request:
self.account = request.session['account']
super(AccountModel, self).save(*args, **kwargs)
class Meta:
abstract = True
</code></pre>
<p>The idea is I set up a base model for objects that need to be associated with an account and then I won't have to deal with the account connections every time they come up (which is a lot). </p>
<p>But: I'd also like to use <code>get_or_create</code>, which saves the new objects without passing in the request. I know it is doable to not use <code>get_or_create</code> and do a <code>try</code>/<code>except</code> instead, but I'd like to know <strong>if there is a way to override <code>get_or_create</code> and what is the proper way to do it</strong>.</p>
<p>I looked at the code for the <code>Manager</code> (which I am looking at overriding) and the <code>get_or_create</code> function just calls a <code>QuerySet.get_or_create</code> function. Maybe I can write it to use other manager functions and not the <code>QuerySet</code> version of <code>get_or_create</code>?
What do y'all think?</p>
|
<p>You could subclass <code>django.db.models.query.QuerySet</code> and override the <code>get_or_create</code> method there to accept your <code>request</code> keyword argument and pass it onto <code>save</code> I guess, but it isn't very pretty.</p>
<pre><code>class AccountQuerySet(models.query.QuerySet):
def get_or_create(...):
...
</code></pre>
<p>You could then add a custom manager to your <code>Account</code> model which uses this custom <code>QuerySet</code>:</p>
<pre><code>class AccountManager(models.Manager):
def get_queryset(self):
return AccountQuerySet(self.model)
</code></pre>
<p>Then use this manager in your model:</p>
<pre><code>class Account(models.Model):
...
objects = AccountManager()
</code></pre>
<p>But you might find that the <code>try-except</code> method is neater after all :)</p>
|
python|django|django-models|subclass|django-managers
| 19 |
1,903,378 | 62,651,532 |
PDF to Image and downloading it to a specific folder using Wand Python
|
<p>I am trying to convert all the pages of a PDF to images and save them to a specific working directory.
The code is:</p>
<pre><code>from wand.image import Image
from wand.image import Image as wi
pdf = wi(filename="work.pdf", resolution=300)
pdfimage = pdf.convert("jpeg")
i=1
for img in pdfimage.sequence:
page = wi(image=img)
page.save(filename=r"C:\Users\...\work" + str(i) + ".jpg")
i +=1
</code></pre>
<p>As you can see, I am converting each page to jpg format and then am trying to save them in the folder. But due to some reason, it is not working.
If instead of the second last line, I try:</p>
<pre><code>from wand.image import Image as wi
pdf = wi(filename="work.pdf", resolution=300)
pdfimage = pdf.convert("jpeg")
i=1
for img in pdfimage.sequence:
page = wi(image=img)
#page.save(filename=r"C:\Users\...\work" + str(i) + ".jpg")
page.save(filename=str(i)+".jpg")
i +=1
</code></pre>
<p>then it saves successfully but in the folder C:\Users\Me.
How can I save them in the working directory?</p>
|
<p>Try this...</p>
<pre class="lang-py prettyprint-override"><code>import os
from wand.image import Image as wi
with wi(filename="work.pdf", resolution=300) as pdf:
pdf.scene = 1
pdf.save(filename=os.path.join(os.getcwd(),"work%02d.jpg")
</code></pre>
<p>Wand should also support <a href="https://docs.python.org/3/library/pathlib.html#module-pathlib" rel="nofollow noreferrer">pathlib</a>, or other classes that implement <code>__fspath__()</code> itereface.</p>
|
python|wand
| 0 |
1,903,379 | 61,686,415 |
Python - cumulative sum until sum matches an exact number
|
<p>I have a column of numbers in a Python Pandas df: 1,8,4,3,1,5,1,4,2
If I create a cumulative sum column it returns the cumulative sum. How do I only return the rows that reaches a cumulative sum of 20 skipping numbers that take cumulative sum over 20?</p>
<pre><code>+-----+-------+------+
| Var | total | cumu |
+-----+-------+------+
| a | 1 | 1 |
| b | 8 | 9 |
| c | 4 | 13 |
| d | 3 | 16 |
| e | 1 | 17 |
| f | 5 | 22 |
| g | 1 | 23 |
| h | 4 | 27 |
| i | 2 | 29 |
+-----+-------+------+
</code></pre>
<p>Desired output:</p>
<pre><code>+-----+-------+------+
| Var | total | cumu |
+-----+-------+------+
| a | 1 | 1 |
| b | 8 | 9 |
| c | 4 | 13 |
| d | 3 | 16 |
| e | 1 | 17 |
| g | 1 | 18 |
| i | 2 | 20 |
+-----+-------+------+
</code></pre>
|
<p>If I understood your question correctly, you want only skip values that get you over cumulative sum of <code>20</code>:</p>
<pre><code>def acc(total):
s, rv = 0, []
for v, t in zip(total.index, total):
if s + t <= 20:
s += t
rv.append(v)
return rv
df = df[df.index.isin(acc(df.total))]
df['cumu'] = df.total.cumsum()
print(df)
</code></pre>
<p>Prints:</p>
<pre><code> Var total cumu
0 a 1 1
1 b 8 9
2 c 4 13
3 d 3 16
4 e 1 17
6 g 1 18
8 i 2 20
</code></pre>
|
python|pandas
| 1 |
1,903,380 | 67,492,573 |
Discord - Screenshot Embed Messages
|
<p>What I'm trying to acheive here is:</p>
<p>I want to create a Discord Bot that will find Embeded messages sent in a particular channel, and Screenshot them.</p>
<p><a href="https://i.stack.imgur.com/h4m0q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h4m0q.png" alt="enter image description here" /></a></p>
<p>I'm not really sure of any good way to do this. The only way I've been doing it now is by manually screenshotting them 1 by 1.</p>
<p>Anyone know of any way to do this automatically? Perheaps using Selenium/Puppeteer or a Discord Bot in Python?</p>
|
<p>You can use the bot access you have to look through the channel history and find messages with embeds, and extract the contents of the embed. If you actually need pictures, then you will have to replicate the HTML markup of a Discord message. For this, you can reverse-engineer an embed generator webapp such as <a href="https://cog-creators.github.io/discord-embed-sandbox/" rel="nofollow noreferrer">this one</a> and implement its features in your Python code.</p>
<p>After that, you can put this HTML, along with the appropriate CSS, into Selenium, and <a href="https://stackoverflow.com/a/6282203/5936187">take a screenshot</a> of the new page containing only the embed.</p>
|
python|node.js|discord|discord.js|discord.py
| 0 |
1,903,381 | 67,280,459 |
How to print row(s) if they meet a certain range
|
<p>I have two mega files that look like below:</p>
<p>f1:</p>
<pre><code>chr1,3073253,3074322,gene_id,"ENSMUSG00000102693.1",gene_type,"TEC"
chr1,3074253,3075322,gene_id,"ENSMUSG00000102693.1",transcript_id,"ENSMUST00000193812.1"
chr1,3077253,3078322,gene_id,"ENSMUSG00000102693.1",transcript_id,"ENSMUST00000193812.1"
chr1,3102916,3103025,gene_id,"ENSMUSG00000064842.1",gene_type,"snRNA"
chr1,3105016,3106025,gene_id,"ENSMUSG00000064842.1",transcript_id,"ENSMUST00000082908.1"
</code></pre>
<p>f2:</p>
<pre><code>chr,name,start,end
chr1,linc1320,3073300,3074300
chr3,linc2245,3077270,3078250
chr1,linc8956,4410501,4406025
</code></pre>
<p>What I want to do is to print the rows of file 2 in a separate column in file 1 IF the range of <code>start</code> and <code>end</code> column of file2 is inside the ranges in file1 (columns 2 and 3) and <code>chr</code> is the same. So based on the dummy example files I provided - the desired output should be (only the range of <code>linc1320</code> is in the first row of the file1):</p>
<pre><code>chr1,3073253,3074322,gene_id,"ENSMUSG00000102693.1",gene_type,"TEC",linc1320,3073300,3074300
chr1,3074253,3075322,gene_id,"ENSMUSG00000102693.1",transcript_id,"ENSMUST00000193812.1"
chr1,3077253,3078322,gene_id,"ENSMUSG00000102693.1",transcript_id,"ENSMUST00000193812.1"
chr1,3102916,3103025,gene_id,"ENSMUSG00000064842.1",gene_type,"snRNA"
chr1,3105016,3106025,gene_id,"ENSMUSG00000064842.1",transcript_id,"ENSMUST00000082908.1"
</code></pre>
<p>I am not a professional coder but I have been using this code to manually change the ranges based on the file2:</p>
<pre><code>awk -F ',' '$2<=3073300,$3>=3074300, {print $1,$2,$3,$4,$5,$6,$7}' f1.csv
</code></pre>
<p>I do not have a particular preference for using a specific programming language - both <code>Python</code> and <code>awk</code> would be very helpful. Any help is appreciated thank you.</p>
|
<p>You may use this <code>awk</code>:</p>
<pre class="lang-sh prettyprint-override"><code>awk 'BEGIN{FS=OFS=","} FNR==NR {if (FNR>1) {chr[++n] = $1; id[n]=$2; r1[n]=$3; r2[n]=$4}; next} {for (i=1; i<=n; ++i) if ($1 == chr[i] && r1[i] > $2 && r2[i] < $3) {$0 = $0 OFS id[i] OFS r1[i] OFS r2[i]; break}} 1' file2 file1
chr1,3073253,3074322,gene_id,"ENSMUSG00000102693.1",gene_type,"TEC",linc1320,3073300,3074300
chr1,3074253,3075322,gene_id,"ENSMUSG00000102693.1",transcript_id,"ENSMUST00000193812.1"
chr1,3077253,3078322,gene_id,"ENSMUSG00000102693.1",transcript_id,"ENSMUST00000193812.1"
chr1,3102916,3103025,gene_id,"ENSMUSG00000064842.1",gene_type,"snRNA"
chr1,3105016,3106025,gene_id,"ENSMUSG00000064842.1",transcript_id,"ENSMUST00000082908.1"
</code></pre>
<p>A more readable form:</p>
<pre class="lang-sh prettyprint-override"><code>awk '
BEGIN { FS = OFS = "," }
FNR == NR {
if (FNR > 1) {
chr[++n] = $1
id[n] = $2
r1[n] = $3
r2[n] = $4
}
next
}
{
for (i=1; i<=n; ++i)
if ($1 == chr[i] && r1[i] > $2 && r2[i] < $3) {
$0 = $0 OFS id[i] OFS r1[i] OFS r2[i]
break
}
} 1' file2 file1
</code></pre>
|
python|pandas|awk
| 5 |
1,903,382 | 60,406,742 |
Selenium WebDriver - Unable to locate Element?
|
<p>Code</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chrome = webdriver.Chrome(executable_path= 'C:\webdriver.exe\chromedriver.exe',port=9515)
url = 'https://protonmail.com/'
chrome.get(url)
chrome.implicitly_wait(10)
chrome.find_element_by_xpath('//*[@class="btn btn-default btn-short"]').click()
chrome.find_element_by_class_name("panel-heading").click()
chrome.find_element_by_id("freePlan").click()
chrome.find_element_by_id('username')
chrome.find_element_by_id("password").send_keys('password')
chrome.find_element_by_id("passwordc").send_keys('password')
</code></pre>
<p>HTML</p>
<pre><code><input placeholder="Choose username" required="" name="username" messages="[object Object]" iframename="top" pattern=".{1,40}" id="username" class="input">
</code></pre>
<p>Problem </p>
<pre><code>chrome.find_element_by_id('username')
</code></pre>
<p>I am trying to be able to input a username; however, python says it cannot find the element even though I am using the id it gives you which is username</p>
|
<p>Hi I just modified your code and now it works-:</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
chrome = webdriver.Chrome(executable_path= 'C:\webdriver.exe\chromedriver.exe',port=9515)
url = 'https://protonmail.com/'
chrome.get(url)
chrome.implicitly_wait(10)
chrome.find_element_by_xpath('//*[@class="btn btn-default btn-short"]').click()
chrome.find_element_by_class_name("panel-heading").click()
chrome.find_element_by_id("freePlan").click()
time.sleep(10)
#chrome.find_element_by_xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "top", " " ))]')
chrome.switch_to.frame(chrome.find_element_by_xpath('//*[contains(concat( " ", @class, " " ), concat( " ", "top", " " ))]'))
typeinput = chrome.find_element_by_xpath('//*[@id="username"]')
typeinput.click()
typeinput.clear()
typeinput.send_keys('password')
chrome.switch_to.default_content()
chrome.find_element_by_id("password").send_keys('password')
chrome.find_element_by_id("passwordc").send_keys('password')
</code></pre>
|
python|selenium|google-chrome|selenium-webdriver
| 1 |
1,903,383 | 60,589,052 |
how to add two numbers with this python code
|
<p>//Function prototype:</p>
<p>int solveMeFirst(int a, int b);</p>
<p>where,</p>
<p>a is the first integer input.
b is the second integer input
Return values</p>
<p>sum of the above two integers//</p>
<pre><code>def solveMeFirst(a,b):
return a+b
num1 = int(input(2))
num2 = int(input(3))
res = solveMeFirst(num1,num2)
print(res)
</code></pre>
|
<p>Problem in input(). Which takes user input.</p>
<pre><code>def solveMeFirst(a,b):
return a+b
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
res = solveMeFirst(num1,num2)
print(res)
</code></pre>
|
python|python-3.x
| 3 |
1,903,384 | 71,140,163 |
SQLALCHEMY/FASTAPI/POSTGRESQL | Only retrieve double entries
|
<p>I have a database with a table named <code>friends</code>. That table has two columns, <code>"user_id" and "friend_id"</code>.
Those are foreign keys from the <code>Users</code> table.</p>
<p>My friends table right now:</p>
<pre><code> user_id | friend_id
-------------------------------------+-------------------------------------
google-oauth2|11539665289********** | google-oauth2|11746442253**********
google-oauth2|11746442253********** | google-oauth2|11539665289**********
google-oauth2|11746442253********** | google-oauth2|11111111111**********
</code></pre>
<p>The first two rows are the same IDs but flipped. Those <code>Users</code> I want to retrieve, because they added eachother. The third row only added another guy, that one shouldn't be retrieved.</p>
<p>My SQLModels (models.py):</p>
<pre><code>class Friends(SQLModel, table=True):
__tablename__ = "friends"
user_id: str = Field(sa_column=Column('user_id', VARCHAR(length=50), primary_key=True), foreign_key="users.id")
friend_id: str = Field(sa_column=Column('friend_id', VARCHAR(length=50), primary_key=True), foreign_key="users.id")
class UserBase(SQLModel):
id: str
username: Optional[str]
country_code: Optional[str]
phone: Optional[str]
picture: Optional[str]
class Config:
allow_population_by_field_name = True
class User(UserBase, table=True):
__tablename__ = 'users'
id: str = Field(primary_key=True)
username: Optional[str] = Field(sa_column=Column('username', VARCHAR(length=50), unique=True, default=None))
phone: Optional[str] = Field(sa_column=Column('phone', VARCHAR(length=20), unique=True, default=None))
picture: Optional[str] = Field(sa_column=Column('picture', VARCHAR(length=255), default=None))
</code></pre>
<p>My fastapi endpoint:</p>
<pre><code>@router.get("", status_code=status.HTTP_200_OK, response_model=models.FriendsList, name="Get Friends for ID",
tags=["friends"])
async def get_friends(
user_id: str = Query(default=None, description="The user_id that you want to retrieve friends for"),
session: Session = Depends(get_session)
):
stm = select(models.User, models.Friends).where(models.User.id == models.Friends.friend_id, models.Friends.user_id == user_id)
res = session.exec(stm).all()
if not res:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
detail="There are no friendships associated with this id.")
users = []
for item in res:
users.append(item[0])
return models.FriendsList(users=users)
</code></pre>
<p>My code works perfectly fine, only the query needs to be replaced.</p>
<pre><code>stm = select(models.User, models.Friends).where(models.User.id == models.Friends.friend_id, models.Friends.user_id == user_id)
res = session.exec(stm).all()
</code></pre>
<p>This query returns every <code>User</code> that has the given ID as <code>user_id</code>, but doesn't check if there is an entry the other way around.</p>
<p>Example for what I want to get:</p>
<p>I make a GET request to my endpoint with the id <code>google-oauth2|11746442253**********</code>. I would get the User <code>google-oauth2|11539665289**********</code>. (The User <code>google-oauth2|11111111111**********</code> would not be retrieved because there is no entry the other way arround)</p>
<p>I hope you guys understand my problem. If there are any questions feel free to ask.</p>
<p>Best regards,
Colin</p>
|
<p>As I said in the comment, without a simple example I can't actually try myself, but I did just have an idea. You might need to modify the subquery syntax a little bit, but I reckon theoretically this could work:</p>
<pre><code>stmt = select(Friends.user_id, Friends.friend_id).where(
tuple_(Friends.user_id, Friends.friend_id).in_(select(Friends.friend_id, Friends.user_id))
)
</code></pre>
<p>Basically it's just checking every <code>(user_id, friend_id)</code> if there is a matching <code>(friend_id, user_id)</code>.</p>
|
python|postgresql|sqlalchemy|fastapi
| 0 |
1,903,385 | 71,133,888 |
How to round to 2 decimals?
|
<p>I'm trying to round (d) with 2 decimals but i can't figure it out</p>
<pre><code>if (c == "qc") or (c == "QC"):
print("\nLe coût de l'objet que tu veut acheter est", a, "et ton budget est", b)
blockPrint()
d = input(a * g)
enablePrint()
print("le coût avec la tax est", d)
if d > b:
print("ton budget de", b, "est trop petit")
else:
print("tu as assé d'argent pour acheter ce que tu veux")
</code></pre>
|
<p>To round you can use <code>round(d, 2)</code>.</p>
<ul>
<li>d is the var</li>
<li>2 is the 2nd decimal place</li>
</ul>
|
python
| 0 |
1,903,386 | 70,239,073 |
How to plot the values of a groupby on multiple columns
|
<p>I have a dataset similar to the following:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
data = {'Country': ['Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK', 'Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK', 'Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK'],
'Date': ['Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020'],
'Sales': [20000, 30000, 10000, 10000, 30000, 10000, 10000, 50000, 40000, 30000, 20000, 30000, 10000, 10000, 60000, 70000, 80000, 10000, 30000, 10000, 10000]}
df = pd.DataFrame(data)
Country Date Sales
0 Spain Jan 2020 20000
1 Italy Jan 2020 30000
2 France Jan 2020 10000
3 Germany Jan 2020 10000
4 Portugal Jan 2020 30000
5 Greece Jan 2020 10000
6 UK Jan 2020 10000
7 Spain Feb 2020 50000
8 Italy Feb 2020 40000
9 France Feb 2020 30000
10 Germany Feb 2020 20000
11 Portugal Feb 2020 30000
12 Greece Feb 2020 10000
13 UK Feb 2020 10000
14 Spain Dec 2020 60000
15 Italy Dec 2020 70000
16 France Dec 2020 80000
17 Germany Dec 2020 10000
18 Portugal Dec 2020 30000
19 Greece Dec 2020 10000
20 UK Dec 2020 10000
</code></pre>
<p>I would like to visualize how the Sales varied over the year by Country therefore I would like to show 7 histograms (one for each Country). For each plot, the 'Date' will be on the x-axis and the 'Sales' values on the y-axis. Also, a title to identify the Country is required as well as the x-label, y-label.</p>
<p>I have tried several options found in previous discussions but none of those works with what I want to achieve. I have tried the following:</p>
<pre><code>df.groupby('Country').hist(column='Sales', grid= False, figsize=(2,2))
</code></pre>
<pre><code>df['Sales'].hist(grid=True, by=one_year_df['Country'])
</code></pre>
<pre><code>df.groupby('Country').hist(grid= False, figsize=(2,2))
</code></pre>
<pre><code>df.reset_index().pivot('index','Country','Sales').hist(grid=False, bins=12)
</code></pre>
<pre><code>grouped = df.groupby('Country')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,12), sharey=False)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
</code></pre>
<p>However, none of these options gives me the possibility to set the 'Date' column, also it seems that it is not possible to set the x-axis, y-axis as I wish and as a result, the plots are meaningless.</p>
<p>I have also found another piece of code that seems to consider all the variables but the result still is not as expected:</p>
<pre><code>fig, ax = plt.subplots(figsize=(15,7))
df.groupby(['Country']).sum()['Sales'].plot(ax=ax)
ax.set_xlabel('Date')
ax.set_ylabel('Sales')
</code></pre>
<p>Any comments or suggestions are welcome. Thank you.</p>
|
<ul>
<li><em>For each plot, the 'Date' will be on the x-axis and the 'Sales' values on the y-axis.</em> is best shown with a line or bar plot. A histogram is essentially a bar plot (in terms of a visulization).</li>
<li>Convert the <code>'Date'</code> column to datetime with <a href="https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html" rel="nofollow noreferrer"><code>pd.to_datetime</code></a></li>
<li>Reshape the dataframe with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pivot_table.html" rel="nofollow noreferrer"><code>pivot_table</code></a> and <code>aggfun='sum'</code></li>
<li>Plot with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.html" rel="nofollow noreferrer"><code>pandas.DataFrame.plot</code></a>, which uses <code>matplotlib</code> as the default plotting backend
<ul>
<li>See <a href="https://stackoverflow.com/q/11927715/7758804">How to give a pandas/matplotlib bar graph custom colors</a> to specify different colors for the lines or bars.</li>
<li><a href="https://matplotlib.org/stable/gallery/color/named_colors.html" rel="nofollow noreferrer">List of named colors</a></li>
<li><a href="https://matplotlib.org/stable/tutorials/colors/colormaps.html" rel="nofollow noreferrer">Choosing Colormaps</a></li>
</ul>
</li>
<li>See this <a href="https://stackoverflow.com/a/70137133/7758804">answer</a> to improve subplot size/spacing with many subplots, if necessary.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import matplotlib.pyplot as plt
# convert the column to a datetime dtype
df.Date = pd.to_datetime(df.Date).dt.date
# reshape the dataframe
dfp = df.pivot_table(index='Date', columns='Country', values='Sales', aggfunc='sum')
# plot
ax = dfp.plot(figsize=(8, 5))
ax.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
</code></pre>
<p><a href="https://i.stack.imgur.com/8KFW0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8KFW0.png" alt="enter image description here" /></a></p>
<ul>
<li>If you plot a bar plot, there will be a crowded mess, because there will be a bar for each row of data.</li>
</ul>
<pre class="lang-py prettyprint-override"><code>ax = dfp.plot(kind='bar', subplots=True, figsize=(14, 12), layout=(2, 4), rot=0, legend=False)
</code></pre>
<p><a href="https://i.stack.imgur.com/GHWFg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GHWFg.png" alt="enter image description here" /></a></p>
|
python|pandas|matplotlib|plot|bar-chart
| 0 |
1,903,387 | 63,528,163 |
Writing the output to a different csv file column
|
<p>I have some vocabulary and their counterparts to create an Anki deck. I need the program to write the output of my code in two columns of a csv file; first for the vocabulary and second for the meaning. I've tried two codes but neither of them worked. How can I solve this problem?</p>
<p>Notebook content(vocab):</p>
<pre><code>obligatory,義務的
sole,単独,唯一
defined,一定
obey,従う
...
</code></pre>
<p>First try:</p>
<pre class="lang-py prettyprint-override"><code>with open("C:/Users/berka/Desktop/Vocab.txt") as csv_file:
csv_reader = csv.reader(csv_file)
with open("C:/Users/berka/Desktop/v.csv", "w", newline="") as new_file:
csv_writer = csv.writer(new_file, delimiter=",")
for line in csv_reader:
csv_writer.writerow(line)
</code></pre>
<p>Second try:</p>
<pre class="lang-py prettyprint-override"><code>with open("C:/Users/berka/Desktop/Vocab.txt") as csv_file:
csv_reader = csv.DictReader(csv_file)
with open("C:/Users/berka/Desktop/v.csv", "w",) as f:
field_names = ["Vocabulary", "Meaning"]
csv_writer = csv.DictWriter(f, fieldnames=field_names, extrasaction="ignore")
csv_writer.writeheader()
for line in csv_reader:
csv_writer.writerow(line)
</code></pre>
<p>Result of the first try:
<a href="https://i.stack.imgur.com/U29lG.png" rel="nofollow noreferrer">https://cdn.discordapp.com/attachments/696432733882155138/746404430123106374/unknown.png</a></p>
<p>#Second try was not even close</p>
<p>Expected result:
<a href="https://i.stack.imgur.com/h4a3F.png" rel="nofollow noreferrer">https://cdn.discordapp.com/attachments/734460259560849542/746432094825087086/unknown.png</a></p>
|
<p>Like Kevin said, Excel uses "<strong>;</strong>" as delimiter and your csv code creates a csv file with comma(,) delimiter. That's why it's shown with commas in your Csv Reader. You can pass "<strong>;</strong>" as delimiter if you want Excel to read your file correctly. Or you can create a csv file with your own Csv Reader and read it with notepad if you want to see which delimiter it uses.</p>
|
python|csv
| 1 |
1,903,388 | 55,979,980 |
Failed to load resource: the server responded with a status of 429 (Too Many Requests) and 404 (Not Found) with ChromeDriver Chrome through Selenium
|
<p>I am trying to build a scraper using selenium in python. Selenium webdriver opening window and trying to load the page but suddenly stop loading. I can access the same link in my local chrome browser.</p>
<p>Here are the error logs I'm getting from the webdriver:</p>
<pre><code>{'level': 'SEVERE', 'message': 'https://shop.coles.com.au/a/a-nsw-metro-rouse-hill/everything/browse/baby/nappies-changing?pageNumber=1 - Failed to load resource: the server responded with a status of 429 (Too Many Requests)', 'source': 'network', 'timestamp': 1556997743637}
{'level': 'SEVERE', 'message': 'about:blank - Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME', 'source': 'network', 'timestamp': 1556997745338}
{'level': 'SEVERE', 'message': 'https://shop.coles.com.au/149e9513-01fa-4fb0-aad4-566afd725d1b/2d206a39-8ed7-437e-a3be-862e0f06eea3/fingerprint - Failed to load resource: the server responded with a status of 404 (Not Found)', 'source': 'network', 'timestamp': 1556997748339}
</code></pre>
<p>My script:</p>
<pre><code>from selenium import webdriver
import os
path = os.path.join(os.getcwd(), 'chromedriver')
driver = webdriver.Chrome(executable_path=path)
links = [
"https://shop.coles.com.au/a/a-nsw-metro-rouse-hill/everything/browse/baby/nappies-changing?pageNumber=1",
"https://shop.coles.com.au/a/a-nsw-metro-rouse-hill/everything/browse/baby/baby-accessories?pageNumber=1",
"https://shop.coles.com.au/a/a-nsw-metro-rouse-hill/everything/browse/baby/food?pageNumber=1",
"https://shop.coles.com.au/a/a-nsw-metro-rouse-hill/everything/browse/baby/formula?pageNumber=1",
]
for link in links:
driver.get(link)
</code></pre>
|
<h2>429 Too Many Requests</h2>
<p>The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429" rel="nofollow noreferrer">429 Too Many Requests</a> response status code indicates that the user has sent too many requests in a given amount of time ("rate limiting"). The response representations SHOULD include details explaining the condition, and MAY include a <code>Retry-After</code> header indicating how long to wait before making a new request.</p>
<p>When a server is under attack or just receiving a very large number of requests from a single party, responding to each with a <strong><code>429</code></strong> status code will consume resources. Therefore, servers are not required to use the <code>429</code> status code; when limiting resource usage, it may be more appropriate to just drop connections, or take other steps.</p>
<hr>
<h2>404 Not Found</h2>
<p>The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404" rel="nofollow noreferrer">404 Not Found</a> client error response code indicates that the server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web.</p>
<p>A <code>404</code> status code does not indicate whether the resource is temporarily or permanently missing. But if a resource is permanently removed, a <code>410 (Gone)</code> should be used instead of a <code>404</code> status. Additionally, <code>404</code> status code is used when the requested resource is not found, whether it doesn't exist or if there was a <code>401</code> or <code>403</code> that, for security reasons, the service wants to mask.</p>
<hr>
<h2>Analysis</h2>
<p>When I tried your code block, I faced similar consequences. If you inspect the <a href="https://javascript.info/dom-nodes" rel="nofollow noreferrer">DOM Tree</a> of the <a href="https://shop.coles.com.au/a/a-nsw-metro-rouse-hill/everything/browse/baby/nappies-changing?pageNumber=1" rel="nofollow noreferrer">webpage</a> you will find that quite a few tags are having the keyword <strong>dist</strong>. As an example:</p>
<ul>
<li><code><link rel="shortcut icon" type="image/x-icon" href="/wcsstore/ColesResponsiveStorefrontAssetStore/dist/30e70cfc76bf73d384beffa80ba6cbee/img/favicon.ico"></code></li>
<li><code><link rel="stylesheet" href="/wcsstore/ColesResponsiveStorefrontAssetStore/dist/30e70cfc76bf73d384beffa80ba6cbee/css/google/fonts-Source-Sans-Pro.css" type="text/css" media="screen"></code></li>
<li><code>'appDir': '/wcsstore/ColesResponsiveStorefrontAssetStore/dist/30e70cfc76bf73d384beffa80ba6cbee/app'</code></li>
</ul>
<p>The presence of the term <strong>dist</strong> is a clear indication that the website is protected by <strong>Bot Management</strong> service provider <a href="https://www.distilnetworks.com/" rel="nofollow noreferrer"><strong>Distil Networks</strong></a> and the navigation by <em>ChromeDriver</em> gets detected and subsequently <strong>blocked</strong>.</p>
<hr>
<h2>Distil</h2>
<p>As per the article <a href="https://www.forbes.com/sites/timconneally/2013/01/28/theres-something-about-distil-it/#6e1881e438b9" rel="nofollow noreferrer">There Really Is Something About Distil.it...</a>:</p>
<blockquote>
<p>Distil protects sites against automatic content scraping bots by observing site behavior and identifying patterns peculiar to scrapers. When Distil identifies a malicious bot on one site, it creates a blacklisted behavioral profile that is deployed to all its customers. Something like a bot firewall, Distil detects patterns and reacts.</p>
</blockquote>
<p>Further,</p>
<blockquote>
<p><code>"One pattern with **Selenium** was automating the theft of Web content"</code>, Distil CEO Rami Essaid said in an interview last week. <code>"Even though they can create new bots, we figured out a way to identify Selenium the a tool they're using, so we're blocking Selenium no matter how many times they iterate on that bot. We're doing that now with Python and a lot of different technologies. Once we see a pattern emerge from one type of bot, then we work to reverse engineer the technology they use and identify it as malicious".</code></p>
</blockquote>
<hr>
<h2>Reference</h2>
<p>You can find a couple of detailed discussion in:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/53605757/unable-to-use-selenium-to-automate-chase-site-login/54284776#54284776">Unable to use Selenium to automate Chase site login</a></li>
<li><a href="https://stackoverflow.com/questions/52832413/chrome-browser-initiated-through-chromedriver-gets-detected/52833487#52833487">Chrome browser initiated through ChromeDriver gets detected</a></li>
</ul>
|
python-3.x|selenium|google-chrome|web-scraping|selenium-chromedriver
| 1 |
1,903,389 | 56,602,904 |
Why does transforming from Earth coordinates to galactocentric coordinates in astropy not preserve distances?
|
<p>I'm converting <code>GCRS</code> objects to galactocentric coordinates and finding that distances between two points are not preserved under this transformation.</p>
<pre class="lang-python prettyprint-override"><code>import astropy.units
import astropy.coordinates
import astropy.time
from numpy.linalg import norm
t = astropy.time.Time('1999-01-01T00:00:00.123456789')
def earth2galaxy(lat):
'''
Convert an Earth coordinate to a galactocentric coordinate.
'''
# get GCRS coordinates
earth = astropy.coordinates.EarthLocation(lat=lat*astropy.units.deg,
lon=0,
height=0)
pos, _ = earth.get_gcrs_posvel(obstime=t)
cartrep = astropy.coordinates.CartesianRepresentation(pos.xyz,
unit=astropy.units.m)
gcrs = astropy.coordinates.GCRS(cartrep)
# convert GCRS to galactocentric
gc = gcrs.transform_to(astropy.coordinates.Galactocentric)
return earth, gcrs, gc
earthA, gcrsA, gcA = earth2galaxy(0)
earthB, gcrsB, gcB = earth2galaxy(0.01)
print(norm(earthA-earthB))
print(norm(gcrsA.cartesian.xyz-gcrsB.cartesian.xyz))
print(norm(gcA.cartesian.xyz-gcB.cartesian.xyz))
</code></pre>
<p>This code gives</p>
<pre><code>1105.74275693
1105.74275232
971.796949054
</code></pre>
<p>I find that this isn't a problem for larger distances (e.g. latitude offsets in the 10s of degrees).</p>
<p>I was previously getting around this by -- given points <code>A</code> and <code>B</code> -- transforming points <code>A</code> and <code>C = A + c*AB</code>, where <code>c</code> is some large number. I would then recover the transformed <code>B'</code> by undoing this scaling <code>B' = A' + A'C' / c</code>. However, it feels like I should address the actual root of the problem instead of this workaround.</p>
|
<p>This may simply be a floating point precision problem. If I look at the cartesian values, <code>x</code>, <code>y</code> and <code>z</code> are of order <code>1e6</code>, <code>1e6</code> and <code>1e2</code> for the GCRS frame, but they are of order <code>1e20</code>, <code>1e10</code> and <code>1e17</code>, respectively, for the Galactic frame. </p>
<p>Given a precision of <code>1e-15</code> for 8 byte floating point numbers (<code>numpy.finfo('f8').eps</code>), that means the <code>x</code>-value of the Galactic coordinate can only be precise to about <code>1e5</code> (meters). Then taking the norm (with the <code>x</code>-value uncertainty dominating), would lead to an accuracy of order <code>1e5</code> meters as well, much more than the actual separation.</p>
<p>The fact that the calculated values are still close to each other is largely luck (though it'll have an underlying reason, such as deviations averaging out somewhat). </p>
<p>This also agrees with the fact that you don't see a problem (or less of a problem) for larger offsets. Though testing it myself, I still see difference, of order <code>1e4</code>~<code>1e5</code>). To be precise, using 0 and 10 latitude, I obtain:</p>
<pre><code>GCRS: 1104451.74511518
Galactic: 1108541.8206286128
</code></pre>
<p>If my assumption is correct, then my advice is simple: use the appropriate coordinate system for your coordinates, and take into account the relevant uncertainties (both machine precision and that of the coordinate system used). </p>
|
python|debugging|astropy
| 3 |
1,903,390 | 56,800,281 |
google cloud speech ImportError: cannot import name 'enums'
|
<p>I'm using google-cloud-speech api for my project . I'm using pipenv for virtual environment i installed google-cloud-speech api with </p>
<blockquote>
<p>pipenv install google-cloud-speech</p>
</blockquote>
<p>and</p>
<blockquote>
<p>pipenv update google-cloud-speech</p>
</blockquote>
<p>i followed this docs <a href="https://cloud.google.com/speech-to-text/docs/reference/libraries" rel="noreferrer">https://cloud.google.com/speech-to-text/docs/reference/libraries</a></p>
<p>This is my code:</p>
<p><strong>google.py:</strong></p>
<pre><code># !/usr/bin/env python
# coding: utf-8
import argparse
import io
import sys
import codecs
import datetime
import locale
import os
from google.cloud import speech_v1 as speech
from google.cloud.speech import enums
from google.cloud.speech import types
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.join("alt_speech_dev_01-fa5fec6806d9.json")
def get_model_by_language_id(language_id):
model = ''
if language_id == 1:
model = 'ja-JP'
elif language_id == 2:
model = 'en-US'
elif language_id == 3:
model = "zh-CN"
else:
raise ('Not Match Lang')
return model
def transcribe_gcs_without_speech_contexts(audio_file_path, model):
client = speech.SpeechClient()
with io.open(audio_file_path, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = {
"encoding": enums.RecognitionConfig.AudioEncoding.FLAC,
"sample_rate_hertz": 16000,
"languageCode": model
}
operation = client.long_running_recognize(config, audio)
print('Waiting for operation to complete...')
operationResult = operation.result()
ret=''
for result in operationResult.results:
for alternative in result.alternatives:
ret = alternative.transcript
return ret
def transcribe_gcs(audio_file_path, model, keywords=None):
client = speech.SpeechClient()
with io.open(audio_file_path, 'rb') as audio_file:
content = audio_file.read()
audio = types.RecognitionAudio(content=content)
config = {
"encoding": enums.RecognitionConfig.AudioEncoding.FLAC,
"sample_rate_hertz": 16000,
"languageCode": model,
"speech_contexts":[{"phrases":keywords}]
}
operation = client.long_running_recognize(config, audio)
print('Waiting for operation to complete...')
operationResult = operation.result()
ret=''
for result in operationResult.results:
for alternative in result.alternatives:
ret = alternative.transcript
return ret
transcribe_gcs_without_speech_contexts('alt_en.wav', get_model_by_language_id(2))
</code></pre>
<p>When i try to run the python file with </p>
<blockquote>
<p>python google.py</p>
</blockquote>
<p>it return error ImportError: cannot import name 'SpeechClient' with the following traceback:</p>
<pre><code>Traceback (most recent call last):
File "google.py", line 11, in <module>
from google.cloud import speech_v1 as speech
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/google/cloud/speech_v1/__init__.py", line 17, in <module>
from google.cloud.speech_v1.gapic import speech_client
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/google/cloud/speech_v1/gapic/speech_client.py", line 18, in <module>
import pkg_resources
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3241, in <module>
@_call_aside
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3225, in _call_aside
f(*args, **kwargs)
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3269, in _initialize_master_working_set
for dist in working_set
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3269, in <genexpr>
for dist in working_set
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2776, in activate
declare_namespace(pkg)
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2275, in declare_namespace
_handle_ns(packageName, path_item)
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2208, in _handle_ns
loader.load_module(packageName)
File "/home/hoanglinh/Documents/practice_speech/google.py", line 12, in <module>
from google.cloud.speech import enums
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/google/cloud/speech.py", line 19, in <module>
from google.cloud.speech_v1 import SpeechClient
ImportError: cannot import name 'SpeechClient'
</code></pre>
<p>Am i doing something wrong ? when i search the error online there only 1 question with no answer to it </p>
<p><strong>UPDATE:</strong>
i changed from </p>
<blockquote>
<p>google.cloud import speech_v1 as speech</p>
</blockquote>
<p>to this </p>
<blockquote>
<p>from google.cloud import speech</p>
</blockquote>
<p>now i got another return error with traceback like so</p>
<pre><code>Traceback (most recent call last):
File "google.py", line 11, in <module>
from google.cloud import speech
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/google/cloud/speech.py", line 19, in <module>
from google.cloud.speech_v1 import SpeechClient
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/google/cloud/speech_v1/__init__.py", line 17, in <module>
from google.cloud.speech_v1.gapic import speech_client
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/google/cloud/speech_v1/gapic/speech_client.py", line 18, in <module>
import pkg_resources
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3241, in <module>
@_call_aside
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3225, in _call_aside
f(*args, **kwargs)
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3269, in _initialize_master_working_set
for dist in working_set
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 3269, in <genexpr>
for dist in working_set
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2776, in activate
declare_namespace(pkg)
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2275, in declare_namespace
_handle_ns(packageName, path_item)
File "/home/hoanglinh/Documents/practice_speech/.venv/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2208, in _handle_ns
loader.load_module(packageName)
File "/home/hoanglinh/Documents/practice_speech/google.py", line 12, in <module>
from google.cloud.speech import enums
ImportError: cannot import name 'enums'
</code></pre>
<p>Have anyone tried this library before ? because it seem there so much errors just with following the docs of its</p>
|
<p>The following error message is seen</p>
<pre><code> from google.cloud.speech import enums
ImportError: cannot import name 'enums'
</code></pre>
<p>if an 'new' installation of the google speech api was performed. Please see <a href="https://github.com/googleapis/python-speech/blob/master/UPGRADING.md#enums-and-types" rel="nofollow noreferrer">this page</a>.</p>
<p>Along the same lines usage of nanos attributes would result in the following message if you have update the api</p>
<pre><code>AttributeError: 'datetime.timedelta' object has no attribute 'nanos'
</code></pre>
<p>Please see <a href="https://github.com/googleapis/python-speech/issues/71" rel="nofollow noreferrer">this page</a>. Use 'microseconds' instead of 'nanos'.</p>
|
python|import|google-speech-api|pipenv|google-cloud-speech
| 4 |
1,903,391 | 56,829,001 |
Doubling amount per day, need to convert number of pennies to dollars + cents
|
<p>This program starts with 1 cent and doubles each day. However, I'm stuck on trying to find a way to convert the number of pennies into a dollar and cent amount. For example, converting 1020 pennies to $10.20.</p>
<p>I'm also attempting to make it so if user input is not a positive number, the user will be continously prompted until they enter a positive number. This isn't working, however.</p>
<p>I also feel I've messed up by using range, as I want to enter a set number of days, say 16 days, and when I enter 16, I receive the days 1-17, as range should be doing, and I'm not sure how to go about fixing that.</p>
<pre><code>b = int(input("Input number of days "))
if b > 0:
print(b)
else:
b = int(input("Days must be positive "))
print("Day 1:","1")
days = 1
aIncrement = 2
penny = 1
for i in range(b):
pAmount = int(penny*2)
addAmount = int(2**aIncrement -1)
aIncrement +=1
days +=1
penny *= 2
print("Day " + str(days) + ":",pAmount)
</code></pre>
|
<p>Your question has multiple parts, which is not ideal for stackoverflow, but I will try to hit them all.</p>
<h2>Fixing the numeric values to show dollars and cents.</h2>
<p>As noted in comments to other answers, division can often run into snags due to floating point notation. But in this case, since all we really care about is the number of times 100 will go into the penny count and the remainder, we can probably safely get away with using <code>divmod()</code> which is included with Python and calculates the number of times a number is divisible in another number and the remainder in whole numbers.</p>
<p>For clarity, <code>divmod()</code> returns a <code>tuple</code> and in the sample below, I unpack the two values stored in the tuple and assign each individual value to one of two variables: <code>dollars</code> and <code>cents</code>.</p>
<pre><code> dollars, cents = divmod(pAmount, 100) # unpack values (ints)
# from divmod() function
output = '$' + str(dollars) + '.' + str(cents) # create a string from
# each int
</code></pre>
<h2>Fixing the range issue</h2>
<p>The <code>range()</code> function produces a number and you can set it to start and end where you want, keeping in mind that the ending number must be set at one value higher than you want to go to... i.e. to get the numbers from one to ten, you must use a range of 1 to 11. In your code, you use <code>i</code> as a placeholder and you separately use <code>days</code> to keep track of the value of the current day. Since your user will tell you that they want <code>b</code> days, you would need to increment that value immediately. I suggest combining these to simplify things and potentially using slightly more self-documenting variable names. An additional note since this starts off on day one, we can remove some of the setup code that we were using to manually process day one before the loop started (more on that in a later section).</p>
<pre><code>days = int(input("Input number of days "))
for day in range(1, days + 1):
# anywhere in your code, you can now refer to day
# and it will be able to tell you the current day
</code></pre>
<h2>Continuous input</h2>
<p>If we ask the user for an initial input, they can put in:</p>
<ul>
<li>a negative number</li>
<li>a zero</li>
<li>a positive number</li>
</ul>
<p>So our <code>while</code> loop should check for any condition that is not positive (i.e. <code>days <= 0</code>). If the first request is a positive number, then the while loop is effectively skipped entirely and the script continues, otherwise it keeps asking for additional inputs. Notice... I edited the string in the second <code>input()</code> function to show the user both the problem and to tell them what to do next.</p>
<pre><code>days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input positive number of days: "))
</code></pre>
<h2>Putting all this together, the code might look something like this:</h2>
<p>I put the items above together AND cleaned up a few additional things.</p>
<pre><code>days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input number of days: "))
# aIncrement = 2 # this line not needed
penny = 1
for day in range(1, days + 1):
pAmount = int(penny) # this line was cleaned up
# because we don't need to manually
# handle day one
dollars, cents = divmod(pAmount, 100)
output = '$' + str(dollars) + '.' + str(cents)
# addAmount = int(2**aIncrement -1) # this line not needed
# aIncrement +=1 # this line not needed
penny *= 2
print("Day " + str(day) + ":", output)
</code></pre>
|
python
| 1 |
1,903,392 | 17,710,849 |
Python post increment variable in function call
|
<p>Premise: I am trying to make a bunch of buttons in Tkinter and put them in a grid layout one after the other. I don't want to hard code each grid value that way I can add more buttons later with ease.</p>
<p>My first thought was to:</p>
<pre><code>Button(root, text = "example", command = self.example_action).grid(row = count++)
</code></pre>
<p>But this did not work, I did some searching and found that python does not have a pre or post increment operator (<a href="https://stackoverflow.com/questions/1485841/behaviour-of-increment-and-decrement-operators-in-python">Behaviour of increment and decrement operators in Python</a>). So my next thought was to:</p>
<pre><code>Button(root, text = "example", command = self.example_action).grid(row = count = count + 1)
</code></pre>
<p>This gives: SyntaxError: invalid syntax</p>
<p>So other than splitting my code onto two lines (use the variable then update it on the next line) is there a good way to do this all on one line to make my code more beautiful?</p>
|
<p>I suppose you could use a generator. Initialize count like:</p>
<pre><code>count = itertools.count()
</code></pre>
<p>then you can do the following as much as you like</p>
<p>Python 2.x:</p>
<pre><code>Button(root, text = "example", command = self.example_action).grid(row = count.next())
</code></pre>
<p>Python 3.x:</p>
<pre><code>Button(root, text = "example", command = self.example_action).grid(row = next(count))
</code></pre>
<p>But I probably wouldn't</p>
|
python|tkinter|post-increment
| 1 |
1,903,393 | 60,832,217 |
Do I need to install Hadoop in order to use all aspects of Pyspark?
|
<p>I've installed pyspark, but have not installed any hadoop or spark version seperatly.</p>
<p>Apparently under Windows pyspark needs access to the winutils.exe for Hadoop for some things (e.g. writing files to disk). When pyspark wants to access the winutilis.exe it looks for it in the bin directory of the folder specified by the HADOOP_HOME environment variable (user variable). Therefore I copied the winutils.exe into the bin directory of pyspark (<code>.\site-packages\pyspark\bin</code>) and specified HADOOP_HOME as <code>.\site-packages\pyspark\</code>. This solved the problem of getting the error message: <code>Failed to locate the winutils binary in the hadoop binary path</code>.</p>
<p>However, when I start a Spark session using pyspark I still get the following warning:</p>
<pre><code>WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
</code></pre>
<p>Installing Hadoop and then specifying its installation directory for HADDOP_HOME did prevent the warning. Has a specific hadoop version to be installed to make pyspark work without restrictions?</p>
|
<p><strong>Hadoop installation is not mandatory.</strong> </p>
<p>Spark is distributed computing engine only.</p>
<p>Spark offers only computation & it doesn't have any storage.
But Spark is integrated with huge variety of storage systems like HDFS, Cassandra, HBase, Mongo DB, Local file system etc....</p>
<p>Spark is designed to run on top of variety of resource management platforms like Spark, Mesos, YARN, Local, Kubernetes etc....</p>
<p>PySpark is Python API on top of Spark to develop Spark applications in Python. So Hadoop installation is not mandatory.</p>
<p><strong>Note: Hadoop Installation is only required either to run Pyspark application on top of YARN or to access input/output of Pyspark application from/to HDFS/Hive/HBase or Both.</strong></p>
<p>About the warning you posted is normal one. So ignore it.</p>
|
python|apache-spark|hadoop|pyspark
| 2 |
1,903,394 | 69,219,878 |
How can I convert object to integer from the dataframe in Python with contains colon(:) and space?
|
<p>Data contains colon(:) and also space, so all the columns type is object. How can I convert to all columns object to integer or float.</p>
<p>I try this, but its not working.</p>
<pre><code>df = pd.concat([df[col].str.split()
.str[0]
.str.replace(':','').astype(float) for col in df], axis=1)
df['col'] = df['col'].astype(int)
print(df)
AttributeError: Can only use .str accessor with string values!
</code></pre>
|
<p>You can use regex to extract the numbers, then convert it to integer afterwards. See the code below:</p>
<pre class="lang-py prettyprint-override"><code>import re
def to_integer(x):
result = re.findall('[0-9]+', str(x))
num = ''.join(result)
return int(num)
df['col'] = df['col'].apply(to_integer)
</code></pre>
|
python|string|object|integer
| 0 |
1,903,395 | 68,993,336 |
Vertorize Matching Two dataframe datetimeindex comparison
|
<p>I have two datetime ordered dataframes using a DatetimeIndex (timestamp) as per below.</p>
<pre><code>df1
timestamp price side
2021-08-27 12:45:00.475100160+00:00 47.34
2021-08-27 12:45:00.475100160+00:00 47.02
2021-08-27 12:45:00.488067957+00:00 47.18
2021-08-27 12:45:00.779297294+00:00 47.26
2021-08-27 12:45:00.779297294+00:00 47.27
df2
timestamp bid_price ask_price
2021-08-27 12:44:59.740064471+00:00 47.08 47.34
2021-08-27 12:45:00.475100160+00:00 47.02 47.34
2021-08-27 12:45:00.914411789+00:00 47.02 47.26
2021-08-27 12:45:00.915470114+00:00 47.02 47.34
</code></pre>
<p>I need to compare the datetimeIndex of each row in the first dataframe (df1) against the datetimeIndex of the second dataframe (df2). The first row in df2 which has a datetime that is equal to or below the datetimeindex of the row in df1 will be used to evaluate the columns of df2.bid_price and df2.ask_price against the column df1.price. If df1.price == df2.bid_price then add 'Bid' to the df1.side column. If df1.price == df2.ask_price then add 'Ask' to the df1.side column. If df1.price is between dff2.ask_price and df2.bid_price then add 'Inside' to df1.side column else add 'Outside' to the df1.side column.</p>
<p>My code below is the least efficient way of doing this by iterating through every row of df1 and comparing it to df2. In short, it takes forever when I start looking at anything over 10-20k rows. I was looking for more efficient ways of doing this.</p>
<pre><code>for x in range(len(df1)):
price = df1.price.iloc[x]
quote = df2[(df1.index[x] >= df2.index)][['bid_price','ask_price']].iloc[-1]
if price == quote.bid_price:
df1.side.iloc[x] = 'Bid'
elif price == quote.ask_price:
df1.side.iloc[x] = 'Ask'
elif (price > quote.bid_price) & (price < quote.ask_price):
df1.side.iloc[x] = 'Inside'
else:
df1.side.iloc[x] = 'Outside'
</code></pre>
|
<p>Here is a working solution using <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.asof.html" rel="nofollow noreferrer"><code>pandas.merge_asof</code></a> to merge the timestamps and <a href="https://numpy.org/doc/stable/reference/generated/numpy.select.html" rel="nofollow noreferrer"><code>numpy.select</code></a> to match the various conditions:</p>
<pre><code>import numpy as np
df3 = pd.merge_asof(df1, df2, on='timestamp', direction='backward')
df3['side'] = np.select([df3['price']==df3['bid_price'],
df3['price']==df3['ask_price'],
df3['price'].between(df3['bid_price'], df3['ask_price'])
],
['Bid', 'Ask', 'Inside'],
default='Outside'
)
</code></pre>
<p>output:</p>
<pre><code>>>> df3
timestamp price side bid_price ask_price
0 2021-08-27 12:45:00.475100160+00:00 47.34 Ask 47.02 47.34
1 2021-08-27 12:45:00.475100160+00:00 47.02 Bid 47.02 47.34
2 2021-08-27 12:45:00.488067957+00:00 47.18 Inside 47.02 47.34
3 2021-08-27 12:45:00.779297294+00:00 47.26 Inside 47.02 47.34
4 2021-08-27 12:45:00.779297294+00:00 47.27 Inside 47.02 47.34
</code></pre>
<p><em>NB. if needed, you can drop the intermediate columns: <code>df3.drop(['bid_price', 'ask_price'], axis=1)</code></em></p>
|
python|python-3.x|pandas|dataframe
| 1 |
1,903,396 | 72,732,599 |
predict() error : X does not have valid feature names, but LinearRegression was fitted with feature names warnings.warn(
|
<pre><code>import pandas as pd
import numpy as np
from sklearn import linear_model
df = pd.read_csv('https://raw.githubusercontent.com/codebasics/py/master/ML/1_linear_reg/Exercise/canada_per_capita_income.csv')
reg = linear_model.LinearRegression()
reg.fit( df[['year']], df['per capita income (US$)'] )
reg.predict(2020)
</code></pre>
<p>I am using scikit 1.0.2 version. I am new learner and exactly copied this from a video it works in video but do not work on me, What should I do?</p>
<pre><code>X does not have valid feature names, but LinearRegression was fitted with feature names
warnings.warn(
</code></pre>
|
<pre><code>mask = df['year'] == 2000
aaa = reg.predict(df.loc[mask, 'year'].values.reshape(-1, 1))
print(aaa[0])
</code></pre>
<p>Output</p>
<pre><code>24719.392589963274
</code></pre>
<p>Use an equality test and apply masking to access the value. And extract the value from aaa[0].</p>
|
python|pandas|machine-learning|scikit-learn|data-science
| 0 |
1,903,397 | 72,698,385 |
Extracting JSON value from its parent
|
<p>I am making a request and I want to parse its response:</p>
<pre><code>{"hash160":"4b1ddbf92df072c298a0c58043db58b26771f926","address":"17rBT3f4UmnFGrngasBprqXjQQnZVztfDz","n_tx":0,"n_unredeemed":0,"total_received":0,"total_sent":0,"final_balance":0,"txs":[]}
</code></pre>
<p>I tried to extract values <code>total_sent</code> and <code>final_balance</code> like this: <code>print(str(wallet['n_tx']['total_sent']))</code> and I got a <code>Type Error: 'int' object is not subscriptable</code></p>
<p>How can I extract those values?</p>
|
<p>If you just want to print them both out you can try this:</p>
<pre><code>[print(str(wallet[i])) for i in ['n_tx', 'total_sent']]
</code></pre>
<p>The reason you are getting the error is because <code>wallet['n_tx']</code> is an integer and therefore has no <code>total_sent</code> key. In order to access both values you need to extract them one at a time.</p>
<pre><code>a = wallet['n_tx']
b = wallet['total_sent']
</code></pre>
|
python|json
| 0 |
1,903,398 | 59,252,184 |
Django: unpack tuple in for loop
|
<p>I've a queryset of items.</p>
<p>And I've used itertools grouper to group them by 3. </p>
<p>However, when the list contains more than a mutiple of 3, for example 7 elemenets, the last tuple is completed with <code>None</code>.</p>
<p>I need to go through all groups (that contain 3 elements) and for each element:<br>
- Test if it is not None.<br>
- Compare the prices of each element inside the group, and return the id of the element with the lowers price and it's price. </p>
<p><strong>views.py:</strong></p>
<p><strong>Queryset:</strong></p>
<pre><code> pack_items = PackItem.objects.filter(cart=cart)
</code></pre>
<p>Grouping by 3:</p>
<pre><code>pack_items_grouped_by_3 = list(grouper(pack_items, 3))
for p_item in pack_items_grouped_by_3:
print(type(p_item)) #prints <class 'tuple'>
print(p_item) #prints (<PackItem: PackItem object (65)>, <PackItem: PackItem object (66)>, <PackItem: PackItem object (67)>)
for a, b, c in p_item:
if a is not None:
print(a)
#print(a.pack.price)
elif b is not None:
print(b)
#print(b.pack.price)
elif c is not None:
print(c)
#print(c.pack.price)
</code></pre>
<blockquote>
<p>Error:</p>
<p>for a, b, c in p_item: TypeError: cannot unpack non-iterable PackItem
object</p>
</blockquote>
|
<p>What's happening is that when you run</p>
<pre><code>for element in p_item:
</code></pre>
<p><code>element</code> will be the three pack item instances in the tuple that is p_item. The error is raised because it's trying to split a single PackItem instance into <code>a, b, c</code>.</p>
<p>You could do either of the following:</p>
<pre><code>a, b, c = p_item
</code></pre>
<p>Or what I think is better:</p>
<pre><code> pack_items_grouped_by_3 = list(grouper(pack_items, 3))
for a, b, c in pack_items_grouped_by_3:
if a is not None:
print(a)
#print(a.pack.price)
elif b is not None:
print(b)
#print(b.pack.price)
elif c is not None:
print(c)
#print(c.pack.price)
</code></pre>
|
python|django|itertools
| 0 |
1,903,399 | 59,143,045 |
How to filter s3 objects by last modified date with Boto3
|
<p>Is there a way to filter s3 objects by last modified date in boto3? I've constructed a large text file list of all the contents in a bucket. Some time has passed and I'd like to list only objects that were added after the last time I looped through the entire bucket. </p>
<p>I know I can use the <code>Marker</code> property to start from a certain object name,so I could give it the last object I processed in the text file but that does not guarantee a new object wasn't added before that object name. e.g. if the last file in the text file was oak.txt and a new file called apple.txt was added, it would not pick that up. </p>
<pre><code>s3_resource = boto3.resource('s3')
client = boto3.client('s3')
def list_rasters(bucket):
bucket = s3_resource.Bucket(bucket)
for bucket_obj in bucket.objects.filter(Prefix="testing_folder/"):
print bucket_obj.key
print bucket_obj.last_modified
</code></pre>
|
<p>The following code snippet gets all objects under specific folder and check if the file last modified is created after the time you specify :</p>
<p>Replace <code>YEAR,MONTH, DAY</code> with your values.</p>
<pre><code>import boto3
import datetime
#bucket Name
bucket_name = 'BUCKET NAME'
#folder Name
folder_name = 'FOLDER NAME'
#bucket Resource
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket_name)
def lambda_handler(event, context):
for file in bucket.objects.filter(Prefix= folder_name):
#compare dates
if file.last_modified.replace(tzinfo = None) > datetime.datetime(YEAR,MONTH, DAY,tzinfo = None):
#print results
print('File Name: %s ---- Date: %s' % (file.key,file.last_modified))
</code></pre>
|
python|python-3.x|amazon-web-services|amazon-s3|boto3
| 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.