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
|
---|---|---|---|---|---|---|---|
2d320058c96f88348d8226fa4a827a6c2c973237 | Add Classical multidimensional scaling algorithm. | mds.py | mds.py | Python | 0.000001 | @@ -0,0 +1,1664 @@
+%22%22%22%0ASimple implementation of classical MDS.%0ASee http://www.stat.cmu.edu/~ryantibs/datamining/lectures/09-dim3-marked.pdf for more details.%0A%22%22%22%0A%0Aimport numpy as np%0Aimport numpy.linalg as linalg%0Aimport matplotlib.pyplot as plt%0A%0Adef square_points(size):%0A%09nsensors = size**2%0A%09return np.array(%5B(i/size, i%25size) for i in range(nsensors)%5D)%0A%09%0Adef norm(vec):%0A%09return np.sqrt(np.sum(vec**2))%0A%09%0Adef mds(D, dim=2):%0A%09%22%22%22%0A%09Classical multidimensional scaling algorithm.%0A%09Given a matrix of interpoint distances D, find a set of low dimensional points%0A%09that have a similar interpoint distances.%0A%09%22%22%22%0A%09(n,n) = D.shape%0A%09A = (-0.5 * D**2)%0A%09M = np.ones((n,n))/n%0A%09I = np.eye(n)%0A%09B = np.dot(np.dot(I-M, A),I-M)%0A%09%0A%09'''Another way to compute inner-products matrix B%0A%09Ac = np.mat(np.mean(A, 1))%0A%09Ar = np.mat(np.mean(A, 0))%0A%09B = np.array(A - np.transpose(Ac) - Ar + np.mean(A))%0A%09'''%0A%09%0A%09%5BU,S,V%5D = linalg.svd(B)%0A%09Y = U * np.sqrt(S)%0A%09return (Y%5B:,0:dim%5D, S)%0A%09%0Adef test():%0A%09points = square_points(10)%0A%09distance = np.zeros((100,100))%0A%09for (i, pointi) in enumerate(points):%0A%09%09for (j, pointj) in enumerate(points):%0A%09%09%09distance%5Bi,j%5D = norm(pointi-pointj)%0A%09%0A%09Y, eigs = mds(distance)%0A%09%0A%09plt.figure()%0A%09plt.plot(Y%5B:,0%5D, Y%5B:,1%5D, '.')%0A%09plt.figure(2)%0A%09plt.plot(points%5B:,0%5D, points%5B:,1%5D, '.')%0A%09plt.show()%0A%09%0Adef main():%0A%09import sys, os, getopt, pdb%0A%09def usage():%0A%09%09print sys.argv%5B0%5D + %22%5B-h%5D %5B-d%5D%22%0A%09%09%0A%09try:%0A%09%09(options, args) = getopt.getopt(sys.argv%5B1:%5D, 'dh', %5B'help', 'debug'%5D)%0A%09except getopt.GetoptError:%0A%09%09usage()%0A%09%09sys.exit(2)%0A%09%09%0A%09for o, a in options:%0A%09%09if o in ('-h', '--help'):%0A%09%09%09usage()%0A%09%09%09sys.exit()%0A%09%09elif o in ('-d', '--debug'):%0A%09%09%09pdb.set_trace()%0A%09%09%09%0A%09test()%0A%09%0A%09%0Aif __name__ == '__main__':%0A%09main()
|
|
fe128c1172070476ba09536bbbbe81c69a46ef57 | fix bgp reggression | ryu/services/protocols/bgp/operator/commands/show/route_formatter_mixin.py | ryu/services/protocols/bgp/operator/commands/show/route_formatter_mixin.py | import io
class RouteFormatterMixin(object):
fmtstr = ' {0:<3s} {1:<32s} {2:<8s} {3:<20s} {4:<15s} '\
'{5:<6s} {6:<6s} {7:<}\n'
@classmethod
def _format_family_header(cls):
ret = ''
ret += ('Status codes: * valid, > best\n')
ret += ('Origin codes: i - IGP, e - EGP, ? - incomplete\n')
ret += cls.fmtstr.format('', 'Network', 'Labels', 'Next Hop', 'Reason',
'Metric', 'LocPrf', 'Path')
return ret
@classmethod
def _format_family(cls, dest_list):
msg = io.StringIO()
def _append_path_info(buff, path, is_best, show_prefix):
aspath = path.get('aspath')
origin = path.get('origin')
if origin:
aspath.append(origin)
bpr = path.get('bpr')
next_hop = path.get('nexthop')
med = path.get('metric')
labels = path.get('labels')
localpref = path.get('localpref')
# Construct path status string.
path_status = '*'
if is_best:
path_status += '>'
# Check if we want to show prefix.
prefix = ''
if show_prefix:
prefix = path.get('prefix')
# Append path info to String buffer.
buff.write(cls.fmtstr.format(path_status, prefix, labels,
next_hop, bpr, str(med),
str(localpref),
' '.join(map(str, aspath))))
for dist in dest_list:
for idx, path in enumerate(dist.get('paths')):
_append_path_info(msg, path, path['best'], (idx == 0))
ret = msg.getvalue()
msg.close()
return ret
| Python | 0 | @@ -1,17 +1,18 @@
import
-io
+six
%0A%0A%0Aclass
@@ -557,16 +557,142 @@
-msg = io
+if six.PY3:%0A import io%0A msg = io.StringIO()%0A else:%0A import StringIO%0A msg = StringIO
.Str
|
a78d879c9c097c32c58f5246d46a4a188b17d99c | Add workup vebose name change migration. | workup/migrations/0002_add_verbose_names.py | workup/migrations/0002_add_verbose_names.py | Python | 0 | @@ -0,0 +1,2539 @@
+# -*- 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 ('workup', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='historicalworkup',%0A name='fam_hx',%0A field=models.TextField(verbose_name=b'Family History'),%0A ),%0A migrations.AlterField(%0A model_name='historicalworkup',%0A name='labs_ordered_internal',%0A field=models.TextField(null=True, verbose_name=b'Labs Ordered Internally', blank=True),%0A ),%0A migrations.AlterField(%0A model_name='historicalworkup',%0A name='labs_ordered_quest',%0A field=models.TextField(null=True, verbose_name=b'Labs Ordered from Quest', blank=True),%0A ),%0A migrations.AlterField(%0A model_name='historicalworkup',%0A name='ros',%0A field=models.TextField(verbose_name=b'ROS'),%0A ),%0A migrations.AlterField(%0A model_name='historicalworkup',%0A name='rx',%0A field=models.TextField(null=True, verbose_name=b'Prescription Orders', blank=True),%0A ),%0A migrations.AlterField(%0A model_name='historicalworkup',%0A name='soc_hx',%0A field=models.TextField(verbose_name=b'Social History'),%0A ),%0A migrations.AlterField(%0A model_name='workup',%0A name='fam_hx',%0A field=models.TextField(verbose_name=b'Family History'),%0A ),%0A migrations.AlterField(%0A model_name='workup',%0A name='labs_ordered_internal',%0A field=models.TextField(null=True, verbose_name=b'Labs Ordered Internally', blank=True),%0A ),%0A migrations.AlterField(%0A model_name='workup',%0A name='labs_ordered_quest',%0A field=models.TextField(null=True, verbose_name=b'Labs Ordered from Quest', blank=True),%0A ),%0A migrations.AlterField(%0A model_name='workup',%0A name='ros',%0A field=models.TextField(verbose_name=b'ROS'),%0A ),%0A migrations.AlterField(%0A model_name='workup',%0A name='rx',%0A field=models.TextField(null=True, verbose_name=b'Prescription Orders', blank=True),%0A ),%0A migrations.AlterField(%0A model_name='workup',%0A name='soc_hx',%0A field=models.TextField(verbose_name=b'Social History'),%0A ),%0A %5D%0A
|
|
d4a87c2131c02b3638743167ce32c779ece14fd5 | Create crawlerino.py | crawlerino.py | crawlerino.py | Python | 0.000005 | @@ -0,0 +1,2583 @@
+%22%22%22Simple web crawler, to be extended for various uses.%0A%0AWritten in Python 3, uses requests and BeautifulSoup modules.%0A%22%22%22%0A%0A%0Adef crawler(startpage, maxpages=100, singledomain=True):%0A %22%22%22Crawl the web starting from specified page.%0A%0A 1st parameter = starting page url%0A maxpages = maximum number of pages to crawl%0A singledomain = whether to only crawl links within startpage's domain%0A %22%22%22%0A import requests, re, bs4%0A from urllib.parse import urldefrag, urljoin, urlparse%0A from collections import deque%0A%0A pagequeue = deque() # queue of pages to be crawled%0A pagequeue.append(startpage)%0A crawled = %5B%5D # list of pages already crawled%0A domain = urlparse(startpage).netloc # for singledomain option%0A%0A pages = 0 # number of pages succesfully crawled so far%0A failed = 0 # number of pages that couldn't be crawled%0A%0A while pages %3C maxpages and pagequeue:%0A url = pagequeue.popleft() # get next page to crawl (FIFO queue)%0A try:%0A response = requests.get(url)%0A if not response.headers%5B'content-type'%5D.startswith('text/html'):%0A continue # don't crawl non-HTML links%0A soup = bs4.BeautifulSoup(response.text, %22html.parser%22)%0A print('Crawling:', url)%0A pages += 1%0A crawled.append(url)%0A%0A # PROCESSING CODE GOES HERE:%0A # do something interesting with this page%0A%0A # get target URLs for all links on the page%0A links = %5Ba.attrs.get('href') for a in soup.select('a%5Bhref%5D')%5D%0A # remove fragment identifiers%0A links = %5Burldefrag(link)%5B0%5D for link in links%5D%0A # remove any empty strings%0A links = list(filter(None,links))%0A # if it's a relative link, change to absolute%0A links = %5Blink if bool(urlparse(link).netloc) else urljoin(url,link) for link in links%5D%0A # if singledomain=True, remove links to other domains%0A if singledomain:%0A links = %5Blink for link in links if (urlparse(link).netloc == domain)%5D%0A%0A # add these links to the queue (except if already crawled)%0A for link in links:%0A if link not in crawled and link not in pagequeue:%0A pagequeue.append(link)%0A except:%0A print(%22*FAILED*:%22, url)%0A failed += 1%0A%0A print('%7B0%7D pages crawled, %7B1%7D pages failed to load.'.format(pages, failed))%0A%0A%0A# if running standalone, crawl some Microsoft pages as a test%0Aif __name__ == %22__main__%22:%0A crawler('http://www.microsoft.com', maxpages=30, singledomain=True)%0A
|
|
91facfcc42e001e2a598d6d06e55270ef9239b1d | add migration | actstream/migrations/0006_auto_20170329_2048.py | actstream/migrations/0006_auto_20170329_2048.py | Python | 0.000001 | @@ -0,0 +1,634 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.10.6 on 2017-03-29 20:48%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('actstream', '0005_auto_20161119_2211'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='action',%0A name='deleted',%0A field=models.BooleanField(default=False),%0A ),%0A migrations.AlterField(%0A model_name='action',%0A name='timestamp',%0A field=models.DateTimeField(auto_now_add=True, db_index=True),%0A ),%0A %5D%0A
|
|
1e050f30e8307a75976a52b8f1258a5b14e43733 | Add middleware for static serving | wsgi_static.py | wsgi_static.py | Python | 0.000001 | @@ -0,0 +1,207 @@
+import wsgi_server%0Aimport os%0Afrom werkzeug.wsgi import SharedDataMiddleware%0A%0Aapplication = SharedDataMiddleware(wsgi_server.application, %7B%0A '/static': os.path.join(os.path.dirname(__file__), 'static')%0A%7D)%0A
|
|
a086307e6aac341ed8a6596d0a05b7a8d198c7ec | Add command to dump and restore user pointers. | zephyr/management/commands/dump_pointers.py | zephyr/management/commands/dump_pointers.py | Python | 0 | @@ -0,0 +1,1046 @@
+from optparse import make_option%0Afrom django.core.management.base import BaseCommand%0Afrom zephyr.models import Realm, UserProfile%0Aimport simplejson%0A%0Adef dump():%0A pointers = %5B%5D%0A for u in UserProfile.objects.select_related(%22user__email%22).all():%0A pointers.append((u.user.email, u.pointer))%0A file(%22dumped-pointers%22, %22w%22).write(simplejson.dumps(pointers) + %22%5Cn%22)%0A%0Adef restore(change):%0A for (email, pointer) in simplejson.loads(file(%22dumped-pointers%22).read()):%0A u = UserProfile.objects.get(user__email=email)%0A print %22%25s: pointer %25s =%3E %25s%22 %25 (email, u.pointer, pointer)%0A if change:%0A u.pointer = pointer%0A u.save()%0A%0Aclass Command(BaseCommand):%0A option_list = BaseCommand.option_list + (%0A make_option('--restore', default=False, action='store_true'),%0A make_option('--dry-run', '-n', default=False, action='store_true'),)%0A%0A def handle(self, *args, **options):%0A if options%5B%22restore%22%5D:%0A restore(change=not options%5B'dry_run'%5D)%0A else:%0A dump()%0A
|
|
769abf579f7bd082f7c6f4295edb49b41b252bce | Add empty alembic revision | alembic/versions/4784a128a6dd_empty_revision.py | alembic/versions/4784a128a6dd_empty_revision.py | Python | 0.000003 | @@ -0,0 +1,520 @@
+%22%22%22Empty revision%0A%0AThis is the empty revision that can be used as the base for future%0Amigrations.%0A%0AInitial database creation shall be done via %60metadata.create_all()%60 and%0A%60alembic stamp head%60.%0A%0ARevision ID: 4784a128a6dd%0ARevises:%0ACreate Date: 2017-12-13 00:48:12.079431%0A%0A%22%22%22%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0Aimport pycroft%0A%0A%0A# revision identifiers, used by Alembic.%0Arevision = '4784a128a6dd'%0Adown_revision = None%0Abranch_labels = None%0Adepends_on = None%0A%0A%0Adef upgrade():%0A pass%0A%0A%0Adef downgrade():%0A pass%0A
|
|
4bf84b05b183916fd211f77ab8099ef14c9cec06 | Update migrations | app/timetables/migrations/0003_auto_20171107_1103.py | app/timetables/migrations/0003_auto_20171107_1103.py | Python | 0.000001 | @@ -0,0 +1,1250 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11 on 2017-11-07 11:03%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('timetables', '0002_auto_20171005_2209'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='course',%0A name='name',%0A field=models.CharField(help_text='Example: appetizer, main course, dessert', max_length=150, verbose_name='Course Name'),%0A ),%0A migrations.AlterField(%0A model_name='dish',%0A name='name',%0A field=models.CharField(max_length=255, verbose_name='Dish Name'),%0A ),%0A migrations.AlterField(%0A model_name='meal',%0A name='name',%0A field=models.CharField(max_length=60, verbose_name='Meal Name'),%0A ),%0A migrations.AlterField(%0A model_name='timetable',%0A name='name',%0A field=models.CharField(max_length=255, verbose_name='Timetable Name'),%0A ),%0A migrations.AlterField(%0A model_name='vendor',%0A name='name',%0A field=models.CharField(max_length=255, verbose_name='Vendor Name'),%0A ),%0A %5D%0A
|
|
74135b8289fa4b6684c54d8c9e37671c75b92447 | add admin for area settings | adhocracy4/maps/admin.py | adhocracy4/maps/admin.py | Python | 0 | @@ -0,0 +1,641 @@
+from django.contrib import admin%0Afrom django.utils.translation import ugettext_lazy as _%0A%0Afrom . import models%0A%0A%[email protected](models.AreaSettings)%0Aclass AreaSettingsAdmin(admin.ModelAdmin):%0A list_filter = ('module__project__organisation', 'module__project')%0A list_display = ('module',)%0A%0A fieldsets = (%0A (None, %7B'fields': ('module',)%7D),%0A (_('Polygon'), %7B%0A 'fields': ('polygon',),%0A 'description': _('Enter a valid GeoJSON object. '%0A 'To initialize a new areasetting enter the '%0A 'string %22false%22 without quotation marks.')%0A %7D)%0A )%0A
|
|
2dce9ed68463b536f246f01b2ac5cb275df2453b | add polynomial | regression.py | regression.py | Python | 0.999999 | @@ -0,0 +1,1838 @@
+# coding: utf8%0Afrom datetime import datetime%0Aimport itertools%0Aimport matplotlib.pyplot as plt%0Aimport numpy as np%0Afrom sklearn.preprocessing import PolynomialFeatures, Imputer%0Afrom sklearn.pipeline import make_pipeline%0Afrom sklearn.linear_model import Ridge, BayesianRidge%0Afrom utils import *%0A%0Adata_accidents = load_data_from_csv('data/parsered1.csv', False)%0Adata_weather = load_data_from_csv('data/weather_utf8.csv',False)%0A%0A'''%0ABecause of the fact that we don't have particular time (only dates) for accidents and do have time for weather%0Ameasurements, let's choose one time for all accident, e.g. 15:00.%0A'''%0A%0Afor i in data_accidents.index:%0A #converting date to standard datetime representation, adding particular time%0A data_accidents.ix%5Bi,'date'%5D = str(datetime.strptime(str(data_accidents.ix%5Bi,'date'%5D) + ' 15:00:00', '%25Y-%25m-%25d %25H:%25M:%25S'))%0A%0Afor i in data_weather.index:%0A data_weather.ix%5Bi,'date'%5D = str(datetime.strptime(str(data_weather.ix%5Bi,'date'%5D),'%25d.%25m.%25Y %25H:%25M'))%0A%0A#merging two datasets on date%0Adata = data_accidents.merge(data_weather, on='date')%0A%0A#casting to numpy array%0Aarray = np.array(data%5B%5B'num_dtp','T'%5D%5D.values, dtype=np.float64)%0A%0A#preprocessing, completing missing values%0Aimp = Imputer(missing_values='NaN', strategy='median', axis=1)%0Anew_data = imp.fit_transform(array)%0A%0A#sorting data by 'T', for better plotting%0Anew_data = new_data%5Bnew_data%5B:, 1%5D.argsort()%5D%0A%0Ax = new_data%5B:,1%5D%0Ay = new_data%5B:,0%5D%0A%0Ax_plot = x%0A%0AX = x%5B:,np.newaxis%5D%0AX_plot = x_plot%5B:,np.newaxis%5D%0A%0Aplt.scatter(x, y, s = 30, label=%22training points%22)%0A%0A#algos = itertools.cycle(%5BRidge(), BayesianRidge()%5D)%0A%0Afor degree in %5B1, 3, 5, 7%5D:%0A model = make_pipeline(PolynomialFeatures(degree), Ridge())%0A model.fit(X, y)%0A y_plot = model.predict(X_plot)%0A plt.plot(x_plot, y_plot, label=%22degree %25d%22 %25 degree)%0A%0Aplt.legend(loc='lower left')%0Aplt.show()%0A
|
|
96fc5553bb958d41ea61fd809102344a354b20bd | unicode to str | quack/quack.py | quack/quack.py | #!/usr/bin/env python
"""Quack!!"""
import argparse
import git
import os
import shutil
import subprocess
import types
import yaml
_ARGS = None
def _setup():
"""Setup parser if executed script directly."""
parser = argparse.ArgumentParser(description='Quack builder')
parser.add_argument(
'-y', '--yaml', help='Provide custom yaml. default: quack.yaml')
parser.add_argument(
'-p', '--profile', help='Run selected profile. default: init',
nargs='?')
return parser.parse_args()
def _remove_dir(directory):
"""Remove directory."""
if os.path.exists(directory):
shutil.rmtree(directory)
return True
return False
def _create_dir(directory):
"""Create directory."""
if not os.path.exists(directory):
os.makedirs(directory)
def _get_config():
"""Return yaml configuration."""
yaml_file = _ARGS.yaml or 'quack.yaml'
if os.path.isfile(yaml_file):
with open(yaml_file) as file_pointer:
return yaml.load(file_pointer)
return
def _fetch_modules(config, specific_module=None):
"""Fetch git submodules."""
module_list = config.get('modules')
if not module_list:
print('No modules found.')
return
modules = '.quack/modules'
ignore_list = []
_remove_dir('.git/modules/.quack')
_create_dir(modules)
if os.path.isfile('.gitignore'):
with open('.gitignore', 'r') as file_pointer:
ignore_list = list(set(file_pointer.read().split('\n')))
repo = git.Repo('.')
for module in module_list.items():
if specific_module and specific_module != module[0]:
continue
_remove_dir(module[0])
print('Cloning: ' + module[1]['repository'])
sub_module = repo.create_submodule(
module[0], modules + '/' + module[0],
url=module[1]['repository'],
branch=module[1].get('branch', 'master')
)
if module[1].get('hexsha'):
subprocess.call(
['git', 'checkout', '--quiet', module[1].get('hexsha')],
cwd=modules + '/' + module[0])
hexsha = ' (' + module[1].get('hexsha') + ')'
else:
hexsha = ' (' + sub_module.hexsha + ')'
print('\033[1A' + ' Cloned:', module[0] + hexsha)
print('\033[1A' + '\033[32m' + u'\u2713' + '\033[37m')
path = module[1].get('path', '')
from_path = '%s/%s/%s' % (modules, module[0], path)
is_exists = os.path.exists(from_path)
if (path and is_exists) or not path:
shutil.copytree(
from_path, module[0],
ignore=shutil.ignore_patterns('.git*'))
elif not is_exists:
print('%s folder does not exists. Skipped.' % path)
# Remove submodule.
sub_module.remove()
if os.path.isfile('.gitmodules'):
subprocess.call('rm .gitmodules'.split())
subprocess.call('git rm --quiet --cached .gitmodules'.split())
with open('.gitignore', 'a') as file_pointer:
if module[0] not in ignore_list:
file_pointer.write('\n' + module[0])
ignore_list.append(module[0])
def _clean_modules(config, specific_module=None):
"""Remove all given modules."""
for module in config.get('modules').items():
if specific_module and specific_module != module[0]:
continue
if _remove_dir(module[0]):
print('Cleaned', module[0])
def _run_dependencies(dependency):
"""Execute all required dependencies."""
if not dependency or dependency[0] != 'quack':
return
quack = dependency[1]
slash_index = quack.rfind('/')
command = ['quack']
if slash_index == -1:
print('Quack..' + quack)
git.Repo.init(quack)
subprocess.call(command, cwd=quack)
_remove_dir(quack + '/.git')
elif slash_index > 0:
module = quack[:slash_index]
colon_index = quack.find(':')
if len(quack) > colon_index + 1:
command.append('-p')
command.append(quack[colon_index + 1: len(quack)])
if colon_index > 0:
command.append('-y')
command.append(quack[slash_index + 1:colon_index])
print('Quack..' + module)
git.Repo.init(module)
subprocess.call(command, cwd=module)
_remove_dir(module + '/.git')
print
def _run_tasks(config, profile):
"""Run given tasks."""
dependencies = profile.get('dependencies', {})
if isinstance(dependencies, types.DictionaryType):
for dependency in profile.get('dependencies', {}).items():
_run_dependencies(dependency)
tasks = profile.get('tasks', [])
if not tasks:
print('No tasks found.')
return
for command in tasks:
is_negate = command[0] == '-'
if is_negate:
command = command[1:]
module = None
is_modules = command.find('modules:') == 0 or 'modules' == command
is_quack = command.find('quack:') == 0
is_cmd = command.find('cmd:') == 0
if is_modules and command != 'modules':
module = command.replace('modules:', '')
elif is_quack:
_run_dependencies(('quack', command.replace('quack:', '')))
elif is_cmd:
cmd = command.replace('cmd:', '')
subprocess.call(cmd.split())
if is_modules and not is_negate:
_fetch_modules(config, module)
elif is_modules and is_negate:
_clean_modules(config, module)
def _prompt_to_create():
"""Prompt user to create quack configuration."""
yes_or_no = raw_input(
'No quack configuration found, do you want to create one? (y/N): ')
if yes_or_no.lower() == 'y':
project_name = raw_input('Provide project name: ')
with open('quack.yaml', 'a') as file_pointer:
file_pointer.write("""name: %s
modules:
profiles:
init:
tasks: ['modules']""" % project_name)
return _get_config()
return
def main():
"""Entry point."""
_create_dir('.quack')
config = _get_config()
if not config:
config = _prompt_to_create()
if not config:
return
if not _ARGS.profile:
_ARGS.profile = 'init'
profile = config.get('profiles', {}).get(_ARGS.profile, {})
# print(_ARGS.profile, profile)
_run_tasks(config, profile)
if __name__ == '__main__':
_ARGS = _setup()
main()
| Python | 0.999998 | @@ -2352,17 +2352,16 @@
%5B32m' +
-u
'%5Cu2713'
|
eb91b11930319369bc9cfc3b1b15c0b92fb4d85c | Add `OrganizationOption` tests based on `ProjectOption`. | tests/sentry/models/test_organizationoption.py | tests/sentry/models/test_organizationoption.py | Python | 0 | @@ -0,0 +1,1629 @@
+# -*- coding: utf-8 -*-%0A%0Afrom __future__ import absolute_import%0A%0Afrom sentry.models import OrganizationOption%0Afrom sentry.testutils import TestCase%0A%0A%0Aclass OrganizationOptionManagerTest(TestCase):%0A def test_set_value(self):%0A OrganizationOption.objects.set_value(self.organization, 'foo', 'bar')%0A assert OrganizationOption.objects.filter(%0A organization=self.organization, key='foo', value='bar').exists()%0A%0A def test_get_value(self):%0A result = OrganizationOption.objects.get_value(self.organization, 'foo')%0A assert result is None%0A%0A OrganizationOption.objects.create(%0A organization=self.organization, key='foo', value='bar')%0A result = OrganizationOption.objects.get_value(self.organization, 'foo')%0A assert result == 'bar'%0A%0A def test_unset_value(self):%0A OrganizationOption.objects.unset_value(self.organization, 'foo')%0A OrganizationOption.objects.create(%0A organization=self.organization, key='foo', value='bar')%0A OrganizationOption.objects.unset_value(self.organization, 'foo')%0A assert not OrganizationOption.objects.filter(%0A organization=self.organization, key='foo').exists()%0A%0A def test_get_value_bulk(self):%0A result = OrganizationOption.objects.get_value_bulk(%5Bself.organization%5D, 'foo')%0A assert result == %7Bself.organization: None%7D%0A%0A OrganizationOption.objects.create(%0A organization=self.organization, key='foo', value='bar')%0A result = OrganizationOption.objects.get_value_bulk(%5Bself.organization%5D, 'foo')%0A assert result == %7Bself.organization: 'bar'%7D%0A
|
|
f264f8804c208f2b55471f27f92a9e8c1ab5d778 | Test our new happenings-by-year view. | tests/correlations/test_views.py | tests/correlations/test_views.py | Python | 0 | @@ -0,0 +1,620 @@
+# -*- coding: utf-8 -*-%0Aimport datetime%0Aimport pytest%0A%0Afrom django.core.urlresolvers import reverse%0A%0Afrom components.people.factories import GroupFactory, IdolFactory%0A%0A%[email protected]_db%0Adef test_happenings_by_year_view(client):%0A %5BGroupFactory(started=datetime.date(2013, 1, 1)) for i in xrange(5)%5D%0A response = client.get(reverse('happenings-by-year', kwargs=%7B'year': 2013%7D))%0A assert response.status_code == 200%0A assert 'object_list' in response.context%0A assert '2010s' in response.context%5B'years'%5D%0A assert 'correlations/happenings_year.html' in %5Btemplate.name for template in response.templates%5D%0A
|
|
43c4595ae26a7663538e712af37553c7a64fade7 | Add a couple unit tests for teuthology.parallel | teuthology/test/test_parallel.py | teuthology/test/test_parallel.py | Python | 0 | @@ -0,0 +1,762 @@
+from ..parallel import parallel%0A%0A%0Adef identity(item, input_set=None, remove=False):%0A if input_set is not None:%0A assert item in input_set%0A if remove:%0A input_set.remove(item)%0A return item%0A%0A%0Aclass TestParallel(object):%0A def test_basic(self):%0A in_set = set(range(10))%0A with parallel() as para:%0A for i in in_set:%0A para.spawn(identity, i, in_set, remove=True)%0A assert para.any_spawned is True%0A assert para.count == len(in_set)%0A%0A def test_result(self):%0A in_set = set(range(10))%0A with parallel() as para:%0A for i in in_set:%0A para.spawn(identity, i, in_set)%0A for result in para:%0A in_set.remove(result)%0A%0A
|
|
f370ee48c8aec312f9ea8a9ce1737214e51e2eaf | Disable repaint.key_mobile_sites_repaint. | tools/perf/benchmarks/repaint.py | tools/perf/benchmarks/repaint.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from core import perf_benchmark
from benchmarks import silk_flags
from measurements import smoothness
from telemetry import benchmark
import page_sets
class _Repaint(perf_benchmark.PerfBenchmark):
@classmethod
def AddBenchmarkCommandLineArgs(cls, parser):
parser.add_option('--mode', type='string',
default='viewport',
help='Invalidation mode. '
'Supported values: fixed_size, layer, random, viewport.')
parser.add_option('--width', type='int',
default=None,
help='Width of invalidations for fixed_size mode.')
parser.add_option('--height', type='int',
default=None,
help='Height of invalidations for fixed_size mode.')
@classmethod
def Name(cls):
return 'repaint'
def CreateStorySet(self, options):
return page_sets.KeyMobileSitesRepaintPageSet(
options.mode, options.width, options.height)
def CreatePageTest(self, options):
return smoothness.Repaint()
@benchmark.Enabled('android')
class RepaintKeyMobileSites(_Repaint):
"""Measures repaint performance on the key mobile sites.
http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
@classmethod
def Name(cls):
return 'repaint.key_mobile_sites_repaint'
@benchmark.Enabled('android')
class RepaintGpuRasterizationKeyMobileSites(_Repaint):
"""Measures repaint performance on the key mobile sites with forced GPU
rasterization.
http://www.chromium.org/developers/design-documents/rendering-benchmarks"""
tag = 'gpu_rasterization'
def SetExtraBrowserOptions(self, options):
silk_flags.CustomizeBrowserOptionsForGpuRasterization(options)
@classmethod
def Name(cls):
return 'repaint.gpu_rasterization.key_mobile_sites_repaint'
| Python | 0.000002 | @@ -1216,16 +1216,35 @@
aint()%0A%0A
+#crbug.com/499320%0A#
@benchma
@@ -1257,32 +1257,54 @@
bled('android')%0A
[email protected]()%0A
class RepaintKey
|
dd135680c168ee9a25158b10de4335c507dcccbf | Upgrade test to not make umask assumptions | integration/test_operations.py | integration/test_operations.py | from __future__ import with_statement
from StringIO import StringIO
import os
import posixpath
import shutil
from fabric.api import run, path, put, sudo, abort, warn_only, env, cd
from fabric.contrib.files import exists
from util import Integration
def assert_mode(path, mode):
remote_mode = run("stat -c \"%%a\" \"%s\"" % path).stdout
assert remote_mode == mode, "remote %r != expected %r" % (remote_mode, mode)
class TestOperations(Integration):
filepath = "/tmp/whocares"
dirpath = "/tmp/whatever/bin"
not_owned = "/tmp/notmine"
def setup(self):
super(TestOperations, self).setup()
run("mkdir -p %s" % " ".join([self.dirpath, self.not_owned]))
def teardown(self):
super(TestOperations, self).teardown()
# Revert any chown crap from put sudo tests
sudo("chown %s ." % env.user)
# Nuke to prevent bleed
sudo("rm -rf %s" % " ".join([self.dirpath, self.filepath]))
sudo("rm -rf %s" % self.not_owned)
def test_no_trailing_space_in_shell_path_in_run(self):
put(StringIO("#!/bin/bash\necho hi"), "%s/myapp" % self.dirpath, mode="0755")
with path(self.dirpath):
assert run('myapp').stdout == 'hi'
def test_string_put_mode_arg_doesnt_error(self):
put(StringIO("#!/bin/bash\necho hi"), self.filepath, mode="0755")
assert_mode(self.filepath, "755")
def test_int_put_mode_works_ok_too(self):
put(StringIO("#!/bin/bash\necho hi"), self.filepath, mode=0755)
assert_mode(self.filepath, "755")
def _chown(self, target):
sudo("chown root %s" % target)
def _put_via_sudo(self, source=None, target_suffix='myfile', **kwargs):
# Ensure target dir prefix is not owned by our user (so we fail unless
# the sudo part of things is working)
self._chown(self.not_owned)
source = source if source else StringIO("whatever")
# Drop temp file into that dir, via use_sudo, + any kwargs
return put(
source,
self.not_owned + '/' + target_suffix,
use_sudo=True,
**kwargs
)
def test_put_with_use_sudo(self):
self._put_via_sudo()
def test_put_with_dir_and_use_sudo(self):
# Test cwd should be root of fabric source tree. Use our own folder as
# the source, meh.
self._put_via_sudo(source='integration', target_suffix='')
def test_put_with_use_sudo_and_custom_temp_dir(self):
# TODO: allow dependency injection in sftp.put or w/e, test it in
# isolation instead.
# For now, just half-ass it by ensuring $HOME isn't writable
# temporarily.
self._chown('.')
self._put_via_sudo(temp_dir='/tmp')
def test_put_with_use_sudo_dir_and_custom_temp_dir(self):
self._chown('.')
self._put_via_sudo(source='integration', target_suffix='', temp_dir='/tmp')
def test_put_use_sudo_and_explicit_mode(self):
# Setup
target_dir = posixpath.join(self.filepath, 'blah')
subdir = "inner"
subdir_abs = posixpath.join(target_dir, subdir)
filename = "whatever.txt"
target_file = posixpath.join(subdir_abs, filename)
run("mkdir -p %s" % subdir_abs)
self._chown(subdir_abs)
local_path = os.path.join('/tmp', filename)
with open(local_path, 'w+') as fd:
fd.write('stuff\n')
# Upload + assert
with cd(target_dir):
put(local_path, subdir, use_sudo=True, mode='777')
assert_mode(target_file, '777')
def test_put_file_to_dir_with_use_sudo_and_mirror_mode(self):
# Target for _put_via_sudo is a directory by default
uploaded = self._put_via_sudo(
source='integration/test_operations.py', mirror_local_mode=True
)
assert_mode(uploaded[0], '644')
def test_put_directory_use_sudo_and_spaces(self):
localdir = 'I have spaces'
localfile = os.path.join(localdir, 'file.txt')
os.mkdir(localdir)
with open(localfile, 'w') as fd:
fd.write('stuff\n')
try:
uploaded = self._put_via_sudo(localdir, target_suffix='')
# Kinda dumb, put() would've died if it couldn't do it, but.
assert exists(uploaded[0])
assert exists(posixpath.dirname(uploaded[0]))
finally:
shutil.rmtree(localdir)
| Python | 0 | @@ -174,16 +174,23 @@
env, cd
+, local
%0Afrom fa
@@ -3657,16 +3657,242 @@
#
+ Ensure mode of local file, umask varies on eg travis vs various%0A # localhosts%0A source = 'whatever.txt'%0A try:%0A local(%22touch %25s%22 %25 source)%0A local(%22chmod 644 %25s%22 %25 source)%0A #
Target
@@ -3935,32 +3935,36 @@
default%0A
+
+
uploaded = self.
@@ -3994,47 +3994,25 @@
+
source=
-'integration/test_operations.py'
+source
, mi
@@ -4040,18 +4040,26 @@
+
+
)%0A
+
@@ -4089,16 +4089,72 @@
, '644')
+%0A finally:%0A local(%22rm -f %25s%22 %25 source)
%0A%0A de
|
3d523bca7377c0f4c80a4f697b0c41d340eb8200 | add a command to clear the celery queue | crate_project/apps/crate/management/clear_celery.py | crate_project/apps/crate/management/clear_celery.py | Python | 0.000001 | @@ -0,0 +1,334 @@
+import redis%0A%0Afrom django.conf import settings%0Afrom django.core.management.base import BaseCommand%0A%0A%0Aclass Command(BaseCommand):%0A%0A def handle(self, *args, **options):%0A r = redis.StrictRedis(host=settings.GONDOR_REDIS_HOST, port=settings.GONDOR_REDIS_PORT, password=settings.GONDOR_REDIS_PASSWORD)%0A r.delete(%22celery%22)%0A
|
|
33e7216ae9b367c509b5075496fce08d346743e2 | Implement channel limit | txircd/modules/rfc/cmode_l.py | txircd/modules/rfc/cmode_l.py | Python | 0.000001 | @@ -0,0 +1,1212 @@
+from twisted.plugin import IPlugin%0Afrom twisted.words.protocols import irc%0Afrom txircd.module_interface import IMode, IModuleData, Mode, ModuleData%0Afrom txircd.utils import ModeType%0Afrom zope.interface import implements%0A%0Aclass LimitMode(ModuleData, Mode):%0A implements(IPlugin, IModuleData, IMode)%0A %0A name = %22LimitMode%22%0A core = True%0A affectedActions = %5B %22joinpermission%22 %5D%0A %0A def hookIRCd(self, ircd):%0A self.ircd = ircd%0A %0A def channelModes(self):%0A return %5B (%22l%22, ModeType.Param, self) %5D%0A %0A def actions(self):%0A return %5B (%22modeactioncheck-channel-l-joinpermission%22, 10, self.isModeSet) %5D%0A %0A def isModeSet(self, channel, alsoChannel, user):%0A if %22l%22 in channel.modes:%0A return channel.modes%5B%22l%22%5D%0A return None%0A %0A def checkSet(self, param):%0A try:%0A return %5B int(param) %5D%0A except ValueError:%0A return None%0A %0A def apply(self, actionType, channel, param, alsoChannel, user):%0A if len(channel.users) %3E= param:%0A user.sendMessage(irc.ERR_CHANNELISFULL, channel.name, %22:Cannot join channel (Channel is full)%22)%0A return False%0A return None%0A%0AlimitMode = LimitMode()
|
|
ddc9a02ba64c24f8243bc299cd898bd337e5ce9a | isscalar predicate | datashape/predicates.py | datashape/predicates.py | from .util import collect, dshape
from .internal_utils import remove
from .coretypes import *
# https://github.com/ContinuumIO/datashape/blob/master/docs/source/types.rst
__all__ = ['isdimension', 'ishomogeneous', 'istabular', 'isfixed']
dimension_types = (Fixed, Var, Ellipsis)
isunit = lambda x: isinstance(x, Unit)
def isdimension(ds):
""" Is a component a dimension?
>>> isdimension(Fixed(10))
True
>>> isdimension(Var())
True
>>> isdimension(int32)
False
"""
return isinstance(ds, dimension_types)
def ishomogeneous(ds):
""" Does datashape contain only one dtype?
>>> ishomogeneous(int32)
True
>>> ishomogeneous('var * 3 * string')
True
>>> ishomogeneous('var * {name: string, amount: int}')
False
"""
ds = dshape(ds)
return len(set(remove(isdimension, collect(isunit, ds)))) == 1
def _dimensions(ds):
""" Number of dimensions of datashape
Interprets records as dimensional
>>> _dimensions(int32)
0
>>> _dimensions(10 * int32)
1
>>> _dimensions('var * 10 * int')
2
>>> _dimensions('var * {name: string, amount: int}')
2
"""
ds = dshape(ds)
if isdimension(ds[0]):
return 1 + _dimensions(ds.subarray(1))
if isinstance(ds[0], Record):
return 1 + max(map(_dimensions, ds[0].types))
if len(ds) == 1 and isunit(ds[0]):
return 0
if isinstance(ds[0], Option):
return _dimensions(ds[0].ty)
raise NotImplementedError('Can not compute dimensions for %s' % ds)
def isfixed(ds):
""" Contains no variable dimensions
>>> isfixed('10 * int')
True
>>> isfixed('var * int')
False
>>> isfixed('10 * {name: string, amount: int}')
True
>>> isfixed('10 * {name: string, amounts: var * int}')
False
"""
ds = dshape(ds)
if isinstance(ds[0], TypeVar):
return None # don't know
if isinstance(ds[0], Var):
return False
if isinstance(ds[0], Record):
return all(map(isfixed, ds[0].types))
if len(ds) > 1:
return isfixed(ds.subarray(1))
return True
def istabular(ds):
""" Can be represented by a two dimensional with fixed columns
>>> istabular('var * 3 * int')
True
>>> istabular('var * {name: string, amount: int}')
True
>>> istabular('var * 10 * 3 * int')
False
>>> istabular('10 * var * int')
False
"""
ds = dshape(ds)
return _dimensions(ds) == 2 and isfixed(ds.subarray(1))
| Python | 0.999798 | @@ -2467,28 +2467,255 @@
and isfixed(ds.subarray(1))%0A
+%0A%0Adef isscalar(ds):%0A %22%22%22 Has no dimensions%0A%0A %3E%3E%3E isscalar('int')%0A True%0A %3E%3E%3E isscalar('3 * int')%0A False%0A %3E%3E%3E isscalar('%7Bname: string, amount: int%7D')%0A True%0A %22%22%22%0A ds = dshape(ds)%0A return not ds.shape%0A
|
7c24ffe52fe96339d14f522dc7c67122d01cead6 | add istabular predicate | datashape/predicates.py | datashape/predicates.py | from .util import collect, remove, dshape
from .coretypes import *
# https://github.com/ContinuumIO/datashape/blob/master/docs/source/types.rst
dimension_types = (Fixed, Var, Ellipsis)
isunit = lambda x: isinstance(x, Unit)
def isdimension(ds):
""" Is a component a dimension?
>>> isdimension(Fixed(10))
True
>>> isdimension(Var())
True
>>> isdimension(int32)
False
"""
return isinstance(ds, dimension_types)
def ishomogenous(ds):
""" Does datashape contain only one dtype?
>>> ishomogenous(int32)
True
>>> ishomogenous(var * (3 * string))
True
>>> ishomogenous(var * Record([('name', string), ('amount', int32)]))
False
"""
return len(set(remove(isdimension, collect(isunit, ds)))) == 1
def dimensions(ds):
""" Number of dimensions of datashape
Interprets records as dimensional
>>> dimensions(int32)
0
>>> dimensions(10 * int32)
1
>>> dimensions(var * (10 * int32))
2
>>> dimensions(var * Record([('name', string), ('amount', int32)]))
2
"""
if not isinstance(ds, DataShape):
ds = dshape(ds)
if isdimension(ds[0]):
return 1 + dimensions(ds.subarray(1))
if isinstance(ds[0], Record):
return 1 + max(map(dimensions, ds[0].fields.values()))
if len(ds) == 1 and isunit(ds[0]):
return 0
raise NotImplementedError('Can not compute dimensions for %s' % ds)
def isfixed(ds):
""" Contains no variable dimensions
>>> isfixed('10 * int')
True
>>> isfixed('var * int')
False
>>> isfixed('10 * {name: string, amount: int}')
True
>>> isfixed('10 * {name: string, amounts: var * int}')
False
"""
if not isinstance(ds, DataShape):
ds = dshape(ds)
if isinstance(ds[0], Var):
return False
if isinstance(ds[0], Record):
return all(map(isfixed, ds[0].fields.values()))
if len(ds) > 1:
return isfixed(ds.subarray(1))
return True
| Python | 0.999995 | @@ -1974,12 +1974,434 @@
return True%0A
+%0A%0Adef istabular(ds):%0A %22%22%22 Can be represented by a two dimensional with fixed columns%0A%0A %3E%3E%3E istabular('var * 3 * int')%0A True%0A %3E%3E%3E istabular('var * %7Bname: string, amount: int%7D')%0A True%0A %3E%3E%3E istabular('var * 10 * 3 * int')%0A False%0A %3E%3E%3E istabular('10 * var * int')%0A False%0A %22%22%22%0A if not isinstance(ds, DataShape):%0A ds = dshape(ds)%0A return dimensions(ds) == 2 and isfixed(ds.subarray(1))%0A
|
9dd20f8361cff99329a5ab4b526e29edddac9a61 | add session.py | session.py | session.py | Python | 0.000001 | @@ -0,0 +1,1410 @@
+#!/usr/bin/python%0A#A quick and dirty interface to end a session %0A# This assumes systemd and xinitrc (for logout)%0A#By Charles Bos%0A%0Afrom tkinter import *%0Aimport os%0Aimport sys%0A%0Adef getWm() :%0A args = sys.argv%0A if len(args) == 1 : return %22-u $USER%22%0A else : return args%5B1%5D%0A%0Adef runAction() :%0A if option.get() == 1 : os.system(%22pkill %22 + getWm())%0A elif option.get() == 2 : os.system(%22systemctl suspend%22)%0A elif option.get() == 3 : os.system(%22systemctl hibernate%22)%0A elif option.get() == 4 : os.system(%22systemctl reboot%22)%0A elif option.get() == 5 : os.system(%22systemctl poweroff%22)%0A %0Aclass UI() :%0A def __init__(self, parent) :%0A global option%0A option = IntVar()%0A r1 = Radiobutton(parent, text = %22Logout%22, variable = option, value = 1).grid(row = 2, column = 1)%0A r2 = Radiobutton(parent, text = %22Suspend%22, variable = option, value = 2).grid(row = 2, column = 2)%0A r3 = Radiobutton(parent, text = %22Hibernate%22, variable = option, value = 3).grid(row = 2, column = 3)%0A r4 = Radiobutton(parent, text = %22Reboot%22, variable = option, value = 4).grid(row = 2, column = 4)%0A r5 = Radiobutton(parent, text = %22Poweroff%22, variable = option, value = 5).grid(row = 2, column = 5)%0A b1 = Button(parent, text = %22Ok%22, command = runAction).grid(row = 3, column = 1, columnspan = 5)%0A %0Atop = Tk()%0Atop.title(%22End session%22)%0Aui = UI(top)%0Atop.mainloop()%0A
|
|
c43d929f9ee2f21a7e93986171307cd0f17fa96c | add unittests of helpers | tests/test_helper.py | tests/test_helper.py | Python | 0 | @@ -0,0 +1,1823 @@
+#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Aimport unittest%0Afrom types import BuiltinFunctionType%0Afrom clime.helper import *%0A%0Aclass TestClimeHelper(unittest.TestCase):%0A%0A def test_autotype(self):%0A cases = ('string', '100', '100.0', None)%0A answers = ('string', 100 , 100.0 , None)%0A for case, answer in zip(cases, answers):%0A self.assertEqual(autotype(case), answer)%0A%0A def test_getargspec(self):%0A%0A docs = %5B%0A None,%0A '',%0A 'abcd',%0A 'f1()',%0A 'f2(x)',%0A 'f3(x, y)',%0A 'f4(x%5B, a%5D)',%0A 'f5(x, y%5B, a%5D)',%0A 'f6(x, y%5B, a%5B, b%5D%5D)',%0A 'f7(%5Ba%5D)',%0A 'f8(%5Ba%5B, b%5D%5D)',%0A %5D%0A%0A answers = %5B%0A (None, 0),%0A (None, 0),%0A (None, 0),%0A (None, 0),%0A (%5B'x'%5D, 0),%0A (%5B'x', 'y'%5D, 0),%0A (%5B'x', 'a'%5D, 1),%0A (%5B'x', 'y', 'a'%5D, 1),%0A (%5B'x', 'y', 'a', 'b'%5D, 2),%0A (%5B'a'%5D, 1),%0A (%5B'a', 'b'%5D, 2),%0A %5D%0A%0A f = type('Dummy', tuple(), %7B'__doc__': None%7D)()%0A trans = lambda x: (x%5B0%5D, len(x%5B-1%5D or %5B%5D))%0A%0A for doc, answer in zip(docs, answers):%0A f.__doc__ = doc%0A self.assertEqual(trans(getargspec( f )), answer)%0A%0A def test_getoptmetas(self):%0A%0A doc = %22%22%22%0A -d, --debug enable debug mode%0A -q, -s, --quiet, --slient enable slient mode%0A -n N, --times N how many times do you want%0A %22%22%22%0A%0A answer = %5B %5B('d', None), ('debug', None)%5D,%0A %5B('q', None), ('s', None), ('quiet', None), ('slient', None)%5D,%0A %5B('n', 'N'), ('times', 'N')%5D %5D%0A%0A self.assertEqual(list(getoptmetas(doc)), answer)%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
|
|
dd8496c61543b3e39c5ee3ccb8bc7b9f69e9487f | add tests for packet | tests/test_packet.py | tests/test_packet.py | Python | 0.000001 | @@ -0,0 +1,533 @@
+from zope.interface.verify import verifyClass, verifyObject%0Afrom ironman.packet import IPBusPacket%0Afrom ironman.interfaces import IIPbusPacket%0A%0Adef test_ipbus_packet_create():%0A obj = IPBusPacket()%0A assert obj is not None%0A%0Adef test_ipbus_packet_class_iface():%0A # Assure the class implements the declared interface%0A assert verifyClass(IIPBusPacket, IPBusPacket)%0A%0Adef test_ipbus_packet_instance_iface():%0A # Assure instances of the class provide the declared interface%0A assert verifyObject(IIPBusPacket, IPBusPacket())%0A
|
|
148788849fc98c59af7df5ddc157cfbcb6e4aa93 | Update our regex to match actual file names, we've changed them. Doh. | gettor/packages.py | gettor/packages.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
'''
gettor_packages.py: Package related stuff
Copyright (c) 2008, Jacob Appelbaum <[email protected]>,
Christian Fromme <[email protected]>
This is Free Software. See LICENSE for license information.
This module handles all package related functionality
'''
import os
import zipfile
import subprocess
import gettor.gtlog
import gettor.config
import re
__all__ = ["gettorPackages"]
log = gettor.gtlog.getLogger()
class gettorPackages:
packageRegex = { "windows-bundle": "vidalia-bundle-.*.exe$",
"panther-bundle": "vidalia-bundle-.*-panther.dmg$",
"tiger-bundle": "vidalia-bundle-.*-tiger.dmg$",
"source-bundle": "tor-.*.tar.gz",
"tor-browser-bundle": "tor-browser-.*_en-US.exe",
"tor-im-browser-bundle": "tor-im-browser-.*_en-US.exe",
}
def __init__(self, mirror, config, silent=False):
self.mirror = mirror
self.packageList = {}
self.distDir = config.getDistDir()
try:
entry = os.stat(self.distDir)
except OSError, e:
log.error("Bad dist dir %s: %s" % (self.distDir, e))
raise IOError
self.packDir = config.getPackDir()
try:
entry = os.stat(self.packDir)
except OSError, e:
log.error("Bad pack dir %s: %s" % (self.packDir, e))
raise IOError
self.rsync = ["rsync"]
self.rsync.append("-a")
# Don't download dotdirs
self.rsync.append("--exclude='.*'")
if not silent:
self.rsync.append("--progress")
self.rsync.append("rsync://%s/tor/dist/current/" % self.mirror)
self.rsync.append(self.distDir)
def getPackageList(self):
# Build dict like 'name': 'name.z'
try:
for filename in os.listdir(self.packDir):
self.packageList[filename[:-2]] = self.packDir + "/" + filename
except OSError, (strerror):
log.error(_("Failed to build package list: %s") % strerror)
return None
# Check sanity
for key, val in self.packageList.items():
# Remove invalid packages
if not os.access(val, os.R_OK):
log.info(_("Warning: %s not accessable. Removing from list.") % val)
del self.packageList[key]
return self.packageList
def buildPackages(self):
for filename in os.listdir(self.distDir):
for (pack, regex) in self.packageRegex.items():
if re.compile(regex).match(filename):
file = self.distDir + "/" + filename
ascfile = file + ".asc"
zipFileName = self.packDir + "/" + pack + ".z"
# If .asc file is there, build Zip file
if os.access(ascfile, os.R_OK):
zip = zipfile.ZipFile(zipFileName, "w")
zip.write(file, os.path.basename(file))
zip.write(ascfile, os.path.basename(ascfile))
zip.close()
self.packageList[pack] = zipFileName
break
if len(self.packageList) > 0:
return True
else:
return False
def syncWithMirror(self):
process = subprocess.Popen(self.rsync)
process.wait()
return process.returncode
def getCommandToStr(self):
"""This is useful for cronjob installations
"""
return ''.join(self.rsync)
if __name__ == "__main__" :
c = gettor_config.gettorConf()
p = gettorPackages("rsync.torproject.org", c)
print "Building packagelist.."
if p.syncwithMirror() != 0:
print "Failed."
exit(1)
if not p.buildPackageList():
print "Failed."
exit(1)
print "Done."
for (pack, file) in p.getPackageList().items():
print "Bundle is mapped to file: ", pack, file
| Python | 0.000004 | @@ -628,22 +628,18 @@
dle-.*-p
-anther
+pc
.dmg$%22,%0A
@@ -694,21 +694,25 @@
ndle-.*-
-tiger
+universal
.dmg$%22,%0A
|
bd0bdc543ba1e44ddc9d149fbaadd12ab051614d | Add migrations | accession/migrations/0003_auto_20191101_1625.py | accession/migrations/0003_auto_20191101_1625.py | Python | 0.000001 | @@ -0,0 +1,1234 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.25 on 2019-11-01 16:25%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('accession', '0002_auto_20191031_2139'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='object',%0A name='object_era',%0A field=models.CharField(blank=True, choices=%5B('Pre-1770', 'Pre-1770'), ('1770-1779', '1770-1779'), ('1780-1789', '1780-1789'), ('1790-1799', '1790-1799'), ('1800-1809', '1800-1809'), ('1810-1819', '1810-1819'), ('1820-1829', '1820-1829'), ('1830-1839', '1830-1839'), ('1840-1849', '1840-1849'), ('1850-1859', '1850-1859'), ('1860-1869', '1860-1869'), ('1870-1879', '1870-1879'), ('1880-1889', '1880-1889'), ('1890-1899', '1890-1899'), ('1900-1909', '1900-1909'), ('1910-1919', '1910-1919'), ('1920-1929', '1920-1929'), ('1930-1939', '1930-1939'), ('1940-1949', '1940-1949'), ('1950-1959', '1950-1959'), ('1960-1969', '1960-1969'), ('1970-1979', '1970-1979'), ('1980-1989', '1980-1989'), ('1990-1999', '1990-1999'), ('2000-2009', '2000-2009'), ('2010-2019', '2010-2019'), ('2020-2029', '2020-2029')%5D, max_length=10),%0A ),%0A %5D%0A
|
|
7b0ebe74cbaad610bb65f24cc2555d82e7d7a750 | read attachments path from settings, catch jpeg/png | apps/photos/views.py | apps/photos/views.py | from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from rapidsms.webui.utils import render_to_response
from photos.models import Photo
import os
import settings
# default page - show all thumbnails by date
@login_required()
def recent(request, template_name="photos/list.html"):
photos = Photo.objects.all()
return render_to_response(request, template_name, {'photos' : photos})
# show a single photo + comments
@login_required()
def show(request, photo_id, template_name="photos/single.html"):
p = Photo.objects.get(id=photo_id)
return render_to_response(request, template_name, {'photo' : p})
@login_required()
def import_photos(request):
path = 'data/attachments' #settings.RAPIDSMS_APPS['receiver']['attachments_path']
def is_img(filename):
return filename.endswith('.jpg')
def not_in_db_already(filename):
# Note that there's a query for each file here - another way would be to load all existing files to a list in one operation and work with that
# but, that might generate huge list when there are a lot of photos in the DB, and might cause data freshness issues in some edge cases
# so, we just do n queries each time (where n is probably not too big) instead
return (Photo.objects.filter(original_image="%s/%s" % (path, filename)).count() == 0)
files = os.listdir(path)
img_files = filter(is_img, files)
new_img_files = filter(not_in_db_already, img_files)
out = ''
for f in new_img_files:
out += "%s/%s <br/> " % (path, f)
p = Photo(name=f, original_image="%s/%s" % (path, f))
p.save()
return HttpResponseRedirect("/photos")
# return HttpResponse(out)
@login_required()
def populate(request):
for i in (1,2,3):
p = Photo(name="test image #%s" % i, original_image="apps/photos/tests/test%s.jpg" % i)
p.save()
return HttpResponseRedirect("/photos")
| Python | 0 | @@ -765,28 +765,8 @@
h =
-'data/attachments' #
sett
@@ -815,16 +815,38 @@
s_path'%5D
+ # -%3E data/attachments
%0A%0A de
@@ -880,16 +880,17 @@
return
+(
filename
@@ -906,16 +906,76 @@
('.jpg')
+ or filename.endswith('.jpeg') or filename.endswith('.png'))
%0A %0A
@@ -1623,21 +1623,8 @@
%0A
- out = ''%0A
@@ -1651,50 +1651,8 @@
es:%0A
- out += %22%25s/%25s %3Cbr/%3E %22 %25 (path, f)%0A
@@ -1778,39 +1778,8 @@
s%22)%0A
- # return HttpResponse(out)%0A
%0A%0A
|
fda4f436bbaea9215efa03648d2df8e413fb47dd | add class loader tests | test/test_loader.py | test/test_loader.py | Python | 0 | @@ -0,0 +1,1695 @@
+# Copyright (c) 2018 Workonline Communications (Pty) Ltd. All rights reserved.%0A#%0A# The contents of this file are licensed under the Apache License version 2.0%0A# (the %22License%22); you may not use this file except in compliance with the%0A# License.%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, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations under%0A# the License.%0A%22%22%22rptk class loader test cases.%22%22%22%0A%0Afrom __future__ import print_function%0Afrom __future__ import unicode_literals%0A%0Afrom helpers import default_format_classes, default_query_classes%0A%0Aimport pytest%0A%0A%0Aclass_sets = (%0A default_query_classes().items(),%0A default_format_classes().items(),%0A pytest.param(%5B(%22foo%22, %22rptk.foo.FooClass%22)%5D, marks=pytest.mark.xfail),%0A pytest.param(0, marks=pytest.mark.xfail)%0A)%0A%0A%0Aclass TestClassLoader(object):%0A %22%22%22Test cases for rptk class loader classes.%22%22%22%0A%0A @pytest.mark.parametrize(%22class_set%22, class_sets)%0A def test_class_loader(self, class_set):%0A %22%22%22Test rptk class loader.%22%22%22%0A from rptk.load import ClassLoader%0A loader = ClassLoader(items=class_set)%0A assert isinstance(loader.class_names, list)%0A for name, path in class_set:%0A assert name in loader.class_names%0A assert name in loader.class_info%0A assert loader.class_info%5Bname%5D%0A assert loader.get_class(name=name).__name__ in path%0A assert isinstance(loader.classes, list)%0A for cls in loader.classes:%0A assert isinstance(cls, type)%0A
|
|
dd75e1c5afb05c5d46adae465947fb3f893cdf6b | Create 7kyu_complete_the_pattern4.py | Solutions/7kyu/7kyu_complete_the_pattern4.py | Solutions/7kyu/7kyu_complete_the_pattern4.py | Python | 0.001969 | @@ -0,0 +1,105 @@
+def pattern(n):%0A l=list(range(1,n+1))%0A return '%5Cn'.join(''.join(map(str,l%5Bi:%5D)) for i in range(n))%0A
|
|
422b5573b72cc2014893aa15758b9d0bc61baf05 | refactor from core.py | Synopsis/Formatters/HTML/DeclarationStyle.py | Synopsis/Formatters/HTML/DeclarationStyle.py | Python | 0.000202 | @@ -0,0 +1,2052 @@
+# $Id: DeclarationStyle.py,v 1.1 2003/11/15 19:55:06 stefan Exp $%0A#%0A# Copyright (C) 2000 Stephen Davies%0A# Copyright (C) 2000 Stefan Seefeld%0A# All rights reserved.%0A# Licensed to the public under the terms of the GNU LGPL (%3E= 2),%0A# see the file COPYING for details.%0A#%0A%0Aclass Style:%0A %22%22%22This class just maintains a mapping from declaration to display style.%0A The style is an enumeration, possible values being: SUMMARY (only display%0A a summary for this declaration), DETAIL (summary and detailed info),%0A INLINE (summary and detailed info, where detailed info is an inline%0A version of the declaration even if it's a class, etc.)%22%22%22%0A%0A SUMMARY = 0%0A DETAIL = 1%0A INLINE = 2%0A %0A def __init__(self):%0A self.__dict = %7B%7D%0A%0A def style_of(self, decl):%0A %22%22%22Returns the style of the given decl%22%22%22%0A SUMMARY = self.SUMMARY%0A DETAIL = self.DETAIL%0A key = id(decl)%0A if self.__dict.has_key(key): return self.__dict%5Bkey%5D%0A if len(decl.comments()) == 0:%0A # Set to summary, as this will mean no detailed section%0A style = SUMMARY%0A else:%0A comment = decl.comments()%5B0%5D%0A # Calculate the style. The default is detail%0A if not comment.text():%0A # No comment, don't show detail%0A style = SUMMARY%0A elif comment.summary() != comment.text():%0A # There is more to the comment than the summary, show detail%0A style = DETAIL%0A else:%0A # Summary == Comment, don't show detail%0A style = SUMMARY%0A%09 # Always show tags%0A if comment.tags():%0A style = DETAIL%0A%09 # Always show enums%0A if isinstance(decl, AST.Enum):%0A style = DETAIL%0A%09 # Show functions if they have exceptions%0A if isinstance(decl, AST.Function) and len(decl.exceptions()):%0A style = DETAIL%0A%09 # Don't show detail for scopes (they have their own pages)%0A if isinstance(decl, AST.Scope):%0A style = SUMMARY%0A self.__dict%5Bkey%5D = style%0A return style%0A%0A __getitem__ = style_of%0A
|
|
20cbfa3646bc38429ee202c0e77c32a9c5c614d9 | blotto.py | blotto.py | blotto.py | Python | 0.999968 | @@ -0,0 +1,1456 @@
+from ea import adult_selection%0Afrom ea import parent_selection%0Afrom ea import reproduction%0Afrom ea import main%0Afrom ea import binary_gtype%0A%0Adef fitness_test(population):%0A '''Naive fitness test for onemax, just the number of ones'''%0A return %5B(ind%5B0%5D, ind%5B1%5D, sum(ind%5B1%5D), ind%5B2%5D) for ind in population%5D%0A%0Adef develop(population):%0A '''Development function for onemax (just copies the genotype)'''%0A return %5B(ind%5B0%5D, list(ind%5B0%5D), ind%5B1%5D) for ind in population%5D%0A%0Adef visualize(generation_list):%0A '''Generate visualizations using matplotlib'''%0A return None%0A%0Aif __name__=='__main__':%0A size = int(raw_input(%22Input problem size:%5Cn%22))%0A popsize = int(raw_input(%22Input population size:%5Cn%22))%0A%0A adult_selection, litter_size = adult_selection.gen_adult_selection(popsize)%0A parent_selection = parent_selection.gen_parent_selection(litter_size)%0A%0A mutate = binary_gtype.gen_mutate()%0A crossover = binary_gtype.gen_crossover()%0A reproduction = reproduction.gen_reproduction(mutate, crossover)%0A%0A generations = int(input(%22Input max number of generations:%5Cn%22))%0A fitness_goal = float(input(%22Input fitness goal, 0 for none:%5Cn%22))%0A%0A initial = %5B(binary_gtype.generate(size), 0) for i in xrange(popsize)%5D%0A generation_list = main.evolutionary_algorithm(initial, develop, fitness_test, adult_selection, parent_selection, reproduction, generations, fitness_goal)%0A%0A print %22Program ran for %22 + str(len(generation_list)) + %22 generations%22%0A
|
|
b8cc84245ae7f3ceda0e0cd92b6b2eecb0426ee3 | add start of peg generator | src/mugen/parser/peg.py | src/mugen/parser/peg.py | Python | 0 | @@ -0,0 +1,1739 @@
+#!/usr/bin/env python%0A%0Anext_var = 0%0Adef nextVar():%0A global next_var;%0A next_var += 1;%0A return next_var%0A%0Aclass Pattern:%0A def __init__(self):%0A pass%0A%0A def generate(self, result):%0A pass%0A%0Aclass PatternNot(Pattern):%0A def __init__(self, next):%0A Pattern.__init__(self)%0A self.next = next%0A%0A def generate(self, result):%0A my_result = %22result_%25d%22 %25 nextVar()%0A data = %22%22%22%0AResult %25s = 0;%0A%25s%0A%25s = ! %25s;%0A %22%22%22 %25 (my_result, self.next.generate(my_result), result, my_result)%0A%0A return data%0A%0Aclass PatternVerbatim(Pattern):%0A def __init__(self, letters):%0A Pattern.__init__(self)%0A self.letters = letters%0A%0A def generate(self, result):%0A data = %22%22%22%0A%25s = %22%25s%22;%0A %22%22%22 %25 (result, self.letters)%0A return data%0A%0Aclass Rule:%0A def __init__(self, name, patterns):%0A self.name = name%0A self.patterns = patterns%0A%0A def generate(self):%0A result = %22result_%25d%22 %25 nextVar()%0A data = %22%22%22%0Astatic Result rule_%25s()%7B%0A Result %25s = 0;%0A %25s%0A return Result;%0A%7D%0A %22%22%22 %25 (self.name, result, '%5Cn'.join(%5Bpattern.generate(result) for pattern in self.patterns%5D))%0A%0A return data%0A %0Aclass Peg:%0A def __init__(self, start, rules):%0A self.start = start%0A self.rules = rules%0A%0A def generate(self):%0A namespace = %22Peg%22%0A data = %22%22%22%0Anamespace %25s%7B%0A %25s%0A%0A Result main()%7B%0A return rule_%25s();%0A %7D%0A%7D%0A %22%22%22 %25 (namespace, '%5Cn'.join(%5Brule.generate() for rule in self.rules%5D), self.start)%0A%0A return data%0A%0Adef generate(peg):%0A print peg.generate()%0A%0Adef test():%0A rules = %5B%0A Rule(%22s%22, %5BPatternNot(PatternVerbatim(%22hello%22))%5D),%0A %5D%0A peg = Peg(%22s%22, rules)%0A generate(peg)%0A%0Atest()%0A
|
|
82f15b2dae1b23b75a019362e5925c4a3591fa92 | Create InputNeuronGroup_multiple_inputs_1.py | examples/InputNeuronGroup_multiple_inputs_1.py | examples/InputNeuronGroup_multiple_inputs_1.py | Python | 0 | @@ -0,0 +1,1910 @@
+'''%0AExample of a spike generator (only outputs spikes)%0A%0AIn this example spikes are generated and sent through UDP packages. At the end of the simulation a raster plot of the %0Aspikes is created.%0A%0A'''%0A%0Afrom brian import *%0Aimport numpy%0A%0Afrom brian_multiprocess_udp import BrianConnectUDP%0A%0Anumber_of_neurons_total = 40%0Anumber_of_neurons_spiking = 30%0A%0Adef main_NeuronGroup(input_Neuron_Group, simulation_clock):%0A print %22main_NeuronGroup!%22 #DEBUG!%0A%0A simclock = simulation_clock%0A%0A delta_t=5%0A %0A random_list=numpy.random.randint(number_of_neurons_total,size=number_of_neurons_spiking)%0A random_list.sort()%0A%0A spiketimes = %5B(i, delta_t*ms) for i in random_list%5D%0A %0A SpikesOut = SpikeGeneratorGroup(number_of_neurons_total, spiketimes, period=300*ms, clock=simclock) # the maximum clock of the input spikes is limited here (period)%0A%0A MSpkOut=SpikeMonitor(SpikesOut) # Spikes sent by UDP%0A%0A return (%5BSpikesOut%5D,%5B%5D,%5BMSpkOut%5D)%0A%0Adef post_simulation_function(input_NG, simulation_NG, simulation_SYN, simulation_MN):%0A %22%22%22%0A input_NG: the neuron group that receives the input spikes%0A simulation_NG: the neuron groups list passed to the system by the user function (main_NeuronGroup)%0A simulation_SYN: the synapses list passed to the system by the user function (main_NeuronGroup)%0A simulation_MN: the monitors list passed to the system by the user function (main_NeuronGroup)%0A%0A This way it is possible to plot, save or do whatever you want with these objects after the end of the simulation!%0A %22%22%22%0A figure()%0A raster_plot(simulation_MN%5B0%5D)%0A title(%22Spikes Sent by UDP%22)%0A show(block=True) %0A%0Aif __name__==%22__main__%22:%0A%0A my_simulation = BrianConnectUDP(main_NeuronGroup, NumOfNeuronsOutput=number_of_neurons_total, post_simulation_function=post_simulation_function,%0A output_addresses=%5B(%22127.0.0.1%22, 14141)%5D, simclock_dt=5, TotalSimulationTime=10000, brian_address=0)%0A
|
|
765897a05a7aae6a89bfd62d8493fb14aa16048a | Create db_migrate.py | db_migrate.py | db_migrate.py | Python | 0.000003 | @@ -0,0 +1,852 @@
+#!venv/bin/python%0Aimport imp%0Afrom migrate.versioning import api%0Afrom app import db%0Afrom config import SQLALCHEMY_DATABASE_URI%0Afrom config import SQLALCHEMY_MIGRATE_REPO%0Av = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)%0Amigration = SQLALCHEMY_MIGRATE_REPO + ('/versions/%2503d_migration.py' %25 (v+1))%0Atmp_module = imp.new_module('old_model')%0Aold_model = api.create_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)%0Aexec(old_model, tmp_module.__dict__)%0Ascript = api.make_update_script_for_model(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO, tmp_module.meta, db.metadata)%0Aopen(migration, %22wt%22).write(script)%0Aapi.upgrade(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)%0Av = api.db_version(SQLALCHEMY_DATABASE_URI, SQLALCHEMY_MIGRATE_REPO)%0Aprint('New migration saved as ' + migration)%0Aprint('Current database version: ' + str(v))%0A
|
|
7e30de04cad1070eb84c1de0c370e950b5e2c783 | Annotate zerver.views.webhooks.pingdom. | zerver/views/webhooks/pingdom.py | zerver/views/webhooks/pingdom.py | # Webhooks for external integrations.
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from zerver.lib.actions import check_send_message
from zerver.lib.response import json_success, json_error
from zerver.decorator import REQ, has_request_variables, api_key_only_webhook_view
import ujson
PINGDOM_SUBJECT_TEMPLATE = '{name} status.'
PINGDOM_MESSAGE_TEMPLATE = 'Service {service_url} changed its {type} status from {previous_state} to {current_state}.'
PINGDOM_MESSAGE_DESCRIPTION_TEMPLATE = 'Description: {description}.'
SUPPORTED_CHECK_TYPES = (
'HTTP',
'HTTP_CUSTOM'
'HTTPS',
'SMTP',
'POP3',
'IMAP',
'PING',
'DNS',
'UDP',
'PORT_TCP',
)
@api_key_only_webhook_view('Pingdom')
@has_request_variables
def api_pingdom_webhook(request, user_profile, client, payload=REQ(argument_type='body'), stream=REQ(default='pingdom')):
check_type = get_check_type(payload)
if check_type in SUPPORTED_CHECK_TYPES:
subject = get_subject_for_http_request(payload)
body = get_body_for_http_request(payload)
else:
return json_error(_('Unsupported check_type: {check_type}').format(check_type=check_type))
check_send_message(user_profile, client, 'stream', [stream], subject, body)
return json_success()
def get_subject_for_http_request(payload):
return PINGDOM_SUBJECT_TEMPLATE.format(name=payload['check_name'])
def get_body_for_http_request(payload):
current_state = payload['current_state']
previous_state = payload['previous_state']
data = {
'service_url': payload['check_params']['hostname'],
'previous_state': previous_state,
'current_state': current_state,
'type': get_check_type(payload)
}
body = PINGDOM_MESSAGE_TEMPLATE.format(**data)
if current_state == 'DOWN' and previous_state == 'UP':
description = PINGDOM_MESSAGE_DESCRIPTION_TEMPLATE.format(description=payload['long_description'])
body += '\n{description}'.format(description=description)
return body
def get_check_type(payload):
return payload['check_type']
| Python | 0 | @@ -69,16 +69,39 @@
e_import
+%0Afrom typing import Any
%0A%0Afrom d
@@ -144,16 +144,66 @@
ext as _
+%0Afrom django.http import HttpRequest, HttpResponse
%0A%0Afrom z
@@ -385,16 +385,62 @@
ook_view
+%0Afrom zerver.models import Client, UserProfile
%0A%0Aimport
@@ -446,16 +446,27 @@
t ujson%0A
+import six%0A
%0A%0APINGDO
@@ -1035,16 +1035,110 @@
dom')):%0A
+ # type: (HttpRequest, UserProfile, Client, Dict%5Bstr, Any%5D, six.text_type) -%3E HttpResponse%0A
chec
@@ -1574,32 +1574,78 @@
quest(payload):%0A
+ # type: (Dict%5Bstr, Any%5D) -%3E six.text_type%0A
return PINGD
@@ -1737,24 +1737,70 @@
t(payload):%0A
+ # type: (Dict%5Bstr, Any%5D) -%3E six.text_type%0A
current_
@@ -2382,16 +2382,16 @@
body%0A%0A%0A
-
def get_
@@ -2407,24 +2407,70 @@
e(payload):%0A
+ # type: (Dict%5Bstr, Any%5D) -%3E six.text_type%0A
return p
|
d8c359b27d371f5bd66825202860a0a376a2466c | add script to convert old plans to new ones | jsonQueries/old_to_new_plan.py | jsonQueries/old_to_new_plan.py | Python | 0 | @@ -0,0 +1,1370 @@
+#!/usr/bin/env python%0A%0Aimport json%0Aimport sys%0A%0Adef read_json(filename):%0A with open(filename, 'r') as f:%0A return json.load(f)%0A%0Adef uniquify_fragments(query_plan):%0A fragment_inv = %5B%5D%0A for worker in sorted(query_plan.keys()):%0A worker_plan = query_plan%5Bworker%5D%0A for fragment in worker_plan:%0A flag = False%0A for (i,(x,y)) in enumerate(fragment_inv):%0A if y == fragment:%0A fragment_inv%5Bi%5D = (x + %5Bworker%5D, y)%0A flag = True%0A break%0A if flag:%0A continue%0A fragment_inv.append((%5Bworker%5D, fragment))%0A return fragment_inv%0A%0Adef json_pretty(obj):%0A return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))%0A%0Aif __name__ == %22__main__%22:%0A if len(sys.argv) != 2:%0A print %3E%3E sys.stderr, %22Usage: %25s %3Cold json file%3E%22 %25 sys.argv%5B0%5D%0A sys.exit(1)%0A%0A myria_json_plan = read_json(sys.argv%5B1%5D)%0A fragments = %5B%5D%0A frags = uniquify_fragments(myria_json_plan%5B'query_plan'%5D)%0A for (ws,ops) in frags:%0A fragments.append(%7B%0A 'workers' : ws,%0A 'operators' : ops%0A %7D)%0A output = %7B%0A 'raw_datalog' : myria_json_plan%5B'raw_datalog'%5D,%0A 'logical_ra' : myria_json_plan%5B'logical_ra'%5D,%0A 'fragments' : fragments%0A %7D%0A%0A print json_pretty(output)%0A
|
|
f71ce70330f7dea86820f1d9cdc390ea972aaeca | add 2s-complement | algorithms/bit-manipulation/2s-complement.py | algorithms/bit-manipulation/2s-complement.py | Python | 0.999978 | @@ -0,0 +1,842 @@
+import sys%0A%0Adef ones(x):%0A uCount = x - ((x %3E%3E 1) & 033333333333) - ((x %3E%3E 2) & 011111111111);%0A return ((uCount + (uCount %3E%3E 3)) & 030707070707) %25 63;%0A%0Adef count(x):%0A if x %3E= 0:%0A if x == 0:%0A return 0%0A if x %25 2 == 0:%0A return count(x - 1) + ones(x)%0A return (x + 1) / 2 + 2 * count(x / 2)%0A else:%0A x += 1%0A return 32 * (1 - x) - count(-x)%0A %0Adef solve(A, B):%0A if A %3E= 0:%0A if A == 0:%0A return count(B)%0A return count(B) - count(A - 1)%0A else:%0A if B %3E= 0:%0A return count(A) + count(B)%0A return count(A) - count(B + 1)%0A%0Aif __name__ == '__main__':%0A T = int(sys.stdin.readline())%0A for i in range(T):%0A %5BA, B%5D = map(int, sys.stdin.readline().split());%0A #print count(A), count(B)%0A print solve(A, B)%0A
|
|
173565f7f2b9ffa548b355a0cbc8f972f1445a50 | Add test coverage for rdopkg.guess version2tag and tag2version | tests/test_guess.py | tests/test_guess.py | Python | 0 | @@ -0,0 +1,1712 @@
+from rdopkg import guess%0Afrom collections import namedtuple%0Aimport pytest%0A%0AVersionTestCase = namedtuple('VersionTestCase', ('expected', 'input_data'))%0A%0A%0Adata_table_good = %5B%0A VersionTestCase(('1.2.3', None), '1.2.3'),%0A VersionTestCase(('1.2.3', 'vX.Y.Z'), 'v1.2.3'),%0A VersionTestCase(('1.2.3', 'VX.Y.Z'), 'V1.2.3'),%0A VersionTestCase(('banana', None), 'banana'),%0A%5D%0A%0Adata_table_bad = %5B%0A VersionTestCase((None, None), None),%0A VersionTestCase((None, None), %5B%5D),%0A VersionTestCase((None, None), ()),%0A VersionTestCase((None, None), ''),%0A VersionTestCase((None, None), %7B%7D),%0A%5D%0A%0Adata_table_ugly = %5B%0A VersionTestCase((None, None), ('foo', 'bar', 'bah')),%0A VersionTestCase((None, None), %5B'foo', 'bar', 'bah'%5D),%0A VersionTestCase((None, None), %7B'foo': 'bar'%7D),%0A%5D%0A%0A%0Adef test_table_data_good_tag2version():%0A for entry in data_table_good:%0A assert entry.expected == guess.tag2version(entry.input_data)%0A%0A%0Adef test_table_data_bad_tag2version():%0A for entry in data_table_bad:%0A # Input Validation should probably return to us (None, None)%0A # assert entry.expected == guess.tag2version(entry.input_data)%0A assert (entry.input_data, None) == guess.tag2version(entry.input_data)%0A%0A%0Adef test_table_data_ugly_tag2version():%0A for entry in data_table_ugly:%0A # TODO: probably should be a more specific exception%0A with pytest.raises(Exception):%0A guess.tag2version(entry.input_data)%0A%0A%0Adef test_version2tag_simple():%0A assert '1.2.3' == guess.version2tag('1.2.3')%0A%0A%0Adef test_version2tag_type1():%0A assert 'v1.2.3' == guess.version2tag('1.2.3', 'vX.Y.Z')%0A%0A%0Adef test_version2tag_type2():%0A assert 'V1.2.3' == guess.version2tag('1.2.3', 'VX.Y.Z')%0A
|
|
e50060ca76c667b77db433ca03ef640140831dc9 | Add migration for dagman_metrics | migrations/004_add_dagman_metrics.py | migrations/004_add_dagman_metrics.py | Python | 0.000001 | @@ -0,0 +1,978 @@
+import migrations%0A%0Aconn = migrations.connect()%0A%0Acur = conn.cursor()%0A%0Acur.execute(%22%22%22%0Acreate table dagman_metrics (%0A id INTEGER UNSIGNED NOT NULL,%0A ts DOUBLE,%0A remote_addr VARCHAR(15),%0A hostname VARCHAR(256),%0A domain VARCHAR(256),%0A version VARCHAR(10),%0A wf_uuid VARCHAR(36),%0A root_wf_uuid VARCHAR(36),%0A start_time DOUBLE,%0A end_time DOUBLE,%0A duration FLOAT,%0A exitcode SMALLINT,%0A dagman_id VARCHAR(32),%0A parent_dagman_id VARCHAR(32),%0A jobs INTEGER,%0A jobs_failed INTEGER,%0A jobs_succeeded INTEGER,%0A dag_jobs INTEGER,%0A dag_jobs_failed INTEGER,%0A dag_jobs_succeeded INTEGER,%0A dag_status INTEGER,%0A planner VARCHAR(1024),%0A planner_version VARCHAR(10),%0A rescue_dag_number INTEGER,%0A total_job_time DOUBLE,%0A total_jobs INTEGER,%0A total_jobs_run INTEGER,%0A PRIMARY KEY (id),%0A FOREIGN KEY (id) REFERENCES raw_data(id) ON DELETE CASCADE%0A) ENGINE=InnoDB DEFAULT CHARSET=utf8;%0A%22%22%22)%0A%0Aconn.commit()%0A%0Acur.close()%0A%0A
|
|
dc314e50a573f3ecb2cf41d1e08df29ea991d3b6 | Add migrations versions | migrations/versions/d71a3e9499ef_.py | migrations/versions/d71a3e9499ef_.py | Python | 0.000001 | @@ -0,0 +1,2515 @@
+%22%22%22empty message%0A%0ARevision ID: d71a3e9499ef%0ARevises: %0ACreate Date: 2017-11-21 23:19:12.740735%0A%0A%22%22%22%0Afrom alembic import op%0Aimport sqlalchemy as sa%0A%0A%0A# revision identifiers, used by Alembic.%0Arevision = 'd71a3e9499ef'%0Adown_revision = None%0Abranch_labels = None%0Adepends_on = None%0A%0A%0Adef upgrade():%0A # ### commands auto generated by Alembic - please adjust! ###%0A op.create_table('user',%0A sa.Column('id', sa.Integer(), nullable=False),%0A sa.Column('username', sa.String(length=50), nullable=True),%0A sa.Column('password_hash', sa.String(length=128), nullable=True),%0A sa.Column('email', sa.String(length=120), nullable=True),%0A sa.Column('surname', sa.String(length=100), nullable=False),%0A sa.Column('first_name', sa.String(length=100), nullable=False),%0A sa.Column('active', sa.Boolean(), nullable=True),%0A sa.Column('date_created', sa.DateTime(), nullable=True),%0A sa.Column('date_modified', sa.DateTime(), nullable=True),%0A sa.PrimaryKeyConstraint('id'),%0A sa.UniqueConstraint('email'),%0A sa.UniqueConstraint('username')%0A )%0A op.create_table('bucket_list',%0A sa.Column('id', sa.Integer(), nullable=False),%0A sa.Column('name', sa.String(length=100), nullable=True),%0A sa.Column('description', sa.Text(), nullable=True),%0A sa.Column('interests', sa.String(length=120), nullable=True),%0A sa.Column('date_created', sa.DateTime(), nullable=True),%0A sa.Column('date_modified', sa.DateTime(), nullable=True),%0A sa.Column('created_by', sa.Integer(), nullable=False),%0A sa.ForeignKeyConstraint(%5B'created_by'%5D, %5B'user.id'%5D, ),%0A sa.PrimaryKeyConstraint('id'),%0A sa.UniqueConstraint('name')%0A )%0A op.create_table('item',%0A sa.Column('id', sa.Integer(), nullable=False),%0A sa.Column('name', sa.String(length=100), nullable=True),%0A sa.Column('description', sa.Text(), nullable=True),%0A sa.Column('status', sa.Text(), nullable=True),%0A sa.Column('date_accomplished', sa.DateTime(), nullable=True),%0A sa.Column('date_created', sa.DateTime(), nullable=True),%0A sa.Column('date_modified', sa.DateTime(), nullable=True),%0A sa.Column('bucketlists', sa.Integer(), nullable=False),%0A sa.ForeignKeyConstraint(%5B'bucketlists'%5D, %5B'bucket_list.id'%5D, ),%0A sa.PrimaryKeyConstraint('id'),%0A sa.UniqueConstraint('name')%0A )%0A # ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A # ### commands auto generated by Alembic - please adjust! ###%0A op.drop_table('item')%0A op.drop_table('bucket_list')%0A op.drop_table('user')%0A # ### end Alembic commands ###%0A
|
|
4933e4ca107516a667ae3449337746bf7e002cc2 | Create bkvm.py | bkvm.py | bkvm.py | Python | 0.000002 | @@ -0,0 +1,2112 @@
+#!/usr/bin/python%0A%0Aimport commands, time%0A%0Adef prepareTarget():%0A print %22prepare backup Target%22%0A print %22---------------------%22%0A cmd = %22mount -t cifs //10.0.0.9/public/BK%5C VM%5C XEN -o username=xxx,password=yyy /bak/%22%0A output = commands.getoutput(cmd)%0A cmd = %22ls -lht --time-style=%5C%22long-iso%5C%22 /bak/%22%0A output = commands.getoutput(cmd)%0A print output%0A print %22...%22%0A%0Adef releaseTarget():%0A print %22release backup Target%22%0A print %22---------------------%22%0A cmd = %22ls -lht --time-style=%5C%22long-iso%5C%22 /bak/%22%0A output = commands.getoutput(cmd)%0A print output%0A cmd = %22umount /bak/%22%0A output = commands.getoutput(cmd)%0A print %22...%22%0A%0Adef get_backup_vms():%0A result = %5B%5D%0A cmd = %22xe vm-list is-control-domain=false is-a-snapshot=false power-state=running%22%0A output = commands.getoutput(cmd)%0A%0A for vm in output.split(%22%5Cn%5Cn%5Cn%22):%0A lines = vm.splitlines()%0A uuid = lines%5B0%5D.split(%22:%22)%5B1%5D%5B1:%5D%0A name = lines%5B1%5D.split(%22:%22)%5B1%5D%5B1:%5D%0A result += %5B(uuid, name)%5D%0A return result%0A%0Adef backup_vm(uuid, filename, timestamp):%0A cmd = %22xe vm-snapshot uuid=%22 + uuid + %22 new-name-label=%22 + timestamp%0A snapshot_uuid = commands.getoutput(cmd)%0A%0A cmd = %22xe template-param-set is-a-template=false ha-always-run=false uuid=%22%0A cmd = cmd + snapshot_uuid%0A commands.getoutput(cmd)%0A%0A cmd = %22rm %22 + filename+%22.tmp%22%0A commands.getoutput(cmd)%0A%0A cmd = %22xe vm-export vm=%22 + snapshot_uuid + %22 filename=%22 + filename+%22.tmp%22%0A (status,output)=commands.getstatusoutput(cmd)%0A if (status==0):%0A cmd = %22rm %22 + filename + %22 ; mv %22 + filename+%22.tmp%22+ %22 %22 + filename %0A commands.getoutput(cmd)%0A else:%0A print %22Error%22%0A print output%0A%0A cmd = %22xe vm-uninstall uuid=%22 + snapshot_uuid + %22 force=true%22%0A commands.getoutput(cmd)%0A%0A%0AprepareTarget()%0A%0Aprint %22Backup Running VMs%22%0Aprint %22------------------%22%0Afor (uuid, name) in get_backup_vms():%0A timestamp = time.strftime(%22%25Y%25m%25d-%25H%25M%22, time.gmtime())%0A# filename = %22%5C%22/bak/%22 + timestamp + %22 %22 + name + %22.xva%5C%22%22%0A filename = %22%5C%22/bak/%22 + name + %22.xva%5C%22%22%0A print timestamp, uuid, name,%22 to %22, filename%0A backup_vm(uuid, filename, timestamp)%0Aprint %22...%22%0A%0AreleaseTarget()%0A
|
|
bc8d68fbe63bd6add932947222b82e00e768e7bf | Add logger.debug calls in to make debugging easier | djangosaml2/backends.py | djangosaml2/backends.py | # Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es)
# Copyright (C) 2009 Lorenzo Gil Sanchez <[email protected]>
#
# 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 logging
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User, SiteProfileNotAvailable
from django.core.exceptions import ObjectDoesNotExist
logger = logging.getLogger('djangosaml2')
class Saml2Backend(ModelBackend):
def authenticate(self, session_info=None, attribute_mapping=None,
create_unknown_user=True):
if session_info is None or attribute_mapping is None:
logger.error('Session info or attribute mapping are None')
return None
if not 'ava' in session_info:
logger.error('"ava" key not found in session_info')
return None
attributes = session_info['ava']
if not attributes:
logger.error('The attributes dictionary is empty')
saml_user = None
for saml_attr, django_fields in attribute_mapping.items():
if 'username' in django_fields and saml_attr in attributes:
saml_user = attributes[saml_attr][0]
if saml_user is None:
logger.error('Could not find saml_user value')
return None
user = None
username = self.clean_username(saml_user)
# Note that this could be accomplished in one try-except clause, but
# instead we use get_or_create when creating unknown users since it has
# built-in safeguards for multiple threads.
if create_unknown_user:
logger.debug(
'Check if the user "%s" exists or create otherwise' % username)
user, created = User.objects.get_or_create(username=username)
if created:
logger.debug('New user created')
user = self.configure_user(user, attributes, attribute_mapping)
else:
logger.debug('User updated')
user = self.update_user(user, attributes, attribute_mapping)
else:
logger.debug('Retrieving existing user "%s"' % username)
try:
user = User.objects.get(username=username)
user = self.update_user(user, attributes, attribute_mapping)
except User.DoesNotExist:
logger.error('The user "%s" does not exist' % username)
pass
return user
def clean_username(self, username):
"""Performs any cleaning on the "username" prior to using it to get or
create the user object. Returns the cleaned username.
By default, returns the username unchanged.
"""
return username
def configure_user(self, user, attributes, attribute_mapping):
"""Configures a user after creation and returns the updated user.
By default, returns the user with his attributes updated.
"""
user.set_unusable_password()
return self.update_user(user, attributes, attribute_mapping,
force_save=True)
def update_user(self, user, attributes, attribute_mapping,
force_save=False):
"""Update a user with a set of attributes and returns the updated user.
By default it uses a mapping defined in the settings constant
SAML_ATTRIBUTE_MAPPING. For each attribute, if the user object has
that field defined it will be set, otherwise it will try to set
it in the profile object.
"""
if not attribute_mapping:
return user
try:
profile = user.get_profile()
except ObjectDoesNotExist:
profile = None
except SiteProfileNotAvailable:
profile = None
user_modified = False
profile_modified = False
for saml_attr, django_attrs in attribute_mapping.items():
try:
for attr in django_attrs:
if hasattr(user, attr):
setattr(user, attr, attributes[saml_attr][0])
user_modified = True
elif profile is not None and hasattr(profile, attr):
setattr(profile, attr, attributes[saml_attr][0])
profile_modified = True
except KeyError:
# the saml attribute is missing
pass
if user_modified or force_save:
user.save()
if profile is not None and (profile_modified or force_save):
profile.save()
return user
| Python | 0.000001 | @@ -1489,16 +1489,134 @@
mpty')%0A%0A
+ logger.debug('attributes: %25s' %25 attributes)%0A logger.debug('attribute_mapping: %25s' %25 attribute_mapping)%0A
|
e050d9ce4fb4d63ec7857f581033258f87c805b0 | Create pyPdfMerger.py | pyPdfMerger.py | pyPdfMerger.py | Python | 0 | @@ -0,0 +1,1202 @@
+# -*- coding: utf-8 -*-%0A%0A%22%22%22%0A%09TITLE:%09%09pyPdfMerger.py%0A%09AUTHOR: %09John Himics%0A%09EMAIL: %09%[email protected]%0A%09TIMEZONE: %09EST%0A%09VERSION: %090%0A%09%0A%09DESCRIPTION: %09Merges pdf files together%0A%09%0A%09DEPENDANCIES: %09PyPDF2%0A%09%0A%22%22%22%0Afrom PyPDF2 import PdfFileMerger%0A%0A#Global Variables%0Amerger = PdfFileMerger()%0A%0A#Methods%0A%0A%0A#Program starts here%0Aif __name__ == %22__main__%22:%0A%0A%09input1 = open(%22C:%5CPFile%5C@ActiveProjects%5C1050LF Yeild Issues%5CEmails%5CAll emails 11-18-13 2.pdf%22, %22rb%22)%0A%09input2 = open(%22C:%5CPFile%5C@ActiveProjects%5C1050LF Yeild Issues%5CEmails%5CWade 343005 %5Bcompatibility mode%5D.pdf%22, %22rb%22)%0A%09input3 = open(%22C:%5CPFile%5C@ActiveProjects%5C1050LF Yeild Issues%5CEmails%5C1050LF Mill Mix MDR.pdf%22, %22rb%22)%0A%0A%09# add the first 3 pages of input1 document to output%0A%09#merger.append(fileobj = input1, pages = (0,3))%0A%0A%09# insert the first page of input2 into the output beginning after the second page%0A%09#merger.merge(position = 2, fileobj = input2, pages = (0,1))%0A%0A%09# append entire input3 document to the end of the output document%0A%09merger.append(input1)%0A%09merger.append(input2)%0A%09merger.append(input3)%0A%0A%09# Write to an output PDF document%0A%09output = open(%22C:%5CPFile%5C@ActiveProjects%5C1050LF Yeild Issues%5CEmails%5Cdocument-output.pdf%22, %22wb%22)%0A%09merger.write(output)%0A
|
|
62e65ae978b703b6af0b594e958e79d467e83421 | add 63 | python/p063.py | python/p063.py | Python | 0.99912 | @@ -0,0 +1,426 @@
+def g(power):%0A count = 0%0A i = 1%0A min = 10**(power - 1)%0A max = 10**power - 1%0A%0A while True:%0A result = i**power%0A if result %3E= min:%0A if result %3C= max:%0A count += 1%0A else:%0A break%0A i += 1%0A%0A return count%0A%0Acount = 0%0Afor i in xrange(1, 1000):%0A current = g(i)%0A if current %3E 0:%0A count += current%0A else:%0A break%0A%0Aprint count%0A%0A
|
|
600bf1bbce7db5f62d55537a33d4586fa2892d8a | Create conf.py | conf.py | conf.py | Python | 0.000001 | @@ -0,0 +1,4 @@
+#OK%0A
|
|
45cb6df45df84cb9ae85fc8aa15710bde6a15bad | Add create image functional negative tests | nova/tests/functional/test_images.py | nova/tests/functional/test_images.py | Python | 0.000005 | @@ -0,0 +1,2585 @@
+# Licensed under the Apache License, Version 2.0 (the %22License%22); you may%0A# not use this file except in compliance with the License. You may obtain%0A# 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, WITHOUT%0A# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the%0A# License for the specific language governing permissions and limitations%0A# under the License.%0A%0Afrom nova.tests.functional.api import client%0Afrom nova.tests.functional import test_servers%0A%0A%0Aclass ImagesTest(test_servers.ServersTestBase):%0A%0A def test_create_images_negative_invalid_state(self):%0A # Create server%0A server = self._build_minimal_create_server_request()%0A created_server = self.api.post_server(%7B%22server%22: server%7D)%0A server_id = created_server%5B'id'%5D%0A found_server = self._wait_for_state_change(created_server, 'BUILD')%0A self.assertEqual('ACTIVE', found_server%5B'status'%5D)%0A%0A # Create image%0A name = 'Snapshot 1'%0A self.api.post_server_action(%0A server_id, %7B'createImage': %7B'name': name%7D%7D)%0A self.assertEqual('ACTIVE', found_server%5B'status'%5D)%0A # Confirm that the image was created%0A images = self.api.get_images(detail=False)%0A image_map = %7Bimage%5B'name'%5D: image for image in images%7D%0A found_image = image_map.get(name)%0A self.assertTrue(found_image)%0A%0A # Change server status from ACTIVE to SHELVED for negative test%0A self.flags(shelved_offload_time = -1)%0A self.api.post_server_action(server_id, %7B'shelve': %7B%7D%7D)%0A found_server = self._wait_for_state_change(found_server, 'ACTIVE')%0A self.assertEqual('SHELVED', found_server%5B'status'%5D)%0A%0A # Create image in SHELVED (not ACTIVE, etc.)%0A name = 'Snapshot 2'%0A ex = self.assertRaises(client.OpenStackApiException,%0A self.api.post_server_action,%0A server_id,%0A %7B'createImage': %7B'name': name%7D%7D)%0A self.assertEqual(409, ex.response.status_code)%0A self.assertEqual('SHELVED', found_server%5B'status'%5D)%0A%0A # Confirm that the image was not created%0A images = self.api.get_images(detail=False)%0A image_map = %7Bimage%5B'name'%5D: image for image in images%7D%0A found_image = image_map.get(name)%0A self.assertFalse(found_image)%0A%0A # Cleanup%0A self._delete_server(server_id)%0A
|
|
18e2263a636e97519272a21562cbba4b978fcf49 | Create EmailForm | headlines/forms.py | headlines/forms.py | Python | 0 | @@ -0,0 +1,435 @@
+from flask_wtf import FlaskForm%0Afrom wtforms import StringField, TextAreaField, SubmitField%0Afrom wtforms.validators import DataRequired, Email%0A%0A%0Aclass EmailForm(FlaskForm):%0A %22%22%22 Form used to submit messages to the admin. %22%22%22%0A name = StringField('Name')%0A reply_to = StringField('Email', validators=%5BEmail(), DataRequired()%5D)%0A message = TextAreaField('Message', validators=%5BDataRequired()%5D)%0A submit = SubmitField('Submit')
|
|
61b21d1ec14e0be683f8da2b92b3ca2aa9fdcf59 | add sample for api caller | InvenTree/plugin/samples/integration/api_caller.py | InvenTree/plugin/samples/integration/api_caller.py | Python | 0 | @@ -0,0 +1,873 @@
+%22%22%22%0ASample plugin for calling an external API%0A%22%22%22%0Afrom django.utils.translation import ugettext_lazy as _%0A%0Afrom plugin import IntegrationPluginBase%0Afrom plugin.mixins import APICallMixin, SettingsMixin%0A%0A%0Aclass SampleApiCallerPlugin(APICallMixin, SettingsMixin, IntegrationPluginBase):%0A %22%22%22%0A A small api call sample%0A %22%22%22%0A PLUGIN_NAME = %22Sample API Caller%22%0A%0A SETTINGS = %7B%0A 'API_TOKEN': %7B%0A 'name': 'API Token',%0A 'protected': True,%0A %7D,%0A 'API_URL': %7B%0A 'name': 'External URL',%0A 'description': 'Where is your API located?',%0A 'default': 'https://reqres.in',%0A %7D,%0A %7D%0A API_URL_SETTING = 'API_URL'%0A API_TOKEN_SETTING = 'API_TOKEN'%0A%0A def get_external_url(self):%0A %22%22%22%0A returns data from the sample endpoint%0A %22%22%22%0A return self.api_call('api/users/2')%0A
|
|
d5fcaf05d100d3fe709b34b8f6b839736773a130 | Create dict.py | dict.py | dict.py | Python | 0.000001 | @@ -0,0 +1,1476 @@
+import random%0Aa=%5B%22a%22,%22b%22,%22c%22,%22d%22,%22e%22,%22f%22,%22g%22,%22h%22,%22i%22,%22j%22,%22k%22,%22l%22,%22m%22,%22n%22,%22o%22,%22p%22,%22q%22,%22r%22,%22s%22%5C%0A ,%22t%22,%22u%22,%22v%22,%22w%22,%22x%22,%22y%22,%22z%22%5D%0Adef create():%0A dictionary=open(%22dictionary.py%22,%22w%22)%0A tablewenn=%5B%22a%22,%22b%22,%22c%22,%22d%22,%22e%22,%22f%22,%22g%22,%22h%22,%22i%22,%22j%22,%22k%22,%22l%22,%22m%22,%22n%22,%22o%22,%22p%22,%22q%22,%22r%22,%22s%22%5C%0A ,%22t%22,%22u%22,%22v%22,%22w%22,%22x%22,%22y%22,%22z%22,%22 %22%5D%0A tablewennupper=%5B%22A%22,%22B%22,%22C%22,%22D%22,%22E%22,%22F%22,%22G%22,%22H%22,%22I%22,%22J%22,%22K%22,%22L%22,%22M%22,%22N%22,%22O%22,%22P%22,%22Q%22,%22R%22,%22S%22%5C%0A ,%22T%22,%22U%22,%22V%22,%22W%22,%22X%22,%22Y%22,%22Z%22%5D%0A tabledann=%5B%22a%22,%22b%22,%22c%22,%22d%22,%22e%22,%22f%22,%22g%22,%22h%22,%22i%22,%22j%22,%22k%22,%22l%22,%22m%22,%22n%22,%22o%22,%22p%22,%22q%22,%22r%22,%22s%22%5C%0A ,%22t%22,%22u%22,%22v%22,%22w%22,%22x%22,%22y%22,%22z%22,%22A%22,%22B%22,%22C%22,%22D%22,%22E%22,%22F%22,%22G%22,%22H%22,%22I%22,%22J%22,%22K%22,%22L%22,%22M%22,%22N%22,%22O%22,%22P%22,%22Q%22,%22R%22,%22S%22%5C%0A ,%22T%22,%22U%22,%22V%22,%22W%22,%22X%22,%22Y%22,%22Z%22,%22 %22%5D%0A dictionary.write(%22def ver(letter):%5Cn%22)%0A entkeys=%5B%5D%0A for i in tablewenn:%0A returning=random.choice(tabledann)%0A tabledann.remove(returning)%0A dictionary.write(%22 if letter == '%22+i+%22' :%5Cn return '%22+returning+%22'%5Cn%22)%0A entkeys.append(%5Breturning,i%5D)%0A for i in tablewennupper:%0A returning=random.choice(tabledann)%0A tabledann.remove(returning)%0A dictionary.write(%22 if letter == '%22+i+%22' :%5Cn return '%22+returning+%22'%5Cn%22)%0A entkeys.append(%5Breturning,i%5D)%0A dictionary.write(%22 else:%5Cn return letter%5Cn%22)%0A dictionary.write(%22def ent(letter):%5Cn%22)%0A for i in entkeys:%0A dictionary.write(%22 if letter == '%22+i%5B0%5D+%22':%5Cn return '%22+i%5B1%5D+%22'%5Cn%22)%0A dictionary.write(%22 else:%5Cn return letter%22)%0Adef debug():%0A pass%0A
|
|
2fba29b90156e844d7d61a15c9ad9c37e2b5dfe2 | load template | examples/aimsun/load_template.py | examples/aimsun/load_template.py | Python | 0.000001 | @@ -0,0 +1,910 @@
+%22%22%22%0ALoad an already existing Aimsun template and run the simulation%0A%22%22%22%0A%0Afrom flow.core.experiment import Experiment%0Afrom flow.core.params import AimsunParams, EnvParams, NetParams%0Afrom flow.core.params import VehicleParams%0Afrom flow.envs import TestEnv%0Afrom flow.scenarios.loop import Scenario%0Afrom flow.controllers.rlcontroller import RLController%0A%0A%0A%0Asim_params = AimsunParams(%0A sim_step=0.1, %0A render=True, %0A emission_path='data',%0A subnetwork_name=%22Subnetwork 8028981%22)%0A%0A%0Aenv_params = EnvParams()%0A%0Avehicles = VehicleParams()%0Avehicles.add(%0A veh_id=%22rl%22,%0A acceleration_controller=(RLController, %7B%7D),%0A num_vehicles=22)%0A%0Ascenario = Scenario(%0A name=%22test%22,%0A vehicles=vehicles,%0A net_params=NetParams(template=%22/Users/nathan/internship/I-210Pasadena/I-210subnetwork.ang%22)%0A)%0A%0Aenv = TestEnv(env_params, sim_params, scenario, simulator='aimsun')%0A%0Aexp = Experiment(env)%0A%0Aexp.run(1, 3000)%0A
|
|
c6f6278c1915ef90e8825f94cc33a4dea4124722 | Add http directory listing with content display | network/http_server_cat.py | network/http_server_cat.py | Python | 0 | @@ -0,0 +1,2212 @@
+#!/bin/env python3%0Aimport http.server%0Aimport string%0Aimport click%0Aimport pathlib%0Aimport urllib.parse%0Aimport os%0A%0A%[email protected]()%[email protected](%22port%22, required=False)%[email protected](%22-s%22, %22--server%22, default=%220.0.0.0%22)%0Adef main(port, server):%0A if not port:%0A port = 8888%0A http_server = http.server.HTTPServer((server, port), PostHandler)%0A print('Starting server on %7B0%7D:%7B1%7D, use %3CCtrl-C%3E to stop'.format(%0A server, port))%0A http_server.serve_forever()%0A%0Aclass PostHandler(http.server.BaseHTTPRequestHandler):%0A cwd = pathlib.Path(%22.%22)%0A%0A def do_GET(self):%0A body_file_cat = string.Template(%22$content%22)%0A body_dir_list = string.Template(%22%22%22%0A%3Ch1%3EDirectory listing for $cwd%3C/h1%3E%0A%3Cul%3E%0A$items%0A%3C/ul%3E%0A%22%22%22)%0A page = string.Template(%22%22%22%3Chtml%3E%0A%3Chead%3E%0A%3Cmeta http-equiv=%22Content-Type%22 content=%22text/html; charset=utf-8%22%3E%0A%3Ctitle%3EDirectory listing for $cwd%3C/title%3E%0A%3C/head%3E%0A%3Cbody%3E%0A$body%0A%3C/body%3E%0A%3C/html%3E%0A%22%22%22)%0A path = urllib.parse.urlparse(self.path)%0A fs_path = pathlib.Path(%22%7B%7D%7B%7D%22.format(self.cwd, path.path))%0A prefix_ref = %22%7B%7D/%22.format(path.path)%0A if fs_path.is_file():%0A body = body_file_cat%0A content = %22%22%0A with fs_path.open() as f:%0A content = %22%22.join(f.readlines())%0A content = %22%3Cpre%3E%7B%7D%3C/pre%3E%22.format(content)%0A body = body.substitute(content=content)%0A%0A else:%0A body = body_dir_list%0A items = list()%0A item_template = string.Template('%3Cli%3E%3Ca href=%22$item_path%22%3E$item_name%3C/a%3E%3C/li%3E')%0A for p in fs_path.iterdir():%0A item_path = urllib.parse.urljoin(prefix_ref, p.name)%0A item_name = p.name%0A if os.path.isdir(p):%0A item_name = %22%7B%7D/%22.format(item_name)%0A items.append(item_template.substitute(item_path=item_path, item_name=item_name))%0A body = body.substitute(cwd=fs_path, items=%22%5Cn%22.join(items))%0A%0A page = page.substitute(cwd=fs_path, body=body)%0A%0A self.send_response(200)%0A self.send_header(%22Content-type%22, %22text/html%22)%0A self.end_headers()%0A self.wfile.write(page.encode(%22UTF-8%22))%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
8fa81263cfcc63f6bf22ed2ad50103f91bc43b21 | Create hira.py | hira.py | hira.py | Python | 0.000002 | @@ -0,0 +1,484 @@
+#coding:utf-8%0Aimport hashlib%0A%0Astart = ord(u'%E3%81%82')%0Aend = ord(u'%E3%82%93')%0A%0Ahira = %5B%5D%0Aprint %22Create hiragana%22%0Afor i in range(start, end+1, 1):%0A hira.append(unichr(i).encode('utf-8'))%0A%0Anum = len(hira)%0Afor i4 in range(num):%0A for i3 in range(num):%0A for i2 in range(num):%0A for i1 in range(num):%0A msg = hira%5Bi1%5D + hira%5Bi2%5D + hira%5Bi3%5D + hira%5Bi4%5D%0A print msg,%0A print hashlib.md5(msg).hexdigest()%0A
|
|
92bc1ad22b6147f61ef4b51b16e115109bc04596 | add build.gyp | build.gyp | build.gyp | Python | 0.000001 | @@ -0,0 +1,398 @@
+%7B%0A 'targets':%5B%0A %7B%0A 'target_name':'start_first',%0A 'type':'executable',%0A 'dependencies':%5B%5D,%0A 'defines':%5B%5D,%0A 'include_dirs':%5B%5D,%0A 'sources':%5B%0A 'start_first/opengl_first.c',%0A %5D,%0A 'libraries':%5B%0A '-lGLU -lGL -lglut'%0A %5D,%0A 'conditions':%5B%5D%0A %7D%0A %5D,%0A%7D%0A
|
|
45a0b65106f665872f14780e93ab9f09e65bbce3 | add genRandomGraph.py | ComplexCiPython/genRandomGraph.py | ComplexCiPython/genRandomGraph.py | Python | 0.000001 | @@ -0,0 +1,293 @@
+import networkx%0Aimport sys%0A%0Aif len(sys.argv) %3C 2:%0A%0A%09print (%22python genRandomGraph.py %5Boutput folder%5D%22);%0A%09input()%0A%09sys.exit(0);%0A%0AoutputPath = sys.argv%5B1%5D%0A%0AG=networkx.erdos_renyi_graph(100000,3/100000)%0Anetworkx.write_edgelist(G, outputPath + %22/genRandomGraph.csv%22, data=False , delimiter=',')%0A%0A%0A
|
|
3b15fb1d43bad6d6cf2112538d1de8c1710d0272 | add test for within_page_range | freelancefinder/freelancefinder/tests/test_within_page_range_templatetag.py | freelancefinder/freelancefinder/tests/test_within_page_range_templatetag.py | Python | 0.000001 | @@ -0,0 +1,903 @@
+%22%22%22Test the within_page_range function.%22%22%22%0A%0Afrom ..templatetags.within_page_range import within_filter%0A%0A%0Adef test_in_range_above():%0A %22%22%22One page above current should be displayed.%22%22%22%0A test_page = 5%0A current_page = 4%0A%0A result = within_filter(test_page, current_page)%0A assert result%0A%0A%0Adef test_in_range_below():%0A %22%22%22One page below current should be displayed.%22%22%22%0A test_page = 3%0A current_page = 4%0A%0A result = within_filter(test_page, current_page)%0A assert result%0A%0A%0Adef test_out_of_range_above():%0A %22%22%2220 pages above current should not be displayed.%22%22%22%0A test_page = 74%0A current_page = 54%0A%0A result = within_filter(test_page, current_page)%0A assert not result%0A%0A%0Adef test_out_of_range_below():%0A %22%22%2220 pages below current should not be displayed.%22%22%22%0A test_page = 34%0A current_page = 54%0A%0A result = within_filter(test_page, current_page)%0A assert not result%0A
|
|
0c315f766b31c105c60b39746db977d6702955ca | Remove unneeded model attributes | successstories/views.py | successstories/views.py | from django.contrib import messages
from django.core.urlresolvers import reverse
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, DetailView, ListView
from honeypot.decorators import check_honeypot
from .forms import StoryForm
from .models import Story, StoryCategory
class ContextMixin:
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
ctx['category_list'] = StoryCategory.objects.all()
return ctx
class StoryCreate(ContextMixin, CreateView):
model = Story
form_class = StoryForm
template_name = 'successstories/story_form.html'
success_message = (
'Your success story submission has been recorded. '
'It will be reviewed by the PSF staff and published.'
)
@method_decorator(check_honeypot)
def dispatch(self, *args, **kwargs):
return super().dispatch(*args, **kwargs)
def get_success_url(self):
return reverse('success_story_create')
def form_valid(self, form):
messages.add_message(self.request, messages.SUCCESS, self.success_message)
return super().form_valid(form)
model = Story
class StoryDetail(ContextMixin, DetailView):
template_name = 'successstories/story_detail.html'
context_object_name = 'story'
def get_queryset(self):
if self.request.user.is_staff:
return Story.objects.select_related()
return Story.objects.select_related().published()
class StoryList(ListView):
model = Story
template_name = 'successstories/story_list.html'
context_object_name = 'stories'
def get_queryset(self):
return Story.objects.select_related().published()
class StoryListCategory(ContextMixin, DetailView):
model = StoryCategory
| Python | 0.000001 | @@ -1166,34 +1166,16 @@
(form)%0A%0A
- model = Story%0A
class St
@@ -1505,34 +1505,16 @@
tView):%0A
- model = Story%0A
temp
|
9abb8108f62451fb993a398c8165a4605e40ec4a | Add tests for JSONPResponseMiddleware | mapit/tests/test_middleware.py | mapit/tests/test_middleware.py | Python | 0 | @@ -0,0 +1,1965 @@
+from django.test import TestCase%0Afrom django.test.client import RequestFactory%0Afrom django.http import HttpResponse, HttpResponsePermanentRedirect%0A%0Afrom ..middleware import JSONPMiddleware%0A%0A%0Aclass JSONPMiddlewareTest(TestCase):%0A%0A def setUp(self):%0A self.middleware = JSONPMiddleware()%0A self.factory = RequestFactory()%0A%0A def test_process_response_ignores_302_redirects(self):%0A request = self.factory.get(%22/dummy_url%22, %7B%22callback%22: %22xyz%22%7D)%0A response = HttpResponsePermanentRedirect(%22/new_url%22)%0A middleware_response = self.middleware.process_response(request, response)%0A self.assertEqual(middleware_response, response)%0A%0A def test_process_response_uses_callback(self):%0A request = self.factory.get(%22/dummy_url%22, %7B%22callback%22: %22xyz%22%7D)%0A response = HttpResponse(content=%22blah%22)%0A middleware_response = self.middleware.process_response(request, response)%0A self.assertEqual(middleware_response.content, u'xyz(blah)')%0A%0A def test_process_response_uses_ignores_requests_without_callback(self):%0A request = self.factory.get(%22/dummy_url%22)%0A response = HttpResponse(content=%22blah%22)%0A middleware_response = self.middleware.process_response(request, response)%0A self.assertEqual(middleware_response, response)%0A%0A def test_process_response_callback_allowed_characters(self):%0A request = self.factory.get(%22/dummy_url%22, %7B%22callback%22: %22xyz123_$.%22%7D)%0A response = HttpResponse(content=%22blah%22)%0A middleware_response = self.middleware.process_response(request, response)%0A self.assertEqual(middleware_response.content, u'xyz123_$.(blah)')%0A%0A # Try with a character not allowed in the callback%0A request = self.factory.get(%22/dummy_url%22, %7B%22callback%22: %22xyz123_$.%5B%22%7D)%0A response = HttpResponse(content=%22blah%22)%0A middleware_response = self.middleware.process_response(request, response)%0A self.assertEqual(middleware_response, response)%0A%0A
|
|
e20d3ff6147b857cb9a8efa32bfb4ee80610dd34 | Revert "dump" | dump/fastMessageReaderOriginal.py | dump/fastMessageReaderOriginal.py | Python | 0.000002 | @@ -0,0 +1,1383 @@
+#!/usr/bin/python%0A%0Aimport sys%0Aimport re%0A%0A# ============================================================================ %0A%0Aclass MessageReader:%0A%0A messageRegexp = r%22s*(%5Cw+)%5C%5B%5Cd+%5C%5D=(.*?)(?=%5Cs%5Cw+%5C%5B%5Cd+%5C%5D%7C$)%22;%0A%0A def __init__(self, fileName):%0A self.fileName = fileName%0A #self.file = open(fileName, encoding=%22utf8%22)%0A self.file = open(fileName)%0A%0A self.carryover = %22%22;%0A%0A def __del__(self):%0A self.file.close()%0A%0A def getMessage(self):%0A if (self.carryover != %22%22):%0A line = self.carryover%0A self.carryover = %22%22%0A else:%0A line = self.file.readline()%0A%0A while (line.startswith('ApplVerID') is not True):%0A if not line: return %7B%7D%0A line = self.file.readline()%0A message = dict(re.findall(self.messageRegexp, line))%0A message%5B'entries'%5D = %5B%5D%0A%0A line = self.file.readline();%0A noEntries = re.sub(%22.*?NoMDEntries%5C%5B268%5C%5D%5Cs*=%5Cs*(%5Cd+)%5B%5E%5Cd%5D*%22, r'%5C1', line)%0A if (noEntries == line):%0A self.carryover = line;%0A return message%0A%0A for i in range(int(noEntries)):%0A line = self.file.readline().split(':')%5B1%5D.strip()%0A entry = dict(re.findall(self.messageRegexp, line))%0A message%5B%22entries%22%5D.append(entry)%0A%0A return message%0A%0A# ============================================================================%0A
|
|
f917c7ccfbe22a50049e76957a05f35eaaa46b2a | migrate child table | polling_stations/apps/addressbase/migrations/0010_remove_onsud_ctry_flag.py | polling_stations/apps/addressbase/migrations/0010_remove_onsud_ctry_flag.py | Python | 0.000002 | @@ -0,0 +1,326 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.20 on 2019-02-15 14:12%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B(%22addressbase%22, %220009_onsud_ced%22)%5D%0A%0A operations = %5Bmigrations.RemoveField(model_name=%22onsud%22, name=%22ctry_flag%22)%5D%0A
|
|
1553cdda2edc16368ba2281616923e849f09bdee | Create matching_{x,y}.py | hacker_rank/regex/repetitions/matching_{x,y}.py | hacker_rank/regex/repetitions/matching_{x,y}.py | Python | 0.998695 | @@ -0,0 +1,69 @@
+Regex_Pattern = r'%5E%5Cd%7B1,2%7D%5Ba-zA-Z%5D%7B3,%7D%5CW%7B0,3%7D$'%09# Do not delete 'r'.%0A
|
|
527a53ee1e43f59462b94b50ea997058836a7031 | Create voicersss-inmoovservice-test.py | home/moz4r/Test/voicersss-inmoovservice-test.py | home/moz4r/Test/voicersss-inmoovservice-test.py | Python | 0 | @@ -0,0 +1,459 @@
+i01 = Runtime.createAndStart(%22i01%22, %22InMoov%22)%0Ai01.mouth = Runtime.createAndStart(%22i01.mouth%22, %22voiceRSS%22)%0A%0Apython.subscribe(i01.mouth.getName(),%22publishStartSpeaking%22)%0Apython.subscribe(i01.mouth.getName(),%22publishEndSpeaking%22)%0A%0Adef onEndSpeaking(text):%0A%09print %22end speak%22%0Adef onStartSpeaking(text):%0A%09print %22start speak%22%0A%0Ai01.mouth.setKey(%226b714718f09e48c9a7f260e385ca99a4%22)%0Ai01.mouth.setVoice(%22fr-fr%22);%0Ai01.mouth.speakBlocking(u%22test accent utf8 : %C3%A9l%C3%A9phant%22)%0A
|
|
75980fc2e2f63e210f1e58e9a1d56c09072aa04e | add play_camera.py | python/video/play_camera.py | python/video/play_camera.py | Python | 0.000002 | @@ -0,0 +1,681 @@
+#!/usr/bin/env python3%0A# encoding: utf-8%0A# pylint: disable=no-member%0A%0A%22%22%22Play a video with OpenCV.%22%22%22%0A%0Aimport sys%0Aimport cv2%0A%0Adef main():%0A %22%22%22The main function of this module.%22%22%22%0A cv2.namedWindow('video', cv2.WINDOW_AUTOSIZE)%0A%0A cap = cv2.VideoCapture(0)%0A i = 0%0A while cap.isOpened():%0A ret, frame = cap.read()%0A if not ret: # done%0A break%0A%0A i += 1%0A if i == 1:%0A print frame.shape, frame.dtype, frame.size%0A%0A cv2.imshow('video', frame)%0A%0A key = cv2.waitKey(30)%0A if key & 0xFF == ord('q'): # quit%0A break%0A%0A cap.release()%0A cv2.destroyAllWindows()%0A%0Aif __name__ == '__main__':%0A main()%0A
|
|
6dfc5a3d7845633570b83aac06c47756292cf8ac | Add tests for get_uid() method for common DB models. | st2common/tests/unit/test_db_model_uids.py | st2common/tests/unit/test_db_model_uids.py | Python | 0 | @@ -0,0 +1,1948 @@
+# contributor license agreements. See the NOTICE file distributed with%0A# this work for additional information regarding copyright ownership.%0A# The ASF licenses this file to You under the Apache License, Version 2.0%0A# (the %22License%22); you may not use this file except in compliance with%0A# the License. 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%0Aimport unittest2%0A%0Afrom st2common.models.db.pack import PackDB%0Afrom st2common.models.db.sensor import SensorTypeDB%0Afrom st2common.models.db.action import ActionDB%0Afrom st2common.models.db.rule import RuleDB%0Afrom st2common.models.db.trigger import TriggerTypeDB%0Afrom st2common.models.db.trigger import TriggerDB%0A%0A__all__ = %5B%0A 'DBModelUIDFieldTestCase'%0A%5D%0A%0A%0Aclass DBModelUIDFieldTestCase(unittest2.TestCase):%0A def test_get_uid(self):%0A pack_db = PackDB(ref='ma_pack')%0A self.assertEqual(pack_db.get_uid(), 'pack:ma_pack')%0A%0A sensor_type_db = SensorTypeDB(name='sname', pack='spack')%0A self.assertEqual(sensor_type_db.get_uid(), 'sensor_type:spack:sname')%0A%0A action_db = ActionDB(name='aname', pack='apack', runner_info=%7B%7D)%0A self.assertEqual(action_db.get_uid(), 'action:apack:aname')%0A%0A rule_db = RuleDB(name='rname', pack='rpack')%0A self.assertEqual(rule_db.get_uid(), 'rule:rpack:rname')%0A%0A trigger_type_db = TriggerTypeDB(name='ttname', pack='ttpack')%0A self.assertEqual(trigger_type_db.get_uid(), 'trigger_type:ttpack:ttname')%0A%0A trigger_db = TriggerDB(name='tname', pack='tpack')%0A self.assertTrue(trigger_db.get_uid().startswith('trigger:tpack:tname:'))%0A
|
|
5d64acfd475ca0bb0db2ef7c032fc4ee16df4f75 | remove highlight table | alembic/versions/186928676dbc_remove_highlights.py | alembic/versions/186928676dbc_remove_highlights.py | Python | 0.000005 | @@ -0,0 +1,1695 @@
+%22%22%22remove_highlights%0A%0ARevision ID: 186928676dbc%0ARevises: f163a00a02aa%0ACreate Date: 2019-06-01 15:14:13.999836%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '186928676dbc'%0Adown_revision = 'f163a00a02aa'%0Abranch_labels = None%0Adepends_on = None%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0Afrom sqlalchemy.dialects import mysql%0A%0Adef upgrade():%0A # ### commands auto generated by Alembic - please adjust! ###%0A op.drop_table('tb_stream_chunk_highlight')%0A # ### end Alembic commands ###%0A%0A%0Adef downgrade():%0A # ### commands auto generated by Alembic - please adjust! ###%0A op.create_table('tb_stream_chunk_highlight',%0A sa.Column('id', mysql.INTEGER(display_width=11), autoincrement=True, nullable=False),%0A sa.Column('stream_chunk_id', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),%0A sa.Column('created_at', mysql.DATETIME(), nullable=False),%0A sa.Column('highlight_offset', mysql.INTEGER(display_width=11), autoincrement=False, nullable=False),%0A sa.Column('description', mysql.VARCHAR(length=128), nullable=True),%0A sa.Column('override_link', mysql.VARCHAR(length=256), nullable=True),%0A sa.Column('thumbnail', mysql.TINYINT(display_width=1), autoincrement=False, nullable=True),%0A sa.Column('created_by', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),%0A sa.Column('last_edited_by', mysql.INTEGER(display_width=11), autoincrement=False, nullable=True),%0A sa.ForeignKeyConstraint(%5B'stream_chunk_id'%5D, %5B'tb_stream_chunk.id'%5D, name='tb_stream_chunk_highlight_ibfk_1'),%0A sa.PrimaryKeyConstraint('id'),%0A mysql_default_charset='utf8mb4',%0A mysql_engine='InnoDB'%0A )%0A # ### end Alembic commands ###%0A
|
|
8658ad72c74306617e58ca82ff0f3fdba35bd353 | implement auto build database interface | app/tools/dbautocreat.py | app/tools/dbautocreat.py | Python | 0 | @@ -0,0 +1,892 @@
+#-*- coding:utf-8 -*-%0Aimport asyncio%0Aimport aiomysql%0Afrom tools.config import Config%0A%0A%0Aclass AutoCreate(obj):%0A%09def __init__(self):%0A%09%09pass%0A%09def _create_db(self):%0A%09%09pass%0A%09def _create_field_type(self):%0A%09%09pass%0A%09def _create_field_primary_key(self):%0A%09%09pass%0A%09def _create_field_unique_key(self):%0A%09%09pass%0A%09def _create_auto_increment(self):%0A%09%09pass%0A%09def _create_default(self):%0A%09%09pass%0A%09def _create_table(self):%0A%09%09pass%0A%09def run(self):%0A%09%09pass%0A%[email protected]%0Adef auto_create():%0A%09conn=yield from aiomysql.connect(db=Config.database.database,%0A%09%09%09%09%09host=Config.database.host,%0A%09%09%09%09%09password=Config.database.password,%0A%09%09%09%09%09user=Config.database.user)%0A%09cursor =yield from conn.cursor()%0A%09yield from cursor.execute('show databases;')%0A%09ret=yield from cursor.fetchall()%0A%09print(ret)%0A%0Aif __name__=='__main__':%0A%09loop=asyncio.get_event_loop()%0A%09loop.run_until_complete(asyncio.wait(%5Bauto_create()%5D))%0A%09loop.close()%0A%0A%09%0A%0A%0A
|
|
36b8c44f8c2554109ab4ab09add9ac10fae20781 | add entities orm | cliche/services/tvtropes/entities.py | cliche/services/tvtropes/entities.py | Python | 0.000406 | @@ -0,0 +1,2072 @@
+from sqlalchemy import Column, DateTime, ForeignKey, String%0Afrom sqlalchemy.ext.declarative import declarative_base%0Afrom sqlalchemy.orm import relationship%0A%0A%0ABase = declarative_base()%0A%0A%0A__all__ = 'Entity'%0A%0A%0Aclass Entity(Base):%0A namespace = Column(String, primary_key=True)%0A name = Column(String, primary_key=True)%0A url = Column(String)%0A last_crawled = Column(DateTime)%0A type = Column(String)%0A%0A relations = relationship('Relation', foreign_keys=%5Bnamespace, name%5D,%0A primaryjoin='and_(Entity.namespace == %5C%0A Relation.origin_namespace, %5C%0A Entity.name == Relation.origin)',%0A collection_class=set)%0A%0A def __init__(self, namespace, name, url, last_crawled, type):%0A self.namespace = namespace%0A self.name = name%0A self.url = url%0A self.last_crawled = last_crawled%0A self.type = type%0A%0A def __repr__(self):%0A return %22%3CEntity('%25s', '%25s', '%25s', '%25s', '%25s')%22 %25 (%0A self.namespace, self.name, self.url, str(self.last_crawled),%0A self.type%0A )%0A%0A __tablename__ = 'entities'%0A __repr_columns__ = namespace, name%0A%0A%0Aclass Relation(Base):%0A origin_namespace = Column(String, ForeignKey(Entity.namespace),%0A primary_key=True)%0A origin = Column(String, ForeignKey(Entity.name), primary_key=True)%0A destination_namespace = Column(String, primary_key=True)%0A destination = Column(String, primary_key=True)%0A%0A origin_entity = relationship('Entity',%0A foreign_keys=%5Borigin_namespace, origin%5D)%0A%0A def __init__(self, origin_namespace, origin, destination_namespace,%0A destination):%0A self.origin_namespace = origin_namespace%0A self.origin = origin%0A self.destination_namespace = destination_namespace%0A self.destination = destination%0A%0A __tablename__ = 'relations'%0A __repr_columns__ = origin_namespace, origin, destination_namespace, %5C%0A destination%0A
|
|
ad664a7722da63d783a2b9d73077d91a8a012057 | Create hello.py | Python/hello.py | Python/hello.py | Python | 0.999979 | @@ -0,0 +1,24 @@
+print(%22hello world!!!%22)%0A
|
|
dfed8f837b5fe07445b3914b33c1dab1b0b5741b | add basic UAV object incl. very basic search algo | uav.py | uav.py | Python | 0 | @@ -0,0 +1,692 @@
+import random%0A%0Aclass Uav:%0A def __init__(x,y, worldMap):%0A self.x = x%0A self.y = y%0A self.worldMap = worldMap%0A self.sensorStrength = None%0A%0A def setMap(self, newMap):%0A self.worldMap = newMap%0A%0A def nextStep(self):%0A %22%22%22 where should we go next tick? %22%22%22%0A options = self.surroundingValues()%0A m = max(a)%0A maxIndexes = %5Bi for i, j in enumerate(a) if j == m%5D%0A%0A return random.choice(maxIndexes)%0A%0A def surroundingValues(self):%0A return %5Bself.worldMap%5Bself.x%5D%5Bself.y+1%5D,%0A self.worldMap%5Bself.x+1%5D%5Bself.y%5D,%0A self.worldMap%5Bself.x%5D%5Bself.y-1%5D,%0A self.worldMap%5Bself.x-1%5D%5Bself.y%5D%5D%0A
|
|
8d1946c9656ea6c29d4730a68cbf4610152cd98b | make migrations | poll/migrations/0002_vote_user_id.py | poll/migrations/0002_vote_user_id.py | Python | 0.000057 | @@ -0,0 +1,423 @@
+# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('poll', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='vote',%0A name='user_id',%0A field=models.IntegerField(default=None),%0A preserve_default=False,%0A ),%0A %5D%0A
|
|
64109dddedb7441456ae8e255c6a4b20ccaa6a73 | Create ReinhardNorm.py | ReinhardNorm.py | ReinhardNorm.py | Python | 0.000001 | @@ -0,0 +1,2058 @@
+import numpy%0A%0Adef ReinhardNorm(I, TargetMu, TargetSigma):%0A'''%0APerforms Reinhard color normalization to transform the color characteristics of an image to %0Aa desired standard. The standard is defined by the mean and standard deviations of%0Athe target image in LAB color space defined by Ruderman. The input image is converted to %0ARuderman's LAB space, the LAB channels are each centered and scaled to zero-mean unit %0Avariance, and then rescaled and shifted to match the target image statistics.%0A*Inputs:%0A%09I (rgbimage) - an RGB image of type unsigned char.%0A%09TargetMu - a 3-element list containing the means of the target image channels in LAB %0A%09%09%09%09color space.%0A%09TargetSigma - a 3-element list containing the standard deviations of the target image%0A%09%09%09%09%09channels in LAB color space.%0A*Outputs:%0A%09Normalized (rgbimage) - a normalized RGB image with corrected color characteristics.%0A*Related functions:%0A%09RudermanLABFwd, RudermanLABInv%0A*References:%0AErik Reinhard, Michael Ashikhmin, Bruce Gooch, and Peter Shirley. 2001. Color Transfer between Images. IEEE Comput. Graph. Appl. 21, 5 (September 2001), 34-41. %0ADaniel Ruderman, Thomas Cronin, Chuan-Chin Chiao, Statistics of Cone Responses to Natural Images: Implications for Visual Coding, J. Optical Soc. of America, vol. 15, no. 8, 1998, pp. 2036-2045.%0A'''%0A%0A#get input image dimensions%0Am = I.shape%5B0%5D%0An = I.shape%5B1%5D%0A%0A#convert input image to LAB color space%0ALAB = RudermanLAB(I)%0A%0A#center and scale to zero-mean and unit variance%0AMu = LAB.sum(axis=0).sum(axis=0)%0ALAB%5B:,:,0%5D = LAB%5B:,:,0%5D - Mu%5B0%5D%0ALAB%5B:,:,1%5D = LAB%5B:,:,1%5D - Mu%5B1%5D%0ALAB%5B:,:,2%5D = LAB%5B:,:,2%5D - Mu%5B2%5D%0ASigma = (LAB*LAB).sum(axis=0).sum(axis=0) / (m*n-1)%0ALAB%5B:,:,0%5D = LAB%5B:,:,0%5D / Sigma%5B0%5D%0ALAB%5B:,:,1%5D = LAB%5B:,:,1%5D / Sigma%5B1%5D%0ALAB%5B:,:,2%5D = LAB%5B:,:,2%5D / Sigma%5B2%5D%0A%0A#rescale and recenter to match target statistics%0ALAB%5B:,:,0%5D = LAB%5B:,:,0%5D * TargetSigma%5B0%5D + TargetMu%5B0%5D%0ALAB%5B:,:,1%5D = LAB%5B:,:,1%5D * TargetSigma%5B1%5D + TargetMu%5B1%5D%0ALAB%5B:,:,2%5D = LAB%5B:,:,2%5D * TargetSigma%5B2%5D + TargetMu%5B2%5D%0A%0A#convert back to RGB colorspace%0ANormalized = RudermanLABInv(LAB)%0A%0Areturn(Normalized)%0A
|
|
ebabfa0e14bdfd061e248285b8f7b5473f5a676e | Create convert_to_morse.py | morse_code/convert_to_morse.py | morse_code/convert_to_morse.py | Python | 0.998175 | @@ -0,0 +1,791 @@
+from ConfigParser import SafeConfigParser%0Aimport string%0A%0Atarget = 'target.txt'%0A%0A%0Adef parse_ini():%0A parser = SafeConfigParser()%0A parser.read('conversion.ini')%0A morselist = list(string.ascii_uppercase)%0A number = 0%0A for i in morselist:%0A i = parser.get('CONVERSIONS', i)%0A morselist%5Bnumber%5D = i%0A number += 1%0A return morselist%0A%0Adef convert_target():%0A with open(target, %22r%22) as targetfile:%0A targetstring = targetfile.read()%0A for i in xrange(0, len(targetstring)):%0A print targetstring%5Bi%5D%0A if any(character in targetstring)%0A%0A pass%0A%0A%0Amorselist = parse_ini()%0A#print morselist%0Acapital_alphabet = list(string.ascii_uppercase)%0Alower_alphabet = list(string.ascii_lowercase)%0A#print capital_alphabet%0A#print lower_alphabet%0Aconvert_target()%0A
|
|
fcb311ffd264821767f58c92e96101aa8086acf5 | rewrite DHKE.py as crypto.py | crypto.py | crypto.py | Python | 0.999999 | @@ -0,0 +1,2486 @@
+import random%0Aimport time%0A%0Atimestamp = int(time.time())%0Arandom.seed(timestamp)%0A%0A%0Adef gen_check(n):%0A if not isprime(n):%0A while not isprime(n):%0A n = random.randint(0, timestamp)%0A%0A%0Adef input_check(n):%0A if not isprime(n):%0A n = input(%22Sorry, that number isn't prime. Please try another: %22)%0A%0A%0Adef isprime(n):%0A '''check if integer n is a prime'''%0A # make sure n is a positive integer%0A n = abs(int(n))%0A # 0 and 1 are not primes%0A if n %3C 2:%0A return False%0A # 2 is the only even prime number%0A if n == 2:%0A return True%0A # all other even numbers are not primes%0A if not n & 1:%0A return False%0A # range starts with 3 and only needs to go up the squareroot of n%0A # for all odd numbers%0A for x in range(3, int(n**0.5) + 1, 2):%0A if n %25 x == 0:%0A return False%0A return True%0A%0A%0Adef publicKey():%0A resp = input(%22Do you have a shared base integer? (y/n): %22)%0A if resp.lower() == %22y%22:%0A b = input(%22Please enter your shared base integer: %22)%0A input_check(b)%0A elif resp.lower() == %22n%22:%0A b = random.randint(0, timestamp)%0A gen_check(b)%0A print(%22Your shared base integer is: %22, b)%0A%0A resp = input(%22Do you have a secret integer? (y/n): %22)%0A if resp.lower() == %22y%22:%0A alex = input(%22Please enter your secret integer: %22)%0A input_check(alex)%0A elif resp.lower() == %22n%22:%0A alex = random.randint(0, timestamp)%0A gen_check(alex)%0A print(%22Your secret integer is: %22, alex)%0A%0A resp = input(%22Do you have a shared modulus? (y/n): %22)%0A if resp.lower() == %22y%22:%0A mp = input(%22Please enter your shared modulus: %22)%0A input_check(mp)%0A elif resp.lower() == %22n%22:%0A mp = random.randint(0, timestamp)%0A gen_check(mp)%0A print(%22Your shared modulus is: %22, mp)%0A%0A b = int(b)%0A alex = int(alex)%0A mp = int(mp)%0A pubKey = b ** alex%0A pubKey = pubKey %25 mp%0A return pubKey%0A%0A%0Adef sharedSecret():%0A pK = input(%22Please enter your public key: %22)%0A mp = input(%22Please enter your shared modulus: %22)%0A alex = input(%22Please enter your secret integer: %22)%0A sharedSec = (int(pK) ** int(alex)) %25 int(mp)%0A return sharedSec%0A%0A%0Aanswer = input(%22Would you like to calculate a public key, or a shared secret? %22)%0Aif answer.lower() == %22public key%22:%0A public = publicKey()%0A print(%22Your public key is: %22, public)%0Aelif answer.lower() == %22shared secret%22:%0A shared = sharedSecret()%0A print(%22Your shared secret is: %22, shared)%0A
|
|
615e51ce1bf15c012a6c7cc2d026cb69bf0ce2b8 | Create MAIN.py | MAIN.py | MAIN.py | Python | 0.000002 | @@ -0,0 +1,2161 @@
+def pythagoras(SIDE, LEN1, LEN2):%0A %0A from math import sqrt # This is function is needed to work, it **SHOULD** be included with the default install. %0A%0A ANSWER = %22Error Code 1%22 # This should not logicaly happen if the user is not an idiot and follows the usage.%0A %0A%0A if type(LEN1) is str or type(LEN2) is str: # This checks if the user didn't listen to the usage // Was the LEN a string?%0A ANWSER = %22Error Code 2%22%0A return ANWSER # This will return an error to the user that didn't listen.%0A%0A if type(SIDE) is int or type(SIDE) is float: # This checks if the user didn't listen to the usage // Was the SIDE an integer or float?%0A ANWSER = %22Error Code 4%22%0A return ANWSER # This will return an error to the user that didn't listen.%0A%0A #--SIDE C--%0A if SIDE.lower() == %22c%22:%0A%0A #SIDE C CALCULATION (Hypotenuse)%0A A_SIDE = LEN1 %0A B_SIDE = LEN2 %0A C_SIDE = sqrt(A_SIDE * A_SIDE + B_SIDE * B_SIDE) %0A%0A ANSWER = C_SIDE # This sets the answer to be returned.%0A %0A #--SIDE A--%0A elif SIDE.lower() == 'a': %0A%0A if LEN1 %3C LEN2: # This will happen if the user did not follow instructions. See error below. %0A print(%22The hypotenues should be bigger%22)%0A anwser = %22Error code 2%22%0A return ANSWER # This will return an error to the user that didn't listen.%0A%0A #SIDE A CALCULATION %0A B_SIDE = LEN2 %0A C_SIDE = LEN1 %0A ASIDE = sqrt((C_SIDE * C_SIDE) - (B_SIDE * B_SIDE)) %0A%0A ANSWER = A_SIDE # This sets the answer to be returned.%0A%0A #--SIDE B--%0A elif SIDE.lower() == 'b':%0A%0A if LEN1 %3C LEN2: # This will happen if the user did not follow instructions. See error below. %0A print(%22The hypotenues should be bigger%22)%0A ANSWER = %22Error code 2%22%0A return ANSWER # This will return an error to the user that didn't listen.%0A%0A #SIDE B CALCULATION %0A A_SIDE = LEN2%0A C_SIDE = LEN1%0A B_SIDE = sqrt(C_SIDE * C_SIDE - A_SIDE * A_SIDE) %0A%0A ANSWER = B_SIDE # This sets the answer to be returned.%0A %0A%0A return ANSWER # Returns the anwser for the user to use. %0A%0A%0A
|
|
cbe0d5b37d4055ea78568838c3fd4cc953342b80 | remove stale data | geoconnect/apps/gis_tabular/utils_stale_data.py | geoconnect/apps/gis_tabular/utils_stale_data.py | Python | 0.002077 | @@ -0,0 +1,1531 @@
+from datetime import datetime, timedelta%0A%0Afrom apps.gis_tabular.models import TabularFileInfo # for testing%0Afrom apps.gis_tabular.models import WorldMapTabularLayerInfo,%5C%0A WorldMapLatLngInfo, WorldMapJoinLayerInfo%0Afrom apps.worldmap_connect.models import WorldMapLayerInfo%0A%0ADEFAULT_STALE_AGE = 3 * 60 * 60 # 3 hours, in seconds%0A%0Adef remove_stale_map_data(stale_age_in_seconds=DEFAULT_STALE_AGE):%0A %22%22%22%0A Remove old map data...%0A %22%22%22%0A current_time = datetime.now()%0A%0A for wm_info in WorldMapLatLngInfo.objects.all():%0A remove_if_stale(wm_info, stale_age_in_seconds, current_time)%0A%0A for wm_info in WorldMapLatLngInfo.objects.all():%0A remove_if_stale(wm_info, stale_age_in_seconds, current_time)%0A%0A for wm_info in WorldMapLayerInfo.objects.all():%0A remove_if_stale(wm_info, stale_age_in_seconds, current_time)%0A%0A%0Adef remove_if_stale(info_object, stale_age_in_seconds, current_time=None):%0A assert hasattr(info_object, 'modified'),%5C%0A 'The info_object must have %22modified%22 date'%0A%0A if not current_time:%0A current_time = datetime.now()%0A%0A mod_time = info_object.modified%0A if hasattr(mod_time, 'tzinfo'):%0A mod_time = mod_time.replace(tzinfo=None)%0A%0A # Is this object beyond it's time limit%0A time_diff = (current_time - mod_time).total_seconds()%0A if time_diff %3E stale_age_in_seconds:%0A # Yes! delete it%0A print 'Removing: ', info_object%0A info_object.delete()%0A%22%22%22%0Afrom apps.gis_tabular.utils_stale_data import *%0Aremove_stale_map_data()%0A%22%22%22%0A
|
|
cb56e0151b37a79e2ba95815555cde0633e167e7 | add client subscribe testing | samples/client_subscribe.py | samples/client_subscribe.py | Python | 0 | @@ -0,0 +1,700 @@
+import logging%0Afrom hbmqtt.client._client import MQTTClient%0Aimport asyncio%0A%0Alogger = logging.getLogger(__name__)%0A%0AC = MQTTClient()%0A%[email protected]%0Adef test_coro():%0A yield from C.connect(uri='mqtt://iot.eclipse.org:1883/', username=None, password=None)%0A yield from C.subscribe(%5B%0A %7B'filter': '$SYS/broker/uptime', 'qos': 0x00%7D,%0A %5D)%0A logger.info(%22Subscribed%22)%0A%0A yield from asyncio.sleep(60)%0A yield from C.disconnect()%0A%0A%0Aif __name__ == '__main__':%0A formatter = %22%5B%25(asctime)s%5D %7B%25(filename)s:%25(lineno)d%7D %25(levelname)s - %25(message)s%22%0A logging.basicConfig(level=logging.DEBUG, format=formatter)%0A asyncio.get_event_loop().run_until_complete(test_coro())
|
|
c422b5019c6e638bce40a7fecef6977aa5e63ce0 | add __init__.py | python/18-package/parent/__init__.py | python/18-package/parent/__init__.py | Python | 0.00212 | @@ -0,0 +1,170 @@
+#!/usr/bin/env python%0A#-*- coding=utf-8 -*-%0A%0Aif __name__ == %22__main__%22:%0A print %22Package parent running as main program%22%0Aelse:%0A print %22Package parent initializing%22%0A%0A
|
|
8d6a5c4092d4f092416fc39fc7faa8bb20e701c3 | Add a manage command to sync reservations from external hook .. hard coded first product only atm (cherry picked from commit 63a80b711e1be9a6047965b8d0061b676d8c50ed) | cartridge/shop/management/commands/syncreshooks.py | cartridge/shop/management/commands/syncreshooks.py | Python | 0 | @@ -0,0 +1,375 @@
+from django.core.management.base import BaseCommand%0Afrom django.core.management.base import CommandError%0Afrom mezzanine.conf import settings%0A%0Afrom cartridge.shop.models import *%0A%0Aclass Command(BaseCommand):%0A help = 'Sync reservations from external hook'%0A%0A def handle(self, *args, **options):%0A p = ReservableProduct.objects.all()%5B0%5D%0A p.update_from_hook()%0A%0A
|
|
7e71b21f655ec35bd5ebd79aeb5dbec6945a77a7 | Add purdue harvester | scrapi/harvesters/purdue.py | scrapi/harvesters/purdue.py | Python | 0.999533 | @@ -0,0 +1,569 @@
+'''%0AHarvester for the Purdue University Research Repository for the SHARE project%0A%0AExample API call: http://purr.purdue.edu/oaipmh?verb=ListRecords&metadataPrefix=oai_dc%0A'''%0Afrom __future__ import unicode_literals%0A%0Afrom scrapi.base import OAIHarvester%0A%0A%0Aclass PurdueHarvester(OAIHarvester):%0A short_name = 'purdue'%0A long_name = 'PURR - Purdue University Research Repository'%0A url = 'http://purr.purdue.edu'%0A%0A base_url = 'http://purr.purdue.edu/oaipmh'%0A property_list = %5B'date', 'relation', 'identifier', 'type', 'setSpec'%5D%0A timezone_granularity = True%0A
|
|
7ecfe7d20f8708a1dada5761cdc02905b0e370e5 | use correct separator | scripts/ci/wheel_factory.py | scripts/ci/wheel_factory.py | #!/usr/bin/env python
import requirements
import argparse
import glob
import os
parser = argparse.ArgumentParser()
parser.add_argument('file', help="requirements.txt", type=str)
parser.add_argument('wheeldir', help="wheeldir location", type=str)
args = parser.parse_args()
req_file = open(args.file, 'r')
for req in requirements.parse(req_file):
print "Checking " + args.wheeldir + os.path.pathsep + req.name + "*.whl"
if not glob.glob(args.wheeldir + os.path.pathsep + req.name + "*.whl"):
os.system("pip wheel --wheel-dir=" + args.wheeldir + " " + req.name + "".join(req.specs) + "".join(req.extras))
| Python | 0.000691 | @@ -383,36 +383,32 @@
eldir + os.path.
-path
sep + req.name +
@@ -461,20 +461,16 @@
os.path.
-path
sep + re
|
027a199924ee256170a2e369733a57fcc7483c88 | Add missing numeter namespace in poller | poller/numeter/__init__.py | poller/numeter/__init__.py | Python | 0.00005 | @@ -0,0 +1,56 @@
+__import__('pkg_resources').declare_namespace(__name__)%0A
|
|
2022245c9172037bf71be29d0da53f1c47f6aac9 | guess user number: python3 | guess_user_number/python3/guess_user_number.py | guess_user_number/python3/guess_user_number.py | Python | 0.999999 | @@ -0,0 +1,455 @@
+#!/usr/bin/python%0A%0Amin=1%0Amax=100%0A%0Aprint(%22Think of a number from %22+str(min)+%22 to %22+str(max)+%22. Then, tell the computer if its guess is correct (Y), lower than the number (L), or higher than the number (H).%22)%0A%0Afound=False%0A%0Awhile not found:%0A%09mid = int((max-min)/2+min)%0A%09response = input(str(mid)+%22? %3E%3E%3E %22)%0A%09response = response.upper()%0A%09if response == %22Y%22:%0A%09%09print(%22found it!!%22)%0A%09%09found=True%0A%09elif response == %22L%22:%0A%09%09min=mid%0A%09elif response == %22H%22:%0A%09%09max=mid%0A
|
|
7420f49f8e1508fa2017c629d8d11a16a9e28c4a | add abstract biobox class | biobox_cli/biobox.py | biobox_cli/biobox.py | Python | 0.000001 | @@ -0,0 +1,1061 @@
+from abc import ABCMeta, abstractmethod%0Aimport biobox_cli.container as ctn%0Aimport biobox_cli.util.misc as util%0Aimport tempfile as tmp%0A%0Aclass Biobox:%0A __metaclass__ = ABCMeta%0A%0A @abstractmethod%0A def prepare_volumes(opts):%0A pass%0A%0A @abstractmethod%0A def get_doc(self):%0A pass%0A%0A @abstractmethod%0A def after_run(self, host_dst_dir):%0A pass%0A%0A def run(self, argv):%0A opts = util.parse_docopt(self.get_doc(), argv, False)%0A task = opts%5B'--task'%5D%0A image = opts%5B'%3Cimage%3E'%5D%0A output = opts%5B'--output'%5D%0A host_dst_dir = tmp.mkdtemp()%0A volumes = self.prepare_volumes(opts, host_dst_dir)%0A ctn.exit_if_no_image_available(image)%0A ctnr = ctn.create(image, task, volumes)%0A ctn.run(ctnr)%0A self.after_run(output, host_dst_dir)%0A return ctnr%0A%0A def remove(self, container):%0A %22%22%22%0A Removes a container%0A Note this method is not tested due to limitations of circle ci%0A %22%22%22%0A ctn.remove(container)
|
|
4d1b006e5ba559715d55a88528cdfc0bed755182 | add import script for Weymouth | polling_stations/apps/data_collection/management/commands/import_weymouth.py | polling_stations/apps/data_collection/management/commands/import_weymouth.py | Python | 0 | @@ -0,0 +1,412 @@
+from data_collection.management.commands import BaseXpressDCCsvInconsistentPostcodesImporter%0A%0Aclass Command(BaseXpressDCCsvInconsistentPostcodesImporter):%0A council_id = 'E07000053'%0A addresses_name = 'parl.2017-06-08/Version 1/Democracy_Club__08June2017WPBC.TSV'%0A stations_name = 'parl.2017-06-08/Version 1/Democracy_Club__08June2017WPBC.TSV'%0A elections = %5B'parl.2017-06-08'%5D%0A csv_delimiter = '%5Ct'%0A
|
|
2ce80e667de438fca20de7b4ab6847751b683e33 | Add digikey command. | src/commands/digikey.py | src/commands/digikey.py | Python | 0.000001 | @@ -0,0 +1,685 @@
+#%0A# Copyright (c) 2013 Joshua Hughes %[email protected]%3E%0A#%0Aimport urllib%0Aimport webbrowser%0A%0Aimport qmk%0A%0Aclass DigikeyCommand(qmk.Command):%0A %22%22%22Look up a part on Digi-Key.%0A%0A A new tab will be opened in the default web browser that contains the%0A search results.%0A %22%22%22%0A def __init__(self):%0A self._name = 'digikey'%0A self._help = self.__doc__%0A self.__baseURL = 'http://www.digikey.com/product-search/en?KeyWords=%7B%7D'%0A%0A @qmk.Command.actionRequiresArgument%0A def action(self, arg):%0A webbrowser.open_new_tab(self.__baseURL.format(urllib.quote_plus(%0A ' '.join(arg.split()).encode('utf-8'))))%0A%0Adef commands(): return %5B DigikeyCommand() %5D%0A
|
|
8b4bbd23bf37fb946b664f5932e4903f802c6e0d | Add first pass at integration style tests | flake8/tests/test_integration.py | flake8/tests/test_integration.py | Python | 0 | @@ -0,0 +1,2378 @@
+from __future__ import with_statement%0A%0Aimport os%0Aimport unittest%0Atry:%0A from unittest import mock%0Aexcept ImportError:%0A import mock # %3C PY33%0A%0Afrom flake8 import engine%0A%0A%0Aclass IntegrationTestCase(unittest.TestCase):%0A %22%22%22Integration style tests to exercise different command line options.%22%22%22%0A%0A def this_file(self):%0A %22%22%22Return the real path of this file.%22%22%22%0A this_file = os.path.realpath(__file__)%0A if this_file.endswith(%22pyc%22):%0A this_file = this_file%5B:-1%5D%0A return this_file%0A%0A def check_files(self, arglist=%5B%5D, explicit_stdin=False, count=0):%0A %22%22%22Call check_files.%22%22%22%0A if explicit_stdin:%0A target_file = %22-%22%0A else:%0A target_file = self.this_file()%0A argv = %5B'flake8'%5D + arglist + %5Btarget_file%5D%0A with mock.patch(%22sys.argv%22, argv):%0A style_guide = engine.get_style_guide(parse_argv=True)%0A report = style_guide.check_files()%0A self.assertEqual(report.total_errors, count)%0A return style_guide, report%0A%0A def test_no_args(self):%0A # assert there are no reported errors%0A self.check_files()%0A%0A def _job_tester(self, jobs):%0A # mock stdout.flush so we can count the number of jobs created%0A with mock.patch('sys.stdout.flush') as mocked:%0A guide, report = self.check_files(arglist=%5B'--jobs=%25s' %25 jobs%5D)%0A self.assertEqual(guide.options.jobs, jobs)%0A self.assertEqual(mocked.call_count, jobs)%0A%0A def test_jobs(self):%0A self._job_tester(2)%0A self._job_tester(10)%0A%0A def test_stdin(self):%0A self.count = 0%0A%0A def fake_stdin():%0A self.count += 1%0A with open(self.this_file(), %22r%22) as f:%0A return f.read()%0A%0A with mock.patch(%22pep8.stdin_get_value%22, fake_stdin):%0A guide, report = self.check_files(arglist=%5B'--jobs=4'%5D,%0A explicit_stdin=True)%0A self.assertEqual(self.count, 1)%0A%0A def test_stdin_fail(self):%0A def fake_stdin():%0A return %22notathing%5Cn%22%0A with mock.patch(%22pep8.stdin_get_value%22, fake_stdin):%0A # only assert needed is in check_files%0A guide, report = self.check_files(arglist=%5B'--jobs=4'%5D,%0A explicit_stdin=True,%0A count=1)%0A
|
|
0d2adfcce21dd2efb5d781babec3e6b03464b6d5 | Add basic tests | tests/app/main/test_request_header.py | tests/app/main/test_request_header.py | Python | 0.000004 | @@ -0,0 +1,831 @@
+from tests.conftest import set_config_values%0A%0A%0Adef test_route_correct_secret_key(app_, client):%0A with set_config_values(app_, %7B%0A 'ROUTE_SECRET_KEY_1': 'key_1',%0A 'ROUTE_SECRET_KEY_2': '',%0A 'DEBUG': False,%0A %7D):%0A%0A response = client.get(%0A path='/_status',%0A headers=%5B%0A ('X-Custom-forwarder', 'key_1'),%0A %5D%0A )%0A assert response.status_code == 200%0A%0A%0Adef test_route_incorrect_secret_key(app_, client):%0A with set_config_values(app_, %7B%0A 'ROUTE_SECRET_KEY_1': 'key_1',%0A 'ROUTE_SECRET_KEY_2': '',%0A 'DEBUG': False,%0A %7D):%0A%0A response = client.get(%0A path='/_status',%0A headers=%5B%0A ('X-Custom-forwarder', 'wrong_key'),%0A %5D%0A )%0A assert response.status_code == 403%0A
|
|
77af87198d1116b77df431d9139b30f76103dd64 | Add migration for latitute and longitude of event | fellowms/migrations/0023_auto_20160617_1350.py | fellowms/migrations/0023_auto_20160617_1350.py | Python | 0.000001 | @@ -0,0 +1,608 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.5 on 2016-06-17 13:50%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('fellowms', '0022_event_report_url'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='event',%0A name='lat',%0A field=models.FloatField(blank=True, null=True),%0A ),%0A migrations.AddField(%0A model_name='event',%0A name='lon',%0A field=models.FloatField(blank=True, null=True),%0A ),%0A %5D%0A
|
|
fb07837db870a5fdea3a98aa1381793b1b20d2c0 | Create main.py | main.py | main.py | Python | 0.000001 | @@ -0,0 +1,2041 @@
+import webapp2%0Aimport jinja2%0Aimport os%0Aimport urllib%0A%0Afrom google.appengine.api import users%0Afrom google.appengine.ext import ndb%0A%0A%0AJINJA_ENVIRONMENT = jinja2.Environment(%0A loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),%0A extensions=%5B'jinja2.ext.autoescape'%5D,%0A autoescape=True)%0A%0A%0Adef user_key(id):%0A return ndb.Key('GroceryList',id)%0A%0A%0Aclass GroceryItem(ndb.Model):%0A name = ndb.StringProperty()%0A cost = ndb.FloatProperty()%0A quantity = ndb.IntegerProperty()%0A total = ndb.FloatProperty()%0A picture = ndb.BlobProperty()%0A time = ndb.DateTimeProperty(auto_now_add=True)%0A%0A%0Aclass MainHandler(webapp2.RequestHandler):%0A%0A def get(self):%0A user = users.get_current_user()%0A items_query = GroceryItem.query(%0A ancestor=user_key(users.get_current_user().user_id())).order(-GroceryItem.time)%0A items = items_query.fetch(10)%0A if user:%0A url = users.create_logout_url(self.request.uri)%0A url_linktext = 'Logout'%0A else:%0A url = users.create_login_url(self.request.uri)%0A url_linktext = 'Login'%0A template_values = %7B%0A 'user':users.get_current_user(),%0A 'items':items,%0A 'url':url,%0A 'url_linktext':url_linktext,%0A %7D%0A template = JINJA_ENVIRONMENT.get_template('index.html')%0A self.response.write(template.render(template_values))%0A%0A%0Aclass GroceryList(webapp2.RequestHandler):%0A%0A def post(self):%0A user = users.get_current_user();%0A item = GroceryItem(parent=user_key(user.user_id()))%0A item.name = self.request.get('name')%0A item.cost = self.request.get('cost')%0A item.quantity = self.request.get('quantity')%0A item.picture = self.request.get('img')%0A item.total = item.cost * item.quantity%0A item.put()%0A%0A query_params = %7B'user': user_key(user.user_id())%7D%0A self.redirect('/?' + urllib.urlencode(query_params))%0A%0A%0Aapp = webapp2.WSGIApplication(%5B%0A ('/', MainHandler)%0A ('/add', GroceryList)%0A%5D, debug=True)%0A
|
|
b920f5aeecf7843fcc699db4a70a9a0f124fa198 | Add unit test for protonate.py | tests/test_protonate.py | tests/test_protonate.py | Python | 0 | @@ -0,0 +1,372 @@
+import propka.atom%0Aimport propka.protonate%0A%0A%0Adef test_protonate_atom():%0A atom = propka.atom.Atom(%0A %22HETATM 4479 V VO4 A1578 -19.097 16.967 0.500 1.00 17.21 V %22%0A )%0A assert not atom.is_protonated%0A p = propka.protonate.Protonate()%0A p.protonate_atom(atom)%0A assert atom.is_protonated%0A assert atom.number_of_protons_to_add == 6%0A
|
|
f502b9bb7c0cddda05cd85cf60f88f0a801b43d1 | Add docstrings | flocker/common/script.py | flocker/common/script.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""Helpers for flocker shell commands."""
import sys
from twisted.internet.task import react
from twisted.python import usage
from zope.interface import Interface
from .. import __version__
def flocker_standard_options(cls):
"""
Add various standard command line options to flocker commands and
subcommands.
"""
original_init = cls.__init__
def __init__(self, *args, **kwargs):
"""
"""
self._sys_module = kwargs.pop('sys_module', sys)
self['verbosity'] = 0
original_init(self, *args, **kwargs)
cls.__init__ = __init__
def opt_version(self):
"""
Print the program's version and exit.
"""
self._sys_module.stdout.write(__version__.encode('utf-8') + b'\n')
raise SystemExit(0)
cls.opt_version = opt_version
def opt_verbose(self):
"""
Increase the verbosity.
"""
self['verbosity'] += 1
cls.opt_verbose = opt_verbose
cls.opt_v = opt_verbose
return cls
class ICommandLineScript(Interface):
"""
A script which can be run by ``FlockerScriptRunner``.
"""
def main(reactor, options):
"""
:param twisted.internet.reactor reactor: A Twisted reactor.
:param dict options: A dictionary of configuration options.
:return: A ``Deferred`` which fires when the script has completed.
"""
class FlockerScriptRunner(object):
"""
An API for running standard flocker scripts.
:ivar ICommandLineScript script: See ``script`` of ``__init__``.
"""
def __init__(self, script, options, sys_module=None):
"""
"""
self.script = script
self.options = options
if sys_module is None:
sys_module = sys
self.sys_module = sys_module
def _parseOptions(self, arguments):
"""
Parse the options defined in the script's options class.
L{UsageErrors} are caught and printed to I{stderr} and the script then
exits.
@param arguments: The command line arguments to be parsed.
@rtype: L{Options}
"""
try:
self.options.parseOptions(arguments)
except usage.UsageError as e:
self.sys_module.stderr.write(unicode(self.options).encode('utf-8'))
self.sys_module.stderr.write(
b'ERROR: ' + e.message.encode('utf-8') + b'\n')
raise SystemExit(1)
return self.options
def main(self):
"""
Parse arguments and run the script's main function via L{react}.
"""
options = self._parseOptions(self.sys_module.argv[1:])
return react(self.script.main, (options,))
__all__ = [
'flocker_standard_options',
'ICommandLineScript',
'FlockerScriptRunner',
]
| Python | 0.000005 | @@ -382,16 +382,97 @@
mands.%0A%0A
+ :param type cls: The %60class%60 to decorate.%0A :return: The decorated %60class%60.
%0A %22%22%22
@@ -551,32 +551,244 @@
s):%0A %22%22%22%0A
+ Set the default verbosity to %600%60 and then call the original%0A %60%60cls.__init__%60%60.%0A%0A :param sys_module: An optional %60%60sys%60%60 like fake module for use in%0A testing. Defaults to %60%60sys%60%60.%0A
%22%22%22%0A
@@ -1985,32 +1985,306 @@
e):%0A %22%22%22%0A
+ :param ICommandLineScript script: A script object with a %60%60main%60%60%0A method.%0A :param usage.Options options: An option parser object.%0A :param sys_module: An optional %60%60sys%60%60 like fake module for use in%0A testing. Defaults to %60%60sys%60%60.%0A
%22%22%22%0A
@@ -2564,18 +2564,18 @@
-L%7B
+%60%60
UsageErr
@@ -2576,18 +2576,19 @@
ageError
+%60%60
s
-%7D
are cau
@@ -2610,17 +2610,16 @@
to
-I%7B
+%60
stderr
-%7D
+%60
and
@@ -2663,15 +2663,20 @@
-@
+:
param
+list
argu
@@ -2735,26 +2735,53 @@
-@rtype: L%7BO
+:return: A %60%60dict%60%60 of configuration o
ptions
-%7D
+.
%0A
@@ -3235,16 +3235,17 @@
via
-L%7B
+%60%60
react
-%7D
+%60%60
.%0A
@@ -3325,23 +3325,16 @@
-return
react(se
|
addba07842f95e9b5bac3a97ddb4f81035bb2fc8 | Don't add args that return None names | ouimeaux/device/api/service.py | ouimeaux/device/api/service.py | import logging
from xml.etree import cElementTree as et
import requests
from .xsd import service as serviceParser
log = logging.getLogger(__name__)
REQUEST_TEMPLATE = """
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<s:Body>
<u:{action} xmlns:u="{service}">
{args}
</u:{action}>
</s:Body>
</s:Envelope>
"""
class Action(object):
def __init__(self, service, action_config):
self._action_config = action_config
self.name = action_config.get_name()
self.serviceType = service.serviceType
self.controlURL = service.controlURL
self.args = {}
self.headers = {
'Content-Type': 'text/xml',
'SOAPACTION': '"%s#%s"' % (self.serviceType, self.name)
}
arglist = action_config.get_argumentList()
if arglist is not None:
for arg in arglist.get_argument():
# TODO: Get type instead of setting 0
self.args[arg.get_name()] = 0
def __call__(self, **kwargs):
arglist = '\n'.join('<{0}>{1}</{0}>'.format(arg, value)
for arg, value in kwargs.iteritems())
body = REQUEST_TEMPLATE.format(
action=self.name,
service=self.serviceType,
args=arglist
)
response = requests.post(self.controlURL, body.strip(), headers=self.headers)
d = {}
for r in et.fromstring(response.content).getchildren()[0].getchildren()[0].getchildren():
d[r.tag] = r.text
return d
def __repr__(self):
return "<Action %s(%s)>" % (self.name, ", ".join(self.args))
class Service(object):
"""
Represents an instance of a service on a device.
"""
def __init__(self, service, base_url):
self._base_url = base_url.rstrip('/')
self._config = service
url = '%s/%s' % (base_url, service.get_SCPDURL().strip('/'))
xml = requests.get(url)
self.actions = {}
self._svc_config = serviceParser.parseString(xml.content).actionList
for action in self._svc_config.get_action():
act = Action(self, action)
name = action.get_name()
self.actions[name] = act
setattr(self, name, act)
@property
def hostname(self):
return self._base_url.split('/')[-1]
@property
def controlURL(self):
return '%s/%s' % (self._base_url,
self._config.get_controlURL().strip('/'))
@property
def serviceType(self):
return self._config.get_serviceType()
| Python | 0.999303 | @@ -978,24 +978,91 @@
argument():%0A
+ name = arg.get_name()%0A if name:%0A
@@ -1103,16 +1103,20 @@
tting 0%0A
+
|
2bf763e39e91ef989c121bba420e4ae09ea0a569 | Add Diagonal Difference HackerRank Problem | algorithms/diagonal_difference/kevin.py | algorithms/diagonal_difference/kevin.py | Python | 0.000006 | @@ -0,0 +1,393 @@
+#!/usr/bin/env python%0A%0A%0Adef get_matrix_row_from_input():%0A return %5Bint(index) for index in input().strip().split(' ')%5D%0A%0A%0An = int(input().strip())%0Aprimary_diag_sum = 0%0Asecondary_diag_sum = 0%0Afor row_count in range(n):%0A row = get_matrix_row_from_input()%0A primary_diag_sum += row%5Brow_count%5D%0A secondary_diag_sum += row%5B-1 - row_count%5D%0A%0Aprint(abs(primary_diag_sum - secondary_diag_sum))%0A
|
|
9b0b3c474e250193730308b555034d458697e01b | Fix dispatching of WeMo switch devices. | homeassistant/components/wemo.py | homeassistant/components/wemo.py | """
homeassistant.components.wemo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
WeMo device discovery.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/wemo/
"""
import logging
from homeassistant.components import discovery
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
REQUIREMENTS = ['pywemo==0.3.12']
DOMAIN = 'wemo'
DISCOVER_LIGHTS = 'wemo.light'
DISCOVER_MOTION = 'wemo.motion'
DISCOVER_SWITCHES = 'wemo.switch'
# mapping from Wemo model_name to service
WEMO_MODEL_DISPATCH = {
'Bridge': DISCOVER_LIGHTS,
'Insight': DISCOVER_SWITCHES,
'Maker': DISCOVER_SWITCHES,
'Motion': DISCOVER_MOTION,
'Switch': DISCOVER_SWITCHES,
}
WEMO_SERVICE_DISPATCH = {
DISCOVER_LIGHTS: 'light',
DISCOVER_MOTION: 'binary_sensor',
DISCOVER_SWITCHES: 'switch',
}
SUBSCRIPTION_REGISTRY = None
KNOWN_DEVICES = []
_LOGGER = logging.getLogger(__name__)
# pylint: disable=unused-argument, too-many-function-args
def setup(hass, config):
"""Common set up for WeMo devices."""
import pywemo
global SUBSCRIPTION_REGISTRY
SUBSCRIPTION_REGISTRY = pywemo.SubscriptionRegistry()
SUBSCRIPTION_REGISTRY.start()
def stop_wemo(event):
"""Shutdown Wemo subscriptions and subscription thread on exit."""
_LOGGER.info("Shutting down subscriptions.")
SUBSCRIPTION_REGISTRY.stop()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wemo)
def discovery_dispatch(service, discovery_info):
"""Dispatcher for WeMo discovery events."""
# name, model, location, mac
_, model_name, _, mac = discovery_info
# Only register a device once
if mac in KNOWN_DEVICES:
return
KNOWN_DEVICES.append(mac)
service = WEMO_MODEL_DISPATCH.get(model_name)
component = WEMO_SERVICE_DISPATCH.get(service)
if service is not None:
discovery.discover(hass, service, discovery_info,
component, config)
discovery.listen(hass, discovery.SERVICE_WEMO, discovery_dispatch)
_LOGGER.info("Scanning for WeMo devices.")
devices = [(device.host, device) for device in pywemo.discover_devices()]
# Add static devices from the config file
devices.extend((address, None) for address in config.get('static', []))
for address, device in devices:
port = pywemo.ouimeaux_device.probe_wemo(address)
if not port:
_LOGGER.warning('Unable to probe wemo at %s', address)
continue
_LOGGER.info('Adding wemo at %s:%i', address, port)
url = 'http://%s:%i/setup.xml' % (address, port)
if device is None:
device = pywemo.discovery.device_from_description(url, None)
discovery_info = (device.name, device.model_name, url, device.mac)
discovery.discover(hass, discovery.SERVICE_WEMO, discovery_info)
return True
| Python | 0 | @@ -685,21 +685,21 @@
,%0A 'S
-witch
+ocket
': DISC
|
edb28fffe19e2b0de3113b43aeb075119c9e5830 | Work in progress. Creating new data migration. | emgapi/migrations/0019_auto_20200110_1455.py | emgapi/migrations/0019_auto_20200110_1455.py | Python | 0 | @@ -0,0 +1,1710 @@
+# -*- coding: utf-8 -*-%0A# Generated by Django 1.11.24 on 2020-01-10 14:55%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Adef create_download_description(apps, schema_editor):%0A DownloadDescriptionLabel = apps.get_model(%22emgapi%22, %22DownloadDescriptionLabel%22)%0A downloads = (%0A (%22Phylum level taxonomies UNITE (TSV)%22, %22Phylum level taxonomies UNITE%22),%0A (%22Phylum level taxonomies ITSoneDB (TSV)%22, %22Phylum level taxonomies ITSoneDB%22),%0A (%22Taxonomic assignments UNITE (TSV)%22, %22Taxonomic assignments UNITE%22),%0A (%22Taxonomic assignments ITSoneDB (TSV)%22, %22Taxonomic assignments ITSoneDB%22),%0A )%0A _downloads = list()%0A for d in downloads:%0A _downloads.append(%0A DownloadDescriptionLabel(%0A description=d%5B0%5D,%0A description_label=d%5B1%5D%0A )%0A )%0A DownloadDescriptionLabel.objects.bulk_create(_downloads)%0A%0A%0Adef create_group_types(apps, schema_editor):%0A DownloadGroupType = apps.get_model(%22emgapi%22, %22DownloadGroupType%22)%0A group_types = (%0A %22Taxonomic analysis ITS%22,%0A %22Taxonomic analysis ITSoneDB%22,%0A %22Taxonomic analysis UNITE%22,%0A %22Pathways and Systems%22,%0A # TODO: Do we need sub groups for the function and pathways%0A )%0A _groups = list()%0A for group_type in group_types:%0A _groups.append(%0A DownloadGroupType(group_type=group_type)%0A )%0A DownloadGroupType.objects.bulk_create(_groups)%0A%0A%0Aclass Migration(migrations.Migration):%0A dependencies = %5B%0A ('emgapi', '0018_auto_20191105_1052'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(create_download_description),%0A migrations.RunPython(create_group_types)%0A %5D%0A
|
|
d41274ce2a54d37c35f23c8c78de196e57667b0a | add google translate plugin | plugins_examples/translate.py | plugins_examples/translate.py | Python | 0 | @@ -0,0 +1,1111 @@
+#!/usr/bin/env python%0Aimport sys%0Aimport re%0Afrom googletrans import Translator%0Atranslator = Translator()%0A%0Aline = sys.stdin.readline()%0Awhile line:%0A match = re.search('%5E:(%5B%5E%5Cs%5D+) PRIVMSG (#%5B%5E%5Cs%5D+) :(.+)', line)%0A if not match:%0A line = sys.stdin.readline()%0A continue%0A%0A who = match.group(1)%0A chan = match.group(2)%0A what = match.group(3).strip().strip('%5Cr%5Cn')%0A%0A def reply(text):%0A print(%22PRIVMSG %25s :%25s%22 %25 (chan, text))%0A sys.stdout.flush()%0A%0A if what%5B:10%5D == ':translate':%0A m2 = re.search('%5E:translate (.*)', what)%0A if not m2:%0A line = sys.stdin.readline()%0A continue%0A try:%0A reply(translator.translate(m2.group(1), dest='fr').text)%0A except:%0A reply('Oups!')%0A elif what%5B:4%5D == ':tr ':%0A m2 = re.search('%5E:tr (%5Cw+) (%5Cw+) (.+)', what)%0A if not m2:%0A line = sys.stdin.readline()%0A continue%0A try:%0A reply(translator.translate(m2.group(3), src=m2.group(1), dest=m2.group(2)).text)%0A except:%0A reply('Oups!')%0A line = sys.stdin.readline()%0A
|
|
b450734eea74f5f3536a44ed40c006c3da13656c | Add diff.py | diff.py | diff.py | Python | 0.000001 | @@ -0,0 +1,2020 @@
+# vim: set et ts=4 sw=4 fdm=marker%0A%22%22%22%0AMIT License%0A%0ACopyright (c) 2016 Jesse Hogan%0A%0APermission is hereby granted, free of charge, to any person obtaining a copy%0Aof this software and associated documentation files (the %22Software%22), to deal%0Ain the Software without restriction, including without limitation the rights%0Ato use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0Acopies of the Software, and to permit persons to whom the Software is%0Afurnished to do so, subject to the following conditions:%0A%0AThe above copyright notice and this permission notice shall be included in all%0Acopies or substantial portions of the Software.%0A%0ATHE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0AIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0AFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0AAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0ALIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0AOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE%0ASOFTWARE.%0A%22%22%22%0Afrom diff_match_patch import diff_match_patch%0Afrom entities import entity%0Afrom pdb import set_trace; B=set_trace%0A%0A# TODO Write test%0Aclass diff(entity):%0A def __init__(self, data1, data2):%0A self._data1 = data1%0A self._data2 = data2%0A self._ps = None%0A self._dmp = None%0A%0A @property%0A def _diff_match_patch(self):%0A if not self._dmp:%0A self._dmp = diff_match_patch()%0A return self._dmp;%0A%0A @property%0A def _patches(self):%0A if self._ps == None:%0A dmp = self._diff_match_patch%0A diffs = dmp.diff_main(self._data1, self._data2)%0A dmp.diff_cleanupSemantic(diffs)%0A self._ps = dmp.patch_make(diffs)%0A return self._ps%0A%0A def apply(self, data):%0A return patch_apply(self._patches, data)%5B0%5D%0A%0A def __str__(self):%0A dmp = self._diff_match_patch%0A return dmp.patch_toText(self._patches) %0A%0A
|
|
176af82121da5282842fd7e77809da9780ac57a5 | implement server pool. | rsocks/pool.py | rsocks/pool.py | Python | 0 | @@ -0,0 +1,895 @@
+from __future__ import unicode_literals%0A%0Aimport logging%0Aimport contextlib%0A%0Afrom .eventlib import GreenPool%0Afrom .utils import debug%0A%0A%0A__all__ = %5B'ServerPool'%5D%0A%0Alogger = logging.getLogger(__name__)%0Alogger.setLevel(logging.DEBUG if debug() else logging.INFO)%0Alogger.addHandler(logging.StreamHandler())%0A%0A%0Aclass ServerPool(object):%0A%0A def __init__(self):%0A self.pool = GreenPool()%0A self.servers = %7B%7D%0A%0A @contextlib.contextmanager%0A def new_server(self, name, server_class, *args, **kwargs):%0A server = server_class(*args, **kwargs)%0A yield server%0A self.servers%5Bname%5D = server%0A%0A def loop(self):%0A for name, server in self.servers.items():%0A logger.info('Prepared %22%25s%22' %25 name)%0A self.pool.spawn(server.loop)%0A try:%0A self.pool.waitall()%0A except (SystemExit, KeyboardInterrupt):%0A logger.info('Exit')%0A
|
|
416d2b0ffd617c8c6e58360fefe554ad7dc3057b | add example for discovering existing connections | examples/connections.py | examples/connections.py | Python | 0.000001 | @@ -0,0 +1,566 @@
+%0A%22%22%22%0APrint out a list of existing Telepathy connections.%0A%22%22%22%0A%0Aimport dbus.glib%0A%0Aimport telepathy%0A%0Aprefix = 'org.freedesktop.Telepathy.Connection.'%0A%0Aif __name__ == '__main__':%0A for conn in telepathy.client.Connection.get_connections():%0A conn_iface = conn%5Btelepathy.CONN_INTERFACE%5D%0A handle = conn_iface.GetSelfHandle()%0A print conn_iface.InspectHandles(%0A telepathy.CONNECTION_HANDLE_TYPE_CONTACT, %5Bhandle%5D)%5B0%5D%0A print ' Protocol:', conn_iface.GetProtocol()%0A print ' Name:', conn.service_name%5Blen(prefix):%5D%0A print%0A%0A
|
|
ff53f699ac371266791487f0b863531dd8f5236a | Add hug 'hello_world' using to be developed support for optional URLs | examples/hello_world.py | examples/hello_world.py | Python | 0.000009 | @@ -0,0 +1,68 @@
+import hug%0A%0A%[email protected]()%0Adef hello_world():%0A return %22Hello world%22%0A
|
|
397ab61df61d5acac46cf60ede38fa928fdacd7c | Create solution.py | data_structures/linked_list/problems/pos_num_to_linked_list/solution.py | data_structures/linked_list/problems/pos_num_to_linked_list/solution.py | Python | 0.000018 | @@ -0,0 +1,478 @@
+import LinkedList%0A%0A# Linked List Node inside the LinkedList module is declared as:%0A#%0A# class Node:%0A# def __init__(self, val, nxt=None):%0A# self.val = val%0A# self.nxt = nxt%0A#%0A%0A%0Adef ConvertPositiveNumToLinkedList(val: int) -%3E LinkedList.Node:%0A node = None%0A%0A while True:%0A dig = val %25 10%0A val //= 10%0A prev = LinkedList.Node(dig, node)%0A node = prev%0A %0A if val == 0:%0A break%0A%0A return node%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.