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
06f66859c305465c3f6f38617ecada4da94d41ff
set up skeleton
algorithms/sorting/quicksort.py
algorithms/sorting/quicksort.py
Python
0.000002
@@ -0,0 +1,612 @@ +from random import randint%0A%0Adef quicksort(unsorted):%0A if len(unsorted) %3C= 1:%0A return unsorted%0A %0A start = 0%0A end = start + 1%0A pivot = choose_pivot(start, end)%0A %0A sort(unsorted, start, pivot, end)%0A %0A %0A%0Adef choose_pivot(start, end):%0A pivot = randint(start, end)%0A %0A return pivot%0A%0A%0Adef sort(unsorted, start, pivot, end):%0A pass%0A%0A%0A%0A%0A%0A%0Aif __name__ == '__main__':%0A unsorted = %5B3,345,456,7,879,970,7,4,23,123,45,467,578,78,6,4,324,145,345,3456,567,5768,6589,69,69%5D%0A sort = quicksort(unsorted)%0A%0A print '%25r %3C-- unsorted' %25 unsorted%0A print '%25r %3C-- sorted' %25 sort%0A
0e31b15e4dae95b862fd4777659a9210e5e4ec86
change of file path
preprocessing/python_scripts/renpass_gis/simple_feedin/renpassgis_feedin.py
preprocessing/python_scripts/renpass_gis/simple_feedin/renpassgis_feedin.py
Python
0.000002
@@ -0,0 +1,1163 @@ +%22%22%22%0A%0AToDO:%0A * Greate one scaled time series%0A * %0A %0ADatabase table: %0A * model_draft.ego_weather_measurement_point%0A * model_draft.ego_simple_feedin_full%0A%0A%0AChange db.py and add ego_simple_feedin_full%0A%0A%0A%22%22%22 %0A%0A__copyright__ = %22ZNES%22%0A__license__ = %22GNU Affero General Public License Version 3 (AGPL-3.0)%22%0A__url__ = %22https://github.com/openego/data_processing/blob/master/LICENSE%22%0A__author__ = %22wolf_bunke%22%0A%0A%0Afrom oemof.db import coastdat%0Aimport db%0Aimport pandas as pd%0A%0A# get Classes and make settings%0Apoints = db.Points%0Aconn = db.conn%0Ascenario_name = 'eGo 100'%0Aweather_year = 2011%0Afilename = '2017-08-21_simple_feedin_ego-100-wj2011_all.csv'%0Aconfig = 'config.ini'%0A%0A%0A%0Aimport pandas as pd%0Aimport psycopg2%0Afrom sqlalchemy import create_engine%0Aimport numpy as np%0Afrom db import conn, readcfg, dbconnect%0Aimport os%0A%0A# Settings%0A#filename = '2017-08-07_simple_feedin_All_subids_weatherids_ego_weatherYear2011.csv'%0Afilename = 'simple_feedin_full.csv'%0Aconn = conn%0A# read configuration file%0Apath = os.path.join(os.path.expanduser(%22~%22), '.open_eGo', 'config.ini')%0Aconfig = readcfg(path=path)%0A%0A# establish DB connection%0Asection = 'oedb'%0Aconn = dbconnect(section=section, cfg=config)%0A
cbd64641f30c1a464528a2ec6d5323d29766830d
Add word embedding
hazm/embedding.py
hazm/embedding.py
Python
0.00733
@@ -0,0 +1,2437 @@ +from . import word_tokenize%0Afrom gensim.models import KeyedVectors%0Afrom gensim.scripts.glove2word2vec import glove2word2vec%0Aimport fasttext, os%0A%0Asupported_embeddings = %5B'fasttext', 'keyedvector', 'glove'%5D%0A%0A%0Aclass WordEmbedding:%0A def __init__(self, model_type, model=None):%0A if model_type not in supported_embeddings:%0A raise KeyError(f'Model type %22%7Bmodel_type%7D%22 is not supported! Please choose from %7Bsupported_embeddings%7D')%0A if model:%0A self.model = model %0A self.model_type = model_type %0A%0A def load_model(self, model_file):%0A if self.model_type == 'fasttext':%0A self.model = fasttext.load_model(model_file)%0A elif self.model_type == 'keyedvector':%0A if model_file.endswith('bin'):%0A self.model = KeyedVectors.load_word2vec_format(model_file, binary=True)%0A else:%0A self.model = KeyedVectors.load_word2vec_format(model_file)%0A elif self.model_type == 'glove':%0A word2vec_addr = str(model_file) + '_word2vec_format.vec'%0A if not os.path.exists(word2vec_addr):%0A _ = glove2word2vec(model_file, word2vec_addr)%0A self.model = KeyedVectors.load_word2vec_format(word2vec_addr)%0A self.model_type = 'keyedvector'%0A else:%0A raise KeyError(f'%7Bself.model_type%7D not supported! Please choose from %7Bsupported_embeddings%7D')%0A%0A %0A def __getitem__(self, word):%0A if not self.model:%0A raise AttributeError('Model must not be None! Please load model first.')%0A return self.model%5Bword%5D%0A %0A%0A def doesnt_match(self, txt):%0A if not self.model:%0A raise AttributeError('Model must not be None! Please load model first.')%0A return self.model.doesnt_match(word_tokenize(txt))%0A%0A %0A def similarity(self, word1, word2):%0A if not self.model:%0A raise AttributeError('Model must not be None! Please load model first.')%0A return self.model.similarity(word1, word2)%0A %0A%0A def get_vocab(self):%0A if not self.model:%0A raise AttributeError('Model must not be None! Please load model first.')%0A return self.model.get_words(include_freq=True)%0A %0A%0A def nearest_words(self, word, topn):%0A if not self.model:%0A raise AttributeError('Model must not be None! Please load model first.')%0A return self.model.get_nearest_neighbors(word, topn)%0A%0A %0A%0A%0A
13851dd6f2101ceea917504bd57540a4e54f0954
Create __init__.py
fb_nsitbot/migrations/__init__.py
fb_nsitbot/migrations/__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
14647b71fec7a81d92f044f6ac88304a4b11e5fd
create http server module
src/step1.py
src/step1.py
Python
0
@@ -0,0 +1,99 @@ +%22%22%22A simple HTTP server.%22%22%22%0A%0A%0Adef response_ok():%0A %22%22%22Testing for 200 response code.%22%22%22%0A pass%0A
0a97f34b4ae4f7f19bfe00c26f495f399f827fab
Add file_regex
python/file_regex/tmp.py
python/file_regex/tmp.py
Python
0.000001
@@ -0,0 +1,405 @@ +# -*- coding: utf-8 -*-%0Aimport re%0A%0Afile_name = 'hogehoge'%0A%0Aorg_file = open(file_name + '.txt')%0Alines = org_file.readlines()%0Aorg_file.close()%0A%0Adist_file = open(file_name + '_after.txt', 'w')%0Apattern = r'title=%5C%22.+?%5C%22'%0Aall_title = re.findall(pattern, ''.join(lines))%0Aif all_title:%0A for title in all_title:%0A dist_file.write(title.replace('%5C%22', '').replace('title=', '') + '%5Cn')%0A%0A%0Adist_file.close()%0A
0297e8b1762d495ffd696106bc6498def0ddf600
Add membership.utils.monthRange to calculate start and end dates of months easily
spiff/membership/utils.py
spiff/membership/utils.py
Python
0
@@ -0,0 +1,442 @@ +import datetime%0Aimport calendar%0Afrom django.utils.timezone import utc%0A%0Adef monthRange(today=None):%0A if today is None:%0A today = datetime.datetime.utcnow().replace(tzinfo=utc)%0A lastDayOfMonth = calendar.monthrange(today.year, today.month)%5B1%5D%0A startOfMonth = datetime.datetime(today.year, today.month, 1, tzinfo=utc)%0A endOfMonth = datetime.datetime(today.year, today.month, lastDayOfMonth, tzinfo=utc)%0A return (startOfMonth, endOfMonth)%0A
fb16bb12e12fd820856ca0397a2cb4a857d2c7ca
chatbot function
src/tuling.py
src/tuling.py
Python
0.999999
@@ -0,0 +1,332 @@ +# coding:utf-8%0Aimport requests%0A%0A%0Adef chatbot(body):%0A resp = requests.post(%22http://www.tuling123.com/openapi/api%22, data=%7B%0A # %22key%22: %22d59c41e816154441ace453269ea08dba%22,%0A %22key%22: %22ff772ad12e0c421f98da2dd7f6a9289c%22,%0A %22info%22: body,%0A %22userid%22: %22xiaopeng%22%0A %7D)%0A resp = resp.json()%0A return resp%0A
0a079e378fcb4994a2e1fd9bc8c71e22d4342901
Generate HTML snippet for Jekyll
kuveja-html.py
kuveja-html.py
Python
0.999999
@@ -0,0 +1,427 @@ +#!/usr/bin/env python3%0Aimport json%0A%0AFILE = 'kuveja.json'%0APREFIX = 'http://joneskoo.kapsi.fi/kuveja/'%0AHEADER = %22%22%22---%0Alayout: main%0Atitle: joneskoon kuvafeedi%0A---%22%22%22%0AHTML = %22%22%22%3Cdiv class=%22kuva%22%3E%0A %3Ch3%3E%25(title)s%3C/h3%3E%0A %3Cimg src=%22%25(url)s%22 alt=%22%25(title)s%22 /%3E%0A%3C/div%3E%22%22%22%0A%0A%0Awith open(FILE) as f:%0A data = json.load(f)%0A%0Aprint(HEADER)%0Afor d in data%5B0:10%5D:%0A title = d%5B'file'%5D%0A url = PREFIX + d%5B'file'%5D%0A print(HTML %25 vars())
e30f1c21363e96801f75ee6bf913d2ea3366d8f2
add browserid
settings.py
settings.py
LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'h98sp-!d$d15*u+-1^_&)!v5t)d^u(mhm-ksmi!$-raz+=wlv+' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'sunoss.urls' # Python dotted path to the WSGI application used by Django's runserver. #WSGI_APPLICATION = 'sunoss.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', #'django.contrib.admin', ) try: from local_settings import * except ImportError: pass
Python
0.000001
@@ -1687,16 +1687,160 @@ er',%0A)%0A%0A +TEMPLATE_CONTEXT_PROCESSORS = (%0A 'django.contrib.auth.context_processors.auth',%0A 'django_browserid.context_processors.browserid_form',%0A)%0A%0A MIDDLEWA @@ -2850,17 +2850,16 @@ s',%0A -# 'django. @@ -2874,16 +2874,117 @@ admin',%0A + 'django_browserid',%0A)%0A%0AAUTHENTICATION_BACKENDS = (%0A 'django_browserid.auth.BrowserIDBackend',%0A )%0A%0A%0Atry:
0ec3fd40c85f2a61eee5960031318c7f5ab06bc5
Allow whitelisted shell calls in transforms
humfrey/update/transform/shell.py
humfrey/update/transform/shell.py
Python
0.000001
@@ -0,0 +1,1323 @@ +import logging%0Aimport subprocess%0Aimport tempfile%0A%0Afrom django.conf import settings%0A%0Afrom .base import Transform, TransformException%0A%0ASHELL_TRANSFORMS = getattr(settings, 'SHELL_TRANSFORMS', %7B%7D)%0A%0Alogger = logging.getLogger(__name__)%0A%0Aclass Shell(Transform):%0A def __init__(self, name, extension, params):%0A self.shell = SHELL_TRANSFORMS%5Bname%5D%0A self.extension = extension%0A%0A def execute(self, transform_manager, input):%0A params = self.params.copy()%0A if 'store' not in params:%0A params%5B'store'%5D = transform_manager.store.slug%0A%0A popen_args = %5Binput if arg is None else arg.format(params) for arg in self.shell%5D%0A%0A with open(transform_manager(self.extension), 'w') as output:%0A with tempfile.TemporaryFile() as stderr:%0A transform_manager.start(self, %5Binput%5D)%0A%0A returncode = subprocess.call(popen_args, stdout=output, stderr=stderr)%0A%0A if stderr.tell():%0A stderr.seek(0)%0A logger.warning(%22Shell warnings:%5Cn%5Cn%25s%5Cn%22, stderr.read())%0A%0A if returncode != 0:%0A logger.error(%22Shell transform failed with code %25d%22, returncode)%0A raise TransformException%0A%0A transform_manager.end(%5Boutput.name%5D)%0A return output.name%0A
2a1b46740c4cf14f7db4f344431aced9bf06d1e7
Add a little program that calls sync until is is done
scripts/sync_for_real.py
scripts/sync_for_real.py
Python
0.000001
@@ -0,0 +1,608 @@ +#!/usr/bin/env python3%0A%0Aimport subprocess%0Aimport sys%0Afrom time import time%0A%0A%0A%0Adef eprint(*args, **kwargs):%0A print(*args, file=sys.stderr, **kwargs)%0A%0A%0Adef main():%0A nr_fast = 3%0A while nr_fast %3E 0:%0A eprint('syncing... ', end='', flush=True)%0A start_t = time()%0A subprocess.Popen('/usr/bin/sync', stdout=None, stderr=None).wait()%0A time_length = time() - start_t%0A eprint('%7B0:0.3f%7D'.format(time_length))%0A%0A if time_length %3C 0.10:%0A nr_fast = nr_fast - 1%0A else:%0A nr_fast = 3%0A%0A return 0%0A%0Aif __name__ == '__main__':%0A sys.exit(main())%0A%0A
3e2c4f19d1eb5d66430ea46abe18a6a7022e13ef
Create svg_filter.py
svg_filter.py
svg_filter.py
Python
0.000006
@@ -0,0 +1,1104 @@ +f = open(%22domusdomezones.svg%22, %22r%22)%0Asvg = %5B%5D%0Afor line in f:%0A line = line.strip()%0A svg.append(line)%0Af.close()%0A%0Avector_paths = %5B%5D%0Afor i in range(0, len(svg)):%0A if svg%5Bi%5D == %22%3Cpath%22:# spot the paths location %0A i = i+1 %0A svg%5Bi%5D = svg%5Bi%5D.replace(',', ' ')# remove the first 5 items in each path, replace spaces with commas%0A svg%5Bi%5D = svg%5Bi%5D%5B5:-1%5D.split(' ')# remove the first 5 and the last item of the line of each path, split each vector into a iterable list%0A vector_paths.append(svg%5Bi%5D)%0A%0Apaths = %5B%5D%0Afor n in range(0, len(vector_paths)):%0A paths.append(vector_paths%5Bn%5D)%0A for m in range(0, len(vector_paths%5Bn%5D)):%0A vector_paths%5Bn%5D%5Bm%5D = float(vector_paths%5Bn%5D%5Bm%5D) # float all strings of the vector_paths list %0Afor p in range(0, len(paths)):%0A for o in range(2, len(paths%5Bp%5D)-1):# loop to sum vectors%0A paths%5Bp%5D%5Bo%5D = paths%5Bp%5D%5Bo-2%5D + paths%5Bp%5D%5Bo%5D# sum the vectors of each cordinate%0A for o in range(0, len(paths%5Bp%5D)):#loop to round each cordinate%0A paths%5Bp%5D%5Bo%5D = round(paths%5Bp%5D%5Bo%5D,2) #round the floating points to a two decimal float %0Aprint paths %0A
353d717c425cca9941d650d715c3ed8caf0aae64
Reset tooltip timer also when cell editor is closed
src/robotide/editor/tooltips.py
src/robotide/editor/tooltips.py
# Copyright 2008-2009 Nokia Siemens Networks Oyj # # 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. import wx from popupwindow import Tooltip class GridToolTips(object): def __init__(self, grid): self._tooltip = Tooltip(grid, (250, 80), False, True) self._information_popup = Tooltip(grid, (450, 300)) self._grid = grid self._tooltip_timer = wx.Timer(grid.GetGridWindow()) grid.GetGridWindow().Bind(wx.EVT_MOTION, self.OnMouseMotion) grid.GetGridWindow().Bind(wx.EVT_TIMER, self.OnShowToolTip) def OnMouseMotion(self, event): self._hide_tooltip() self._tooltip_timer.Start(500, True) event.Skip() def OnShowToolTip(self, event): self._hide_tooltip() content = self._grid.get_tooltip_content() if content: self._show_tooltip_at(content, self._calculate_tooltip_position()) self._grid.SetFocus() def _show_tooltip_at(self, content, position): if not self._information_popup.IsShown(): self._tooltip.set_content(content) self._tooltip.show_at(position) def _calculate_tooltip_position(self): x, y = wx.GetMousePosition() return x+5, y+5 def _hide_tooltip(self): self._tooltip.hide() def hide_information(self): self._information_popup.hide() def hide(self): self._hide_tooltip() self.hide_information() def show_info_at(self, info, title, position): self._tooltip.hide() self._information_popup.set_content(info, title) self._information_popup.show_at(position)
Python
0
@@ -608,16 +608,31 @@ mport wx +%0Aimport wx.grid %0A%0Afrom p @@ -1063,16 +1063,91 @@ ToolTip) +%0A grid.Bind(wx.grid.EVT_GRID_EDITOR_HIDDEN, self.OnGridEditorHidden) %0A%0A de @@ -1211,32 +1211,38 @@ )%0A self._ +start_ tooltip_timer.St @@ -1242,45 +1242,112 @@ imer -.Start(500, True)%0A event.Skip( +()%0A event.Skip()%0A%0A def _start_tooltip_timer(self):%0A self._tooltip_timer.Start(500, True )%0A%0A @@ -1591,24 +1591,191 @@ SetFocus()%0A%0A + def OnGridEditorHidden(self, event):%0A cell = event.Row, event.Col%0A if cell == self._grid.cell_under_cursor:%0A self._start_tooltip_timer()%0A%0A def _sho
86434fb902caeea7bb740c35607dc6f9f7766d88
Fix searching for notes in the django admin
notes/admin.py
notes/admin.py
# # Copyright (c) 2009 Brad Taylor <[email protected]> # # 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 the GNU Affero General Public License for more # details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from snowy.accounts.models import UserProfile from snowy.notes.models import Note, NoteTag from reversion.admin import VersionAdmin from django.contrib import admin class NoteAdmin(VersionAdmin): list_display = ('created', 'author', 'title') search_fields = ['body', 'title'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Note, NoteAdmin) admin.site.register(NoteTag) admin.site.register(UserProfile)
Python
0
@@ -981,12 +981,15 @@ = %5B' -body +content ', '
75717747ffbc36f306e0f771a65ed101bd3ca9be
Create parser.py
parser.py
parser.py
Python
0.000011
@@ -0,0 +1,1294 @@ +from HTMLParser import HTMLParser%0A%0A# create a subclass and override the handler methods%0Aclass Parser(HTMLParser):%0A tag = %22%22%0A doc = new Document()%0A %0A def handle_starttag(self, tag, attrs):%0A tag = tag%0A print %22Encountered a start tag:%22, tag%0A%0A def handle_endtag(self, tag):%0A tag = %22%22%0A print %22Encountered an end tag :%22, tag%0A%0A def handle_data(self, data):%0A print %22Encountered some data :%22, data%0A if tag == %22DOCNO%22:%0A doc.setId(data)%0A if tag == %22title%22:%0A doc.setTitle(data)%0A if tag == %22h1%22:%0A doc.addH1(data)%0A if tag == %22h2%22:%0A doc.addH2(data)%0A if tag == %22h3%22:%0A doc.addH4(data)%0A elif tag != %22%22:%0A doc.addContent(data)%0A %0Aclass Document():%0A def __init__():%0A id = %22%22%0A title = %22%22%0A h1 = %5B%5D%0A h2 = %5B%5D%0A h3 = %5B%5D%0A content = %22%22%0A %0A def setId(self, id):%0A self.id = id%0A %0A def setTitle(self, title):%0A self.title = title%0A %0A def addH1(self, h1):%0A self.append(h1)%0A %0A def addH2(self, h2):%0A self.append(h2)%0A %0A def addH3(self, h3):%0A self.append(h3)%0A %0A def addContent(self, content):%0A self.content += content + %22 %22%0A
ecde3b823724e612fd4e5cc575eb75f0d3652a4b
add script for running test
test/run-test.py
test/run-test.py
Python
0.000001
@@ -0,0 +1,843 @@ +import imp%0Aimport json%0Aimport os%0Amustache = imp.load_source('mustache', '../src/mustache.py')%0A%0A#test_files = %5B'comments.json',%0A #'delimiters.json',%0A #'interpolation.json',%0A #'inverted.json',%0A #'~lambdas.json',%0A #'partials.json',%0A #'sections.json'%5D%0A%0Atest_files = %5B'interpolation.json',%0A 'delimiters.json'%5D%0A%0Afor filename in test_files:%0A with open(os.path.join('./spec/specs/', filename)) as fp:%0A data = json.load(fp)%5B'tests'%5D%0A%0A for test in data:%0A context = test%5B'data'%5D%0A template = test%5B'template'%5D%0A expected = test%5B'expected'%5D%0A result = mustache.render(template, %5Bcontext%5D)%0A if result != expected:%0A print('%3E%3E%3E%3E%3E%3E%3E%3E%3E Error %3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E%3E')%0A print('template:', template)%0A print('expected:', expected)%0A print('result :', result)%0A%0A%0A
0feb8f3ae65fadaf600e7681349cfa537b41a8c3
Add ParseBigCSV.py
parseBigCSV.py
parseBigCSV.py
Python
0.000001
@@ -0,0 +1,221 @@ +import csv%0Aimport json%0A%0Awith open(%22evidata.csv%22, %22r%22) as bigCSV:%0A with open(%22file.json%22, %22w%22) as outFile:%0A reader = csv.DictReader(bigCSV)%0A output = json.dumps(list(reader))%0A outFile.write(output)%0A
3536b98a3adf5087c78b92432585654bec40d64e
add problem 045
problem_045.py
problem_045.py
Python
0.000294
@@ -0,0 +1,444 @@ +#!/usr/bin/env python%0A#-*-coding:utf-8-*-%0A%0A'''%0A'''%0A%0Aimport math%0Aimport timeit%0A%0A%0Adef is_pentagonal(n):%0A if (1+math.sqrt(1+24*n)) %25 6 == 0:%0A return True%0A else:%0A return False%0A%0A%0Adef calc():%0A i = 143%0A while True:%0A i += 1%0A n = i*(2*i-1)%0A if is_pentagonal(n):%0A return n%0A%0A%0Aif __name__ == '__main__':%0A print calc()%0A print timeit.Timer('problem_045.calc()', 'import problem_045').timeit(1)%0A
ef95e8f3c9c9f12b7073b02e95c2a464ed26c8df
hard code the value of the service url
ceph_installer/cli/constants.py
ceph_installer/cli/constants.py
Python
0.999698
@@ -0,0 +1,43 @@ +%0Aserver_address = 'http://localhost:8181/'%0A
91bb7506bd20ed22b8787e7a8b9975cc07e97175
Add owners client to depot_tools.
owners_client.py
owners_client.py
Python
0.000001
@@ -0,0 +1,1195 @@ +# Copyright (c) 2020 The Chromium Authors. All rights reserved.%0A# Use of this source code is governed by a BSD-style license that can be%0A# found in the LICENSE file.%0A%0A%0Aclass OwnersClient(object):%0A %22%22%22Interact with OWNERS files in a repository.%0A%0A This class allows you to interact with OWNERS files in a repository both the%0A Gerrit Code-Owners plugin REST API, and the owners database implemented by%0A Depot Tools in owners.py:%0A%0A - List all the owners for a change.%0A - Check if a change has been approved.%0A - Check if the OWNERS configuration in a change is valid.%0A%0A All code should use this class to interact with OWNERS files instead of the%0A owners database in owners.py%0A %22%22%22%0A def __init__(self, host):%0A self._host = host%0A%0A def ListOwnersForFile(self, project, branch, path):%0A %22%22%22List all owners for a file.%22%22%22%0A raise Exception('Not implemented')%0A%0A def IsChangeApproved(self, change_number):%0A %22%22%22Check if the latest patch set for a change has been approved.%22%22%22%0A raise Exception('Not implemented')%0A%0A def IsOwnerConfigurationValid(self, change_number, patch):%0A %22%22%22Check if the owners configuration in a change is valid.%22%22%22%0A raise Exception('Not implemented')%0A
beae2bdc47949f78e95e3444d248ce035766e719
Add ascii table test
smipyping/_asciitable.py
smipyping/_asciitable.py
Python
0.000007
@@ -0,0 +1,2717 @@ +# (C) Copyright 2017 Inova Development Inc.%0A# All Rights Reserved%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%22%22%22%0AInternal module with utilities to write to ascii outputs.%0A%0A%22%22%22%0A%0Afrom __future__ import print_function, absolute_import%0A%0Afrom textwrap import wrap%0Aimport six%0Afrom terminaltables import SingleTable%0A%0A%0Adef print_ascii_table(title, table_header, table_data, inner_border=False,%0A outer_border=False):%0A %22%22%22 Print table data as an ascii table. The input is a dictionary%0A of table data in the format used by terminaltable package.%0A%0A title: list of strings defining the row titles%0A%0A table_header:%0A list of strings defining the column names%0A%0A table data:%0A List of lists of strings. Each list of strings represents the%0A data for a single row in the table%0A%0A inner_border:%0A optional flag that tells table builder to create inner borders%0A%0A outer_border:%0A Optional flag that tells table builder to create border around%0A complete table%0A%0A NOTE: Currently this outputs in the terminatable SingleTable format%0A It may be extended in the future to allow other formats such as the%0A asciitable format, etc. However these only differ in the table%0A boundary character representation%0A %22%22%22%0A table_data = %5Btable_header%5D + table_data%0A table_instance = SingleTable(table_data, title)%0A table_instance.inner_column_border = inner_border%0A table_instance.outer_border = outer_border%0A%0A print(table_instance.table)%0A print()%0A%0A%0Adef fold_cell(cell_string, max_cell_width):%0A %22%22%22 Fold a string within a maximum width to fit within a table entry%0A%0A Parameters:%0A%0A cell_string:%0A The string of data to go into the cell%0A max_cell_width:%0A Maximum width of cell. Data is folded into multiple lines to%0A fit into this width.%0A%0A Return:%0A String representing the folded string%0A %22%22%22%0A new_cell = cell_string%0A if isinstance(cell_string, six.string_types):%0A if max_cell_width %3C len(cell_string):%0A new_cell = '%5Cn'.join(wrap(cell_string, max_cell_width))%0A%0A return new_cell%0A
672e4378421d2014644e23195706ef011934ffdb
test for fixes on #55
category_encoders/tests/test_basen.py
category_encoders/tests/test_basen.py
Python
0
@@ -0,0 +1,431 @@ +import category_encoders as ce%0Aimport unittest%0Aimport pandas as pd%0A%0A__author__ = 'willmcginnis'%0A%0A%0Aclass TestBasen(unittest.TestCase):%0A %22%22%22%0A %22%22%22%0A%0A def test_basen(self):%0A df = pd.DataFrame(%7B'col1': %5B'a', 'b', 'c'%5D, 'col2': %5B'd', 'e', 'f'%5D%7D)%0A df_1 = pd.DataFrame(%7B'col1': %5B'a', 'b', 'd'%5D, 'col2': %5B'd', 'e', 'f'%5D%7D)%0A enc = ce.BaseNEncoder(verbose=1)%0A enc.fit(df)%0A print(enc.transform(df_1))%0A
a4c8818225941b84e6958dcf839fc78c2adc5cee
Create test_pxssh.py
test_pxssh.py
test_pxssh.py
Python
0.000005
@@ -0,0 +1,684 @@ +# commandsshbotnet.py%0A# author: @shipcod3%0A# %0A# %3E%3E used for testing the pxssh module%0A%0Aimport pxssh%0Aimport getpass%0Atry:%0A s = pxssh.pxssh()%0A hostname = raw_input('SET HOST: ')%0A username = raw_input('SET USERNAME: ')%0A password = getpass.getpass('SET PASSWORD: ')%0A s.login (hostname, username, password)%0A s.sendline ('uptime') # run a command%0A s.prompt() # match the prompt%0A print s.before # print everything before the prompt.%0A s.sendline ('ls -l')%0A s.prompt()%0A print s.before%0A s.sendline ('df')%0A s.prompt()%0A print s.before%0A s.logout()%0Aexcept pxssh.ExceptionPxssh, e:%0A print %22pxssh failed on login.%22%0A print str(e)%0A
1be4e6f97b3d062c4fa07f70b05305bf32593fd4
Add test cases for smudge
dotbriefs/tests/test_smudge.py
dotbriefs/tests/test_smudge.py
Python
0.000002
@@ -0,0 +1,1471 @@ +import unittest%0A%0Afrom dotbriefs.smudge import SmudgeTemplate%0A%0A%0Aclass TestCleanSecret(unittest.TestCase):%0A%0A def setUp(self):%0A self.secrets = %7B%7D%0A self.secrets%5B'password'%5D = 's3cr3t'%0A self.secrets%5B'question'%5D = 'h1dd3n 4g3nd4'%0A self.template = %5B%5D%0A self.template.append(SmudgeTemplate('name', self.secrets))%0A%0A def test_nosecret_sub(self):%0A self.assertEqual(self.template%5B0%5D.sub('password = hi # comment'),%0A 'password = hi # comment')%0A%0A def test_nokey_sub(self):%0A self.assertEqual(self.template%5B0%5D.sub('password = $DotBriefs: $ # comment'),%0A 'password = $DotBriefs: $ # comment')%0A%0A def test_nomatch_sub(self):%0A self.assertEqual(self.template%5B0%5D.sub('password = $DotBriefs: notfound$ # comment'),%0A 'password = $DotBriefs: notfound$ # comment')%0A%0A def test_single_sub(self):%0A self.assertEqual(self.template%5B0%5D.sub('password = $DotBriefs: password$ # comment'),%0A 'password = s3cr3t # comment')%0A%0A def test_double_sub(self):%0A self.assertEqual(self.template%5B0%5D.sub('password = $DotBriefs: password$; security question = $DotBriefs: question$ # comment'),%0A 'password = s3cr3t; security question = h1dd3n 4g3nd4 # comment')%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
aa2d97dfe52628e1bb7ab123890a895f7f630cda
add problem 070
problem_070.py
problem_070.py
Python
0.000962
@@ -0,0 +1,1737 @@ +#!/usr/bin/env python%0A#-*-coding:utf-8-*-%0A%0A'''%0A'''%0A%0Afrom fractions import Fraction%0Aimport itertools%0Aimport math%0Aimport timeit%0A%0A%0A%0Aprimes = %5B2, 3, 5, 7%5D%0A%0A%0Adef is_prime(n):%0A for p in primes:%0A if n %25 p == 0:%0A return False%0A for i in range(max(primes), int(math.sqrt(n))+1):%0A if n %25 i == 0:%0A return False%0A return True%0A%0A%0Adef factorize(n, factors):%0A for i in range(2, int(math.sqrt(n))+1):%0A if n %25 i == 0:%0A factors.add(i)%0A return factorize(int(n/i), factors)%0A factors.add(n)%0A return factors%0A%0A%0Adef totient(n):%0A factors = factorize(n, set())%0A return n*reduce(lambda x,y: x*y, map(lambda x: 1-Fraction(1, x), factors))%0A%0A%0A# slow%0Adef loop(n):%0A num, min_ratio = None, None%0A for i in range(2, n+1):%0A phi = totient(i)%0A if sorted(str(i)) == sorted(str(phi)):%0A ratio = n/phi%0A if min_ratio is None or ratio %3C min_ratio:%0A num = i%0A min_ratio = ratio%0A return num, min_ratio%0A%0A%0Adef multiple_prime(n):%0A # prepare primes%0A for i in range(1000, 5000): # narrow search space%0A if is_prime(i):%0A primes.append(i)%0A # main loop%0A num, min_ratio = None, None%0A for i, j in itertools.combinations(primes, 2):%0A m = i*j%0A if m %3E n:%0A continue%0A phi = totient(m)%0A if sorted(str(m)) == sorted(str(phi)):%0A ratio = m/phi%0A if min_ratio is None or ratio %3C min_ratio:%0A num = m%0A min_ratio = ratio%0A return num, min_ratio%0A%0A%0Aif __name__ == '__main__':%0A # print loop(10**7)%0A print multiple_prime(10**7)%0A print timeit.Timer('problem_070.multiple_prime(10**7)', 'import problem_070').timeit(1)%0A
16ccb2a670461e8ceb9934fd4ba8823b866c9d8e
Create plot.py
src/plot.py
src/plot.py
Python
0.000021
@@ -0,0 +1,721 @@ +import pandas as pd%0Afrom matplotlib import pyplot as plt%0Afrom abc import ABCMeta, abstractmethod%0A%0A%0Aclass Plot(metaclass=ABCMeta):%0A @abstractmethod%0A def show(self):%0A plt.show()%0A%0A%0Aclass CsvPlot(Plot):%0A def __init__(self, parent_path):%0A self.parent_path = parent_path%0A%0A def show(self, is_execute=False):%0A super().show() if is_execute else None%0A%0A def plot(self, file_name, title, is_execute=False):%0A (lambda f, t: pd.read_csv(self.parent_path.format(f)).plot(title=t))(%0A file_name, title)%0A self.show(is_execute)%0A%0A def plots(self, file_names, titles, is_execute=False):%0A %5Bself.plot(f, t) for f, t in zip(file_names, titles)%5D%0A self.show(is_execute)%0A
254239102955bb8916aab98530251b5cdd79ce50
Add script to write base signatures
cypher/siggen.py
cypher/siggen.py
Python
0.000001
@@ -0,0 +1,1261 @@ +#!/usr/bin/env python%0Aimport argparse%0Aimport subprocess%0Aimport os%0Aimport shutil%0Aimport sys%0A%0Afrom util import write_signature%0A%0Aparser = argparse.ArgumentParser()%0Aparser.add_argument(%0A %22-l%22,%0A %22--language%22,%0A help=%22Source code language.%22,%0A required=True%0A)%0A%0ATEMP_DIR = os.path.join(os.getcwd(), %22cypher%22, %22temp%22)%0Aif os.path.exists(TEMP_DIR):%0A shutil.rmtree(TEMP_DIR)%0Alang = vars(parser.parse_args())%5B%22language%22%5D%0Aif lang == %22Python%22:%0A repo = %22https://github.com/django/django.git%22%0A ext = %5B%22.py%22%5D%0Aelif lang == %22Ruby%22:%0A repo = %22https://github.com/Homebrew/legacy-homebrew.git%22%0A ext = %5B%22.rb%22%5D%0Aelif lang == %22C%22:%0A repo = %22https://github.com/git/git.git%22%0A ext = %5B%22.c%22, %22.h%22%5D%0Aelif lang == %22C++%22:%0A repo = %22https://github.com/apple/swift.git%22%0A ext = %5B%22.cpp%22, %22.cc%22, %22.h%22%5D%0Aelif lang == %22R%22:%0A repo = %22https://github.com/rstudio/shiny.git%22%0A ext = %5B%22.R%22, %22.r%22%5D%0Aelse:%0A print(%22%7B%7D not found.%22.format(lang))%0A sys.exit(0)%0A%0Aos.makedirs(TEMP_DIR)%0Apro = subprocess.Popen(%0A %5B%22git%22, %22clone%22, repo%5D,%0A cwd=TEMP_DIR,%0A stdout=subprocess.PIPE,%0A stderr=subprocess.PIPE%0A)%0A(out, error) = pro.communicate()%0A%0Asrc_dir = os.path.join(TEMP_DIR, repo.split(%22/%22)%5B-1%5D.split(%22.%22)%5B0%5D)%0Awrite_signature(src_dir, lang, ext)%0Ashutil.rmtree(TEMP_DIR)%0A
19b13f0fb9b86ec99025bd1baf2c4d5fe757f809
Add a test to make sure exception is raised
tests/test_tests.py
tests/test_tests.py
Python
0
@@ -0,0 +1,600 @@ +import pytest%0A%0A%0Adef test_BeautifulSoup_methods_are_overridden(%0A client_request,%0A mock_get_service_and_organisation_counts,%0A):%0A client_request.logout()%0A page = client_request.get(%22main.index%22, _test_page_title=False)%0A%0A with pytest.raises(AttributeError) as exception:%0A page.find(%22h1%22)%0A%0A assert str(exception.value) == %22Don%E2%80%99t use BeautifulSoup.find %E2%80%93 try BeautifulSoup.select_one instead%22%0A%0A with pytest.raises(AttributeError) as exception:%0A page.find_all(%22h1%22)%0A%0A assert str(exception.value) == %22Don%E2%80%99t use BeautifulSoup.find_all %E2%80%93 try BeautifulSoup.select instead%22%0A
1f4190a6d4ef002e75a8ac5ef80d326c712c749c
add test to verify the trace assignment
tests/test_trace.py
tests/test_trace.py
Python
0
@@ -0,0 +1,1016 @@ +from __future__ import absolute_import%0A%0Aimport pytest%0A%0Afrom tchannel import TChannel, schemes%0Afrom tchannel.errors import BadRequestError%0Afrom tchannel.event import EventHook%0A%0A%[email protected]_test%0Adef test_error_trace():%0A tchannel = TChannel('test')%0A%0A class ErrorEventHook(EventHook):%0A def __init__(self):%0A self.request_trace = None%0A self.error_trace = None%0A%0A def before_receive_request(self, request):%0A self.request_trace = request.tracing%0A%0A def after_send_error(self, error):%0A self.error_trace = error.tracing%0A%0A hook = ErrorEventHook()%0A tchannel.hooks.register(hook)%0A%0A tchannel.listen()%0A%0A with pytest.raises(BadRequestError):%0A yield tchannel.call(%0A scheme=schemes.RAW,%0A service='test',%0A arg1='endpoint',%0A hostport=tchannel.hostport,%0A timeout=0.02,%0A )%0A%0A assert hook.error_trace%0A assert hook.request_trace%0A assert hook.error_trace == hook.request_trace%0A
7fa8417cb7635e238f1e95971fa0a86a95b64dca
Migrate deleted_at fields away
aleph/migrate/versions/aa486b9e627e_hard_deletes.py
aleph/migrate/versions/aa486b9e627e_hard_deletes.py
Python
0
@@ -0,0 +1,1033 @@ +%22%22%22Hard delete various model types.%0A%0ARevision ID: aa486b9e627e%0ARevises: 9dcef7592cea%0ACreate Date: 2020-07-31 08:56:43.679019%0A%0A%22%22%22%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0Arevision = %22aa486b9e627e%22%0Adown_revision = %229dcef7592cea%22%0A%0A%0Adef upgrade():%0A meta = sa.MetaData()%0A meta.bind = op.get_bind()%0A meta.reflect()%0A for table_name in (%22alert%22, %22entity%22, %22mapping%22, %22permission%22):%0A table = meta.tables%5Btable_name%5D%0A q = sa.delete(table).where(table.c.deleted_at != None) # noqa%0A meta.bind.execute(q)%0A table = meta.tables%5B%22permission%22%5D%0A q = sa.delete(table).where(table.c.read == False) # noqa%0A meta.bind.execute(q)%0A%0A op.drop_column(%22alert%22, %22deleted_at%22)%0A op.drop_column(%22entity%22, %22deleted_at%22)%0A op.drop_column(%22mapping%22, %22deleted_at%22)%0A op.drop_column(%22permission%22, %22deleted_at%22)%0A op.alter_column(%22entityset%22, %22label%22, existing_type=sa.VARCHAR(), nullable=True)%0A op.alter_column(%22role%22, %22is_muted%22, existing_type=sa.BOOLEAN(), nullable=False)%0A%0A%0Adef downgrade():%0A pass%0A
c61d3d5b4b31912c48e86425fe7e4861fc2f8c28
test for read_be_array that fails in Python 2.x (see GH-6)
tests/test_utils.py
tests/test_utils.py
Python
0
@@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import absolute_import%0Afrom io import BytesIO%0A%0Afrom psd_tools.utils import read_be_array%0A%0Adef test_read_be_array_from_file_like_objects():%0A fp = BytesIO(b%22%5Cx00%5Cx01%5Cx00%5Cx05%22)%0A res = read_be_array(%22H%22, 2, fp)%0A assert list(res) == %5B1, 5%5D%0A
eb82e816e4dece07aeebd7b9112156dacdb2d9bc
Add set_global_setting.py, not sure how this file dissapeared
commands/set_global_setting.py
commands/set_global_setting.py
Python
0.000002
@@ -0,0 +1,144 @@ +from .command import CmakeCommand%0A%0A%0Aclass CmakeSetGlobalSettingCommand(CmakeCommand):%0A%0A def run(self):%0A self.server.global_settings()%0A
96bea6812919067c28e0c28883226434d81f6e8d
add locusattrs class
locuspocus/locusattrs.py
locuspocus/locusattrs.py
Python
0
@@ -0,0 +1,1475 @@ +%0Aclass LocusAttrs():%0A # a restricted dict interface to attributes%0A def __init__(self,attrs=None):%0A self._attrs = attrs%0A%0A def __len__(self):%0A if self.empty:%0A return 0%0A else:%0A return len(self._attrs)%0A%0A def __eq__(self, other):%0A if self.empty and other.empty:%0A return True%0A elif len(self) != len(other):%0A # Short circuit on length%0A return False%0A else:%0A return sorted(self.items()) == sorted(other.items())%0A%0A @property%0A def empty(self):%0A if self._attrs is None:%0A return True%0A else:%0A return False%0A%0A def keys(self):%0A if self.empty:%0A return %5B%5D%0A else:%0A return self._attrs.keys()%0A%0A def values(self):%0A if self.empty:%0A return %5B%5D%0A else:%0A return self._attrs.values()%0A%0A def items(self):%0A if self.empty:%0A return %7B%7D%0A else:%0A return self._attrs.items()%0A%0A def __contains__(self,key):%0A if self.empty:%0A return False%0A return key in self._attrs%0A%0A def __getitem__(self,key):%0A if self.empty:%0A raise KeyError()%0A return self._attrs%5Bkey%5D%0A%0A def __setitem__(self,key,val):%0A if self.empty:%0A self._attrs = %7B%7D%0A self._attrs%5Bkey%5D = val%0A%0A def __repr__(self):%0A if self.empty:%0A return repr(%7B%7D)%0A return repr(self._attrs)%0A%0A%0A
cebb3a9cdbdee7c02b0c86e1879d0c20d36b4276
add example
examples/example_cityfynder.py
examples/example_cityfynder.py
Python
0.000002
@@ -0,0 +1,659 @@ +# Which city would like to live?%0A# Created by City Fynders - University of Washington%0A%0Aimport pandas as pd%0Aimport numpy as np%0Aimport geopy as gy%0Afrom geopy.geocoders import Nominatim%0A%0Aimport data_processing as dp%0Afrom plotly_usmap import usmap%0A%0A%0A%0A# import data%0A(natural, human, economy, tertiary) = dp.read_data()%0A%0A%0A# Add ranks in the DataFrame%0A(natural, human, economy, tertiary) = dp.data_rank(natural, human, economy, tertiary)%0A%0A%0A# Get location information%0A(Lat, Lon) = dp.find_loc(human)%0A%0A%0A# Create a rank DataFrame and save as csv file%0Arank = dp.create_rank(natural, human, economy, tertiary, Lat, Lon)%0A%0A%0A# Plot US city general ranking usmap%0Ausmap(rank)%0A
9269afee9099ef172ac2ef55ea0af85b0c77587a
Add databases.py
py/database.py
py/database.py
Python
0.000001
@@ -0,0 +1,1583 @@ +import sqlalchemy%0Aimport sqlalchemy.orm%0Aimport uuid%0Aimport configmanager%0A%0Aclass ConnectionManager():%0A%09_connections = %7B%7D%0A%0A%09@staticmethod%0A%09def addConnection(self, connection, connectionName = uuid.uuid4().hex):%0A%09%09if type(connectionName) == str:%0A%09%09%09if type(connection) == DatabaseConnection:%0A%09%09%09%09_connections%5BconnectionName%5D = connection%0A%09%09%09%09return connectionName%0A%09%09%09else if type(connection) == str:%0A%09%09%09%09c = DatabaseConnection(connection)%0A%09%09%09%09_connections%5BconnectionName%5D = connection%0A%09%09%09%09return connectionName%0A%09%09%09else:%0A%09%09%09%09raise ValueError(%22connection must be of type str, not %25s%22, type(connection))%0A%09%09else:%0A%09%09%09raise ValueError(%22connectionName must be of type str, not %25s%22, type(name))%0A%09%0A%09@staticmethod%0A%09def getConnection(self, connectionName):%0A%09%09if type(connectionName) == str:%0A%09%09%09try:%0A%09%09%09%09return _connections%5BconnectionName%5D%0A%09%09%09except KeyError:%0A%09%09%09%09return None%0A%0A%09@staticmethod%09%0A%09def closeConnection(self, connectionName):%0A%09%09if type(connectionName) == str:%0A%09%09%09_connections%5BconnectionName%5D.session.close()%0A%09%09%09_connections.close()%0A%09%09%09del _connections%5BconnectionName%5D%0A%09%09else:%0A%09%09%09raise ValueError(%22connectionName must be of type str, not %25s%22, type(name))%0A%0Aclass DatabaseConnection():%0A%09def __init__(self, connectionString):%0A%09%09self.connectionString = configs%5B'connection_string'%5D%0A%09%09self.engine = sqlalchemy.create_engine(bind = self.connectionString)%0A%09%09self._Session = sqlalchemy.orm.create_session(bind = engine)%0A%09%09self.session = Session()%0A%09%09%0A%09def getSelectedDatabase(self):%0A%09%09result = session.execute(%22SELECT DATABASE()%22).fetchone()%0A%09%09if result != None:%0A%09%09%09return result%5B0%5D%0A%09%09return None%0A
5dfb7ad67216b31544c5f4dc785930ef0d9ffd56
add faceAssigned tester
python/medic/plugins/Tester/faceAssigned.py
python/medic/plugins/Tester/faceAssigned.py
Python
0
@@ -0,0 +1,810 @@ +from medic.core import testerBase%0Afrom maya import OpenMaya%0A%0A%0Aclass FaceAssigned(testerBase.TesterBase):%0A Name = %22FaceAssigned%22%0A%0A def __init__(self):%0A super(FaceAssigned, self).__init__()%0A%0A def Match(self, node):%0A return node.object().hasFn(OpenMaya.MFn.kDagNode)%0A%0A def Test(self, node):%0A inst_grp = node.dg().findPlug(%22instObjGroups%22, True)%0A if not inst_grp:%0A return False%0A%0A obj_grp = None%0A%0A for i in range(inst_grp.numChildren()):%0A child = inst_grp.child(i)%0A if child.partialName() == %22iog%5B-1%5D.og%22:%0A obj_grp = child%0A break%0A%0A if not obj_grp:%0A return False%0A%0A if obj_grp.numConnectedElements() %3E 0:%0A return True%0A%0A return False%0A%0A%0ATester = FaceAssigned%0A
971570b4288c9ac7131a1756e17574acbe6d1b9a
Add script for converting a solarized dark file to solarized dark high contrast
python/misc/solarized-dark-high-contrast.py
python/misc/solarized-dark-high-contrast.py
Python
0
@@ -0,0 +1,2126 @@ +#!/usr/bin/env python%0A%0Aimport sys%0A%0Aif sys.version_info %3C (3, 4):%0A sys.exit('ERROR: Requires Python 3.4')%0A%0Afrom enum import Enum%0A%0Adef main():%0A Cases = Enum('Cases', 'lower upper')%0A infile_case = None%0A %0A if len(sys.argv) %3C 2:%0A sys.stderr.write('ERROR: Must provide a file to modify%5Cn')%0A sys.exit('Usage: %7B%7D FILE'.format(sys.argv%5B0%5D))%0A %0A # Keep these in lists instead of a dict to preserve ordering%0A color_codes_dark = %5B%0A 'eee8d5',%0A '93a1a1',%0A '839496',%0A '657b83',%0A '586e75',%0A %5D%0A color_codes_dark_high_contrast = %5B%0A 'fdf6e3',%0A 'eee8d5',%0A '93a1a1',%0A '839496',%0A '657b83',%0A %5D%0A %0A with open(sys.argv%5B1%5D, 'r') as infile:%0A outfile_data = infile.read()%0A %0A # Figure out whether the input is using upper or lower case color codes%0A for color_code in color_codes_dark:%0A # Skip color codes that don't contain letters%0A if color_code.lower() == color_code.upper():%0A continue%0A if outfile_data.find(color_code.lower()) != -1:%0A infile_case = Cases.lower%0A # Use the first one we find as the decisive case%0A break%0A elif outfile_data.find(color_code.upper()) != -1:%0A infile_case = Cases.upper%0A break%0A %0A for i in range(len(color_codes_dark)):%0A if infile_case == Cases.lower:%0A outfile_data = outfile_data.replace(color_codes_dark%5Bi%5D.lower(), color_codes_dark_high_contrast%5Bi%5D.lower())%0A outfile_data = outfile_data.replace(color_codes_dark%5Bi%5D.upper(), color_codes_dark_high_contrast%5Bi%5D.lower())%0A elif infile_case == Cases.upper:%0A outfile_data = outfile_data.replace(color_codes_dark%5Bi%5D.lower(), color_codes_dark_high_contrast%5Bi%5D.upper())%0A outfile_data = outfile_data.replace(color_codes_dark%5Bi%5D.upper(), color_codes_dark_high_contrast%5Bi%5D.upper())%0A %0A with open('%7B%7D-high-contrast.%7B%7D'.format(*sys.argv%5B1%5D.rsplit('.', 1)), 'w') as outfile:%0A outfile.write(outfile_data)%0A%0A%0Aif __name__ == '__main__':%0A main()
b72c421696b5714d256b7ac461833bc692ca5354
Add an autonomous mode to strafe and shoot. Doesn't work
robot/robot/src/autonomous/hot_aim_shoot.py
robot/robot/src/autonomous/hot_aim_shoot.py
Python
0.000002
@@ -0,0 +1,3122 @@ +%0D%0Atry:%0D%0A import wpilib%0D%0Aexcept ImportError:%0D%0A from pyfrc import wpilib%0D%0A%0D%0Aimport timed_shoot%0D%0A%0D%0Aclass HotShootAutonomous(timed_shoot.TimedShootAutonomous):%0D%0A '''%0D%0A Based on the TimedShootAutonomous mode. Modified to allow%0D%0A shooting based on whether the hot goal is enabled or not.%0D%0A '''%0D%0A %0D%0A DEFAULT = False%0D%0A MODE_NAME = %22Hot Aim shoot%22%0D%0A%0D%0A def __init__(self, components):%0D%0A super().__init__(components)%0D%0A %0D%0A wpilib.SmartDashboard.PutNumber('DriveStrafeSpeed', 0.5)%0D%0A wpilib.SmartDashboard.PutBoolean('IsHotLeft', False)%0D%0A wpilib.SmartDashboard.PutBoolean('IsHotRight', False)%0D%0A%0D%0A def on_enable(self):%0D%0A '''these are called when autonomous starts'''%0D%0A %0D%0A super().on_enable()%0D%0A %0D%0A self.drive_strafe_speed = wpilib.SmartDashboard.GetNumber('DriveStrafeSpeed')%0D%0A %0D%0A print(%22-%3E Drive strafe:%22, self.drive_strafe_speed)%0D%0A %0D%0A self.decided = False%0D%0A self.start_time = None%0D%0A %0D%0A def on_disable(self):%0D%0A '''This function is called when autonomous mode is disabled'''%0D%0A pass%0D%0A%0D%0A def update(self, time_elapsed): %0D%0A '''The actual autonomous program''' %0D%0A %0D%0A %0D%0A # decide if it's hot or not%0D%0A if not self.decided:%0D%0A self.hotLeft = wpilib.SmartDashboard.GetBoolean(%22IsHotLeft%22)%0D%0A self.hotRight = wpilib.SmartDashboard.GetBoolean(%22IsHotRight%22)%0D%0A %0D%0A if (self.hotLeft or self.hotRight) and not (self.hotLeft and self.hotRight):%0D%0A self.decided = True%0D%0A %0D%0A if self.hotLeft:%0D%0A self.drive_strafe_speed *= -1%0D%0A %0D%0A elif time_elapsed %3E 6:%0D%0A # at 6 seconds, give up and shoot anyways%0D%0A self.decided = True%0D%0A %0D%0A %0D%0A # always keep the arm down%0D%0A self.intake.armDown()%0D%0A %0D%0A # wait a split second for the arm to come down, then%0D%0A # keep bringing the catapult down so we're ready to go%0D%0A if time_elapsed %3E 0.3:%0D%0A self.catapult.pulldown()%0D%0A %0D%0A %0D%0A # wait some period before we start driving%0D%0A if time_elapsed %3C self.drive_wait:%0D%0A pass%0D%0A %0D%0A else:%0D%0A %0D%0A if self.decided:%0D%0A %0D%0A # only set this once, so we can calculate time from this%0D%0A # point on %0D%0A if self.start_time is None:%0D%0A self.start_time = time_elapsed%0D%0A %0D%0A %0D%0A time_elapsed = time_elapsed - self.start_time%0D%0A %0D%0A if time_elapsed %3C self.drive_time:%0D%0A # Drive slowly forward for N seconds%0D%0A self.drive.move(self.drive_strafe_speed, self.drive_speed, 0)%0D%0A %0D%0A %0D%0A elif time_elapsed %3C self.drive_time + 1.0:%0D%0A # Finally, fire and keep firing for 1 seconds%0D%0A self.catapult.launchNoSensor()%0D%0A
3c046062af376603145545f37b917a5c927b3aba
Create mergesort_recursive.py
recursive_algorithms/mergesort_recursive.py
recursive_algorithms/mergesort_recursive.py
Python
0.000004
@@ -0,0 +1,622 @@ +def merge_sort(array):%0A temp = %5B%5D%0A if( len(array) == 1):%0A return array;%0A %0A half = len(array) / 2%0A lower = merge_sort(array%5B:half%5D)%0A upper = merge_sort(array%5Bhalf:%5D)%0A lower_len = len(lower)%0A upper_len = len(upper)%0A i = 0%0A j = 0%0A while i != lower_len or j != upper_len:%0A if( i != lower_len and (j == upper_len or lower%5Bi%5D %3C upper%5Bj%5D)):%0A temp.append(lower%5Bi%5D)%0A i += 1%0A else:%0A temp.append(upper%5Bj%5D)%0A j += 1%0A%0A return temp%0A%0A %0Aarray = %5B11, 12, 3, 28, 41, 62,16, 10%5D%0Aar = merge_sort(array)%0Aprint %22 %22.join(str(x) for x in ar)%0A
06b0f93ecd5fac8eda02fce96c1e4ec0306a7989
Increase coverage
test/test_google.py
test/test_google.py
Python
0
@@ -0,0 +1,2173 @@ +# -*- coding: utf8 -*-%0A# This file is part of PyBossa.%0A#%0A# Copyright (C) 2013 SF Isle of Man Limited%0A#%0A# PyBossa is free software: you can redistribute it and/or modify%0A# it under the terms of the GNU Affero General Public License as published by%0A# the Free Software Foundation, either version 3 of the License, or%0A# (at your option) any later version.%0A#%0A# PyBossa is distributed in the hope that it will be useful,%0A# but WITHOUT ANY WARRANTY; without even the implied warranty of%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the%0A# GNU Affero General Public License for more details.%0A#%0A# You should have received a copy of the GNU Affero General Public License%0A# along with PyBossa. If not, see %3Chttp://www.gnu.org/licenses/%3E.%0Afrom base import web, model, Fixtures%0Aimport pybossa.view.google as google%0A%0A%0Aclass TestGoogle:%0A def setUp(self):%0A self.app = web.app%0A model.rebuild_db()%0A Fixtures.create()%0A%0A def test_manage_user(self):%0A %22%22%22Test GOOGLE manage_user works.%22%22%22%0A with self.app.test_request_context('/'):%0A # First with a new user%0A user_data = dict(id='1', name='google',%0A email='[email protected]')%0A token = 't'%0A user = google.manage_user(token, user_data, None)%0A assert user.email_addr == user_data%5B'email'%5D, user%0A assert user.name == user_data%5B'name'%5D, user%0A assert user.fullname == user_data%5B'name'%5D, user%0A assert user.google_user_id == user_data%5B'id'%5D, user%0A%0A # Second with the same user%0A user = google.manage_user(token, user_data, None)%0A assert user.email_addr == user_data%5B'email'%5D, user%0A assert user.name == user_data%5B'name'%5D, user%0A assert user.fullname == user_data%5B'name'%5D, user%0A assert user.google_user_id == user_data%5B'id'%5D, user%0A%0A # Finally with a user that already is in the system%0A user_data = dict(id='10', name=Fixtures.name,%0A email=Fixtures.email_addr)%0A token = 'tA'%0A user = google.manage_user(token, user_data, None)%0A assert user is None%0A
17e2b9ecb67c8b1f3a6f71b752bc70b21584092e
Add initial tests for scriptserver.
tests/test_scriptserver.py
tests/test_scriptserver.py
Python
0
@@ -0,0 +1,2156 @@ +import unittest%0Afrom mock import patch, Mock%0A%0Aimport sys%0Asys.path.append(%22.%22)%0Afrom scriptserver import ZoneScriptRunner%0A%0Aclass TestZoneScriptRunner(unittest.TestCase):%0A @classmethod%0A def setUpClass(cls):%0A cls.mongoengine_patch = patch('scriptserver.me')%0A cls.mongoengine_patch.start()%0A%0A @classmethod%0A def tearDownClass(cls):%0A cls.mongoengine_patch.stop()%0A%0A def test___init__(self):%0A zoneid = %22zoneid%22%0A with patch('scriptserver.Object'):%0A with patch.object(ZoneScriptRunner, 'load_scripts') as mock_load_scripts:%0A zone_script_runner = ZoneScriptRunner(zoneid)%0A self.assertTrue(zone_script_runner)%0A self.assertEqual(1, mock_load_scripts.call_count)%0A%0A def test_load_scripts(self):%0A expected = %7B%7D%0A zoneid = %22zoneid%22%0A with patch.object(ZoneScriptRunner, 'load_scripts'):%0A with patch('scriptserver.Object'):%0A zone_script_runner = ZoneScriptRunner(zoneid)%0A%0A with patch('scriptserver.ScriptedObject') as ScriptedObject:%0A MockThing = Mock()%0A with patch.dict('sys.modules', %7B'thing': MockThing, 'thing.fake': MockThing.fake,%0A 'thing.fake.chicken': MockThing.fake.chicken%7D):%0A MockThing.fake.chicken.Chicken.tick = Mock()%0A MockScriptedObject = Mock()%0A MockScriptedObject.scripts = %5B'thing.fake.chicken'%5D%0A ScriptedObject.objects.return_value = %5BMockScriptedObject%5D%0A result = zone_script_runner.load_scripts()%0A%0A self.assertNotEqual(expected, result)%0A self.assertIn('thing.fake.chicken', result)%0A%0A def test_start(self):%0A # zone_script_runner = ZoneScriptRunner(zoneid)%0A # self.assertEqual(expected, zone_script_runner.start())%0A pass # TODO: implement your test here%0A%0A def test_tick(self):%0A # zone_script_runner = ZoneScriptRunner(zoneid)%0A # self.assertEqual(expected, zone_script_runner.tick())%0A pass # TODO: implement your test here%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
e5243d0fb792e82825633f1afdd6e799238a90f3
Add portable buildtools update script (#46)
tools/buildtools/update.py
tools/buildtools/update.py
Python
0
@@ -0,0 +1,1345 @@ +#!/usr/bin/python%0D%0A# Copyright 2017 The Chromium Authors. All rights reserved.%0D%0A# Use of this source code is governed by a BSD-style license that can be%0D%0A# found in the LICENSE file.%0D%0A%0D%0A%22%22%22Pulls down tools required to build flutter.%22%22%22%0D%0A%0D%0Aimport os%0D%0Aimport subprocess%0D%0Aimport sys%0D%0A%0D%0ASRC_ROOT = (os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))%0D%0ABUILDTOOLS = os.path.join(SRC_ROOT, 'buildtools')%0D%0A%0D%0Asys.path.insert(0, os.path.join(SRC_ROOT, 'tools'))%0D%0Aimport find_depot_tools%0D%0A%0D%0ADEPOT_PATH = find_depot_tools.add_depot_tools_to_path()%0D%0A%0D%0A%0D%0Adef Update():%0D%0A path = os.path.join(BUILDTOOLS, 'update.sh')%0D%0A return subprocess.call(%5B'/bin/bash', path, '--toolchain', '--gn'%5D, cwd=SRC_ROOT)%0D%0A%0D%0A%0D%0Adef UpdateOnWindows():%0D%0A sha1_file = os.path.join(BUILDTOOLS, 'win', 'gn.exe.sha1')%0D%0A downloader_script = os.path.join(DEPOT_PATH, 'download_from_google_storage.py')%0D%0A download_cmd = %5B%0D%0A 'python',%0D%0A downloader_script,%0D%0A '--no_auth',%0D%0A '--no_resume',%0D%0A '--quiet',%0D%0A '--platform=win*',%0D%0A '--bucket',%0D%0A 'chromium-gn',%0D%0A '-s',%0D%0A sha1_file%0D%0A %5D%0D%0A return subprocess.call(download_cmd)%0D%0A%0D%0A%0D%0Adef main(argv):%0D%0A if sys.platform.startswith('win'):%0D%0A return UpdateOnWindows()%0D%0A return Update()%0D%0A%0D%0A%0D%0Aif __name__ == '__main__':%0D%0A sys.exit(main(sys.argv))%0D%0A
d1f02226fe805fb80a17f1d22b84b748b65b4e7f
add sam2fq.py
sam2fq.py
sam2fq.py
Python
0.001125
@@ -0,0 +1,994 @@ +import sys%0Afrom collections import namedtuple%0A%0ARead = namedtuple('Read', %5B'name','qual','seq'%5D)%0A%0Aread1 = None%0Aleft = open('pe_1.fq', 'w')%0Aright = open('pe_2.fq', 'w')%0Aunpaired = open('unpaired.fq', 'w')%0Afor line in sys.stdin:%0A items = line.split('%5Ct')%0A name, qual, seq = items%5B0%5D, items%5B10%5D, items%5B9%5D%0A if not read1:%0A read1 = Read(name, qual, seq)%0A continue%0A else:%0A read2 = Read(name, qual, seq)%0A%0A if read1.name == read2.name:%0A print read1.name, '%3C--%3E', read2.name%0A #print %3E%3E left, '@%25s%5Cn%25s%5Cn+%5Cn%25s' %25 (read1.name, read1.seq, read1.qual)%0A #print %3E%3E right, '@%25s%5Cn%25s%5Cn+%5Cn%25s' %25 (read2.name, read2.seq, read2.qual)%0A read1 = None%0A else:%0A print read1.name%0A #print %3E%3E unpaired, '@%25s%5Cn%25s%5Cn+%5Cn%25s' %25 (read1.name, read1.seq, read1.qual)%0A read1 = read2%0A read2 = None%0A%0Aif read1:%0A print read1.name%0A #print %3E%3E unpaired, '@%25s%5Cn%25s%5Cn+%5Cn%25s' %25 (read1.name, read1.seq, read1.qual)%0A read1 = read2%0A read2 = None%0A
dbdfb1b5a703e0392ca67a03113e607678015a66
add kattis/settlers2
Kattis/settlers2.py
Kattis/settlers2.py
Python
0.001804
@@ -0,0 +1,2176 @@ +%22%22%22%0AProblem: settlers2%0ALink: https://open.kattis.com/problems/settlers2%0ASource: NWERC 2009%0A%22%22%22%0Afrom collections import defaultdict%0Aimport math%0A%0AMAXN = 10000%0A%0AcurrentPosition = (0,0)%0AcurrentNum = 1%0Acounter = defaultdict()%0Alayers = 1%0Adirection = 0%0AdirectionCounter = 0%0AlimitDirectionCounter = %5Blayers, layers-1, layers, layers, layers, layers%5D%0AtransitionVectors = %5B(-1,1), (-2,0), (-1,-1), (1,-1), (2,0), (1,1)%5D%0AnMoves = 0%0A%0AtilesMap = dict()%0AtilesMap%5BcurrentPosition%5D = currentNum%0AtilesList = %5BNone, currentNum%5D%0Afor num in %5B1,2,3,4,5%5D: counter%5Bnum%5D = 0%0Acounter%5BcurrentNum%5D += 1%0A%0A%0Adef add(position, vector):%0A return (position%5B0%5D + vector%5B0%5D, position%5B1%5D + vector%5B1%5D)%0A%0A# Preprocess%0Awhile len(tilesList) - 1 %3C MAXN:%0A currentPosition = add(currentPosition, transitionVectors%5Bdirection%5D)%0A directionCounter += 1%0A while limitDirectionCounter%5Bdirection%5D == directionCounter:%0A # Increase limit counter for next round%0A limitDirectionCounter%5Bdirection%5D += 1%0A%0A # Change direction%0A direction = (direction + 1) %25 len(transitionVectors)%0A%0A # Reset direction counter%0A directionCounter = 0%0A%0A%0A neighbors = %5Badd(currentPosition, transitionVector) for transitionVector in transitionVectors%5D%0A possibilities = set(%5B1,2,3,4,5%5D)%0A%0A # Eliminate similar tiles%0A for neighbor in neighbors:%0A if neighbor in tilesMap and tilesMap%5Bneighbor%5D in possibilities:%0A possibilities.remove(tilesMap%5Bneighbor%5D)%0A%0A # Keep only the least number of tiles%0A minCounter = math.inf%0A for possibility in possibilities:%0A minCounter = min(minCounter, counter%5Bpossibility%5D)%0A possibilityToRemove = %5B%5D%0A for possibility in possibilities:%0A if counter%5Bpossibility%5D != minCounter:%0A possibilityToRemove.append(possibility)%0A for possibility in possibilityToRemove:%0A possibilities.remove(possibility)%0A%0A # Sort by number%0A possibilities = sorted(possibilities)%0A%0A currentNum = possibilities%5B0%5D%0A tilesMap%5BcurrentPosition%5D = currentNum%0A tilesList.append(currentNum)%0A counter%5BcurrentNum%5D += 1%0A%0A# Post-process%0AC = int(input())%0Afor i in range(C):%0A n = int(input())%0A print(tilesList%5Bn%5D)%0A
48443f8a8f5a15b3116ba7b4a842189f5e659f26
test script for pymatbridge
test_pymatbridge.py
test_pymatbridge.py
Python
0
@@ -0,0 +1,249 @@ +#!/usr/bin/python%0A%0Afrom pymatbridge import Matlab%0A%0Amlab = Matlab()%0Amlab.start()%0Aprint %22Matlab started?%22, mlab.started%0Aprint %22Matlab is connected?%22, mlab.is_connected()%0A%0Amlab.run_code(%22conteo = 1:10%22)%0Amlab.run_code(%22magica = magic(5)%22)%0A%0Amlab.stop()%0A%0A
4d08d50d73e8d3d3a954c9ef8ddffc23444d7d28
Create script.py
script.py
script.py
Python
0.000002
@@ -0,0 +1,817 @@ +#!/usr/bin/env python3%0A%0A# premi%C3%A8re tentative de documenter l'API de coco.fr%0A%0Aimport random%0Aimport requests%0A%0Apseudo = %22caecilius%22 # doit %C3%AAtre en minuscule et de plus de 4 caract%C3%A8res%0Aage = %2222%22 # minimum %2218%22%0Asexe = %221%22 # %221%22 pour homme, %222%22 pour femme%0A%0Acodeville = %2230929%22 # %C3%A0 r%C3%A9cuperer ici http://coco.fr/cocoland/foo.js par exemple pour Paris 15 :%0A # http://coco.fr/cocoland/75015.js va donner %22var cityco='30929*PARIS*'; procecodo();%22%0A # le codeville est donc %2230929%22%0A%0Areferenz = %220%22 # aucune id%C3%A9e de ce que %C3%A7a fait, pour l'instant la valeur est toujours %220%22%0A%0Asalt = str(random.randrange(100000000, 999999999))%0A%0Aurl = str(%22http://coco.fr#%22 + pseudo + %22_%22 + sexe + %22_%22 + age + %22_%22 + codeville + %22_0_%22 + salt + %22_%22 + referenz)%0A%0Ar = requests.get(url)%0A
dbacf8cd0c2bae394b6c67a810836668d510787d
test for index (re)generation
tests/test_index.py
tests/test_index.py
Python
0
@@ -0,0 +1,1280 @@ +from cheeseprism.utils import resource_spec%0Afrom itertools import count%0Afrom path import path%0Afrom pprint import pprint%0Aimport unittest%0A%0A%0Aclass IndexTestCase(unittest.TestCase):%0A counter = count()%0A base = %22egg:CheesePrism#tests/test-indexes%22%0A %0A def make_one(self, index_name='test-index'):%0A from cheeseprism import index%0A index_path = path(resource_spec(self.base)) / %22%25s-%25s%22 %25(next(self.counter), index_name) %0A return index.IndexManager(index_path)%0A%0A def setUp(self):%0A self.im = self.make_one()%0A dummy = path(__file__).parent / %22dummypackage/dist/dummypackage-0.0dev.tar.gz%22%0A dummy.copy(self.im.path)%0A self.dummypath = self.im.path / dummy.name%0A%0A def test_regenerate_index(self):%0A self.im.regenerate(self.im.path)%0A pth = self.im.path%0A file_structure = %5B(x.parent.name, x.name) for x in pth.walk()%5D%0A expected = %5B(u'0-test-index', u'dummypackage'),%0A (u'dummypackage', u'index.html'),%0A (u'0-test-index', u'dummypackage-0.0dev.tar.gz'),%0A (u'0-test-index', u'index.html')%5D%0A assert file_structure == expected, %22File structure does not match:%5Cnexpected: %25s.%5Cn actual: %25s%22 %25(pprint(expected), pprint(file_structure))%0A%0A %0A
554c6490330760690fbbd1cd5ece3da563e342eb
update queen4.py
python/queen4.py
python/queen4.py
Python
0.000001
@@ -0,0 +1,384 @@ +f = lambda A, x, y: y %3C 0 or (not (A%5By%5D in (A%5Bx%5D, A%5Bx%5D + (x - y), A%5Bx%5D - (x - y))))%0D%0Ag = lambda A, x, y: (not x) or (f(A, x, y) and ((y %3C 0) or g(A, x, y - 1)))%0D%0Ah = lambda A, x: sum(%5B g(A, x, x - 1) and 1 or 0 for A%5Bx%5D in range(len(A)) %5D)%0D%0Aq = lambda A, x: h(A, x) if (x == 7) else sum(%5B q(A, x + 1) for A%5Bx%5D in range(8) if g(A, x, x - 1) %5D)%0D%0A%0D%0Aprint(q(%5B 0 for i in range(8) %5D, 0))%0D%0A
076fcbb4876bd76887f7d64b533fec66f8366b70
Add tests for cancellation
openprocurement/tender/esco/tests/cancellation.py
openprocurement/tender/esco/tests/cancellation.py
Python
0
@@ -0,0 +1,2582 @@ +# -*- coding: utf-8 -*-%0Aimport unittest%0A%0Afrom openprocurement.api.tests.base import snitch%0A%0Afrom openprocurement.tender.belowthreshold.tests.cancellation import (%0A TenderCancellationResourceTestMixin,%0A TenderCancellationDocumentResourceTestMixin%0A)%0Afrom openprocurement.tender.belowthreshold.tests.cancellation_blanks import (%0A # TenderLotsCancellationResourceTest%0A create_tender_lots_cancellation,%0A patch_tender_lots_cancellation,%0A # TenderLotCancellationResourceTest%0A create_tender_lot_cancellation,%0A patch_tender_lot_cancellation,%0A)%0A%0Afrom openprocurement.tender.openua.tests.cancellation_blanks import (%0A # TenderCancellationResourceTest%0A create_tender_cancellation,%0A patch_tender_cancellation,%0A)%0A%0Afrom openprocurement.tender.esco.tests.base import (%0A BaseESCOEUContentWebTest,%0A test_bids,%0A test_lots%0A)%0A%0A%0Aclass TenderCancellationResourceTest(BaseESCOEUContentWebTest, TenderCancellationResourceTestMixin):%0A%0A initial_auth = ('Basic', ('broker', ''))%0A%0A test_create_tender_cancellation = snitch(create_tender_cancellation)%0A test_patch_tender_cancellation = snitch(patch_tender_cancellation)%0A%0A%0Aclass TenderLotCancellationResourceTest(BaseESCOEUContentWebTest):%0A initial_lots = test_lots%0A%0A initial_auth = ('Basic', ('broker', ''))%0A%0A test_create_tender_cancellation = snitch(create_tender_lot_cancellation)%0A test_patch_tender_cancellation = snitch(patch_tender_lot_cancellation)%0A%0A%0Aclass TenderLotsCancellationResourceTest(BaseESCOEUContentWebTest):%0A initial_lots = 2 * test_lots%0A%0A initial_auth = ('Basic', ('broker', ''))%0A test_create_tender_cancellation = snitch(create_tender_lots_cancellation)%0A test_patch_tender_cancellation = snitch(patch_tender_lots_cancellation)%0A%0A%0Aclass TenderCancellationDocumentResourceTest(BaseESCOEUContentWebTest, TenderCancellationDocumentResourceTestMixin):%0A%0A initial_auth = ('Basic', ('broker', ''))%0A%0A def setUp(self):%0A super(TenderCancellationDocumentResourceTest, self).setUp()%0A # Create cancellation%0A response = self.app.post_json('/tenders/%7B%7D/cancellations?acc_token=%7B%7D'.format(%0A self.tender_id, self.tender_token), %7B'data': %7B'reason': 'cancellation reason'%7D%7D)%0A cancellation = response.json%5B'data'%5D%0A self.cancellation_id = cancellation%5B'id'%5D%0A%0A%0Adef suite():%0A suite = unittest.TestSuite()%0A suite.addTest(unittest.makeSuite(TenderCancellationDocumentResourceTest))%0A suite.addTest(unittest.makeSuite(TenderCancellationResourceTest))%0A return suite%0A%0A%0Aif __name__ == '__main__':%0A unittest.main(defaultTest='suite')%0A
abe586ac1275901fc9d9cf1bde05b225a9046ab7
add admin tests
test/test_admin.py
test/test_admin.py
Python
0
@@ -0,0 +1,2112 @@ +from werkzeug.exceptions import Unauthorized%0Afrom flask import url_for%0Afrom flask_login import current_user%0A%0Afrom .conftest import logged_in, assert_logged_in, assert_not_logged_in, create_user%0Afrom app.user import random_string%0Afrom app.form.login import ERROR_ACCOUNT_DISABLED%0A%0A%0AUSERNAME = 'cyberwehr87654321'%0APASSWORD = random_string()%0AEMAIL = '%7B%[email protected]'.format(USERNAME)%0A%0A%0A@create_user(username=USERNAME, password=PASSWORD)%0A@logged_in%0Adef test_delete_user(db, client):%0A resp = client.post(url_for('delete_user', username=USERNAME), follow_redirects=True,%0A data=dict(confirm='confirm'))%0A resp = client.post(url_for('logout'), follow_redirects=True)%0A assert_not_logged_in(resp)%0A%0A resp = client.post(url_for('login'), follow_redirects=True,%0A data=dict(username=USERNAME, password=PASSWORD))%0A assert_not_logged_in(resp, status_code=Unauthorized.code)%0A%0A%0A@logged_in%0Adef test_create_user(db, client):%0A resp = client.post(url_for('create_user'), follow_redirects=True,%0A data=dict(username=USERNAME, password=PASSWORD,%0A email=EMAIL, active=True))%0A assert resp.status_code == 200%0A%0A resp = client.post(url_for('logout'), follow_redirects=True)%0A assert_not_logged_in(resp)%0A%0A resp = client.post(url_for('login'), follow_redirects=True,%0A data=dict(username=USERNAME, password=PASSWORD))%0A assert_logged_in(resp)%0A assert USERNAME == current_user.name%0A%0A%0A@create_user(username=USERNAME, password=PASSWORD)%0A@logged_in%0Adef test_edit_user(db, client):%0A resp = client.post(url_for('edit_user', username=USERNAME), follow_redirects=True,%0A data=dict(username=USERNAME, email=EMAIL, password=PASSWORD))%0A assert resp.status_code == 200%0A%0A resp = client.post(url_for('logout'), follow_redirects=True)%0A assert_not_logged_in(resp)%0A%0A resp = client.post(url_for('login'), data=%7B'username': USERNAME, 'password': PASSWORD%7D)%0A assert_not_logged_in(resp, status_code=Unauthorized.code)%0A assert ERROR_ACCOUNT_DISABLED in resp.data.decode()%0A
b63e65b1a41f809caf1c2dcd689955df76add20f
Add a plot just of backscatter phase vs. diameter.
test/test_delta.py
test/test_delta.py
Python
0
@@ -0,0 +1,1140 @@ +import matplotlib.pyplot as plt%0Aimport numpy as np%0Aimport scattering%0Aimport scipy.constants as consts%0A%0Adef plot_csec(scatterer, d, var, name):%0A plt.plot(d / consts.centi, var,%0A label='%25.1f cm' %25 (scatterer.wavelength / consts.centi))%0A plt.xlabel('Diameter (cm)')%0A plt.ylabel(name)%0A%0Adef plot_csecs(d, scatterers):%0A for s in scatterers:%0A plt.subplot(1,1,1)%0A plot_csec(s, d, np.rad2deg(np.unwrap(-np.angle(-s.S_bkwd%5B0,0%5D.conj() *%0A s.S_bkwd%5B1,1%5D).squeeze())), 'delta')%0A plt.gca().set_ylim(-4, 20)%0A%0Ad = np.linspace(0.01, 0.7, 200).reshape(200, 1) * consts.centi%0Asband = 3e8 / 2.8e9%0Acband = 3e8 / 5.4e9%0Axband = 3e8 / 9.4e9%0A%0Atemp = 10.0%0A%0Ax_fixed = scattering.scatterer(xband, temp, 'water', diameters=d, shape='oblate')%0Ax_fixed.set_scattering_model('tmatrix')%0A%0Ac_fixed = scattering.scatterer(cband, temp, 'water', diameters=d, shape='oblate')%0Ac_fixed.set_scattering_model('tmatrix')%0A%0As_fixed = scattering.scatterer(sband, temp, 'water', diameters=d, shape='oblate')%0As_fixed.set_scattering_model('tmatrix')%0A%0Aplot_csecs(d, %5Bx_fixed, c_fixed, s_fixed%5D)%0Aplt.legend(loc = 'upper left')%0Aplt.show()%0A
55768b5133d8155b16e798a335cc0f46930aab12
create my own .py for question 5
totaljfb/Q5.py
totaljfb/Q5.py
Python
0.000092
@@ -0,0 +1,1828 @@ +#-------------------------------------------------------------------------------%0A# Name: module1%0A# Purpose:%0A#%0A# Author: Jason Zhang%0A#%0A# Created: 15/11/2017%0A# Copyright: (c) Jason Zhang 2017%0A# Licence: %3Cyour licence%3E%0A#-------------------------------------------------------------------------------%0A%0Adef main():%0A pass%0A%0Aif __name__ == '__main__':%0A main()%0Aimport re%0A%0A#create a URL class%0Aclass URL:%0A def __init__(self, url_scheme, url_netloc, url_path, url_query_params, url_fragment):%0A self.scheme = url_scheme%0A self.netloc = url_netloc%0A self.path = url_path%0A self.query_params = url_query_params%0A self.fragment = url_fragment%0A def display_result(self):%0A print 'scheme: ' + self.scheme%0A print 'netloc: ' + self.netloc%0A print 'path: ' + self.path%0A print 'query_params: '+ self.query_params%0A print 'fragment: '+ self.fragment%0A%0A#the parsing function to parse the url address%0Adef url_parse(url):%0A regex = re.compile(r'''(%0A %5Cw*) #scheme%0A :%5C/%5C/ #://, separator%0A (.*) #netloc%0A (%5C/.*) #path%0A %5C? #?, separator%0A (.*) #query_params%0A %5C# # #, separator%0A (.* #fragment%0A )''',re.VERBOSE)%0A result = regex.search(url)%0A #TODO: parse the query_params to get a dictionary%0A return URL(result.group(1),result.group(2),result.group(3),result.group(4),result.group(5))%0A%0A%0Aurl = raw_input(%22Enter an url address to parse: %22)%0Atest = url_parse(url)%0Atest.display_result()%0A%0A
3cb42b54fa8ed2cac6e05aa521a3a61a037a35ee
add rest cliant on python
rest/client.py
rest/client.py
Python
0
@@ -0,0 +1,376 @@ +# pip install requests%0Aimport requests%0Aresp = requests.post(%22http://127.0.0.1:8008/api/v1/addrecord/3%22, json='%7B%22id%22:%22name%22%7D')%0Aprint resp.status_code%0Aprint resp.text%0A%0Aresp = requests.get(%22http://127.0.0.1:8008/api/v1/getrecord/3%22)%0Aprint resp.status_code%0Aprint resp.json()%0A%0Aresp = requests.get(%22http://127.0.0.1:8008/api/v1/getrecord/4%22)%0Aprint resp.status_code%0Aprint resp.json()
277f026f96ba94b7c7fa0ba3cde4c6e425fe4853
Make use of the cached decorator instead of manually memoizing get_style
rinoh/style.py
rinoh/style.py
# This file is part of RinohType, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. """ Base classes and exceptions for styled document elements. * :class:`Style`: Dictionary storing a set of style attributes * :class:`Styled`: A styled entity, having a :class:`Style` associated with it * :class:`StyleStore`: Dictionary storing a set of related `Style`s by name * :const:`PARENT_STYLE`: Special style that forwards style lookups to the parent :class:`Styled` * :exc:`ParentStyleException`: Thrown when style attribute lookup needs to be delegated to the parent :class:`Styled` """ from .document import DocumentElement __all__ = ['Style', 'Styled', 'StyleStore', 'PARENT_STYLE', 'ParentStyleException'] class ParentStyleException(Exception): """Style attribute not found. Consult the parent :class:`Styled`.""" class DefaultValueException(Exception): """The attribute is not specified in this :class:`Style` or any of its base styles. Return the default value for the attribute.""" class Style(dict): """"Dictionary storing style attributes. Attrributes can also be accessed as attributes.""" attributes = {} """Dictionary holding the supported style attributes for this :class:`Style` class (keys) and their default values (values)""" def __init__(self, base=None, **attributes): """Style attributes are as passed as keyword arguments. Supported attributes include those defined in the :attr:`attributes` attribute of this style class and those defined in style classes this one inherits from. Optionally, a `base` (:class:`Style`) is passed, where attributes are looked up when they have not been specified in this style. Alternatively, if `base` is :class:`PARENT_STYLE`, the attribute lookup is forwarded to the parent of the element the lookup originates from. If `base` is a :class:`str`, it is used to look up the base style in the :class:`StyleStore` this style is stored in.""" self.base = base self.name = None self.store = None for attribute in attributes: if attribute not in self._supported_attributes(): raise TypeError('%s is not a supported attribute' % attribute) super().__init__(attributes) @property def base(self): """Return the base style for this style.""" if isinstance(self._base, str): return self.store[self._base] else: return self._base @base.setter def base(self, base): """Set this style's base to `base`""" self._base = base def __repr__(self): """Return a textual representation of this style.""" return '{0}({1}) > {2}'.format(self.__class__.__name__, self.name or '', self.base) def __copy__(self): copy = self.__class__(base=self.base, **self) if self.name is not None: copy.name = self.name + ' (copy)' copy.store = self.store return copy def __getattr__(self, attribute): return self[attribute] def __getitem__(self, attribute): """Return the value of `attribute`. If the attribute is not specified in this :class:`Style`, find it in this style's base styles (hierarchically), or ultimately return the default value for `attribute`.""" try: return self._recursive_get(attribute) except DefaultValueException: return self._get_default(attribute) def _recursive_get(self, attribute): """Recursively search for the value of `attribute`. If the attribute is not specified in this style, defer the lookup to the base style. When the attribute is specified nowhere in the chain of base styles, raise a :class:`DefaultValueException`. """ try: return super().__getitem__(attribute) except KeyError: if self.base is None: raise DefaultValueException return self.base._recursive_get(attribute) def _get_default(self, attribute): """Return the default value for `attribute`. If no default is specified in this style, get the default from the nearest superclass. If `attribute` is not supported, raise a :class:`KeyError`.""" try: for cls in self.__class__.__mro__: if attribute in cls.attributes: return cls.attributes[attribute] except AttributeError: raise KeyError("No attribute '{}' in {}".format(attribute, self)) def _supported_attributes(self): """Return a :class:`dict` of the attributes supported by this style class.""" attributes = {} for cls in reversed(self.__class__.__mro__): try: attributes.update(cls.attributes) except AttributeError: pass return attributes class ParentStyle(object): """Special style that delegates attribute lookups by raising a :class:`ParentStyleException` on each attempt to access an attribute.""" def __repr__(self): return self.__class__.__name__ def __getattr__(self, attribute): raise ParentStyleException def __getitem__(self, attribute): raise ParentStyleException PARENT_STYLE = ParentStyle() """Special style that forwards style lookups to the parent of the :class:`Styled` from which the lookup originates.""" class Styled(DocumentElement): """An element that has a :class:`Style` associated with it.""" style_class = None """The :class:`Style` subclass that corresponds to this :class:`Styled` subclass.""" def __init__(self, style=None, parent=None): """Associates `style` with this element. If `style` is `None`, an empty :class:`Style` is create, effectively using the defaults defined for the associated :class:`Style` class). A `parent` can be passed on object initialization, or later by assignment to the `parent` attribute.""" super().__init__(parent=parent) if style is None: style = self.style_class() if style != PARENT_STYLE and not isinstance(style, self.style_class): raise TypeError('the style passed to {0} should be of type {1}' .format(self.__class__.__name__, self.style_class.__name__)) self.style = style self.cached_style = {} def get_style(self, attribute): """Return `attribute` of the associated :class:`Style`. If this element's :class:`Style` or one of its bases is `PARENT_STYLE`, the style attribute is fetched from this element's parent.""" try: return self.cached_style[attribute] except KeyError: try: value = self.style[attribute] except ParentStyleException: value = self.parent.get_style(attribute) self.cached_style[attribute] = value return value class StyleStore(dict): """Dictionary storing a set of related :class:`Style`s by name. :class:`Style`s stored in a :class:`StyleStore` can refer to their base style by name. See :class:`Style`.""" def __setitem__(self, key, value): value.name = key value.store = self super().__setitem__(key, value)
Python
0.000001
@@ -851,16 +851,41 @@ Element%0A +from .util import cached%0A %0A%0A__all_ @@ -6823,39 +6823,20 @@ yle%0A - self.cached_style = %7B%7D%0A +%0A @cached %0A @@ -7100,102 +7100,8 @@ ry:%0A - return self.cached_style%5Battribute%5D%0A except KeyError:%0A try:%0A @@ -7134,28 +7134,24 @@ %5Battribute%5D%0A - exce @@ -7179,36 +7179,32 @@ on:%0A - value = self.par @@ -7232,61 +7232,8 @@ te)%0A - self.cached_style%5Battribute%5D = value%0A
d0f6167cb7e95c17997bc42af6cd1766b1ac7864
add related_name migration
paralapraca/migrations/0005_auto_20171204_1006.py
paralapraca/migrations/0005_auto_20171204_1006.py
Python
0.000002
@@ -0,0 +1,753 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('paralapraca', '0004_contract_classes'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='contract',%0A name='classes',%0A field=models.ManyToManyField(related_name='contract', to='core.Class'),%0A ),%0A migrations.AlterField(%0A model_name='contract',%0A name='groups',%0A field=models.ManyToManyField(help_text='Groups created to enforce this contract restrictions in several other models', related_name='contract', verbose_name='groups', to='auth.Group', blank=True),%0A ),%0A %5D%0A
e84d19bdc580f4d392f5b7abdc4eb8eb30919cf5
add example: negative binomial maximum likelihood via newton's method
examples/negative_binomial_maxlike.py
examples/negative_binomial_maxlike.py
Python
0.003656
@@ -0,0 +1,2041 @@ +from __future__ import division, print_function%0Aimport autograd.numpy as np%0Aimport autograd.numpy.random as npr%0Afrom autograd.scipy.special import gammaln%0Afrom autograd import grad%0A%0Aimport scipy.optimize%0A%0A%0A# The code in this example implements a method for finding a stationary point of%0A# the negative binomial likelihood via Newton's method, described here:%0A# https://en.wikipedia.org/wiki/Negative_binomial_distribution#Maximum_likelihood_estimation%0A%0A%0Adef newton(f, x0):%0A # wrap scipy.optimize.newton with our automatic derivatives%0A return scipy.optimize.newton(f, x0, fprime=grad(f), fprime2=grad(grad(f)))%0A%0A%0Adef negbin_loglike(r, p, x):%0A # the negative binomial log likelihood we want to maximize%0A return gammaln(r+x) - gammaln(r) - gammaln(x+1) + x*np.log(p) + r*np.log(1-p)%0A%0A%0Adef fit_maxlike(x, r_guess):%0A assert np.var(x) %3E np.mean(x), %22Likelihood-maximizing parameters don't exist!%22%0A loglike = lambda r, p: np.sum(negbin_loglike(r, p, x))%0A p = lambda r: np.sum(x) / np.sum(r+x)%0A rprime = lambda r: grad(loglike)(r, p(r))%0A r = newton(rprime, r_guess)%0A return r, p(r)%0A%0A%0Adef negbin_sample(r, p, size):%0A # a negative binomial is a gamma-compound-Poisson%0A return npr.poisson(npr.gamma(r, p/(1-p), size=size))%0A%0A%0Aif __name__ == %22__main__%22:%0A # generate data%0A npr.seed(0)%0A data = negbin_sample(r=5, p=0.5, size=1000)%0A%0A # fit likelihood-extremizing parameters%0A r, p = fit_maxlike(data, r_guess=1)%0A%0A print('Check that we are at a local stationary point:')%0A print(grad(lambda rp: np.sum(negbin_loglike(rp%5B0%5D, rp%5B1%5D, data)))((r, p)))%0A%0A print('Fit parameters:')%0A print('r=%7Br%7D, p=%7Bp%7D'.format(r=r, p=p))%0A%0A # plot data and fit%0A import matplotlib.pyplot as plt%0A xm = data.max()%0A plt.figure()%0A plt.hist(data, bins=np.arange(xm+1)-0.5, normed=True, label='normed data counts')%0A plt.xlim(0,xm)%0A plt.plot(np.arange(xm), np.exp(negbin_loglike(r, p, np.arange(xm))), label='maxlike fit')%0A plt.xlabel('k')%0A plt.ylabel('p(k)')%0A plt.legend(loc='best')%0A plt.show()%0A
6d96e9d67e50d7806be175577968ec8fed8393d7
Create libBase.py
test/libBase.py
test/libBase.py
Python
0.000001
@@ -0,0 +1,2440 @@ +# ./test/testCommon.py%0A''' There are some assumptions made by this unittest%0Athe directory structure%0A+ ./%0A%7C files -%3E lib*.py %0A+----./local/*%0A%7C %7C files -%3E *.ini%0A%7C %7C files -%3E *.json%0A%7C %7C files -%3E*.csv%0A+----./log/*%0A%7C %7C files -%3E *.log%0A+----./test/*%0A %7C files -%3E test*.py%0A +----./test_input/*%0A %7C see ../local%0A +----./test_output/*%0A'''%0Aimport sys%0Asys.path.append('../')%0Aimport logging as log%0Aimport unittest%0Aimport libCommon as TEST%0A%0Aclass TestFILL_IN_THE_BLANK(unittest.TestCase) :%0A def setUp(self) : pass%0A def testEnviron(self) :%0A log.debug(TEST.load_environ())%0A def FindFiles(self) :%0A log.debug(TEST.find_files('test*.py'))%0A log.debug(TEST.find_files('test_input/*'))%0A log.debug(TEST.find_files('test_input/'))%0A def testBuildArgs(self) :%0A expected = 'test102020'%0A results = TEST.build_arg('test',10,2020)%0A log.debug(results)%0A self.assertTrue( results == expected)%0A%0A expected = %22test102020%7B'something': 10%7D%22%0A results = TEST.build_arg('test',10,2020,%7B'something' : 10%7D)%0A log.debug(results)%0A self.assertTrue( results == expected)%0A def testBuidlPath(self) :%0A expected = 'test/10/2020'%0A results = TEST.build_path('test',10,2020)%0A log.debug(results)%0A self.assertTrue( results == expected)%0A%0A expected = %22test/10/2020/%7B'something': 10%7D%22%0A results = TEST.build_path('test',10,2020,%7B'something' : 10%7D)%0A log.debug(results)%0A self.assertTrue( results == expected)%0A def testBuildCommand(self) :%0A expected = 'test 10 2020'%0A results = TEST.build_command('test',10,2020)%0A log.debug(results)%0A self.assertTrue( results == expected)%0A%0A expected = %22test 10 2020 %7B'something': 10%7D%22%0A results = TEST.build_command('test',10,2020,%7B'something' : 10%7D)%0A log.debug(results)%0A self.assertTrue( results == expected)%0A%0A def testJson(self) :%0A log.debug(TEST.pretty_print(TEST.load_json('test_input/json_test.json')))%0A def testConfig(self) :%0A log.debug(TEST.pretty_print(TEST.load_config('test_input/conf_test.ini')))%0A%0Aif __name__ == '__main__' :%0A log_file = TEST.build_arg(*sys.argv).replace('.py','') + '.log'%0A log_file = TEST.build_path('../log',log_file)%0A TEST.remove_file(log_file)%0A log.basicConfig(filename=log_file, format=TEST.LOG_FORMAT_TEST, level=log.DEBUG)%0A unittest.main()%0A
4172b35bfdd1b4b12592d81b07843ca2c902a732
solved 45
045/eul045.py
045/eul045.py
Python
0.999983
@@ -0,0 +1,705 @@ +#! /usr/bin/python%0Afrom __future__ import print_function%0Afrom time import time%0Afrom math import sqrt%0A%0A%0A# Project Euler # 45%0A%0A# Since an integer x is triangular if and only if 8x + 1 is a square%0Adef is_triangle(x):%0A return sqrt(8 * x + 1).is_integer()%0A%0A%0Adef is_pentagonal(x):%0A if x %3C 1:%0A return False%0A n = (sqrt(24 * x + 1) + 1) / 6%0A if n.is_integer():%0A return n%0A else:%0A return False%0A%0Aif __name__ == '__main__':%0A start = time()%0A # start one higher than H143%0A n = 144%0A while True:%0A Hn = n * (2 * n - 1)%0A if is_triangle(Hn) and is_pentagonal(Hn):%0A break%0A n += 1%0A print(%22TP and H value:%22, Hn, %22in%22, time() - start, %22seconds%22)%0A
b209c45fe32ee7b73bddff5419c1931a16da0bbd
Test file request.py
test/request.py
test/request.py
Python
0.000003
@@ -0,0 +1,271 @@ +#!/usr/bin/python%0A# -*- coding: utf-8 -*-%0A%0Aimport urllib2%0Aimport threading%0A%0A%0Adef worker():%0A urllib2.urlopen('http://localhost:8080').read()%0A%0A%0Aif __name__ == '__main__':%0A for i in xrange(1024):%0A threading.Thread(target=worker).start()%0A print 'Partiti...'%0A%0A
be544817908ba3f9377d24a61047496c3dbf4f7a
Add test
test_rlev_model.py
test_rlev_model.py
Python
0.000005
@@ -0,0 +1,586 @@ +import os%0Aimport unittest%0A%0Afrom click.testing import CliRunner%0A%0Afrom rlev_model import cli%0A%0A%0Aclass TestCli(unittest.TestCase):%0A def test_cli(self):%0A runner = CliRunner()%0A sample_filename = os.path.join('data', 'sample-data.txt')%0A result = runner.invoke(cli, %5Bsample_filename%5D)%0A assert result.exit_code == 0%0A%0A output_filename = os.path.join('data', 'sample-output.txt')%0A with open(output_filename) as fp:%0A expected_output = fp.read()%0A assert result.output == expected_output%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
da2a4fa9e618b212ddbb2fcbc079fa37970ae596
Add handler for concurrently logging to a file
tfd/loggingutil.py
tfd/loggingutil.py
Python
0
@@ -0,0 +1,1865 @@ +%0A'''%0AUtilities to assist with logging in python%0A'''%0A%0Aimport logging%0A%0A%0Aclass ConcurrentFileHandler(logging.Handler):%0A %22%22%22%0A A handler class which writes logging records to a file. Every time it%0A writes a record it opens the file, writes to it, flushes the buffer, and%0A closes the file. Perhaps this could create problems in a very tight loop.%0A This handler is an attempt to overcome concurrent write issues that%0A the standard FileHandler has when multiple processes distributed across%0A a cluster are all writing to the same log file. Specifically, the records%0A can become interleaved/garbled with one another.%0A %22%22%22%0A def __init__(self, filename, mode=%22a%22):%0A %22%22%22%0A Open the specified file and use it as the stream for logging.%0A%0A :param mode: defaults to 'a', append.%0A %22%22%22%0A logging.Handler.__init__(self)%0A # keep the absolute path, otherwise derived classes which use this%0A # may come a cropper when the current directory changes%0A self.filename = os.path.abspath(filename)%0A self.mode = mode%0A%0A%0A def _openWriteClose(self, msg):%0A f = open(self.filename, self.mode)%0A f.write(msg)%0A f.flush() # improves consistency of writes in a concurrent environment%0A f.close()%0A%0A %0A def emit(self, record):%0A %22%22%22%0A Emit a record.%0A%0A If a formatter is specified, it is used to format the record.%0A The record is then written to the stream with a trailing newline%0A %5BN.B. this may be removed depending on feedback%5D. If exception%0A information is present, it is formatted using%0A traceback.print_exception and appended to the stream.%0A %22%22%22%0A try:%0A msg = self.format(record)%0A fs = %22%25s%5Cn%22%0A self._openWriteClose(fs %25 msg)%0A except:%0A self.handleError(record)%0A%0A%0A
ba599deb23c75a6dbcbc0de897afedc287c2ea94
Create 02str_format.py
02str_format.py
02str_format.py
Python
0.000019
@@ -0,0 +1,137 @@ +age = 38%0Aname = 'Murphy Wan'%0Aprint('%7B0%7D is %7B1%7D yeaers old'.format(name, age))%0Aprint('why is %7B0%7D playing with that python?'.format(name))%0A
464f011b2a87d18ea3e8d16339898987cf190a72
Task2_1
test_example.py
test_example.py
Python
0.999999
@@ -0,0 +1,820 @@ +import pytest%0Afrom selenium import webdriver%0Afrom selenium.webdriver.support.wait import WebDriverWait%0A#from selenium.webdriver.support import expected_conditions as EC%0A%0A%[email protected]%0Adef driver(request):%0A wd = webdriver.Safari()%0A print(wd.capabilities)%0A request.addfinalizer(wd.quit)%0A return wd%0A%0A%0Adef test_example(driver):%0A driver.get(%22http://www.google.com/%22)%0A WebDriverWait(driver, 10)%0A# driver.find_element_by_name(%22q%22).send_keys(%22webdriver%22)%0A# driver.find_element_by_name(%22btnG%22).click()%0A# WebDriverWait(driver, 10).until(EC.title_is(%22webdriver - %D0%9F%D0%BE%D0%B8%D1%81%D0%BA %D0%B2 Google%22))%0A%0A# %D0%92%D0%BE%D0%BF%D1%80%D0%BE%D1%81 %D1%82%D1%80%D0%B5%D0%BD%D0%B5%D1%80%D1%83: %D1%82%D0%B5%D1%81%D1%82 %D0%BE%D1%82%D1%80%D0%B0%D0%B1%D0%B0%D1%82%D1%8B%D0%B2%D0%B0%D0%B5%D1%82 c %D1%80%D0%B5%D0%B7%D1%83%D0%BB%D1%8C%D1%82%D0%B0%D1%82%D0%BE%D0%BC %221 test passed%22, %D1%8F %D0%B2%D0%B8%D0%B6%D1%83, %D1%87%D1%82%D0%BE %D0%B1%D1%80%D0%B0%D1%83%D0%B7%D0%B5%D1%80 Safari %D0%B7%D0%B0%D0%BF%D1%83%D1%81%D0%BA%D0%B0%D0%B5%D1%82%D1%81%D1%8F,%0A# %D0%BD%D0%BE %D0%BF%D0%BE %D0%BE%D0%BA%D0%BE%D0%BD%D1%87%D0%B0%D0%BD%D0%B8%D0%B8 %D0%BE%D0%BA%D0%BD%D0%BE %D0%B1%D1%80%D0%B0%D1%83%D0%B7%D0%B5%D1%80%D0%B0 %D0%BD%D0%B5 %D0%B7%D0%B0%D0%BA%D1%80%D1%8B%D0%B2%D0%B0%D0%B5%D1%82%D1%81%D1%8F, %D0%B0 %D0%BF%D0%BE%D0%BA%D0%B0%D0%B7%D1%8B%D0%B2%D0%B0%D0%B5%D1%82 %D0%B4%D0%BE%D0%BC%D0%B0%D1%88%D0%BD%D1%8E%D1%8E %D1%81%D1%82%D1%80%D0%B0%D0%BD%D0%B8%D1%86%D1%83. %D0%AD%D1%82%D0%BE %D0%BE%D0%B6%D0%B8%D0%B4%D0%B0%D0%B5%D0%BC%D0%BE? %D0%98%D0%BB%D0%B8 %D1%87%D1%82%D0%BE-%D1%82%D0%BE %D0%BD%D0%B5 %D1%82%D0%B0%D0%BA?
700db5c742be8a893b1c362ae0955a934b88c39b
Add test_learning_journal.py with test_app() for configuring the app for testing
test_journal.py
test_journal.py
Python
0.000005
@@ -0,0 +1,535 @@ +# -*- coding: utf-8 -*-%0Afrom contextlib import closing%0Aimport pytest%0A%0Afrom journal import app%0Afrom journal import connect_db%0Afrom journal import get_database_connection%0Afrom journal import init_db%0A%0ATEST_DSN = 'dbname=test_learning_journal'%0A%0A%0Adef clear_db():%0A with closing(connect_db()) as db:%0A db.cursor().execute(%22DROP TABLE entries%22)%0A db.commit()%0A%0A%[email protected](scope='session')%0Adef test_app():%0A %22%22%22configure our app for use in testing%22%22%22%0A app.config%5B'DATABASE'%5D = TEST_DSN%0A app.config%5B'TESTING'%5D = True%0A
59d51e90203a20f9e0b01eda43afc268311009e7
Comment about JSON
firefox/src/py/extensionconnection.py
firefox/src/py/extensionconnection.py
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # # 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. """Communication with the firefox extension.""" import logging import socket import time try: import json except ImportError: # Python < 2.6 import simplejson as json # FIXME: What is this? if not hasattr(json, 'dumps'): import simplejson as json from selenium.remote.command import Command from selenium.remote.remote_connection import RemoteConnection _DEFAULT_TIMEOUT = 20 _DEFAULT_PORT = 7055 LOGGER = logging.getLogger("webdriver.ExtensionConnection") class ExtensionConnection(RemoteConnection): """This class maintains a connection to the firefox extension. """ def __init__(self, timeout=_DEFAULT_TIMEOUT): RemoteConnection.__init__( self, "http://localhost:%d/hub" % _DEFAULT_PORT) LOGGER.debug("extension connection initiated") self.timeout = timeout def quit(self, sessionId=None): self.execute(Command.QUIT, {'sessionId':sessionId}) while self.is_connectable(): logging.info("waiting to quit") time.sleep(1) def connect(self): """Connects to the extension and retrieves the session id.""" return self.execute(Command.NEW_SESSION, {'desiredCapabilities':{ 'browserName': 'firefox', 'platform': 'ANY', 'version': '', 'javascriptEnabled': True}}) def connect_and_quit(self): """Connects to an running browser and quit immediately.""" self._request('%s/extensions/firefox/quit' % self._url) def is_connectable(self): """Trys to connect to the extension but do not retrieve context.""" try: socket_ = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_.settimeout(1) socket_.connect(("localhost", _DEFAULT_PORT)) socket_.close() return True except socket.error: return False class ExtensionConnectionError(Exception): """An internal error occurred int the extension. Might be caused by bad input or bugs in webdriver """ pass
Python
0
@@ -800,28 +800,80 @@ %0A%0A# -FIXME: What is this? +Some old JSON libraries don't have %22dumps%22, make sure we have a good one %0Aif
1f3c1af308be68393ac8f7caab17d04cdd632d2b
Add the get_arguments function in include
survey_creation/include/get_arguments.py
survey_creation/include/get_arguments.py
Python
0.000027
@@ -0,0 +1,914 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Aimport sys%0Aimport getopt%0A%0A%22%22%22%0AShort script to parse%0Athe argments from the command line%0A%22%22%22%0A%0A%0Adef get_arguments(argv):%0A %22%22%22%0A %22%22%22%0A country = None%0A year = None%0A try:%0A opts, args = getopt.getopt(argv, 'hc:y:', %5B'country=', 'year='%5D)%0A except getopt.GetoptError:%0A print('run.py -c %3Ccountry%3E -y %3Cyear%3E')%0A sys.exit(2)%0A for opt, arg in opts:%0A if opt == '-h':%0A print('run.py -c %3Ccountry%3E -y %3Cyear%3E')%0A sys.exit()%0A elif opt in ('-c', '--country'):%0A country = arg%0A elif opt in ('-y', '--year'):%0A year = arg%0A if country and year:%0A # folder_path = os.path.join(year, country)%0A return year, country%0A else:%0A print('Need a country and a year. Please use the following command:%5Cn' +%0A '%5Ctrun.py -c %3Ccountry%3E -y %3Cyear%3E')%0A sys.exit(2)%0A
4276e1b991ea923a2a3bdd227bb3d98ced1fd4e2
add alias function
thefuck/main.py
thefuck/main.py
from imp import load_source from pathlib import Path from os.path import expanduser from subprocess import Popen, PIPE import os import sys from psutil import Process, TimeoutExpired import colorama from . import logs, conf, types def setup_user_dir(): """Returns user config dir, create it when it doesn't exist.""" user_dir = Path(expanduser('~/.thefuck')) rules_dir = user_dir.joinpath('rules') if not rules_dir.is_dir(): rules_dir.mkdir(parents=True) conf.initialize_settings_file(user_dir) return user_dir def load_rule(rule): """Imports rule module and returns it.""" rule_module = load_source(rule.name[:-3], str(rule)) return types.Rule(rule.name[:-3], rule_module.match, rule_module.get_new_command, getattr(rule_module, 'enabled_by_default', True)) def get_rules(user_dir, settings): """Returns all enabled rules.""" bundled = Path(__file__).parent \ .joinpath('rules') \ .glob('*.py') user = user_dir.joinpath('rules').glob('*.py') for rule in sorted(list(bundled)) + list(user): if rule.name != '__init__.py': loaded_rule = load_rule(rule) if loaded_rule in settings.rules: yield loaded_rule def wait_output(settings, popen): """Returns `True` if we can get output of the command in the `wait_command` time. Command will be killed if it wasn't finished in the time. """ proc = Process(popen.pid) try: proc.wait(settings.wait_command) return True except TimeoutExpired: for child in proc.get_children(recursive=True): child.kill() proc.kill() return False def get_command(settings, args): """Creates command from `args` and executes it.""" if sys.version_info[0] < 3: script = ' '.join(arg.decode('utf-8') for arg in args[1:]) else: script = ' '.join(args[1:]) if not script: return result = Popen(script, shell=True, stdout=PIPE, stderr=PIPE, env=dict(os.environ, LANG='C')) if wait_output(settings, result): return types.Command(script, result.stdout.read().decode('utf-8'), result.stderr.read().decode('utf-8')) def get_matched_rule(command, rules, settings): """Returns first matched rule for command.""" for rule in rules: try: if rule.match(command, settings): return rule except Exception: logs.rule_failed(rule, sys.exc_info(), settings) def confirm(new_command, settings): """Returns `True` when running of new command confirmed.""" if not settings.require_confirmation: logs.show_command(new_command, settings) return True logs.confirm_command(new_command, settings) try: sys.stdin.read(1) return True except KeyboardInterrupt: logs.failed('Aborted', settings) return False def run_rule(rule, command, settings): """Runs command from rule for passed command.""" new_command = rule.get_new_command(command, settings) if confirm(new_command, settings): print(new_command) def is_second_run(command): """Is it the second run of `fuck`?""" return command.script.startswith('fuck') def main(): colorama.init() user_dir = setup_user_dir() settings = conf.get_settings(user_dir) command = get_command(settings, sys.argv) if command: if is_second_run(command): logs.failed("Can't fuck twice", settings) return rules = get_rules(user_dir, settings) matched_rule = get_matched_rule(command, rules, settings) if matched_rule: run_rule(matched_rule, command, settings) return logs.failed('No fuck given', settings)
Python
0.000005
@@ -3324,24 +3324,98 @@ h('fuck')%0A%0A%0A +def alias():%0A print(%22%5Cnalias fuck='eval $(thefuck $(fc -ln -1))'%5Cn%22)%0A%0A%0A def main():%0A
7a3e53ec0537e7e63bfbc8caf1a30a350c2e9eea
Allow turning of the human timestamp format after it's been turned on.
shinken/log.py
shinken/log.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2009-2012: # Gabes Jean, [email protected] # Gerhard Lausser, [email protected] # Gregory Starck, [email protected] # Hartmut Goebel, [email protected] # # This file is part of Shinken. # # Shinken 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. # # Shinken 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Shinken. If not, see <http://www.gnu.org/licenses/>. import time import logging from logging.handlers import TimedRotatingFileHandler from brok import Brok obj = None name = None local_log = None human_timestamp_log = False class Log: """Please Add a Docstring to describe the class here""" NOTSET = logging.NOTSET DEBUG = logging.DEBUG INFO = logging.INFO WARNING = logging.WARNING ERROR = logging.ERROR CRITICAL = logging.CRITICAL def __init__(self): self._level = logging.NOTSET def load_obj(self, object, name_=None): """ We load the object where we will put log broks with the 'add' method """ global obj global name obj = object name = name_ @staticmethod def get_level_id(lvlName): """Convert a level name (string) to its integer value Raise KeyError when name not found """ return logging._levelNames[lvlName] # We can have level as an int (logging.INFO) or a string INFO # if string, try to get the int value def set_level(self, level): if not isinstance(level, int): raise TypeError('log level must be an integer') self._level = level logging.getLogger().setLevel(level) def debug(self, msg, *args, **kwargs): self._log(logging.DEBUG, msg, *args, **kwargs) def info(self, msg, *args, **kwargs): self._log(logging.INFO, msg, *args, **kwargs) def warning(self, msg, *args, **kwargs): self._log(logging.WARNING, msg, *args, **kwargs) def error(self, msg, *args, **kwargs): self._log(logging.ERROR, msg, *args, **kwargs) def critical(self, msg, *args, **kwargs): self._log(logging.CRITICAL, msg, *args, **kwargs) def log(self, message, format=None, print_it=True): """Old log method, kept for NAGIOS compatibility""" self._log(logging.INFO, message, format, print_it, display_level=False) def _log(self, level, message, format=None, print_it=True, display_level=True): """We enter a log message, we format it, and we add the log brok""" global obj global name global local_log global human_timestamp_log # ignore messages when message level is lower than Log level if level < self._level: return # We format the log in UTF-8 if isinstance(message, str): message = message.decode('UTF-8', 'replace') if format is None: lvlname = logging.getLevelName(level) if display_level: fmt = u'[%(date)s] %(level)s: %(name)s%(msg)s\n' else: fmt = u'[%(date)s] %(name)s%(msg)s\n' args = { 'date': (human_timestamp_log and time.asctime() or int(time.time())), 'level': lvlname.capitalize(), 'name': name and ('[%s] ' % name) or '', 'msg': message } s = fmt % args else: s = format % message if print_it and len(s) > 1: # If the daemon is launched with a non UTF8 shell # we can have problems in printing try: print s[:-1] except UnicodeEncodeError: print s.encode('ascii', 'ignore') # We create and add the brok but not for debug that don't need # to do a brok for it, and so go in all satellites. Debug # should keep locally if level != logging.DEBUG: b = Brok('log', {'log': s}) obj.add(b) # If we want a local log write, do it if local_log is not None: logging.log(level, s.strip()) def register_local_log(self, path, level=None): """The log can also write to a local file if needed and return the file descriptor so we can avoid to close it """ global local_log if level is not None: self._level = level # Open the log and set to rotate once a day basic_log_handler = TimedRotatingFileHandler(path, 'midnight', backupCount=5) basic_log_handler.setLevel(self._level) basic_log_formatter = logging.Formatter('%(asctime)s %(message)s') basic_log_handler.setFormatter(basic_log_formatter) logger = logging.getLogger() logger.addHandler(basic_log_handler) logger.setLevel(self._level) local_log = basic_log_handler # Return the file descriptor of this file return basic_log_handler.stream.fileno() def quit(self): """Close the local log file at program exit""" global local_log if local_log: self.debug("Closing %s local_log" % str(local_log)) local_log.close() def set_human_format(self): """Set the output as human format""" global human_timestamp_log human_timestamp_log = True logger = Log()
Python
0
@@ -5866,24 +5866,33 @@ _format(self +, on=True ):%0A %22 @@ -5893,16 +5893,25 @@ %22%22%22 +%0A Set the @@ -5932,16 +5932,142 @@ n format +.%0A%0A If the optional parameter %60on%60 is False, the timestamp format%0A will be reset to the default format.%0A %22%22%22%0A @@ -6127,20 +6127,24 @@ p_log = -True +bool(on) %0A%0Alogger
d7945d85dcce968d6430e079662b1ef9fc464c97
update ukvi org branding spelling
migrations/versions/0047_ukvi_spelling.py
migrations/versions/0047_ukvi_spelling.py
Python
0
@@ -0,0 +1,638 @@ +%22%22%22empty message%0A%0ARevision ID: 0047_ukvi_spelling%0ARevises: 0046_organisations_and_branding%0ACreate Date: 2016-08-22 16:06:32.981723%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '0047_ukvi_spelling'%0Adown_revision = '0046_organisations_and_branding'%0A%0Afrom alembic import op%0A%0A%0Adef upgrade():%0A op.execute(%22%22%22%0A UPDATE organisation%0A SET name = 'UK Visas & Immigration'%0A WHERE id = '9d25d02d-2915-4e98-874b-974e123e8536'%0A %22%22%22)%0A%0A%0Adef downgrade():%0A op.execute(%22%22%22%0A UPDATE organisation%0A SET name = 'UK Visas and Immigration'%0A WHERE id = '9d25d02d-2915-4e98-874b-974e123e8536'%0A %22%22%22)%0A
be3acc4a869c9e45e4d1fdd563571da0d12ae85f
Add modify code Hello World code
HelloWorld.py
HelloWorld.py
Python
0.000857
@@ -0,0 +1,55 @@ +print(%22HelloWorld%22)%0A%0Atext=%22HelloWorld_Text%22%0Aprint(text)
f2864289f02a6e221d6fafbb1885d20aa26417fd
Add default conftest
test/unit/conftest.py
test/unit/conftest.py
Python
0.000001
@@ -0,0 +1,1519 @@ +# :coding: utf-8%0A%0Aimport os%0Aimport shutil%0Aimport tempfile%0Aimport uuid%0A%0Aimport pytest%0A%0A%[email protected]()%0Adef unique_name():%0A %22%22%22Return a unique name.%22%22%22%0A return %22unique-%7B0%7D%22.format(uuid.uuid4())%0A%0A%[email protected]()%0Adef temporary_file(request):%0A %22%22%22Return a temporary file path.%22%22%22%0A file_handle, path = tempfile.mkstemp()%0A os.close(file_handle)%0A%0A def cleanup():%0A %22%22%22Remove temporary file.%22%22%22%0A try:%0A os.remove(path)%0A except OSError:%0A pass%0A%0A request.addfinalizer(cleanup)%0A return path%0A%0A%[email protected]()%0Adef temporary_directory(request):%0A %22%22%22Return a temporary directory path.%22%22%22%0A path = tempfile.mkdtemp()%0A%0A def cleanup():%0A %22%22%22Remove temporary directory.%22%22%22%0A shutil.rmtree(path)%0A%0A request.addfinalizer(cleanup)%0A%0A return path%0A%0A%[email protected]()%0Adef code_folder():%0A return os.path.join(os.path.dirname(__file__), %22example%22)%0A%0A%[email protected]()%0Adef docs_folder(temporary_directory):%0A path = os.path.join(temporary_directory, %22docs%22)%0A os.makedirs(path)%0A%0A # Create minimal conf.py file%0A conf_file = os.path.join(path, %22conf.py%22)%0A%0A with open(conf_file, %22w%22) as f:%0A f.write(%0A %22# :coding: utf-8%5Cn%22%0A %22extensions=%5B'sphinxcontrib.es6'%5D%5Cn%22%0A %22source_suffix = '.rst'%5Cn%22%0A %22master_doc = 'index'%5Cn%22%0A %22author = u'Jeremy Retailleau'%5Cn%22%0A %22exclude_patterns = %5B'Thumbs.db', '.DS_Store'%5D%5Cn%22%0A %22js_source='./example'%22%0A )%0A%0A return path%0A%0A
1dba0fb24f98bb09bd0c918439c0457c603e1386
Create ullman.py
ullman.py
ullman.py
Python
0.000001
@@ -0,0 +1,847 @@ +import requests%0Afrom multiprocessing import Pool%0Aimport time%0A%0AstartURL = 'http://i.stanford.edu/~ullman/focs/ch'%0Aextension = '.pdf'%0AsavePath = '' #enter the path for the pdfs to be stored on your system%0Achapters = range(1,15) #chapters 1-14%0A%0Adef chapterStringManipulate(chapter):%0A if chapter %3C 10 :%0A download('0%7B%7D'.format(chapter))%0A else :%0A download('%7B%7D'.format(chapter))%0A%0A return None%0A%0A%0Adef download(chapter):%0A%0A url = '%7B%7D%7B%7D%7B%7D'.format(startURL, chapter, extension)%0A r = requests.get(url, stream=True)%0A%0A path = '%7B%7D%7B%7D%7B%7D'.format(savePath, chapter, extension)%0A%0A with open(path, 'wb') as fd:%0A for chunk in r.iter_content(2048):%0A fd.write(chunk)%0A %0A print '%7B%7D downloaded'.format(chapter)%0A%0A return None%0A%0A%0Aif __name__ == '__main__':%0A pool = Pool(processes=len(chapters))%0A results = pool.map(chapterStringManipulate, chapters)%0A
9d3925c4809791d2366bc1d6fd6b04bc8a710c9b
add fmt to repo
toolshed/fmt.py
toolshed/fmt.py
Python
0
@@ -0,0 +1,450 @@ +import re%0A%0Adef fmt2header(fmt):%0A %22%22%22%0A Turn a python format string into a usable header:%0A %3E%3E%3E fmt = %22%7Bchrom%7D%5Ct%7Bstart:d%7D%5Ct%7Bend:d%7D%5Ct%7Bpvalue:.4g%7D%22%0A %3E%3E%3E fmt2header(fmt)%0A 'chrom start end pvalue'%0A %3E%3E%3E fmt.format(chrom='chr1', start=1234, end=3456, pvalue=0.01232432)%0A 'chr1 1234 3456 0.01232'%0A %22%22%22%0A return re.sub(%22%7B%7C(?:%5C:.+?)?%7D%22, %22%22, fmt)%0A%0Aif __name__ == %22__main__%22:%0A import doctest%0A print(doctest.testmod())%0A
dd9b683b24cea02c93a6e23a163065c0f26f6a68
Test manager
tests/test.manager.py
tests/test.manager.py
Python
0.000003
@@ -0,0 +1,634 @@ +import opensim%0A%0Amodel_path = %22../osim/models/arm2dof6musc.osim%22%0Amodel = opensim.Model(model_path)%0Amodel.setUseVisualizer(True)%0Astate = model.initSystem()%0Amanager = opensim.Manager(model)%0AmuscleSet = model.getMuscles()%0Astepsize = 0.01%0A%0Afor i in range(10):%0A for j in range(muscleSet.getSize()):%0A# muscleSet.get(j).setActivation(state, 1.0)%0A muscleSet.get(j).setExcitation(state, 1.0)%0A t = state.getTime()%0A manager.setInitialTime(stepsize * i)%0A manager.setFinalTime(stepsize * (i + 1))%0A manager.integrate(state)%0A model.realizeDynamics(state)%0A print(%22%25f %25f%22 %25 (t,muscleSet.get(0).getActivation(state)))%0A
5d18f7c7145bf8d5e7248392d644e521222929b8
add tests for _extras
tests/test__extras.py
tests/test__extras.py
Python
0.000001
@@ -0,0 +1,2077 @@ +%22%22%22Tests for %60%60_extras%60%60 module.%22%22%22%0Aimport pytest%0A%0Afrom rstcheck import _compat, _extras%0A%0A%0Aclass TestInstallChecker:%0A %22%22%22Test %60%60is_installed_with_supported_version%60%60.%22%22%22%0A%0A @staticmethod%0A @pytest.mark.skipif(_extras.SPHINX_INSTALLED, reason=%22Test for absence of sphinx.%22)%0A def test_false_on_missing_sphinx_package() -%3E None:%0A %22%22%22Test install-checker returns %60%60False%60%60 when %60%60sphinx%60%60 is missing.%22%22%22%0A result = _extras.is_installed_with_supported_version(%22sphinx%22)%0A%0A assert result is False%0A%0A @staticmethod%0A @pytest.mark.skipif(not _extras.SPHINX_INSTALLED, reason=%22Test for presence of sphinx.%22)%0A def test_true_on_installed_sphinx_package() -%3E None:%0A %22%22%22Test install-checker returns %60%60True%60%60 when %60%60sphinx%60%60 is installed with good version.%22%22%22%0A result = _extras.is_installed_with_supported_version(%22sphinx%22)%0A%0A assert result is True%0A%0A @staticmethod%0A @pytest.mark.skipif(not _extras.SPHINX_INSTALLED, reason=%22Test for presence of sphinx.%22)%0A def test_false_on_installed_sphinx_package_too_old(monkeypatch: pytest.MonkeyPatch) -%3E None:%0A %22%22%22Test install-checker returns %60%60False%60%60 when %60%60sphinx%60%60 is installed with bad version.%22%22%22%0A monkeypatch.setattr(_compat, %22metadata%22, lambda _: %7B%22Version%22: %220.0%22%7D)%0A%0A result = _extras.is_installed_with_supported_version(%22sphinx%22)%0A%0A assert result is False%0A%0A%0Aclass TestInstallGuard:%0A %22%22%22Test %60%60install_guard%60%60.%22%22%22%0A%0A @staticmethod%0A @pytest.mark.skipif(_extras.SPHINX_INSTALLED, reason=%22Test for absence of sphinx.%22)%0A def test_false_on_missing_sphinx_package() -%3E None:%0A %22%22%22Test install-guard raises exception when %60%60sphinx%60%60 is missing.%22%22%22%0A with pytest.raises(ModuleNotFoundError):%0A _extras.install_guard(%22sphinx%22) # act%0A%0A @staticmethod%0A @pytest.mark.skipif(not _extras.SPHINX_INSTALLED, reason=%22Test for presence of sphinx.%22)%0A def test_true_on_installed_sphinx_package() -%3E None:%0A %22%22%22Test install-guard doesn't raise when %60%60sphinx%60%60 is installed.%22%22%22%0A _extras.install_guard(%22sphinx%22) # act%0A
eb1c7d1c2bfaa063c98612d64bbe35dedf217143
Add initial tests for alerter class
tests/test_alerter.py
tests/test_alerter.py
Python
0
@@ -0,0 +1,892 @@ +import unittest%0Aimport datetime%0Aimport Alerters.alerter%0A%0A%0Aclass TestAlerter(unittest.TestCase):%0A%0A def test_groups(self):%0A config_options = %7B'groups': 'a,b,c'%7D%0A a = Alerters.alerter.Alerter(config_options)%0A self.assertEqual(%5B'a', 'b', 'c'%5D, a.groups)%0A%0A def test_times_always(self):%0A config_options = %7B'times_type': 'always'%7D%0A a = Alerters.alerter.Alerter(config_options)%0A self.assertEqual(a.times_type, 'always')%0A self.assertEqual(a.time_info, %5BNone, None%5D)%0A%0A def test_times_only(self):%0A config_options = %7B%0A 'times_type': 'only',%0A 'time_lower': '10:00',%0A 'time_upper': '11:00'%0A %7D%0A a = Alerters.alerter.Alerter(config_options)%0A self.assertEqual(a.times_type, 'only')%0A self.assertEqual(a.time_info, %5B%0A datetime.time(10, 00), datetime.time(11, 00)%0A %5D)%0A
33658163b909073aae074b5b2cdae40a0e5c44e8
Add unit tests for asyncio coroutines
tests/test_asyncio.py
tests/test_asyncio.py
Python
0.000001
@@ -0,0 +1,1969 @@ +from trollius import test_utils%0Afrom trollius import From, Return%0Aimport trollius%0Aimport unittest%0A%0Atry:%0A import asyncio%0Aexcept ImportError:%0A from trollius.test_utils import SkipTest%0A raise SkipTest('need asyncio')%0A%0A%0A# %22yield from%22 syntax cannot be used directly, because Python 2 should be able%0A# to execute this file (to raise SkipTest)%0Acode = '''%[email protected]%0Adef asyncio_noop(value):%0A yield from %5B%5D%0A return (value,)%0A%[email protected]%0Adef asyncio_coroutine(coro, value):%0A res = yield from coro%0A return res + (value,)%0A'''%0Aexec(code)%0A%[email protected]%0Adef trollius_noop(value):%0A yield From(None)%0A raise Return((value,))%0A%[email protected]%0Adef trollius_coroutine(coro, value):%0A res = yield trollius.From(coro)%0A raise trollius.Return(res + (value,))%0A%0A%0Aclass AsyncioTests(test_utils.TestCase):%0A def setUp(self):%0A policy = trollius.get_event_loop_policy()%0A self.loop = policy.new_event_loop()%0A self.set_event_loop(self.loop)%0A%0A asyncio_policy = asyncio.get_event_loop_policy()%0A self.addCleanup(asyncio.set_event_loop_policy, asyncio_policy)%0A asyncio.set_event_loop_policy(policy)%0A%0A def test_policy(self):%0A trollius.set_event_loop(self.loop)%0A self.assertIs(asyncio.get_event_loop(), self.loop)%0A%0A def test_asyncio(self):%0A coro = asyncio_noop(%22asyncio%22)%0A res = self.loop.run_until_complete(coro)%0A self.assertEqual(res, (%22asyncio%22,))%0A%0A def test_asyncio_in_trollius(self):%0A coro1 = asyncio_noop(1)%0A coro2 = asyncio_coroutine(coro1, 2)%0A res = self.loop.run_until_complete(trollius_coroutine(coro2, 3))%0A self.assertEqual(res, (1, 2, 3))%0A%0A def test_trollius_in_asyncio(self):%0A coro1 = trollius_noop(4)%0A coro2 = trollius_coroutine(coro1, 5)%0A res = self.loop.run_until_complete(asyncio_coroutine(coro2, 6))%0A self.assertEqual(res, (4, 5, 6))%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
72ff3bfcbfb9e4144d43ca03c77f0692cccd0fc2
add small interface for DHT Adafruit lib (in rpi.py)
gsensors/rpi.py
gsensors/rpi.py
Python
0
@@ -0,0 +1,1200 @@ +#-*- coding:utf-8 -*-%0A%22%22%22 Drivers for common sensors on a rPi%0A%22%22%22%0Aimport sys%0Aimport gevent%0A%0Afrom gsensors import AutoUpdateValue%0A%0A%0Aclass DHTTemp(AutoUpdateValue):%0A def __init__(self, pin, stype=%222302%22, name=None):%0A update_freq = 10 #seconds%0A super(DHTTemp, self).__init__(name=name, unit=%22%C2%B0C%22, update_freq=update_freq)%0A import Adafruit_DHT%0A self.Adafruit_DHT = Adafruit_DHT #XXX:mv dans un module a part pour %C3%A9viter import merdique ici%0A TYPES = %7B%0A '11': Adafruit_DHT.DHT11,%0A '22': Adafruit_DHT.DHT22,%0A '2302': Adafruit_DHT.AM2302%0A %7D%0A self.sensor = TYPES.get(stype, stype) #TODO: check stype%0A self.pin = pin%0A%0A def update(self):%0A humidity, temperature = self.Adafruit_DHT.read_retry(self.sensor, self.pin)%0A self.value = temperature%0A%0A%0Adef main():%0A sources = %5B%0A DHTTemp(18, %2222%22),%0A %5D%0A%0A def change_callback(src):%0A print(%22%25s: %25s %25s%22 %25 (src.name, src.value, src.unit))%0A%0A # plug change callback%0A for src in sources:%0A src.on_change(change_callback)%0A%0A for src in sources:%0A src.start()%0A%0A gevent.wait()%0A%0Aif __name__ == '__main__':%0A sys.exit(main())%0A%0A%0A
28d764994b8abd821b6cec4682cd8e4efa4e2f18
Fix tvdb online test.
tests/test_thetvdb.py
tests/test_thetvdb.py
from __future__ import unicode_literals, division, absolute_import from nose.plugins.attrib import attr from flexget.manager import Session from flexget.plugins.api_tvdb import lookup_episode from tests import FlexGetBase class TestThetvdbLookup(FlexGetBase): __yaml__ = """ templates: global: thetvdb_lookup: yes # Access a tvdb field to cause lazy loading to occur set: afield: "{{ tvdb_id }}{{ tvdb_ep_name }}" tasks: test: mock: - {title: 'House.S01E02.HDTV.XViD-FlexGet'} - {title: 'Doctor.Who.2005.S02E03.PDTV.XViD-FlexGet'} series: - House - Doctor Who 2005 test_unknown_series: mock: - {title: 'Aoeu.Htns.S01E01.htvd'} series: - Aoeu Htns test_mark_expired: mock: - {title: 'House.S02E02.hdtv'} metainfo_series: yes accept_all: yes disable_builtins: [seen] test_date: mock: - title: the daily show 2012-6-6 series: - the daily show (with jon stewart) test_absolute: mock: - title: naruto 128 series: - naruto """ @attr(online=True) def test_lookup(self): """thetvdb: Test Lookup (ONLINE)""" self.execute_task('test') entry = self.task.find_entry(title='House.S01E02.HDTV.XViD-FlexGet') assert entry['tvdb_ep_name'] == 'Paternity', \ '%s tvdb_ep_name should be Paternity' % entry['title'] assert entry['tvdb_status'] == 'Ended', \ 'runtime for %s is %s, should be Ended' % (entry['title'], entry['tvdb_status']) assert entry['tvdb_genres'] == ['Comedy', 'Drama'] assert entry['afield'] == '73255Paternity', 'afield was not set correctly' assert self.task.find_entry(tvdb_ep_name='School Reunion'), \ 'Failed imdb lookup Doctor Who 2005 S02E03' @attr(online=True) def test_unknown_series(self): # Test an unknown series does not cause any exceptions self.execute_task('test_unknown_series') # Make sure it didn't make a false match entry = self.task.find_entry('accepted', title='Aoeu.Htns.S01E01.htvd') assert entry.get('tvdb_id') is None, 'should not have populated tvdb data' @attr(online=True) def test_mark_expired(self): def test_run(): # Run the task and check tvdb data was populated. self.execute_task('test_mark_expired') entry = self.task.find_entry(title='House.S02E02.hdtv') assert entry['tvdb_ep_name'] == 'Autopsy' # Run the task once, this populates data from tvdb test_run() # Run the task again, this should load the data from cache test_run() # Manually mark the data as expired, to test cache update session = Session() ep = lookup_episode(name='House', seasonnum=2, episodenum=2, session=session) ep.expired = True ep.series.expired = True session.commit() session.close() test_run() @attr(online=True) def test_date(self): self.execute_task('test_date') entry = self.task.find_entry(title='the daily show 2012-6-6') assert entry assert entry['tvdb_ep_name'] == 'Michael Fassbender' @attr(online=True) def test_absolute(self): self.execute_task('test_absolute') entry = self.task.find_entry(title='naruto 128') assert entry assert entry['tvdb_ep_name'] == 'A Cry on Deaf Ears' class TestThetvdbFavorites(FlexGetBase): """ Tests thetvdb favorites plugin with a test user at thetvdb. Test user info: username: flexget password: flexget Account ID: 80FB8BD0720CA5EC Favorites: House, Doctor Who 2005, Penn & Teller: Bullshit, Hawaii Five-0 (2010) """ __yaml__ = """ tasks: test: mock: - {title: 'House.S01E02.HDTV.XViD-FlexGet'} - {title: 'Doctor.Who.2005.S02E03.PDTV.XViD-FlexGet'} - {title: 'Lost.S03E02.720p-FlexGet'} - {title: 'Penn.and.Teller.Bullshit.S02E02.720p.x264'} configure_series: from: thetvdb_favorites: account_id: 80FB8BD0720CA5EC test_strip_dates: thetvdb_favorites: account_id: 80FB8BD0720CA5EC strip_dates: yes """ @attr(online=True) def test_favorites(self): """thetvdb: Test favorites (ONLINE)""" self.execute_task('test') assert self.task.find_entry('accepted', title='House.S01E02.HDTV.XViD-FlexGet'), \ 'series House should have been accepted' assert self.task.find_entry('accepted', title='Doctor.Who.2005.S02E03.PDTV.XViD-FlexGet'), \ 'series Doctor Who 2005 should have been accepted' assert self.task.find_entry('accepted', title='Penn.and.Teller.Bullshit.S02E02.720p.x264'), \ 'series Penn and Teller Bullshit should have been accepted' entry = self.task.find_entry(title='Lost.S03E02.720p-FlexGet') assert entry, 'Entry not found?' assert entry not in self.task.accepted, \ 'series Lost should not have been accepted' @attr(online=True) def test_strip_date(self): self.execute_task('test_strip_dates') assert self.task.find_entry(title='Hawaii Five-0'), \ 'series Hawaii Five-0 (2010) should have date stripped'
Python
0.000001
@@ -1852,39 +1852,30 @@ vdb_ -genres'%5D == %5B'Comedy', 'Drama'%5D +absolute_number'%5D == 3 %0A
3bc341036730ab8e9fd5ac61e10556af028813e2
Add migration -Remove dupes -Add index preventing dupe creation
osf/migrations/0044_basefilenode_uniqueness_index.py
osf/migrations/0044_basefilenode_uniqueness_index.py
Python
0
@@ -0,0 +1,3385 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0Aimport logging%0A%0Afrom django.db import connection%0Afrom django.db import migrations%0A%0Alogger = logging.getLogger(__name__)%0A%0Adef remove_duplicate_filenodes(*args):%0A from osf.models.files import BaseFileNode%0A sql = %22%22%22%0A SELECT id%0A FROM (SELECT%0A *,%0A LEAD(row, 1)%0A OVER () AS nextrow%0A FROM (SELECT%0A *,%0A ROW_NUMBER()%0A OVER (w) AS row%0A FROM (SELECT *%0A FROM osf_basefilenode%0A WHERE (node_id IS NULL OR name IS NULL OR parent_id IS NULL OR type IS NULL OR _path IS NULL) AND%0A type NOT IN ('osf.trashedfilenode', 'osf.trashedfile', 'osf.trashedfolder')) AS null_files%0A WINDOW w AS (%0A PARTITION BY node_id, name, parent_id, type, _path%0A ORDER BY id )) AS x) AS y%0A WHERE row %3E 1 OR nextrow %3E 1;%0A %22%22%22%0A visited = %5B%5D%0A with connection.cursor() as cursor:%0A cursor.execute(sql)%0A dupes = BaseFileNode.objects.filter(id__in=%5Bt%5B0%5D for t in cursor.fetchall()%5D)%0A logger.info('%5CnFound %7B%7D dupes, merging and removing'.format(dupes.count()))%0A for dupe in dupes:%0A visited.append(dupe.id)%0A force = False%0A next_dupe = dupes.exclude(id__in=visited).filter(node_id=dupe.node_id, name=dupe.name, parent_id=dupe.parent_id, type=dupe.type, _path=dupe._path).first()%0A if dupe.node_id is None:%0A # Bad data, force-delete%0A force = True%0A if not next_dupe:%0A # Last one, don't delete%0A continue%0A if dupe.versions.count() %3E 1:%0A logger.warn('%7B%7D Expected 0 or 1 versions, got %7B%7D'.format(dupe.id, dupe.versions.count()))%0A # Don't modify versioned files%0A continue%0A for guid in list(dupe.guids.all()):%0A guid.referent = next_dupe%0A guid.save()%0A if force:%0A BaseFileNode.objects.filter(id=dupe.id).delete()%0A else:%0A dupe.delete()%0A with connection.cursor() as cursor:%0A logger.info('Validating clean-up success...')%0A cursor.execute(sql)%0A dupes = BaseFileNode.objects.filter(id__in=cursor.fetchall())%0A if dupes.exists():%0A logger.error('Dupes exist after migration, failing%5Cn%7B%7D'.format(dupes.values_list('id', flat=True)))%0A logger.info('Indexing...')%0A%0Adef noop(*args):%0A pass%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('osf', '0043_set_share_title'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(remove_duplicate_filenodes, noop),%0A migrations.RunSQL(%0A %5B%0A %22%22%22%0A CREATE UNIQUE INDEX active_file_node_path_name_type_unique_index%0A ON public.osf_basefilenode (node_id, _path, name, type)%0A WHERE (type NOT IN ('osf.trashedfilenode', 'osf.trashedfile', 'osf.trashedfolder')%0A AND parent_id IS NULL);%0A %22%22%22%0A %5D, %5B%0A %22%22%22%0A DROP INDEX IF EXISTS active_file_node_path_name_type_unique_index RESTRICT;%0A %22%22%22%0A %5D%0A )%0A %5D%0A
e322daa6d92a9dad8db9b8c9b6085aded90bef39
add beta release script
scripts/release_beta.py
scripts/release_beta.py
Python
0
@@ -0,0 +1,1266 @@ +%0Aimport argparse%0Aimport subprocess%0A%0A%0Aparser = argparse.ArgumentParser(description='Release Mixpanel Objective-C SDK')%0Aparser.add_argument('--old', help='old version number', action=%22store%22)%0Aparser.add_argument('--new', help='new version number for the release', action=%22store%22)%0Aargs = parser.parse_args()%0A%0Adef bump_version():%0A replace_version('Mixpanel.podspec', args.old, args.new)%0A replace_version('Mixpanel/Mixpanel.m', args.old, args.new)%0A subprocess.call('git add Mixpanel.podspec', shell=True)%0A subprocess.call('git add Mixpanel/Mixpanel.m', shell=True)%0A subprocess.call('git commit -m %22Version %7B%7D%22'.format(args.new), shell=True)%0A subprocess.call('git push', shell=True)%0A%0Adef replace_version(file_name, old_version, new_version):%0A with open(file_name) as f:%0A file_str = f.read()%0A assert(old_version in file_str)%0A file_str = file_str.replace(old_version, new_version)%0A%0A with open(file_name, %22w%22) as f:%0A f.write(file_str)%0A%0Adef add_tag():%0A subprocess.call('git tag -a v%7B%7D -m %22version %7B%7D%22'.format(args.new, args.new), shell=True)%0A subprocess.call('git push origin --tags', shell=True)%0A%0A%0Adef main():%0A bump_version()%0A add_tag()%0A print(%22Congratulations, done!%22)%0A%0Aif __name__ == '__main__':%0A main()
c783c26c6362cdd0702211552578a09f380e9dac
Add tags module.
src/pu/tags.py
src/pu/tags.py
Python
0
@@ -0,0 +1,1123 @@ +#%0A# Copyright (c) 2013 Joshua Hughes %[email protected]%3E%0A#%0Aimport sys%0A%0Aclass Tag(object):%0A _name = ''%0A def __init__(self, *a, **kw):%0A super(Tag, self).__init__()%0A self.content = list(a)%0A self.attributes = kw%0A%0A def __str__(self):%0A name = self._name%0A content = ''.join(str(c) for c in self.content)%0A atts = ''.join(%0A ' %7B%7D=%22%7B%7D%22'.format(k, v) for k, v in self.attributes.iteritems())%0A if content:%0A return '%3C%7B0%7D%7B1%7D%3E%7B2%7D%3C/%7B0%7D%3E'.format(name, atts, content)%0A else:%0A return '%3C%7B0%7D%7B1%7D/%3E'.format(name, atts)%0A%0A def add(self, *content):%0A self.content.extend(content)%0A if 1 == len(content):%0A return content%5B0%5D%0A else:%0A return content%0A%0A @staticmethod%0A def factory(name):%0A class NT(Tag): _name = name%0A NT.__name__ = name.replace('-', '_').replace('.', '_')%0A return NT.__name__, NT%0A%0A @staticmethod%0A def vivify(tags, into = None):%0A if into is None:%0A into = sys.modules%5B__name__%5D%0A for tag in tags:%0A setattr(into, *Tag.factory(tag))%0A
9c6130b5f9337b428f530cfae7036b7be2a9eea4
test commit
etk2/DefaultDocumentSelector.py
etk2/DefaultDocumentSelector.py
Python
0.000001
@@ -0,0 +1,3356 @@ +import json%0Aimport jsonpath_rw%0Aimport re%0Afrom document import Document%0A%0A%0Aclass DefaultDocumentSelector(DocumentSelector):%0A%0A def __init__(self):%0A pass%0A %22%22%22%0A A concrete implementation of DocumentSelector that supports commonly used methods for%0A selecting documents.%0A %22%22%22%0A%0A %22%22%22%0A Args:%0A document ():%0A datasets (List%5Bstr%5D): test the %22dataset%22 attribute in the doc contains any of the strings provided%0A url_patterns (List%5Bstr%5D): test the %22url%22 of the doc matches any of the regexes using regex.search%0A website_patterns (List%5Bstr%5D): test the %22website%22 of the doc contains any of the regexes using regex.search%0A json_paths (List%5Bstr%5D): test existence of any of the given JSONPaths in a document%0A json_paths_regex(List%5Bstr%5D): test that any of the values selected in 'json_paths' satisfy any of%0A the regexex provided using regex.search%0A%0A Returns: True if the document satisfies all non None arguments.%0A Each of the arguments can be a list, in which case satisfaction means%0A that one of the elements in the list is satisfied, i.e., it is an AND of ORs%0A%0A For efficiency, the class caches compiled representations of all regexes and json_paths given%0A that the same selectors will be used for consuming all documents in a stream.%0A %22%22%22%0A def select_document(self,%0A document: Document,%0A datasets: List%5Bstr%5D = None,%0A url_patterns: List%5Bstr%5D = None,%0A website_patterns: List%5Bstr%5D = None,%0A json_paths: List%5Bstr%5D = None,%0A json_paths_regex: List%5Bstr%5D = None) -%3E bool:%0A%0A if (json_paths_regex is not None) and (json_paths is None):%0A # TODO: print out some error message here%0A%0A if url_patterns is not None:%0A rw_url_patterns = map(lambda re: re.compile(), url_patterns)%0A%0A if website_patterns is not None:%0A rw_website_patterns = map(lambda re: re.compile(), website_patterns)%0A%0A if json_paths is not None:%0A rw_json_paths = map(lambda jsonpath_rw: jsonpath_rw.parse(), json_paths)%0A%0A if json_paths_regex is not None:%0A rw_json_paths_regex = map(lambda re: re.compile(), json_paths_regex)%0A%0A%0A doc = Document.cdr_document%0A%0A return False;%0A%0A raise NotImplementedError%0A%0A def check_datasets_condition(self, json_doc: dict, datasets: List%5Bstr%5D) -%3E bool:%0A%0A raise NotImplementedError%0A%0A def check_url_patterns_condition(self, json_doc: dict, %0A compiled_url_patterns: List%5Bstr%5D) -%3E bool:%0A%0A raise NotImplementedError%0A%0A def check_website_patterns_condition(self, json_doc: dict, %0A compiled_website_patterns: List%5Bstr%5D) -%3E bool:%0A %0A raise NotImplementedError%0A%0A def check_json_path_codition(self, json_doc: dict, %0A rw_json_paths: List%5Bjsonpath_rw.jsonpath.Child%5D, %0A compiled_json_paths_regex: List%5Bstr%5D) -%3E bool:%0A for json_path_expr in rw_json_paths:%0A json_path_values = %5Bmatch.value for match in json_path_expr.find(json_doc)%5D%0A for %0A%0A pass%0A raise NotImplementedError%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A
e5f77ccc2f51fdcaa32c55b56f6b801b3ae2e0e2
Add triggered oscilloscope example
example/pyaudio_triggerscope.py
example/pyaudio_triggerscope.py
Python
0.000001
@@ -0,0 +1,1843 @@ +%22%22%22%0ASimple demonstration of streaming data from a PyAudio device to a QOscilloscope%0Aviewer.%0A%0ABoth device and viewer nodes are created locally without a manager.%0A%22%22%22%0A%0Afrom pyacq.devices.audio_pyaudio import PyAudio%0Afrom pyacq.viewers import QTriggeredOscilloscope%0Aimport pyqtgraph as pg%0A%0A%0A# Start Qt application%0Aapp = pg.mkQApp()%0A%0A%0A# Create PyAudio device node%0Adev = PyAudio()%0A%0A# Print a list of available input devices (but ultimately we will just use the %0A# default device).%0Adefault_input = dev.default_input_device()%0Aprint(%22%5CnAvaliable devices:%22)%0Afor device in dev.list_device_specs():%0A index = device%5B'index'%5D%0A star = %22*%22 if index == default_input else %22 %22%0A print(%22 %25s %25d: %25s%22 %25 (star, index, device%5B'name'%5D))%0A%0A# Configure PyAudio device with a single (default) input channel.%0Adev.configure(nb_channel=1, sample_rate=44100., input_device_index=default_input,%0A format='int16', chunksize=1024)%0Adev.output.configure(protocol='tcp', interface='127.0.0.1', transfertmode='plaindata')%0Adev.initialize()%0A%0A%0A# Create a triggered oscilloscope to display data.%0Aviewer = QTriggeredOscilloscope()%0Aviewer.configure(with_user_dialog = True)%0A%0A# Connect audio stream to oscilloscope%0Aviewer.input.connect(dev.output)%0A%0Aviewer.initialize()%0Aviewer.show()%0A#viewer.params%5B'decimation_method'%5D = 'min_max'%0A#viewer.by_channel_params%5B'Signal0', 'gain'%5D = 0.001%0A%0Aviewer.trigger.params%5B'threshold'%5D = 1.%0Aviewer.trigger.params%5B'debounce_mode'%5D = 'after-stable'%0Aviewer.trigger.params%5B'front'%5D = '+'%0Aviewer.trigger.params%5B'debounce_time'%5D = 0.1%0Aviewer.triggeraccumulator.params%5B'stack_size'%5D = 3%0Aviewer.triggeraccumulator.params%5B'left_sweep'%5D = -.2%0Aviewer.triggeraccumulator.params%5B'right_sweep'%5D = .5%0A%0A%0A# Start both nodes%0Adev.start()%0Aviewer.start()%0A%0A%0Aif __name__ == '__main__':%0A import sys%0A if sys.flags.interactive == 0:%0A app.exec_()%0A
5c5c2e9ae69b6543830975239068d34620205119
add context logger
logging/logger_reload_with_context.py
logging/logger_reload_with_context.py
Python
0.000007
@@ -0,0 +1,1089 @@ +import logging%0Aimport traceback%0Afrom yaml_config import yaml_config%0A%0Ayaml_config('yaml.conf')%0A%0A%0Aclass ContextLogger(object):%0A def __init__(self, name):%0A self.logger = logging.getLogger(name)%0A%0A def _context(self):%0A stack = traceback.extract_stack()%0A (filename, line, procname, text) = stack%5B-3%5D%0A return ' %5Bloc%5D ' + filename + ':' + procname + ':' + str(line)%0A%0A def critical(self, msg):%0A self.logger.critical('%5Bmsg%5D ' + str(msg) + self._context())%0A%0A def error(self, msg):%0A self.logger.error('%5Bmsg%5D ' + str(msg) + self._context())%0A%0A def warning(self, msg):%0A self.logger.warning('%5Bmsg%5D ' + str(msg) + self._context())%0A%0A def info(self, msg):%0A self.logger.info('%5Bmsg%5D ' + str(msg) + self._context())%0A%0A def debug(self, msg):%0A self.logger.debug('%5Bmsg%5D ' + str(msg) + self._context())%0A%0A%0Alogger = ContextLogger('root') # logging.getLogger('test')%0A%0A%0Aclass A(object):%0A def test(self):%0A try:%0A raise Exception('WTF!')%0A except Exception as e:%0A logger.error(e)%0A%0A%0Aa = A()%0Aa.test()%0A
bc7f1363a7da1375b62f70caf441423af2718641
Create example.py
BMP085/example.py
BMP085/example.py
Python
0.000001
@@ -0,0 +1,432 @@ +# Continuously polls the BMP180 Pressure Sensor%0Aimport pyb%0Aimport BMP085 %0A%0A# creating objects%0Ablue = pyb.LED(4)%0Abmp180 = BMP085.BMP085(port=2,address=0x77,mode=3,debug=False)%0Awhile 1:%0A blue.toggle()%0A temperature = bmp180.readTemperature()%0A print(%22%25f celcius%22 %25 temperature) %0A pressure = bmp180.readPressure()%0A print(%22%25f pascal%22 %25 pressure)%0A altitude = bmp180.readAltitude()%0A print(%22%25f meters%22 %25 altitude)%0A pyb.delay(100)%0A
153d36cd0c9eb4229156ac944c2ba64f2f9e72d6
fix test
msmbuilder/tests/test_featurizer.py
msmbuilder/tests/test_featurizer.py
import numpy as np from mdtraj import compute_dihedrals, compute_phi from mdtraj.testing import eq from msmbuilder.example_datasets import fetch_alanine_dipeptide from msmbuilder.featurizer import get_atompair_indices, FunctionFeaturizer, \ DihedralFeaturizer, AtomPairsFeaturizer, SuperposeFeaturizer, \ RMSDFeaturizer, VonMisesFeaturizer, Slicer def test_function_featurizer(): dataset = fetch_alanine_dipeptide() trajectories = dataset["trajectories"] trj0 = trajectories[0] # use the dihedral to compute phi for ala atom_ind = [[4, 6, 8, 14]] func = compute_dihedrals # test with args f = FunctionFeaturizer(func, func_args={"indices": atom_ind}) res1 = f.transform([trj0]) # test with function in a fucntion without any args def funcception(trj): return compute_phi(trj)[1] f = FunctionFeaturizer(funcception) res2 = f.transform([trj0]) # know results f3 = DihedralFeaturizer(['phi'], sincos=False) res3 = f3.transform([trj0]) # compare all for r in [res2, res3]: np.testing.assert_array_almost_equal(res1, r) def test_that_all_featurizers_run(): # TODO: include all featurizers, perhaps with generator tests dataset = fetch_alanine_dipeptide() trajectories = dataset["trajectories"] trj0 = trajectories[0][0] atom_indices, pair_indices = get_atompair_indices(trj0) featurizer = AtomPairsFeaturizer(pair_indices) X_all = featurizer.transform(trajectories) featurizer = SuperposeFeaturizer(np.arange(15), trj0) X_all = featurizer.transform(trajectories) featurizer = DihedralFeaturizer(["phi", "psi"]) X_all = featurizer.transform(trajectories) featurizer = VonMisesFeaturizer(["phi", "psi"]) X_all = featurizer.transform(trajectories) # Below doesn't work on ALA dipeptide # featurizer = msmbuilder.featurizer.ContactFeaturizer() # X_all = featurizer.transform(trajectories) featurizer = RMSDFeaturizer(trj0) X_all = featurizer.transform(trajectories) def test_von_mises_featurizer(): dataset = fetch_alanine_dipeptide() trajectories = dataset["trajectories"] featurizer = VonMisesFeaturizer(["phi", "psi"], n_bins=18) X_all = featurizer.transform(trajectories) assert X_all[0].shape == (9999, 36), ("unexpected shape returned: (%s, %s)" % X_all[0].shape) featurizer = VonMisesFeaturizer(["phi", "psi"], n_bins=10) X_all = featurizer.transform(trajectories) assert X_all[0].shape == (9999, 20), ("unexpected shape returned: (%s, %s)" % X_all[0].shape) def test_slicer(): X = ([np.random.normal(size=(50, 5), loc=np.arange(5))] + [np.random.normal(size=(10, 5), loc=np.arange(5))]) slicer = Slicer(index=[0, 1]) Y = slicer.transform(X) eq(len(Y), len(X)) eq(Y[0].shape, (50, 2)) slicer = Slicer(first=2) Y2 = slicer.transform(X) eq(len(Y2), len(X)) eq(Y2[0].shape, (50, 2)) eq(Y[0], Y2[0]) eq(Y[1], Y2[1])
Python
0.000002
@@ -2256,32 +2256,72 @@ m(trajectories)%0A + n_frames = trajectories%5B0%5D.n_frames%0A assert X_all @@ -2334,20 +2334,24 @@ ape == ( -9999 +n_frames , 36), ( @@ -2593,12 +2593,16 @@ == ( -9999 +n_frames , 20
6c08209ee26210df07b9d80da45d815b595205ae
test for new Wigner function
test_wigner.py
test_wigner.py
Python
0.000001
@@ -0,0 +1,516 @@ +from qutip import *%0Afrom mpl_toolkits.mplot3d import Axes3D%0Afrom matplotlib import cm%0Afrom pylab import *%0AN = 20;%0Apsi=(coherent(N,-2-2j)+coherent(N,2+2j)).unit()%0A#psi = ket2dm(basis(N,0))%0Axvec = linspace(-5.,5.,200)%0Ayvec = xvec%0AX,Y = meshgrid(xvec, yvec)%0AW = wigner(psi,xvec,xvec);%0Afig2 = plt.figure(figsize=(9, 6))%0Aax = Axes3D(fig2,azim=-107,elev=49)%0Asurf=ax.plot_surface(X, Y, W, rstride=1, cstride=1, cmap=cm.jet, alpha=1.0,linewidth=0.05)%0Afig2.colorbar(surf, shrink=0.65, aspect=20)%0Asavefig(%22test.png%22)%0A#show()%0A%0A
1ffdfc3c7ae11c583b2ea4d45b50136996bcf3e3
Add mock HTTP server to respond to requests from web UI
tests/mocks.py
tests/mocks.py
Python
0
@@ -0,0 +1,2149 @@ +from http.server import BaseHTTPRequestHandler, HTTPServer%0Aimport json%0Aimport socket%0Afrom threading import Thread%0A%0Aimport requests%0A%0A# https://realpython.com/blog/python/testing-third-party-apis-with-mock-servers/%0A%0Aclass MockHTTPServerRequestHandler(BaseHTTPRequestHandler):%0A%0A def do_OPTIONS(self):%0A # add response codes%0A self.send_response(requests.codes.okay)%0A%0A # add response headers%0A self.send_header('Access-Control-Allow-Origin', '*')%0A self.send_header('Access-Control-Allow-Credentials', 'true')%0A self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')%0A self.send_header('Access-Control-Allow-Headers', 'dataType, accept, authoriziation')%0A self.end_headers()%0A%0A def do_GET(self):%0A # add response codes%0A self.send_response(requests.codes.ok)%0A%0A # add response headers%0A self.send_header('Content-Type', 'application/json; charset=utf-8')%0A self.end_headers()%0A%0A # add response content%0A response_content = json.dumps(%7B'Message': 'Success'%7D)%0A self.wfile.write(response_content.encode('utf-8'))%0A return%0A%0A def do_POST(self):%0A # add response codes%0A self.send_response(requests.codes.created)%0A%0A # add response headers%0A self.send_header('Content-Type', 'application/json; charset=utf-8')%0A self.send_header('Access-Control-Allow-Origin', '*')%0A self.send_header('Access=Control-Allow-Methods', 'POST, GET, OPTIONS, DELETE, PUT')%0A self.end_headers()%0A%0A # add response content%0A response_content = json.dumps(%7B'Message': %7B'task_ids': %5B1234%5D%7D%7D)%0A self.wfile.write(response_content.encode('utf-8'))%0A return%0A%0Adef get_free_server_port():%0A s = socket.socket(socket.AF_INET, type=socket.SOCK_STREAM)%0A s.bind(('localhost', 0))%0A address, port = s.getsockname()%0A s.close()%0A return port%0A%0Adef start_mock_server(port=8080):%0A mock_server = HTTPServer(('localhost', port), MockHTTPServerRequestHandler)%0A mock_server_thread = Thread(target=mock_server.serve_forever)%0A mock_server_thread.setDaemon(True)%0A mock_server_thread.start()%0A
481b822125de1d29de09975a6607c4fa038b98df
Add model List
todo/models.py
todo/models.py
Python
0.000001
@@ -0,0 +1,370 @@ +from django.db import models%0Afrom django.utils.text import slugify%0A%0Afrom common.models import TimeStampedModel%0A%0A%0Aclass List(TimeStampedModel):%0A name = models.CharField(max_length=50)%0A slug = models.CharField(max_length=50, editable=False)%0A%0A def save(self, *args, **kwargs):%0A self.slug = slugify(self.name)%0A super(List, self).save(*args, **kwargs)%0A
744d7971926bf7672ce01388b8617be1ee35df0e
Add missing test data folder
xunit-autolabeler-v2/ast_parser/core/test_data/parser/exclude_tags/exclude_tags_main.py
xunit-autolabeler-v2/ast_parser/core/test_data/parser/exclude_tags/exclude_tags_main.py
Python
0.000001
@@ -0,0 +1,729 @@ +# Copyright 2020 Google LLC.%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0A%0A# %5BSTART main_method%5D%0Adef main():%0A return 'main method'%0A# %5BSTART_EXCLUDE%5D%0A%0A# %5BEND_EXCLUDE%5D%0Adef not_main():%0A return 'not main'%0A# %5BEND main_method%5D%0A
156c0b09930bd7700cb7348197a9e167831dca6d
ADD initial syft.lib.util tests
packages/syft/tests/syft/lib/util_test.py
packages/syft/tests/syft/lib/util_test.py
Python
0
@@ -0,0 +1,593 @@ +#absolute%0Afrom syft.lib.util import full_name_with_name%0Afrom syft.lib.util import full_name_with_qualname%0A%0Aclass TSTClass:%0A pass%0A%0Aclass FromClass:%0A%0A @staticmethod%0A def static_method():%0A pass%0A %0A def not_static_method(self):%0A pass%0A%0Aclass ToClass:%0A pass%0A%0A%0Adef test_full_name_with_name():%0A assert full_name_with_name(TSTClass) == f%22%7BTSTClass.__module__%7D.%7BTSTClass.__name__%7D%22%0A%0Adef test_full_name_with_qualname():%0A class LocalTSTClass:%0A pass%0A assert full_name_with_qualname(LocalTSTClass) == f%22%7BLocalTSTClass.__module__%7D.%7BLocalTSTClass.__qualname__%7D%22%0A
2eb849578b7306762f1e9dc4962a9db2ad651fc9
add solution for Linked List Cycle II
src/linkedListCycleII.py
src/linkedListCycleII.py
Python
0
@@ -0,0 +1,642 @@ +# Definition for singly-linked list.%0A# class ListNode:%0A# def __init__(self, x):%0A# self.val = x%0A# self.next = None%0A%0A%0Aclass Solution:%0A # @param head, a ListNode%0A # @return a list node%0A%0A def detectCycle(self, head):%0A slow = fast = head%0A no_loop = True%0A while fast and fast.next:%0A slow = slow.next%0A fast = fast.next.next%0A if slow == fast:%0A no_loop = False%0A break%0A if no_loop:%0A return None%0A fast = head%0A while slow != fast:%0A slow = slow.next%0A fast = fast.next%0A return slow%0A
855f9afa6e8d7afba020dc5c1dc8fabfc84ba2d4
add new package : jafka (#14304)
var/spack/repos/builtin/packages/jafka/package.py
var/spack/repos/builtin/packages/jafka/package.py
Python
0
@@ -0,0 +1,1340 @@ +# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass Jafka(Package):%0A %22%22%22%0A Jafka is a distributed publish-subscribe messaging system.%0A %22%22%22%0A%0A homepage = %22https://github.com/adyliu/jafka%22%0A url = %22https://github.com/adyliu/jafka/releases/download/3.0.6/jafka-3.0.6.tgz%22%0A%0A version('3.0.6', sha256='89c9456360ace5d43c3af52b5d2e712fc49be2f88b1b3dcfe0c8f195a3244e17')%0A version('3.0.5', sha256='43f1b4188a092c30f48f9cdd0bddd3074f331a9b916b6cb566da2e9e40bc09a7')%0A version('3.0.4', sha256='a5334fc9280764f9fd4b5eb156154c721f074c1bcc1e5496189af7c06cd16b45')%0A version('3.0.3', sha256='226e902af7754bb0df2cc0f30195e4f8f2512d9935265d40633293014582c7e2')%0A version('3.0.2', sha256='c7194476475a9c3cc09ed5a4e84eecf47a8d75011f413b26fd2c0b66c598f467')%0A version('3.0.1', sha256='3a75e7e5bb469b6d9061985a1ce3b5d0b622f44268da71cab4a854bce7150d41')%0A version('3.0.0', sha256='4c4bacdd5fba8096118f6e842b4731a3f7b3885514fe1c6b707ea45c86c7c409')%0A version('1.6.2', sha256='fbe5d6a3ce5e66282e27c7b71beaeeede948c598abb452abd2cae41149f44196')%0A%0A depends_on('java@7:', type='run')%0A%0A def install(self, spec, prefix):%0A install_tree('.', prefix)%0A
665a373f12f030d55a5d004cbce51e9a86428a55
Add the main rohrpost handler
rohrpost/main.py
rohrpost/main.py
Python
0.00017
@@ -0,0 +1,1274 @@ +import json%0Afrom functools import partial%0A%0Afrom . import handlers # noqa%0Afrom .message import send_error%0Afrom .registry import HANDLERS%0A%0A%0AREQUIRED_FIELDS = %5B'type', 'id'%5D%0A%0A%0Adef handle_rohrpost_message(message):%0A %22%22%22%0A Handling of a rohrpost message will validate the required format:%0A A valid JSON object including at least an %22id%22 and %22type%22 field.%0A It then hands off further handling to the registered handler (if any).%0A %22%22%22%0A _send_error = partial(send_error, message, None, None)%0A if not message.content%5B'text'%5D:%0A return _send_error('Received empty message.')%0A%0A try:%0A request = json.loads(message.content%5B'text'%5D)%0A except json.JSONDecodeError as e:%0A return _send_error('Could not decode JSON message. Error: %7B%7D'.format(str(e)))%0A%0A if not isinstance(request, dict):%0A return _send_error('Expected a JSON object as message.')%0A%0A for field in REQUIRED_FIELDS:%0A if field not in request:%0A return _send_error(%22Missing required field '%7B%7D'.%22.format(field))%0A%0A if not request%5B'type'%5D in HANDLERS:%0A return send_error(%0A message, request%5B'id'%5D, request%5B'type'%5D,%0A %22Unknown message type '%7B%7D'.%22.format(request%5B'type'%5D),%0A )%0A%0A HANDLERS%5Brequest%5B'type'%5D%5D(message, request)%0A
8084a3be60e35e5737047f5b2d2daf8dce0cec1a
Update sliding-window-maximum.py
Python/sliding-window-maximum.py
Python/sliding-window-maximum.py
# Time: O(n) # Space: O(k) # Given an array nums, there is a sliding window of size k # which is moving from the very left of the array to the # very right. You can only see the k numbers in the window. # Each time the sliding window moves right by one position. # # For example, # Given nums = [1,3,-1,-3,5,3,6,7], and k = 3. # # Window position Max # --------------- ----- # [1 3 -1] -3 5 3 6 7 3 # 1 [3 -1 -3] 5 3 6 7 3 # 1 3 [-1 -3 5] 3 6 7 5 # 1 3 -1 [-3 5 3] 6 7 5 # 1 3 -1 -3 [5 3 6] 7 6 # 1 3 -1 -3 5 [3 6 7] 7 # Therefore, return the max sliding window as [3,3,5,5,6,7]. # # Note: # You may assume k is always valid, ie: 1 <= k <= input array's size for non-empty array. # # Follow up: # Could you solve it in linear time? from collections import deque class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ dq = deque() max_numbers = [] for i in xrange(len(nums)): while dq and nums[i] >= nums[dq[-1]]: dq.pop() dq.append(i) if i >= k and dq and dq[0] <= i - k: dq.popleft() if i >= k - 1: max_numbers.append(nums[dq[0]]) return max_numbers
Python
0.000001
@@ -1248,17 +1248,17 @@ d dq%5B0%5D -%3C += = i - k:
f8bd2205e57e7a3b457e20b678d69065b620c965
Create __init__.py
votesim/__init__.py
votesim/__init__.py
Python
0.000429
@@ -0,0 +1 @@ +%0A
24baf3e5e7a608d0b34d74be25f96f1b74b7622e
Add feed update task for social app
web/social/tasks.py
web/social/tasks.py
Python
0.000014
@@ -0,0 +1,393 @@ +from celery.task import PeriodicTask%0Afrom datetime import timedelta%0A%0Afrom social.utils import FeedUpdater, UpdateError%0A%0Aclass UpdateFeedsTask(PeriodicTask):%0A run_every = timedelta(minutes=15)%0A%0A def run(self, **kwargs):%0A logger = self.get_logger()%0A updater = FeedUpdater(logger)%0A print %22Updating feeds%22%0A updater.update_feeds()%0A print %22Feed update done%22%0A
115145da5063c47009e93f19aa5645e0dbb2580f
add missing migration for tests
tests/migrations/0002_auto_20210712_1629.py
tests/migrations/0002_auto_20210712_1629.py
Python
0.000001
@@ -0,0 +1,1951 @@ +# Generated by Django 2.2.24 on 2021-07-12 21:29%0A%0Aimport django.contrib.gis.db.models.fields%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('tests', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.CreateModel(%0A name='Pizzeria',%0A fields=%5B%0A ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),%0A ('hq', django.contrib.gis.db.models.fields.PointField(srid=4326)),%0A ('directions', django.contrib.gis.db.models.fields.LineStringField(srid=4326)),%0A ('floor_plan', django.contrib.gis.db.models.fields.PolygonField(srid=4326)),%0A ('locations', django.contrib.gis.db.models.fields.MultiPointField(srid=4326)),%0A ('routes', django.contrib.gis.db.models.fields.MultiLineStringField(srid=4326)),%0A ('delivery_areas', django.contrib.gis.db.models.fields.MultiPolygonField(srid=4326)),%0A ('all_the_things', django.contrib.gis.db.models.fields.GeometryCollectionField(srid=4326)),%0A ('rast', django.contrib.gis.db.models.fields.RasterField(srid=4326)),%0A %5D,%0A ),%0A migrations.AlterField(%0A model_name='chef',%0A name='email_address',%0A field=models.EmailField(max_length=254),%0A ),%0A migrations.AlterField(%0A model_name='chef',%0A name='twitter_profile',%0A field=models.URLField(),%0A ),%0A migrations.AlterField(%0A model_name='pizza',%0A name='thickness',%0A field=models.CharField(choices=%5B(0, 'thin'), (1, 'thick'), (2, 'deep dish')%5D, max_length=50),%0A ),%0A migrations.AlterField(%0A model_name='pizza',%0A name='toppings',%0A field=models.ManyToManyField(related_name='pizzas', to='tests.Topping'),%0A ),%0A %5D%0A