qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
53,632,979 | i recently start learning about python, and made simple source of 2 balls in canvas which are moving with 2d vector rule. i want multiply the number of balls with list in python. here is source of that.
```
import time
import random
from tkinter import *
import numpy as np
import math
window = Tk()
canvas = Canvas(win... | 2018/12/05 | [
"https://Stackoverflow.com/questions/53632979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10749521/"
] | 1) You should be. I highly recommend avoiding secondary indexes and ALLOW FILTERING consider them advanced features for corner cases.
2) It can be more efficient with index, but still horrible, and also horrible in more new ways. There are only very few scenarios where secondary indexes are acceptable. There are very ... | As worst case for your use case, consider searching for an Austrian composer born in 1756. Yes, you can find him (Mozart) in a table of all humans who ever lived by intersecting the index of nationality=Austria, the index of birth=1756 and the index of profession=composer. But Cassandra will implement such a query very... | 10,240 |
69,301,316 | Im currently trying to get the mean() of a group in my dataframe (tdf), but I have a mix of some NaN values and filled values in my dataset. Example shown below
| Test # | a | b |
| --- | --- | --- |
| 1 | 1 | 1 |
| 1 | 2 | NaN |
| 1 | 3 | 2 |
| 2 | 4 | 3 |
My code needs to take this dataset, and make a new dataset c... | 2021/09/23 | [
"https://Stackoverflow.com/questions/69301316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16985105/"
] | You can use
```py
(?<![a-zA-Z0-9_.-])@(?=([A-Za-z]+[A-Za-z0-9_-]*))\1(?![@\w])
(?a)(?<![\w.-])@(?=([A-Za-z][\w-]*))\1(?![@\w])
```
See the [regex demo](https://regex101.com/r/KFHwo8/3). *Details*:
* `(?<![a-zA-Z0-9_.-])` - a negative lookbehind that matches a location that is not immediately preceded with ASCII dig... | Another option is to assert a whitespace boundary to the left, and assert no word char or @ sign to the right.
```
(?<!\S)@([A-Za-z]+[\w-]+)(?![@\w])
```
The pattern matches:
* `(?<!\S)` Negative lookbehind, assert not a non whitespace char to the left
* `@` Match literally
* `([A-Za-z]+[\w-]+)` Capture group1, mat... | 10,241 |
29,240,807 | What is the complexity of the function `most_common` provided by the `collections.Counter` object in Python?
More specifically, is `Counter` keeping some kind of sorted list while it's counting, allowing it to perform the `most_common` operation faster than `O(n)` when `n` is the number of (unique) items added to the ... | 2015/03/24 | [
"https://Stackoverflow.com/questions/29240807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3397458/"
] | From the source code of [collections.py](https://github.com/python/cpython/blob/a8e814db96ebfeb1f58bc471edffde2176c0ae05/Lib/collections/__init__.py#L571), we see that if we don't specify a number of returned elements, `most_common` returns a sorted list of the counts. This is an `O(n log n)` algorithm.
If we use `mos... | [The source](https://github.com/python/cpython/blob/1b85f4ec45a5d63188ee3866bd55eb29fdec7fbf/Lib/collections/__init__.py#L575) shows exactly what happens:
```
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all eleme... | 10,242 |
54,565,417 | When I'm visiting my website (<https://osm-messaging-platform.appspot.com>), I get this error on the main webpage:
```
502 Bad Gateway. nginx/1.14.0 (Ubuntu).
```
It's really weird, since when I run it locally
```
python app.py
```
I get no errors, and my app and the website load fine.
I've already tried lookin... | 2019/02/07 | [
"https://Stackoverflow.com/questions/54565417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10808093/"
] | The error is produced because the App Engine Standard Python37 runtime handles the requests in the `main.py` file by default. I guess that you don't have this file and you are handling the requests in the `app.py` file.
Also the logs traceback is pointing to it: `ModuleNotFoundError: No module named 'main'`
Change t... | My mistake was naming the main app "main" which conflicted with main.py. It worked fine locally as it did not use main.py. I changed it to root and everything worked fine. It took me a whole day to solve it out. | 10,243 |
70,147,775 | I am just learning python and was trying to loop through a list and use pop() to remove all items from original list and add them to a new list formatted. Here is the code I use:
```
languages = ['russian', 'english', 'spanish', 'french', 'korean']
formatted_languages = []
for a in languages:
formatted_languages.... | 2021/11/28 | [
"https://Stackoverflow.com/questions/70147775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17534746/"
] | Look:
```
languages = ['russian', 'english', 'spanish', 'french', 'korean']
formatted_languages = []
for a in languages:
print(a)
print(languages)
formatted_languages.append(languages.pop().title())
print(formatted_languages)
```
Notice what "a" is:
```
russian
['russian', 'english', 'spanish', 'f... | What you're doing here is changing the size of the list whilst the list is being processed, so that once you've got to spanish in the list (3rd item), you've removed french and korean already, so once you've removed spanish, there are no items left to loop through. You can use the code below to get around this.
```py
... | 10,246 |
17,509,607 | I have seen questions like this asked many many times but none are helpful
Im trying to submit data to a form on the web ive tried requests, and urllib and none have worked
for example here is code that should search for the [python] tag on SO:
```
import urllib
import urllib2
url = 'http://stackoverflow.com/'
# P... | 2013/07/07 | [
"https://Stackoverflow.com/questions/17509607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2292723/"
] | If you want to pass `q` as a parameter in the URL using [`requests`](http://docs.python-requests.org/), use the `params` argument, not `data` (see [Passing Parameters In URLs](http://docs.python-requests.org/en/latest/user/quickstart.html#passing-parameters-in-urls)):
```
r = requests.get('http://stackoverflow.com', p... | ```
import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
```
... | 10,248 |
17,847,869 | I have this following Python Tkinter code which redraw the label every 10 second. My question is , to me it seems like it is drawing the new label over and over again over the old label. So, eventually, after a few hours there will be hundreds of drawing overlapping (at least from what i understand). Will this use more... | 2013/07/25 | [
"https://Stackoverflow.com/questions/17847869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2180836/"
] | The correct way to run a function or update a label in tkinter is to use the [after](http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.after-method) method. This puts an event on the event queue to be executed at some time in the future. If you have a function that does some work, then puts itself back on the eve... | To allow the cleanup with minimal code changes, you could pass previous frames explicitly:
```
import Tkinter as tk
def Draw(oldframe=None):
frame = tk.Frame(root,width=100,height=100,relief='solid',bd=1)
frame.place(x=10,y=10)
tk.Label(frame, text='HELLO').pack()
frame.pack()
if oldframe is not N... | 10,251 |
8,008,829 | I am working on a project in python in which I need to extract only a subfolder of tar archive not all the files.
I tried to use
```
tar = tarfile.open(tarfile)
tar.extract("dirname", targetdir)
```
But this does not work, it does not extract the given subdirectory also no exception is thrown. I am a beginner in py... | 2011/11/04 | [
"https://Stackoverflow.com/questions/8008829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517272/"
] | Building on the second example from the [tarfile module documentation](https://docs.python.org/3.5/library/tarfile.html#examples), you could extract the contained sub-folder and all of its contents with something like this:
```
with tarfile.open("sample.tar") as tar:
subdir_and_files = [
tarinfo for tarinf... | The other answer will retain the subfolder path, meaning that `subfolder/a/b` will be extracted to `./subfolder/a/b`. To extract a subfolder to the root, so `subfolder/a/b` would be extracted to `./a/b`, you can rewrite the paths with something like this:
```
def members(tf):
l = len("subfolder/")
for member i... | 10,252 |
31,767,292 | I may be way off here - but would appreciate insight on just how far ..
In the following `getFiles` method, we have an anonymous function being passed as an argument.
```
def getFiles(baseDir: String, filter: (File, String) => Boolean ) = {
val ffilter = new FilenameFilter {
// How to assign to the anonymous fun... | 2015/08/01 | [
"https://Stackoverflow.com/questions/31767292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1056563/"
] | There is no way easy or type-safe way (that I know of) to assign a function to a method as they are different types. In Python or JavaScript you could do something like this:
```
var fnf = new FilenameFilter();
fnf.accepts = filter;
```
But in Scala you have to do the delegation:
```
val fnf = new FilenameFilter {
... | I think you are actually misunderstanding the meaning of the override keyword.
It is for redefining methods defined in the superclass of a class, not redefining a method in an instance of a class.
If you want to redefine the accept method in the instances of FilenameFilter, you will need to add the filter method to th... | 10,253 |
35,201,647 | How to use hook in bottle?
<https://pypi.python.org/pypi/bottle-session/0.4>
I am trying to implement session plug in with bottle hook.
```
@bottle.route('/loginpage')
def loginpage():
return '''
<form action="/login" method="post">
Username: <input name="username" type="text" />
Passwo... | 2016/02/04 | [
"https://Stackoverflow.com/questions/35201647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3282945/"
] | Try this .................
Your **initializers/carrierwave.rb** look like this.
```
CarrierWave.configure do |config|
config.fog_credentials = {
:provider => 'AWS', # required
:aws_access_key_id => 'xxx', # required
:aws_secret_access_key ... | `CarrierWave::Uploader::Base:Class#fog_provider=` is not released yet. It is only available on the CarrierWave `master` branch.
**Solution 1 (Use master):**
Change your `Gemfile` entry to
```
gem "carrierwave", git: "[email protected]:carrierwaveuploader/carrierwave.git"
```
But this is not recommended since it is ... | 10,254 |
10,043,636 | A common antipattern in Python is to concatenate a sequence of strings using `+` in a loop. This is bad because the Python interpreter has to create a new string object for each iteration, and it ends up taking quadratic time. (Recent versions of CPython can apparently optimize this in some cases, but other implementat... | 2012/04/06 | [
"https://Stackoverflow.com/questions/10043636",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1064659/"
] | There is nothing wrong in concatenating *two* strings with `+`. Indeed it's easier to read than `''.join([a, b])`.
You are right though that concatenating more than 2 strings with `+` is an O(n^2) operation (compared to O(n) for `join`) and thus becomes inefficient. However this has not to do with using a loop. Even `... | The assumption that one should never, ever use + for string concatenation, but instead always use ''.join may be a myth. It is true that using `+` creates unnecessary temporary copies of immutable string object but the other not oft quoted fact is that calling `join` in a loop would generally add the overhead of `funct... | 10,255 |
11,566,355 | Why it executes the script every 2 minutes?
Shouldn't it execute every 10 minutes ?
```
*\10 * * * * /usr/bin/python /var/www/py/LSFchecker.py
``` | 2012/07/19 | [
"https://Stackoverflow.com/questions/11566355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1131053/"
] | ```
*\10 * * * *
```
Should probably be
```
*/10 * * * *
``` | You can try:
00,10,20,30,40,50 \* \* \* \* /usr/bin/python /var/www/py/LSFchecker.py | 10,265 |
39,003,106 | Comrades,
I'd like to capture images from the laptop camera in Python. Currently all signs point to OpenCV. Problem is OpenCV is a nightmare to install, and it's a nightmare that reoccurs every time you reinstall your code on a new system.
Is there a more lightweight way to capture camera data in Python? I'm looking... | 2016/08/17 | [
"https://Stackoverflow.com/questions/39003106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/851699/"
] | I've done this before using [pygame](http://www.pygame.org/download.shtml). But I can't seem to find the script that I used... It seems there is a tutorial [here](http://www.pygame.org/docs/tut/camera/CameraIntro.html) which uses the native camera module and is not dependent on OpenCV.
Try this:
```
import pygame
imp... | Videocapture for Windows
========================
I've used [videocapture](http://videocapture.sourceforge.net/) in the past and it was perfect:
```
from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')
``` | 10,266 |
32,231,589 | *Question:* I am trying to debug a function in a `class` to make sure a list is implemented and if not, I want an error to be thrown up. I am new to programming and am trying to figure how to effectively add an `assert` for the debugging purposes mentioned above.
In the method body of `class BaseAPI()` I have to iter... | 2015/08/26 | [
"https://Stackoverflow.com/questions/32231589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5140076/"
] | I am going to go for my Self Learner badge, here, and answer my own question.
I did about 8 hours of research on this and came up with a great solution. Three things had to be done.
1. Set the HTML5 video src to something other than the original URL. This will trigger the player to close the open socket connection.
2... | Added a line between pause() and remove():
```
// Handling Bootstrap Modal Window Close Event
// Trigger player destroy
$("#xr-interaction-detail-modal").on("hidden.bs.modal", function () {
var player = xr.ui.mediaelement.xrPlayer();
if (player) {
player.pause();
("video,audio").attr("src", ""... | 10,269 |
44,472,252 | I am very beginner Python. So my question could be quite naive.
I just started to study this language principally due to mathematical tools such as Numpy and Matplotlib which seem to be very useful.
In fact I don't see how python works in fields other than maths
I wonder if it is possible (and if yes, how?) to use Pyt... | 2017/06/10 | [
"https://Stackoverflow.com/questions/44472252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8141006/"
] | If you want to concatenate them the good ol' fashioned way, and put them in a new file, you can do this:
```
a = open('A.txt')
b = open('B.txt')
c = open('C.txt', 'w')
for a_line, b_line in zip(a, b):
c.write(a_line.rstrip() + ' ' + b_line)
a.close()
b.close()
c.close()
``` | Try this,read files as numpy arrays
```
a = np.loadtxt('a.txt')
b = np.genfromtxt('b.txt',dtype='str')
```
In case of b you need genfromtext because of string content.Than
```
np.concatenate((a, b), axis=1)
```
Finally, you will get
```
np.concatenate((a, b), axis=1)
array([['0.22222', '0.11111', '0.0', 'F', 'F... | 10,270 |
3,999,829 | I wouldn't call myself programmer, but I've started learning Python recently and really enjoy it.
I mainly use it for small tasks so far - scripting, text processing, KML generation and ArcGIS.
From my experience with R (working with excellent Notepad++ and [NppToR](http://sourceforge.net/projects/npptor/) combo) I u... | 2010/10/22 | [
"https://Stackoverflow.com/questions/3999829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/319487/"
] | I use Notepad++ for most of my Windows based Python development and for debugging I use [Winpdb](http://winpdb.org/about/). It's a cross platform GUI based debugger. You can actually setup a keyboard shortcut in Notepad++ to launch the debugger on your current script:
To do this go to "Run" -> "Run ..." in the menu an... | [Light Table](http://lighttable.com/) was doing that for me, unfortunately it is discontinued:
>
> INLINE EVALUTION No more printing to the console in order to view your
> results. Simply evaluate your code and the results will be displayed
> inline.
>
>
>
[ server, it seems to be much easier to deploy.
Here is a [good tutorial for deploying to EC2](http://www.yaconiello.com/blog/setting-aws-ec2-instance-nginx-django-uwsgi-and-mysql/#sthash.E2Gg8vGi.dpbs) but you can use parts of it to configure the server. | 10,283 |
41,320,092 | I am new to `python` and `boto3`, I want to get the latest snapshot ID.
I am not sure if I wrote the sort with lambda correctly and how to access the last snapshot, or maybe I can do it with the first part of the script when I print the `snapshot_id` and `snapshot_date` ?
Thanks.
Here is my script
```
import boto3
... | 2016/12/25 | [
"https://Stackoverflow.com/questions/41320092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4308473/"
] | You should it sort in `reverse` order.
```
sorted(list_to_be_sorted, key=lambda k: k['date'], reverse=True)[0]
```
sorts the list by the date (in ascending order - oldest to the latest)
If you add `reverse=True`, then it sorts in descending order (latest to the oldest). `[0]` returns the first element in the list wh... | You can append the snapshots to list, then sort the list based on date
```
def find_snapshots():
list_of_snaps = []
for snapshot in ec2client_describe_snapshots['Snapshots']:
snapshot_volume = snapshot['VolumeId']
mnt_vol = "vol-xxxxx"
if mnt_vol == snapshot_volume:
snapshot_date = snapsho... | 10,286 |
25,985,491 | I have a sentiment analysis task and i need to specify how much data (in my case text) does scikit can handle. I have a corpus of 2500 opinions all ready tagged. I now that it´s a small corpus but my thesis advisor is asking me to specifically argue how many data does scikit learn can handle. My advisor has his doubts ... | 2014/09/23 | [
"https://Stackoverflow.com/questions/25985491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3930105/"
] | Here are some timings for scikit-learn's document classification example on my machine (Python 2.7, NumPy 1.8.2, SciPy 0.13.3, scikit-learn 0.15.2, Intel Core i7-3540M laptop running on battery power). The dataset is twenty newsgroups; I've trimmed the output quite a bit.
```
$ python examples/document_classification_... | [This Scikit page](http://scikit-learn.org/stable/modules/scaling_strategies.html) may provide some answers if you are experiencing some issues with the amount of data that you are trying to load.
As stated in your other question on data size [concerning Weka](https://stackoverflow.com/questions/25979182/how-much-tex... | 10,291 |
9,291,036 | I'm putting together a basic photoalbum on appengine using python 27. I have written the following method to retrieve image details from the datastore matching a particular "adventure". I'm using limits and offsets for pagination, however it is very inefficient. After browsing 5 pages (of 5 photos per page) I've alread... | 2012/02/15 | [
"https://Stackoverflow.com/questions/9291036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/714852/"
] | A few things:
1. You don't need to have count called each time, you can cache it
2. Same goes to the query, why are you querying all the time? cache it also.
3. Cache the pages also, you should not calc the data per page each time.
4. You only need the blob\_key but your are loading the entire photo entity, try to mod... | The way you handle paging is inefficient as it goes through every record before the offset to deliver the data. You should consider building the paging mechanisms using the bookmark methods described by Google <http://code.google.com/appengine/articles/paging.html>.
Using this method you only go through the items you ... | 10,293 |
35,390,152 | I am new to selenium with python. Tried this sample test script.
```
from selenium import webdriver
def browser():
driver= webdriver.Firefox()
driver.delete_all_cookies()
driver.get('http://www.gmail.com/')
driver.maximize_window()
driver.save_screenshot('D:\Python Programs\Sc... | 2016/02/14 | [
"https://Stackoverflow.com/questions/35390152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5861605/"
] | Just use [pandas](http://pandas.pydata.org/):
```
In [1]: import pandas as pd
```
Change the number of decimals:
```
In [2]: pd.options.display.float_format = '{:.3f}'.format
```
Make a data frame:
```
In [3]: df = pd.DataFrame({'gof_test': gof_test, 'gof_train': gof_train})
```
and display:
```
In [4]: df
... | Indeed you cannot affect the display of the Python output with CSS, but you can give your results to a formatting function that will take care of making it "beautiful". In your case, you could use something like this:
```
def compare_dicts(dict1, dict2, col_width):
print('{' + ' ' * (col_width-1) + '{')
for k1... | 10,296 |
42,449,296 | In OpenAPI, inheritance is achieved with `allof`. For instance, in [this example](https://github.com/OAI/OpenAPI-Specification/blob/master/examples/v2.0/json/petstore-simple.json):
```js
"definitions": {
"Pet": {
"type": "object",
"allOf": [
{
"$ref": "#/definitions/NewPet" # <---... | 2017/02/24 | [
"https://Stackoverflow.com/questions/42449296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653485/"
] | JSON Schema doesn't support inheritance. The behavior of `allOf` can sometimes look like inheritance, but if you think about it that way you will end up getting confused.
The `allOf` keyword means just what it says: all of the schemas must validate. Nothing gets overridden or takes precedence over anything else. Every... | One thing to consider is what inheritance means. In Eclipse Modeling Framework trying to create a class that extends 2 classes with the same attribute is an error. Never the less I consider that multiple inheritance.
This is called the Diamond Problem. See <https://en.wikipedia.org/wiki/Multiple_inheritance> | 10,297 |
60,942,530 | I'm working on an Django project, and building and testing with a database on GCP. Its full of test data and kind of a mess.
Now I want to release the app with a new and fresh another database.
How do I migrate to the new database? with all those `migrations/` folder?
I don't want to delete the folder cause the deve... | 2020/03/31 | [
"https://Stackoverflow.com/questions/60942530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4971866/"
] | >
> or maybe a different data structure to keep both the name and the value of the variable?
>
>
>
Ding ding! You want to use a map for this. A map stores a key and a value as a pair. To give you a visual representation, a map looks like this:
```
Cats: 5
Dogs: 3
Horses: 2
```
Using a map you can access both th... | You might want to consider priority queue in java. But first you need a class which have 2 attributes (the word and its quantity). This class should implement Comparable and compareTo method should be overridden. Here's an example: <https://howtodoinjava.com/java/collections/java-priorityqueue/> | 10,298 |
37,972,029 | [PEP 440](https://www.python.org/dev/peps/pep-0440) lays out what is the accepted format for version strings of Python packages.
These can be simple, like: `0.0.1`
Or complicated, like: `2016!1.0-alpha1.dev2`
What is a suitable regex which could be used for finding and validating such strings? | 2016/06/22 | [
"https://Stackoverflow.com/questions/37972029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1728179/"
] | I had the same question. This is the most thorough regex pattern I could find. PEP440 links to the codebase of the packaging library in it's references section.
```
pip install packaging
```
To access just the pattern string you can use the global
```
from packaging import version
version.VERSION_PATTERN
```
See:... | I think this should comply with PEP440:
```
^(\d+!)?(\d+)(\.\d+)+([\.\-\_])?((a(lpha)?|b(eta)?|c|r(c|ev)?|pre(view)?)\d*)?(\.?(post|dev)\d*)?$
```
### Explained
Epoch, e.g. `2016!`:
```
(\d+!)?
```
Version parts (major, minor, patch, etc.):
```
(\d+)(\.\d+)+
```
Acceptable separators (`.`, `-` or `_`):
```
(... | 10,299 |
19,512,457 | What can i do to optimize this function, and make it looks like more pythonic?
```
def flatten_rows_to_file(filename, rows):
f = open(filename, 'a+')
temp_ls = list()
for i, row in enumerate(rows):
temp_ls.append("%(id)s\t%(price)s\t%(site_id)s\t%(rating)s\t%(shop_id)s\n" % row)
if i and i ... | 2013/10/22 | [
"https://Stackoverflow.com/questions/19512457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2000477/"
] | A few things that come to mind immediately:
1. Use a `with` statement, rather than manually closing your file.
2. Pass a generator expression to `f.writelines` rather than building up a 100000 row list over and over (let the standard library handle how much, if any, it buffers the output).
3. Or, better yet, use the `... | It is generally a good idea to use the `with` statement to make sure the file is closed properly. Also, unless I'm mistaken there should be no need to manually buffer the lines. You can just as well specify a buffer size when opening the file, determining [how often the file is flushed](https://stackoverflow.com/q/3167... | 10,300 |
36,380,144 | i'm new at here and im new at coding something at node.js. My question is how to use the brackets i mean, i'm working on a steam trade bot and i need to get understand how to use options and callbacks. Let me give you a example,
[](https://i.stack.img... | 2016/04/03 | [
"https://Stackoverflow.com/questions/36380144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The brackets are documentation notation indicating that those parameters are optional, and can be omitted from any given invocation.
They are not indicative of syntax you should be using in your program.
Both of these styles should work, given that documentation. The callback being optional.
```
makeOffer({ ... });
... | ~~`makeOffer(accessToken[, itemsFromThem])` is not JavaScript syntax. It's just common notation that's used to indicate that the function can take any number of arguments, like so:~~
```
makeOffer(accessToken, something, somethingElse);
makeOffer(accessToken, something, secondThing, thirdThing);
makeOffer(accessToken)... | 10,301 |
62,919,733 | I have an ascii file containing 2 columns as following;
```
id value
1 15.1
1 12.1
1 13.5
2 12.4
2 12.5
3 10.1
3 10.2
3 10.5
4 15.1
4 11.2
4 11.5
4 11.7
5 12.5
5 12.2
```
I want to estimate the average value of column "value" for each id (i.e. group by id)
Is it possible to do that in python using nu... | 2020/07/15 | [
"https://Stackoverflow.com/questions/62919733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5834711/"
] | If you don't know how to read the file, there are several methods as you can see [here](https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html) that you could use, so you can try one of them, e.g. `pd.read_csv()`.
Once you have read the file, you could try this using pandas functions as `pd.DataFrame.groupby`... | ```
import pandas as pd
filename = "data.txt"
df = pd.read_fwf(filename)
df.groupby(['id']).mean()
```
Output
```
value
id
1 13.566667
2 12.450000
3 10.266667
4 12.375000
5 12.350000
``` | 10,304 |
15,316,886 | I'm new to python and would like to take this
```
K=[['d','o','o','r'], ['s','t','o','p']]
```
to print:
```
door, stop
``` | 2013/03/09 | [
"https://Stackoverflow.com/questions/15316886",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2152618/"
] | How about:
`', '.join(''.join(x) for x in K)` | Using `str.join()` and `map()`:
```
In [26]: K=[['d','o','o','r'], ['s','t','o','p']]
In [27]: ", ".join(map("".join,K))
Out[27]: 'door, stop'
```
>
> S.join(iterable) -> string
>
>
> Return a string which is the concatenation of the strings in the
> iterable. The separator between elements is S.
>
>
> | 10,305 |
30,331,919 | Can someone explain why the following occurs? My use case is that I have a python list whose elements are all numpy ndarray objects and I need to search through the list to find the index of a particular ndarray obj.
Simplest Example:
```
>>> import numpy as np
>>> a,b = np.arange(0,5), np.arange(1,6)
>>> a
array([0,... | 2015/05/19 | [
"https://Stackoverflow.com/questions/30331919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2383529/"
] | Applying the idea in <https://stackoverflow.com/a/17703076/901925> (see the Related sidebare)
```
[np.array_equal(b,x) for x in l].index(True)
```
should be more reliable. It ensures a correct array to array comparison.
Or `[id(b)==id(x) for x in l].index(True)` if you want to ensure it compares ids. | The idea is to convert numpy arrays to lists and transform the problem to finding a list in an other list:
```py
def find_array(list_of_numpy_array,taregt_numpy_array):
out = [x.tolist() for x in list_of_numpy_array].index(taregt_numpy_array.tolist())
return out
``` | 10,306 |
53,723,025 | I have anaconda installed, and I use Anaconda Prompt to install python packages. But I'm unable to install RASA-NLU using conda prompt. Please let me know the command for the same
I have used the below command:
```
conda install rasa_nlu
```
Error:
```
PackagesNotFoundError: The following packages are not availab... | 2018/12/11 | [
"https://Stackoverflow.com/questions/53723025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7905329/"
] | Turns out the framework search path (under Project->Target->Build Settings) was indeed the culprit. Removing my custom overrides solved the issue. Interestingly, if I remember correctly, I had added them, because Xcode wasn't able to find my frameworks...
See also <https://forums.developer.apple.com/message/328635#328... | Set "Always Search User Paths" to NO and problem will be solved | 10,307 |
68,299,665 | I am new to using webdataset library from pytorch. I have created .tar files of a sample dataset present locally in my system using webdataset.TarWriter(). The .tar files creation seems to be successful as I could extract them separately on windows platform and verify the same dataset files.
Now, I create `train_datas... | 2021/07/08 | [
"https://Stackoverflow.com/questions/68299665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2562870/"
] | I have had the same error since yesterday, I finally found the culprit. [WebDataset/tarIterators.py](https://github.com/webdataset/webdataset/blob/master/webdataset/tariterators.py) makes use of [WebDataset/gopen.py](https://github.com/webdataset/webdataset/blob/master/webdataset/gopen.py). In gopen.py `urllib.parse.ur... | Add "file:" in the front of local file path, like this:
```
from itertools import islice
import webdataset as wds
import os
import tqdm
path = "file:D:/Dataset/00000.tar"
dataset = wds.WebDataset(path)
for sample in islice(dataset, 0, 3):
for key, value in sample.items():
print(key, repr(value)[:50])
... | 10,308 |
66,178,922 | I am trying to run Django tests on Gitlab CI but getting this error, Last week it was working perfectly but suddenly I am getting this error during test run
>
> django.db.utils.OperationalError: could not connect to server: Connection refused
> Is the server running on host "database" (172.19.0.3) and accepting
> TCP... | 2021/02/12 | [
"https://Stackoverflow.com/questions/66178922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15200334/"
] | Unsure if it would help in your case but I was getting the same issue with docker-compose. What solved it for me was explicitly specifying the hostname for postgres.
```
services:
database:
image: postgres:12-alpine
hostname: database
environment:
- POSTGRES_DB=test
- POSTGRES_USER=test
... | Could you do a `docker container ls` and check if the container name of the database is in fact, "database"?
You've skipped setting the `container_name` for that container, and it may be so that docker isn't creating it with the default name of the service, i.e. "database", thus the DNS isn't able to find it under that... | 10,309 |
44,130,318 | env:linux + python3 + rornado
When i run client.py,he suggested that my connection was rejected, for a few ports,Using the 127.0.0.1:7233,The server does not have any response, but the client prompts to refuse to connect,Who can tell me why?
server.py
```
# coding:utf8
import socket
import time
import threading
# ... | 2017/05/23 | [
"https://Stackoverflow.com/questions/44130318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5472490/"
] | Are the `featured_value_id` array values unique inside the array? If not does it make a difference if you give the planner a little hand by making them unique?:
```
select distinct c.id
from
dematerialized_products
cross join lateral
(
select distinct id
from unnest(feature_value_ids) u (id... | You didn't show execution plans, but obviously the time is spent sorting the values to eliminate doubles.
If `EXPLAIN (ANALYZE)` shows that the sort is performed using temporary files, you can improve the performance by raising `work_mem` so that the sort can be performed in memory.
You will still experience a perfor... | 10,311 |
74,428,888 | `polars.LazyFrame.var` will return variance value for each column in a table as below:
```
>>> df = pl.DataFrame({"a": [1, 2, 3, 4], "b": [1, 2, 1, 1], "c": [1, 1, 1, 1]}).lazy()
>>> df.collect()
shape: (4, 3)
┌─────┬─────┬─────┐
│ a ┆ b ┆ c │
│ --- ┆ --- ┆ --- │
│ i64 ┆ i64 ┆ i64 │
╞═════╪═════╪═════╡
│ 1 ┆ 1... | 2022/11/14 | [
"https://Stackoverflow.com/questions/74428888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20497072/"
] | polars doesn't know what the variance is until after it is calculated but that's the same time that it is displaying the results so there's no way to filter the columns reported and also have it be more performant than just displaying all the columns, at least with respect to the polars calculation. It could be that py... | Building on the answer from @dean MacGregor, we:
* do the var calculation
* melt
* apply the filter
* extract the `variable` column with column names
* pass it as a list to `select`
```py
df.select(
(
df.var().melt().filter(pl.col('value')>0).collect()
["variable"]
)
.to_list()
).... | 10,312 |
16,748,592 | I'm trying to build a simple Scapy script which manually manages 3-way-handshake, makes an HTTP GET request (by sending a single packet) to a web server and manually manages response packets (I need to manually send ACK packets for the response).
Here is the beginning of the script:
```
#!/usr/bin/python
import logg... | 2013/05/25 | [
"https://Stackoverflow.com/questions/16748592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1194426/"
] | Use sr(), read the data in from every ans that is received (you'll need to parse, as you go, the Content-Length or the chunk lengths depending on whether you're using transfer chunking) then send ACKs in response to the *last* element in the ans list, then repeat until the end criteria is satisfied (don't forget to inc... | Did you try:
```
responce = sr1(request)
print responce.show2
```
Also try using a different sniffer like wireshark or tcpdump as netcat has a few bugs. | 10,313 |
57,327,185 | I'm using Telethon in python to automatic replies in Telegram's Group. I wanna reporting spam or abuse an account automatically via the Telethon and I read the Telethon document and google it, but I can't find any example.
If this can be done, please provide an example with a sample code. | 2019/08/02 | [
"https://Stackoverflow.com/questions/57327185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5704891/"
] | `display: flex;`
This CSS property will make all child inline element.
```
<div style="display:flex; flex-direction: row;">
<div>1</div>
<div>2</div>
</div
```
This is an example of inline child.
for more info please Check this link [CSS Flexbox Layout](https://www.w3schools.com/css/css3_flexbox.asp) | Can you describe what do you mean by "when the "Add Dates" button is pressed I want another line be available." ?
In any case, when trying to inline two objects, you should put style="display: inline" property onto very element you want to be displayed inline. Thus, try to add style="display: inline" property on eleme... | 10,316 |
66,510,970 | I've tried relentlessly for about 1-2hrs to get this piece of code to work. I need to add the role to a user, simple enough right?
This code, searches for the role but cannot find it, is this because I am sending it from a channel which that role doesn't have access to? I need help please.
Edit 1: removed quotations ... | 2021/03/06 | [
"https://Stackoverflow.com/questions/66510970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15250234/"
] | Use `in_array` and looking for last character in array:
```
if (in_array(substr($var, -1, 1), ['s', 'z']))
``` | Or maybe:
```
in_array(array_pop(explode('', $var)), ['s', 'z'])` ?
```
not really much more readable neither gallant, but what do I know? :) | 10,319 |
49,510,815 | I am trying to create a class that returns the class name together with the attribute. This needs to work both with instance attributes and class attributes
```
class TestClass:
obj1 = 'hi'
```
I.e. I want the following (note: both with and without class instantiation)
```
>>> TestClass.obj1
('TestClass', 'hi')... | 2018/03/27 | [
"https://Stackoverflow.com/questions/49510815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9490769/"
] | I got help from a colleague for defining meta classes, and came up with the following solution
```
class MyMeta(type):
def __new__(mcs, name, bases, dct):
c = super(MyMeta, mcs).__new__(mcs, name, bases, dct)
c._member_names = []
for key, value in c.__dict__.items():
if type(val... | Way 1
-----
You can use [`classmethod`](https://www.programiz.com/python-programming/methods/built-in/classmethod) decorator to define methods callable at the whole class:
```
class TestClass:
_obj1 = 'hi'
@classmethod
def obj1(cls):
return cls.__name__, cls._obj1
class TestSubClass(TestClass):
... | 10,324 |
40,615,604 | I am looking for a nice, efficient and pythonic way to go from something like this:
`('zone1', 'pcomp110007')`
to this:
`'ZONE 1, PCOMP 110007'`
without the use of `regex` if possible (unless it does make a big difference that is..). So turn every letter into uppercase, put a space between letters and numbers and j... | 2016/11/15 | [
"https://Stackoverflow.com/questions/40615604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6162307/"
] | Using `re`:
```
import re
tupl = ('zone1', 'pcomp110007')
", ".join(map(lambda x: " ".join(re.findall('([A-Z]+)([0-9])+',x.upper())[0]), tupl))
#'ZONE 1, PCOMP 7'
``` | A recursive solution:
```
def non_regex_split(s,i=0):
if len(s) == i:
return s
try:
return '%s %d' %(s[:i], int(s[i:]))
except:
return non_regex_split(s,i+1)
', '.join(non_regex_split(s).upper() for s in tags)
``` | 10,325 |
23,407,824 | I am building a website with django for months. So now i thought its time to test it with some friend. While deploying it to a Ubuntu 14.4 64bit LTS ( Same as development environment ) i found a strange error.
Called
```
OSError at /accounts/edit/
[Errno 21] Is a directory: '/var/www/media/'
```
I also tried with ... | 2014/05/01 | [
"https://Stackoverflow.com/questions/23407824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2665252/"
] | Looks like `profile.avatar.name` evaluates to a **blank string**
So No file is being provided to `os.remove` to remove and It **can't remove a directory** and **raises OSError** : See here: <https://docs.python.org/2/library/os.html#os.remove>
You can rectify this error by **applying a conditional**, which is what to... | This just happened to me for another reason. Answering here in case it is not the situation above.
I had a file named "admin" in my static folder, which matched the directory "admin" where Django's admin app stores its static files.
When running `collectstatic` it would conflict between those two. I had to remove my ... | 10,335 |
73,401,346 | In the following code I am having a problem, the log file should get generated each day with timestamp in its name. Right now the first file has name as **dashboard\_asset\_logs** and then other subsequent log files come as **dashboard\_asset\_logs.2022\_08\_18.log, dashboard\_asset\_logs.2022\_08\_19.log**.
How can t... | 2022/08/18 | [
"https://Stackoverflow.com/questions/73401346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8838167/"
] | In short, you will have to write your own `TimedRotatingFileHandler` implementation to make it happen.
The more important question is why you need it? File name without date is a file with log from the current day and this log is incomplete during the day. When log is rotated at midnight, old file (the one without the ... | You might be able to use the `namer` property of the handler, which you can set to a callable to customise naming. See [the documentation](https://docs.python.org/3/library/logging.handlers.html#logging.handlers.BaseRotatingHandler.namer) for it. | 10,336 |
27,656,401 | I've got rather small flask application which I run using:
```
$ python wsgi.py
```
When editing files, server reloads on each file save. This reload takes even up to 10sec.
That's system section from my Virtual Box:
```
Base: 2048Mb,
Memory:
Processors: 4
Acceleration: VT-x/AMD-V, Nested Paging, PAE/NX
```
How ... | 2014/12/26 | [
"https://Stackoverflow.com/questions/27656401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2743105/"
] | Your problem might be virtualenv being sync'd too.
I stumbled upon the same problem, and the issue was that VirtualBox's default synchronization implementation is very very slow when dealing with too many files in the mounted directory. Upon investigating, I found:
```
$ cd my-project
$ tree | tail -n 1
220 director... | Try changing the file system for NFS. I had this problem, I switched to NFS and has been fixed.
```
config.vm.synced_folder ".", "/vagrant", type: "nfs"
```
[ENABLING NFS SYNCED FOLDERS](http://docs.vagrantup.com/v2/synced-folders/nfs.html) | 10,337 |
19,077,580 | I use python 2.7.5.
I have got some files in the directory/sub directory. Sample of the `file1` is given below
```
Title file name
path1 /path/to/file
options path2=/path/to/file1,/path/to/file2,/path/to/file3,/path/to/file4 some_vale1 some_vale2 some_value3=abcdefg some_value4=/path/to/value some_value5
```
... | 2013/09/29 | [
"https://Stackoverflow.com/questions/19077580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2221360/"
] | This one-liner does the entire transformation:
```
str = re.sub(r'(options) (\S+)', r'\2\n \1', str.replace('/path/', '/root/directory/path/')
```
See a [live demo](http://codepad.org/I5IpoYcW) of this code | You can try this:
```
result = re.sub(r'([ \t =,])/', replace_text, text, 1)
```
The last `1` is to indicate the first match only, so that only the first path is substituted.
By the way, I think that you want to conserve the space/tab or comma right? Make replace\_text like this:
```
replace_text = r'\1/root/direc... | 10,338 |
30,265,557 | I have a matrix with x rows (i.e. the number of draws) and y columns (the number of observations). They represent a distribution of y forecasts.
Now I would like to make sort of a 'heat map' of the draws. That is, I want to plot a 'confidence interval' (not really a confidence interval, but just all the values with s... | 2015/05/15 | [
"https://Stackoverflow.com/questions/30265557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2151205/"
] | So, the hard part of this is transforming your data into the right shape, which is why it's nice to share something that really looks like your data, not just a single column.
Let's say your data is this a matrix with 10,000 rows and 10 columns. I'll just use a uniform distribution so it will be a boring plot at the e... | That is not a lot to go on, but I would probably start with the `hexbin` or `hexbinplot` package. Several alternatives are presented in this SO post.
[Formatting and manipulating a plot from the R package "hexbin"](https://stackoverflow.com/questions/15504983/formatting-and-manipulating-a-plot-from-the-r-package-hexbi... | 10,340 |
38,729,374 | My `.profile` defines a function
```
myps () {
ps -aef|egrep "a|b"|egrep -v "c\-"
}
```
I'd like to execute it from my python script
```
import subprocess
subprocess.call("ssh user@box \"$(typeset -f); myps\"", shell=True)
```
Getting an error back
```
bash: -c: line 0: syntax error near unexpected token... | 2016/08/02 | [
"https://Stackoverflow.com/questions/38729374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/359862/"
] | ```
script='''
. ~/.profile # load local function definitions so typeset -f can emit them
ssh user@box ksh -s <<EOF
$(typeset -f)
myps
EOF
'''
import subprocess
subprocess.call(['ksh', '-c', script]) # no shell=True
```
---
There are a few pertinent items here:
* The dotfile defining this function needs to be loca... | The original command was not interpreting the `;` before `myps` properly. Using `sh -c` fixes that, but... ( please see Charles Duffy comments below ).
Using a combination of single/double quotes sometimes makes the syntax easier to read and less prone to mistakes. With that in mind, a safe way to run the command ( pr... | 10,341 |
21,083,746 | How do you cache a paginated Django queryset, specifically in a ListView?
I noticed one query was taking a long time to run, so I'm attempting to cache it. The queryset is huge (over 100k records), so I'm attempting to only cache paginated subsections of it. I can't cache the entire view or template because there are ... | 2014/01/13 | [
"https://Stackoverflow.com/questions/21083746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/247542/"
] | The problem turned out to be a combination of factors. Mainly, the result returned by the `paginate_queryset()` contains a reference to the unlimited queryset, meaning it's essentially uncachable. When I called `cache.set(mykey, (paginator, page, object_list, other_pages))`, it was trying to serialize thousands of reco... | I wanted to paginate my infinite scrolling view on my home page and this is the solution I came up with. It's a mix of Django CCBVs and the author's initial solution.
The response times, however, didn't improve as much as I would've hoped for but that's probably because I am testing it on my local with just 6 posts an... | 10,344 |
35,795,663 | **[What I want]** is to find the only one smallest positive real root of quartic function **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e**
**[Existing Method]**
My equation is for collision prediction, the maximum degree is quartic function as **f(x)** = **a**x^4 + **b**x^3 + **c**x^2 + **d**x + **e**
and **a,b,c,d,e**... | 2016/03/04 | [
"https://Stackoverflow.com/questions/35795663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6017946/"
] | An other answer :
do it with analytic methods ([Ferrari](https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Ferrari),[Cardan](https://fr.wikipedia.org/wiki/M%C3%A9thode_de_Cardan#Formules_de_Cardan)), and speed the code with Just in Time compilation ([Numba](http://numba.pydata.org)) :
Let see the improvement first :
```... | the numpy solution to do that without loop is :
```
p=array([a,b,c,d,e])
r=roots(p)
r[(r.imag==0) & (r.real>=0) ].real.min()
```
`scipy.optimize` methods will be slower, unless you don't need precision:
```
In [586]: %timeit r=roots(p);r[(r.imag==0) & (r.real>=0) ].real.min()
1000 loops, best of 3: 334 µs per loop... | 10,346 |
68,400,475 | I am trying to display a 2d list as CSV like structure in a new tkinter window
here is my code
```
import tkinter as tk
import requests
import pandas as pd
import numpy as np
from tkinter import messagebox
from finta import TA
from math import exp
import xlsxwriter
from tkinter import *
from tkinter.ttk import *
impo... | 2021/07/15 | [
"https://Stackoverflow.com/questions/68400475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15530206/"
] | The problem update 2 is that you are using pack and grid in the same window. When I click submit the new window comes up (I couldn't reproduce that problem) but the word "results" is missing. This is because you are trying to use pack and grid on the same window. To fix this, show "results" using grid like this:
```
c... | I've organized your imports. This should remove naming conflicts.
Note: You will have to declare `tkinter` objects with `tk.` and `ttk` objects with `ttk.` This should also help to remove naming conflicts.
```py
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import requests
import csv
i... | 10,351 |
61,529,832 | I have a python script called script.py that has two optional arguments (-a, -b) and has a single positional argument that either accepts a file or uses stdin. I want to make it so that a flag/file cannot be used multiple times. Thus, something like this shouldn't be allowed
```
./script.py -a 5 -a 7 test.txt
./script... | 2020/04/30 | [
"https://Stackoverflow.com/questions/61529832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12912748/"
] | @ajrwhite adding attachments had one trick, you need to use 'Alias' from mactypes to convert a string/path object to a mactypes path. I'm not sure why but it works.
here's a working example which creates messages with recipients and can add attachments:
```
from appscript import app, k
from mactypes import Alias
from... | Figured it out using [py-appscript](http://appscript.sourceforge.net/py-appscript/doc_3x/appscript-manual/03_quicktutorial.html)
```
pip install appscript
```
```
from appscript import app, k
outlook = app('Microsoft Outlook')
msg = outlook.make(
new=k.outgoing_message,
with_properties={
k.subject:... | 10,352 |
22,699,040 | I'm trying to pull the parsable-cite info from this [webpage](http://deepbills.cato.org/api/1/bill?congress=113&billnumber=499&billtype=s&billversion=is) using python. For example, for the page listed I would pull pl/111/148 and pl/111/152. My current regex is listed below, but it seems to return everything after parsa... | 2014/03/27 | [
"https://Stackoverflow.com/questions/22699040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1153018/"
] | I highly recommend to use this regex which will capture what you want:
```
re.findall(r'parsable-cite=\\\"(.*?)\\\"\>',page)
```
explanation:
```
parsable-cite= matches the characters parsable-cite= literally (case sensitive)
\\ matches the character \ literally
\" matches the character " literally
1st Captur... | Make your regex lazy:
```
re.findall(r'^parsable-cite=.*?>$',page)
^
```
Or use a negated class (preferable):
```
re.findall(r'^parsable-cite=[^>]*>$',page)
```
`.*` is greedy by default and will try to match as much as possible before concluding a match.
[regex101 demo](http://rege... | 10,355 |
45,954 | I'm working on a utility which needs to resolve hex addresses to a symbolic function name and source code line number within a binary. The utility will run on Linux on x86, though the binaries it analyzes will be for a MIPS-based embedded system. The MIPS binaries are in ELF format, using DWARF for the symbolic debuggi... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4761/"
] | You might be interested in the DWARF library from [pydevtools](http://code.google.com/p/pydevtools/):
```
>>> from bintools.dwarf import DWARF
>>> dwarf = DWARF('test/test')
>>> dwarf.get_loc_by_addr(0x8048475)
('/home/emilmont/Workspace/dbg/test/main.c', 36, 0)
``` | I don't know of any, but if all else fails you could use [ctypes](http://docs.python.org/lib/module-ctypes.html) to directly use libdwarf, libelf or libbfd. | 10,361 |
45,107,439 | This is more a question out of interest.
I observed the following behaviour and would like to know why / how this happens (tried in python 2.7.3 & python 3.4.1)
```
ph = {1:0, 2:0}
d1 = {'a':ph, 'b':ph}
d2 = {'a':{1:0,2:0},{'b':{1:0,2:0}}
>>> d1
{'a':{1:0,2:0},{'b':{1:0,2:0}}
```
so d1 and d2 are the same.
However w... | 2017/07/14 | [
"https://Stackoverflow.com/questions/45107439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8308726/"
] | Try using [pythontutor](http://www.pythontutor.com). If you put your code into it you will see this:
[](https://i.stack.imgur.com/z3sr1.png)
You can see that as you suspected the dictionaries in `d1` are references to the same object, `ph`.
This mea... | Both keys in `d1` point to the same reference, so when you delete from `d1` it affects `ph` whether you reach it by `d1['a']` or `d1['b']` - you're getting to the same place.
`d2` on the other hand instantiates two separate objects, so you're only affecting one of those in your example.
Your workaround would be [`.de... | 10,370 |
69,687,722 | I wanna know how can i get **1 minute** gold price data **of a specific time and date interval** (such as an 1 houre interval in 18th october: 2021-10-18 09:30:00 to 2021-10-18 10:30:00) from yfinance or any other source in python?
my code is:
```
gold = yf.download(tickers="GC=F", period="5d", interval="1m")
```
i... | 2021/10/23 | [
"https://Stackoverflow.com/questions/69687722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4688178/"
] | Your call to `yfinance` returns a Pandas `DataFrame` with `datetime` as the index. We can use this to filter the dataframe to only entries between our `start` and `end` times.
```
import yfinance as yf
from datetime import datetime
gold = yf.download(tickers="GC=F", period="5d", interval="1m")
start = datetime(2021,... | Edit 2021-10-25
===============
To clear my answer. Question was:
>
> i wanna set specific date and time intervals. thanks
>
>
>
All you need is in the code documentation.
So `start` and `end` could be date or **\_datetime**
```
start: str
Download start date string (YYYY-MM-DD) or _datetime... | 10,371 |
59,819,633 | i want to login on instagram using selenium python. I tried to find elements by name, tag and css selector but selenium doesn't find any element (i think). I also tried to switch to the iFrame but nothing.
This is the error:
>
> Traceback (most recent call last):
> File "C:/Users/anton/Desktop/Instabot/chrome insta... | 2020/01/20 | [
"https://Stackoverflow.com/questions/59819633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12507302/"
] | You try to return an Object and this is not possible.
```
function Main(){
// create an array that holds objects
const people = [
{
firstName: 'Fathi',
lastName: 'Noor',
age: 27,
colors: ['red', 'blue'],
bodyAttributes: {
weig... | You have to `map` the array. See this [doc](https://reactjs.org/docs/lists-and-keys.html).
For each person, you decide how to display each field, here I used `<p>` tags, you can display them in a table, or in a custom card.. Your choice!
Remember that inside `{}` brackets goes Javascript expressions while in `()` go... | 10,372 |
50,091,373 | I am new to using Pandas on Windows and I'm not sure what I am doing wrong here.
My data is located at 'C:\Users\me\data\lending\_club\loan.csv'
```
path = 'C:\\Users\\me\\data\\lending_club\\loan.csv'
pd.read_csv(path)
```
And I get this error:
```
----------------------------------------------------------------... | 2018/04/29 | [
"https://Stackoverflow.com/questions/50091373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3971910/"
] | Just use forward slash(`'/'`) instead of backslash(`'\'`)
```
path = 'C:/Users/me/data/lending_club/loan.csv'
``` | Python only access to the current folder's files.
If you want to access files from an other folder, try this :
```
import sys
sys.path.insert(0, 'C:/Users/myFolder')
```
Those lines allow your script to access an other folder. Be carrefull, you shoud use slashes /, not backslashes \ | 10,374 |
51,947,506 | i have been trying to install module for python-3.6 through pip. i've read these post from stackoverflow and from python website, which seemed promising but they didn't worked for me.
[Install a module using pip for specific python version](https://stackoverflow.com/questions/10919569/install-a-module-using-pip-for-sp... | 2018/08/21 | [
"https://Stackoverflow.com/questions/51947506",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10088290/"
] | to install package for a specific python installation, you need a package installer shipped with that installation, in your case, `pip` is installed by an anaconda installation, use `pip.exe` or `easy_install.exe` from this python3.6 installation's `Scripts` directory instead. | First, Uninstall all the versions you have!
then go to the library <https://www.python.org/downloads/>
Select the required vesrsion MSI file. Run as administrator! | 10,375 |
42,776,294 | I need to extract list of IP addresses and port number as well as other information in the following html table, I am using python 2.7 with lxml currently, but have no idea how to find the proper path to these elements,
here is the address to table:
[link to table](https://hidester.com/proxylist/) | 2017/03/14 | [
"https://Stackoverflow.com/questions/42776294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1624681/"
] | Looking at the examples at [github](https://github.com/kivy/kivy/search?utf8=%E2%9C%93&q=background_color "github") it seems the values aren't 0-255 RGB like you might expect but are 0.0-1.1
```
bubble.background_color = (1, 0, 0, .5) #50% translucent red
background_color: .8, .8, 0, 1
```
etc.
You'll probably need... | delete background\_normal: ' ', just use background\_color: (R, G, B, A) pick a color in this [tool](https://developer.mozilla.org/es/docs/Web/CSS/CSS_Colors/Herramienta_para_seleccionar_color) and divide R, G and B by 100 A=always 1 (transparency), for example if you choose (255, 79, 25, 1) write instead (2.55, 0.79, ... | 10,377 |
21,821,045 | I want to get a buffer from a numpy array in Python 3.
I have found the following code:
```
$ python3
Python 3.2.3 (default, Sep 25 2013, 18:25:56)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> a = numpy.arange(10)
>>> numpy.getbuffer(a)
```
Howeve... | 2014/02/17 | [
"https://Stackoverflow.com/questions/21821045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/856504/"
] | According to [Developer notes on the transition to Python 3](https://github.com/numpy/numpy/blob/master/doc/Py3K.rst.txt#pybuffer-object):
>
> PyBuffer (object)
>
>
> Since there is a native buffer object in Py3, the `memoryview`, the
> `newbuffer` and **`getbuffer` functions are removed from multiarray in Py3**:
... | Numpy's [`arr.tobytes()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tobytes.html) seems to be significantly faster than [`bytes(memoryview(arr))`](https://docs.python.org/dev/library/stdtypes.html#memoryview) in returning a `bytes` object.
So, you may want to have a look at `tobytes()` as well.
... | 10,378 |
10,830,820 | I need to backup various file types to GDrive (not just those convertible to GDocs formats) from some linux server.
What would be the simplest, most elegant way to do that with a python script? Would any of the solutions pertaining to GDocs be applicable? | 2012/05/31 | [
"https://Stackoverflow.com/questions/10830820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/303295/"
] | You can use the Documents List API to write a script that writes to Drive:
<https://developers.google.com/google-apps/documents-list/>
Both the Documents List API and the Drive API interact with the same resources (i.e. same documents and files).
This sample in the Python client library shows how to upload an unconv... | The current documentation for saving a file to google drive using python can be found here:
<https://developers.google.com/drive/v3/web/manage-uploads>
However, the way that the google drive api handles document storage and retrieval does not follow the same architecture as POSIX file systems. As a result, if you wish... | 10,379 |
42,852,722 | I'm iterating through such a feed:
```
{"siri":{"serviceDelivery":{"responseTimestamp":"2017-03-14T18:37:23Z","producerRef":"IVTR_RELAIS","status":"true","estimatedTimetableDelivery":[
{"lineRef":{"value":"C01742"},"directionRef":{"value":""},"datedVehicleJourneyRef":{"value":"SNCF-ACCES:VehicleJourney::UPAL97_2017031... | 2017/03/17 | [
"https://Stackoverflow.com/questions/42852722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5689072/"
] | See the code snippet
```
public static class MyDownloadTask extends AsyncTask<Void, Integer, Void> {
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// receive the published update here
// progressBar.setProgress(values[0]);
}
@O... | With this example you can set download speed on your progressdialog
```
public class AsyncDownload extends AsyncTask<Void, Double, String> {
ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.thi... | 10,381 |
22,923,983 | I am embedding python code in my c++ program.
The use of PyFloat\_AsDouble is causing loss of precision. It keeps only up to 6 precision digits. My program is very sensitive to precision. Is there a known fix for this?
Here is the relevant C++ code:
```
_ret = PyObject_CallObject(pFunc, pArgs);
vector<double> retVals... | 2014/04/07 | [
"https://Stackoverflow.com/questions/22923983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249560/"
] | Assuming that the Python object contains floating point values stored to double precision, then your code works as you expect.
Most likely you are simply mis-diagnosing a problem that does not exist. My guess is that you are looking at the values in the debugger which only displays the values to a limited precision. O... | print type(PyList\_GetItem(\_ret, i))
My bet is it will show float.
Edit: in the python code, not in the C++ code. | 10,382 |
44,576,509 | I am having a problem like
```
In [5]: x = "this string takes two like {one} and {two}"
In [6]: y = x.format(one="one")
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-6-b3c89fbea4d3> in <module>()
-... | 2017/06/15 | [
"https://Stackoverflow.com/questions/44576509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3282434/"
] | you can escape the interpolation of `{two}` by doubling the curly brackets:
```
x = "this string takes two like {one} and {{two}}"
y = x.format(one=1)
z = y.format(two=2)
print(z) # this string takes two like 1 and 2
```
---
a different way to go are [template strings](https://docs.python.org/3/library/string.html#... | You can replace `{two}` by `{two}` to enable further replacement later:
```
y = x.format(one="one", two="{two}")
```
This easily extends in multiple replacement passages, but it requires that you give all keys, in each iteration. | 10,383 |
32,703,469 | I am new to kafka. We are trying to import data from a csv file to Kafka. We need to import everyday, in the mean while the previous day's data is depredated.
How could remove all messages under a Kafka topic in python? or how could I remove the Kafka topic in python?
Or I saw someone suggest to wait to data expire, ho... | 2015/09/21 | [
"https://Stackoverflow.com/questions/32703469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1028315/"
] | You cannot delete messages in Kafka topic. You can:
* Set `log.retention.*` properties which is basically the expiration of messages. You can choose either time-based expiration (e. g. keep messages that are six hour old or newer) or space-based expiration (e. g. keep at max 1 GB of messages). See [Broker config](http... | The simplest approach is to simply delete the topic. I use this in Python automated test suites, where I want to verify a specific set of test messages gets sent through Kafka, and don't want to see results from previous test runs
```
def delete_kafka_topic(topic_name):
call(["/usr/bin/kafka-topics", "--zookeeper"... | 10,392 |
43,214,036 | I've a python script that I'm invoking from C#. Code Provided below. Issue with this process is that if Python script fails I'm not able to understand in C# and display that exception. I'm using C#, MVC, Python. Can you please modify below code and show me how can I catch the exception thrown at the time of Python Scri... | 2017/04/04 | [
"https://Stackoverflow.com/questions/43214036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4879531/"
] | Here is the working code.. To get the error or any exception in Python to C# RedirectStandardError property true and next get the Standard Error. Working version of the code is provided below -
```
process.StartInfo = processStartInfo;
processStartInfo.RedirectStandardError = true;
... | You can subscribe for `ErrorDataReceived` event and read the error message.
```
process.ErrorDataReceived+=process_ErrorDataReceived;
```
and here is your event handler
```
void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
``` | 10,393 |
37,947,258 | Newbie in mongodb/python/pymongo. My mongodb client code works OK. Here it is :
```
db.meteo.find().forEach( function(myDoc) {
db.test.update({"contract_name" : myDoc.current_observation.observation_location.city},
{ $set: { "temp_c_meteo" : myDoc.current_observation.temp_c ,
... | 2016/06/21 | [
"https://Stackoverflow.com/questions/37947258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6494503/"
] | Try this solution:
```
ArrayList<IonicBond> list = IonicBond.where { typeRs { classCode == "WD996" } || typeIIs { classCode == "WD996" } }.list()
``` | Detached Criteria is one way to query the GORM. You first create a DetachedCriteria with the name of the domain class for which you want to execute the query. Then you call the method 'build' with a 'where' query or criteria query.
```
def criteria = new DetachedCriteria(IonicBond).build {
or {
typeI... | 10,395 |
19,252,087 | Hi all we are using google api for e.g. this one '<http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s>' % query via python script but very fast it gets blocked. Any work around for this? Thank you.
Below is my current codes.
```
#!/usr/bin/env python
import math,sys
import json
import urllib
def gsearch(s... | 2013/10/08 | [
"https://Stackoverflow.com/questions/19252087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2711681/"
] | Try this:
```
$(".profileImage").click(function() {
$(this).animate({opacity: "0.0"}).animate({width: 0}).hide(0);
})
```
Animate your opacity to 0 to fade it from view, then animate your width to 0 to regain the space, then hide it to remove it from visibility altogether. Note that if you want to redisplay, you... | what about using the fadeOut callback
```
$(".profileImage").click(function() {
$(this).animate({opacity:0},400, function(){
// sliding code goes here
$(this).animate({width:0},300).hide();
});
});
``` | 10,397 |
67,764,659 | I working with vscode for python programming.how can i change color text error output in terminal?
.can you help me? | 2021/05/30 | [
"https://Stackoverflow.com/questions/67764659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11847527/"
] | may be useful for someOne.
for First and last day of Persian Month :
```
function GetStartEndMonth(currentDate) {
const splitDate = splitGeorgianDateToPersianDateArray(currentDate);
const year = splitDate[0];
const month = splitDate[1];
const lastDayOfPersianMonth = GetLastDayOfPersianMonth(month, ... | I think you need to set
```
dayGridMonthPersian :{duration: { week: 4 }}
``` | 10,398 |
53,489,173 | I understand there are many answers already on SO dealing with split python URL's. BUT, I want to split a URL and then use it in a function.
I'm using a curl request in python:
```
r = requests.get('http://www.datasciencetoolkit.org/twofishes?query=New%York')
r.json()
```
Which provides the following:
```
{'interp... | 2018/11/26 | [
"https://Stackoverflow.com/questions/53489173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9439560/"
] | Taking your example, I'd suggest using regex and string interpolation. This answer assumes the API returns data the same way every time.
```
import re, requests
def lat_long(city: str) -> tuple:
# replace spaces with escapes
city = re.sub('\s', '%20', city)
res = requests.get(f'http://www.datasciencetoolk... | You can loop over this list 'interpretations' looking for the city name, and return the coordinates when you find the correct city.
```
def lat_long(city):
geocode_result = requests.get('http://www.datasciencetoolkit.org/twofishes?query= "city"')
for interpretation in geocode_result["interpretations"]:
... | 10,399 |
29,000,392 | When I Try to use the sorted() function in python it only sorts the elements within each array alphabetically as the first 3 outputs are:
```
[u'A', u'a', u'a', u'f', u'g', u'h', u'i', u'n', u'n', u's', u't']
[u'N', u'a', u'e', u'g', u'i', u'i', u'r']
[u'C', u'a', u'e', u'm', u'n', u'o', u'o', u'r']
```
These shoul... | 2015/03/12 | [
"https://Stackoverflow.com/questions/29000392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3092868/"
] | As far as I'm concerned, the built in VBE is the best way to go. It has not changed in the last 10 years or even longer, but it is tightly integrated into Excel and does everything you need, especially as a beginner. | some time passed since you asked, but maybe someone else might find it useful. I looked for the same thing and couldn't find anything good until I found Notepad++.
It makes analyzing the code much easier. | 10,400 |
31,388,514 | I have to split a list of characters such that it gets cut when it encounters a vowel. For example, a string like
```
toy = ['b', 'a', 'm', 'b', 'i', 'n', 'o']
```
the output should be
```
[('b', 'a'), ('m', 'b', 'i'), ('n', 'o')]
```
I tried to run 2 loops, one behind the other.
```
# usr/bin/env/python
appl... | 2015/07/13 | [
"https://Stackoverflow.com/questions/31388514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3116297/"
] | You seem to be overcomplicating things. A simple solution for this would be -
```
>>> toy = ['b', 'a', 'm', 'b', 'i', 'n', 'o']
>>> vowels = ['a','i','e','o','u']
>>> apples = []
>>> k = 0
>>> for i ,x in enumerate(toy):
... if x in vowels:
... apples.append(tuple(toy[k:i+1]))
... k = i+1
.... | You could also use this :
```
#usr/bin/env/python
apple = []
vowels = ('i', 'a', 'u')
toy = ('k', 'h', 'u', 'b', 'a', 'n', 'i')
collector = []
for i in toy:
collector.append(i)
if i in vowels:
apple.append(collector)
collector = []
print apple
```
Result:
```
[['k', 'h', 'u'], ['b', 'a'], ... | 10,401 |
13,608,029 | I have 365 2d `numpy` arrays for the every day of the year, displaying an image like this:

I have them all stacked in a 3d numpy array. Pixels with a value that represents cloud i want to get rid of, i want to search through the previous 7 da... | 2012/11/28 | [
"https://Stackoverflow.com/questions/13608029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1860229/"
] | You are essentially trying to write a filter for your array.
First you need to write a function that when given an array of values, with the middle one being the element currently examined, will return some computation of those values. In your case the function will expect to take 1-d array and returns the element nea... | I would think that you could do something like:
```
data = somehow_get_your_3d_data() #indexed as [day_of_year,y,x]
for i,dat in enumerate(data):
weeks2 = data[max(i-7,i):min(i+7,len(data)), ... ]
new_value = get_new_value(weeks2) #get value from weeks2 here somehow
dat[dat == cloud_value] = new_value
``` | 10,403 |
71,401,616 | While writing a program to help myself study, I run into a problem with my program not displaying the Chinese characters properly.
The Chinese characters are loaded in from a .JSON file, and are then printed using a python program.
The JSON entries look like this.
```
{
"symbol": "我",
"reading": "wo",
"meaning... | 2022/03/08 | [
"https://Stackoverflow.com/questions/71401616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15465144/"
] | An example creating a precompiled header:
```sh
mkdir -p pch/bits &&
g++ -O3 -std=c++20 -pedantic-errors -o pch/bits/stdc++.h.gch \
/usr/include/c++/11/x86_64-redhat-linux/bits/stdc++.h
```
Check what you got:
```sh
$ file pch/bits/stdc++.h.gch
pch/bits/stdc++.h.gch: GCC precompiled header (version 014) for C++
... | Building on Ted's answer, I would actually do something like this (untested):
my\_pch.h:
```
#include <bits/stdc++.h> // might need to specify the full path here
```
And then:
```
g++ -O3 -std=c++20 -pedantic-errors -o pch/bits/my_pch.h.gch my_pch.h
```
And finally, your program would look like this:
`... | 10,405 |
17,504,570 | So, I'm on simple project for a online course to make an image gallery using python. The thing is to create 3 buttons one Next, Previous and Quit. So far the quit button works and the next loads a new image but in a different window, I'm quite new to python and GUI-programming with Tkinter so this is a big part of the ... | 2013/07/06 | [
"https://Stackoverflow.com/questions/17504570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2475520/"
] | Change image by setting image item: `Label['image'] = photoimage_obj`
```
import Image
import ImageTk
import Tkinter
image_list = ['1.jpg', '2.jpg', '5.jpg']
text_list = ['apple', 'bird', 'cat']
current = 0
def move(delta):
global current, image_list
if not (0 <= current + delta < len(image_list)):
t... | My UI is not so good. But my logics works well i tested well. U can change the UI. How it works is, First we need to browse the file and when we click open it displays the image and also it will creates a list of images that are in that selected image folder. I mentioned only '.png' and '.jpg' fils only. If u want to a... | 10,410 |
64,774,439 | I'm trying to install some packages, and for some reason I can't for the life of me make it happen. My set up is that I'm using PyCharm on Windows with Conda. I'm having these problems with all the non-standard packages I'd like to install (things like numpy install just fine), but for reference I'll use [this](https:/... | 2020/11/10 | [
"https://Stackoverflow.com/questions/64774439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5559681/"
] | You should do sth like [installation package from git](https://stackoverflow.com/questions/20101834/pip-install-from-git-repo-branch) , but for conda. (replace pip with conda, and provide valid URL). This is not a pypi package, it is not known to pip by default. | In response to @buran's comments above, I updated conda using
`conda update --name base conda`
Then used the recommended install for Windows, with
```
conda install -c wmayner pyphi
```
which now gives the error:
```
Found conflicts! Looking for incompatible packages.
This can take several minutes. Press CTRL-C ... | 10,411 |
41,850,809 | ```
import datetime
from nltk_contrib import timex
now = datetime.date.today()
basedate = timex.Date(now.year, now.month, now.day)
print timex.ground(timex.tag("Hai i would like to go to mumbai 22nd of next month"), basedate)
print str(datetime.date.day)
```
when i am trying to run the above code i am getting the ... | 2017/01/25 | [
"https://Stackoverflow.com/questions/41850809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7334656/"
] | The `timex` module has a bug where a global variable is referenced without assignment in the `ground` function.
To fix the bug, add the following code which should start at line 171:
def ground(tagged\_text, base\_date):
```
# Find all identified timex and put them into a list
timex_regex = re.compile(r'<TIMEX2>.*?<... | The solution above about adding month as a global variable causes other problems when timex is called multiple times in a row, because variables are not reset unless you import again. This happens for me in a deployed environment in AWS Lambda.
A solution that isn't super pretty but will not cause problems is just to ... | 10,412 |
8,399,341 | I can't find any tutorial for jQuery + web.py.
So I've got basic question on POST method.
I've got jQuery script:
```
<script>
jQuery('#continue').click(function() {
var command = jQuery('#continue').attr('value');
jQuery.ajax({
type: "POST",
data: {signal : command}... | 2011/12/06 | [
"https://Stackoverflow.com/questions/8399341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1073589/"
] | you need to use web.input in web.py to access POST variables
look at the docs: <http://webpy.org/docs/0.3/api> (search for "function input")
```
def POST(self):
s = web.input().signal
print s
return
``` | ```
<script>
jQuery('#continue').click(function() {
var command = jQuery('#continue').attr('value');
jQuery.ajax({
type: "POST",
data: {signal : command},
url: "add the url here"
});
});
</script>
```
**add the url of the server.** | 10,413 |
42,237,103 | I'm writing a python program for the purpose of studying HTML source code used in different countries. I'm testing in a UNIX Shell. The code I have so far works fine, except that I'm getting [HTTP Error 403: Forbidden](https://i.stack.imgur.com/9gzqG.png). Through testing it line by line, I know it has something to do ... | 2017/02/14 | [
"https://Stackoverflow.com/questions/42237103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6115937/"
] | With jQuery you need to also provide the other transformation:
```
//Image Category size change effect
$('.cat-wrap div').hover(function() {
$(this).css('width', '30%');
$(this).children().css('opacity', '1');
$(this).siblings().css("width", "16.5%");
}, function() {
$(this).css('width', '19.2%');
$(this).... | For it to revert back, you need to add the handler for the mouseout event. This is simply passing a second callback argument to the `hover()` method.
```
$('.cat-wrap div').hover(function() {
$(this).css('width', '30%');
$(this).children().css('opacity','1');
$(this).siblings().css( "width", "16.5%");... | 10,414 |
44,181,879 | I believe that I have installed virtualenvwrapper incorrectly (the perils of following different tutorials for python setup).
I would like to remove the extension completely from my Mac OSX system but there seems to be no documentation on how to do this.
Does anyone know how to completely reverse the installation? It... | 2017/05/25 | [
"https://Stackoverflow.com/questions/44181879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7442842/"
] | ```
pip uninstall virtualenvwrapper
```
Or
```
sudo pip uninstall virtualenvwrapper
```
worked for me. | On windows - This works great
pip uninstall virtualenvwrapper-win | 10,417 |
38,129,357 | In the python difflib library, is the SequenceMatcher class behaving unexpectedly, or am I misreading what the supposed behavior is?
Why does the isjunk argument seem to not make any difference in this case?
```
difflib.SequenceMatcher(None, "AA", "A A").ratio() return 0.8
difflib.SequenceMatcher(lambda x: x in ' ',... | 2016/06/30 | [
"https://Stackoverflow.com/questions/38129357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5839052/"
] | This is happening because the `ratio` function uses total sequences' length while calculating the ratio, **but it doesn't filter elements using `isjunk`**. So, as long as the number of matches in the matching blocks results in the same value (with and without `isjunk`), the ratio measure will be the same.
I assume tha... | You can remove the characters from the string before sequencing it
```
def withoutJunk(input, chars):
return input.translate(str.maketrans('', '', chars))
a = withoutJunk('AA', ' ')
b = withoutJunk('A A', ' ')
difflib.SequenceMatcher(None, a, b).ratio()
# -> 1.0
``` | 10,418 |
58,674,723 | I have a new MacBook with fresh installs of everything which I upgraded to macOS Catalina. I installed homebrew and then pyenv, and installed Python 3.8.0 using pyenv. All these things seemed to work properly.
However, neither `pyenv local` nor `pyenv global` seem to take effect. Here are all the details of what I'm s... | 2019/11/02 | [
"https://Stackoverflow.com/questions/58674723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/783314/"
] | I added the following to my ~/.zprofile and got it working.
```
export PYENV_ROOT="$HOME/.pyenv/versions/3.7.3"
export PATH="$PYENV_ROOT/bin:$PATH"
``` | catalina (and OS X in general) uses `/etc/zprofile` to set the `$PATH` in advance of what you're specifying within the local dotfiles.
it uses the `path_helper` utility to specify the `$PATH` and i suspect this is overriding the shim injection in your local dotfiles. you can comment out the following lines in `/etc/zp... | 10,419 |
54,569,512 | I need to parse json file size of 200MB, at the end I would like to write data from the file in sqlite3 database. I have a working python code, but it takes around 9 minutes to complete the task.
```
@transaction.atomic
def create_database():
with open('file.json') as f:
data = json.load(f)
cve_i... | 2019/02/07 | [
"https://Stackoverflow.com/questions/54569512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9517224/"
] | ```
'ODataManifestModel>EntitySetForBoolean>booleanProperty'
```
A few things:
* your screenshot is probably wrong because you always need the entitySet name that can be found in the "folder" `Entity Sets` not the `Entity Type`. Although your name looks correct.
* you have to bind one element of the entitySet (array... | **mode** property from ListBase can have a the following properties (**None, SingleSelect, MultiSelect, Delete**) and it is applied to all the list elements | 10,426 |
56,793,083 | I am getting an error and I'm not sure what is causing the error to occur.
The error is:
```
Parts[n] = PN
IndexError: list assignment index out of range
```
The code I'm using is this. I'm pretty new to python and tried to look out similar problems but didn't seem to find anything exactly similar to this. Any help... | 2019/06/27 | [
"https://Stackoverflow.com/questions/56793083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10560733/"
] | If the chunks you need to upper are separated with `-` or `.` you may use
```
"Filename to UPPER_SNAKE_CASE": {
"prefix": "usc_",
"body": [
"${TM_FILENAME/\\.component\\.html$|(^|[-.])([^-.]+)/${1:+_}${2:/upcase}/g}"
],
"description": "Convert filename to UPPER_SNAKE_CASE dropping .component.ht... | Here is a pretty simple alternation regex:
```
"upcaseSnake": {
"prefix": "rf1",
"body": [
"${TM_FILENAME_BASE/(\\..*)|(-)|(.)/${2:+_}${3:/upcase}/g}",
"${TM_FILENAME/(\\..*)|(-)|(.)/${2:+_}${3:/upcase}/g}"
],
"description": "upcase and snake the filename"
},
```
Either version works.
`(\\..*)|(-)|... | 10,428 |
74,165,004 | i have 2d list implementation as follows. It shows no. of times every student topped in exams:-
```
list = main_record
['student1',1]
['student2',1]
['student2',2]
['student1',5]
['student3',3]
```
i have another list of unique students as follows:-
```
list = students_enrolled
['student1','student2... | 2022/10/22 | [
"https://Stackoverflow.com/questions/74165004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1028289/"
] | You define a `dict` base key of `studentX` and save the max value for each student `key` then sort the `students_enrolled` base max value of each key.
```
from collections import defaultdict
main_record = [['student1',1], ['student2',1], ['student2',2], ['student1',5], ['student3',3]]
students_enrolled = ['student1',... | If it is a 2D list it should look like this: `l = [["student1", 2], ["student2", 3], ["student3", 4]]`. To get the highest numeric value from the 2nd column you can use a loop like this:
```
numbers = []
for student in list:
numbers.append(student[1])
for num in numbers:
n = numbers.copy()
n.sort()
n.... | 10,429 |
51,903,617 | How can a check for list membership be inverted based on a boolean variable?
I am looking for a way to simplify the following code:
```python
# variables: `is_allowed:boolean`, `action:string` and `allowed_actions:list of strings`
if is_allowed:
if action not in allowed_actions:
print(r'{action} must be... | 2018/08/17 | [
"https://Stackoverflow.com/questions/51903617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191246/"
] | Compare the result of the test to `is_allowed`. Then use `is_allowed` to put together the correct error message.
```
if (action in allowed_actions) != is_allowed:
print(action, "must" if is_allowed else "must NOT", "be allowed!")
``` | Given the way your specific code is structured, I think the only improvement you can make is to just store `action in allowed_actions` in a variable:
```
present = action in allowed_actions
if is_allowed:
if not present:
print(r'{action} must be allowed!')
else:
if present:
print(r'{action} mu... | 10,430 |
18,033,700 | I generate lot of messages for sending to client (push notifications using push woosh). I collect messages for a period of time and the send a bucket of messages. Need advice, what is the best to use for queue python list ( I am afraid to store in memory lot of messages and to lose if server restarts), Redis or MySQL ? | 2013/08/03 | [
"https://Stackoverflow.com/questions/18033700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1800871/"
] | Redis can save the data contained in memory on your hard drive, so you don't have to be worried about to lose informations. And you can add a key expiration to your data saved in memory, so you can remove old messages.
Have a look here :
<http://redis.io/topics/persistence>
And here :
<http://redis.io/commands/expi... | I don't know what is the best from MySQL or Redis to process message queues since I don't know Redis.
But I could tell, MySQL is *not* designed for that purpose.
You should take a look at dedicated tools such as [RabitMQ](http://www.rabbitmq.com/) that will probably serve better your purpose. Here is a basic tutorial... | 10,431 |
34,939,762 | I have a function called `prepared_db` in submodule `db.db_1`:
```
from spam import db
submodule_name = "db_1"
func_name = "prepare_db"
func = ...
```
how can I get the function by the submodule name and function name in the context above?
**UPDATE**:
To respond @histrio 's answer, I can verify his code works for... | 2016/01/22 | [
"https://Stackoverflow.com/questions/34939762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/489564/"
] | It's simple. You can consider module as object.
```
import os
submodule_name = "path"
func_name = "exists"
submodule = getattr(os, submodule_name)
function = getattr(submodule, func_name)
function('/home') # True
```
or [just for fun, don't do that]
```
fn = reduce(getattr, ('sub1', 'sub2', 'sub3', 'fn'), module)... | I think I figured it out, you need to add the function to the `__all__` variable in the `__init__.py` file, so that would be something along the lines of:
```
from .db_1 import prepare_db
__all__ = ['prepare_db']
```
After that, it should work just fine. | 10,432 |
54,833,296 | I am using spyder python 2.7 and i changed the syntax coloring in Spyder black theme, but i really want my python programme to look in full black, so WITHOUT the white windows.
Can someone provide me a good explanation about how to change this?
[Python example of how i want it to be](https://i.stack.imgur.com/MO17A.... | 2019/02/22 | [
"https://Stackoverflow.com/questions/54833296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11103122/"
] | If you can't wait for Spyder 4 - this is what does it for **Spyder 3.3.2 in Windows, using Anaconda3**.
1. Exit Spyder
2. Open command prompt or Anaconda prompt
3. Run `pip install qdarkstyle` and exit the prompt
4. Go to ...\Anaconda3\Lib\site-packages\spyder\utils and open
*qhelpers.py*
5. Add `import qdarkstyle` to... | (*Spyder maintainer here*) This functionality will be available in Spyder **4**, to be released later in 2019. For now there's nothing you can do to get what you want with Spyder's current version, sorry. | 10,433 |
51,839,083 | I am using `MacOS`.
I used following command:
```
gcloud beta functions deploy start --runtime python37
--trigger-http --memory 2048MB --timeout 540s
```
But while deploying `google cloud functions` I got this error:
```
(gcloud.beta.functions.deploy) OperationError: code=3, message=Build failed: USER ERROR:
pi... | 2018/08/14 | [
"https://Stackoverflow.com/questions/51839083",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10223950/"
] | Do you have a Pipfile in your directory? I was able to replicate this same error when I tried to deploy a GCF containing a Pipfile but no accompanying Pipfile.lock. To fix, either remove Pipfile and just include requirements.txt, or generate Pipfile.lock:
`$ pipenv install` without the --skip-lock flag
While the curr... | According to the google cloud function [documentation](https://cloud.google.com/appengine/docs/standard/python3/runtime#dependencies) it only supports installing dependency from `requirements.txt` file.
And the file `Pipfile/Pipfile.lock` must not be present in the root directory. | 10,438 |
1,611,625 | I only just noticed this feature today!
```
s={1,2,3} #Set initialisation
t={x for x in s if x!=3} #Set comprehension
t=={1,2}
```
What version is it in? I also noticed that it has set comprehension. Was this added in the same version?
**Resources**
* [Sets in Python 2.4 Docs](http://docs.python.org/library/stdty... | 2009/10/23 | [
"https://Stackoverflow.com/questions/1611625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165495/"
] | The `sets` module was added in Python 2.3, but the built-in set type was added to the language in 2.4, with essentially the same interface. (As of 2.6, the `sets` module has been deprecated.)
So you can use sets as far back as 2.3, as long as you
```
import sets
```
But you will get a `DeprecationWarning` if you tr... | Well, testing it:
```
>>> s = {1, 2, 3}
File "<stdin>", line 1
s = {1, 2, 3}
^
SyntaxError: invalid syntax
```
I'm running 2.5, so I would assume that this syntax was added sometime in 2.6 (Update: actually added in 3.0, but Ian beat me). I should probably be upgrading sometime soon. I'm glad they ad... | 10,439 |
12,698,646 | How can I create a list of methods in python to be applied to an object?
Given some arbitrary class:
```
class someClass:
def __init__(self, s):
self.size = s
def shrink(self):
self.size -= 1
def grow(self):
self.size += 1
def invert(self):
self.size = -self.size
``... | 2012/10/02 | [
"https://Stackoverflow.com/questions/12698646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175133/"
] | You could create a list of the method *names* then use [`getattr()`](https://docs.python.org/3/library/functions.html#getattr) to access the methods:
```
instructions = ["shrink", "grow", "shrink"]
for i in instructions:
getattr(elephant, i)()
``` | Possibly naïvely:
```
for ins in instructions:
getattr(elephant, ins)()
```
Gotchas include that `ins` must be a string and that it's probably wise to validate both that `ins` is what you really want to call and that `getattr(elephant, ins)` is a callable. | 10,441 |
33,225,888 | I'm new to python. I had a difficult time understanding why the output would be 2 for the problem below. Can someone explain it to be in very basic terms.
```
a = [1, 2, 3, 4, 0]
b = [3, 0, 2, 4, 1]
c = [3, 2, 4, 1, 5]
print c[a[a[4]]]
``` | 2015/10/20 | [
"https://Stackoverflow.com/questions/33225888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5464930/"
] | Maybe it helps understanding splitting it in 3 rows ?
```
inner_one = a[4] # a[4] = 0
inner_two = a[inner_one] # a[0] = 1
result = c[inner_two] # c[1] = 2
``` | Python lists are 0-indexed. So your first call, `a[4]`, returns `0`, then `a[0]` returns `1`, and finally `c[1]` returns `2`. | 10,446 |
38,025,218 | I am running python 2.7 and django 1.8.
[I have this exact issue.](https://stackoverflow.com/questions/24983777/cant-add-a-new-field-in-migration-column-does-not-exist)
The answer, posted as a comment is: `What I did is completely remake the db, erase the migration history and folders.`
I am very uncertain about del... | 2016/06/25 | [
"https://Stackoverflow.com/questions/38025218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1261774/"
] | You can create a separate interface for your static needs:
```
interface IPerson {
name: string;
getName(): string;
}
class Person implements IPerson {
public name: string;
constructor(name: string) {
this.name = name;
}
public getName() {
return this.name;
}
public ... | I added `IPersonConstructor` to your example. The rest is identical; just included for clarity.
`new (arg1: typeOfArg1, ...): TypeOfInstance;` describes a class, since it can be invoked with `new` and will return an instance of the class.
```
interface IPerson {
name: string;
getName(): string;
}
class Perso... | 10,447 |
17,134,897 | i'm using the popular pythonscript ( <http://code.google.com/p/edim-mobile/source/browse/trunk/ios/IncrementalLocalization/localize.py> ) to localize my storyboards in ios5.
I did only some changes in storyboard and got this error:
>
> Please file a bug at <http://bugreport.apple.com> with this warning
> message an... | 2013/06/16 | [
"https://Stackoverflow.com/questions/17134897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | The second query is an example of an implicit cross join (aka Cartesian join) - every record from users will be joined to every record from roles with `id=5`, since all these combinations will have the `where` clause evaluate as true. | A join will be required to have correct data returned
```
SELECT u.username
FROM users u
JOIN roles r
ON u.roleid = r.id
WHERE r.id = 5;
```
I think is better to use explicit join with `ON` to dtermine which columns have relationship rather than using realtionship in `WHERE` clause | 10,449 |
63,336,300 | My Tensorflow model makes heavy use of data preprocessing that should be done on the CPU to leave the GPU open for training.
```
top - 09:57:54 up 16:23, 1 user, load average: 3,67, 1,57, 0,67
Tasks: 400 total, 1 running, 399 sleeping, 0 stopped, 0 zombie
%Cpu(s): 19,1 us, 2,8 sy, 0,0 ni, 78,1 id, 0,0 wa, ... | 2020/08/10 | [
"https://Stackoverflow.com/questions/63336300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9280994/"
] | Just setting the `set_intra_op_parallelism_threads` and `set_inter_op_parallelism_threads` wasn't working for me. Incase someone else is in the same place, after a lot of struggle with the same issue, below piece of code worked for me in limiting the CPU usage of tensorflow below 500%:
```
import os
import tensorflo... | There can be many issues for this, I solved it for me the following way:
Set
`tf.config.threading.set_intra_op_parallelism_threads(<Your_Physical_Core_Count>) tf.config.threading.set_inter_op_parallelism_threads(<Your_Physical_Core_Count>)`
both to your *physical* core count. You do not want Hyperthreading for highly... | 10,452 |
1,544,535 | I have to synchronize two different LDAP servers with different schemas. To make my life easier I'm searching for an object mapper for python like SQLobject/SQLAlchemy, but for LDAP.
I found the following packages via pypi and google that might provide such functionality:
* **pumpkin 0.1.0-beta1**:
Pumpkin is LDAP ORM... | 2009/10/09 | [
"https://Stackoverflow.com/questions/1544535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179014/"
] | If I were you I would either use python-ldap or ldaptor. Python-ldap is a wrapper for OpenLDAP so you may have problems with using it on Windows unless you are able to build from source.
LDAPtor, is pure python so you avoid that problem. Also, there is a very well written, and graphical description of ldaptor on the w... | Giving links to the projects in question would help a lot.
Being the developer of [Python LDAP Object Mapper](https://launchpad.net/python-ldap-om), I can tell that it is quite dead at the moment. If you (or anybody else) is up for taking it over, you're welcome :) | 10,453 |
45,321,425 | I am using python transitions module ([link](http://github.com/pytransitions/transitions)) to create finite state machine.
How do I run this finite state machine forever?
Bascically what I want is a fsm model which can stay "idle" when there is no more event to trigger.
For examplel, in example.py:
```
state = [ '... | 2017/07/26 | [
"https://Stackoverflow.com/questions/45321425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8368519/"
] | @BaptisteM, Instead of using AsyncTask for this you can use Handler and Runnable like this,
```
private void startColorTimer() {
mColorHandler.postDelayed(ColorRunnable, interval);
timerOn = true;
}
private Handler mColorHandler = new Handler();
private Runnable ColorRunnable = new Runnable() {
@Overrid... | The question have been asked, I started to answer it but a moderator closed it so I put my exemple here.
This exemple change randomly the color of a TextView every 1000ms.
The interval can be changed.
```
package com.your.package;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
... | 10,455 |
44,753,426 | I have a .csv file with two columns of interest 'latitude' and 'longitude' with populated values
I would like to return [latitude, longitude] pairs of each row from the two columns as lists...
[10.222, 20.445]
[10.2555, 20.119] ... and so forth for each row of my csv...
The problem with
>
import pandas
colnames = ... | 2017/06/26 | [
"https://Stackoverflow.com/questions/44753426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8124002/"
] | Most basic way
```
import csv
with open('filename.txt', 'r') as csvfile:
spamreader = csv.reader(csvfile)
for row in spamreader:
print row
``` | So from what I understand is that you want many lists of two elements: lat and long. However what you are receiving is two lists, one of lat and one of long. what I would do is loop over the length of those lists and then take that element in the lat/long lists and put them together in their own list.
```
for x in ra... | 10,464 |
65,511,540 | I am new to this world and I am starting to take my first steps in python. I am trying to extract in a single list the indices of certain values of my list (those that are greater than 10). When using append I get the following error and I don't understand where the error is.
```py
dbs = [0, 1, 0, 0, 0, 0, 1, 0, 1, 23... | 2020/12/30 | [
"https://Stackoverflow.com/questions/65511540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14914879/"
] | You probably mean to write
```
for i, d in enumerate(dbs):
if d > 10:
exceed2.append(i)
print(exceed2)
```
Few fixes here:
* `append=()` is invalid syntax, you should just write `append()`
* the `i, d` values from `enumerate()` are returning the values and indexes. You should be checking `d > 10`, since... | Welcome to this world :D
the problem is that .append is actually a function that only takes one input, and appends this input to the very end of whatever list you provide.
Try this instead:
```
dbs = [0, 1, 0, 0, 0, 0, 1, 0, 1, 23, 1, 0, 1, 1, 0, 0, 0,
1, 1, 0, 20, 1, 1, 15, 1, 0, 0, 0, 40, 15, 0, 0]
exceed2... | 10,465 |
14,320,758 | Is there a way to run an arbitrary method whenever a new thread is started in Python (2.7)? My goal is to use [setproctitle](http://pypi.python.org/pypi/setproctitle) to set an appropriate title for each spawned thread. | 2013/01/14 | [
"https://Stackoverflow.com/questions/14320758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/186971/"
] | Just inherit from threading.Thread and use this class instead of Thread - as long as you have control over the Threads.
```
import threading
class MyThread(threading.Thread):
def __init__(self, callable, *args, **kwargs):
super(MyThread, self).__init__(*args, **kwargs)
self._call_on_start = callab... | Use `threading.setprofile`. You give it your callback and Python will invoke it every time a new thread starts.
Documentation [here](https://docs.python.org/2/library/threading.html). | 10,466 |
40,879,394 | I am new to python and pydev. I have tensorflow source and am able to run the example files using python3 /pathtoexamplefile.py. I want to try to step thru the word2vec\_basic.py code inside pydev. The debuger keep throwing
File "/Users/me/workspace/tensorflow/tensorflow/python/**init**.py", line 45, in
from tensor... | 2016/11/30 | [
"https://Stackoverflow.com/questions/40879394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1058511/"
] | ```
SELECT StockNo
FROM sales
GROUP BY StockNo
HAVING SUM(CASE WHEN DATE_FORMAT(Date, '%Y-%m') = '2016-11' THEN 1 ELSE 0 END) > 0
```
If you also want to retrieve the full records for those matching stock numbers in the above query, you can just add a join:
```
SELECT s1.*
FROM sales s1
INNER JOIN
(
SELECT Stock... | Thank you very much Tim for pointing me in the right direction. Your answer was close but it still only returned records from the current month and in the end I used the following query:
```
SELECT s1.* FROM `sales` s1
INNER JOIN
(
SELECT * FROM `sales` GROUP BY `StockNo` HAVING COUNT(`StockNo`) > 1
AND SUM(CA... | 10,467 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.