spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » PYTHON » Page 3
Getting Deeper Level JSON Values in Python
Are you using json.loads()? If so you can then get the keys, and do an if statement against the keys. An example on how to get the keys and their respective values is shown below. import json some_json = """{ "id": 35436, "url": "https://company.zendesk.com/api/v2/tickets/35436.json", "external_id": "ahg35h3jh", "created_at": "2009-07-20T22:55:29Z", "update

Categories : Python

Why doesn't the program print anything
You define the function but never call it and return before your print statements. import re def is_email(email): pattern = '[.w]{1,}[@]w+[.]w+' if re.match(pattern, email): print("Valid Email") return True else: print("Invalid Email") return False email=input("Enter your email") is_email(email)

Categories : Python

Guaranteeing 0 at same level on left and right y axes (Python matplotlib)
Edit I have updated my code to reflect my comments on leaving alone the function with the greatest range and rescaling the other one, and also about the yticks. While at it, I throw in also the legends (note that you have to save the lines you plot, the comma is essential) and grids of differing colors. import numpy as np import matplotlib.pyplot as plt a = 1.0*np.sin(np.linspace(0,5,51))+0.6

Categories : Python

Cleaning memory in python
usually python takes care of the memory pretty well. I would guess you have some memory leak in your script (e.g. global varables containing more and more data every loop iteration) It is a good idea to use small functions and have local variables there. At the exit of the function all memory allocated for local variables is automatically released. I don't know details of your script so that's d

Categories : Python

Widgets not showing in NBViewer
Widgets are not shown in nbviewer with current ipython 2.x. IPython 3 is supposed to add persistent widgets that can be shown by nbviewer. The release of ipython 3 was scheduled for this fall but it is likely to happen early next year.

Categories : Python

Dropping values from a list of tuples
You can use zip function : >>> set(zip(*mytuple)[1]) set(['Sarah@gmail.com', 'Jim@gmail.com', 'Andrew@gmail.com']) Or as a less performance way you can use map and operator.itemgetter and use set to get the unique tuple : >>> from operator import itemgetter >>> tuple(set(map(lambda x:itemgetter(1)(x),mytuple))) ('Sarah@gmail.com', 'Jim@gmail.com', 'Andrew@gmail.com'

Categories : Python

How do you set the results_directory in SST Python
I had the following script working for me using Google. The trick was to add result directory to actual config file which is located @{dir}Python27Libsite-packagessstconfig.py and add results_directory = "C:Users{me}DesktopPython-pip-SST esults" import unittest from sst.actions import * from sst import cases, config #config.results_directory = "C:Users{me}DesktopPython-pip-SST esults" go_to('ht

Categories : Python

Should I use sqlite3 for storing username and password with python?
You'll need to store the names and (secured) passwords on the server. SQLite is a perfectly good solution for this but there are many, many other ways to do it. If your application does not otherwise use a database for storage there's no need to add database support just for this simple task. Assuming that you don't have a very large and every-growing list of users it could be as easy as pickli

Categories : Python

example of continuous integration on binstar
The tricky part of building for all the different platforms is the conda recipe, not the Binstar matrix. In that case, you should look at the example recipes in https://github.com/conda/conda-recipes.

Categories : Python

reCaptcha with password_reset() in Django
One way to do this is to create your own view that calls the password reset view: from django.contrib.auth.views import password_reset def my_password_reset(request): # check captcha here return password_reset() One of the parameters the password_reset method receives is "password_reset_form", the class of the form you want to use to Reset the password. I would recommend, instead of ch

Categories : Python

find all elements with same name selenium webdriver
The easiest way would be to use find_elements_by_css_selector(): driver.find_elements_by_css_selector('i.icon.icon-calendar.fn-tooltip.tooltipstered')

Categories : Python

Django Tastypie POST Unauthorized on different servers
This happens because you have not enabled cors. class BaseModelResource(ModelResource): class Meta: queryset = BaseModel.objects.all() resource_name = 'api' authorization = DjangoAuthorization() detail_allowed_methods = ['get', 'post'] always_return_data = True authentication = OAuth20Authentication() Also in production or on any server: You

Categories : Python

Sieve of Eratosthenes python
You didn't create s to be a list of n+1 Trues; you created a list with one element, n+1, and then ask if it is True (and ignore the answer). Try this instead: s = [True for x in xrange(n+1)] You also never do anything to s, but one thing at a time.

Categories : Python

Search and replace multiple patterns in a string in python script
You can do something like >>> val=re.sub(r'hxxps.*u=hxxp-3A__([^&]+).*', r'hxxp://1', str) >>> re.sub(r'_', '/', val) 'hxxp://developer.apple.com/contact/'

Categories : Python

How to remove [] on __repr__ return
you must hide some thing. i think you have a list to contain all your instances, that's why you see a pair of [, ]. i don't have any such issue. >>> class A: def __repr__(self): return "a" >>> >>> A() a i think this seems to be your situation: >>> [A(),A()] [a, a]

Categories : Python

Django: Admin template shows old values after page refresh
It's because srv_time is being set as a 'class' level attribute and not an 'instance' level attribute. Python keeps two namespaces for both 'class' level attributes and 'instance' level attributes. When Django gets loaded (when you start your server), it runs the calculation for srv_time just once. This is why when you refresh the page it isn't recalculating this value. You'll need to override

Categories : Python

How to search for question mark and / with regular expression ? python
To search for a literal ? character, you need to escape it with a . ? is a special character in regexes, and cannot (usually) be used on its own. pattern = r"test/?n=(d+)"

Categories : Python

NumPy: counting sizes of row-wise intersections between two arrays
Here is one approach that takes on the order of a second for inputs of size 100000 and 50000: import numpy as np import scipy.sparse def intersection_counts(x,y): # find the size of the input arrays n_x, n_d = x.shape n_y, n_d = y.shape # get a list of the unique values appearing in x and y, as well # as a list of inverse indices (see docs for np.unique) values, ix = np.

Categories : Python

Subject lines using send_templated_mail
I've found the issue. in common.py (settings) the subject was being written like this: TEMPLATED_EMAIL_MANDRILL = { '_default': { 'auto_html': None, 'auto_text': None, 'from_email': 'return@address.com', 'from_name': 'Reply Name', 'google_analytics_campaign': 'email@address.com', 'google_analytics_domains': ['email@address.com'], 'head

Categories : Python

Django rest framework custom filter for POST request
figured it out: class MyPostViewSet(BaseModelViewSet): def post(self, request, *args, **kwargs): queryset = self.queryset filter_params = request.DATA or request.GET if filter_params: queryfilter = self.filter_class(filter_params, queryset=queryset) queryset = queryfilter.qs page = self.paginate_queryset(queryset) serializer = s

Categories : Python

python ete2 TreeNode check if it has attribute
You could just use the generic pythonic way if not hasattr(node, "a"): print "a attribute not found in node:", node If "a" is registered as a regular feature in your ETE tree, you could also use the following approach: from ete2 import Tree t = Tree() t.populate(5) t.children[0].add_features(a = "My annotation") for node in t.traverse(): if "a" in node.features: print node.get

Categories : Python

Tkinter program not running while trying to run from console
You forgot to change pack to grid on this line: top.pack(side=TOP) You cannot mix pack and grid in the same container. Doing so will cause Tkinter to enter an infinite loop as it tries to determine what geometry manager to follow. This in turn will prevent the window from being established and the program will seemingly "freeze".

Categories : Python

Python pandas cumsum() reset after hitting max
Here's an example of how you might do this by iterating over each row in the dataframe. I created new data for the example for simplicity: df = pd.DataFrame({'TimeDelta': np.random.normal( 900, 60, size=100)}) print df.head() TimeDelta 0 971.021295 1 734.359861 2 867.000397 3 992.166539 4 853.281131 So let's do an accumulator loop with your desired 3000 max: maxvalue = 3000 lastvalue

Categories : Python

Python: wget randomly prints "-1 / unknown"
Wget.download() needs a third argument for a progress bar which I left out. Just add bar=None to wget.download(url, out='cache/page'): wget.download(url, out='cache/page', bar=None)

Categories : Python

Looping over items in a List to return Dictionary Values Python
I dance - obviously returns juka-pinyi because 'i' is not in dictionary and you are lower casing the user input :) Otherwise, code seems fine. I am assuming it is a typo that the last line is incorrectly indented.

Categories : Python

How to send Google Maps API Marker from Python server?
There are a number of ways to handle this. I would create an API with the locations (lat, long). Then on the client side, use AJAX to consume the API and then use a loop to create new markers, appending each to the DOM. Make sense?

Categories : Python

Conditional Conjunction of two Iterables
Quick 'dirty' solution: s1 = set([1, 2, 3]) s2 = set([4, -2, 5]) res = [x for x in s1 | s2 if -x not in s1 and -x not in s2] 2 and -2 are opposite elements which we exclude. It gives [1, 3, 4, 5].

Categories : Python

Running part of python script
If you want something similar to Matlab, check out ipython - it comes with the goodness of python with a workflow similar to Matlab. ipython has the concept of Notebooks which are composed of cells. These cells can be executed individually giving you the behavior you expect.

Categories : Python

placement of widgets in kivy when useing a BoxLayout and no absolute coordinates
To restrict a label width to the texture width (same logic for height if you need), you can: Label: size_hint_x: None width: self.texture_size[0] If you use a such label in a BoxLayout, it will be left/bottom aligned by default. For your information, you can use pos_hint to place it somewhere else. I guess in your example, just using the method described above in your description Label

Categories : Python

Couchbase, 4 nodes with replicas (not sharding), select from 127.0.0.1
Couchbase does provide efficient sharding and replicas mechanism. So your #2 "no sharding" will be alien to Couchbase (but achievable via XCDR) Therefore, if you have 4 physical nodes with CB server instance on each I recommend the following setup (to achieve under 1 millisecond access times and HA 24/7 setup): Join all 4 instances into one cluster so you have real HA setup (if node is down, op

Categories : Python

Getting (in Python) the text output of executing a CMD command from Python
As Cyber mentioned, subprocess.check_output is a really easy way of doing it: import subprocess file = "foo.txt" text = "'comment'" output = subprocess.check_output(["BZR", "commit", file, "-m", text]) print(output) Disclaimer: This code will only work with Python 2.7+

Categories : Python

Enter interactive mode in piped python scripts
You'll need to reset stdin to come from the terminal, rather than the pipe. That is, before asking for input from the user (and assuming you're on a Unix-y environment) invoke sys.stdin = open("/dev/tty"). For example: import sys for line in sys.stdin.readlines(): print 'from s2: ' + line sys.stdin = open("/dev/tty") raw_input()

Categories : Python

ROS Python msg, send list of ints
When you do str(perc) you are creating a string like this '[0, 70, 85, 13, 54, 60, 67, 26]' you need to remove the brackets(first and last character) and then split it with the "," as delimiter like this: perc = [int(i) for i in emo_perc.percentage[1:-1].split(",")] Output: [0, 70, 85, 13, 54, 60, 67, 26]

Categories : Python

Matplotlib | Change the orientation to portrait
I think you're wanting to change the figure size, rather than anything having to do with page layout. The orientation kwarg to savefig really only applies to the PS and EPS backends. For a PDF, the page size is defined as equal to the figure size, so it has no effect. As a quick example of what your current results might look like: import matplotlib.pyplot as plt fig, ax = plt.subplots(nrows=7

Categories : Python

Django forms with clean_field(self) return empty element on raise
Sorry for answering my own question. My problem was at template level. my template was waging for a diatomite object because need to localize the date in the timezone of the user. but when there was an error in the form. the value did not contain a datetime object. just a buffer with the previous input. so the timezone date tags failed to parse the data. printing an empty value. now the part i

Categories : Python

Cannot compile two .py files into stand alone executable using py2exe
Add the background image as a data file: setup( options = {'py2exe': {'bundle_files': 1, 'compressed': True}}, windows=[{'script': "main.py"}], zipfile = None, data_files= [ ("prog",["background_image.py"])] )

Categories : Python

DrawingArea inside scrolledwindow fails to draw
You are using the GtkDrawingArea incorrectly. A drawing area is not a canvas on which you can draw only once and expect the system to refresh the drawing; it is a widget that allows (and requires) you to draw on it during the expose event. This is useful when you need to process the image, e.g. by scaling it to the area. If all you just need is a widget to show an existing image, use gtk.Image ins

Categories : Python

Mandrill API: Filter out scheduled emails list by metadata
The best bet would probably be to store the data when you schedule the email in the first place, in your own database, including the recipient, subject line, and what data you want to be able to display. If you need or want to be able to compare that to the messages scheduled in Mandrill, store the _id that's returned for each scheduled message, too, in your database, so you have a unique identifi

Categories : Python

When I read from a file, The last letter is printed twice
encoded=file.readline() When readline reads a line, it includes the newline character at the end of the line. So even though "eph" looks like it's three characters long in the text file, encoded will actually be "eph ". Try stripping the input of whitespace before doing anything with it. encoded=file.readline().strip() Without the strip, your loop will iterate four times, with letters being "

Categories : Python


Recently Add
Adding json to new Django database
document clustering in python
Only read the last character in a .txt file
Is it possible to redirect to different domain retaining the trailing endpoint, from a route?
Python NameError: not defined
Numpy array loop
Turning off Tick Marks in Bokeh
Python: Number and operator concatenation not working (Euler's Method)
Python: Twitter API tweets/search: Flatten nested dictionary to columns
Python 2.7 cmd autocomplete readline buffers seem stale
Memory usage/efficiency for pandas dataframe versus lists versus tuples, etc.
How can i use multiple lists as arguments in a function and receive them differently?
PyQt - setText method of QTableWidget gets AttributeError
Matplotlib - get value of autoscale
Backwards axes in numpy.delete
Twilio - How to determine the length of a conference call?
Counting string using for loop
Automating creation of class instances in python for an undetermined amount of instances
Printing 2D-array in a grid
Load PreComputed Vectors Gensim
IPython _repr_html_
Reversing a number using recursion
Is there a configuration under which a numpy operation will work on more than a single core/thread?
Is there a better way to write this if-statement?
Python: Effective reading from a file using csv module
Django/Python: CSV for-in loop overriding first row each time through
How to read the pickled igraph graph object from old version by new version igraph
Tornado WebSocket with Django ORM with shared session
trying to plot contours of bivariate normal, won't work with a correlation term
Python split users input
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.