commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
6e87102251f6448ffa7b9c662ace3b50b00b69b2
Test for git config.
apgl/data/ExamplesGenerator.py
apgl/data/ExamplesGenerator.py
''' A simple class which can be used to generate test sets of examples. ''' #import numpy import numpy.random class ExamplesGenerator(): def __init__(self): pass def generateBinaryExamples(self, numExamples=100, numFeatures=10, noise=0.4): """ Generate a certain number of examples with a uniform distribution between 0 and 1. Create binary -/+ 1 labels """ if numExamples == 0 or numFeatures == 0: raise ValueError("Cannot generate empty dataset") X = numpy.random.rand(numExamples, numFeatures) c = numpy.random.rand(numFeatures) y = numpy.sign((X.dot(c)) - numpy.mean(X.dot(c)) + numpy.random.randn(numExamples)*noise) return X, y def generateRandomBinaryExamples(self, numExamples=100, numFeatures=10): """ Generate a certain number of examples with a uniform distribution between 0 and 1. Create binary -/+ 1 labels """ X = numpy.random.rand(numExamples, numFeatures) y = (numpy.random.rand(numExamples)>0.5)*2 - 1 return X, y
Python
0
@@ -402,32 +402,77 @@ ary -/+ 1 labels +. Must have more than 1 example and feature. %0D%0A %22%22%22%0D%0A
25870e710ca51a6fe373677f2d2889a0df3641ca
Revert "test commit heroku"
farmsList/public/api.py
farmsList/public/api.py
import jsonpickle from flask import Blueprint from farmsList.public.models import Parcel blueprint = Blueprint('api', __name__, url_prefix='/api', static_folder="../static") @blueprint.route("/parcel/", methods=["GET", "POST"]) def api_parcel(): print "HELLO" parcelData = Parcel.query.filter(Parcel.listedToPublic == True).all() print "HELLO 2" return jsonpickle.encode(parcelData, unpicklable=False, make_refs=False)
Python
0
@@ -252,23 +252,8 @@ ():%0A -%09print %22HELLO%22%0A %09par @@ -323,25 +323,8 @@ l()%0A -%09print %22HELLO 2%22%0A %09ret
0163d94f2ad28d8457b99f05c427b88bc97881f1
fix links
examples/ensemble/plot_partial_dependence.py
examples/ensemble/plot_partial_dependence.py
""" ======================== Partial Dependence Plots ======================== Partial dependence plots show the dependence between the target function [1]_ and a set of 'target' features, marginalizing over the values of all other features (the complement features). Due to the limits of human perception the size of the target feature set must be small (usually, one or two) thus the target features are usually chosen among the most important features (see :meth:`ensemble.GradientBoostingRegressor.feature_importances_`). This example shows how to obtain partial dependence plots from a :class:`ensemble.GradientBoostingRegressor` trained on the California housing dataset. The example is taken from [HTF2009]_. The first plot shows four one-dimensional partial dependence plots. The target variables are: median income (`MedInc`), avg. occupants per household (`AvgOccup`), median house age (`HouseAge`), and avg. rooms per household (`AveRooms`). We can clearly see that the median house price shows a linear relationship with the median income (top left) and that the house price drops when the avg. occupants per household increases (top right). The lower left plot shows that the house age in a district does not have a strong influence on the (median) house price. The red tick marks on the x-axis represent the deciles of the feature values in the trainig data. Partial dependence plots with two target features enable us to visualize interactions among them. The two-variable partial dependence plot shows the dependence of median house price on joint values of house age and avg. occupants per household. We can clearly see an interaction between the two features: For an avg. occupancy greather than two, the house price is nearly independent of the house age, whereas for values less than two there is a strong dependence on age. .. [HTF2009] T. Hastie, R. Tibshirani and J. Friedman, "Elements of Statistical Learning Ed. 2", Springer, 2009. .. [1] For classification you can think of it as the regression score before the link function. """ print __doc__ import numpy as np import pylab as pl import matplotlib from mpl_toolkits.mplot3d import Axes3D from scipy.stats.mstats import mquantiles from sklearn.cross_validation import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.ensemble.partial_dependence import partial_dependence_plots from sklearn.datasets.california_housing import fetch_california_housing # fetch California housing dataset cal_housing = fetch_california_housing() # split 80/20 train-test X_train, X_test, y_train, y_test = train_test_split(cal_housing.data, cal_housing.target, test_size=0.2, random_state=1) names = cal_housing.feature_names print('_' * 80) print("Training GBRT...") clf = GradientBoostingRegressor(n_estimators=80, max_depth=4, learning_rate=0.1, loss='huber', random_state=1) clf.fit(X_train, y_train) print("done.") print('_' * 80) print('One-way partial dependence plots') print features = [0, 5, 1, 2, (5, 1)] partial_dependence_plots(clf, X_train, features, feature_names=names, n_jobs=3, verbose=3) pl.show() ## sub_plots = [] ## fig = pl.figure() ## for i, fx in enumerate([0, 5, 1, 2]): ## name = names[fx] ## target_feature = np.array([fx], dtype=np.int32) ## ax = pl.subplot(2, 2, i + 1) ## # plot partial dependence ## pdp, (axis,) = gradient_boosting.partial_dependence(clf, target_feature, ## X=X_train) ## ax.plot(axis, pdp.ravel(), 'g-') ## # plot data deciles ## deciles = mquantiles(X_train[:, fx], prob=np.arange(0.1, 1.0, 0.1)) ## trans = matplotlib.transforms.blended_transform_factory(ax.transData, ## ax.transAxes) ## ax.vlines(deciles, 0.0, 0.05, transform=trans, color='red') ## pl.xlabel(name) ## pl.ylabel('Partial Dependence') ## sub_plots.append(ax) ## # set common ylim ## y_min = min((ax.get_ylim()[0] for ax in sub_plots)) ## y_max = max((ax.get_ylim()[1] for ax in sub_plots)) ## for ax in sub_plots: ## ax.set_ylim((y_min, y_max)) ## fig.suptitle('Partial dependence of house value on nonlocation features ' \ ## 'for the California housing dataset') ## print('_' * 80) ## print('Two-way partial dependence plot') ## print ## fig = pl.figure() ## target_feature = np.array([1, 5], dtype=np.int32) ## pdp, (x_axis, y_axis) = gradient_boosting.partial_dependence(clf, ## target_feature, ## X=X_train, ## grid_resolution=50) ## XX, YY = np.meshgrid(x_axis, y_axis) ## Z = pdp.T.reshape(XX.shape).T ## ax = Axes3D(fig) ## surf = ax.plot_surface(XX, YY, Z, rstride=1, cstride=1, cmap=pl.cm.BuPu) ## ax.set_xlabel(names[target_feature[0]]) ## ax.set_ylabel(names[target_feature[1]]) ## ax.set_zlabel('Partial dependence') ## # pretty init view ## ax.view_init(elev=22, azim=122) ## pl.colorbar(surf) ## pl.suptitle('Partial dependence of house value on median age and ' \ ## 'average occupancy') ## pl.show()
Python
0
@@ -459,14 +459,23 @@ ee : -meth:%60 +attr:%60~sklearn. ense @@ -603,16 +603,25 @@ :class:%60 +~sklearn. ensemble
cebc863ebd4942bf7393d04bdf1066c57652fe75
add --no-pager for git call in log_since.py
appengine/components/tools/log_since.py
appengine/components/tools/log_since.py
#!/usr/bin/env python # Copyright 2014 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Prints a short log from HEAD (or [end]) to a pseudo revision number.""" from __future__ import print_function __version__ = '1.0.1' import json import optparse import subprocess import sys import calculate_version # pylint: disable=W0403 def get_logs(root, pseudo_revision, mergebase, start, end): start_ref = '%s~%d' % (mergebase, pseudo_revision - start) end_ref = mergebase if end is not None: end_ref += '~%d' % (pseudo_revision - end) refspec = '%s..%s' % (start_ref, end_ref) cmd = [ 'git', '--no-pager', 'log', refspec, '--date=short', '--format=%ad %ae %s' ] nb_commits = (end or pseudo_revision) - start try: log = subprocess.check_output(cmd, cwd=root) except subprocess.CalledProcessError: print( '\nFailed to retrieve the log of last %d commits.' % nb_commits, file=sys.stderr) return 1 maxlen = 0 lines = [] for l in log.rstrip().splitlines(): parts = l.split(' ', 2) parts[1] = parts[1].split('@', 1)[0] maxlen = max(maxlen, len(parts[1])) lines.append(parts) out = '\n'.join( '%s %-*s %s' % (parts[0], maxlen, parts[1], parts[2]) for parts in lines) return out, refspec def get_revision_from_project(project): out = subprocess.check_output([ 'gcloud', '--project', project, 'app', 'versions', 'list', '--service=default', '--format=json', '--filter', 'TRAFFIC_SPLIT=1' ]) service_info = json.loads(out) return int(service_info[0]["id"].split('-')[0]) def main(): root = calculate_version.checkout_root('.') pseudo_revision, mergebase = calculate_version.get_head_pseudo_revision( root, 'origin/master') is_pristine = calculate_version.is_pristine(root, mergebase) parser = optparse.OptionParser( usage='%prog [options] <start> [end]', version=__version__, description=sys.modules[__name__].__doc__) parser.add_option( '-f', '--force', action='store_true', help='Run even if not pristine checkout, e.g. HEAD != origin/master') parser.add_option( '-F', '--files', action='store_true', help='List all modified files') parser.add_option('--project', help='Project ID used to take active revision') options, args = parser.parse_args() print( 'Current version: %s @ %s\n' % (pseudo_revision, mergebase), file=sys.stderr) if not args and not options.project: parser.error( 'Specify --project or the pseudo-revision number of the last push.') if options.project: start = get_revision_from_project(options.project) else: start = int(args[0]) end = None if len(args) == 2: end = int(args[1]) if len(args) > 2: parser.error('Too many arguments.') if start >= pseudo_revision: parser.error( '%d >= %d, you specified \'start\' that was not committed yet?' % (start, pseudo_revision)) if end is not None: if start >= end: parser.error('%d >= %d, did you reverse start and end?' % (start, end)) if end > pseudo_revision: parser.error( '%d >= %d, you specified \'end\' that was not committed yet?' % (end, pseudo_revision)) nb_commits = (end or pseudo_revision) - start if not is_pristine: if not options.force: parser.error( 'Make sure to sync to what was committed and uploaded first.') print( 'Warning: --force was specified, continuing even if not pristine.\n', file=sys.stderr) out, refspec = get_logs(root, pseudo_revision, mergebase[:12], start, end) remote = subprocess.check_output(['git', 'remote', 'get-url', 'origin'], cwd=root).strip() print(remote + '/+log/' + refspec) print('') print(out) if options.files: print('') cmd = ['git', 'diff', refspec, '--stat', '-C', '-C'] try: subprocess.check_call(cmd, cwd=root) except subprocess.CalledProcessError: print( '\nFailed to list files of last %d commits.' % nb_commits, file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())
Python
0
@@ -3941,16 +3941,30 @@ %5B'git', + '--no-pager', 'diff',
e265fd0ab0845ab20751ce0291436922e00ef1cc
version 0.1.17 release
fastprogress/version.py
fastprogress/version.py
__all__ = ['__version__'] __version__ = '0.1.16'
Python
0
@@ -43,7 +43,7 @@ .1.1 -6 +7 '%0A
e6c8706a87cf83e5e5ffbadad4b8b96effd14e04
Fix tests
features/files/tests.py
features/files/tests.py
import os import shutil import django import django_mailbox import core from features.associations import models as associations from features.images import tests as images from features.memberships import test_mixins as memberships class GroupMessageMixin(memberships.MemberMixin): def setUp(self): mailbox = django_mailbox.models.Mailbox.objects.create(name='Test') self.message = django_mailbox.models.Message.objects.create( mailbox=mailbox, from_header=self.gestalt.user.email, to_header='{}@localhost'.format(self.group.slug), body='Text A') class GroupMessageWithAttachmentMixin(GroupMessageMixin): def setUp(self): super().setUp() test_file = os.path.join( os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'images', 'tests', 'test.png') shutil.copy(test_file, django.conf.settings.MEDIA_ROOT) self.message.attachments.create( document='./test.png', headers='Content-Type: image/png') class SendFileByEmail(GroupMessageWithAttachmentMixin, core.tests.Test): def test_send_file_by_email(self): django_mailbox.signals.message_received.send(self, message=self.message) self.assertNotificationSent() self.assertEqual(len(django.core.mail.outbox[0].attachments), 1) class Guest(images.ImageMixin, memberships.MemberMixin, core.tests.Test): def create_group_file(self, **kwargs): self.client.force_login(self.gestalt.user) kwargs.update({'title': 'Group File', 'text': 'Test', 'file': self.image.file}) self.client.post(self.get_url('create-group-file', self.group.slug), kwargs) self.client.logout() def get_group_file_url(self): return associations.Association.objects.get( content__title='Group File').get_absolute_url() def test_guest_create_group_file(self): self.assertLogin(url_name='create-group-file', url_args=[self.group.slug]) self.assertLogin( url_name='create-group-file', url_args=[self.group.slug], method='post') def test_guest_public_group_file(self): self.create_group_file(public=True) self.assertContainsLink(obj=self.group, link_url=self.get_group_file_url()) self.assertOk(url=self.get_group_file_url()) self.assertLogin(url=self.get_group_file_url(), method='post') def test_guest_internal_group_file(self): self.create_group_file(public=False) self.assertNotContainsLink(obj=self.group, link_url=self.get_group_file_url()) self.assertLogin(url=self.get_group_file_url()) self.assertLogin(url=self.get_group_file_url(), method='post') class Gestalt(images.ImageMixin, memberships.AuthenticatedMemberMixin, core.tests.Test): def create_group_file(self, **kwargs): kwargs.update({'title': 'Group File', 'text': 'Test', 'file': self.image.file}) return self.client.post(self.get_url('create-group-file', self.group.slug), kwargs) def get_group_file_url(self): return associations.Association.objects.get( content__title='Group File').get_absolute_url() def test_gestalt_create_group_file(self): self.assertEqual(self.client.get(self.get_url( 'create-group-file', self.group.slug)).status_code, 200) response = self.create_group_file() self.assertRedirects(response, self.get_group_file_url()) self.assertExists(associations.Association, content__title='Group File') def test_gestalt_public_group_file(self): self.create_group_file(public=True) self.assertContainsLink(obj=self.group, link_url=self.get_group_file_url()) self.assertOk(url=self.get_group_file_url()) def test_gestalt_internal_group_file(self): self.create_group_file(public=False) self.assertContainsLink(obj=self.group, link_url=self.get_group_file_url()) self.assertOk(url=self.get_group_file_url()) class TestUrls(core.tests.Test): def test_files_404(self): r = self.client.get(self.get_url('create-group-file', 'non-existent')) self.assertEqual(r.status_code, 404)
Python
0.000003
@@ -552,19 +552,28 @@ -to_header=' +body='Delivered-To: %7B%7D@l @@ -580,16 +580,26 @@ ocalhost +%5Cn%5CnText A '.format @@ -619,39 +619,8 @@ lug) -,%0A body='Text A' )%0A%0A%0A
145b25626dd018c4dd8b86e17361b9e4eeb935ea
Add some more comments to filter file.
filter_nsized_groups.py
filter_nsized_groups.py
#!/usr/bin/python import struct import sys def parse_arguments(): options = {} for arg in sys.argv[1:]: if arg == "--help": print "usage: ./filter_nsized_causes.py --outfile=OUTPUT [--n=N] [--infile=INPUT]" print "" print "n: threshold of group size to include in output file. (default = 1)" exit(0) try: key, value = arg.strip().split('=') key = key[2:].replace('-', '_') options[key] = value except ValueError: pass return options class FilterGroup: def __init__(self, options): self.options = options self.CAUSE_IDX = 1 self.threshold = int(self.options.get('n', 1)) self.open_files() groups_members = self.count_membership(self.fin) # Blacklist small groups. group_id_blacklist = set([id for id in groups_members if groups_members[id] <= self.threshold]) self.write_result(group_id_blacklist) # Open input and output files. def open_files(self): self.fout = open(self.options['outfile'], 'wb+') try: self.fin = open(self.options['infile'], 'r') except KeyError: self.fin = sys.stdin # Return a dictionary mapping groups to member count. def count_membership(self, input_file): groups_members = {} for i, line in enumerate(input_file): try: group_id = int(line[:-1].split(',')[self.CAUSE_IDX]) except IndexError: print "CSV file is improperly formatted on line %d (no comma found)" % i continue try: groups_members[group_id] += 1 except KeyError: groups_members[group_id] = 1 if i % 1000000 == 0: print "Progress: %d" % i return groups_members # Write out pairs of user_id, group_id to binary file, removing all pairs # that have a group_id in BLACKLIST. def write_result(self, blacklist): self.fin.seek(0) for i, line in enumerate(self.fin): try: user_id, group_id = map(int, line[:-1].split(',')) except ValueError: continue if group_id not in blacklist: self.fout.write(struct.pack('II', user_id, group_id)) if i % 1000000 == 0: print "Write progress: %d" % i if __name__ == "__main__": f = FilterGroup(parse_arguments())
Python
0
@@ -37,16 +37,469 @@ rt sys%0A%0A +# filter_nsized_groups: Given a CSV file of (user, group) pairs, each indicating%0A# that user USER belongs to group GROUP, do two things:%0A#%0A# 1. Remove all groups with a size that fall under a threshold, specified in %0A# arguments passed to the file (defaults to 1).%0A#%0A# 2. Writes the resulting pairs to a new binary file, with a name specified in%0A# the arguments passed in.%0A%0A# Parses command line arguments. See --help screen for more information.%0A def pars @@ -764,16 +764,156 @@ lt = 1)%22 +%0A print %22%22%0A print %22outfile: location of the output of this file.%22%0A print %22%22%0A print %22infile: CSV of (user, group) pairs.%22 %0A%0A @@ -1107,17 +1107,228 @@ terGroup -: +s:%0A # OPTIONS is a dictionary of settings.%0A #%0A # options%5B'infile'%5D : The input file. Required.%0A # options%5B'outfile'%5D : The output file. Required.%0A # options%5B'n'%5D : Group size threshold. Defaults to 1. %0A def _ @@ -1351,16 +1351,40 @@ tions):%0A + self.GROUP_IDX = 1%0A%0A self @@ -1406,31 +1406,8 @@ ons%0A - self.CAUSE_IDX = 1%0A @@ -1453,24 +1453,46 @@ n', 1))%0A%0A + self.fin, self.fout = self.open_f @@ -1498,17 +1498,16 @@ files()%0A -%0A grou @@ -1783,29 +1783,24 @@ (self):%0A -self. fout = open( @@ -1831,16 +1831,31 @@ 'wb+')%0A + fin = None%0A try: @@ -1857,29 +1857,24 @@ try:%0A -self. fin = open(s @@ -1928,21 +1928,16 @@ :%0A -self. fin = sy @@ -1945,16 +1945,40 @@ .stdin%0A%0A + return (fin, fout)%0A%0A # Retu @@ -2198,13 +2198,13 @@ elf. -CAUSE +GROUP _IDX @@ -3052,16 +3052,17 @@ terGroup +s (parse_a
119b154f0cad59b11306995b774e225f6061dc6f
Clarify Task.tick design choice
py/g1/asyncs/kernels/g1/asyncs/kernels/tasks.py
py/g1/asyncs/kernels/g1/asyncs/kernels/tasks.py
__all__ = [ 'Task', ] import inspect import logging import weakref from g1.bases.assertions import ASSERT from . import contexts from . import errors from . import traps LOG = logging.getLogger(__name__) class Task: """Task object. A ``Task`` object wraps an coroutine object, and is the basic unit of scheduling. It is modelled after ``Future` object, which is commonly used for wrapping a ``Thread`` object. There are a few notable differences between ``Task`` and ``Future``: * ``Task`` is cancellable due to its cooperative nature, but ``Future`` is not because threads in general are not cancellable. * ``get_result`` and ``get_exception`` does not take a ``timeout`` argument. While it is possible to add a ``timeout`` argument, as a convention we would prefer not to. """ @staticmethod def is_coroutine(coro): # ``types.coroutine`` returns a generator function. return inspect.iscoroutine(coro) or inspect.isgenerator(coro) def __init__(self, coroutine): self._coroutine = ASSERT.predicate(coroutine, self.is_coroutine) self._num_ticks = 0 self._completed = False self._result = None self._exception = None self._callbacks = [] # Extra debug info (pre-format it to prevent it from leaking # into logging sub-system). task_repr = '<%s at %#x: %r, ...>' % ( self.__class__.__qualname__, id(self), self._coroutine, ) self._finalizer = weakref.finalize( self, LOG.warning, 'task is garbage-collected but never joined: %s', task_repr, ) def __repr__(self): return '<%s at %#x: %r, ticks=%d, %s, %r, %r>' % ( self.__class__.__qualname__, id(self), self._coroutine, self._num_ticks, 'completed' if self._completed else 'uncompleted', self._result, self._exception, ) def is_completed(self): return self._completed def cancel(self): # Add ``Task.cancel`` for convenience. contexts.get_kernel().cancel(self) async def join(self): self._finalizer.detach() await traps.join(self) async def get_result(self): await self.join() return self.get_result_nonblocking() async def get_exception(self): await self.join() return self.get_exception_nonblocking() def get_result_nonblocking(self): ASSERT.true(self.is_completed()) self._finalizer.detach() if self._exception: raise self._exception else: return self._result def get_exception_nonblocking(self): ASSERT.true(self.is_completed()) self._finalizer.detach() return self._exception # # Package-private interface. # def tick(self, trap_result, trap_exception): """Run coroutine through the next trap point.""" ASSERT.false(self.is_completed()) if trap_exception: func = self._coroutine.throw arg = trap_exception else: func = self._coroutine.send arg = trap_result try: self._num_ticks += 1 trap = func(arg) except errors.TaskCancellation as exc: self._completed = True self._exception = errors.Cancelled() self._exception.__cause__ = exc except StopIteration as exc: self._completed = True self._result = exc.value except BaseException as exc: self._completed = True self._exception = exc else: return ASSERT.not_none(trap) ASSERT.true(self._completed) callbacks, self._callbacks = self._callbacks, None for callback in callbacks: self._call_callback(callback) return None def add_callback(self, callback): if self._completed: self._call_callback(callback) else: self._callbacks.append(callback) def _call_callback(self, callback): try: callback(self) except Exception: LOG.exception('callback err: %r, %r', self, callback)
Python
0.000053
@@ -3036,16 +3036,574 @@ p point. +%0A%0A NOTE: %60%60tick%60%60 catches %60%60BaseException%60%60 raised from the%0A coroutine. As a result, %60%60SystemExit%60%60 does not bubble up to%0A the kernel event loop. I believe this behavior is similar to%0A Python threading library and thus more expected (%60%60SystemExit%60%60%0A raised in non- main thread does not cause CPython process to%0A exit). If you want raising %60%60SystemExit%60%60 in a task to be%0A effective, you have to call %60%60Task.get_result_nonblocking%60%60 in%0A the main thread (or implicitly through %60%60Kernel.run%60%60).%0A %22%22%22%0A
10bddfe09f5026f32951e9d3608166515a755613
Document the NFKC-normalized ligature in the Arabic test.
tests/test.py
tests/test.py
from wordfreq import ( word_frequency, available_languages, cB_to_freq, top_n_list, random_words, random_ascii_words, tokenize ) from nose.tools import ( eq_, assert_almost_equal, assert_greater, raises ) def test_freq_examples(): # Stopwords are most common in the correct language assert_greater(word_frequency('the', 'en'), word_frequency('de', 'en')) assert_greater(word_frequency('de', 'es'), word_frequency('the', 'es')) def test_languages(): # Make sure the number of available languages doesn't decrease avail = available_languages() assert_greater(len(avail), 14) # Laughter is the universal language for lang in avail: if lang not in {'zh', 'ja'}: # we do not have enough Chinese data # Japanese people do not lol assert_greater(word_frequency('lol', lang), 0) # Make up a weirdly verbose language code and make sure # we still get it new_lang_code = '%s-001-x-fake-extension' % lang.upper() assert_greater(word_frequency('lol', new_lang_code), 0) def test_twitter(): avail = available_languages('twitter') assert_greater(len(avail), 12) for lang in avail: assert_greater(word_frequency('rt', lang, 'twitter'), word_frequency('rt', lang, 'combined')) def test_minimums(): eq_(word_frequency('esquivalience', 'en'), 0) eq_(word_frequency('esquivalience', 'en', minimum=1e-6), 1e-6) eq_(word_frequency('the', 'en', minimum=1), 1) def test_most_common_words(): # If something causes the most common words in well-supported languages to # change, we should know. def get_most_common(lang): """ Return the single most common word in the language. """ return top_n_list(lang, 1)[0] eq_(get_most_common('ar'), 'ููŠ') eq_(get_most_common('de'), 'die') eq_(get_most_common('en'), 'the') eq_(get_most_common('es'), 'de') eq_(get_most_common('fr'), 'de') eq_(get_most_common('it'), 'di') eq_(get_most_common('ja'), 'ใฎ') eq_(get_most_common('nl'), 'de') eq_(get_most_common('pt'), 'de') eq_(get_most_common('ru'), 'ะฒ') eq_(get_most_common('zh'), '็š„') def test_language_matching(): freq = word_frequency('็š„', 'zh') eq_(word_frequency('็š„', 'zh-TW'), freq) eq_(word_frequency('็š„', 'zh-CN'), freq) eq_(word_frequency('็š„', 'zh-Hant'), freq) eq_(word_frequency('็š„', 'zh-Hans'), freq) eq_(word_frequency('็š„', 'yue-HK'), freq) eq_(word_frequency('็š„', 'cmn'), freq) def test_cB_conversion(): eq_(cB_to_freq(0), 1.) assert_almost_equal(cB_to_freq(-100), 0.1) assert_almost_equal(cB_to_freq(-600), 1e-6) @raises(ValueError) def test_failed_cB_conversion(): cB_to_freq(1) def test_tokenization(): # We preserve apostrophes within words, so "can't" is a single word in the # data eq_(tokenize("can't", 'en'), ["can't"]) eq_(tokenize('๐Ÿ˜‚test', 'en'), ['๐Ÿ˜‚', 'test']) # We do split at other punctuation, causing the word-combining rule to # apply. eq_(tokenize("can.t", 'en'), ['can', 't']) def test_casefolding(): eq_(tokenize('WEISS', 'de'), ['weiss']) eq_(tokenize('weiรŸ', 'de'), ['weiss']) def test_phrase_freq(): plant = word_frequency("plan.t", 'en') assert_greater(plant, 0) assert_almost_equal( 1.0 / plant, 1.0 / word_frequency('plan', 'en') + 1.0 / word_frequency('t', 'en') ) def test_not_really_random(): # If your xkcd-style password comes out like this, maybe you shouldn't # use it eq_(random_words(nwords=4, lang='en', bits_per_word=0), 'the the the the') # This not only tests random_ascii_words, it makes sure we didn't end # up with 'eos' as a very common Japanese word eq_(random_ascii_words(nwords=4, lang='ja', bits_per_word=0), 'rt rt rt rt') @raises(ValueError) def test_not_enough_ascii(): random_ascii_words(lang='zh') def test_ar(): # Remove tatweels eq_( tokenize('ู…ุชู€ู€ู€ู€ู€ู€ู€ู€ุนุจ', 'ar'), ['ู…ุชุนุจ'] ) # Remove combining marks eq_( tokenize('ุญูŽุฑูŽูƒูŽุงุช', 'ar'), ['ุญุฑูƒุงุช'] ) eq_( tokenize('\ufefb', 'ar'), ['\u0644\u0627'] )
Python
0.001611
@@ -4282,33 +4282,103 @@ r'), -%0A %5B'%5Cu0644%5Cu0627'%5D + # An Arabic ligature...%0A %5B'%5Cu0644%5Cu0627'%5D # ...that is affected by NFKC normalization %0A
57c0668b9dd11845fb2d845ecbcb0a8aae19eb9c
Add default params to template
exercises/scale-generator/scale_generator.py
exercises/scale-generator/scale_generator.py
class Scale(object): def __init__(self): pass
Python
0
@@ -35,16 +35,49 @@ t__(self +, tonic, scale_name, pattern=None ):%0A
321e285f853280204371a882808c116e59892e27
Make wording of message describing not passing filter more clear
extraction/runnables.py
extraction/runnables.py
import collections import sys import traceback class Runnable(object): # runnable properties result_file_name = None dependencies = frozenset() def __init__(self): pass def check_dep_errors(self, dep_results): deps = self.__class__.dependencies filter_deps = [e for e in deps if issubclass(e, Filter)] extractor_deps = [e for e in deps if issubclass(e, Extractor)] for filter in filter_deps: result = dep_results[filter] if isinstance(result, RunnableError): return DependencyError('Did not run because dependency filter %s errored' % filter.__name__) elif not result: return DependencyError('Did not run because dependency filter %s failed' % filter.__name__) for extractor in extractor_deps: result = dep_results[extractor] if isinstance(result, RunnableError): return DependencyError('Did not run because dependency extractor %s errored' % extractor.__name__) return None def log(self, msg): self.logger.info('{0} for run {1}: {2}'.format(self.__class__.__name__, self.run_name, msg)) def run(self, data, dep_results): dep_error = self.check_dep_errors(dep_results) if dep_error: return dep_error try: if isinstance(self, Filter): return self.filter(data, dep_results) elif isinstance(self, Extractor): return self.extract(data, dep_results) except RunnableError as r: return r except Exception as e: e_info = sys.exc_info() self.log(''.join(traceback.format_exception(*e_info))) return RunnableError('{0}: {1}'.format(e.__class__.__name__, e)) class Filter(Runnable): def filter(self, data, dep_results): """ Override this method in Filter subclasses to define custom filtering logic This method will be called automatically by the ExtractionRunner during the extraction process Arguments passed in: data -- the original data the extractor started with dep_results -- the results of any declared dependency filters or extractors If the filter is successful, this method should: return True If the filter fails, this method should: return False If the filters encounters something unexpected, this method should: raise RunnableError('Error Description Here') """ return False class Extractor(Runnable): def extract(self, data, dep_results): """ Override this method in Extractor subclasses to define custom extraction logic This method will be called automatically by the ExtractionRunner during the extraction process Arguments passed in: data -- the original data the extractor started with dep_results -- the results of any declared dependencies These results will be a dictionary where each key is an Extractor class and each value is an instance of the ExtractorResult named tuple If the extractor succeeds, it should return an ExtractorResult named tuple If at any point the extractor encouters a critical error, it should raise a RunnableError """ raise RunnableError('Override this method') # Define namedtuple class for results form extractions ExtractorResult = collections.namedtuple('ExtractorResult', 'xml_result files') # Set files field to be None be default so it's optional ExtractorResult.__new__.__defaults__ = (None,) class RunnableError(Exception): def __init__(self, msg): self.msg = msg def __unicode__(self): return "RunnableError: {0}".format(self.msg) class DependencyError(RunnableError): def __init__(self, msg): self.msg = msg def __unicode__(self): return "DependencyError: {0}".format(self.msg)
Python
0.000671
@@ -732,14 +732,22 @@ %25s -failed +returned false ' %25
2b3431f302cf08d3892eb613079df905ba1f68cb
Add tests to check content page rendering
src/core/tests.py
src/core/tests.py
import pytest from django.test import override_settings from core.utils import collect_language_codes def test_locale_fallback_middleware(client, settings): response = client.get('/en/', follow=True) assert response.redirect_chain == [('/en-us/', 302)] @override_settings(USE_I18N=False) def test_locale_fallback_middleware_no_i18n(client, settings): response = client.get('/en/') assert response.status_code == 404 def test_collect_language_codes(): assert collect_language_codes('zh-tw') == ['zh-tw', 'zh', 'en-us', 'en'] assert collect_language_codes('zh') == ['zh', 'en-us', 'en'] assert collect_language_codes('en-us') == ['en-us', 'en', 'en-us', 'en'] assert collect_language_codes('en') == ['en', 'en-us', 'en'] def test_index_page(client): response = client.get('/en-us/') assert response.status_code == 200 assert 'PyCon' in response.content.decode('utf-8') @pytest.mark.parametrize('path,expected', [ ('/en-us/speaking/cfp/', 200), ('/en-us/speaking/talk/', 200), ('/en-us/speaking/base/', 404), ('/en-us/speaking/_base/', 404), ]) def test_speaking_pages(client, path, expected): assert client.get(path).status_code == expected
Python
0
@@ -1,12 +1,23 @@ +import os%0A%0A import pytes @@ -18,16 +18,16 @@ pytest%0A - %0Afrom dj @@ -60,16 +60,62 @@ settings +%0Afrom django.utils.translation import activate %0A%0Afrom c @@ -1217,16 +1217,16 @@ ected):%0A - asse @@ -1269,8 +1269,1454 @@ xpected%0A +%0A%0Adef content_page_path_gen():%0A from django.conf import settings%0A for template_setting in settings.TEMPLATES:%0A for template_dir in template_setting%5B'DIRS'%5D:%0A for lang in %5B'en', 'zh'%5D:%0A contents_path = os.path.join(template_dir, 'contents', lang)%0A os.chdir(contents_path)%0A for dirpath, _, filenames in os.walk('.'):%0A if os.path.basename(dirpath).startswith('_'):%0A continue%0A for filename in filenames:%0A if filename.startswith('_'):%0A continue%0A root, ext = os.path.splitext(filename)%0A if ext != '.html':%0A continue%0A comps = %5Bc for c in dirpath.split(os.sep) if c != '.'%5D%0A yield '/'.join(%5B''%5D + comps + %5Broot, ''%5D)%0A%0A%0A@pytest.fixture(params=content_page_path_gen())%0Adef content_page_path(request):%0A return request.param%0A%0A%0Adef language_gen():%0A from django.conf import settings%0A for lang_code, _ in settings.LANGUAGES:%0A yield lang_code%0A%0A%0A@pytest.fixture(params=language_gen())%0Adef language(request):%0A return request.param%0A%0A%0Adef test_content_pages(client, language, content_page_path):%0A activate(language)%0A path = '/' + language + '/' + content_page_path%0A response = client.get(path)%0A assert response.status_code == 200, path%0A
2b403cb00f3dd7e676a40fffcbd14a22c8e54635
work in progress...
metadata_export_batch/metadata_batch_operations.py
metadata_export_batch/metadata_batch_operations.py
import arcpy import os.path, os,fnmatch import time import pdb #Get the record and path to XMLs record = raw_input("Enter record number: ") record_path = raw_input("Enter path to shapefiles: ") blankMXD = r'D:\drive\Map Library Projects\MGS\Metadata Templates\blank.mxd' #Static vars TRANSLATOR = "C:\\Program Files\\ArcGIS\\Desktop10.2\\Metadata\\Translator\\ARCGIS2FGDC.xml" base_path = "D:\\drive\\Map Library Projects\\MGS\\Records" #set workspace arcpy.env.workspace = os.path.join(base_path, record, record_path) ws = arcpy.env.workspace #create final_XMLs dir if it doesn't already exist if os.path.exists(os.path.join(base_path,record,"final_XMLs")) == False: arcpy.CreateFolder_management(os.path.join(base_path,record),"final_XMLs") #set the output path for export metadata function OUTPUT = os.path.join(base_path,record,"final_XMLs") def import_XML(): importXMLpath = raw_input("Enter path to XML template: ") importXMLpath = importXMLpath.replace('"','') #importXMLext = importXMLfile+'.xml' #importXMLpath = os.path.join(base_path,record,'converted',importXMLext) print importXMLpath #get a list of all the SHPs if record_path == "converted\GISfiles": files = [] for dirpath,dirnames,filenames in os.walk(os.path.join(base_path,record,record_path)): if dirpath.endswith("shapefiles"): for f in filenames: if fnmatch.fnmatch(f,"*.shp"): files.append(os.path.join(dirpath,f)) else: files = arcpy.ListFiles("*.shp") totalTimeTic = time.time() #loop through SHPs and import the metadata for each for f in files: shapefilePath = os.path.join(base_path,record,record_path,f) tic = time.time() print 'Trying to import XML to: ', f arcpy.ImportMetadata_conversion (importXMLpath,"FROM_FGDC",f, "DISABLED") '''# get the map document mxd = arcpy.mapping.MapDocument(blankMXD) # get the data frame df = arcpy.mapping.ListDataFrames(mxd,"*")[0] # create a new layer newlayer = arcpy.mapping.Layer(shapefilePath) # add the layer to the map at the bottom of the TOC in data frame 0 arcpy.mapping.AddLayer(df, newlayer,"BOTTOM") print "creating thumbnail for " + f mxd.makeThumbnail() mxd.save() arcpy.mapping.RemoveLayer(df, newlayer) mxd.save()''' toc = time.time() s = toc-tic m, s = divmod(s, 60) h, m = divmod(m, 60) timeFormat = "%d:%02d:%02d" % (h, m, s) print 'Time elapsed: ',timeFormat totalTimeToc = time.time() s = totalTimeToc-totalTimeTic m, s = divmod(s, 60) h, m = divmod(m, 60) timeFormat = "%d:%02d:%02d" % (h, m, s) print 'Total time elapsed: ',timeFormat def export_xml(): #set the output path for export metadata function OUTPUT = os.path.join(base_path,record,"final_XMLs") #get a list of all the XMLs if record_path == "converted\GISfiles": files = [] for dirpath,dirnames,filenames in os.walk(os.path.join(base_path,record,record_path)): if dirpath.endswith("shapefiles"): for f in filenames: if fnmatch.fnmatch(f,"*.xml"): files.append(os.path.join(dirpath,f)) else: files = arcpy.ListFiles("*.xml") #loop through XMLs and export the metadata for each to the final_XMLs directory for f in files: if f[len(f)-7:len(f)-4] == 'shp': if os.path.isabs(f) == False: filePath = os.path.join(OUTPUT,f[:-8]+'.xml') else: filePath = os.path.join(OUTPUT,os.path.split(f)[1]) elif f[len(f)-7:len(f)-4] == 'txt': pass else: if os.path.isabs(f) == False: filePath = os.path.join(OUTPUT,f) else: filePath = os.path.join(OUTPUT,os.path.split(f)[1]) print filePath statinfo = os.stat(os.path.join(base_path,record,record_path,f)) print f, '=', statinfo.st_size if statinfo.st_size == 0: continue if os.path.exists(filePath): print f, 'already exists. Deleting now.' os.remove(filePath) print 'Trying to export XML for: ', f arcpy.ExportMetadata_conversion(f, TRANSLATOR, os.path.join(OUTPUT, f[:f.find(".")]+ ".xml")) imp_xml = raw_input('Do you want to batch import XML? ') if imp_xml.lower() in ('yes', 'y'): import_XML() exp_xml = raw_input('Do you want to batch export XML? ') if exp_xml.lower() in ('yes','y'): export_xml()
Python
0
@@ -55,16 +55,28 @@ port pdb +%0Aimport glob %0A%0A#Get t @@ -1006,150 +1006,8 @@ %0A - #importXMLext = importXMLfile+'.xml'%0A #importXMLpath = os.path.join(base_path,record,'converted',importXMLext)%0A print importXMLpath%0A @@ -1439,32 +1439,59 @@ s = -arcpy.ListFiles( +glob.glob(os.path.join(arcpy.env.workspace, %22*.shp%22) %0A%0A @@ -1486,16 +1486,17 @@ %22*.shp%22) +) %0A%0A to @@ -1606,16 +1606,17 @@ +# shapefil @@ -3298,24 +3298,25 @@ + files = arcpy.Li @@ -3311,31 +3311,59 @@ s = -arcpy.ListFiles(%22*.xml%22 +glob.glob(os.path.join(arcpy.env.workspace,%22*.shp%22) )%0A%0A%0A @@ -3479,36 +3479,48 @@ -if f%5Blen(f)-7:len(f)-4 +%0A if os.path.splitext(f)%5B1 %5D == ' +. shp' @@ -3614,15 +3614,70 @@ PUT, -f%5B:-8%5D+ +%0A os.path.split(os.path.splitext(f)%5B0%5D)%5B1%5D, '.xm
ee98b5a5c6b82671738bc60e68ea87d838c5400f
Improve the migration for unique data source name
migrations/0020_change_ds_name_to_non_uniqe.py
migrations/0020_change_ds_name_to_non_uniqe.py
from redash.models import db import peewee from playhouse.migrate import PostgresqlMigrator, migrate if __name__ == '__main__': migrator = PostgresqlMigrator(db.database) with db.database.transaction(): # Change the uniqueness constraint on data source name to be (org, name): success = False for index_name in ['unique_name', 'data_sources_name']: try: print "Trying to remove data source name uniqueness index with the name: {}".format(index_name) migrate(migrator.drop_index("data_sources", index_name)) print "Success!" success = True break except peewee.ProgrammingError: db.close_db(None) if not success: print "Failed removing uniqueness constraint on data source name." print "Please verify its name in the schema, update the migration and run again." exit(1) migrate( migrator.add_index('data_sources', ('org_id', 'name'), unique=True) ) db.close_db(None)
Python
0.000017
@@ -300,288 +300,139 @@ -success = False%0A for index_name in %5B'unique_name', 'data_sources_name'%5D:%0A try:%0A print %22Trying to remove data source name uniqueness index with the name: %7B%7D%22.format(index_name)%0A migrate(migrator.drop_index(%22data_sources%22, index +# In some cases it's a constraint:%0A db.database.execute_sql('ALTER TABLE data_sources DROP CONSTRAINT IF EXISTS unique _name -) +' )%0A @@ -441,380 +441,107 @@ - print %22Success!%22%0A success = True%0A break%0A except peewee.ProgrammingError:%0A db.close_db(None)%0A%0A if not success:%0A print %22Failed removing uniqueness constraint on +# In others only an index:%0A db.database.execute_sql('DROP INDEX IF EXISTS data - +_ source - name.%22%0A print %22Please verify its name in the schema, update the migration and run again.%22%0A exit(1 +s_name' )%0A%0A @@ -647,16 +647,16 @@ )%0A%0A + db.c @@ -669,10 +669,8 @@ b(None)%0A -%0A%0A
791546d9fa1fc0317dc613e0ba7e74ca1cbf8210
Update __init__.py
flask_admin/__init__.py
flask_admin/__init__.py
__version__ = '1.4.1' __author__ = 'Flask-Admin team' __email__ = 'serge.koval+github@gmail.com' from .base import expose, expose_plugview, Admin, BaseView, AdminIndexView
Python
0.000072
@@ -12,17 +12,17 @@ = '1.4. -1 +2 '%0A__auth
558085de2a32ef14d7b9ef2884f34699b7f7c39b
Update test.py
tests/test.py
tests/test.py
from nose.tools import with_setup from ..MyModule import MyModule count = 0 def setup_module(): print('<<<Setup Module>>>') def teardown_module(): print('<<<Teardown Module>>>') def setup_function(): print('<<<Setup Function>>>') global count count = 1 def teardown_function(): print('<<<Teardown Function>>>') global count count = 0 @with_setup(setup_function, teardown_function) def test_function(): print('<<<Test function>>>') global count assert count == 1 @with_setup(setup_function, teardown_function) def test_generator(): print('<<<Test generator>>>') for i in range(5): yield generator_function, 2, i def setup_generator_function(): print('<<<Setup generator_function>>>') def teardown_generator_function(): print('<<<Teardown generator_function>>>') @with_setup(setup_generator_function, teardown_generator_function) def generator_function(step,i): print('<<<generator_function {}>>>'.format(i+1)) global count count = count + step assert count == 1 + step*(i+1) class TestMyModule: @classmethod def setup_class(cls): print('<<<Setup Class>>>') cls.obj = MyModule() @classmethod def teardown_class(cls): print('<<<Teardown Class>>>') del cls.obj def setup(self): print('<<<Setup Method>>>') self.obj = self.__class__.obj def teardown(self): print('<<<Teardown Method>>>') self.obj = None def test___init__(self): print('<<<Test __init__>>>') assert self.obj.number1 == 1 assert self.obj.number2 == 2 def test_my_function(self): print('<<<Test my_function>>>') assert self.obj.my_function() == self.obj.number1 + self.obj.number2 assert self.obj.my_function(3,4) == 7 assert self.obj.my_function(num1=5) == 5 + self.obj.number2 assert self.obj.my_function(num2=3) == self.obj.number1 + 3 assert self.obj.my_function(10,-5) == 5 assert self.obj.my_function(-10,-5) == -15
Python
0.000001
@@ -1,12 +1,46 @@ +import sys%0Asys.path.append('..')%0A%0A from nose.to @@ -67,18 +67,16 @@ p%0A%0Afrom -.. MyModule
53d75c14d79b92ad1fdf9c99b0773db6427d4294
update to reveal.js 3.2.0
flask_reveal/tools/commands/installreveal.py
flask_reveal/tools/commands/installreveal.py
# -*- coding: utf-8 -*- import argparse import os from urllib import request import flask_reveal from flask_reveal.tools.helpers import extract_file, move_and_replace class InstallReveal(argparse.ArgumentParser): info = ({ 'prog': 'installreveal', 'description': 'installs Reveal.js', }) def __init__(self): super(InstallReveal, self).__init__(**self.info) self.url = None self.path = None self.add_argument('-u', '--url', action='store') self.add_argument('-p', '--path', action='store') def parse_args(self, args=None, namespace=None): super(InstallReveal, self).parse_args(args, self) if not self.url and not self.path: self.url = 'https://github.com/hakimel/reveal.js/' + \ 'archive/3.1.0.tar.gz' def run(self, args=None): self.parse_args(args) if self.url: try: response = request.urlretrieve(self.url) self.path = response[0] except Exception: raise move_and_replace( extract_file(self.path), os.path.join(os.path.dirname(flask_reveal.__file__), 'static/') ) command = InstallReveal()
Python
0
@@ -817,9 +817,9 @@ e/3. -1 +2 .0.t
b663fd1a42506eeddc6c86a72f6833d737c7e135
fix logger
keystone_spassword/contrib/spassword/mailer.py
keystone_spassword/contrib/spassword/mailer.py
# # Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import smtplib from keystone import exception try: from oslo_log import log except ImportError: from keystone.openstack.common import log try: from oslo_config import cfg except ImportError: from oslo.config import cfg CONF = cfg.CONF LOG = log.getLogger(__name__) class SendMail(object): def send_email(self, to, subject, text): dest = [to] # must be a list # # Prepare actual message # mail_headers = ("From: \"%s\" <%s>\r\nTo: %s\r\n" % (CONF.spassword.smtp_from, CONF.spassword.smtp_from, ", ".join(dest))) msg = mail_headers msg += ("Subject: %s\r\n\r\n" % subject) msg += text # # Send the mail # try: # TODO: server must be initialized by current object server = smtplib.SMTP(CONF.spassword.smtp_server, CONF.spassword.smtp_port) except smtplib.socket.gaierror: LOG.error('SMTP socket error %s %s' % ( CONF.spassword.smtp_server, CONF.spassword.smtp_port)) return False server.ehlo() server.starttls() server.ehlo try: server.login(CONF.spassword.smtp_user, CONF.spassword.smtp_password) except smtplib.SMTPAuthenticationError: LOG.error('SMTP authentication error %s' % CONF.spassword.smtp_user) return False try: server.sendmail(CONF.spassword.smtp_from, dest, msg) except Exception, ex: # try to avoid catching Exception unless you have too LOG.error('SMTP sendmail error %s' % ex) return False finally: server.quit() logger.info('email was sent to %s' % dest) return True
Python
0.000005
@@ -2656,14 +2656,11 @@ -logger +LOG .inf
623d49f79dcc1986c224f2fdfdfdd825e923c53f
Add treeview
python/regvar/webapps/alignments/application.py
python/regvar/webapps/alignments/application.py
import bx.align.maf import cStringIO import os from flask import Flask, request ENVSETTINGSVAR = 'ALIGNMENTS_SETTINGS' app = Flask(__name__) # # Change this to ProductionConfig when finished app.config.from_object('regvar.webapps.alignments.DevelopmentConfig') if ENVSETTINGSVAR in os.environ: app.config.from_envvar(ENVSETTINGSVAR) def get_maf(genome, alignment, chrom): return os.path.join( app.config['UCSC_DIR'], 'goldenPath', genome, alignment, 'maf', '{0}.maf.bz2'.format(chrom)) @app.route('/alignment/<genome>/<alignment>/<chrom>/<int:start>/<int:end>') def alignment(genome, alignment, chrom, start, end): chop = bool(int(request.headers.get('Chop', 0))) mincols = int(request.headers.get('Min-Cols', 0)) src = '{0}.{1}'.format(genome, chrom) # app.logger.info(request.headers.get('User-Agent')) # app.logger.info(chop) index = bx.align.maf.MultiIndexed( [get_maf(genome, alignment, chrom)], keep_open=True, parse_e_rows=True, use_cache=True) # Write MAF into string output = cStringIO.StringIO() out = bx.align.maf.Writer(output) strand = None # Find overlap with reference component blocks = index.get(src, start, end) # Write each intersecting block if chop: for block in blocks: ref = block.get_component_by_src(src) slice_start = max(start, ref.get_forward_strand_start()) slice_end = min(end, ref.get_forward_strand_end()) sliced = block.slice_by_component(ref, slice_start, slice_end) # If the block is shorter than the minimum allowed size, stop if mincols and (sliced.text_size < mincols): continue # If the reference component is empty, don't write the block if sliced.get_component_by_src(src).size < 1: continue # Keep only components that are not empty sliced.components = [c for c in sliced.components if c.size > 0] # Reverse complement if needed if (strand is not None) and (ref.strand != strand): sliced = sliced.reverse_complement() # Write the block out.write(sliced) else: for block in blocks: out.write(block) result = output.getvalue() output.close() # Close output MAF index.close() out.close() return result if __name__ == '__main__': app.run(host='0.0.0.0', port=9083)
Python
0
@@ -39,16 +39,38 @@ mport os +%0Aimport io%0Aimport ete2 %0A%0Afrom f @@ -95,16 +95,27 @@ request +, send_file %0AENVSETT @@ -370,27 +370,37 @@ )%0A%0A%0Adef get_ -maf +alignment_dir (genome, ali @@ -405,23 +405,16 @@ lignment -, chrom ):%0A r @@ -490,62 +490,1046 @@ ome, -%0A alignment, 'maf', '%7B0%7D.maf.bz2'.format(chrom) + alignment)%0A%0A%0Adef get_maf(genome, alignment, chrom):%0A return os.path.join(get_alignment_dir(genome, alignment),%0A 'maf', '%7B0%7D.maf.bz2'.format(chrom))%0A%0A%0Adef get_treefile(genome, alignment, treename):%0A return os.path.join(get_alignment_dir(genome, alignment),%0A '%7B0%7D.nh'.format(treename))%0A%0A%0A@app.route('/newick/%3Cgenome%3E/%3Calignment%3E/%3Ctreename%3E')%0Adef newick(genome, alignment, treename):%0A return open(get_treefile(genome, alignment, treename)).read()%0A%0A%0A@app.route('/treeview/%3Cgenome%3E/%3Calignment%3E/%3Ctreename%3E')%0Adef treeview(genome, alignment, treename):%0A tree = ete2.Tree(open(get_treefile(genome, alignment, treename)).read())%0A ts = ete2.TreeStyle()%0A ts.show_leaf_name = True%0A ts.show_branch_length = True%0A ts.show_branch_support = True%0A treefilename = '/tmp/treeview.png'%0A tree.render(treefilename, tree_style=ts)%0A return send_file(io.BytesIO(open(treefilename).read()),%0A attachment_filename='logo.png',%0A mimetype='image/png' )%0A%0A%0A
d060a9ad8483b86c1417ac4e439b90d2a35c6f2f
Fix management command for Django 1.11.
kitsune/sumo/management/commands/extract_db.py
kitsune/sumo/management/commands/extract_db.py
import os from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.db.models.loading import get_model HEADER = """\ ####################################################################### # # Note: This file is a generated file--do not edit it directly! # Instead make changes to the appropriate content in the database or # write up a bug here: # # https://bugzilla.mozilla.org/enter_bug.cgi?product=support.mozilla.org # # with the specific lines that are problematic and why. # # You can generate this file by running: # # ./manage.py extract_db # ####################################################################### """ L10N_STRING = u'pgettext("{context}", """{id}""")\n' class Command(BaseCommand): """ Pulls strings from the database and puts them in a python file, wrapping each one in a gettext call. The models and attributes to pull are defined by DB_LOCALIZE: DB_LOCALIZE = { 'some_app': { SomeModel': { 'attrs': ['attr_name', 'another_attr'], } }, 'another_app': { AnotherModel': { 'attrs': ['more_attrs'], 'comments': ['Comment that will appear to localizers.'], } }, } Database columns are expected to be CharFields or TextFields. """ help = ('Pulls strings from the database and writes them to python file.') def add_arguments(self, parser): parser.add_argument( '--output-file', '-o', default=os.path.join( settings.ROOT, 'kitsune', 'sumo', 'db_strings.py'), dest='outputfile', help=( 'The file where extracted strings are written to. ' '(Default: %default)'), ) def handle(self, *args, **options): try: apps = settings.DB_LOCALIZE except AttributeError: raise CommandError('DB_LOCALIZE setting is not defined!') strings = [] for app, models in apps.items(): for model, params in models.items(): model_class = get_model(app, model) attrs = params['attrs'] qs = model_class.objects.all().values_list(*attrs).distinct() for item in qs: for i in range(len(attrs)): if not item[i]: # Skip empty strings because empty string msgids # are super bad. continue msg = { 'id': item[i], 'context': 'DB: %s.%s.%s' % (app, model, attrs[i]), 'comments': params.get('comments')} strings.append(msg) py_file = os.path.expanduser(options.get('outputfile')) py_file = os.path.abspath(py_file) print 'Outputting db strings to: {filename}'.format(filename=py_file) with open(py_file, 'w+') as f: f.write(HEADER) f.write('from django.utils.translation import pgettext\n\n') for s in strings: comments = s['comments'] if comments: for c in comments: f.write(u'# {comment}\n'.format(comment=c).encode('utf8')) f.write(L10N_STRING.format(id=s['id'], context=s['context']).encode('utf8'))
Python
0
@@ -119,42 +119,24 @@ ngo. -db.models.loading import get_model +apps import apps %0A%0A%0AH @@ -1876,16 +1876,23 @@ +django_ apps = s @@ -2061,16 +2061,23 @@ dels in +django_ apps.ite @@ -2161,16 +2161,21 @@ class = +apps. get_mode @@ -2970,17 +2970,17 @@ print - +( 'Outputt @@ -3034,16 +3034,17 @@ py_file) +) %0A
4d5b82a33473475adc3042f7fb6a2718cb17e9fe
handle resource leak
python/selenium_load_page/selenium_load_page.py
python/selenium_load_page/selenium_load_page.py
#!/usr/bin/python ##------------------------------------------------------------------- ## ## File : selenium_load_page.py ## Author : ## Description : ## Test page loading with selenium: slow load, severe ## errors when launching network requests, and save screenshots as images. ## ## More reading: http://www.dennyzhang.com/selenium_docker/ ## ## Sample: ## - Test page load: basic test ## python ./selenium_load_page.py --page_url http://www.dennyzhang.com ## ## - Test page load: if it takes more than 5 seconds, fail the test. Default timeout is 10 seconds ## python ./selenium_load_page.py --page_url http://www.dennyzhang.com --max_load_seconds 5 ## ## - Test page load: after page loading, save screenshot ## python ./selenium_load_page.py --page_url http://www.dennyzhang.com --should_save_screenshot true ## ## -- ## Created : <2017-02-24> ## Updated: Time-stamp: <2017-04-24 13:12:44> ##------------------------------------------------------------------- import sys, argparse from datetime import datetime import time from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities def load_page(page_url, remote_server, max_load_seconds, \ screenshot_dir, should_save_screenshot): load_timeout = 120 # seconds is_ok = True driver = webdriver.Remote(command_executor = remote_server, \ desired_capabilities=DesiredCapabilities.CHROME) # Cleanup cache driver.delete_all_cookies() driver.set_page_load_timeout(load_timeout) print("Open page: %s" % (page_url)) start_clock = time.clock() p = driver.get(page_url) end_clock = time.clock() elapsed_seconds = ((end_clock - start_clock) * 1000) if elapsed_seconds > max_load_seconds: print("ERROR: page load too slow. It took %f seconds, more than %d" \ % (elapsed_seconds, max_load_seconds)) is_ok = False else: print("Page load took: %f seconds." % (elapsed_seconds)) all_warnings = driver.get_log('browser') critical_errors = [] for warning in all_warnings: if warning['level'] == 'SEVERE': critical_errors.append(warning) if len(critical_errors) != 0: print("ERROR: severe errors have happened when loading the page. Details:\n\t%s" \ % "\n\t".join([str(error) for error in critical_errors])) is_ok = False save_screenshot_filepath = "%s/%s-%s.png" % \ (screenshot_dir, datetime.now().strftime('%Y-%m-%d_%H%M%S'), \ page_url.rstrip("/").split("/")[-1]) if should_save_screenshot is True: print("Save screenshot to %s" % (save_screenshot_filepath)) driver.get_screenshot_as_file(save_screenshot_filepath) driver.close() return is_ok if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--page_url', required=True, help="URL for the web page to test", type=str) parser.add_argument('--remote_server', required=False, default="http://127.0.0.1:4444/wd/hub", \ help="Remote selenium server to run the test", type=str) parser.add_argument('--max_load_seconds', required=False, default=10, \ help="If page load takes too long, quit the test", type=int) parser.add_argument('--should_save_screenshot', required=False, dest='should_save_screenshot', \ action='store_true', default=True, \ help="Once enabled, selenium will save the page as screenshot in the selenium server", \ type=bool) parser.add_argument('--screenshot_dir', required=False, default="/tmp/screenshot""", \ help="Where to save screenshots", type=str) l = parser.parse_args() page_url = l.page_url remote_server = l.remote_server max_load_seconds = l.max_load_seconds should_save_screenshot = l.should_save_screenshot screenshot_dir = l.screenshot_dir # Run page loading test is_ok = load_page(page_url, remote_server, max_load_seconds, \ screenshot_dir, should_save_screenshot) if is_ok is False: sys.exit(1) ## File : selenium_load_page.py ends
Python
0.000001
@@ -1543,24 +1543,26 @@ okies()%0A%0A + # driver.set_ @@ -2865,16 +2865,34 @@ close()%0A + driver.quit()%0A retu
a7db7bdb277eed65c93fbc9f5e9e923487711071
Update file_system_storage.py
image_diet/file_system_storage.py
image_diet/file_system_storage.py
import os from image_diet import settings from django.conf import settings as main_settings from django.contrib.staticfiles.storage import StaticFilesStorage class ImageDietFileSystemStorage(StaticFilesStorage): def post_process(self, files, *args, **kwargs): results = [] print settings die if settings.DIET_COMPRESS_STATIC_IMAGES: if 'image_diet' not in main_settings.INSTALLED_APPS: raise NotImplementedError("You need to install django_image_diet to use DIET_COMPRESS_STATIC_IMAGES") from image_diet.diet import squeeze for f in files: processed_file = squeeze(os.path.join(main_settings.STATIC_ROOT, f)) results.append([f, processed_file, True if processed_file is not None else False]) return results
Python
0.000002
@@ -281,16 +281,37 @@ ts = %5B%5D%0A + print 'test'%0A
9c3b3cb541e8d42d1206fabae83fbef4a249f3ec
bump version
backslash/__version__.py
backslash/__version__.py
__version__ = "2.3.1"
Python
0
@@ -14,9 +14,9 @@ %222. -3.1 +4.0 %22%0A
2f76784cc016f9ed5afef704cbcf8a445af9fc45
Fix the test by sorting the results before comparing
flocker/cli/functional/test_deploy_script.py
flocker/cli/functional/test_deploy_script.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Functional tests for the ``flocker-deploy`` command line tool. """ from subprocess import check_output, CalledProcessError import time from unittest import skipUnless from twisted.python.procutils import which from twisted.python.filepath import FilePath from twisted.trial.unittest import TestCase from ...testtools.ssh import create_ssh_server, create_ssh_agent from .._sshconfig import OpenSSHConfiguration from ...control import Deployment, Node from ..script import DeployScript from ... import __version__ _require_installed = skipUnless(which("flocker-deploy"), "flocker-deploy not installed") class FlockerDeployTests(TestCase): """ Tests for ``flocker-deploy``. """ @_require_installed def setUp(self): pass def test_version(self): """``flocker-deploy --version`` returns the current version.""" result = check_output([b"flocker-deploy"] + [b"--version"]) self.assertEqual(result, b"%s\n" % (__version__,)) class FlockerDeployConfigureSSHTests(TestCase): """ Tests for ``DeployScript._configure_ssh``. """ @_require_installed def setUp(self): self.sshd_config = FilePath(self.mktemp()) self.server = create_ssh_server(self.sshd_config) self.addCleanup(self.server.restore) self.flocker_config = FilePath(self.mktemp()) self.local_user_ssh = FilePath(self.mktemp()) self.config = OpenSSHConfiguration( ssh_config_path=self.local_user_ssh, flocker_path=self.flocker_config) self.configure_ssh = self.config.configure_ssh # ``configure_ssh`` expects ``ssh`` to already be able to # authenticate against the server. Set up an ssh-agent to # help it do that against our testing server. self.agent = create_ssh_agent(self.server.key_path, self) def test_installs_public_sshkeys(self): """ ``DeployScript._configure_ssh`` installs the cluster wide public ssh keys on each node in the supplied ``Deployment``. """ deployment = Deployment( nodes=frozenset([ Node( hostname=str(self.server.ip), applications=None ), # Node( # hostname='node2.example.com', # applications=None # ) ]) ) script = DeployScript( ssh_configuration=self.config, ssh_port=self.server.port) result = script._configure_ssh(deployment) local_key = self.local_user_ssh.child(b'id_rsa_flocker.pub') authorized_keys = self.sshd_config.descendant([ b'home', b'.ssh', b'authorized_keys']) def check_authorized_keys(ignored): self.assertIn(local_key.getContent().rstrip(), authorized_keys.getContent().splitlines()) result.addCallback(check_authorized_keys) return result def test_sshkey_installation_failure(self): """ ``DeployScript._configure_ssh`` fires with an errback if one of the configuration attempts fails. """ def fail(host, port): raise ZeroDivisionError() self.config.configure_ssh = fail deployment = Deployment( nodes=frozenset([ Node( hostname=str(self.server.ip), applications=None ), ]) ) script = DeployScript( ssh_configuration=self.config, ssh_port=self.server.port) result = script._configure_ssh(deployment) result.addErrback(lambda f: f.value.subFailure) result = self.assertFailure(result, ZeroDivisionError) # Handle errors logged by gather_deferreds self.addCleanup(self.flushLoggedErrors, ZeroDivisionError) return result def test_sshkey_installation_ssh_process_failure(self): """ ``DeployScript._configure_ssh`` fires with a ``SystemExit`` errback containing the SSH process output if one of the configuration attempts fails. """ def fail(host, port): raise CalledProcessError(1, "ssh", output=b"onoes") self.config.configure_ssh = fail deployment = Deployment( nodes=frozenset([ Node( hostname=str(self.server.ip), applications=None ), ]) ) script = DeployScript( ssh_configuration=self.config, ssh_port=self.server.port) result = script._configure_ssh(deployment) result = self.assertFailure(result, SystemExit) result.addCallback(lambda exc: self.assertEqual( exc.args, (b"Error connecting to cluster node: onoes",))) # Handle errors logged by gather_deferreds self.addCleanup(self.flushLoggedErrors, CalledProcessError) return result def test_sshkey_installation_failure_logging(self): """ ``DeployScript._configure_ssh`` logs all failed configuration attempts. """ expected_errors = [ ZeroDivisionError("error1"), ZeroDivisionError("error2"), ZeroDivisionError("error3"), ] # SSH configuration is performed in parallel threads so the order of # logged errors depends on the thread scheduling. Introduce some # delays, so that we can see this clearly expected_delays = [0.2, 0.1, 0] error_iterator = iter(zip(expected_delays, expected_errors)) def fail(host, port): delay, error = error_iterator.next() time.sleep(delay) raise error self.config.configure_ssh = fail deployment = Deployment( nodes=frozenset([ Node( hostname=b'node1.example.com', applications=None ), Node( hostname=b'node2.example.com', applications=None ), Node( hostname=b'node3.example.com', applications=None ), ]) ) script = DeployScript( ssh_configuration=self.config, ssh_port=self.server.port) result = script._configure_ssh(deployment) def check_logs(ignored_first_error): failures = self.flushLoggedErrors(ZeroDivisionError) self.assertEqual( expected_errors, [f.value for f in failures] ) result.addErrback(check_logs) return result
Python
0.001031
@@ -6676,32 +6676,39 @@ +sorted( expected_errors, @@ -6706,16 +6706,17 @@ d_errors +) ,%0A @@ -6725,17 +6725,23 @@ -%5B +sorted( f.value @@ -6757,17 +6757,17 @@ failures -%5D +) %0A
9834fab5a7e061f0eb1cb7b737cec8d2b23b4c7c
Declare numpydoc template in setup_package.py
astropy_helpers/extern/setup_package.py
astropy_helpers/extern/setup_package.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): return {'astropy_helpers.extern': ['automodapi/templates/*/*.rst']}
Python
0.000001
@@ -151,11 +151,39 @@ */*.rst' +, 'numpydoc/templates/*.rst' %5D%7D%0A
65636f9545018b887f7a8aa6c063de63570119c9
Load DOS briefs_search_filters separately
app/__init__.py
app/__init__.py
from flask import Flask, request, redirect, session, abort from flask_login import LoginManager from flask_wtf.csrf import CsrfProtect import dmapiclient from dmutils import init_app, flask_featureflags from dmcontent.content_loader import ContentLoader from dmutils.user import User from config import configs login_manager = LoginManager() data_api_client = dmapiclient.DataAPIClient() search_api_client = dmapiclient.SearchAPIClient() feature_flags = flask_featureflags.FeatureFlag() csrf = CsrfProtect() content_loader = ContentLoader('app/content') from .main.helpers.framework_helpers import get_latest_live_framework def create_app(config_name): application = Flask(__name__) init_app( application, configs[config_name], data_api_client=data_api_client, feature_flags=feature_flags, login_manager=login_manager, search_api_client=search_api_client ) frameworks = data_api_client.find_frameworks().get('frameworks') for framework_data in frameworks: if not framework_data['slug'] in application.config.get('DM_FRAMEWORK_CONTENT_MAP', {}): if framework_data['framework'] == 'g-cloud': if framework_data['status'] != 'expired': content_loader.load_manifest(framework_data['slug'], 'services', 'services_search_filters') # we need to be able to display old services, even on expired frameworks content_loader.load_manifest(framework_data['slug'], 'services', 'display_service') content_loader.load_manifest(framework_data['slug'], 'services', 'download_results') elif framework_data['framework'] == 'digital-outcomes-and-specialists': content_loader.load_manifest(framework_data['slug'], 'briefs', 'display_brief') content_loader.load_manifest( get_latest_live_framework(frameworks, 'digital-outcomes-and-specialists')['slug'], 'briefs', 'briefs_search_filters', ) from .main import main as main_blueprint from .main import direct_award as direct_award_blueprint from .external.views.external import external as external_blueprint from .status import status as status_blueprint application.register_blueprint(status_blueprint) application.register_blueprint(main_blueprint) application.register_blueprint(direct_award_blueprint) application.register_blueprint(external_blueprint) login_manager.login_view = '/user/login' login_manager.login_message_category = "must_login" csrf.init_app(application) @csrf.error_handler def csrf_handler(reason): if 'user_id' not in session: application.logger.info( u'csrf.session_expired: Redirecting user to log in page' ) return application.login_manager.unauthorized() application.logger.info( u'csrf.invalid_token: Aborting request, user_id: {user_id}', extra={'user_id': session['user_id']}) abort(400, reason) @application.before_request def remove_trailing_slash(): if request.path != '/' and request.path.endswith('/'): if request.query_string: return redirect( '{}?{}'.format( request.path[:-1], request.query_string.decode('utf-8') ), code=301 ) else: return redirect(request.path[:-1], code=301) @application.before_request def refresh_session(): session.permanent = True session.modified = True return application @login_manager.user_loader def load_user(user_id): return User.load_user(data_api_client, user_id)
Python
0
@@ -2000,24 +2000,26 @@ rs',%0A )%0A%0A +%0A%0A from .ma
8bc306d466034d0d44fc41e935a5499631011149
Add missing module
factory/glideFactory.py
factory/glideFactory.py
# # Description: # This is the main of the glideinFactory # # Arguments: # $1 = poll period (in seconds) # $2 = advertize rate (every $2 loops) # $3 = glidein submit_dir # # Author: # Igor Sfiligoi (Apr 9th 2007 - moved old glideFactory to glideFactoryEntry) # import os import os.path import sys import fcntl import traceback import time import string import copy #import threading sys.path.append("../lib") import glideFactoryConfig import glideFactoryLib #import glideFactoryMonitoring import logSupport ############################################################ def spawn(cleanupObj,sleep_time,advertize_rate,startup_dir, glideinDescript,entries): childs={} try: for entry_name in entries: childs[entry_name]=popen2.Popen3("%s glideFactoryEntry.py %s %s %s %s"%(sys.executable,sleep_time,advertize_rate,startup_dir,entry_name),True) for entry_name in childs.keys(): childs[entry_name].tochild.close() while 1: for entry_name in childs.keys(): child=childs[entry_name] if child.poll()!=-1: # the child exited tempOut = child.fromchild.readlines() tempErr = child.childerr.readlines() del childs[entry_name] raise RuntimeError,"Entry '%s' exited, quit the whole factory:\n%s\n%s"%(entry_name,tempOut,tempErr) time.sleep(sleep_time) finally: # cleanup at exit for entry_name in childs.keys(): os.kill(childs[entry_name].pid) ############################################################ def main(sleep_time,advertize_rate,startup_dir): startup_time=time.time() # create log files in the glidein log directory activity_log=logSupport.DayLogFile(os.path.join(startup_dir,"log/factory_info")) warning_log=logSupport.DayLogFile(os.path.join(startup_dir,"log/factory_err")) glideFactoryLib.factoryConfig.activity_log=activity_log glideFactoryLib.factoryConfig.warning_log=warning_log #glideFactoryMonitoring.monitoringConfig.monitor_dir=os.path.join(startup_dir,"monitor") cleanupObj=logSupport.DirCleanup(os.path.join(startup_dir,"log"),"(factory_info\..*)|(factory_err\..*)", 7*24*3600, activity_log,warning_log) glideFactoryConfig.factoryConfig.glidein_descript_file=os.path.join(startup_dir,glideFactoryConfig.factoryConfig.glidein_descript_file) glideinDescript=glideFactoryConfig.GlideinDescript() entries=string.split(glideinDescript.data['Entries'],',') # check lock file lock_file=os.path.join(startup_dir,"glideinWMS.lock") if not os.path.exists(lock_file): #create a lock file if needed fd=open(lock_file,"w") fd.close() fd=open(lock_file,"r+") try: fcntl.flock(fd,fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: fd.close() raise RuntimeError, "Another glidein factory already running" fd.seek(0) fd.truncate() fd.write("PID: %s\nStarted: %s\n"%(os.getpid(),time.ctime(startup_time))) fd.flush() # start try: spawn(cleanupObj,sleep_time,advertize_rate,startup_dir, glideinDescript,entries) finally: fd.close() ############################################################ # # S T A R T U P # ############################################################ if __name__ == '__main__': main(int(sys.argv[1]),int(sys.argv[2]),sys.argv[3])
Python
0.000016
@@ -314,16 +314,30 @@ t fcntl%0A +import popen2%0A import t
a37d8a9874898b072b72c85a8b611e46a459a19e
Move order of installed apps
imagersite/imagersite/settings.py
imagersite/imagersite/settings.py
""" Django settings for imagersite project. Generated by 'django-admin startproject' using Django 1.8.3. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TESTING = 'test' in sys.argv # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '=l8!p3)j!gw59j1p+d#vkpp-e!8smm%4_=y_6&k1=0o5qd53b^' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'imager_profile', 'imager_images', 'bootstrap3', 'registration', ) ACCOUNT_ACTIVATION_DAYS = 7 MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'imagersite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'imagersite.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 'TEST': { 'NAME': os.path.join(BASE_DIR, 'testdb.sqlite3') } } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Los_Angeles' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') # Media file handling MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_test' if TESTING else 'media') MEDIA_TEST = os.path.join(BASE_DIR, 'media_test') EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
Python
0.000001
@@ -1111,81 +1111,81 @@ ' -imager_profile',%0A 'imager_images',%0A 'bootstrap3',%0A 'registration +bootstrap3',%0A 'registration',%0A 'imager_profile',%0A 'imager_images ',%0A)
220708945a18b5d876cdff32dcfb9b8b8971d85b
Add time/space complexity
lc017_letter_combinations_of_a_phone_number.py
lc017_letter_combinations_of_a_phone_number.py
"""Leetcode 17. Letter Combinations of a Phone Number Medium URL: https://leetcode.com/problems/letter-combinations-of-a-phone-number/ Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters. Example: Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want. """ class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ # Store digit->letter-list dict. d2l_d = { '2': ['a', 'b', 'c'], '3': ['d', 'e', 'f'], '4': ['g', 'h', 'i'], '5': ['j', 'k' ,'l'], '6': ['m', 'n', 'o'], '7': ['p', 'q', 'r', 's'], '8': ['t', 'u', 'v'], '9': ['w', 'x', 'y', 'z'] } # Edge cases handling. if not digits: return [] if len(digits) == 1: return d2l_d[digits] # Initialize output lc by the 0th digit's letter-list. lc = d2l_d[digits[0]] # Run for loop over digits starting from index i = 1. # - Get the ith digit's letter list li. # - Use list comprehension to combine lc and li to replace lc. for i in range(1, len(digits)): li = d2l_d[digits[i]] lc = [m + n for m in lc for n in li] return lc def main(): digits = "23" # Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. print Solution().letterCombinations(digits) if __name__ == '__main__': main()
Python
0.002369
@@ -711,16 +711,193 @@ st%5Bstr%5D%0A + %0A Time complexity: O(n * m%5E2)%0A - n is the length of digits,%0A - m is the mean length of digit's letters, basically 3.%0A Space complexity: O(m%5En).%0A
8161561499e813c8821d6f810e6e28d4e3984922
Update __init__.py
app/__init__.py
app/__init__.py
from flask import Flask, render_template from flask_assets import Bundle, Environment from flask_socketio import SocketIO, emit from flask.ext.mail import Mail from flask.ext.login import LoginManager from flask.ext.moment import Moment from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.pagedown import PageDown from flask.ext.flatpages import FlatPages from flask.ext.cache import Cache from flask_sitemap import Sitemap from config import config mail = Mail() moment = Moment() pagedown = PageDown() pages = FlatPages() db = SQLAlchemy() cache = Cache(config={'CACHE_TYPE': 'simple'}) ext = Sitemap() socketio = SocketIO() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' def create_app(config_name): app = Flask(__name__) assets = Environment(app) app.config.from_object(config[config_name]) config[config_name].init_app(app) if not app.debug and not app.testing and not app.config['SSL_DISABLE']: from flask.ext.sslify import SSLify sslify = SSLify(app) mail.init_app(app) moment.init_app(app) pagedown.init_app(app) pages.init_app(app) cache.init_app(app) ext.init_app(app) socketio.init_app(app) db.init_app(app) login_manager.init_app(app) from .main import main as main_blueprint from .auth import auth as auth_blueprint from .api_1_0 import api as api_1_0_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') app.register_blueprint(main_blueprint) app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0') root_js = Bundle( 'js/vendors/jquery-2.1.1.min.js', #'js/vendors/materialize.min.js', 'js/app.js', 'js/init.js', output='dist/bundle.js') root_css = Bundle( 'css/vendors/reset.css', 'css/vendors/materialize.min.css', 'css/style.css', 'css/common.css', 'css/app.css', output='dist/styles.css') assets.register('root_js', root_js) assets.register('root_css', root_css) return app
Python
0.000072
@@ -83,50 +83,8 @@ ent%0A -from flask_socketio import SocketIO, emit%0A from @@ -568,30 +568,8 @@ p()%0A -socketio = SocketIO()%0A logi @@ -1152,35 +1152,8 @@ pp)%0A - socketio.init_app(app)%0A
2b482f638a2ff51eeed595b15f338333b5dd8856
Fix --no-progress-bar option in generate.py (#115)
fairseq/progress_bar.py
fairseq/progress_bar.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # """ Progress bar wrapper around tqdm which handles non-TTY outputs. """ from collections import OrderedDict from numbers import Number import sys from tqdm import tqdm class progress_bar(tqdm): enabled = sys.stderr.isatty() print_interval = 1000 def __new__(cls, *args, **kwargs): if cls.enabled: return tqdm(*args, **kwargs) else: return simple_progress_bar(cls.print_interval, *args, **kwargs) class simple_progress_bar(object): """A minimal replacement for tqdm in non-TTY environments.""" def __init__(self, print_interval, iterable, desc, *_args, **_kwargs): super().__init__() self.print_interval = print_interval self.iterable = iterable self.desc = desc def __enter__(self): return self def __exit__(self, *exc): return False def __iter__(self): size = len(self.iterable) for i, obj in enumerate(self.iterable): yield obj if i > 0 and i % self.print_interval == 0: msg = '{}: {:5d} / {:d} {}\n'.format(self.desc, i, size, self.postfix) sys.stdout.write(msg) sys.stdout.flush() def set_postfix(self, ordered_dict=None, refresh=True, **kwargs): # Sort in alphabetical order to be more deterministic postfix = OrderedDict([] if ordered_dict is None else ordered_dict) for key in sorted(kwargs.keys()): postfix[key] = kwargs[key] # Preprocess stats according to datatype for key in postfix.keys(): # Number: limit the length of the string if isinstance(postfix[key], Number): postfix[key] = '{0:2.3g}'.format(postfix[key]) # Else for any other type, try to get the string conversion elif not isinstance(postfix[key], str): postfix[key] = str(postfix[key]) # Else if it's a string, don't need to preprocess anything # Stitch together to get the final postfix self.postfix = ', '.join(key + '=' + postfix[key].strip() for key in postfix.keys()) @classmethod def write(cls, s, file=None, end="\n"): fp = file if file is not None else sys.stdout fp.write(s) fp.write(end) fp.flush()
Python
0.000003
@@ -891,16 +891,21 @@ le, desc +=None , *_args @@ -1346,16 +1346,94 @@ +desc = '' if self.desc is None else '%7B%7D: '.format(self.desc)%0A msg = '%7B @@ -1433,19 +1433,16 @@ sg = '%7B%7D -: %7B:5d%7D / @@ -1455,29 +1455,24 @@ %7D%5Cn'.format( -self. desc, i, siz
007c8bd8bba14b2c16ba9a79d47f7c0630d20f85
Add __del__
aioinflux/client.py
aioinflux/client.py
import asyncio import logging from typing import Union, AnyStr, Mapping, Iterable from urllib.parse import urlencode import aiohttp from .line_protocol import parse_data PointType = Union[AnyStr, Mapping] class AsyncInfluxDBClient: def __init__(self, host='localhost', port=8086, database='testdb', username=None, password=None, loop=None, log_level=None): self.logger = self._make_logger(log_level) self.loop = asyncio.get_event_loop() if loop is None else loop self.session = aiohttp.ClientSession(loop=self.loop) self.db = database self.base_url = f'http://{host}:{port}/' self.query_url = self.base_url + 'query' self.write_url = self.base_url + 'write' def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.session.close() async def create_database(self, dbname): data = dict(q=f'CREATE DATABASE {dbname}') return await self._post(self.query_url, data=data) async def write(self, data: Union[PointType, Iterable[PointType]]): """Write query to InfluxDB.""" data = parse_data(data) self.logger.debug(data) url = self.write_url + '?' + urlencode(dict(db=self.db)) return await self._post(url, data=data) async def query(self, q: AnyStr, epoch=None): """Send a query to InfluxDB.""" data = dict(q=q, db=self.db) if epoch: data['epoch'] = epoch return await self._post(self.query_url, data=data) def run(self, coro, *args, **kwargs): """Testing function""" return self.loop.run_until_complete(coro(*args, **kwargs)) async def _post(self, *args, **kwargs): async with self.session.post(*args, **kwargs) as resp: self.logger.info(f'{resp.status}: {resp.reason}') return dict(resp=resp, json=await resp.json()) @staticmethod def _make_logger(log_level): logger = logging.getLogger('aioinflux') formatter = logging.Formatter('%(asctime)s | %(name)s | %(levelname)s: %(message)s') if log_level and not logger.handlers: logger.setLevel(log_level) stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) return logger
Python
0.0006
@@ -862,16 +862,69 @@ lose()%0A%0A + def __del__(self):%0A self.session.close()%0A%0A asyn
cc734b39fe18ae66fee0f5b35deaf4f864fa9a4f
remove old imports
game.py
game.py
# from cardsource import * # import cardsource as cs from collections import deque class SheddingGame(object): """ Represents a Shedding-type game https://en.wikipedia.org/wiki/Shedding-type_game """ def __init__(self, deck): super(SheddingGame, self).__init__() self.players = deque() self.state = {'deck': deck, 'round': 0} def add_player(self, player): self.players.append(player) def next_player(self): self.players.rotate(1) return self.players[0] def deal_all_cards(self): ''' Deal all cards to all players ''' self.state['deck'].shuffle() while len(self.state['deck']) > 0: card = self.state['deck'].pop() player = self.next_player() player.hand.append(card) def setup(self): ''' Deal cards and setup board ''' raise NotImplemented("Cannot setup without a specific game!") def round(self): ''' A single round of the game ''' for p in self.players: card = p.play() if (not 'X' in card.rank): # skip their turn if they play a joker print "Player " + p.name + " chose " + str(card) try: p.hand.remove(card) except ValueError: print "illegal move, card not in hand!" exit(1) self.update_state(card) self.update_players() if (self.victory(p)): return p else: print "Skipping " + p.name + "'s turn" return None def run(self): while True: print "Playing round " + str(self.state['round']) self.state['round'] += 1 winner = self.round() if winner: print "Player " + str(winner.name) + " has won!" break def legal(self, card): raise NotImplemented("Cannot check legality without a specific game!") def update_state(self, card): raise NotImplemented("Cannot update_state without a specific game!") def update_players(self): ''' Construct an update message and send it to all players ''' raise NotImplemented("Cannot update_players without a specific game!") def finish(self): raise NotImplemented("Cannot finish without a specific game!") def victory(self, player): raise NotImplemented("Cannot declare victory without a specific game!") def print_state(self): print self.state
Python
0.998694
@@ -1,57 +1,4 @@ -# from cardsource import *%0A# import cardsource as cs%0A from
65f8dc529a78593621f4f2b2477707b8e877f0d3
Add Mooseman to privileged users. --autopull
globalvars.py
globalvars.py
import os from datetime import datetime from ChatExchange.chatexchange.client import Client import HTMLParser class GlobalVars: false_positives = [] whitelisted_users = [] blacklisted_users = [] ignored_posts = [] auto_ignored_posts = [] startup_utc = datetime.utcnow().strftime("%H:%M:%S") latest_questions = [] blockedTime = 0 charcoal_room_id = "11540" meta_tavern_room_id = "89" site_filename = { "electronics.stackexchange.com" : "ElectronicsGood.txt", "gaming.stackexchange.com" : "GamingGood.txt", "german.stackexchange.com" : "GermanGood.txt", "italian.stackexchange.com" : "ItalianGood.txt", "math.stackexchange.com" : "MathematicsGood.txt", "spanish.stackexchange.com" : "SpanishGood.txt", "stats.stackexchange.com" : "StatsGood.txt" } parser = HTMLParser.HTMLParser() wrap = Client("stackexchange.com") wrapm = Client("meta.stackexchange.com") privileged_users = { charcoal_room_id: ["117490", "66258", "31768","103081","73046","88521","59776", "31465"], meta_tavern_room_id: ["259867", "244519", "244382", "194047", "158100", "178438", "237685", "215468", "229438", "180276", "161974", "244382", "186281", "266094", "245167", "230261", "213575", "241919", "203389"] } smokeDetector_user_id = { charcoal_room_id: "120914", meta_tavern_room_id: "266345" } commit = os.popen("git log --pretty=format:'%h' -n 1").read() commit_with_author = os.popen("git log --pretty=format:'%h (%cn: *%s*)' -n 1").read() on_master = os.popen("git rev-parse --abbrev-ref HEAD").read().strip() == "master" charcoal_hq = None tavern_on_the_meta = None s = "" s_reverted = "" specialrooms = [] bayesian_testroom = None apiquota = -1 bodyfetcher = None
Python
0
@@ -1416,16 +1416,26 @@ %22203389%22 +, %22202832%22 %5D %7D%0A
b518de210dc3ae075beea60a06e981844ecff3d8
fix lint errors
app/__init__.py
app/__init__.py
import os from flask import Flask, render_template from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.openid import OpenID from flask.ext.mail import Mail from config import config, basedir db = SQLAlchemy() mail = Mail() login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login' oid = OpenID(fs_store_path=os.path.join(basedir, 'tmp')) def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) config[config_name].init_app(app) mail.init_app(app) db.init_app(app) login_manager.init_app(app) oid.init_app(app) from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app
Python
0.000037
@@ -30,25 +30,8 @@ lask -, render_template %0Afro @@ -421,16 +421,17 @@ tmp'))%0A%0A +%0A def crea
f775efb26a274f6a77c30ac70a17eeee8c215011
Update fields.py
graphene_django_extras/paginations/fields.py
graphene_django_extras/paginations/fields.py
# -*- coding: utf-8 -*- from functools import partial from math import fabs from graphene import Field, Int, List, NonNull, String from .utils import _nonzero_int, _get_count from ..settings import graphql_api_settings __all__ = ('LimitOffsetPaginationField', 'PagePaginationField', 'CursorPaginationField') class AbstractPaginationField(Field): @property def model(self): return self.type.of_type._meta.node._meta.model def get_resolver(self, parent_resolver): return partial(self.list_resolver, self.type.of_type._meta.model._default_manager) # *********************************************** # # ************* PAGINATION FIELDS *************** # # *********************************************** # class LimitOffsetPaginationField(AbstractPaginationField): def __init__(self, _type, default_limit=graphql_api_settings.DEFAULT_PAGE_SIZE, max_limit=graphql_api_settings.MAX_PAGE_SIZE, limit_query_param='limit', offset_query_param='offset', order_query_param='order', *args, **kwargs): kwargs.setdefault('args', {}) self.limit_query_param = limit_query_param self.offset_query_param = offset_query_param self.order_query_param = order_query_para self.max_limit = max_limit self.default_limit = default_limit self.limit_query_description = 'Number of results to return per page. Actual \'default_limit\': {}, and ' \ '\'max_limit\': {}'.format(self.default_limit, self.max_limit) self.offset_query_description = 'The initial index from which to return the results.' kwargs[limit_query_param] = Int(default_value=self.default_limit, description=self.limit_query_description) kwargs[offset_query_param] = Int(default_value=0, description=self.offset_query_description) kwargs[order_query_param] = String(default_value='', description=self.order_query_description) super(LimitOffsetPaginationField, self).__init__(List(_type), *args, **kwargs) def list_resolver(self, manager, root, info, **kwargs): qs = manager.get_queryset() count = _get_count(qs) limit = _nonzero_int( kwargs.get(self.limit_query_param, None), strict=True, cutoff=self.max_limit ) order = kwargs.pop(self.order_query_param, None) if order: qs = qs.order_by(order) if limit < 0: offset = kwargs.pop(self.offset_query_param, None) or count return qs[offset - fabs(limit):offset] offset = kwargs.pop(self.offset_query_param, 0) return qs[offset:offset + limit] class PagePaginationField(AbstractPaginationField): def __init__(self, _type, page_size=graphql_api_settings.DEFAULT_PAGE_SIZE, page_size_query_param=None, max_page_size=graphql_api_settings.MAX_PAGE_SIZE, *args, **kwargs): kwargs.setdefault('args', {}) # Client can control the page using this query parameter. self.page_query_param = 'page' # The default page size. Defaults to `None`. self.page_size = page_size # Client can control the page size using this query parameter. # Default is 'None'. Set to eg 'page_size' to enable usage. self.page_size_query_param = page_size_query_param # Set to an integer to limit the maximum page size the client may request. # Only relevant if 'page_size_query_param' has also been set. self.max_page_size = max_page_size self.page_size_query_description = 'Number of results to return per page. Actual \'page_size\': {}'.format( self.page_size) kwargs[self.page_query_param] = Int(default_value=1, description='A page number within the result paginated set. Default: 1') if self.page_size_query_param: if not page_size: kwargs[self.page_size_query_param] = NonNull(Int, description=self.page_size_query_description) else: kwargs[self.page_size_query_param] = Int(description=self.page_size_query_description) super(PagePaginationField, self).__init__(List(_type), *args, **kwargs) def list_resolver(self, manager, root, info, **kwargs): qs = manager.get_queryset() count = _get_count(qs) page = kwargs.pop(self.page_query_param, 1) if self.page_size_query_param: page_size = _nonzero_int( kwargs.get(self.page_size_query_param, None), strict=True, cutoff=self.max_page_size ) else: page_size = self.page_size assert page != 0, ValueError('Page value for PageGraphqlPagination must be ' 'greater than or smaller than that zero, not a zero value') assert page_size > 0, ValueError('Page_size value for PageGraphqlPagination must be a non-null value, you must' ' set global DEFAULT_PAGE_SIZE on GRAPHENE_DJANGO_EXTRAS dict on your' ' settings.py or specify a page_size_query_param value on paginations ' 'declaration to specify a custom page size value through a query parameters') offset = int(count - fabs(page_size * page)) if page < 0 else page_size * (page - 1) return qs[offset:offset + page_size] class CursorPaginationField(AbstractPaginationField): def __init__(self, _type, ordering='-created', cursor_query_param='cursor', *args, **kwargs): kwargs.setdefault('args', {}) self.page_size = graphql_api_settings.DEFAULT_PAGE_SIZE self.page_size_query_param = 'page_size' if not self.page_size else None self.cursor_query_param = cursor_query_param self.ordering = ordering self.cursor_query_description = 'The pagination cursor value.' self.page_size_query_description = 'Number of results to return per page.' kwargs[self.cursor_query_param] = NonNull(String, description=self.cursor_query_description) if self.page_size_query_param: if not self.page_size: kwargs[self.page_size_query_param] = NonNull(Int, description=self.page_size_query_description) else: kwargs[self.page_size_query_param] = Int(description=self.page_size_query_description) super(CursorPaginationField, self).__init__(List(_type), *args, **kwargs) def list_resolver(self, manager, root, info, **kwargs): raise NotImplementedError('{} list_resolver() are not implemented yet.'.format(self.__class__.__name__))
Python
0.000001
@@ -1265,16 +1265,17 @@ ery_para +m %0A
10bbd489e4123363ee4ecafe0ca43151f52a9813
Create compatibility settings/functions for pluggable auth user functionality. See #24
allaccess/compat.py
allaccess/compat.py
"Python and Django compatibility functions." from __future__ import unicode_literals from django.conf import settings try: from django.utils.crypto import get_random_string except ImportError: # pragma: no cover # Backport implementation from Django 1.4 import hashlib import random import string import time try: random = random.SystemRandom() using_sysrandom = True except NotImplementedError: import warnings warnings.warn('A secure pseudo-random number generator is not available ' 'on your system. Falling back to Mersenne Twister.') using_sysrandom = False def get_random_string(length=12, allowed_chars=string.ascii_letters + string.digits): "Returns a securely generated random string." if not using_sysrandom: # Re-seed random bytes = b"{0}{1}{2}".format(random.getstate(), time.time(), settings.SECRET_KEY) random.seed(hashlib.sha256(bytes).digest()) return ''.join([random.choice(allowed_chars) for i in range(length)])
Python
0
@@ -114,16 +114,86 @@ tings%0A%0A%0A +AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')%0A%0A%0A try:%0A @@ -1156,8 +1156,206 @@ ngth)%5D)%0A +%0A%0Atry:%0A from django.contrib.auth import get_user_model%0Aexcept ImportError: # pragma: no cover%0A # Django %3C 1.5%0A from django.contrib.auth.models import User%0A get_user_model = lambda: User%0A
15f00997113ecb87de9daf636738bc0b51686918
Fix assertion in AutocompleteList.choices_for_request for empty lists
autocomplete_light/autocomplete/list.py
autocomplete_light/autocomplete/list.py
from __future__ import unicode_literals from django.utils.encoding import force_text __all__ = ('AutocompleteList',) class AutocompleteList(object): """ Simple Autocomplete implementation which expects :py:attr:`choices` to be a list of string choices. .. py:attribute:: choices List of string choices. .. py:attribute:: limit_choices The maximum of items to suggest from :py:attr:`choices`. .. py:attribute:: order_by :py:meth:`~.list.AutocompleteList.order_choices` will use this against :py:attr:`choices` as an argument :py:func:`sorted`. It was mainly used as a starter for me when doing test-driven development and to ensure that the Autocomplete pattern would be concretely simple and yet powerful. """ limit_choices = 20 order_by = lambda cls, choice: force_text(choice).lower() def choices_for_values(self): """ Return any :py:attr:`choices` that is in :py:attr:`values`. """ values_choices = [] for choice in self.choices: if choice in self.values: values_choices.append(choice) return self.order_choices(values_choices) def choices_for_request(self): """ Return any :py:attr:`choices` that contains the search string. It is case insensitive and ignores spaces. """ assert self.choices, 'autocomplete.choices is not set' requests_choices = [] q = self.request.GET.get('q', '').lower().strip() for choice in self.choices: if q in force_text(choice).lower(): requests_choices.append(choice) return self.order_choices(requests_choices)[0:self.limit_choices] def order_choices(self, choices): """ Run :py:func:`sorted` against ``choices`` and :py:attr:`order_by`. """ return sorted(choices, key=self.order_by)
Python
0
@@ -1408,16 +1408,28 @@ .choices + is not None , 'autoc
d92cfdf6644663a6e615e032c6bc6ca52bed3edb
Add DragonLord to privileged users
globalvars.py
globalvars.py
import os from datetime import datetime from ChatExchange.chatexchange.client import Client import HTMLParser class GlobalVars: false_positives = [] whitelisted_users = [] blacklisted_users = [] ignored_posts = [] auto_ignored_posts = [] startup_utc = datetime.utcnow().strftime("%H:%M:%S") latest_questions = [] blockedTime = 0 charcoal_room_id = "11540" meta_tavern_room_id = "89" site_filename = {"electronics.stackexchange.com": "ElectronicsGood.txt", "gaming.stackexchange.com": "GamingGood.txt", "german.stackexchange.com": "GermanGood.txt", "italian.stackexchange.com": "ItalianGood.txt", "math.stackexchange.com": "MathematicsGood.txt", "spanish.stackexchange.com": "SpanishGood.txt", "stats.stackexchange.com": "StatsGood.txt"} parser = HTMLParser.HTMLParser() wrap = Client("stackexchange.com") wrapm = Client("meta.stackexchange.com") privileged_users = {charcoal_room_id: ["117490", "66258", "31768", "103081", "73046", "88521", "59776", "31465"], meta_tavern_room_id: ["259867", "244519", "244382", "194047", "158100", "178438", "237685", "215468", "229438", "180276", "161974", "244382", "186281", "266094", "245167", "230261", "213575", "241919", "203389", "202832"]} smokeDetector_user_id = {charcoal_room_id: "120914", meta_tavern_room_id: "266345"} commit = os.popen("git log --pretty=format:'%h' -n 1").read() commit_with_author = os.popen("git log --pretty=format:'%h (%cn: *%s*)' -n 1").read() on_master = os.popen("git rev-parse --abbrev-ref HEAD").read().strip() == "master" charcoal_hq = None tavern_on_the_meta = None s = "" s_reverted = "" specialrooms = [] bayesian_testroom = None apiquota = -1 bodyfetcher = None
Python
0
@@ -1414,16 +1414,26 @@ %22202832%22 +, %22160017%22 %5D%7D%0A s
cc1000824237cd74dec3e0ff210ee08020c2cd92
add config ini to ament_mypy site package (#182)
ament_mypy/setup.py
ament_mypy/setup.py
from setuptools import find_packages from setuptools import setup setup( name='ament_mypy', version='0.7.3', packages=find_packages(exclude=['test']), install_requires=['setuptools'], zip_safe=False, author='Ted Kern', author_email='ted.kern@canonical.com', maintainer='Ted Kern', maintainer_email='ted.kern@canonical.com', url='https://github.com/ament/ament_lint', download_url='https://github.com/ament/ament_lint/releases', keywords=['ROS'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python', 'Topic :: Software Development', ], description='Check Python static typing using mypy.', long_description="""\ The ability to check code for user specified static typing with mypy.""", license='Apache License, Version 2.0', tests_require=['pytest'], entry_points={ 'console_scripts': [ 'ament_mypy = ament_mypy.main:main', ], }, )
Python
0
@@ -190,24 +190,96 @@ tuptools'%5D,%0A + package_data=%7B'': %5B%0A 'configuration/ament_mypy.ini',%0A %5D%7D,%0A zip_safe
d2eb8bd9588bdda2e05967d10ffc6da786f0e82b
fix LinearFA_Agent batch mode learn method. self.laststate is not defined, use self.lastobs instead
pybrain/rl/agents/linearfa.py
pybrain/rl/agents/linearfa.py
from __future__ import print_function __author__ = 'Tom Schaul, tom@idsia.ch' from pybrain.rl.agents.logging import LoggingAgent from pybrain.utilities import drawIndex from scipy import array class LinearFA_Agent(LoggingAgent): """ Agent class for using linear-FA RL algorithms. """ init_exploration = 0.1 # aka epsilon exploration_decay = 0.99 # per episode init_temperature = 1. temperature_decay = 0.99 # per episode # default is boltzmann exploration epsilonGreedy = False # flags for different modes learning = True greedy = False def __init__(self, learner, **kwargs): LoggingAgent.__init__(self, learner.num_features, 1, **kwargs) self.learner = learner self.learner._behaviorPolicy = self._actionProbs self.reset() def _actionProbs(self, state): if self.greedy: return self.learner._greedyPolicy(state) elif self.epsilonGreedy: return (self.learner._greedyPolicy(state) * (1 - self._expl_proportion) + self._expl_proportion / float(self.learner.num_actions)) else: return self.learner._boltzmannPolicy(state, self._temperature) def getAction(self): self.lastaction = drawIndex(self._actionProbs(self.lastobs), True) if self.learning and not self.learner.batchMode and self._oaro is not None: self.learner._updateWeights(*(self._oaro + [self.lastaction])) self._oaro = None return array([self.lastaction]) def integrateObservation(self, obs): if self.learning and not self.learner.batchMode and self.lastobs is not None: if self.learner.passNextAction: self._oaro = [self.lastobs, self.lastaction, self.lastreward, obs] else: self.learner._updateWeights(self.lastobs, self.lastaction, self.lastreward, obs) LoggingAgent.integrateObservation(self, obs) def reset(self): LoggingAgent.reset(self) self._temperature = self.init_temperature self._expl_proportion = self.init_exploration self.learner.reset() self._oaro = None self.newEpisode() def newEpisode(self): """ Indicate the beginning of a new episode in the training cycle. """ if self.logging: self.history.newSequence() if self.learning and not self.learner.batchMode: self.learner.newEpisode() else: self._temperature *= self.temperature_decay self._expl_proportion *= self.exploration_decay self.learner.newEpisode() def learn(self): if not self.learning: return if not self.learner.batchMode: print('Learning is done online, and already finished.') return for seq in self.history: for obs, action, reward in seq: if self.laststate is not None: self.learner._updateWeights(self.lastobs, self.lastaction, self.lastreward, obs) self.lastobs = obs self.lastaction = action[0] self.lastreward = reward self.learner.newEpisode()
Python
0
@@ -3077,21 +3077,19 @@ elf.last -state +obs is not
3b8385e75f9d6259f085746fe90e6ab3d9dbdc90
Update perms.py
discord/perms.py
discord/perms.py
# -*- coding: utf-8 -*- """Ces fonctions sont utilisรฉes afin de permettre de rรฉcupรฉrer la totalitรฉ des donnรฉes de permissions des utilisateurs. Crรฉรฉ par @Sakiut25#7390 (c)""" ##################################################################################################################################################### def get_perm_admin(user): """Retourne si l'utilisateur a les permissions administrateur ou non""" if user.server_permissions.administrator == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_create_instant_invite(user): """Retourne si l'utilisateur a la permission de crรฉer une invitation ou non""" if user.server_permissions.create_instant_invite == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_kick_members(user): """Retourne si l'utilisateur a la permission de kick un membre ou non""" if user.server_permissions.kick_members == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_ban_members(user): """Retourne si l'utilisateur a la permission de bannir un membre ou non""" if user.server_permissions.ban_members == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_manage_channels(user): """Retourne si l'utilisateur a la permission de gรฉrer les channels ou non""" if user.server_permissions.manage_channels == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_manage_server(user): """Retourne si l'utilisateur a la permission de gรฉrer le serveur ou non""" if user.server_permissions.manage_server == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_add_reactions(user): """Retourne si l'utilisateur a la permission d'ajouter des rรฉactions aux messages ou non""" if user.server_permissions.add_reactions == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_send_tts_messages(user): """Retourne si l'utilisateur a la permission d'envoyer des TTS ou non""" if user.server_permissions.send_tts_messages == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_manage_messages(user): """Retourne si l'utilisateur a la permission de gรฉrer les messages ou non""" if user.server_permissions.manage_messages == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_mute(user): """Retourne si l'utilisateur a la permission de mute ou non""" if user.server_permissions.mute_members == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_deafen(user): """Retourne si l'utilisateur a la permission d'assourdir ou non""" if user.server_permissions.deafen_members == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_send_embed_links(user): """Returns True if a userโ€™s messages will automatically be embedded by Discord.""" if user.server_permissions.embed_links == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_attach_files(user): """Retourne si l'utilisateur a la permission d'envoyer des fichiers ou non""" if user.server_permissions.attach_files == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_mention_everyone(user): """Retourne si l'utilisateur a la permission de mentionner @everyone ou non""" if user.server_permissions.mention_everyone == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_external_emojis(user): """Retourne si l'utilisateur a la permission d'utiliser les emojis externes au serveur ou non""" if user.server_permissions.external_emojis == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_change_nickname(user): """Retourne si l'utilisateur a la permission de changer de pseudo ou non""" if user.server_permissions.change_nickname == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_manage_nicknames(user): """Retourne si l'utilisateur a la permission de gรฉrer les pseudos des membres du serveur ou non""" if user.server_permissions.manage_nicknames == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_manage_roles(user): """Retourne si l'utilisateur a la permission de gรฉrer les rรดles du serveur ou non""" if user.server_permissions.manage_roles == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_manage_webhooks(user): """Retourne si l'utilisateur a la permission de gรฉrer les webhooks du serveur ou non""" if user.server_permissions.manage_webhooks == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_perm_manage_emojis(user): """Retourne si l'utilisateur a la permission de gรฉrer les emojis du serveur ou non""" if user.server_permissions.manage_emojis == True: return 'Autorisรฉ' else: return 'Non autorisรฉ' ##################################################################################################################################################### def get_user_roles(user): """Retourne une sรฉrie de str, les roles de l'utilisateur""" roles = user.roles RoleList = [] RoleStr = "" for x in range(len(roles)): role = roles[x].name RoleList.append(role) del RoleList[0] for x in range(len(RoleList)): role = RoleList[x] RoleStr += role + ", " RoleFinal = RoleStr.rstrip(', ') return RoleFinal ##################################################################################################################################################### def getServerRules(): fileName = './rules.txt' with open(fileName) as f: rulesLines = f.read() return rulesLines #####################################################################################################################################################
Python
0
@@ -8704,28 +8704,295 @@ ############################ +%0D%0A%0D%0Adef getToken():%0D%0A%09%0D%0A%09fileName = './token.txt'%0D%0A%09with open(fileName) as f: token = f.read()%0D%0A%09%0D%0A%09return token%0D%0A%0D%0A#####################################################################################################################################################%0D%0A
1ec0b7bf12b8d0ea452caa9aad17535a2fd745d8
Optimise for readability
scell/core.py
scell/core.py
""" scell.core ~~~~~~~~~~ Provides abstractions over lower level APIs and file objects and their interests. """ from select import select as _select from collections import namedtuple def select(rl, wl, timeout=None): """ Returns the file objects ready for reading/writing from the read-list (*rl*) and write-list (*wl*), subject to *timeout* in seconds. :param rl: Objects interested in readability. :param wl: Objects interested in writability. :param timeout: Maximum blocking time in seconds, *None* for no timeout. """ if not (rl or wl): return [], [] readers, writers, _ = _select(rl, wl, (), timeout) return readers, writers class Monitored(namedtuple('_Monitored', 'fp,wants_read,wants_write,callback')): """ Represents the interests of a file handle *fp*, and whether it *wants_read* and or *wants_write*, as well as an attached *callback*. """ __slots__ = () class Event(namedtuple('_Event', 'monitored,readable,writable,fp,callback,ready')): """ Represents the readability or writability of a *monitored* file object. """ __slots__ = () def __new__(cls, monitored, readable, writable): ready = ( readable >= monitored.wants_read and writable >= monitored.wants_write ) return super(Event, cls).__new__( cls, monitored, readable, writable, fp=monitored.fp, callback=monitored.callback, ready=ready, )
Python
0.672366
@@ -709,22 +709,17 @@ iters%0A%0A%0A -class +_ Monitore @@ -719,17 +719,19 @@ onitored -( + = namedtup @@ -734,17 +734,16 @@ dtuple(' -_ Monitore @@ -783,16 +783,127 @@ llback') +%0A_Event = namedtuple('Event', 'monitored,readable,writable,fp,callback,ready')%0A%0A%0Aclass Monitored(_Monitored ):%0A %22 @@ -1095,77 +1095,14 @@ ent( -namedtuple('_Event', 'monitored,readable,writable,fp,callback,ready') +_Event ):%0A
9f0837d387c7303d5c8c925a9989ca77a1a96e3e
Bump version after keras model fix
fancyimpute/__init__.py
fancyimpute/__init__.py
from __future__ import absolute_import, print_function, division from .solver import Solver from .nuclear_norm_minimization import NuclearNormMinimization from .iterative_imputer import IterativeImputer from .matrix_factorization import MatrixFactorization from .iterative_svd import IterativeSVD from .simple_fill import SimpleFill from .soft_impute import SoftImpute from .scaler import BiScaler from .knn import KNN from .similarity_weighted_averaging import SimilarityWeightedAveraging __version__ = "0.4.2" __all__ = [ "Solver", "NuclearNormMinimization", "MatrixFactorization", "IterativeSVD", "SimpleFill", "SoftImpute", "BiScaler", "KNN", "SimilarityWeightedAveraging", "IterativeImputer" ]
Python
0
@@ -508,9 +508,9 @@ 0.4. -2 +3 %22%0A%0A_
63fd814c8989881f5e805eff89e568bd35ac0006
move the combine_page_rank param to the analyze methode.
analyzer/cosinus.py
analyzer/cosinus.py
import math import os from analyzer.hit import Hit from analyzer.hit import Hits from model.index import Index from model.page import Page from model.page import Pages from indexer.lexer import TokenLexer from utils.string import StringUtil class CosinusAnalyzer: def __init__(self, index, pages, combine_with_page_rank=False): if not isinstance(index, Index): raise TypeError('index must be an instance of Index') if not isinstance(pages, Pages): raise TypeError('index must be an instance of Index') self.index = index self.count_of_pages = pages.count() self.pages = pages self.length_of_pages = self.caclulate_length_of_pages() self.combine_with_page_rank = combine_with_page_rank def analyze(self, query): """ Analyze a given query and returns the corresponding hits """ query_length = 0 page_scores = {} query_tokens = self.__query_to_tokens(query) # Calculate page_scores for term in query_tokens: wtq = self.idf_weight(term) query_length += wtq ** 2 for page_id in self.index.get_posting_list(term): tf_idf_weight = self.tf_idf_weight(term, page_id) if page_id not in page_scores: page_scores[page_id] = 0 page_scores[page_id] += tf_idf_weight * wtq query_length = math.sqrt(query_length) # Normalize score vectors and build the hit list hits = Hits(query_tokens) for page_id, score in page_scores.items(): hit = Hit(page_id, score) hit.score /= self.length_of_pages[page_id] hit.score /= query_length if ( self.combine_with_page_rank ): hit.score *= self.pages.get_page_by_title(page_id).page_rank hits.append(hit) hits.sort() return hits def caclulate_length_of_pages(self): """ Calculate the length of the vector space for each page in the index """ page_lengths = {} for term in self.index: for page_id in self.index.get_posting_list(term): if page_id not in page_lengths: page_lengths[page_id] = 0 tf_idf_weight = self.tf_idf_weight(term, page_id) page_lengths[page_id] += tf_idf_weight ** 2 for page_id, page in page_lengths.items(): page_lengths[page_id] = math.sqrt(page_lengths[page_id]) return page_lengths def get_length_of_pages_text(self): """ Create the string representation for the length of pages vector. """ output = [StringUtil.header('doc_lengthes.txt')] for page_id in sorted(self.length_of_pages): length_entry = page_id + ':' + ' ' * 4 + str(self.length_of_pages[page_id]) output.append(length_entry) return os.linesep.join(output) + os.linesep def tf_idf_weight(self, term, page_id): """ Calculate the tf-idf weight for the term in the page with the id 'page_id'. """ return self.tf_weight(term, page_id) * self.idf_weight(term) def tf_weight(self, term, page_id): """ Calculate log frequency weight of the term in the page with the id 'page_id'. """ frequence = self.index.get_term_frequency(term, page_id) if frequence > 0: return 1 + math.log10(frequence) return 0 def idf_weight(self, term): """ Calculate idf weight of the term, idf is a measure of the informativeness of the term. """ if term not in self.index: return 0 dft = self.index.get_document_frequency(term) return math.log10(float(self.count_of_pages / dft)) def __query_to_tokens(self, query): """ Split the query into tokens """ page = Page() page.content = query lexer = TokenLexer(page) return list(lexer.tokens())
Python
0
@@ -299,38 +299,8 @@ ages -, combine_with_page_rank=False ):%0A%0A @@ -681,97 +681,66 @@ s()%0A +%0A - self.combine_with_page_rank = combine_with_page_rank%0A%0A def analyze(self, query +def analyze(self, query, combine_with_page_rank=False ):%0A @@ -1695,21 +1695,16 @@ if ( -self. combine_
5b7abc62a541622b007da367e52488eab72f2b5a
Fix font usage.
graph-deps.py
graph-deps.py
#!/usr/bin/env python3 # file: graph-deps.py # vim:fileencoding=utf-8:fdm=marker:ft=python # # Author: R.F. Smith <rsmith@xs4all.nl> # Created: 2017-04-27 13:50:28 +0200 # Last modified: 2017-06-04 13:38:06 +0200 # # To the extent possible under law, R.F. Smith has waived all copyright and # related or neighboring rights to graph-deps.py. This work is published # from the Netherlands. See http://creativecommons.org/publicdomain/zero/1.0/ """ Creates a graph of FreeBSD package dependencies. Use it like this: pkg info -dx py27- | python3 graph-deps.py | dot -o py27-deps.pdf -Tpdf This will output a graphviz digraph for all Python 2.7 packages on stdout, which is processed by the โ€œdotโ€ program from the graphics/graphviz port and turned into a PDF rendering of the graph. """ import sys if len(sys.argv) > 1 and sys.argv[1] in ('-h', '--help'): print(__doc__) exit(0) output = ['digraph deps {', 'rankdir=LR;', 'node [shape=box];'] parent = None try: for ln in sys.stdin: pkgname = ln.strip() if pkgname.endswith(':'): pkgname = pkgname[:-1] output.append('"{0}" [label="{0}"];'.format(pkgname)) if ln[0] not in ' \t': # parent parent = pkgname else: output.append('"{}" -> "{}";'.format(parent, pkgname)) except KeyboardInterrupt: print('\n', __doc__) else: print('\n'.join(output) + '}')
Python
0.000002
@@ -187,28 +187,28 @@ 201 -7-06-04 13:38:06 +02 +8-03-10 22:50:33 +01 00%0A# @@ -932,23 +932,99 @@ ', ' -node %5Bshape=box +fontname=%22Alegreya%22;', 'concentratr=true;',%0A 'node %5Bshape=box, fontname=%22Alegreya%22 %5D;'%5D
8408f5431e56309d95076db16c86b0aa2ef044ba
Decrease number of messages from MoveToFort worker
pokemongo_bot/event_manager.py
pokemongo_bot/event_manager.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals class EventNotRegisteredException(Exception): pass class EventMalformedException(Exception): pass class EventHandler(object): def __init__(self): pass def handle_event(self, event, kwargs): raise NotImplementedError("Please implement") class EventManager(object): def __init__(self, *handlers): self._registered_events = dict() self._handlers = list(handlers) or [] def event_report(self): for event, parameters in self._registered_events.iteritems(): print '-'*80 print 'Event: {}'.format(event) if parameters: print 'Parameters:' for parameter in parameters: print '* {}'.format(parameter) def add_handler(self, event_handler): self._handlers.append(event_handler) def register_event(self, name, parameters=[]): self._registered_events[name] = parameters def emit(self, event, sender=None, level='info', formatted='', data={}): if not sender: raise ArgumentError('Event needs a sender!') levels = ['info', 'warning', 'error', 'critical', 'debug'] if not level in levels: raise ArgumentError('Event level needs to be in: {}'.format(levels)) if event not in self._registered_events: raise EventNotRegisteredException("Event %s not registered..." % event) # verify params match event parameters = self._registered_events[event] if parameters: for k, v in data.iteritems(): if k not in parameters: raise EventMalformedException("Event %s does not require parameter %s" % (event, k)) formatted_msg = formatted.format(**data) # send off to the handlers for handler in self._handlers: handler.handle_event(event, sender, level, formatted_msg, data)
Python
0.000001
@@ -57,16 +57,39 @@ iterals%0A +from sys import stdout%0A %0A%0Aclass @@ -508,16 +508,48 @@ s) or %5B%5D +%0A self._last_event = None %0A%0A de @@ -1533,16 +1533,254 @@ event)%0A%0A + if (event == self._last_event) and (event in %5B%22moving_to_fort%22, %22moving_to_lured_fort%22%5D):%0A stdout.write(%22%5C033%5B1A%5C033%5B0K%5Cr%22)%0A stdout.flush()%0A if level == %22info%22 and formatted: self._last_event = event%0A%0A
05835304797c9486d0c715d5a07d02fffd676b67
Fix test to account for new composition
karld/tests/test_run_together.py
karld/tests/test_run_together.py
from itertools import islice import string import unittest from mock import patch, Mock from ..run_together import csv_file_to_file class TestCSVFileToFile(unittest.TestCase): def setUp(self): self.csv_contents = iter([ ['a', 'b'], ['c', 'd'], ['e', 'f'], ]) @patch('karld.run_together.ensure_dir') @patch('karld.run_together.write_as_csv') @patch('karld.run_together.i_get_csv_data') def test_csv_file_to_file(self, mock_in_csv, mock_out_csv, mock_ensure_dir): """ Ensure csv_file_to_file ensures the out directory, then writes as csv to a filename the same as the input filename, but lowercase with a prefix and to the out directory the data from the input file as called with the csv_row_consumer. """ def out_csv(rows, out_file): return list(islice(rows, 3)) mock_out_csv.side_effect = out_csv mock_in_csv.return_value = self.csv_contents def row_consumer(rows): for row in rows: yield map(string.upper, row) mock_row_consumer = Mock(side_effect=row_consumer) out_prefix = "yeah_" out_dir = "out" file_path_name = ("in/File.csv", "File.csv") csv_file_to_file(mock_row_consumer, out_prefix, out_dir, file_path_name) mock_ensure_dir.assert_called_once_with("out") self.assertIn('out/yeah_file.csv', mock_out_csv.call_args[0]) mock_row_consumer.assert_called_once_with(self.csv_contents)
Python
0
@@ -244,14 +244,110 @@ -%5B +'a,b',%0A 'c,d',%0A 'e,f',%0A %5D)%0A self.csv_list = (%0A %5Bu 'a', +u 'b'%5D @@ -365,13 +365,15 @@ %5B +u 'c', +u 'd'%5D @@ -391,13 +391,15 @@ %5B +u 'e', +u 'f'%5D @@ -408,17 +408,16 @@ -%5D )%0A%0A @ @@ -538,20 +538,70 @@ r.i_ -get_csv_data +read_buffered_file')%0A @patch('karld.run_together.csv_reader ')%0A @@ -670,22 +670,74 @@ mock_ -in_ csv +_reader,%0A mock_file_reader ,%0A @@ -1261,14 +1261,19 @@ ock_ -in_csv +file_reader .ret @@ -1301,16 +1301,69 @@ contents +%0A mock_csv_reader.return_value = self.csv_list %0A%0A @@ -1972,18 +1972,14 @@ elf.csv_ -contents +list )%0A
034c361f4bf455ef468c1e500ce717d21aad7bc7
Bump version
form_error_reporting.py
form_error_reporting.py
from collections import OrderedDict import logging from math import ceil import re import uuid import warnings from django.conf import settings import requests from six.moves.urllib.parse import quote, urljoin VERSION = (0, 4) __version__ = '.'.join(map(str, VERSION)) __all__ = ('GAErrorReportingMixin', 'GARequestErrorReportingMixin') logger = logging.getLogger(__name__) class OrderedQueryDict(OrderedDict): """ A simplified version of django.http.request.QueryDict that preserves key order """ def urlencode(self): """ Convert dictionary into a query string; keys are assumed to always be str """ output = ('%s=%s' % (k, quote(v)) for k, v in self.items()) return '&'.join(output) class GAErrorReportingMixin(object): """ Form mixin that reports form errors to Google Analytics with events """ ga_endpoint_base = 'https://ssl.google-analytics.com/' # NB: non-ssl version is http://www.google-analytics.com/ ga_tracking_id = None ga_client_id = None ga_event_category = None ga_batch_hits = True def is_valid(self): """ Error reporting is triggered when a form is checked for validity """ is_valid = super(GAErrorReportingMixin, self).is_valid() if self.is_bound and not is_valid: try: self.report_errors_to_ga(self.errors) except: logger.exception('Failed to report form errors to Google Analytics') return is_valid def get_ga_single_endpoint(self): """ URL for collecting a single hit """ return urljoin(self.ga_endpoint_base, 'collect') def get_ga_batch_endpoint(self): """ URL for collecting multiple hits """ return urljoin(self.ga_endpoint_base, 'batch') def get_ga_tracking_id(self): """ Google Analytics ID """ return self.ga_tracking_id def get_ga_client_id(self): """ Client ID by which multiple requests are tracked """ return self.ga_client_id or str(uuid.uuid4()) def get_ga_event_category(self): """ Event category, defaults to form class name """ return self.ga_event_category or '%s.%s' % (self.__class__.__module__, self.__class__.__name__) def get_ga_query_dict(self): """ Default hit parameters """ return OrderedQueryDict([ ('v', '1'), ('tid', ''), ('cid', ''), ('t', 'event'), ('ec', ''), ('ea', ''), ('el', ''), ]) def format_ga_hit(self, field_name, error_message): """ Format a single hit """ tracking_id = self.get_ga_tracking_id() if not tracking_id: warnings.warn('Google Analytics tracking ID is not set') return None query_dict = self.get_ga_query_dict() query_dict['tid'] = tracking_id query_dict['cid'] = self.get_ga_client_id() query_dict['ec'] = self.get_ga_event_category() query_dict['ea'] = field_name query_dict['el'] = error_message return query_dict.urlencode() def report_errors_to_ga(self, errors): """ Report errors to Google Analytics https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide """ hits = [] responses = [] for field_name in sorted(errors): for error_message in errors[field_name]: event = self.format_ga_hit(field_name, error_message) if event: hits.append(event) if self.ga_batch_hits: for hit_batch in _batch_hits(hits): response = requests.post(self.get_ga_batch_endpoint(), data=hit_batch) responses.append(response) else: for hit in hits: response = requests.post(self.get_ga_single_endpoint(), data=hit) responses.append(response) return responses class GARequestErrorReportingMixin(GAErrorReportingMixin): """ Form mixin that reports form errors to Google Analytics with events, taking additional information from the HttpRequest object that should be set in the __init__ method of subclasses. This mixin also assumes the Google Analytics tracking ID is provided in the Django settings. """ ga_tracking_id_settings_key = 'GOOGLE_ANALYTICS_ID' ga_cookie_re = re.compile(r'^GA\d+\.\d+\.(?P<cid>.*)$', re.I) def get_ga_tracking_id(self): """ Retrieve tracking ID from settings """ if hasattr(settings, self.ga_tracking_id_settings_key): return getattr(settings, self.ga_tracking_id_settings_key) return super(GARequestErrorReportingMixin, self).get_ga_tracking_id() def get_ga_request(self): """ Retrieve current HttpRequest from this form instance """ if hasattr(self, 'request'): return self.request def get_ga_client_id(self): """ Retrieve the client ID from the Google Analytics cookie, if available, and save in the current session """ request = self.get_ga_request() if not request or not hasattr(request, 'session'): return super(GARequestErrorReportingMixin, self).get_ga_client_id() if 'ga_client_id' not in request.session: client_id = self.ga_cookie_re.match(request.COOKIES.get('_ga', '')) client_id = client_id and client_id.group('cid') or str(uuid.uuid4()) request.session['ga_client_id'] = client_id return request.session['ga_client_id'] def get_ga_query_dict(self): """ Adds user agent and IP to the default hit parameters """ query_dict = super(GARequestErrorReportingMixin, self).get_ga_query_dict() request = self.get_ga_request() if not request: return query_dict user_ip = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '')) user_ip = user_ip.split(',')[0].strip() user_agent = request.META.get('HTTP_USER_AGENT') user_language = request.META.get('HTTP_ACCEPT_LANGUAGE') if user_ip: query_dict['uip'] = user_ip if user_agent: query_dict['ua'] = user_agent if user_language: query_dict['ul'] = user_language return query_dict def _batch_hits(hits): # Separate hit payloads into batches of 20 # Block single hit payloads > 8KB # TODO: Perhaps trim single payloads to fit 8KB? e.g. the el & ua parameters # Separate out batches into total payloads <= 16KB def paginate(group): page_size = 20 for page in range(int(ceil(len(group) / page_size))): yield group[page * page_size:page * page_size + page_size] def limit_8kb(payload): return len(payload.encode('utf8')) <= 8 * 1024 def limit_16kb(payload): return len(payload.encode('utf8')) <= 16 * 1024 def separate_groups(group): payload = '\n'.join(group) if limit_16kb(payload): yield payload else: group_size = len(group) // 2 for payload in separate_groups(group[:group_size]): yield payload for payload in separate_groups(group[group_size:]): yield payload for hits_page in paginate(hits): hits_page = list(filter(limit_8kb, hits_page)) for hit_group in separate_groups(hits_page): yield hit_group
Python
0
@@ -219,17 +219,17 @@ N = (0, -4 +5 )%0A__vers
25e7574b6d58444ba81b3ad9321662e3a1a6b7e8
Apply some PEP8 cleanup
product_variant_sale_price/models/product_product.py
product_variant_sale_price/models/product_product.py
# -*- coding: utf-8 -*- # ยฉ 2016 Sergio Teruel <sergio.teruel@tecnativa.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import models, fields, api class ProductTemplate(models.Model): _inherit = "product.template" @api.multi def write(self, vals): res = super(ProductTemplate, self).write(vals) if 'list_price' in vals: for product in self: for variant in product.mapped('product_variant_ids'): variant._onchange_lst_price() return res class ProductProduct(models.Model): _inherit = "product.product" @api.multi @api.depends('fix_price') def _compute_lst_price(self): for product in self: price = product.fix_price or product.list_price if 'uom' in self.env.context: uom = product.uos_id or product.uom_id price = uom._compute_price( product.uom_id.id, price, self.env.context['uom']) product.lst_price = price @api.multi def _inverse_product_lst_price(self): for product in self: vals={} if 'uom' in self.env.context: uom = product.uos_id or product.uom_id vals['fix_price'] = uom._compute_price(product.uom_id.id, product.lst_price, self.env.context['uom']) else: vals['fix_price'] = product.lst_price product.write(vals) lst_price = fields.Float( compute='_compute_lst_price', inverse='_inverse_product_lst_price', ) fix_price = fields.Float(string='Fix Price')
Python
0.000001
@@ -384,45 +384,8 @@ ls:%0A - for product in self:%0A @@ -407,23 +407,20 @@ iant in -product +self .mapped( @@ -443,20 +443,16 @@ _ids'):%0A - @@ -1101,17 +1101,19 @@ vals -= + = %7B%7D%0A @@ -1259,16 +1259,37 @@ e_price( +%0A product.
93181a9a8df89c9ed1ff1e06672cc592a2b689dc
Fix deadcode
polyphony/compiler/deadcode.py
polyphony/compiler/deadcode.py
from .env import env from .ir import * from logging import getLogger logger = getLogger(__name__) class DeadCodeEliminator(object): def process(self, scope): if scope.is_namespace() or scope.is_class() or scope.is_method(): return usedef = scope.usedef for blk in scope.traverse_blocks(): dead_stms = [] for stm in blk.stms: if stm.is_a([MOVE, PHIBase]): if stm.is_a(MOVE) and stm.src.is_a([TEMP, ATTR]) and stm.src.symbol().is_param(): continue if stm.is_a(MOVE) and stm.src.is_a(CALL): continue defvars = usedef.get_vars_defined_at(stm) for var in defvars: if not var.is_a(TEMP): break uses = usedef.get_stms_using(var.symbol()) if uses: break else: dead_stms.append(stm) for stm in dead_stms: blk.stms.remove(stm) logger.debug('removed dead code: ' + str(stm)) if stm.is_a(MOVE): var = stm.dst elif stm.is_a(PHIBase): var = stm.var if var.is_a([TEMP, ATTR]) and var.symbol().typ.is_seq(): memnode = var.symbol().typ.get_memnode() env.memref_graph.remove_node(memnode)
Python
0.999094
@@ -212,29 +212,8 @@ ss() - or scope.is_method() :%0A
e1e4d36096fe2c8cea92b77feabc60d94ac4310a
Break class now inherits behaviour from KitchenTimer.
pomodoro_evolved/rest_break.py
pomodoro_evolved/rest_break.py
from kitchen_timer import KitchenTimer, AlreadyRunningError, TimeAlreadyUp, NotRunningError from math import ceil class BreakAlreadySkipped(Exception): pass class BreakCannotBeSkippedOnceStarted(Exception): pass class BreakAlreadyStarted(Exception): pass class BreakNotStarted(Exception): pass class BreakAlreadyTerminated(Exception): pass class Break(object): ''' Models a timed rest break with a default duration of 5 minutes. Allows the break to be skipped before starting. Does not allow the break to be restarted after time's up or it's stopped. ''' IDLE = "IDLE" RUNNING = "RUNNING" SKIPPED = "SKIPPED" STOPPED = "STOPPED" TIMEUP = "TIMEUP" def __init__(self, whenTimeup, durationInMins=5): self._state = self.IDLE self._canSkip = True self._timer = KitchenTimer(whenTimeup, durationInMins) def skip(self): ''' Skips this break forever. ''' if self._canSkip: self._state = self.SKIPPED else: raise BreakCannotBeSkippedOnceStarted() def start(self): ''' Starts the break counting down from the given durationInMins. ''' if self.wasSkipped(): raise BreakAlreadySkipped() if self._timer.isStopped(): raise BreakAlreadyTerminated try: self._timer.start() except AlreadyRunningError: raise BreakAlreadyStarted() except TimeAlreadyUp: raise BreakAlreadyTerminated() else: self._canSkip = False def stop(self): ''' Stops the break forever. Restarting is forbidden. ''' if self.wasSkipped(): raise BreakAlreadySkipped() try: self._timer.stop() except NotRunningError: raise BreakNotStarted() def isRunning(self): return self._timer.isRunning() def wasSkipped(self): return self._state == self.SKIPPED @property def timeRemaining(self): ''' Returns the number of whole seconds remaining. ''' return ceil(self._timer.timeRemaining)
Python
0
@@ -351,14 +351,20 @@ eak( -object +KitchenTimer ):%0A @@ -838,35 +838,36 @@ + super(Break, self +) ._ -timer = KitchenTimer +_init__ (whe @@ -891,28 +891,16 @@ InMins)%0A - %0A def @@ -1307,23 +1307,16 @@ if self. -_timer. isStoppe @@ -1360,16 +1360,18 @@ rminated +() %0A @@ -1398,26 +1398,33 @@ s -elf._timer +uper(Break, self) .start() @@ -1833,26 +1833,33 @@ s -elf._timer +uper(Break, self) .stop()%0A @@ -1930,85 +1930,8 @@ d()%0A - %0A def isRunning(self):%0A return self._timer.isRunning()%0A @@ -2148,18 +2148,25 @@ il(s -elf._timer +uper(Break, self) .tim
ca15e6523bd34e551528dce6c6ee3dcb70cf7806
Use sed inline (unsure why mv was used originally).
pyinfra/modules/util/files.py
pyinfra/modules/util/files.py
# pyinfra # File: pyinfra/modules/util/files.py # Desc: common functions for handling the filesystem from types import NoneType def ensure_mode_int(mode): # Already an int (/None)? if isinstance(mode, (int, NoneType)): return mode try: # Try making an int ('700' -> 700) return int(mode) except (TypeError, ValueError): pass # Return as-is (ie +x which we don't need to normalise, it always gets run) return mode def sed_replace(state, filename, line, replace, flags=None): flags = ''.join(flags) if flags else '' line = line.replace('/', '\/') replace = replace.replace('/', '\/') temp_filename = state.get_temp_filename() return 'sed "s/{0}/{1}/{2}" {3} > {4} && mv {4} {3}'.format( line, replace, flags, filename, temp_filename ) def chmod(target, mode, recursive=False): return 'chmod {0}{1} {2}'.format(('-R ' if recursive else ''), mode, target) def chown(target, user, group=None, recursive=False): command = 'chown' user_group = None if user and group: user_group = '{0}:{1}'.format(user, group) elif user: user_group = user elif group: command = 'chgrp' user_group = group return '{0}{1} {2} {3}'.format( command, ' -R' if recursive else '', user_group, target )
Python
0
@@ -657,55 +657,8 @@ ')%0A%0A - temp_filename = state.get_temp_filename()%0A%0A @@ -669,16 +669,19 @@ rn 'sed +-i %22s/%7B0%7D/%7B @@ -691,28 +691,8 @@ %7B2%7D%22 - %7B3%7D %3E %7B4%7D && mv %7B4%7D %7B3%7D @@ -743,23 +743,8 @@ name -, temp_filename %0A
f015c3e5973c9424734ff6181563ee7905c73428
fix version pattern
sdcm/utils.py
sdcm/utils.py
# This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # # See LICENSE for more details. # # Copyright (c) 2017 ScyllaDB import logging import re import os import glob from avocado.utils import process def _remote_get_hash(remoter, file_path): try: result = remoter.run('md5sum {}'.format(file_path), verbose=True) return result.stdout.strip().split()[0] except Exception as details: test_logger = logging.getLogger('avocado.test') test_logger.error(str(details)) return None def _remote_get_file(remoter, src, dst): result = remoter.run('curl -L {} -o {}'.format(src, dst), ignore_status=True) def remote_get_file(remoter, src, dst, hash_expected=None, retries=1): if not hash_expected: _remote_get_file(remoter, src, dst) return while retries > 0 and _remote_get_hash(remoter, dst) != hash_expected: _remote_get_file(remoter, src, dst) retries -= 1 #assert _remote_get_hash(remoter, dst) == hash_expected def get_monitor_version(full_version, clone=False): """ Detect matched dashboard version from scylla version. :param full_version: version info returned by `scylla --version` :param clone: force to clone scylla-grafana-monitoring project :return: dashboard version (eg: 1.7, 2.0, master) """ if not os.path.exists('scylla-grafana-monitoring/') or clone: process.run('rm -rf scylla-grafana-monitoring/') process.run('git clone https://github.com/scylladb/scylla-grafana-monitoring/') process.run('cp -r scylla-grafana-monitoring/grafana data_dir/') if not full_version or '666.development' in full_version: ret = 'master' else: ret = re.findall("^\w+.\w+", full_version)[0] # We only add dashboard for release version, let's use master for pre-release version jsons = glob.glob('data_dir/grafana/*.%s.json' % ret) if not jsons: ret = 'master' return ret
Python
0.000003
@@ -2121,16 +2121,19 @@ ll(%22 -%5E%5Cw+.%5Cw+ +-(%5Cd+%5C.%5Cd+) %22, f
1e7ee86b888a7e8ebb4026f13855ed4ca241af44
change a few iterations over keys() in dict to over list; fixing query filters test
portality/lib/query_filters.py
portality/lib/query_filters.py
from flask_login import current_user from portality.core import app from portality import models # query sanitisers ################## def public_query_validator(q): # no deep paging if q.from_result() > 10000: return False if q.size() > 200: return False # if the query has facets, that's fine # otherwise, if it has no facets, only allow "count" style # queries with zero results returned if q.has_facets(): return True else: return q.size() == 0 # query filters ############### def only_in_doaj(q): q.clear_match_all() q.add_must({"term" : {"admin.in_doaj" : True}}) return q def owner(q): q.clear_match_all() q.add_must({"term" : {"admin.owner.exact" : current_user.id}}) return q def update_request(q): q.clear_match_all() q.add_must({"range" : {"created_date" : {"gte" : app.config.get("UPDATE_REQUEST_SHOW_OLDEST")}}}) return q def associate(q): q.clear_match_all() q.add_must({"term" : {"admin.editor.exact" : current_user.id}}) return q def editor(q): gnames = [] groups = models.EditorGroup.groups_by_editor(current_user.id) for g in groups: gnames.append(g.name) q.clear_match_all() q.add_must({"terms" : {"admin.editor_group.exact" : gnames}}) return q def private_source(q): q.add_include(["admin.application_status", "suggestion", "admin.ticked", "admin.seal", "last_updated", "created_date", "id", "bibjson"]) return q def public_source(q): q.add_include(["admin.ticked", "admin.seal", "last_updated", "created_date", "id", "bibjson"]) return q # results filters ################# def public_result_filter(results, unpacked=False): # Dealing with single unpacked result if unpacked: if "admin" in results: for k in results["admin"].keys(): if k not in ["ticked", "seal"]: del results["admin"][k] return results # Dealing with a list of es results if "hits" not in results: return results if "hits" not in results["hits"]: return results for hit in results["hits"]["hits"]: if "_source" in hit: if "admin" in hit["_source"]: for k in hit["_source"]["admin"].keys(): if k not in ["ticked", "seal"]: del hit["_source"]["admin"][k] return results def prune_author_emails(results, unpacked=False): # Dealing with single unpacked ES result if unpacked: if "bibjson" in results: if "author" in results["bibjson"]: for a in results["bibjson"]["author"]: if "email" in a: del a["email"] return results # Dealing with a list of ES results if "hits" not in results: return results if "hits" not in results["hits"]: return results for hit in results["hits"]["hits"]: if "_source" in hit: if "bibjson" in hit["_source"]: if "author" in hit["_source"]["bibjson"]: for a in hit["_source"]["bibjson"]["author"]: if "email" in a: del a["email"] return results def publisher_result_filter(results, unpacked=False): # Dealing with single unpacked ES result if unpacked: if "admin" in results: for k in results["admin"].keys(): if k not in ["ticked", "seal", "in_doaj", "related_applications", "current_application", "current_journal", "application_status"]: del results["admin"][k] return results # Dealing with a list of ES results if "hits" not in results: return results if "hits" not in results["hits"]: return results for hit in results["hits"]["hits"]: if "_source" in hit: if "admin" in hit["_source"]: for k in hit["_source"]["admin"].keys(): if k not in ["ticked", "seal", "in_doaj", "related_applications", "current_application", "current_journal", "application_status"]: del hit["_source"]["admin"][k] return results
Python
0
@@ -1840,32 +1840,37 @@ for k in +list( results%5B%22admin%22%5D @@ -1861,38 +1861,32 @@ results%5B%22admin%22%5D -.keys( ):%0A @@ -2271,32 +2271,37 @@ for k in +list( hit%5B%22_source%22%5D%5B%22 @@ -2299,38 +2299,32 @@ ource%22%5D%5B%22admin%22%5D -.keys( ):%0A @@ -3448,24 +3448,29 @@ for k in +list( results%5B%22adm @@ -3465,38 +3465,32 @@ results%5B%22admin%22%5D -.keys( ):%0A @@ -3978,24 +3978,29 @@ for k in +list( hit%5B%22_source @@ -4014,14 +4014,8 @@ in%22%5D -.keys( ):%0A
c1a263107cac6f55ce01ea5f260c005d307398e7
add env vars to ping.json
laalaa/apps/healthcheck/views.py
laalaa/apps/healthcheck/views.py
import requests from django.http import JsonResponse from django.conf import settings def ping(request): res = { "version_number": None, "build_date": None, "commit_id": None, "build_tag": None } # Get version details try: res['version_number'] = str(open("{0}/../VERSION".format(settings.PROJECT_ROOT)).read().strip()) res['commit_id'] = res['version_number'] res['build'] = res['version_number'] except IOError: pass # Get build tag try: res['build_tag'] = str(open("{0}/../BUILD_TAG".format(settings.PROJECT_ROOT)).read().strip()) except IOError: pass # Get build date try: res['build_date'] = str(open("{0}/../BUILD_DATE".format(settings.PROJECT_ROOT)).read().strip()) except IOError: pass return JsonResponse(res) def healthcheck(request): # Default status is `DOWN` for all services health = { 'postcodeinfo': { 'status': 'DOWN', 'endpoint': settings.POSTCODEINFO_API_URL } } # Test postcodeinfo try: headers = {'Authorization': 'Token {0}'.format( settings.POSTCODEINFO_AUTH_TOKEN)} req = requests.get( '{0}/addresses/?postcode=sw1a1aa'.format( settings.POSTCODEINFO_API_URL), headers=headers) if req.status_code == 200: health['postcodeinfo']['status'] = 'UP' except: pass if health['postcodeinfo']['status'] == 'UP': return JsonResponse(health, status=200) else: return JsonResponse(health, status=503)
Python
0.000001
@@ -1,12 +1,22 @@ +import os%0A import reque @@ -19,16 +19,16 @@ equests%0A - from dja @@ -153,241 +153,93 @@ r%22: -None,%0A %22build_date%22: None,%0A %22commit_id%22: None,%0A %22build_tag%22: None%0A %7D%0A%0A # Get version details%0A try:%0A res%5B'version_number'%5D = str(open(%22%7B0%7D/../VERSION%22.format(settings.PROJECT_ROOT)).read().strip()) +os.environ.get('APPVERSION'),%0A %22build_date%22: os.environ.get('APP_BUILD_DATE'), %0A @@ -243,21 +243,17 @@ -res%5B' +%22 commit_i @@ -257,445 +257,103 @@ t_id -'%5D = res%5B'version_number'%5D%0A res%5B'build'%5D = res%5B'version_number'%5D%0A except IOError:%0A pass%0A%0A # Get +%22: os.environ.get('APP_GIT_COMMIT'),%0A %22 build - tag%0A try:%0A res%5B'build_tag'%5D = str(open(%22%7B0%7D/../BUILD_TAG%22.format(settings.PROJECT_ROOT)).read().strip())%0A except IOError:%0A pass%0A%0A # Get build date%0A try:%0A res%5B'build_date'%5D = str(open(%22%7B0%7D/../BUILD_DATE%22.format(settings.PROJECT_ROOT)).read().strip())%0A except IOError:%0A pass +_tag%22: os.environ.get('APP_BUILD_TAG')%0A %7D %0A%0A
5a4d9255c59be0d5dda8272e0e7ced71822f4d40
Fix memory issues by just trying every number
prime-factors/prime_factors.py
prime-factors/prime_factors.py
import sieve def prime_factors(n): primes = sieve.sieve(n) factors = [] for p in primes: while n % p == 0: factors += [p] n //= p return factors
Python
0.000002
@@ -1,19 +1,4 @@ -import sieve%0A%0A%0A def @@ -23,31 +23,20 @@ -primes = sieve.sieve(n) +factors = %5B%5D %0A @@ -46,34 +46,29 @@ ctor -s = -%5B%5D +2 %0A -for p in primes +while n != 1 :%0A @@ -83,17 +83,22 @@ ile n %25 -p +factor == 0:%0A @@ -120,17 +120,22 @@ ors += %5B -p +factor %5D%0A @@ -146,17 +146,42 @@ n //= -p +factor%0A factor += 1 %0A ret
f0e68095cd0afc0b1d960d726e0e64de9dec14f1
remove unused variable
hack.py
hack.py
import time import json import smbus import logging BUS = None address = 0x42 gpsReadInterval = 0.1 LOG = logging.getLogger() # GUIDE # http://ava.upuaut.net/?p=768 GPSDAT = { 'strType': None, 'fixTime': None, 'lat': None, 'latDir': None, 'lon': None, 'lonDir': None, 'fixQual': None, 'numSat': None, 'horDil': None, 'alt': None, 'altUnit': None, 'galt': None, 'galtUnit': None, 'DPGS_updt': None, 'DPGS_ID': None } def connectBus(): global BUS BUS = smbus.SMBus(1) def parseResponse(gpsLine): global lastLocation gpsChars = ''.join(chr(c) for c in gpsLine) if "*" not in gpsChars: return False gpsStr, chkSum = gpsChars.split('*') gpsComponents = gpsStr.split(',') gpsStart = gpsComponents[0] if (gpsStart == "$GNGGA"): chkVal = 0 for ch in gpsStr[1:]: # Remove the $ chkVal ^= ord(ch) if (chkVal == int(chkSum, 16)): for i, k in enumerate( ['strType', 'fixTime', 'lat', 'latDir', 'lon', 'lonDir', 'fixQual', 'numSat', 'horDil', 'alt', 'altUnit', 'galt', 'galtUnit', 'DPGS_updt', 'DPGS_ID']): GPSDAT[k] = gpsComponents[i] print gpsChars print json.dumps(GPSDAT, indent=2) def readGPS(): c = None response = [] try: while True: # Newline, or bad char. c = BUS.read_byte(address) if c == 255: return False elif c > 126: # FIXME: unprintable char, not sure what these might be... Maybe load an ASCII table library to translate? May be i2c control chars? print "Unprintable char int={0}, chr={1}".format(c, chr(c)) elif c == 10: # FIXME: magic number break else: response.append(c) parseResponse(response) except IOError: time.sleep(0.5) connectBus() except Exception, e: print e LOG.error(e) connectBus() while True: readGPS() time.sleep(gpsReadInterval)
Python
0.00003
@@ -564,32 +564,8 @@ e):%0A - global lastLocation%0A
8ea3350c6944946b60732308c912dc240952237c
Revert "Set the right recalbox.log path"
project/settings_production.py
project/settings_production.py
from .settings import * # Update SITE infos to use the common port 80 to publish the webapp SITE_FIXED = { 'name': "Recalbox Manager", 'ip': None, # If 'None' find the ip automatically. Use a string to define another ip/hostname 'port': None, # If 'None' no port is added to hostname, so the server have to be reachable from port 80 } # Production path to the Recalbox logs file RECALBOX_LOGFILE_PATH = "/recalbox/share/system/logs" # Use packaged assets ASSETS_PACKAGED = True
Python
0
@@ -416,16 +416,21 @@ = %22/ +root/ recalbox /sha @@ -429,26 +429,12 @@ lbox -/share/system/ +. log -s %22%0A%0A#
812efd4b5addeee879e91c6c660ac2a1a2adfe5d
mueve logica de avance de un paso a una funcion
heat.py
heat.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Este script resuelve un problema simple de diffusion en 1D. La ecuaciรณn a resover es: dT/dt = d2T/dx2; T(0,x) = sin(pi * x); T(t, 0) = T(t, 1) = 0 ''' from __future__ import division import numpy as np def inicializa_T(T, N_steps, h): ''' Rellena T con las condiciones iniciales del problema. Se asegura que las condiciones en los bordes sean cero. ''' for i in range(N_steps): x = i * h T[i] = np.sin(np.pi * x) T[0] = 0 T[-1] = 0 def calcula_b(b, N_steps, r): for j in range(1, N_steps - 1): b[j] = r * T[j+1] + (1-2*r) * T[j] + r * T[j-1] def calcula_alpha_y_beta(alhpa, beta, b, r, N_Steps): Aplus = -1 * r Acero = (1+2 * r) Aminus = -1 * r alpha[0] = 0 beta[0] = 0 # viene de la condicion de borde T(t, 0) = 0 for i in range(1, N_steps): alpha[i] = -Aplus / (Acero + Aminus*alpha[i-1]) beta[i] = (b[i] - Aminus*beta[i-1]) / (Aminus*alpha[i-1] + Acero) # Main # setup N_steps = 5 h = 1 / (N_steps - 1) dt = h**2 / 2 # Este es el mรกximo teรณrico para el metodo explicito r = dt / 2 / h**2 T = np.zeros(N_steps) T_next = np.zeros(N_steps) b = np.zeros(N_steps) alpha = np.zeros(N_steps) beta = np.zeros(N_steps) inicializa_T(T, N_steps, h) calcula_b(b, N_steps, r) calcula_alpha_y_beta(alpha, beta, b, r, N_steps) # Avanza T en el tiempo T_next[0] = 0 T_next[-1] = 0 for i in range(N_steps - 2, 0, -1): T_next[i] = alpha[i] * T[i+1] + beta[i]
Python
0.000001
@@ -1009,16 +1009,273 @@ Acero)%0A%0A +def avanza_paso_temporal(T, T_next, alpha, beta, N_steps):%0A T_next%5B0%5D = 0%0A T_next%5B-1%5D = 0%0A for i in range(N_steps - 2, 0, -1):%0A T_next%5Bi%5D = alpha%5Bi%5D * T%5Bi+1%5D + beta%5Bi%5D%0A # T = T_next.copy() # Esto no funciona, hacerlo fuera de la funcion%0A%0A # Main%0A%0A @@ -1653,16 +1653,18 @@ tiempo%0A +# T_next%5B0 @@ -1669,16 +1669,18 @@ %5B0%5D = 0%0A +# T_next%5B- @@ -1686,16 +1686,18 @@ -1%5D = 0%0A +# for i in @@ -1720,24 +1720,26 @@ 2, 0, -1):%0A +# T_next%5Bi @@ -1750,28 +1750,108 @@ alpha%5Bi%5D * T%5Bi+1%5D + beta%5Bi%5D%0A +avanza_paso_temporal(T, T_next, alpha, beta, N_steps)%0AT = T_next.copy()%0Aprint T%0A
6c2da0407bbaf0fb2e77d0847cce9fb9aeab2b02
remove useless ()
python/integer_programming.py
python/integer_programming.py
# Copyright 2010-2011 Google # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Integer programming examples that show how to use the APIs.""" __author__ = """lperron@google.com (Laurent Perron) edanna@google.com (Emilie Danna)""" from google.apputils import app from linear_solver import pywraplp def RunIntegerExampleAlgebraicAPI(optimization_problem_type): """Example of simple integer program with natural language API.""" solver = pywraplp.Solver('RunIntegerExampleAlgebraicAPI', optimization_problem_type) infinity = solver.infinity() # x1 and x2 are integer non-negative variables. x1 = solver.IntVar(0.0, infinity, 'x1') x2 = solver.IntVar(0.0, infinity, 'x2') solver.Minimize(x1 + 2 * x2) solver.Add(3 * x1 + 2 * x2 >= 17) SolveAndPrint(solver, [x1, x2]) def RunIntegerExampleCppStyleAPI(optimization_problem_type): """Example of simple integer program with the C++ style API.""" solver = pywraplp.Solver('RunIntegerExampleCppStyleAPI', optimization_problem_type) infinity = solver.infinity() # x1 and x2 are integer non-negative variables. x1 = solver.IntVar(0.0, infinity, 'x1') x2 = solver.IntVar(0.0, infinity, 'x2') # Minimize x1 + 2 * x2. solver.AddObjectiveTerm(x1, 1) solver.AddObjectiveTerm(x2, 2) # 2 * x2 + 3 * x1 >= 17. ct = solver.Constraint(17, infinity) ct.AddTerm(x1, 3) ct.AddTerm(x2, 2) SolveAndPrint(solver, [x1, x2]) def SolveAndPrint(solver, variable_list): """Solve the problem and print the solution.""" print 'Number of variables = %d' % solver.NumVariables() print 'Number of constraints = %d' % solver.NumConstraints() result_status = solver.Solve() # The problem has an optimal solution. assert result_status == pywraplp.Solver.OPTIMAL print 'Problem solved in %f milliseconds' % solver.wall_time() # The objective value of the solution. print 'Optimal objective value = %f' % solver.objective_value() # The value of each variable in the solution. for variable in variable_list: print '%s = %f' % (variable.name(), variable.solution_value()) print 'Advanced usage:' print 'Problem solved in %d branch-and-bound nodes' % solver.nodes() def RunAllIntegerExampleAlgebraicAPI(): if hasattr(pywraplp.Solver, 'GLPK_MIXED_INTEGER_PROGRAMMING'): print ('---- Integer programming example with GLPK (algebraic API) -----') RunIntegerExampleAlgebraicAPI( pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) if hasattr(pywraplp.Solver, 'CBC_MIXED_INTEGER_PROGRAMMING'): print '---- Integer programming example with CBC (algebraic API) -----' RunIntegerExampleAlgebraicAPI(pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) if hasattr(pywraplp.Solver, 'SCIP_MIXED_INTEGER_PROGRAMMING'): print '---- Integer programming example with SCIP (algebraic API) -----' RunIntegerExampleAlgebraicAPI( pywraplp.Solver.SCIP_MIXED_INTEGER_PROGRAMMING) def RunAllIntegerExampleCppStyleAPI(): if hasattr(pywraplp.Solver, 'GLPK_MIXED_INTEGER_PROGRAMMING'): print '---- Integer programming example with GLPK (C++ style API) ----' RunIntegerExampleCppStyleAPI(pywraplp.Solver.GLPK_MIXED_INTEGER_PROGRAMMING) if hasattr(pywraplp.Solver, 'CBC_MIXED_INTEGER_PROGRAMMING'): print '---- Integer programming example with CBC (C++ style API) ----' RunIntegerExampleCppStyleAPI(pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING) if hasattr(pywraplp.Solver, 'SCIP_MIXED_INTEGER_PROGRAMMING'): print '---- Integer programming example with SCIP (C++ style API) ----' RunIntegerExampleCppStyleAPI( pywraplp.Solver.SCIP_MIXED_INTEGER_PROGRAMMING) def main(unused_argv): RunAllIntegerExampleAlgebraicAPI() RunAllIntegerExampleCppStyleAPI() if __name__ == '__main__': app.run()
Python
0.000003
@@ -2844,17 +2844,16 @@ print -( '---- In @@ -2910,17 +2910,16 @@ ) -----' -) %0A Run
c9b7be796ee886a8407d7d9cf43dbf19aa811a00
Revert "more fixe"
shorten_url.py
shorten_url.py
import json import logging import random import sys import tornado import urllib from tornado.options import define, options from tornado.web import RequestHandler, Application define('debug', default=1, help='hot deployment. use in dev only', type=int) define('port', default=8000, help='run on the given port', type=int) # Custom backend account settings import backend MIN_EXP_TIME = 30 * 24 * 60 * 60 # Expire after 30 days REDIRECT_COUNTS_KEY = 'url:shorturl:resolved' HLL_ORIG_URL_KEY = 'url:hyperloglog:original' DOMAIN_REGEX = '[a-zA-Z\d-]{,63}(\.[a-zA-Z\d-]{,63})*' # TODO: try using zmq based ioloop instead might be more useful # TODO: add that ConsistentHashRing setup to enable redis cluster # TODO: Read up on hashing algorithms and pick best suited one for url # shortening service. see def validate_safe_url(url): # TODO: Sanitize the incoming url, for malicious js. return True class UrlShortener(object): # From RFC 1738 allowed url chars LOWALPHA = [ 'a', 'b','c', 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' ] HIALPHA = [ 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' ] DIGIT = [ '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' ] SAFE = [ '$' , '-' , '_' , '.' , '+' ] EXTRA = [ '!' , '*' , "'" , '(' , ')' , ',' ] PUNCTUATION = [ '<' , '>' , '#' , '%' , "'" ] URL_ALLOWED_CHARS = LOWALPHA +\ HIALPHA +\ DIGIT +\ SAFE +\ EXTRA +\ PUNCTUATION def __init__(self): self.redis = backend.redisConn def get_stats(self): urls_count = self.redis.pfcount(HLL_ORIG_URL_KEY) if self.redis.pfcount(HLL_ORIG_URL_KEY) else 0 redirects = self.redis.get(REDIRECT_COUNTS_KEY) if self.redis.get(REDIRECT_COUNTS_KEY) else 0 stats = {r'urls':urls_count, r'redirects':redirects } return stats def shorten_url(self, url): safe_url = validate_safe_url(url) # Check if the given url is a shortened url. stop malicious programs from inducing a redirect loop if not safe_url: logging.warn("#urlshortener: short_url provided as input for shortening") return None orig_url_not_exists = self.redis.pfadd(HLL_ORIG_URL_KEY, url) if orig_url_not_exists: short_url = "".join([random.choice(self.URL_ALLOWED_CHARS) for i in range(5)]) if not self.redis.get(short_url): self.redis.setex(short_url, url, MIN_EXP_TIME) self.redis.setex(url, short_url, MIN_EXP_TIME) else: # Since collisions are possible, this means there was a # collision logging.warn("#urlshortener: Collision Orig Url: %s, generated short url: %s" %(url, short_url)) self.shorten_url(url) else: # Original url already shortenede, just return th short_url = self.redis.get(url) return short_url def retrieve_orig_url(self, short_url): return str(self.redis.get(short_url)) class ShortUrlHandler(RequestHandler): def get(self): self.post() def post(self): assert self.request.uri.startswith('/url') url_parts = self.request.uri.split('/') short_url = urllib.unquote_plus(url_parts[2]) if (url_parts) > 2 else None if short_url: logging.info('# Received short url: %s' % short_url) orig_url = url_shortener.retrieve_orig_url(short_url) url_shortener.redis.incrby(REDIRECT_COUNTS_KEY, 1) self.redirect(orig_url) else: self.redirect('/url/shorten') class ShortenUrlHandler(RequestHandler): def get(self): self.render('static/index.html') def post(self): orig_url = self.get_argument('orig_url') logging.info('# Received Original url: %s' % orig_url) short_url = url_shortener.shorten_url(orig_url) if short_url: linkified_short_url = '<a href=' + '/'.join([self.request.headers.get('Origin'), 'url', urllib.quote_plus(short_url)]) + '>Click Here</a>' self.finish(json.dumps({'url': linkified_short_url}, ensure_ascii=False).encode('utf-8')) class StatsHandler(RequestHandler): def get(self): self.finish(json.dumps(url_shortener.get_stats(), ensure_ascii=False).encode('utf-8')) class Application(Application): # """ # >>> import requests # >>> requests.post("/shorten", params={"orig_url":"http://google.com"}) # >>> resp = requests.get("/shorten", params={"short_url": "265477614567132497141480353139365708304L"}) # >>> assert resp.url=="http://google.com" # """ def __init__(self): handlers = [ (r'/url/shorten', ShortenUrlHandler), (r'/url/stats',StatsHandler), (r'/url/(?!stats|shorten).*', ShortUrlHandler), ] settings = dict( autoescape=None, # tornado 2.1 backward compatibility debug=options.debug, gzip=True, ) settings.update({'static_path':'./static'}) tornado.web.Application.__init__(self, handlers, **settings) def main(): tornado.options.parse_command_line() app = Application() app.listen(options.port, xheaders=True) loop = tornado.ioloop.IOLoop.instance() loop.start() if __name__ == '__main__': url_shortener = UrlShortener() main()
Python
0
@@ -1993,16 +1993,20 @@ nd.redis +Labs Conn%0A%0A
a5ae77ab93811948c95e579667719971ec47ad3b
Add extra check for ESSID field in case there's a wired connection (#13459)
homeassistant/components/device_tracker/unifi.py
homeassistant/components/device_tracker/unifi.py
""" Support for Unifi WAP controllers. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.unifi/ """ import logging from datetime import timedelta import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA, DeviceScanner) from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD from homeassistant.const import CONF_VERIFY_SSL import homeassistant.util.dt as dt_util REQUIREMENTS = ['pyunifi==2.13'] _LOGGER = logging.getLogger(__name__) CONF_PORT = 'port' CONF_SITE_ID = 'site_id' CONF_DETECTION_TIME = 'detection_time' CONF_SSID_FILTER = 'ssid_filter' DEFAULT_HOST = 'localhost' DEFAULT_PORT = 8443 DEFAULT_VERIFY_SSL = True DEFAULT_DETECTION_TIME = timedelta(seconds=300) NOTIFICATION_ID = 'unifi_notification' NOTIFICATION_TITLE = 'Unifi Device Tracker Setup' PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string, vol.Optional(CONF_SITE_ID, default='default'): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): vol.Any( cv.boolean, cv.isfile), vol.Optional(CONF_DETECTION_TIME, default=DEFAULT_DETECTION_TIME): vol.All( cv.time_period, cv.positive_timedelta), vol.Optional(CONF_SSID_FILTER): vol.All(cv.ensure_list, [cv.string]) }) def get_scanner(hass, config): """Set up the Unifi device_tracker.""" from pyunifi.controller import Controller, APIError host = config[DOMAIN].get(CONF_HOST) username = config[DOMAIN].get(CONF_USERNAME) password = config[DOMAIN].get(CONF_PASSWORD) site_id = config[DOMAIN].get(CONF_SITE_ID) port = config[DOMAIN].get(CONF_PORT) verify_ssl = config[DOMAIN].get(CONF_VERIFY_SSL) detection_time = config[DOMAIN].get(CONF_DETECTION_TIME) ssid_filter = config[DOMAIN].get(CONF_SSID_FILTER) try: ctrl = Controller(host, username, password, port, version='v4', site_id=site_id, ssl_verify=verify_ssl) except APIError as ex: _LOGGER.error("Failed to connect to Unifi: %s", ex) hass.components.persistent_notification.create( 'Failed to connect to Unifi. ' 'Error: {}<br />' 'You will need to restart hass after fixing.' ''.format(ex), title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID) return False return UnifiScanner(ctrl, detection_time, ssid_filter) class UnifiScanner(DeviceScanner): """Provide device_tracker support from Unifi WAP client data.""" def __init__(self, controller, detection_time: timedelta, ssid_filter) -> None: """Initialize the scanner.""" self._detection_time = detection_time self._controller = controller self._ssid_filter = ssid_filter self._update() def _update(self): """Get the clients from the device.""" from pyunifi.controller import APIError try: clients = self._controller.get_clients() except APIError as ex: _LOGGER.error("Failed to scan clients: %s", ex) clients = [] # Filter clients to provided SSID list if self._ssid_filter: clients = [client for client in clients if client['essid'] in self._ssid_filter] self._clients = { client['mac']: client for client in clients if (dt_util.utcnow() - dt_util.utc_from_timestamp(float( client['last_seen']))) < self._detection_time} def scan_devices(self): """Scan for devices.""" self._update() return self._clients.keys() def get_device_name(self, device): """Return the name (if known) of the device. If a name has been set in Unifi, then return that, else return the hostname if it has been detected. """ client = self._clients.get(device, {}) name = client.get('name') or client.get('hostname') _LOGGER.debug("Device mac %s name %s", device, name) return name
Python
0
@@ -3571,16 +3571,61 @@ if +'essid' in client and%0A client%5B'
6102e0aae8ead38351368a1402657447ca8d3ef7
Use new SensorDeviceClass in mitemp-bt (#61925)
homeassistant/components/mitemp_bt/sensor.py
homeassistant/components/mitemp_bt/sensor.py
"""Support for Xiaomi Mi Temp BLE environmental sensor.""" from __future__ import annotations import logging from typing import Any import btlewrap from btlewrap.base import BluetoothBackendException from mitemp_bt import mitemp_bt_poller import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorEntity, SensorEntityDescription, ) from homeassistant.const import ( CONF_FORCE_UPDATE, CONF_MAC, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_TIMEOUT, DEVICE_CLASS_BATTERY, DEVICE_CLASS_HUMIDITY, DEVICE_CLASS_TEMPERATURE, PERCENTAGE, TEMP_CELSIUS, ) import homeassistant.helpers.config_validation as cv try: import bluepy.btle # noqa: F401 pylint: disable=unused-import BACKEND = btlewrap.BluepyBackend except ImportError: BACKEND = btlewrap.GatttoolBackend _LOGGER = logging.getLogger(__name__) CONF_ADAPTER = "adapter" CONF_CACHE = "cache_value" CONF_MEDIAN = "median" CONF_RETRIES = "retries" DEFAULT_ADAPTER = "hci0" DEFAULT_UPDATE_INTERVAL = 300 DEFAULT_FORCE_UPDATE = False DEFAULT_MEDIAN = 3 DEFAULT_NAME = "MiTemp BT" DEFAULT_RETRIES = 2 DEFAULT_TIMEOUT = 10 SENSOR_TYPES: tuple[SensorEntityDescription, ...] = ( SensorEntityDescription( key="temperature", name="Temperature", device_class=DEVICE_CLASS_TEMPERATURE, native_unit_of_measurement=TEMP_CELSIUS, ), SensorEntityDescription( key="humidity", name="Humidity", device_class=DEVICE_CLASS_HUMIDITY, native_unit_of_measurement=PERCENTAGE, ), SensorEntityDescription( key="battery", name="Battery", device_class=DEVICE_CLASS_BATTERY, native_unit_of_measurement=PERCENTAGE, ), ) SENSOR_KEYS = [desc.key for desc in SENSOR_TYPES] PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_KEYS): vol.All( cv.ensure_list, [vol.In(SENSOR_KEYS)] ), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_MEDIAN, default=DEFAULT_MEDIAN): cv.positive_int, vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean, vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int, vol.Optional(CONF_RETRIES, default=DEFAULT_RETRIES): cv.positive_int, vol.Optional(CONF_CACHE, default=DEFAULT_UPDATE_INTERVAL): cv.positive_int, vol.Optional(CONF_ADAPTER, default=DEFAULT_ADAPTER): cv.string, } ) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the MiTempBt sensor.""" backend = BACKEND _LOGGER.debug("MiTempBt is using %s backend", backend.__name__) cache = config[CONF_CACHE] poller = mitemp_bt_poller.MiTempBtPoller( config[CONF_MAC], cache_timeout=cache, adapter=config[CONF_ADAPTER], backend=backend, ) prefix = config[CONF_NAME] force_update = config[CONF_FORCE_UPDATE] median = config[CONF_MEDIAN] poller.ble_timeout = config[CONF_TIMEOUT] poller.retries = config[CONF_RETRIES] monitored_conditions = config[CONF_MONITORED_CONDITIONS] entities = [ MiTempBtSensor(poller, prefix, force_update, median, description) for description in SENSOR_TYPES if description.key in monitored_conditions ] add_entities(entities) class MiTempBtSensor(SensorEntity): """Implementing the MiTempBt sensor.""" def __init__( self, poller, prefix, force_update, median, description: SensorEntityDescription ): """Initialize the sensor.""" self.entity_description = description self.poller = poller self.data: list[Any] = [] self._attr_name = f"{prefix} {description.name}" self._attr_force_update = force_update # Median is used to filter out outliers. median of 3 will filter # single outliers, while median of 5 will filter double outliers # Use median_count = 1 if no filtering is required. self.median_count = median def update(self): """ Update current conditions. This uses a rolling median over 3 values to filter out outliers. """ try: _LOGGER.debug("Polling data for %s", self.name) data = self.poller.parameter_value(self.entity_description.key) except OSError as ioerr: _LOGGER.warning("Polling error %s", ioerr) return except BluetoothBackendException as bterror: _LOGGER.warning("Polling error %s", bterror) return if data is not None: _LOGGER.debug("%s = %s", self.name, data) self.data.append(data) else: _LOGGER.warning( "Did not receive any data from Mi Temp sensor %s", self.name ) # Remove old data from median list or set sensor value to None # if no data is available anymore if self.data: self.data = self.data[1:] else: self._attr_native_value = None return if len(self.data) > self.median_count: self.data = self.data[1:] if len(self.data) == self.median_count: median = sorted(self.data)[int((self.median_count - 1) / 2)] _LOGGER.debug("Median is: %s", median) self._attr_native_value = median else: _LOGGER.debug("Not yet enough data for median calculation")
Python
0
@@ -327,16 +327,39 @@ SCHEMA,%0A + SensorDeviceClass,%0A Sens @@ -538,91 +538,8 @@ UT,%0A - DEVICE_CLASS_BATTERY,%0A DEVICE_CLASS_HUMIDITY,%0A DEVICE_CLASS_TEMPERATURE,%0A @@ -1266,29 +1266,34 @@ e_class= -DEVICE_CLASS_ +SensorDeviceClass. TEMPERAT @@ -1452,29 +1452,34 @@ e_class= -DEVICE_CLASS_ +SensorDeviceClass. HUMIDITY @@ -1635,21 +1635,26 @@ ass= -DEVICE_CLASS_ +SensorDeviceClass. BATT
eb66cae55dee3b401cd84a71f9906cdb42a217bc
Update __init__.py
pytorch_lightning/__init__.py
pytorch_lightning/__init__.py
"""Root package info.""" __version__ = '0.9.0rc3' __author__ = 'William Falcon et al.' __author_email__ = 'waf2107@columbia.edu' __license__ = 'Apache-2.0' __copyright__ = 'Copyright (c) 2018-2020, %s.' % __author__ __homepage__ = 'https://github.com/PyTorchLightning/pytorch-lightning' # this has to be simple string, see: https://github.com/pypa/twine/issues/522 __docs__ = ( "PyTorch Lightning is the lightweight PyTorch wrapper for ML researchers." " Scale your models. Write less boilerplate." ) __long_docs__ = """ Lightning is a way to organize your PyTorch code to decouple the science code from the engineering. It's more of a style-guide than a framework. In Lightning, you organize your code into 3 distinct categories: 1. Research code (goes in the LightningModule). 2. Engineering code (you delete, and is handled by the Trainer). 3. Non-essential research code (logging, etc. this goes in Callbacks). Although your research/production project might start simple, once you add things like GPU AND TPU training, 16-bit precision, etc, you end up spending more time engineering than researching. Lightning automates AND rigorously tests those parts for you. Overall, Lightning guarantees rigorously tested, correct, modern best practices for the automated parts. Documentation ------------- - https://pytorch-lightning.readthedocs.io/en/latest - https://pytorch-lightning.readthedocs.io/en/stable """ import logging as python_logging _logger = python_logging.getLogger("lightning") _logger.addHandler(python_logging.StreamHandler()) _logger.setLevel(python_logging.INFO) try: # This variable is injected in the __builtins__ by the build # process. It used to enable importing subpackages of skimage when # the binaries are not built __LIGHTNING_SETUP__ except NameError: __LIGHTNING_SETUP__ = False if __LIGHTNING_SETUP__: import sys # pragma: no-cover sys.stdout.write(f'Partial import of `{__name__}` during the build process.\n') # pragma: no-cover # We are not importing the rest of the lightning during the build process, as it may not be compiled yet else: from pytorch_lightning.core import LightningDataModule, LightningModule from pytorch_lightning.core.step_result import TrainResult, EvalResult from pytorch_lightning.callbacks import Callback from pytorch_lightning.trainer import Trainer from pytorch_lightning.utilities.seed import seed_everything from pytorch_lightning import metrics __all__ = [ 'Trainer', 'LightningDataModule', 'LightningModule', 'Callback', 'seed_everything', 'metrics', 'EvalResult', 'TrainResult', ] # necessary for regular bolts imports. Skip exception since bolts is not always installed try: from pytorch_lightning import bolts except ImportError: pass # __call__ = __all__ # for compatibility with namespace packages __import__('pkg_resources').declare_namespace(__name__)
Python
0.000072
@@ -41,17 +41,17 @@ '0.9.0rc -3 +4 '%0A__auth
a5f274b5a3dbb72e109184b7a3c56b2a1dac13b4
Enable WebForm page
frappe/website/serve.py
frappe/website/serve.py
import frappe from frappe import _ from frappe.utils import cstr from frappe.website.page_controllers.document_page import DocumentPage from frappe.website.page_controllers.list_page import ListPage from frappe.website.page_controllers.not_permitted_page import NotPermittedPage from frappe.website.page_controllers.print_page import PrintPage from frappe.website.page_controllers.template_page import TemplatePage from frappe.website.page_controllers.static_page import StaticPage from frappe.website.redirect import resolve_redirect from frappe.website.render import build_response, resolve_path def get_response(path=None, http_status_code=200): """render html page""" query_string = None if not path: path = frappe.local.request.path query_string = frappe.local.request.query_string try: path = path.strip('/ ') resolve_redirect(path, query_string) path = resolve_path(path) data = None # there is no way to determine the type of the page based on the route # so evaluate each type of page sequentially response = StaticPage(path, http_status_code).get() if not response: response = TemplatePage(path, http_status_code).get() if not response: response = ListPage(path, http_status_code).get() if not response: response = DocumentPage(path, http_status_code).get() if not response: response = PrintPage(path, http_status_code).get() if not response: response = TemplatePage('404', 404).get() except frappe.Redirect: return build_response(path, "", 301, { "Location": frappe.flags.redirect_location or (frappe.local.response or {}).get('location'), "Cache-Control": "no-store, no-cache, must-revalidate" }) except frappe.PermissionError as e: frappe.local.message = cstr(e) response = NotPermittedPage(path, http_status_code).get() except Exception as e: response = TemplatePage('error', getattr(e, 'http_status_code', None) or http_status_code).get() return response
Python
0.000008
@@ -475,16 +475,81 @@ aticPage +%0Afrom frappe.website.page_controllers.web_form import WebFormPage %0A%0Afrom f @@ -958,22 +958,8 @@ ath) -%0A%09%09data = None %0A%0A%09%09 @@ -1217,32 +1217,32 @@ f not response:%0A - %09%09%09response = Li @@ -1289,32 +1289,107 @@ f not response:%0A +%09%09%09response = WebFormPage(path, http_status_code).get()%0A%09%09if not response:%0A %09%09%09response = Do
19eb327f180bdd9990ea013f2c3b74f46b85545c
Fancier output
ibm1.py
ibm1.py
#!/usr/bin/python # -*- coding: utf-8 -*- import sys ###################################################### #### EM-IBM1 : Expectation-Maximization Algorithm #### ###################################################### # Alexandre Pais Gomes # Master ISI ######################### #### Initializations #### ######################### # Probability initialization of p(t|s) (equiprobable for each tuple) p = {} total = {} count = {} t_total = {} # Source and target paths (change here if needed) source_path = "resources/d10t10.SOURCE.en" target_path = "resources/d10t10.REFERENCE.fr" # Getting the given number of iterations wanted iteration = 1 # Number of iterations (1 by default) if (len(sys.argv) == 2): iteration = int(sys.argv[1]) print 'Setting the number of iteration at ' + str(iteration) else: print 'Setting the number of iteration at ' + str(iteration) + ' (by default)' #endif how_many_words_in_t = len(open(target_path).read().split()) how_many_lines = len(open(source_path).readlines()) # While non-convergence for i in range(iteration): # Opening the files print 'Initializing iteration ' + str(i+1) + '...' source = open(source_path, "r") target = open(target_path, "r") print ' Normalization and counting...', sys.stdout.flush() # For each pairs of sentences (S,T) for i in range(how_many_lines): ls = source.readline() lt = target.readline() ####################### #### Normalization #### ####################### for words_lt in lt.split(): if(words_lt not in t_total): t_total[words_lt] = 0 #endif for words_ls in ls.split(): if((words_lt, words_ls) not in p): p[(words_lt, words_ls)] = 1. / how_many_words_in_t #endif t_total[words_lt] += p[(words_lt, words_ls)] #endfor #endfor ################## #### Counting #### ################## for words_lt in lt.split(): for words_ls in ls.split(): if((words_lt, words_ls) not in count): count[(words_lt, words_ls)] = 0 #endif count[(words_lt, words_ls)] += p[(words_lt, words_ls)] / t_total[words_lt] if(words_ls not in total): total[words_ls] = 0 #endif total[words_ls] += p[(words_lt, words_ls)] / t_total[words_lt] #endfor #endfor #endfor print 'OK' ################################### #### Probabilities estimations #### ################################### # Re-opening the files source = open(source_path, "r") target = open(target_path, "r") print ' Probabilities estimations...', sys.stdout.flush() for i in range(how_many_lines): # There's probably a better way to do this ls = source.readline() lt = target.readline() for words_ls in ls.split(): for words_lt in lt.split(): p[(words_lt, words_ls)] = count[(words_lt, words_ls)] / total[words_ls] #endfor #endfor #endfor print 'OK' # A few tests print ' documents -> documents : ' + str(p[('documents', 'documents')]) print ' par -> documents : ' + str(p[('par', 'documents')]) #endfor # Writing the results in a file print 'Preparing final output...', sys.stdout.flush() output = open("probabilities.txt", "w") output.write(repr(p) + '\n') output.close() print 'OK'
Python
0.999981
@@ -3103,28 +3103,138 @@ w%22)%0A -output.write(repr(p) +s = ''%0Afor (a,b),y in p.items():%0A%09s += repr(a) + %22 %22 + repr(b) + %22 %22 + repr(y) + '%5Cn'%0A#output.write(repr(p) + '%5Cn')%0Aoutput.write(s + '
fccc9c14a46e529bd8af0da83f5efc2d4e675769
Add a device to back the non-existant floppy drive controller.
src/dev/x86/Pc.py
src/dev/x86/Pc.py
# Copyright (c) 2008 The Regents of The University of Michigan # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer; # redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution; # neither the name of the copyright holders nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # Authors: Gabe Black from m5.params import * from m5.proxy import * from Device import IsaFake from Pci import PciConfigAll from Platform import Platform from SouthBridge import SouthBridge from Terminal import Terminal from Uart import Uart8250 def x86IOAddress(port): IO_address_space_base = 0x8000000000000000 return IO_address_space_base + port; class Pc(Platform): type = 'Pc' system = Param.System(Parent.any, "system") pciconfig = PciConfigAll() south_bridge = SouthBridge() # "Non-existant" port used for timing purposes by the linux kernel i_dont_exist = IsaFake(pio_addr=x86IOAddress(0x80), pio_size=1) # Ports behind the pci config and data regsiters. These don't do anything, # but the linux kernel fiddles with them anway. behind_pci = IsaFake(pio_addr=x86IOAddress(0xcf8), pio_size=8) # Serial port and terminal terminal = Terminal() com_1 = Uart8250() com_1.pio_addr = x86IOAddress(0x3f8) com_1.terminal = terminal # Devices to catch access to non-existant serial ports. fake_com_2 = IsaFake(pio_addr=x86IOAddress(0x2f8), pio_size=8) fake_com_3 = IsaFake(pio_addr=x86IOAddress(0x3e8), pio_size=8) fake_com_4 = IsaFake(pio_addr=x86IOAddress(0x2e8), pio_size=8) def attachIO(self, bus): self.south_bridge.attachIO(bus) self.i_dont_exist.pio = bus.port self.behind_pci.pio = bus.port self.com_1.pio = bus.port self.fake_com_2.pio = bus.port self.fake_com_3.pio = bus.port self.fake_com_4.pio = bus.port self.pciconfig.pio = bus.default bus.responder_set = True bus.responder = self.pciconfig
Python
0
@@ -2805,24 +2805,165 @@ io_size=8)%0A%0A + # A device to catch accesses to the non-existant floppy controller.%0A fake_floppy = IsaFake(pio_addr=x86IOAddress(0x3f2), pio_size=4)%0A%0A def atta @@ -3242,32 +3242,72 @@ .pio = bus.port%0A + self.fake_floppy.pio = bus.port%0A self.pci
fd4688cc899b08253cc50b345bb7e836081783d8
Add Beta and Binomial to automatically imported nodes
bayespy/inference/vmp/nodes/__init__.py
bayespy/inference/vmp/nodes/__init__.py
###################################################################### # Copyright (C) 2011,2012 Jaakko Luttinen # # This file is licensed under Version 3.0 of the GNU General Public # License. See LICENSE for a text of the license. ###################################################################### ###################################################################### # This file is part of BayesPy. # # BayesPy is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # BayesPy is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with BayesPy. If not, see <http://www.gnu.org/licenses/>. ###################################################################### # Import some most commonly used nodes from . import * from .gaussian import Gaussian, GaussianARD from .wishart import Wishart from .gamma import Gamma from .dirichlet import Dirichlet from .categorical import Categorical from .dot import Dot, SumMultiply from .mixture import Mixture from .gaussian_markov_chain import GaussianMarkovChain from .gaussian_markov_chain import VaryingGaussianMarkovChain from .gaussian_markov_chain import SwitchingGaussianMarkovChain from .categorical_markov_chain import CategoricalMarkovChain
Python
0
@@ -1097,24 +1097,24 @@ om . -gaussian +binomial import Gaus @@ -1113,69 +1113,64 @@ ort -Gaussian, GaussianARD%0Afrom .wishart import Wishart +Binomial%0Afrom .categorical import Categorical%0A %0Afrom . -gamm +bet a im @@ -1178,12 +1178,11 @@ ort -Gamm +Bet a%0Afr @@ -1216,53 +1216,65 @@ let%0A +%0A from . -categorical import Categorical +gaussian import Gaussian, GaussianARD %0Afrom . -do +wishar t im @@ -1282,46 +1282,35 @@ ort -Dot, SumMultiply%0Afrom .mixture +Wishart%0Afrom .gamma import Mixt @@ -1309,15 +1309,14 @@ ort -Mixture +Gamma%0A %0Afro @@ -1489,24 +1489,25 @@ MarkovChain%0A +%0A from .catego @@ -1543,20 +1543,101 @@ egoricalMarkovChain%0A +%0Afrom .mixture import Mixture%0A%0Afrom .dot import Dot%0Afrom .dot import SumMultiply%0A
6523991e9d3ea7e7a01e5e36c6fb310ca00ea84c
Update simplefetch.py
simplefetch.py
simplefetch.py
import paramiko, logging, socket, time, re, datetime import sys python3_usage=True if sys.version_info[0] < 3: python3_usage=False """ #v2.0 2020.01.20 #Written by Ercin TORUN #automates ssh login using paramiko library """ #==================some variables line_break = "\r" ios_any_cli_length = "terminal length 0" vrp_cli_length = "screen-length 0 temporary" junos_cli_length = "set cli screen-length 0" cli_prompt = ("#", ">") MAX_BUFFER = 65535 #================================== def get_command_results(channel, hostname): ## http://joelinoff.com/blog/?p=905 interval = 0.1 maxseconds = 30 maxcount = maxseconds / interval bufsize = 9192 # Poll until completion or timeout # Note that we cannot directly use the stdout file descriptor # because it stalls at 64K bytes (65536). input_idx = 0 timeout_flag = False start = datetime.datetime.now() start_secs = time.mktime(start.timetuple()) output = '' channel.setblocking(0) while True: if channel.recv_ready(): data = channel.recv(bufsize).decode('ascii') output += data if channel.exit_status_ready(): break # Timeout check now = datetime.datetime.now() now_secs = time.mktime(now.timetuple()) et_secs = now_secs - start_secs if et_secs > maxseconds: timeout_flag = True break rbuffer = output.rstrip(' ') if len(rbuffer) > 0 and hostname in rbuffer: ## got a Cisco command prompt time.sleep(0.5) #sometimes router returns hostname 2 times with an empty line, wait for a short time, example at bottom break time.sleep(0.200) if channel.recv_ready(): data = channel.recv(bufsize) output += data.decode('ascii') return output def send_command_and_get_response(channel, cmd, hostname): if not cmd.endswith("\n"): channel.send(cmd+"\n") else: channel.send(cmd) results = get_command_results(channel, hostname) results = results.split(hostname)[-0] # at the end of the output, an empty line with router name comes, remove it results = results.split(cmd)[-1] #router returns the first command that is send, so split and do not display the command that is sent if results[-1:] in ["<","["]: #if router is huawei before router name there might be a string < or [ e.g. <nw_rt_...> results = results[:-1] return results self, host, port, user, passwd, os): class SSH: """ Simple shell to run a command on the host """ def __init__(self, host, port, user, passwd, network_os=None): self.os=network_os self.host = host self.connectionsuccess = False self.port=port """Connecting to Host""" try: self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) logging.info("Connecting to host "+self.host) self.ssh.connect(self.host, username=user, password=passwd, port=self.port, allow_agent=False, look_for_keys=False, timeout=10) logging.info("Connected to host "+self.host) """Invoking Shell and Pagination""" try: self.chan = self.ssh.invoke_shell(width=255,width_pixels=0, height_pixels=0) resp=self.chan.recv(MAX_BUFFER) if python3_usage: resp=resp.decode() if "failed" in resp: logging.warning ("connection failed, this log is send by the host:" +resp) raise ValueError("connection failed, this log is send by the host:" +resp) return except: logging.warning("could not invoke a shell to %s" % self.host) raise ValueError("could not invoke a shell to %s" % self.host) return self.prompt= re.sub('[><#]', '', resp.split()[-1]) #get device hostname logging.info("the router name connected is %s" % self.prompt) logging.info("Invoked a shell to %s , now sending pagination commands" % self.host) buff="" resp="" if self.os in ("cisco-ios" ,"cisco-nxos","cisco-iosxe","cisco-iosxr"): send_command_and_get_response(self.chan,ios_any_cli_length, self.prompt) elif self.os=="huawei-vrp6": send_command_and_get_response(self.chan,vrp_cli_length, self.prompt) elif self.os=="junos": send_command_and_get_response(self.chan,junos_cli_length, self.prompt) else: logging.info("device software type '%s' is unkown, no pagination command is send to device" % os) raise ValueError("device software type '%s' is unkown, no pagination command is send to device" % os) return time.sleep(1) self.connectionsuccess = True except paramiko.ssh_exception.AuthenticationException: logging.warning("Authentication failure on %s" % self.host) raise ValueError("Authentication failure on %s"% self.host) return except socket.timeout: logging.warning("Timed out on %s") raise ValueError("Authentication failure on %s" % self.host) return except socket.error: logging.warning("Connection refused on %s" % self.host) raise ValueError("Connection refused on %s" %self.host) return def fetchdata(self, cmd): if self.connectionsuccess: logging.info("running "+ str(cmd)+" on host "+self.host) resp = "" buff = "" buff = send_command_and_get_response(self.chan,cmd,self.prompt) logging.info("["+self.host+"] > All initial commands ran.") return buff else: logging.warning("No connection has been established to %s therefore command could not be executed" % self.host) return def disconnect (self): if self.connectionsuccess: self.ssh.close() logging.info("["+self.host+"] < Disconnected") else: logging.warning("No connection exist to %s therefore no need to close" % self.host) raise ValueError("No connection exist to %s therefore no need to close" % self.host) return
Python
0
@@ -3988,17 +3988,16 @@ awei-vrp -6 %22:%0D%0A%09%09%09%09 @@ -5707,28 +5707,30 @@ ose%22 %25 self.host)%0D%0A%09%09%09return +%0D%0A
769a334675cc451c6de07ed21e23ffd4480088df
Add time/space complexity
lc0041_first_missing_positive.py
lc0041_first_missing_positive.py
"""Leetcode 41. First Missing Positive Hard URL: https://leetcode.com/problems/first-missing-positive/ Given an unsorted integer array, find the smallest missing positive integer. Example 1: Input: [1,2,0] Output: 3 Example 2: Input: [3,4,-1,1] Output: 2 Example 3: Input: [7,8,9,11,12] Output: 1 Note: Your algorithm should run in O(n) time and uses constant extra space. """ class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ n = len(nums) for i in range(n): # Keep swapping old & new nums[i] to their correct positions. while nums[i] > 0 and nums[i] <= n and nums[i] != nums[nums[i] - 1]: # If nums[i] = k, swap it and nums[k - 1], with correct position k - 1. nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1] # Check each updated elements in nums with true positive integer. for i in range(n): if i + 1 != nums[i]: return i + 1 # If all elements in nums are correct, return the last one plus one. return n + 1 def main(): # Ans: 3 nums = [1,2,0] print Solution().firstMissingPositive(nums) # Ans: 2 nums = [3,4,-1,1] print Solution().firstMissingPositive(nums) # Ans: 1 nums = [7,8,9,11,12] print Solution().firstMissingPositive(nums) # Ans: 1 nums = [] print Solution().firstMissingPositive(nums) # Ans: 2 nums = [1] print Solution().firstMissingPositive(nums) # Ans: 3 nums = [-1,4,2,1,9,10] print Solution().firstMissingPositive(nums) if __name__ == '__main__': main()
Python
0.002369
@@ -504,16 +504,80 @@ ype: int +%0A%0A Time complexity: O(n).%0A Space complexity: O(1). %0A @@ -676,16 +676,18 @@ nums%5Bi%5D +'s to thei @@ -849,14 +849,11 @@ - 1%5D -, with + at cor
f33b294d60ffbfb5351d4579e38ea197e2c3787a
Complete reverse iter sol
lc0482_license_key_formatting.py
lc0482_license_key_formatting.py
"""Leecode 482. License Key Formatting Easy URL: https://leetcode.com/problems/license-key-formatting/ You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. Given a non-empty string S and a number K, format the string according to the rules described above. Example 1: Input: S = "5F3Z-2e-9-w", K = 4 Output: "5F3Z-2E9W" Explanation: The string S has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. Example 2: Input: S = "2-5g-3-J", K = 2 Output: "2-5G-3J" Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. Note: - The length of string S will not exceed 12,000, and K is a positive integer. - String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-). - String S is non-empty. """ class Solution(object): def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ pass def main(): pass if __name__ == '__main__': main()
Python
0.999999
@@ -1351,16 +1351,27 @@ Solution +ReverseIter (object) @@ -1512,35 +1512,944 @@ -pass%0A%0A%0Adef main():%0A pass +# Upper case and drop dash.%0A S_nodashes = S.upper().replace('-','')%0A size_nodashes = len(S_nodashes)%0A%0A # Reversely iterate through no-dashed list, concat to string until K chars.%0A res_ls = %5B''%5D * (size_nodashes // K + (size_nodashes %25 K %3E 0))%0A%0A cur_idx = len(res_ls) - 1%0A cur_counter = 0%0A%0A for i in range(size_nodashes - 1, -1, -1):%0A if cur_counter %3C K:%0A res_ls%5Bcur_idx%5D = S_nodashes%5Bi%5D + res_ls%5Bcur_idx%5D%0A cur_counter += 1%0A else:%0A cur_idx -= 1%0A res_ls%5Bcur_idx%5D = S_nodashes%5Bi%5D + res_ls%5Bcur_idx%5D%0A cur_counter = 1%0A%0A return '-'.join(res_ls)%0A%0A%0Adef main():%0A # Output: %225F3Z-2E9W%22%0A S = %225F3Z-2e-9-w%22%0A K = 4%0A print SolutionReverseIter().licenseKeyFormatting(S, K)%0A%0A # Output: %225F3Z-2E9W%22%0A S = %222-5g-3-J%22%0A K = 2%0A print SolutionReverseIter().licenseKeyFormatting(S, K) %0A%0A%0Ai
9a1aec04549ed03cb8e0d8e4e59f29c08bce7716
set absolute uri script path
middleware.py
middleware.py
__license__ = "Apache 2.0" __copyright__ = "Copyright 2008 nb.io" __author__ = "Randy Reddig - ydnar@nb.io" import sys import logging import re from time import sleep from random import randint from django.conf import settings from django.http import HttpResponsePermanentRedirect, Http404 from django.core.urlresolvers import resolve from django.template import loader, TemplateDoesNotExist from nbio.django.shortcuts import build_url TEMPLATE_PATH = u'auto' INDEX_TEMPLATE = u'__index__.html' RE_SLASHES = re.compile(r'/+') RE_START_SLASH = re.compile(r'^/+') RE_END_SLASH = re.compile(r'(?<=.)/$') request_counter = 0 def increment(): global request_counter request_counter += 1 return request_counter class CanonicalMiddleware: def process_view(self, request, view_func, view_args, view_kwargs): """ Process the request, and attempt to normalize these components: http vs https canonical hostname port number add trailing slash (if required) """ increment() # test slow ajax #sleep(randint(0, 4)) if 'location' in view_kwargs: return HttpResponsePermanentRedirect(view_kwargs['location']) redirect = False is_secure = request.is_secure() if 'secure' in view_kwargs: if is_secure != bool(view_kwargs['secure']): is_secure = not is_secure redirect = True del view_kwargs['secure'] host = request.META['SERVER_NAME'] if 'host' in view_kwargs: if host != view_kwargs['host']: change = True if hasattr(settings, 'HOST_FILTERS'): for filter in settings.HOST_FILTERS: if filter.search(host): change = False request.META['X_OVERRIDE_SERVER_NAME'] = host break if change: host = view_kwargs['host'] redirect = True del view_kwargs['host'] port = request.META['SERVER_PORT'] if 'port' in view_kwargs: if port != view_kwargs['port']: port = view_kwargs['port'] redirect = True del view_kwargs['port'] # clean up path path = RE_SLASHES.sub(u'/', unicode(request.path)) # redirect to specific path if 'path' in view_kwargs: if path != view_kwargs['path']: path = view_kwargs['path'] del view_kwargs['path'] # handle slashes path_ends_with_slash = path.endswith(u'/') strip_trailing_slash = hasattr(settings, 'STRIP_TRAILING_SLASH') and settings.STRIP_TRAILING_SLASH if strip_trailing_slash and path_ends_with_slash and path != u'/': path = path[:-1] # auto view else: try: view_kwargs['template'] = loader.get_template(TEMPLATE_PATH + path) except (TemplateDoesNotExist, UnicodeError): try: view_kwargs['template'] = loader.get_template(TEMPLATE_PATH + path + u'/' + INDEX_TEMPLATE) if not strip_trailing_slash and not path_ends_with_slash: path += '/' except (TemplateDoesNotExist, UnicodeError): if not strip_trailing_slash and not path_ends_with_slash: if view_func == self._get_view_func(path + u'/'): path += u'/' # redirect if path has changed if path != request.path: redirect = True query_string = request.META['QUERY_STRING'] if redirect: url = build_url(request, is_secure, host, port, path, query_string) return HttpResponsePermanentRedirect(url) def _get_view_func(self, path): try: (view_func, view_args, view_kwargs) = resolve(path) return view_func except Http404: return None
Python
0
@@ -329,16 +329,35 @@ resolve +, set_script_prefix %0Afrom dj @@ -1063,32 +1063,128 @@ ment()%0A %0A + # set script prefix%0A set_script_prefix(request.build_absolute_uri('/'))%0A %0A # test s
dc95d6766d305f2126c158f50417e29d0c47ce3f
Change doc route
backoffice_operateurs/__init__.py
backoffice_operateurs/__init__.py
# -*- coding: utf8 -*- VERSION = (0, 1, 0) __author__ = 'Vincent Lara' __contact__ = "vincent.lara@data.gouv.fr" __homepage__ = "https://github.com/" __version__ = ".".join(map(str, VERSION)) from flask import Flask, make_response from flask.ext.security import Security, SQLAlchemyUserDatastore from flask.ext.script import Manager from flask.ext.security.utils import verify_and_update_password from flask.ext import restful from flask_bootstrap import Bootstrap import os from models import db from models import security as security_models, taxis as taxis_models,\ administrative as administrative_models from flask.ext.restplus import Api app = Flask(__name__) app.config.from_object('default_settings') if 'BO_OPERATEURS_CONFIG_FILE' in os.environ: app.config.from_envvar('BO_OPERATEURS_CONFIG_FILE') db.init_app(app) user_datastore = SQLAlchemyUserDatastore(db, security_models.User, security_models.Role) security = Security(app, user_datastore) api = Api(app) api.model(taxis_models.ADS, taxis_models.ADS.marshall_obj()) ns = api.namespace('ADS', description="Description ADS") from views import ads from views import conducteur from views import zupc from views import home app.register_blueprint(ads.mod) app.register_blueprint(conducteur.mod) app.register_blueprint(zupc.mod) app.register_blueprint(home.mod) @api.representation('text/html') def output_html(data, code=200, headers=None): resp = make_response(data, code) resp.headers.extend(headers or {}) return resp @app.login_manager.request_loader def load_user_from_request(request): auth = request.headers.get('Authorization') if not auth or auth.count(':') != 1: return None login, password = auth.split(':') user = user_datastore.get_user(login.strip()) if user is None: return None if not verify_and_update_password(password.strip(), user): return None if not user.is_active(): return None return user Bootstrap(app) manager = Manager(app)
Python
0
@@ -642,17 +642,25 @@ port Api +, apidoc %0A - %0Aapp = F @@ -1009,16 +1009,26 @@ Api(app +, ui=False )%0Aapi.mo @@ -1140,16 +1140,102 @@ ADS%22)%0A%0A +%0A@app.route('/doc/', endpoint='doc')%0Adef swagger_ui():%0A return apidoc.ui_for(api)%0A%0A from vie @@ -1460,16 +1460,54 @@ ome.mod) +%0Aapp.register_blueprint(apidoc.apidoc) %0A%0A@api.r @@ -2111,24 +2111,24 @@ return None%0A - return u @@ -2132,16 +2132,17 @@ n user%0A%0A +%0A %0A%0ABootst
aa4061887fc750dd63cd226e3fa45f0b56ec2462
Update server.py
site/server.py
site/server.py
#Import flask libraries import json, re, os, datetime, logging;#Import general libraries from flask import Flask, jsonify, request, render_template, send_from_directory; from flask_socketio import SocketIO, send, emit, join_room, leave_room, close_room; from flask_mail import Mail, Message; from flask_socketio import join_room; from flask_sqlalchemy import SQLAlchemy; from sqlalchemy import create_engine;#Engine handler #from PIL import Image; from logging.handlers import RotatingFileHandler; from logging import Formatter; import environment, recorder;#Import custom libraries FlaskServer = Flask(__name__);#Dynamic web server Interactive = SocketIO(FlaskServer);#Socket handler FlaskServer.config.from_object(os.getenv("SERVER_ENV") if os.getenv("SERVER_ENV") else "environment.Testing"); Mailer = Mail(FlaskServer);#Mail handler DB = SQLAlchemy(FlaskServer);#Sqlalchemy database handler import models; #engine = create_engine('mysqli://tcid:tcid@localhost/tcid);#set username, password, and database @app.route('/') def hello_world(): return 'Hello, World!'
Python
0.000001
@@ -447,24 +447,25 @@ ort Image;%0D%0A +# from logging @@ -503,16 +503,17 @@ ndler;%0D%0A +# from log @@ -536,16 +536,17 @@ atter;%0D%0A +# import e
184ac486740cfca13b3fdb42d3965017c93c6fb5
remove streamcloud filter
flashget/pages/ddlme.py
flashget/pages/ddlme.py
# -*- coding: utf-8 -*- from flashget.page import Page, log from flashget.url import UrlMgr from flashget.helper import textextract import json class DdlMe(Page): eregex = r'.*ddl.me.*' ename = 'ddl.me' name = 'ddl me' url = 'http://de.ddl.me' def get(self): link = self.link # this page is special: in it's headers it says it is iso-8859-1 but it actually returns utf-8 url = UrlMgr(url=link, encoding='utf-8') name = textextract(url.data, "<title>",' ยป Download & Stream ยป DDLme</title>') media = self.getMedia(name, link) if not media: return None streams = textextract(url.data, '<script type="text/javascript">var subcats = ', '};')+"}" streams = json.loads(streams) for sid in streams: streamData = streams[sid] part = media.createSub() if 'info' in streamData: part.season = int(streamData['info']['staffel']) part.num = int(streamData['info']['nr']) part.name = textextract(streamData['info']['name'], "", u" ยป") for streamName in streamData['links']: if streamName != "Streamcloud": log.info("at ddl.me only download from streamcloud") continue streamParts = streams[sid]['links'][streamName] alternative = part.createSub() existingPartIds = [] for p in streamParts: # 0=partId, 1=js action, 2=icon, 3=url, 4=hoster id, 5=type # TODO write a system to correct this - but I guess since the dataformat # of them is so bad, it is better to wait until they change it if p[0] in existingPartIds: continue existingPartIds.append(p[0]) alternativePart = alternative.createSub() alternativePart.url = p[3] # for debugging # self.afterExtract(media) # import pprint # pprint.pprint(streams) # print(media.__str__().encode('utf-8')) # import sys # sys.exit() return self.afterExtract(media)
Python
0.000001
@@ -1164,158 +1164,8 @@ '%5D:%0A - if streamName != %22Streamcloud%22:%0A log.info(%22at ddl.me only download from streamcloud%22)%0A continue%0A
d6949099bb718a218d4cce778969ec484e8f4e29
use different position identifier
scripts/ingestors/dotcams/ingest_dot_webcams.py
scripts/ingestors/dotcams/ingest_dot_webcams.py
"""Ingest DOT RWIS Webcams. RUN from RUN_10MIN.sh """ # stdlib from datetime import datetime, timedelta, timezone import os import json import tempfile import subprocess # third party import requests from pyiem import util LOG = util.logger() URI = ( "https://services.arcgis.com/8lRhdTsQyJpO52F1/ArcGIS/rest/services/" "RWIS_Camera_Info_View/FeatureServer/0/query?where=1%3D1&outFields=*&" "f=json" ) CLOUD404 = "/mesonet/tmp/dotcloud404.txt" def process_feature(cursor, feat): """Do what we need to do with this feature.""" props = feat["attributes"] if props["RPUID"] is None: LOG.info("feature has no RPUID, skipping") return rpuid = int(props["RPUID"]) scene = int(props["SCANWEB_POSITIONID"]) # Imagery is stored as IDOT-<RPUID:03i>-<SCENE-02i>.jpg cam = f"IDOT-{rpuid:03.0f}-{scene:02.0f}" # Loop over 10 possible images found with this feature for i in range(1, 11): suffix = f"_{i}" if i > 1 else "" key = f"IMAGE_DATE{suffix}" timestamp = props.get(key) if timestamp is None: continue valid = datetime(1970, 1, 1) + timedelta(seconds=timestamp / 1000.0) valid = valid.replace(tzinfo=timezone.utc) LOG.info("%s %s", cam, valid) # Do we have this image? cursor.execute( "SELECT drct from camera_log where valid = %s and cam = %s", (valid, cam), ) if cursor.rowcount > 0: continue url = props[f"IMAGE_URL{suffix}"] if url.find("Not_Available") > -1: LOG.debug("skipping %s %s %s", cam, valid, url) continue # 15 second timeout may be too aggressive req = requests.get(url, timeout=30) if req.status_code == 404: LOG.debug("cloud 404 %s", url) with open(CLOUD404, "a", encoding="utf8") as fh: fh.write(f"{url}\n") continue if req.status_code != 200: LOG.info("Fetching %s resulted in status %s", url, req.status_code) continue tmpfd = tempfile.NamedTemporaryFile(mode="wb", delete=False) tmpfd.write(req.content) tmpfd.close() # Create log entry cursor.execute( "INSERT into camera_log(cam, valid, drct) VALUES (%s, %s, %s)", (cam, valid, 0), ) # Get current entry cursor.execute( "SELECT valid from camera_current where cam = %s", (cam,) ) if cursor.rowcount == 0: LOG.info("Creating camera_current entry for %s", cam) cursor.execute( "INSERT into camera_current(cam, valid, drct) " "VALUES (%s, %s, %s)", (cam, valid - timedelta(minutes=1), 0), ) cursor.execute( "SELECT valid from camera_current where cam = %s", (cam,) ) lastvalid = cursor.fetchone()[0] routes = "a" if valid > lastvalid: routes = "ac" cursor.execute( "UPDATE camera_current SET valid = %s where cam = %s", (valid, cam), ) cmd = ( f"pqinsert -p 'webcam {routes} {valid:%Y%m%d%H%M} " f"camera/stills/{cam}.jpg " f"camera/{cam}/{cam}_{valid:%Y%m%d%H%M}.jpg jpg' {tmpfd.name}" ) LOG.debug(cmd) with subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) as proc: proc.communicate() os.unlink(tmpfd.name) def main(): """Go Main Go""" pgconn = util.get_dbconn("mesosite") # Fetch the REST service req = util.exponential_backoff(requests.get, URI, timeout=30) if req is None: LOG.info("Failed to fetch REST service, aborting.") return jobj = req.json() if "features" not in jobj: LOG.info( "Got status_code: %s, invalid result of: %s", req.status_code, json.dumps(jobj, sort_keys=True, indent=4, separators=(",", ": ")), ) return LOG.info("len(features): %s", len(jobj["features"])) for feat in jobj["features"]: mcursor = pgconn.cursor() try: process_feature(mcursor, feat) except Exception as exp: LOG.error(exp) mcursor.close() pgconn.commit() if __name__ == "__main__": main()
Python
0.000461
@@ -696,24 +696,84 @@ s%5B%22RPUID%22%5D)%0A + # Changed from SCANWEB_ as that appears to be wrong now%0A scene = @@ -783,23 +783,22 @@ (props%5B%22 -S CA -NWEB +MERA _POSITIO @@ -798,18 +798,16 @@ POSITION -ID %22%5D)%0A @@ -908,16 +908,51 @@ 02.0f%7D%22%0A + LOG.info(%22Processing %25s%22, cam)%0A # Lo
ec149e2e6b56f201ed154eaeecab2f651fe70351
Update docstrings.
dyfunconn/graphs/laplacian_energy.py
dyfunconn/graphs/laplacian_energy.py
# -*- coding: utf-8 -*- """ Laplcian Energy The Laplcian energy (LE) for a graph :math:`G` is computed as .. math:: LE(G) = \sum_{i=1}^n | {\mu_i - \frac{2m}{n}} | ฮพ(A_1, A_2 ; t) = โ€–expโก(-tL_1 ) - expโก(-tL_2 )โ€–_F^2 Where :math:``\mu_i` denote the eigenvalue associated with the node of the Laplcian matrix of :math:`G` (Laplcian spectrum) and :math:`\frac{2m}{n}` the average vertex degree. For a details please go through the original work (Gutman2006_). | ----- .. [Gutman2006] Gutman, I., & Zhou, B. (2006). Laplacian energy of a graph. Linear Algebra and its applications, 414(1), 29-37. """ # Author: Avraam Marimpis <avraam.marimpis@gmail.com>" import numpy as np import scipy from scipy import sparse import bct def laplacian_energy(mtx): """ Laplacian Energy Parameters ---------- mtx : array-like, shape(N, N) Symmetric, weighted and undirected connectivity matrix. Returns ------- le : float The Laplacian Energy. """ lmtx = scipy.sparse.csgraph.laplacian(mtx, normed=False) w, v = np.linalg.eig(lmtx) avg_degree = np.mean(bct.degrees_und(mtx)) le = np.sum(np.abs(w - avg_degree)) return le
Python
0
@@ -123,16 +123,17 @@ LE(G) = +%5C %5Csum_%7Bi= @@ -144,16 +144,21 @@ %7C %7B + %5C %5Cmu_ -i +%7Bi%7D - +%5C %5Cfra @@ -165,16 +165,17 @@ c%7B2m%7D%7Bn%7D + %7D %7C%0A @@ -240,17 +240,16 @@ :math:%60 -%60 %5Cmu_i%60 d @@ -362,16 +362,17 @@ :math:%60%5C +%5C frac%7B2m%7D
cd3e129c1951dbb1d2d99d454b1e07d96d1d5497
Support multi or non-multi mappers for bowtie alignments
bcbio/ngsalign/bowtie.py
bcbio/ngsalign/bowtie.py
"""Next gen sequence alignments with Bowtie (http://bowtie-bio.sourceforge.net). """ import os import subprocess from bcbio.utils import file_transaction galaxy_location_file = "bowtie_indices.loc" def align(fastq_file, pair_file, ref_file, out_base, align_dir, config): """Before a standard or paired end alignment with bowtie. """ qual_format = config["algorithm"].get("quality_format", None) if qual_format is None or qual_format.lower() == "illumina": qual_flags = ["--phred64-quals"] else: qual_flags = [] out_file = os.path.join(align_dir, "%s.sam" % out_base) if not os.path.exists(out_file): cl = [config["program"]["bowtie"]] cl += qual_flags cl += ["-q", "-v", config["algorithm"]["max_errors"], "-k", 1, "-X", 1000, # matches bwa sampe default size "-M", 1, "--best", "--strata", "--sam", ref_file] if pair_file: cl += ["-1", fastq_file, "-2", pair_file] else: cl += [fastq_file] cl += [out_file] cl = [str(i) for i in cl] with file_transaction(out_file): subprocess.check_call(cl) return out_file
Python
0
@@ -543,16 +543,146 @@ gs = %5B%5D%0A + multi_mappers = config%5B%22algorithm%22%5D.get(%22multiple_mappers%22, True)%0A multi_flags = %5B%22-M%22, 1%5D if multi_mappers else %5B%22-m%22, 1%5D%0A out_ @@ -733,16 +733,16 @@ t_base)%0A - if n @@ -838,16 +838,42 @@ l_flags%0A + cl += multi_flags%0A @@ -961,24 +961,24 @@ %22-k%22, 1,%0A + @@ -1029,32 +1029,8 @@ ize%0A - %22-M%22, 1,%0A
18febd5525a745b9f8cf6acacbe22e7823d80ac2
Update references to coala-analyzer
bears/python/MypyBear.py
bears/python/MypyBear.py
from collections import namedtuple import textwrap import sys from coalib.bearlib.abstractions.Linter import linter from dependency_management.requirements.PipRequirement import PipRequirement class FlagInfo(namedtuple('FlagInfo', 'arg doc inverse')): """ Information about a command-line flag. :param arg: The argument to pass to enable the flag. :param doc: A help text for the flag. :param inverse: Set to ``True`` when the coala option is the inverse of the subprocess one, for example coala's ``allow_untyped_calls`` is the inverse of mypy's ``--disallow-untyped-calls``. """ def want_flag(self, value): """ Check if the flag should be added to the argument list. :param value: The configuration value. :return: The flag value, may be negated if the flag specifies so. """ if self.inverse: value = not value return value FLAG_MAP = { 'allow_untyped_functions': FlagInfo( arg='--disallow-untyped-defs', doc='Allow defining functions without type annotations or with ' 'incomplete type annotations.', inverse=True), 'allow_untyped_calls': FlagInfo( arg='--disallow-untyped-calls', doc='Allow calling functions without type annotations from ' 'typed functions.', inverse=True), 'check_untyped_function_bodies': FlagInfo( arg='--check-untyped-defs', doc='Do not check the interior of functions without type annotations.', inverse=False), 'strict_optional': FlagInfo( arg='--strict-optional', doc='Enable experimental strict checks related to Optional types. See ' '<http://mypy-lang.blogspot.com.es/2016/07/mypy-043-released.html>' ' for an explanation.', inverse=False), } def add_param_docs(param_map): """ Append documentation from FLAG_MAP to a function's docstring. :param param_map: A mapping of argument names (strings) to FlagInfo objects. :return: A decorator that appends flag information to a function's docstring. """ def decorator(func): func.__doc__ = textwrap.dedent(func.__doc__) + '\n'.join( ':param {}:\n{}'.format(name, textwrap.indent(arg.doc, ' ')) for name, arg in param_map.items()) return func return decorator # Mypy generates messages in the format: # blabla.py: note: In function "f": # blabla.py:2: error: Unsupported operand types for ... # The "note" messages are only adding info coala should already know, # so discard those. We're only capturing the errors. @linter(executable=sys.executable, prerequisite_check_command=(sys.executable, '-m', 'mypy', '-V'), output_format='regex', output_regex=r'[^:]+:(?:(?P<line>\d+):)? ' '(?P<severity>error): (?P<message>.*)') class MypyBear: """ Type-checks your Python files! Checks optional static typing using the mypy tool. See <http://mypy.readthedocs.io/en/latest/basics.html> for info on how to add static typing. """ LANGUAGES = {'Python', 'Python 2', 'Python 3'} AUTHORS = {'Petr Viktorin'} REQUIREMENTS = {PipRequirement('mypy-lang', '0.4.6')} AUTHORS_EMAILS = {'encukou@gmail.com'} LICENSE = 'AGPL-3.0' ASCIINEMA_URL = 'https://asciinema.org/a/90736' # This detects typing errors, which is pretty unique -- it doesn't # make sense to add a category for it. CAN_DETECT = set() @add_param_docs(FLAG_MAP) def create_arguments(self, filename, file, config_file, language: str='Python 3', python_version: str=None, allow_untyped_functions: bool=True, allow_untyped_calls: bool=True, check_untyped_function_bodies: bool=False, strict_optional: bool=False): """ :param language: Set to ``Python`` or ``Python 3`` to check Python 3.x source. Use ``Python 2`` for Python 2.x. :param python_version: Set the specific Python version, e.g. ``3.5``. """ args = ['-m', 'mypy'] if language.lower() == 'python 2': args.append('--py2') elif language.lower() not in ('python 3', 'python'): # Ideally, this would fail the check, but there's no good # way to fail from create_arguments. # See https://github.com/coala-analyzer/coala/issues/2573 self.err( 'Language needs to be "Python", "Python 2" or "Python 3". ' 'Assuming Python 3.') if python_version: args.extend(['--python-version', python_version]) loc = locals() args.extend(flag.arg for name, flag in FLAG_MAP.items() if flag.want_flag(loc[name])) args.append(filename) return args
Python
0.000001
@@ -4593,17 +4593,8 @@ oala --analyzer /coa
49e86f8f0f16ac5fe20cb9f91893f5aa5eee2237
Remove tests for old api
games/tests/test_api.py
games/tests/test_api.py
from django.test import TestCase from django.core.urlresolvers import reverse from . import factories import json class TestOldApi(TestCase): def setUp(self): game = factories.GameFactory games = [game() for i in range(5)] self.library = factories.GameLibraryFactory(games=games) other_games = [game(name="Metroid"), game(name="Mario")] self.other_library = factories.GameLibraryFactory(games=other_games) def test_anonymous_user_cant_get_library(self): response = self.client.get("/api/v1/library/") self.assertEqual(response.status_code, 401) def test_get_library(self): user = self.library.user self.assertTrue(user.api_key) response = self.client.get("/api/v1/library/?username=%s&api_key=%s" % (user.username, user.api_key.key)) self.assertEqual(response.status_code, 200) library_games = json.loads(response.content)["objects"][0]['games'] game_slugs = [game['slug'] for game in library_games] self.assertIn("quake", game_slugs) self.assertNotIn("mario", game_slugs) class TestGameApi(TestCase): def setUp(self): self.num_games = 10 self.games = [] for n in range(self.num_games): self.games.append( factories.GameFactory(name='game_%d' % n, slug='game-%d' % n) ) def test_can_get_games(self): game_list_url = reverse('api_game_list') response = self.client.get(game_list_url) self.assertEqual(response.status_code, 200) games = json.loads(response.content) self.assertEqual(len(games['results']), self.num_games) def test_can_get_subset_of_games(self): game_slugs = {'games': ['game-1', 'game-2', 'game-4']} game_list_url = reverse('api_game_list') response = self.client.get(game_list_url, data=game_slugs, extra={"Content-Type": "application/json"}) self.assertEqual(response.status_code, 200) games = json.loads(response.content) self.assertEqual(len(games['results']), len(game_slugs['games'])) def test_can_post_subset_of_games(self): game_slugs = {'games': ['game-1', 'game-2', 'game-4']} game_list_url = reverse('api_game_list') response = self.client.post( game_list_url, data=json.dumps(game_slugs), content_type='application/json' ) self.assertEqual(response.status_code, 200) games = json.loads(response.content) self.assertEqual(len(games['results']), len(game_slugs['games'])) def test_can_query_game_details(self): response = self.client.get(reverse('api_game_detail', kwargs={'slug': 'game-1'})) self.assertEqual(response.status_code, 200) class TestGameLibraryApi(TestCase): def setUp(self): game = factories.GameFactory games = [game() for i in range(5)] self.library = factories.GameLibraryFactory(games=games) other_games = [game(name="Metroid"), game(name="Mario")] self.other_library = factories.GameLibraryFactory(games=other_games) def test_anonymous_requests_are_rejected(self): user = self.library.user library_url = reverse('api_game_library', kwargs={'username': user.username}) response = self.client.get(library_url) self.assertEqual(response.status_code, 401) def test_can_get_library(self): user = self.library.user self.client.login(username=user.username, password='password') library_url = reverse('api_game_library', kwargs={'username': user.username}) response = self.client.get(library_url) self.assertEqual(response.status_code, 200)
Python
0
@@ -113,1039 +113,8 @@ n%0A%0A%0A -class TestOldApi(TestCase):%0A def setUp(self):%0A game = factories.GameFactory%0A games = %5Bgame() for i in range(5)%5D%0A self.library = factories.GameLibraryFactory(games=games)%0A other_games = %5Bgame(name=%22Metroid%22), game(name=%22Mario%22)%5D%0A self.other_library = factories.GameLibraryFactory(games=other_games)%0A%0A def test_anonymous_user_cant_get_library(self):%0A response = self.client.get(%22/api/v1/library/%22)%0A self.assertEqual(response.status_code, 401)%0A%0A def test_get_library(self):%0A user = self.library.user%0A self.assertTrue(user.api_key)%0A%0A response = self.client.get(%22/api/v1/library/?username=%25s&api_key=%25s%22%0A %25 (user.username, user.api_key.key))%0A self.assertEqual(response.status_code, 200)%0A library_games = json.loads(response.content)%5B%22objects%22%5D%5B0%5D%5B'games'%5D%0A game_slugs = %5Bgame%5B'slug'%5D for game in library_games%5D%0A self.assertIn(%22quake%22, game_slugs)%0A self.assertNotIn(%22mario%22, game_slugs)%0A%0A%0A clas
a6283772b07a29faa54a8c141947e19005bef61e
append max and min to entire dataset
minMaxCalc.py
minMaxCalc.py
import pandas as pd # read in dataset xl = pd.ExcelFile("data/130N_Cycles_1-47.xlsx") df = xl.parse("Specimen_RawData_1") df """ This is what the dataset currently looks like - it has 170,101 rows and two columns. The dataset contains data from 47 cycles following an experiment. The output of these experiments form the two columns:<br> - time (seconds) - load (exerted force, in Newtons) My task is to find the local maxima and minima in the dataset, and mark these values in a database. Initially, the database will consist of four columns: time, load, max, and min. It can be modified or condensed later on to fit further requirements. This is the criteria I will use to find the maxima: - write each row in the db to a cache - initialize a flag value to false - if the force in the previous row is smaller than the force in the next row, write the new row to the cache (leave the flag as false) - if the force in the previous row is bigger than the force in the next row, write the new row to cache and mark it as a max cycle (change the flag to true) This is the criteria I will use to find the minima: - write each row in the db to a cache - initialize a flag value to false - if the force in the previous row is bigger than the force in the next row, write the new row to the cache (leave the flag as false) - if the force in the previous row is smaller than the force in the next row, write the new row to the cache and mark it as a min cycle (change the flag to true) """ # append data from time column to list time = [] for item in df.index: time.append(df["Time"][item]) # append data from load column to list load = [] for item in df.index: load.append(df["Load"][item]) # create list of tuples for time and load data = [] for i, j in zip(time, load): data.append((i,j)) ############################################################################## # create db model db = [] # create cache store cache = [] load.sort(key=float) # previously key = int totals = [] for count, items in enumerate(load): counter = count + 1 last_object = (counter, load[count], load[(len(load)-1) - count]) totals.append(last_object) our_totals = totals[:47] print(our_totals) combine_data = [] for i in data: for j in our_totals: if i[1] == j[1]: with open("cycleStartEnd.txt", "w") as fp: for item in totals[:47]: fp.write("Cycle: %s" % item[0] + "\n") fp.write("Starting force: %s" % item[1] + "\n") fp.write("Ending force: %s" % item[2] + "\n\n")
Python
0.000294
@@ -2216,16 +2216,17 @@ ls%5B:47%5D%0A +# print(ou @@ -2319,16 +2319,202 @@ = j%5B1%5D:%0A + combine_data.append(i + (%22min%22,))%0A if i%5B1%5D == j%5B2%5D:%0A combine_data.append(i + (%22max%22,))%0A else:%0A combine_data.append(i)%0Aprint(combine_data)%0A
fff56b52afb40ee0a69c9a84b847f7ccc0836bd6
Update some admin list parameters.
greenmine/scrum/admin.py
greenmine/scrum/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from guardian.admin import GuardedModelAdmin from greenmine.scrum import models import reversion class MilestoneInline(admin.TabularInline): model = models.Milestone fields = ('name', 'owner', 'estimated_start', 'estimated_finish', 'closed', 'disponibility', 'order') sortable_field_name = 'order' extra = 0 class UserStoryInline(admin.TabularInline): model = models.UserStory fields = ('subject', 'order') sortable_field_name = 'order' extra = 0 def get_inline_instances(self, request, obj=None): if obj: return obj.user_stories.filter(mileston__isnone=True) else: return models.UserStory.objects.none() class ProjectAdmin(reversion.VersionAdmin): list_display = ["name", "owner"] inlines = [MilestoneInline, UserStoryInline] admin.site.register(models.Project, ProjectAdmin) class MilestoneAdmin(reversion.VersionAdmin): list_display = ["name", "project", "owner", "closed", "estimated_start", "estimated_finish"] admin.site.register(models.Milestone, MilestoneAdmin) class UserStoryAdmin(reversion.VersionAdmin): list_display = ["ref", "milestone", "project", "owner"] admin.site.register(models.UserStory, UserStoryAdmin) class ChangeAdmin(reversion.VersionAdmin): list_display = ["id", "change_type", "project", "owner"] admin.site.register(models.Change, ChangeAdmin) class ChangeAttachmentAdmin(reversion.VersionAdmin): list_display = ["id", "change", "owner"] admin.site.register(models.ChangeAttachment, ChangeAttachmentAdmin) class TaskAdmin(reversion.VersionAdmin): list_display = ["subject", "user_story"] class IssueAdmin(reversion.VersionAdmin): list_display = ["subject", "type"] class SeverityAdmin(admin.ModelAdmin): list_display = ["name", "order", "project"] class PriorityAdmin(admin.ModelAdmin): list_display = ["name", "order", "project"] class PointsAdmin(admin.ModelAdmin): list_display = ["name", "order", "project"] class IssueTypeAdmin(admin.ModelAdmin): list_display = ["name", "order", "project"] class IssueStatusAdmin(admin.ModelAdmin): list_display = ["name", "order", "is_closed", "project"] class TaskStatusAdmin(admin.ModelAdmin): list_display = ["name", "order", "is_closed", "project"] class UserStoryStatusAdmin(admin.ModelAdmin): list_display = ["name", "order", "is_closed", "project"] admin.site.register(models.Task, TaskAdmin) admin.site.register(models.Issue, IssueAdmin) admin.site.register(models.Severity, SeverityAdmin) admin.site.register(models.IssueStatus, IssueStatusAdmin) admin.site.register(models.TaskStatus, TaskStatusAdmin) admin.site.register(models.UserStoryStatus, UserStoryStatusAdmin) admin.site.register(models.Priority, PriorityAdmin) admin.site.register(models.IssueType, IssueTypeAdmin) admin.site.register(models.Points, PointsAdmin)
Python
0
@@ -1217,32 +1217,55 @@ roject%22, %22owner%22 +, 'status', 'is_closed' %5D%0A%0Aadmin.site.re
c36a884b4b3089d507390452d3e6d09654c8a92d
Update API tests
games/tests/test_api.py
games/tests/test_api.py
from django.test import TestCase from django.core.urlresolvers import reverse from . import factories import json class TestOldApi(TestCase): def setUp(self): game = factories.GameFactory games = [game() for i in range(5)] self.library = factories.GameLibraryFactory(games=games) other_games = [game(name="Metroid"), game(name="Mario")] self.other_library = factories.GameLibraryFactory(games=other_games) def test_anonymous_user_cant_get_library(self): response = self.client.get("/api/v1/library/") self.assertEqual(response.status_code, 401) def test_get_library(self): user = self.library.user self.assertTrue(user.api_key) response = self.client.get("/api/v1/library/?username=%s&api_key=%s" % (user.username, user.api_key.key)) self.assertEqual(response.status_code, 200) library_games = json.loads(response.content)["objects"][0]['games'] game_slugs = [game['slug'] for game in library_games] self.assertIn("quake", game_slugs) self.assertNotIn("mario", game_slugs) class TestGameApi(TestCase): def setUp(self): self.num_games = 10 self.games = [] for n in range(self.num_games): self.games.append( factories.GameFactory(name='game_%d' % n, slug='game-%d' % n) ) def test_can_get_games(self): game_list_url = reverse('api_game_list') response = self.client.get(game_list_url) self.assertEqual(response.status_code, 200) games = json.loads(response.content) self.assertEqual(len(games), self.num_games) def test_can_get_subset_of_games(self): game_slugs = {'games': ['game-1', 'game-2', 'game-4']} game_list_url = reverse('api_game_list') response = self.client.get(game_list_url, data=game_slugs, extra={"Content-Type": "application/json"}) self.assertEqual(response.status_code, 200) games = json.loads(response.content) self.assertEqual(len(games), len(game_slugs['games'])) def test_can_post_subset_of_games(self): game_slugs = {'games': ['game-1', 'game-2', 'game-4']} game_list_url = reverse('api_game_list') response = self.client.post( game_list_url, data=json.dumps(game_slugs), content_type='application/json' ) self.assertEqual(response.status_code, 200) games = json.loads(response.content) self.assertEqual(len(games), len(game_slugs['games'])) def test_can_query_game_details(self): response = self.client.get(reverse('api_game_detail', kwargs={'slug': 'game-1'})) self.assertEqual(response.status_code, 200) class TestGameLibraryApi(TestCase): def setUp(self): game = factories.GameFactory games = [game() for i in range(5)] self.library = factories.GameLibraryFactory(games=games) other_games = [game(name="Metroid"), game(name="Mario")] self.other_library = factories.GameLibraryFactory(games=other_games) def test_anonymous_requests_are_rejected(self): user = self.library.user library_url = reverse('api_game_library', kwargs={'username': user.username}) response = self.client.get(library_url) self.assertEqual(response.status_code, 401) def test_can_get_library(self): user = self.library.user self.client.login(username=user.username, password='password') library_url = reverse('api_game_library', kwargs={'username': user.username}) response = self.client.get(library_url) self.assertEqual(response.status_code, 200)
Python
0.000001
@@ -1670,16 +1670,27 @@ en(games +%5B'results'%5D ), self. @@ -1692,32 +1692,32 @@ self.num_games)%0A - %0A def test_ca @@ -2126,32 +2126,43 @@ tEqual(len(games +%5B'results'%5D ), len(game_slug @@ -2580,32 +2580,32 @@ sponse.content)%0A - self.ass @@ -2622,16 +2622,27 @@ en(games +%5B'results'%5D ), len(g
2b00e1de2448b9a80545935354d06950be1ff65f
Add missing path kwarg to update_after_write_time()
beetsplug/importadded.py
beetsplug/importadded.py
# -*- coding: utf-8 -*- """Populate an item's `added` and `mtime` fields by using the file modification time (mtime) of the item's source file before import. Reimported albums and items are skipped. """ from __future__ import division, absolute_import, print_function import os from beets import util from beets import importer from beets.plugins import BeetsPlugin class ImportAddedPlugin(BeetsPlugin): def __init__(self): super(ImportAddedPlugin, self).__init__() self.config.add({ 'preserve_mtimes': False, 'preserve_write_mtimes': False, }) # item.id for new items that were reimported self.reimported_item_ids = None # album.path for old albums that were replaced by a reimported album self.replaced_album_paths = None # item path in the library to the mtime of the source file self.item_mtime = dict() register = self.register_listener register('import_task_created', self.check_config) register('import_task_created', self.record_if_inplace) register('import_task_files', self.record_reimported) register('before_item_moved', self.record_import_mtime) register('item_copied', self.record_import_mtime) register('item_linked', self.record_import_mtime) register('item_hardlinked', self.record_import_mtime) register('album_imported', self.update_album_times) register('item_imported', self.update_item_times) register('after_write', self.update_after_write_time) def check_config(self, task, session): self.config['preserve_mtimes'].get(bool) def reimported_item(self, item): return item.id in self.reimported_item_ids def reimported_album(self, album): return album.path in self.replaced_album_paths def record_if_inplace(self, task, session): if not (session.config['copy'] or session.config['move'] or session.config['link'] or session.config['hardlink']): self._log.debug(u"In place import detected, recording mtimes from " u"source paths") items = [task.item] \ if isinstance(task, importer.SingletonImportTask) \ else task.items for item in items: self.record_import_mtime(item, item.path, item.path) def record_reimported(self, task, session): self.reimported_item_ids = set(item.id for item, replaced_items in task.replaced_items.items() if replaced_items) self.replaced_album_paths = set(task.replaced_albums.keys()) def write_file_mtime(self, path, mtime): """Write the given mtime to the destination path. """ stat = os.stat(util.syspath(path)) os.utime(util.syspath(path), (stat.st_atime, mtime)) def write_item_mtime(self, item, mtime): """Write the given mtime to an item's `mtime` field and to the mtime of the item's file. """ # The file's mtime on disk must be in sync with the item's mtime self.write_file_mtime(util.syspath(item.path), mtime) item.mtime = mtime def record_import_mtime(self, item, source, destination): """Record the file mtime of an item's path before its import. """ mtime = os.stat(util.syspath(source)).st_mtime self.item_mtime[destination] = mtime self._log.debug(u"Recorded mtime {0} for item '{1}' imported from " u"'{2}'", mtime, util.displayable_path(destination), util.displayable_path(source)) def update_album_times(self, lib, album): if self.reimported_album(album): self._log.debug(u"Album '{0}' is reimported, skipping import of " u"added dates for the album and its items.", util.displayable_path(album.path)) return album_mtimes = [] for item in album.items(): mtime = self.item_mtime.pop(item.path, None) if mtime: album_mtimes.append(mtime) if self.config['preserve_mtimes'].get(bool): self.write_item_mtime(item, mtime) item.store() album.added = min(album_mtimes) self._log.debug(u"Import of album '{0}', selected album.added={1} " u"from item file mtimes.", album.album, album.added) album.store() def update_item_times(self, lib, item): if self.reimported_item(item): self._log.debug(u"Item '{0}' is reimported, skipping import of " u"added date.", util.displayable_path(item.path)) return mtime = self.item_mtime.pop(item.path, None) if mtime: item.added = mtime if self.config['preserve_mtimes'].get(bool): self.write_item_mtime(item, mtime) self._log.debug(u"Import of item '{0}', selected item.added={1}", util.displayable_path(item.path), item.added) item.store() def update_after_write_time(self, item): """Update the mtime of the item's file with the item.added value after each write of the item if `preserve_write_mtimes` is enabled. """ if item.added: if self.config['preserve_write_mtimes'].get(bool): self.write_item_mtime(item, item.added) self._log.debug(u"Write of item '{0}', selected item.added={1}", util.displayable_path(item.path), item.added)
Python
0
@@ -5247,32 +5247,38 @@ _time(self, item +, path ):%0A %22%22%22Up
f66a679a1ca8f78a12567a1d8acfe04ca2778ce3
allow removal of genomes and fragments in admin
src/edge/admin.py
src/edge/admin.py
from django.contrib import admin from edge.models import Genome, Fragment class Genome_Admin(admin.ModelAdmin): list_display = ('id', 'name', 'notes', 'parent', 'created_on') search_fields = ('name',) fields = ('name', 'notes', 'active') actions = None def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False def delete_model(self, request, obj): raise Exception("Not allowed") admin.site.register(Genome, Genome_Admin) class Fragment_Admin(admin.ModelAdmin): list_display = ('id', 'name', 'circular', 'parent', 'created_on') search_fields = ('name',) fields = ('name', 'circular', 'active') actions = None def has_add_permission(self, request): return False def has_delete_permission(self, request, obj=None): return False def delete_model(self, request, obj): raise Exception("Not allowed") admin.site.register(Fragment, Fragment_Admin)
Python
0
@@ -334,168 +334,8 @@ se%0A%0A - def has_delete_permission(self, request, obj=None):%0A return False%0A%0A def delete_model(self, request, obj):%0A raise Exception(%22Not allowed%22)%0A%0A admi @@ -647,168 +647,8 @@ se%0A%0A - def has_delete_permission(self, request, obj=None):%0A return False%0A%0A def delete_model(self, request, obj):%0A raise Exception(%22Not allowed%22)%0A%0A admi
ed21e865f346b700c48458f22e3d3f1841f63451
Fix JSON encoder to work with Decimal fields
api/swd6/api/app.py
api/swd6/api/app.py
import flask import flask_cors from sqlalchemy_jsonapi import flaskext as flask_jsonapi import logging from swd6.config import CONF from swd6.db.models import db logging.basicConfig(level=logging.DEBUG) app = flask.Flask(__name__) app.config['DEBUG'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['SQLALCHEMY_DATABASE_URI'] = CONF.db.uri app.config['SERVER_NAME'] = CONF.api.host app.logger.setLevel(logging.DEBUG) flask_cors.CORS(app, origins=CONF.api.cors_hosts) logging.getLogger('flask_cors').level = logging.DEBUG db.init_app(app) api = flask_jsonapi.FlaskJSONAPI(app, db)
Python
0
@@ -561,16 +561,745 @@ p(app)%0A%0A +import json%0Aimport uuid%0Aimport datetime%0Aimport decimal%0A%0Aclass JSONAPIEncoder(json.JSONEncoder):%0A %22%22%22 JSONEncoder Implementation that allows for UUID and datetime %22%22%22%0A%0A def default(self, value):%0A %22%22%22%0A Handle UUID, datetime, decimal, and callables.%0A%0A :param value: Value to encode%0A %22%22%22%0A if isinstance(value, uuid.UUID):%0A return str(value)%0A elif isinstance(value, datetime.datetime):%0A return value.isoformat()%0A elif isinstance(value, decimal.Decimal):%0A return str(value)%0A elif callable(value):%0A return str(value)%0A return json.JSONEncoder.default(self, value)%0A%0Aflask_jsonapi.FlaskJSONAPI.json_encoder = JSONAPIEncoder%0A%0A%0A api = fl
1437018c16c4b2f7197722a65b2bdab0ce59b03b
Use DJANGO_SETTINGS_MODULE from env variable instead of defaulting
appconf/base.py
appconf/base.py
import sys import six from django.core.exceptions import ImproperlyConfigured from .utils import import_attribute class AppConfOptions(object): def __init__(self, meta, prefix=None): self.prefix = prefix self.holder_path = getattr(meta, 'holder', 'django.conf.settings') self.holder = import_attribute(self.holder_path) self.proxy = getattr(meta, 'proxy', False) self.required = getattr(meta, 'required', []) self.configured_data = {} def prefixed_name(self, name): if name.startswith(self.prefix.upper()): return name return "%s_%s" % (self.prefix.upper(), name.upper()) def contribute_to_class(self, cls, name): cls._meta = self self.names = {} self.defaults = {} class AppConfMetaClass(type): def __new__(cls, name, bases, attrs): super_new = super(AppConfMetaClass, cls).__new__ parents = [b for b in bases if isinstance(b, AppConfMetaClass)] if not parents: return super_new(cls, name, bases, attrs) # Create the class. module = attrs.pop('__module__') new_class = super_new(cls, name, bases, {'__module__': module}) attr_meta = attrs.pop('Meta', None) if attr_meta: meta = attr_meta else: attr_meta = type('Meta', (object,), {}) meta = getattr(new_class, 'Meta', None) prefix = getattr(meta, 'prefix', getattr(meta, 'app_label', None)) if prefix is None: # Figure out the prefix by looking one level up. # For 'django.contrib.sites.models', this would be 'sites'. model_module = sys.modules[new_class.__module__] prefix = model_module.__name__.split('.')[-2] new_class.add_to_class('_meta', AppConfOptions(meta, prefix)) new_class.add_to_class('Meta', attr_meta) for parent in parents[::-1]: if hasattr(parent, '_meta'): new_class._meta.names.update(parent._meta.names) new_class._meta.defaults.update(parent._meta.defaults) new_class._meta.configured_data.update( parent._meta.configured_data) for name in filter(str.isupper, list(attrs.keys())): prefixed_name = new_class._meta.prefixed_name(name) new_class._meta.names[name] = prefixed_name new_class._meta.defaults[prefixed_name] = attrs.pop(name) # Add all attributes to the class. for name, value in attrs.items(): new_class.add_to_class(name, value) new_class._configure() for name, value in six.iteritems(new_class._meta.configured_data): prefixed_name = new_class._meta.prefixed_name(name) setattr(new_class._meta.holder, prefixed_name, value) new_class.add_to_class(name, value) # Confirm presence of required settings. for name in new_class._meta.required: prefixed_name = new_class._meta.prefixed_name(name) if not hasattr(new_class._meta.holder, prefixed_name): raise ImproperlyConfigured('The required setting %s is' ' missing.' % prefixed_name) return new_class def add_to_class(cls, name, value): if hasattr(value, 'contribute_to_class'): value.contribute_to_class(cls, name) else: setattr(cls, name, value) def _configure(cls): # the ad-hoc settings class instance used to configure each value obj = cls() for name, prefixed_name in six.iteritems(obj._meta.names): default_value = obj._meta.defaults.get(prefixed_name) value = getattr(obj._meta.holder, prefixed_name, default_value) callback = getattr(obj, "configure_%s" % name.lower(), None) if callable(callback): value = callback(value) cls._meta.configured_data[name] = value cls._meta.configured_data = obj.configure() class AppConf(six.with_metaclass(AppConfMetaClass)): """ An app setting object to be used for handling app setting defaults gracefully and providing a nice API for them. """ def __init__(self, **kwargs): for name, value in six.iteritems(kwargs): setattr(self, name, value) def __dir__(self): return sorted(list(set(self._meta.names.keys()))) # For instance access.. @property def configured_data(self): return self._meta.configured_data # For Python < 2.6: @property def __members__(self): return self.__dir__() def __getattr__(self, name): if self._meta.proxy: return getattr(self._meta.holder, name) raise AttributeError("%s not found. Use '%s' instead." % (name, self._meta.holder_path)) def __setattr__(self, name, value): if name == name.upper(): setattr(self._meta.holder, self._meta.prefixed_name(name), value) object.__setattr__(self, name, value) def configure(self): """ Hook for doing any extra configuration, returning a dictionary containing the configured data. """ return self.configured_data
Python
0
@@ -17,16 +17,27 @@ rt six%0A%0A +import os%0A%0A from dja @@ -281,30 +281,44 @@ r', -'django.conf.settings' +os.environ%5B'DJANGO_SETTINGS_MODULE'%5D )%0A
efe79ebfa2b023e6971244b7f3c803a09dd6d2c7
change check to skipp
tools/pcdo.py
tools/pcdo.py
import glob from joblib import Parallel, delayed import os import click def cdo_comand(ifile, opath, command, ext, checko): if opath != 'no': ofile = os.path.join(opath, '{}_tm.nc'.format(os.path.basename(ifile)[:-3])) else: ofile = ' ' if checko: if os.path.isfile(ofile): print('File {} exist, --checko flag is present, skipping'.format(ofile)) return print('cdo {} {} {}'.format(command, ifile, ofile)) os.system('cdo {} {} {}'.format(command, ifile, ofile)) @click.command() @click.argument('ipath', nargs=-1, type=click.Path(exists=True), required=True) @click.argument('opath', nargs=1, required=False, default='no') @click.option('--ncore', '-n', default=2, help = 'Number of cores (parallel processes)', show_default=True) @click.option('--cdo', required=True, help = 'String of cdo commands !!!IN QUOTATION MARKS!!!, eg \" monmean -shifttime,-12hour \"') @click.option('--ext','-e', default='tm', required=False,show_default=True, help='Extention to be used for the output file.') @click.option('--checko', '-c', is_flag=True, help='Skip the calculation if the output file already exist.') def pcdo(ipath, opath, ncore, cdo, ext, checko): ''' ipath - Input files, must be the path with wildcards (e.g. /path/to/files/temp_fesom_193[3-7]????.nc) opath - Path where the output will be stored or "no" for operators that do not require output file. ''' Parallel(n_jobs=ncore)(delayed(cdo_comand)(l, opath, cdo, ext, checko) for l in ipath) if __name__ == '__main__': pcdo()
Python
0
@@ -78,16 +78,17 @@ cdo_com +m and(ifil @@ -107,30 +107,28 @@ mmand, ext, -checko +skip ):%0A if op @@ -180,18 +180,18 @@ th, '%7B%7D_ -tm +%7B%7D .nc'.for @@ -222,16 +222,21 @@ le)%5B:-3%5D +, ext ))%0A e @@ -268,22 +268,20 @@ %0A if -checko +skip :%0A @@ -821,16 +821,21 @@ '--cdo', +'-c', require @@ -854,30 +854,31 @@ = ' -String of cdo commands +CDO command as a string !!! @@ -1099,20 +1099,18 @@ ('-- -checko +skip ', '- -c +s ', i @@ -1121,17 +1121,16 @@ ag=True, - %0A @@ -1243,24 +1243,287 @@ xt, -checko):%0A ''' +skip):%0A '''%0A Runs several (-n) cdo processes in paralel. Input (ipath) is a list (wildcard) of files. The cdo command (-c) is%0A executed for every file and the output files with extention (-e) will be written to the output path (opath).%0A%0A Example:%0A%0A python pcdo.py%0A %0A @@ -1780,16 +1780,17 @@ (cdo_com +m and)(l, @@ -1806,22 +1806,20 @@ o, ext, -checko +skip ) for l
ad1d33f1a4051a3440c60e4a8a655f167fcee1b6
Rewrite result handling
src/result.py
src/result.py
""" The MIT License (MIT) Copyright (c) 2017 Stefan Graupner Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import json from colorama import Fore, Style class Result(object): """ Validator result object """ class Mode(object): """ Output mode """ Human = 0 Json = 1 class Verbosity(object): """ Result.Verbosity simultaneously describes the verbosity of the output """ Default = 0 Info = 1 Warning = 2 Error = 3 Debug = 4 class Severity(object): """ Severity of messages - This is quite similar to the output verbosity except that there is no default. """ Debug = 0 Info = 1 Warning = 2 Error = 3 silent = False mode = Mode.Human verbosity = Verbosity.Default def __init__(self, mode=Mode.Human, silent=False, verbosity=Verbosity.Default): self.mode = mode self.silent = silent self.verbosity = verbosity def add_message(self, severity, text, context): def process_message(self, type, message, *args): if self.silent: return if type == Result.Verbosity.Default: type = Result.Verbosity.Error message = message.format(*args) if self.mode == Result.Mode.Human: self._print_human(type, message) if self.mode == Result.Mode.Json: self._print_json(type, message) def _print_human(self, type, message): color = Fore.WHITE if type == "ok": color = Fore.GREEN if type == "warn": color = Fore.YELLOW if type == "err": color = Fore.RED print("{}[{}] {}{}".format(color, type.center(4).upper(), message, Style.RESET_ALL)) def _print_json(self, type, message): data = { "type": type, "message": message } print(json.dumps(data))
Python
0.000009
@@ -2051,16 +2051,17 @@ , text, +* context) @@ -2074,228 +2074,116 @@ -%0A%0A def process_message(self, type, message, *args):%0A if self.silent:%0A return%0A%0A if type == Result.Verbosity.Default:%0A type = Result.Verbosity.Error%0A%0A message = message +if self.silent:%0A return%0A%0A if context and len(context) %3E 0:%0A text = text .format( *arg @@ -2182,13 +2182,15 @@ mat( -*args +context )%0A%0A @@ -2224,20 +2224,19 @@ lt.Mode. -Huma +Jso n:%0A @@ -2246,340 +2246,493 @@ -self._print_human(type, message)%0A%0A if self.mode == Result.Mode.Json:%0A self._ +data = %7B%0A %22severity%22: self.format_severity(severity),%0A %22text%22: text,%0A %22context%22: context%0A %7D%0A%0A print -_ +( json -(type, message)%0A%0A def _print_human(self, type, message):%0A color = Fore.WHITE%0A if type == %22ok%22:%0A color = Fore.GREEN%0A if type == %22warn%22:%0A color = Fore.YELLOW%0A if type == %22err%22:%0A +.dumps(data))%0A%0A if self.mode == Result.Mode.Human:%0A color = Fore.WHITE%0A if severity == Result.Severity.Info:%0A color = Fore.GREEN%0A if severity == Result.Severity.Warning:%0A color = Fore.YELLOW%0A if severity == Result.Severity.Error:%0A @@ -2731,32 +2731,33 @@ %0A + color = Fore.RED @@ -2758,16 +2758,20 @@ re.RED%0A%0A + @@ -2808,20 +2808,46 @@ or, -type +self.format_severity(severity) .center( 4).u @@ -2842,17 +2842,17 @@ .center( -4 +8 ).upper( @@ -2854,23 +2854,20 @@ pper(), -message +text , Style. @@ -2891,155 +2891,740 @@ def -_print_json(self, type, message):%0A data = %7B%0A %22type%22: type,%0A %22message%22: message +format_severity(self, severity):%0A if severity == Result.Severity.Debug:%0A return %22Debug%22%0A if severity == Result.Severity.Info:%0A return %22Info%22%0A if severity == Result.Severity.Warning:%0A return %22Warning%22%0A if severity == Result.Severity.Error:%0A return %22Error%22%0A%0A def debug(self, text, *context):%0A self.add_message(Result.Severity.Debug, text, context) %0A +%0A -%7D%0A%0A print(json.dumps(data))%0A +def info(self, text, *context):%0A self.add_message(Result.Severity.Info, text, context)%0A%0A def warning(self, text, *context):%0A self.add_message(Result.Severity.Warning, text, context)%0A%0A def error(self, text, *context):%0A self.add_message(Result.Severity.Error, text, context)
c89ce3e5d9f5745262f547bf53772d55fcf1db4b
Clean up the code path for Just Visiting clients
init.py
init.py
import os import os.path import sys import cgi import cStringIO import hashlib import base64 # Observed that we don't seem to have a sane umask, URL files are # coming out with mode 666, kinda unexpected. os.umask(022) # Get config from the environment URL_STEM = os.environ.get('URL_STEM') URL_STORE = os.environ.get('URL_STORE') URL_ENTRY_FORM = """ <form method="get"> <label for="url">URL to shorten</label> <input type="text" name="new_url" size="60" id="url" accesskey="u" /> <input type="submit" value="Shorten!" accesskey="s" /> </form> """ class http_response(object): def __init__(self, environ, start_response): self.buffer = cStringIO.StringIO() self.environ = environ self.start_response = start_response self.status = '200 OK' self.headers = [('Content-Type', 'text/html; charset=utf-8'), ('P3P', '''policyref="/w3c/p3p.xml", CP="NOI NOR CURa OUR"''')] def write(self, data): self.buffer.write(data) def finalise(self): """ Closes the output buffer, writes the correct header/s and returns something suitable for returning from the top-level application() call """ self.value = self.buffer.getvalue() self.buffer.close() self.headers.append(('Content-Length', str(len(self.value)))) self.start_response(self.status, self.headers) return [self.value] def redirect(self, url): self.buffer.close() self.status = '302 Found' self.headers = [('Content-Type', 'text/html'), ('Location', url)] self.start_response(self.status, self.headers) return ['redirecting'] def boom(self, msg): self.status = '500 Server side error' print >>self.buffer, "Critical error, HTTP status 500" print >>self.buffer, str(msg) return self.finalise() class hash_machine(object): class NoMoreRotationException(Exception): pass def __init__(self, raw_data): self.full_hash = base64.b32encode(hashlib.sha1(raw_data).digest()) self.hash_len = len(self.full_hash) self.rotation_counter = 0 def get_hash(self): if self.rotation_counter < self.hash_len: mini_hash = (self.full_hash[self.rotation_counter:] + self.full_hash[:self.rotation_counter])[:6] self.rotation_counter += 1 return mini_hash else: raise self.NoMoreRotationException def application(environ, start_response): if URL_STORE is None: return output.boom("The URL_STORE environment variable is not set, cannot run.") # Setup our output output = http_response(environ, start_response) sys.stdout = output wsgi_errors = environ['wsgi.errors'] # Get all our form input form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ) SHORT = str(form.getfirst("short", '')) NEW = str(form.getfirst("new_url", '')) if SHORT: URL_FILE = os.path.join(URL_STORE, SHORT) URL = '' if os.path.exists(URL_FILE): f = open(URL_FILE) URL = f.readlines() f.close() if len(URL) < 1: return output.boom("URL file %s doesn't seem to have a URL in it!" % URL_FILE) return output.redirect(URL[0]) else: return output.boom("URL file %s doesn't exist" % URL_FILE) elif NEW: print '''Your URL is <a href="%s">%s</a><br />''' % (NEW, NEW) hasher = hash_machine(NEW) while True: try: h = hasher.get_hash() except NoMoreRotationException: return output.boom("Damn, couldn't get a hash for that URL for some reason") print "<p>Mini hash is %s</p>" % h URL_FILE = os.path.join(URL_STORE, h) if not os.path.exists(URL_FILE): print "<p>%s doesn't exist yet, great!</p>" % URL_FILE f = open(URL_FILE, 'w') f.write(NEW) f.close() URL = URL_STEM + h print "<p>Okay, here's your URL:</p>" print '''<p><a href="%s">%s</a></p>''' % (URL, URL) print '''<p>%s</p>''' % URL print "<hr /><p>Shorten again?<br />" + URL_ENTRY_FORM + "</p>" return output.finalise() else: print "<p>Hmm, that one already exists, let's see if it's the same</p>" f = open(URL_FILE) URL = f.readlines() f.close() if len(URL) < 1: print "<p>URL file %s doesn't seem to have a URL in it, we should use it</p>" % URL_FILE f = open(URL_FILE, 'w') f.write(NEW) f.close() URL = URL_STEM + h print "<p>Okay, here's your URL:</p>" print '''<p><a href="%s">%s</a></p>''' % (URL, URL) print '''<p>%s</p>''' % URL print "<hr /><p>Shorten again?<br />" + URL_ENTRY_FORM + "</p>" return output.finalise() CURRENT_URL = URL[0] if CURRENT_URL == NEW: URL = URL_STEM + h print "<p>Okay, no problem here's your URL:</p>" print '''<p><a href="%s">%s</a></p>''' % (URL, URL) print '''<p>%s</p>''' % URL print "<hr /><p>Shorten again?<br />" + URL_ENTRY_FORM + "</p>" return output.finalise() print "<p>Damn, a collision, let's try again...</p>" return output.finalise() else: print """<p> <center> <img src="/static/poliwag.jpg" width="260" height="240" /><br /> Sorry, nothing to see here<br /> <hr />""" + URL_ENTRY_FORM + """ </center> <div style="color: silver;"> <small><pre>javascript:var%20u='http://lzma.so/?new_url='+encodeURIComponent(document.location.href);a=function(){if(!window.open(u))document.location.href=u;};if(/Firefox/.test(navigator.userAgent))setTimeout(a,0);else%20a();void(0);</pre></small> </div> </p>""" URL_DIR = URL_FILE = URL_STORE print "<ul>" for FILE in os.listdir(URL_DIR): print '''<li><a href="%s">%s</a></li>''' % (FILE, FILE) print "</ul>" return output.finalise() from paste.exceptions.errormiddleware import ErrorMiddleware application = ErrorMiddleware(application, debug=True)
Python
0
@@ -5719,16 +5719,69 @@ %3C/p%3E%22%0A%0A%0A + # Should never get here? Probably proveable.%0A @@ -6385,16 +6385,116 @@ /p%3E%22%22%22%0A%0A + # Dead code, we don't want to enumerate all the short URLs%0A return output.finalise()%0A
f77276f74b2a34aa9b1579940ad3d44dc0b60613
Fix hardcoded maxixum values for layer dimensions
gerberlicious/render.py
gerberlicious/render.py
from .drawable import PointList, ApertureFlash from .aperture import CircleAperture class SVGRenderer: """ SVG Renderer for Layer objects """ def __init__(self, layer): self.layer = layer self.setup_canvas() def setup_canvas(self): self.min_x = 10000 # FIXME self.min_y = 10000 # FIXME self.max_x = 0 self.max_y = 0 self.vertical_padding = 50 self.horizontal_padding = 50 self.scale = 100 for shape in self.layer.shapes: if isinstance(shape, PointList): for point in shape.points: if point.x < self.min_x: self.min_x = point.x if point.x > self.max_x: self.max_x = point.x if point.y < self.min_y: self.min_y = point.y if point.y > self.max_y: self.max_y = point.y elif isinstance(shape, ApertureFlash): if shape.point.x < self.min_x: self.min_x = shape.point.x if shape.point.x > self.max_x: self.max_x = shape.point.x if shape.point.y < self.min_y: self.min_y = shape.point.y if shape.point.y > self.max_x: self.max_x = shape.point.y else: raise NotImplementedError self.min_x = self.min_x * self.scale self.min_y = self.min_y * self.scale self.max_x = self.max_x * self.scale self.max_y = self.max_y * self.scale def _render_point_list(self, shape): res = "<path d=\"" res += "M %i %i " % ( \ self.horizontal_padding + shape.points[0].x * self.scale, \ self.vertical_padding + shape.points[0].y * self.scale) for i in range(1, len(shape.points)-1): res += "L %i %i " % ( \ self.horizontal_padding + shape.points[i].x * self.scale, \ self.vertical_padding + shape.points[i].y * self.scale) res += "Z\" fill=\"transparent\" stroke=\"black\" " if isinstance(shape.aperture, CircleAperture): res += "stroke-linecap=\"round\" stroke-linejoin=\"round\" " res += "stroke-width=\"%i\" " % (shape.aperture.radius * self.scale) else: raise NotImplementedError res += "/>" return res def _render_aperture_flash(self, shape): res = "" if shape.aperture.hole_radius > 0: res = "<circle cx=\"%i\" cy=\"%i\" r=\"%i\" stroke-width=\"%i\" stroke=\"black\" fill=\"white\" />" % ( \ self.horizontal_padding + shape.point.x * self.scale, \ self.vertical_padding + shape.point.y * self.scale, \ shape.aperture.radius * self.scale / 2, \ (shape.aperture.radius - shape.aperture.hole_radius) * self.scale) else: res = "<circle cx=\"%i\" cy=\"%i\" r=\"%i\" fill=\"black\" />" % ( \ self.horizontal_padding + shape.point.x * self.scale, \ self.vertical_padding + shape.point.y * self.scale, \ shape.aperture.radius * self.scale / 2) return res def render(self): res = ( "<svg version=\"1.1\"\n" + \ " baseProfile=\"full\"\n" + \ " width=\"%i\" height=\"%i\"\n" + \ " xmlns=\"http://www.w3.org/2000/svg\">\n") % \ (self.max_x + 2*self.horizontal_padding, self.max_y + 2*self.vertical_padding) for shape in self.layer.shapes: if isinstance(shape, PointList): res += self._render_point_list(shape) elif isinstance(shape, ApertureFlash): res += self._render_aperture_flash(shape) else: raise NotImplementedError res += "</svg>" return res def write_file(self, filename): with open(filename, "w") as f: f.write(self.render()) class GerberRenderer: """ Gerber file Renderer for Layer objects """ def __init__(self, layer): self.layer = layer self.setup_canvas() def setup_canvas(self): pass def _render_number(self, n): res = "" if n == 0: return "0" if n < 0: res += "-" if n >= 1: res += str(int(n)) res += ("%.*f" % (self.layer.decimal_positions, n - int(n)))[2:] return res def _render_point(self, point): res = "X" + self._render_number(point.x) + \ "Y" + self._render_number(point.y) return res def _render_point_list(self, shape): res = "" # select aperture res += "D" + shape.aperture.aperture_identifier + "*\n" # render the start of the shape res += self._render_point(shape.points[0]) + \ "D02*\n" # render the rest of the shape for i in range(1, len(shape.points)): res += self._render_point(shape.points[i]) + \ "D01*\n" return res def _render_aperture_flash(self, shape): res = "" # select aperture res += "D" + shape.aperture.aperture_identifier + "*\n" # render the aperture flash; res += self._render_point(shape.point) + \ "D03*\n" return res def _render_aperture_definition(self, aperture): if isinstance(aperture, CircleAperture): res = "%ADD" + aperture.aperture_identifier res += "C,%f" % aperture.radius if aperture.hole_radius > 0: res += "X%f" % aperture.hole_radius res += "*%\n" return res else: raise NotImplementedError def render(self): res = "" # Format Specification res += "%FSLA" + \ "X" + str(self.layer.integer_positions) + str(self.layer.decimal_positions) + \ "Y" + str(self.layer.integer_positions) + str(self.layer.decimal_positions) + \ "*%\n" # Unit res += "%MO" + \ self.layer.unit + \ "*%\n" # render apertures for aperture in self.layer.apertures: res += self._render_aperture_definition(aperture) # render shapes for shape in self.layer.shapes: if isinstance(shape, PointList): res += self._render_point_list(shape) elif isinstance(shape, ApertureFlash): res += self._render_aperture_flash(shape) else: raise NotImplementedError # End of file res += "M02*" return res def write_file(self, filename): with open(filename, "w") as f: f.write(self.render())
Python
0.000001
@@ -1,12 +1,24 @@ +%0Aimport math %0Afrom .drawa @@ -298,31 +298,24 @@ min_x = -10000 # FIXME +math.inf %0A @@ -332,23 +332,16 @@ y = -10000 # FIXME +math.inf %0A
eb368c11b7d0e481c6539130c34cb0b04c8f57a6
add prompt number
tpl/prompt.py
tpl/prompt.py
# -*- coding:utf-8 -*- import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) import prompt_toolkit from prompt_toolkit.history import FileHistory from prompt_toolkit.completion import Completion, Completer from tpl import path class WordMatchType(object): CONTAINS = 'CONTAINES' STARTSWITH = 'STARTSWITH' class WordCompleter(Completer): def __init__(self, words=None, history=None, match_type=WordMatchType.CONTAINS): self.words = words or [] self.history = history or [] self.match_type = match_type def match(self, word_before_cursor, word): if self.match_type == WordMatchType.CONTAINS: return word_before_cursor in word # TODO ้œ€่ฆๅšไธ€ไธ‹ๅŽป้‡๏ผŒ้ฟๅ… words ๅ’Œ history yield ไบ†็›ธๅŒ็š„ completions def get_completions(self, document, complete_event): word_before_cursor = document.text_before_cursor.lower() for word in self.words: if self.match(word_before_cursor, word): display_meta = ' custom' yield Completion(word, -len(word_before_cursor), display_meta=display_meta) for record in self.history: if self.match(word_before_cursor, record): display_meta = ' history' yield Completion(record, -len(word_before_cursor), display_meta=display_meta) history = FileHistory(os.path.join(path.HOME, '.templates', 'tpl.history')) def prompt_str(message, default=None, multiline=False): completer = WordCompleter(words=[], history=history) res = prompt_toolkit.prompt(message, default=default or '', history=history, completer=completer, multiline=multiline) return str(res) def prompt_path(): pass
Python
0.000007
@@ -1689,16 +1689,159 @@ (res)%0A%0A%0A +def prompt_number(message, default=None):%0A res = prompt_toolkit.prompt(message, default=default or '', history=history)%0A return int(res)%0A %0A%0A%0A%0A%0Adef
fc301544022c00403cc9ba86c8be7dbe3eee3e47
Fix formatting
benchbuild/source/git.py
benchbuild/source/git.py
""" Declare a git source. """ import typing as tp import attr import plumbum as pb from plumbum import local from benchbuild.utils.cmd import git, mkdir from benchbuild.utils.path import flocked from . import base Command = pb.commands.base.BaseCommand VarRemotes = tp.Union[str, tp.Dict[str, str]] Remotes = tp.Dict[str, str] @attr.s class Git(base.BaseSource): """ Fetch the downloadable source via git. """ clone: bool = attr.ib(default=True) limit: tp.Optional[int] = attr.ib(default=10) refspec: str = attr.ib(default='HEAD') shallow: bool = attr.ib(default=True) version_filter: tp.Callable[[str], bool] = attr.ib(default=lambda version: True) @property def default(self) -> base.Variant: """ Return current HEAD as default version for this Git project. """ return self.versions()[0] def fetch(self) -> pb.LocalPath: """ Clone the repository, if needed. This will create a git clone inside the global cache directory. Args: version (Optional[str], optional): [description]. Defaults to None. Returns: str: [description] """ prefix = base.target_prefix() clone = maybe_shallow(git['clone'], self.shallow) cache_path = local.path(prefix) / self.local if clone_needed(self.remote, cache_path): clone(self.remote, cache_path) return cache_path def version(self, target_dir: str, version: str = 'HEAD') -> pb.LocalPath: """ Create a new git worktree pointing to the requested version. Args: target_dir (str): The filesystem path where the new worktree should live. version (str): The desired version the new worktree needs to point to. Defaults to 'HEAD'. Returns: str: [description] """ src_loc = self.fetch() tgt_loc = local.path(target_dir) / self.local lock_file = local.path(target_dir) / self.local + '.lock' worktree = git['worktree'] with local.cwd(src_loc): mkdir('-p', tgt_loc) with flocked(lock_file): worktree('prune') worktree('add', '--detach', tgt_loc, version) return tgt_loc def versions(self) -> tp.List[base.Variant]: cache_path = self.fetch() git_rev_list = git['rev-list', '--abbrev-commit', '--abbrev=10'] rev_list: tp.List[str] = [] with local.cwd(cache_path): rev_list = list(git_rev_list(self.refspec).strip().split('\n')) rev_list = list(filter(self.version_filter, rev_list)) rev_list = rev_list[:self.limit] if self.limit else rev_list revs = [base.Variant(version=rev, owner=self) for rev in rev_list] return revs def maybe_shallow(cmd: Command, enable: bool) -> Command: """ Conditionally add the shallow clone to the given git command. Args: cmd (Any): A git clone command (shallow doesn't make sense anywhere else. shallow (bool): Should we add the shallow options? Returns: Any: A new git clone command, with shallow clone enabled, if selected. """ if enable: return cmd['--depth', '1'] return cmd def clone_needed(repository: VarRemotes, repo_loc: str) -> bool: from benchbuild.utils.download import __clone_needed__ if not isinstance(repository, str): raise TypeError('\'remote\' needs to be a git repo string') return __clone_needed__(repository, repo_loc)
Python
0
@@ -635,16 +635,48 @@ e%5B%5Bstr%5D, +%0A bool%5D =
ee2a385d407ae9f3b5f24897319431c3f0091f78
fix categorize
benchmarks/aggregates.py
benchmarks/aggregates.py
import vaex from benchmarks.fixtures import generate_numerical class Aggregates: pretty_name = "Performance of aggregates: stats, binby etc" version = "1" params = ([10**7, 5*10**7, 10**8],) param_names = ['N'] def setup_cache(self): # ensure the dataframe is generated generate_numerical() def setup(self, N): self.df = vaex.open(generate_numerical())[:N] self.df.categorize(self.df.i8_10, min_value=5, max_value=15) self.df.categorize(self.df.i4_10, min_value=5, max_value=15) self.df.categorize(self.df.i2_10, min_value=5, max_value=15) self.df.categorize(self.df.i1_10, min_value=5, max_value=15) self.df.categorize(self.df.i8_1K, min_value=5, max_value=1_000+5) self.df.categorize(self.df.i4_1K, min_value=5, max_value=1_000+5) self.df.categorize(self.df.i2_1K, min_value=5, max_value=1_000+5) self.df.categorize(self.df.i1_1K, min_value=5, max_value=1_000+5) self.df.categorize(self.df.i8_1M, min_value=5, max_value=1_000_000+5) self.df.categorize(self.df.i4_1M, min_value=5, max_value=1_000_000+5) self.df.categorize(self.df.i2_1M, min_value=5, max_value=1_000_000+5) self.df.categorize(self.df.i1_1M, min_value=5, max_value=1_000_000+5) class Stats(Aggregates): def time_count_star(self, N): self.df.count() def time_mean_x(self, N): self.df.x.mean() def time_mean_x4(self, N): self.df.x4.mean() class BinByCat10(Aggregates): params = Aggregates.params + ([1, 2, 4, 8],) param_names = ['N', 'B'] def setup(self, N, B): super().setup(N) def time_binby_iB_10(self, N, B): self.df.count(binby=f'i{B}_10') class BinByCat1K(Aggregates): params = Aggregates.params + ([2, 4, 8],) param_names = ['N', 'B'] def setup(self, N, B): super().setup(N) def time_binby_iB_1K(self, N, B): self.df.count(binby=f'i{B}_1K') class BinByCat1M(Aggregates): params = Aggregates.params + ([4, 8],) param_names = ['N', 'B'] def setup(self, N, B): super().setup(N) def time_binby_iB_1M(self, N, B): self.df.count(binby=f'i{B}_1M') class GroupByCat10(Aggregates): params = Aggregates.params + ([1, 2, 4, 8],) param_names = ['N', 'B'] def setup(self, N, B): super().setup(N) def time_binby_iB_10(self, N, B): self.df.groupby(f'i{B}_10', agg='count') class GroupByCat1K(Aggregates): params = Aggregates.params + ([2, 4, 8],) param_names = ['N', 'B'] def setup(self, N, B): super().setup(N) def time_binby_iB_1M(self, N, B): self.df.groupby(f'i{B}_1k', agg='count') class GroupByCat1M(Aggregates): params = Aggregates.params + ([4, 8],) param_names = ['N', 'B'] def setup(self, N, B): super().setup(N) def time_binby_iB_1K(self, N, B): self.df.groupby(f'i{B}_1M', agg='count') class BinBy1d(Aggregates): def time_count_star(self, N): self.df.count() def time_count_star_binby128(self, N): self.df.count(binby='x', limits=[-1, 1], shape=128) def time_count_x_binby128(self, N): self.df.count('x', binby='x', limits=[-1, 1], shape=128) class BinBy2d(Aggregates): def time_count_star(self, N): self.df.count(binby=[self.df.x, self.df.y], limits=[-1, -1], shape=128) def time_count_star_x4(self, N): self.df.count(binby=[self.df.x4, self.df.y4], limits=[-1, -1], shape=128)
Python
0.998737
@@ -463,32 +463,46 @@ =5, max_value=15 +, inplace=True )%0A self.d @@ -546,32 +546,46 @@ =5, max_value=15 +, inplace=True )%0A self.d @@ -637,16 +637,30 @@ value=15 +, inplace=True )%0A @@ -720,16 +720,30 @@ value=15 +, inplace=True )%0A%0A @@ -801,32 +801,46 @@ ax_value=1_000+5 +, inplace=True )%0A self.d @@ -889,32 +889,46 @@ ax_value=1_000+5 +, inplace=True )%0A self.d @@ -981,24 +981,38 @@ alue=1_000+5 +, inplace=True )%0A se @@ -1000,32 +1000,34 @@ ce=True)%0A + # self.df.categor @@ -1146,32 +1146,46 @@ alue=1_000_000+5 +, inplace=True )%0A self.d @@ -1238,32 +1238,46 @@ alue=1_000_000+5 +, inplace=True )%0A self.d @@ -1261,32 +1261,34 @@ ce=True)%0A + # self.df.categor @@ -1341,32 +1341,34 @@ 0_000+5)%0A + # self.df.categor
7652ab7388d181f09087bbc69a23fc00452d5309
update params
app/engine/vgg16.py
app/engine/vgg16.py
# -*- coding: utf-8 -*- import operator import functools import numpy as np import tensorflow as tf from app.main import EVAL from app.models.cnn import ConvolutionalNeuralNet from app.settings import IMAGE_PATH, IMAGE_SHAPE, MODEL_PATH, MAX_STEPS, ALPHA from app.pipeline import data_pipe, generate_data_skeleton from app.controllers import generate_validation_set, train, save_session, predict, \ submit, restore_session sess = tf.Session() cnn = ConvolutionalNeuralNet(shape=(None, IMAGE_SHAPE[2], functools.reduce(operator.mul, IMAGE_SHAPE[:2], 1))) x, _y = cnn.x, cnn._y keep_prob = tf.placeholder(tf.float32) # (90, 160, 3) conv_layer_1 = cnn.add_conv_layer(x, [[3, 3, 3, 64], [64]], func='relu') conv_layer_2 = cnn.add_conv_layer(conv_layer_1, [[3, 3, 64, 64], [64]], func='relu') max_pool_1 = cnn.add_pooling_layer(conv_layer_2) # (45, 80, *) conv_layer_3 = cnn.add_conv_layer(max_pool_1, [[3, 3, 64, 128], [128]], func='relu') conv_layer_4 = cnn.add_conv_layer(conv_layer_3, [[3, 3, 128, 128], [128]], func='relu') max_pool_2 = cnn.add_pooling_layer(conv_layer_4) # (23, 40, *) conv_layer_5 = cnn.add_conv_layer(max_pool_2, [[3, 3, 128, 256], [256]], func='relu') conv_layer_6 = cnn.add_conv_layer(conv_layer_5, [[3, 3, 256, 256], [256]], func='relu') conv_layer_7 = cnn.add_conv_layer(conv_layer_6, [[3, 3, 256, 256], [256]], func='relu') max_pool_3 = cnn.add_pooling_layer(conv_layer_7) # (12, 20, *) conv_layer_8 = cnn.add_conv_layer(max_pool_3, [[3, 3, 256, 512], [512]], func='relu') conv_layer_9 = cnn.add_conv_layer(conv_layer_8, [[3, 3, 512, 512], [512]], func='relu') conv_layer_10 = cnn.add_conv_layer(conv_layer_9, [[3, 3, 512, 512], [512]], func='relu') max_pool_4 = cnn.add_pooling_layer(conv_layer_10) # (6, 10, *) conv_layer_11 = cnn.add_conv_layer(max_pool_4, [[3, 3, 512, 512], [512]], func='relu') conv_layer_12 = cnn.add_conv_layer(conv_layer_11, [[3, 3, 512, 512], [512]], func='relu') conv_layer_13 = cnn.add_conv_layer(conv_layer_12, [[3, 3, 512, 512], [512]], func='relu') max_pool_4 = cnn.add_pooling_layer(conv_layer_13) # (3, 5, *) fully_connected_layer_1 = cnn.add_dense_layer( max_pool_4, [[3 * 5 * 512, 4096], [4096], [-1, 3 * 5 * 512]], func='relu' ) drop_out_layer_1 = cnn.add_drop_out_layer(fully_connected_layer_1, keep_prob) fully_connected_layer_2 = cnn.add_dense_layer( drop_out_layer_1, [[4096, 1000], [1000], [-1, 4096]], func='relu' ) # (1, 4096) drop_out_layer_2 = cnn.add_drop_out_layer(fully_connected_layer_2, keep_prob) # (1, 4096) logits = cnn.add_read_out_layer(drop_out_layer_2, [[1000, 8], [8]]) # train cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=_y) loss = tf.reduce_mean(cross_entropy) train_step = tf.train.RMSPropOptimizer(learning_rate=ALPHA).minimize(loss) # eval correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(_y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # prepare data feed train_file_array, train_label_array, valid_file_array, valid_label_array = \ generate_data_skeleton(root_dir=IMAGE_PATH + 'train', valid_size=.2) train_image_batch, train_label_batch = \ data_pipe(train_file_array, train_label_array, num_epochs=None, shuffle=True) valid_image_batch, valid_label_batch = \ data_pipe(valid_file_array, valid_label_array, num_epochs=1, shuffle=False) test_file_array, _ = \ generate_data_skeleton(root_dir=IMAGE_PATH + 'test_stg1', valid_size=None) test_image_batch, _ = \ data_pipe(test_file_array, _, num_epochs=1, shuffle=False) init_op = tf.group( tf.local_variables_initializer(), tf.global_variables_initializer() ) sess.run(init_op) if not EVAL: with sess: train(MAX_STEPS, sess, x, _y, keep_prob, train_image_batch, train_label_batch, valid_image_batch, valid_label_batch, train_step, accuracy, loss) save_session(sess, path=MODEL_PATH) elif EVAL: with sess: restore_session(sess, MODEL_PATH) probs = predict(sess, x, keep_prob, logits, test_image_batch) submit(probs, IMAGE_PATH)
Python
0.000001
@@ -3355,17 +3355,17 @@ d_size=. -2 +1 )%0Atrain_
63fddd07e3b110c06c7369fa9d815e79384ef27e
update try_pandas.py
try_pandas.py
try_pandas.py
# I'm using Spark Cloud Community Edition, sicne my own machine cannot have the right numpy for pandas... # So, in this code, so features could only be used in Spark Cloud Python Notebook # Try pandas :) # cell 1 - load the data (I upload the .csv into Spark Cloud first) import pandas as pd import numpy as np ## The path here is the .csv file path in HDFS pdata = sqlContext.read.format('csv').load("/FileStore/tables/[file name in HDFS]", index_col="ID", header =True).toPandas() # cell 2 - Bollean Indexing pdata.loc[(pdata["Gender"]=="Female") & (pdata["Salary_Account"]=="ICICI Bank") & (pdata["Mobile_Verified"]=="Y"), ["Gender", "Salary_Account", "Mobile_Verified"]] # cell 3 - apply function, similar to R apply() def get_missing_data(x): return sum(x.isnull()) print "find missing data for each column:" print pdata.apply(get_missing_data, axis = 0) print "find missing data for each row:" print pdata.apply(get_missing_data, axis = 1) # cell 4 - fillna(), updating missing values with the overall mean/mode/median of the column from scipy.stats import mode # check the mode mode(pdata['Gender'])[0][0] pdata['Gender'].fillna(mode(pdata['Gender'])[0][0], inplace=True) pdata.apply(get_missing_data, axis=0)
Python
0.000002
@@ -1342,12 +1342,375 @@ , axis=0)%0A%0A%0A +# cell 5 - create Excel style pivot table, I really like this%0A# check data type first%0Apdata.dtypes%0A%0A# convert Monthly_Income into numerical data%0Apdata%5B'Monthly_Income'%5D = pdata%5B'Monthly_Income'%5D.astype(float)%0Apdata.dtypes%0A%0Apivot_t = pdata.pivot_table(values=%5B'Monthly_Income'%5D, index=%5B'Gender', 'Mobile_Verified', 'Device_Type'%5D, aggfunc = np.mean)%0Aprint pivot_t%0A
45d9697bf7758aaf41e2946017e98323ed0845dc
Maybe.is_empty
tryp/maybe.py
tryp/maybe.py
from typing import TypeVar, Generic, Callable, Union, Any from typing import Tuple # NOQA from functools import wraps, partial # type: ignore from operator import eq, is_not # type: ignore import inspect import traceback from fn import _ # type: ignore from fn.op import identity # type: ignore from tryp.logging import log A = TypeVar('A') B = TypeVar('B') class Maybe(Generic[A]): __slots__ = () def __new__(tp, value: A, checker=partial(is_not, None)): return Maybe.inst(value, checker) @staticmethod def inst(value: A, checker=partial(is_not, None)): return Just(value) if checker(value) else Empty() @staticmethod def from_call(f: Callable[..., A], *args, **kwargs): exc = kwargs.pop('exc', Exception) try: return Maybe.inst(f(*args, **kwargs)) except exc: if exc == Exception: stack = traceback.format_stack(inspect.currentframe().f_back) log.exception('Maybe.from_call:') log.error(''.join(stack)) return Empty() @staticmethod def typed(value: A, tpe: type): return Maybe.inst(value, lambda a: isinstance(a, tpe)) @property def _get(self) -> Union[A, None]: pass def cata(self, f: Callable[[A], B], b: Union[B, Callable[[], B]]) -> B: if self.is_just: return f(self._get) elif isinstance(b, Callable): # type: ignore return b() # type: ignore else: return b # type: ignore def map(self, f: Callable[[A], B]) -> 'Maybe[B]': return self.cata(lambda v: Just(f(v)), Empty()) def smap(self, f: Callable[..., B]) -> 'Maybe[B]': return self.cata(lambda v: Just(f(*v)), Empty()) # type: ignore def flat_map(self, f: Callable[[A], 'Maybe[B]']) -> 'Maybe[B]': e = Empty() # type: Maybe[B] return self.cata(f, e) def flat_smap(self, f: Callable[..., 'Maybe[B]']) -> 'Maybe[B]': e = Empty() # type: Maybe[B] return self.cata(lambda v: f(*v), e) # type: ignore @property def flatten(self): return self.flat_map(_) def filter(self, f: Callable[[A], B]): l = lambda a: self if f(a) else Empty() return self.flat_map(l) def get_or_else(self, a: Union[A, Callable[[], A]]): return self.cata(identity, a) __or__ = get_or_else def or_else(self, ma: Union['Maybe[A]', Callable[[], 'Maybe[A]']]): return self.cata(lambda v: self, ma) def exists(self, f: Callable[[A], bool]): return self.cata(f, False) def contains(self, v): return self.exists(_ == v) def zip(self, other: 'Maybe[B]') -> 'Maybe[Tuple[A, B]]': if self.is_just and other.is_just: return Just((self._get, other._get)) else: return Empty() def foreach(self, f: Callable[[A], Any]): self.cata(f, None) def error(self, f: Callable[[], Any]) -> 'Maybe[A]': self.cata(identity, f) return self def observe(self, f: Callable[[A], Any]): self.foreach(f) return self def debug(self, prefix=None): prefix = '' if prefix is None else prefix + ' ' self.observe(lambda a: log.verbose(prefix + str(a))) def __iter__(self): return iter(self.toList) @property def is_just(self): return (isinstance(self, Just)) def __nonzero__(self): return self.is_just @property def toList(self): from tryp.list import List return self.cata(lambda v: List(v), List()) class Just(Maybe): __slots__ = 'x', def __new__(tp, value: A, *args, **kwargs): return object.__new__(tp) def __init__(self, value): self.x = value @property def _get(self) -> Union[A, None]: return self.x def __str__(self): return 'Just({})'.format(self.x) def __repr__(self): return 'Just({!r})'.format(self.x) def __eq__(self, other): if not isinstance(other, Just): return False return eq(self.x, other.x) def __hash__(self): return hash(self._get) class Empty(Maybe): __object = None # type: Empty def __new__(tp, *args, **kwargs): if Empty.__object is None: Empty.__object = object.__new__(tp) return Empty.__object def __str__(self): return 'Empty()' __repr__ = __str__ def __eq__(self, other): return isinstance(other, Empty) def __hash__(self): return hash('Empty') def may(f): @wraps(f) def wrapper(*args, **kwargs): return Maybe.inst(f(*args, **kwargs)) return wrapper def flat_may(f): @wraps(f) def wrapper(*args, **kwargs): res = f(*args, **kwargs) return res if isinstance(res, Maybe) else Maybe(res) return wrapper __all__ = ['Maybe', 'Just', 'Empty', 'may']
Python
0.999887
@@ -3419,24 +3419,95 @@ lf, Just))%0A%0A + @property%0A def is_empty(self):%0A return not self.is_just%0A%0A def __no
5d43a326d5c18f5493f97ed0420187ec7656ca4e
Fix releases path.
twisted_trac_plugins/release_macro.py
twisted_trac_plugins/release_macro.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Trac macros for the Twisted website. """ from StringIO import StringIO from urlparse import urlparse from trac.core import TracError from trac.util.html import Markup from trac.wiki.formatter import OneLinerFormatter from trac.wiki.macros import WikiMacroBase from twisted.python.versions import Version from twisted.python.filepath import FilePath author = "Twisted Matrix Laboratories" revision = "0.1" url = "$URL: https://launchpad.net/twisted-trac-integration $" license = "MIT" class VersionInformation(object): """ C{dict}-alike providing values for interpolation into a format string, with support for lazy calculation of an md5 sum. """ def __init__(self, format, version, md5sums): self.format = format self.version = version self.md5sums = md5sums def __getitem__(self, name): if name == 'md5': return self._md5() elif name == 'base': return self.version.base() try: return getattr(self.version, name) except AttributeError: raise KeyError(name) def _md5(self): """ @rtype: C{str} """ sep = '-----BEGIN PGP SIGNATURE-----\n' lines = self.md5sums.open().readlines() path = urlparse(self.format).path % dict(major=self.version.major, minor=self.version.minor, micro=self.version.micro, base=self.version.base(), md5="") filename = path.split('/')[-1] for entry in lines[3:lines.index(sep)]: entry = entry.rstrip('\n').split(' ') if entry[1] == filename: return entry[0] return '' class ProjectVersionMacro(WikiMacroBase): """ Macro that knows the current [http://twistedmatrix.com Twisted] version number. The version information is loaded from a folder containing text files with md5sums for each released package/installer. Also see the [http://twistedmatrix.com/trac/wiki/Downloads#SignedMD5Sums Twisted downloads] page. '''Standalone''' {{{ [[ProjectVersion]] }}} produces: [[ProjectVersion]] '''URL''' {{{ [[ProjectVersion(http://twistedmatrix.com/Releases/Twisted/%(major)s.%(minor)s/Twisted-%(base)s.win32-py2.7.msi Twisted %(base)s for Python 2.7)]] }}} produces: [[ProjectVersion(http://twistedmatrix.com/Releases/Twisted/%(major)s.%(minor)s/Twisted-%(base)s.win32-py2.7.msi Twisted %(base)s for Python 2.7)]] Including the MD5 hash (eg. `b568b504524fda2440c62aa1616b3fe5`): {{{ - [[ProjectVersion(http://pypi.python.org/packages/source/T/Twisted/Twisted-%(base)s.tar.bz2#md5=%(md5)s Twisted %(base)s tar)]] - [[ProjectVersion(http://pypi.python.org/packages/2.7/T/Twisted/Twisted-%(base)s.win32-py2.7.msi#md5=%(md5)s Twisted %(base)s for Python 2.7)]] }}} produces: - [[ProjectVersion(http://pypi.python.org/packages/source/T/Twisted/Twisted-%(base)s.tar.bz2#md5=%(md5)s Twisted %(base)s tar)]] - [[ProjectVersion(http://pypi.python.org/packages/2.7/T/Twisted/Twisted-%(base)s.win32-py2.7.msi#md5=%(md5)s Twisted %(base)s for Python 2.7)]] '''Source browser''' {{{ [[ProjectVersion(source:/tags/releases/twisted-%(base)s/ Tag for Twisted %(base)s)]] }}} produces: [[ProjectVersion(source:/tags/releases/twisted-%(base)s/ Tag for Twisted %(base)s)]] """ RELEASES = FilePath('/srv/www-data/twisted/Releases/') def getVersion(self): versions = [] pattern = 'twisted-%s-md5sums.txt' for md5sums in self.RELEASES.globChildren(pattern % '*'): try: components = map(int, md5sums.basename().split('-')[1].split('.')) except ValueError: pass else: versions.append(components) try: version = Version('Twisted', *max(versions)) except ValueError: self.log.error( "Could not parse a version from files in the RELEASES directory %s" % ( self.RELEASES.path,)) raise TracError("Error loading Twisted version information") md5sums_file = self.RELEASES.child(pattern % version.base()) return version, md5sums_file def _expandText(self, args): if not self.RELEASES.exists(): self.log.error( "The specified RELEASES directory does not exist at %s" % ( self.RELEASES.path,)) raise TracError("Error loading Twisted version information") version, md5sums = self.getVersion() if args is None: text = version.base() else: uc = unicode(args).replace('%28', '(').replace('%29', ')') values = VersionInformation(uc, version, md5sums) if uc.find('%(md5)s') > -1 and values['md5'] == '': self.log.warn( "Could not find a matching hexdigest for %s" % ( version.base(),)) raise TracError("Error loading Twisted version information") url = urlparse(uc).netloc text = uc % values # handle links if args.startswith('source:') or url != '': text = "[%s]" % (text,) return text def expand_macro(self, formatter, name, args): """ Return output that will be displayed in the Wiki content. @param name: the actual name of the macro @param args: the text enclosed in parenthesis at the call of the macro. Note that if there are ''no'' parenthesis (like in, e.g. [[ProjectVersion]]), then `args` is `None`. """ text = self._expandText(args) out = StringIO() OneLinerFormatter(self.env, formatter.context).format(text, out) return Markup(out.getvalue())
Python
0
@@ -3514,26 +3514,20 @@ srv/ -www-data/twisted/R +t-web/data/r elea
348711795607844bb9c0f84154849f7f25235268
Add missing shop ID on article creation
byceps/services/shop/article/service.py
byceps/services/shop/article/service.py
""" byceps.services.shop.article.service ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2006-2018 Jochen Kupperschmidt :License: Modified BSD, see LICENSE for details. """ from datetime import datetime from decimal import Decimal from typing import Dict, Optional, Sequence, Set from flask_sqlalchemy import Pagination from ....database import BaseQuery, db from ..shop.models import Shop from ..shop.transfer.models import ShopID from .models.article import Article, ArticleID from .models.attached_article import AttachedArticle, AttachedArticleID from .models.compilation import ArticleCompilation, ArticleCompilationItem from .transfer.models import ArticleNumber def create_article(shop_id: ShopID, item_number: ArticleNumber, description: str, price: Decimal, tax_rate: Decimal, quantity: int) -> Article: """Create an article.""" article = Article(item_number, description, price, tax_rate, quantity) db.session.add(article) db.session.commit() return article def update_article(article: Article, description: str, price: Decimal, tax_rate: Decimal, available_from: Optional[datetime], available_until: Optional[datetime], quantity: int, max_quantity_per_order: int, not_directly_orderable: bool, requires_separate_order: bool, shipping_required: bool ) -> None: """Update the article.""" article.description = description article.price = price article.tax_rate = tax_rate article.available_from = available_from article.available_until = available_until article.quantity = quantity article.max_quantity_per_order = max_quantity_per_order article.not_directly_orderable = not_directly_orderable article.requires_separate_order = requires_separate_order article.shipping_required = shipping_required db.session.commit() def attach_article(article_to_attach: Article, quantity: int, article_to_attach_to: Article) -> None: """Attach an article to another article.""" attached_article = AttachedArticle(article_to_attach, quantity, article_to_attach_to) db.session.add(attached_article) db.session.commit() def count_articles_for_shop(shop_id: ShopID) -> int: """Return the number of articles that are assigned to that shop.""" return Article.query \ .for_shop(shop_id) \ .count() def unattach_article(attached_article: Article) -> None: """Unattach an article from another.""" db.session.delete(attached_article) db.session.commit() def find_article(article_id: ArticleID) -> Optional[Article]: """Return the article with that ID, or `None` if not found.""" return Article.query.get(article_id) def find_article_with_details(article_id: ArticleID) -> Optional[Article]: """Return the article with that ID, or `None` if not found.""" return Article.query \ .options( db.joinedload('articles_attached_to').joinedload('article'), db.joinedload('attached_articles').joinedload('article'), ) \ .get(article_id) def find_attached_article(attached_article_id: AttachedArticleID ) -> Optional[AttachedArticle]: """Return the attached article with that ID, or `None` if not found.""" return AttachedArticle.query.get(attached_article_id) def get_article_count_by_shop_id() -> Dict[ShopID, int]: """Return article count (including 0) per shop, indexed by shop ID.""" shop_ids_and_article_counts = db.session \ .query( Shop.id, db.func.count(Article.shop_id) ) \ .outerjoin(Article) \ .group_by(Shop.id) \ .all() return dict(shop_ids_and_article_counts) def get_articles_by_numbers(article_numbers: Set[ArticleNumber] ) -> Sequence[Article]: """Return the articles with those numbers.""" if not article_numbers: return [] return Article.query \ .filter(Article.item_number.in_(article_numbers)) \ .all() def get_articles_for_shop(shop_id: ShopID) -> Sequence[Article]: """Return all articles for that shop, ordered by article number.""" return _get_articles_for_shop_query(shop_id) \ .all() def get_articles_for_shop_paginated(shop_id: ShopID, page: int, per_page: int ) -> Pagination: """Return all articles for that shop, ordered by article number.""" return _get_articles_for_shop_query(shop_id) \ .paginate(page, per_page) def _get_articles_for_shop_query(shop_id: ShopID) -> BaseQuery: return Article.query \ .for_shop(shop_id) \ .order_by(Article.item_number) def get_article_compilation_for_orderable_articles(shop_id: ShopID ) -> ArticleCompilation: """Return a compilation of the articles which can be ordered from that shop, less the ones that are only orderable in a dedicated order. """ orderable_articles = Article.query \ .for_shop(shop_id) \ .filter_by(not_directly_orderable=False) \ .filter_by(requires_separate_order=False) \ .currently_available() \ .order_by(Article.description) \ .all() compilation = ArticleCompilation() for article in orderable_articles: compilation.append(ArticleCompilationItem(article)) _add_attached_articles(compilation, article.attached_articles) return compilation def get_article_compilation_for_single_article(article: Article, *, fixed_quantity: Optional[int]=None ) -> ArticleCompilation: """Return a compilation built from just the given article plus the articles attached to it (if any). """ compilation = ArticleCompilation() compilation.append( ArticleCompilationItem(article, fixed_quantity=fixed_quantity)) _add_attached_articles(compilation, article.attached_articles) return compilation def _add_attached_articles(compilation: ArticleCompilation, attached_articles: Sequence[AttachedArticle] ) -> None: """Add the attached articles to the compilation.""" for attached_article in attached_articles: compilation.append( ArticleCompilationItem(attached_article.article, fixed_quantity=attached_article.quantity)) def get_attachable_articles(article: Article) -> Sequence[Article]: """Return the articles that can be attached to that article.""" attached_articles = {attached.article for attached in article.attached_articles} unattachable_articles = {article}.union(attached_articles) unattachable_article_ids = {article.id for article in unattachable_articles} return Article.query \ .for_shop(article.shop_id) \ .filter(db.not_(Article.id.in_(unattachable_article_ids))) \ .order_by(Article.item_number) \ .all()
Python
0.000001
@@ -904,16 +904,25 @@ Article( +shop_id, item_num @@ -955,16 +955,38 @@ ax_rate, +%0A quantit