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
07a122374abb60140e05b09f49ef942bd14c05f6
add missed migration
measure_mate/migrations/0026_auto_20160531_0716.py
measure_mate/migrations/0026_auto_20160531_0716.py
Python
0
@@ -0,0 +1,696 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.5 on 2016-05-31 07:16%0Afrom __future__ import unicode_literals%0A%0Aimport django.core.validators%0Afrom django.db import migrations, models%0Aimport re%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('measure_mate', '0025_auto_20160516_0046'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterField(%0A model_name='tag',%0A name='name',%0A field=models.SlugField(unique=True, validators=%5Bdjango.core.validators.RegexValidator(re.compile(b'%5BA-Z%5D'), %22Enter a valid 'slug' consisting of lowercase letters, numbers, underscores or hyphens.%22, b'invalid', True)%5D, verbose_name=b'Tag Name'),%0A ),%0A %5D%0A
d3b4053c2ef39eda9246af2000bdf9460730b33b
convert json to git-versionable versions which current TinyDB user can live with.
prettifyjson.py
prettifyjson.py
Python
0
@@ -0,0 +1,279 @@ +#!/usr/bin/env python%0Afrom os import path%0Aimport sys%0A%0Aimport json%0A%0Aif len(sys.argv) %3E 1:%0A print(%22usage:%5Cn%5Ct%7B%7D %3C your_json_file %3E your_prettified_json_file%22.format(%0A path.basename(sys.argv%5B0%5D)))%0A sys.exit(1)%0A%0Ajson.dump(json.load(sys.stdin), sys.stdout, indent=2)%0A
caf0b00bc21208515d0ddded3cbb934735d45939
add migration to create new model fields
coupons/migrations/0004_auto_20151105_1456.py
coupons/migrations/0004_auto_20151105_1456.py
Python
0
@@ -0,0 +1,1564 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0Afrom django.conf import settings%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A migrations.swappable_dependency(settings.AUTH_USER_MODEL),%0A ('coupons', '0003_auto_20150416_0617'),%0A %5D%0A%0A operations = %5B%0A migrations.CreateModel(%0A name='CouponUser',%0A fields=%5B%0A ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')),%0A ('redeemed_at', models.DateTimeField(blank=True, verbose_name='Redeemed at', null=True)),%0A %5D,%0A ),%0A migrations.AddField(%0A model_name='coupon',%0A name='user_limit',%0A field=models.PositiveIntegerField(verbose_name='User limit', default=1),%0A ),%0A migrations.AlterField(%0A model_name='coupon',%0A name='type',%0A field=models.CharField(choices=%5B('monetary', 'Money based coupon'), ('percentage', 'Percentage discount'), ('virtual_currency', 'Virtual currency')%5D, verbose_name='Type', max_length=20),%0A ),%0A migrations.AddField(%0A model_name='couponuser',%0A name='coupon',%0A field=models.ForeignKey(related_name='users', to='coupons.Coupon'),%0A ),%0A migrations.AddField(%0A model_name='couponuser',%0A name='user',%0A field=models.ForeignKey(null=True, to=settings.AUTH_USER_MODEL, blank=True, verbose_name='User'),%0A ),%0A %5D%0A
b181f2a57d57caaa6e53e193e88002a15e284fd0
add the missing file. i are senior dvlpr
cryptography/hazmat/backends/openssl/utils.py
cryptography/hazmat/backends/openssl/utils.py
Python
0.000523
@@ -0,0 +1,1113 @@ +# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or%0A# implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Afrom __future__ import absolute_import, division, print_function%0A%0Aimport six%0A%0A%0Adef _truncate_digest(digest, order_bits):%0A digest_len = len(digest)%0A%0A if 8 * digest_len %3E order_bits:%0A digest_len = (order_bits + 7) // 8%0A digest = digest%5B:digest_len%5D%0A%0A if 8 * digest_len %3E order_bits:%0A rshift = 8 - (order_bits & 0x7)%0A assert rshift %3E 0 and rshift %3C 8%0A%0A mask = 0xFF %3E%3E rshift %3C%3C rshift%0A%0A # Set the bottom rshift bits to 0%0A digest = digest%5B:-1%5D + six.int2byte(six.indexbytes(digest, -1) & mask)%0A%0A return digest%0A
4a0e00574fc551dde74db1a817229eeb23c4e0a8
Create prueba.py
prueba.py
prueba.py
from flask import Flask from flask import request import os import xml.etree.ElementTree as ET from threading import Thread import email_lib app = Flask(__name__) xml = "" def send_email(xml): print "2" email_lib.prueba() print xml return None @app.route('/webhook', methods=['POST','GET']) def webhook(): print "webhook" global xml xml = "hola" t = Thread(target=send_email, args=(xml,)) t.start() print "acabando" #Jasper resend the notification unless it receives a status 200 confirming the reception return '',200 @app.route('/response', methods=['POST','GET']) def response(): print xml #Comprobar como comparto la variable. return "Acabamos de procesar su peticion, en breve recibira un email con los detalles" if __name__ == '__main__': port = int(os.getenv('PORT', 5000)) app.run(debug=True, port=port, host='0.0.0.0', threaded=True)
Python
0.000008
@@ -238,24 +238,90 @@ print xml%0A + email_lib.email_alert(customer_email,iccid, admin_details%5B1%5D)%0A return N
7e4fd6b92040788bda1760cb261730f627ca6a10
Add example from listing 7.6
ch7/profile_read.py
ch7/profile_read.py
Python
0
@@ -0,0 +1,3006 @@ +'''%0AListing 7.6: Profiling data transfer%0A'''%0A%0Aimport numpy as np%0Aimport pyopencl as cl%0Aimport pyopencl.array%0A%0Aimport utility%0Afrom time import sleep%0A%0ANUM_VECTORS = 8192%0ANUM_ITERATIONS = 2000%0A%0Akernel_src = '''%0A__kernel void profile_read(__global char16 *c, int num) %7B%0A%0A for(int i=0; i%3Cnum; i++) %7B%0A c%5Bi%5D = (char16)(5);%0A %7D%0A%7D%0A'''%0A%0A# Get device and context, create command queue and program%0Adev = utility.get_default_device()%0Acontext = cl.Context(devices=%5Bdev%5D, properties=None, dev_type=None, cache_dir=None)%0A%0A# Create a command queue with the profiling flag enabled%0Aqueue = cl.CommandQueue(context, dev, properties=cl.command_queue_properties.PROFILING_ENABLE)%0A%0A# Build program in the specified context using the kernel source code%0Aprog = cl.Program(context, kernel_src)%0Atry:%0A prog.build(options=%5B'-Werror'%5D, devices=%5Bdev%5D, cache_dir=None)%0Aexcept:%0A print('Build log:')%0A print(prog.get_build_info(dev, cl.program_build_info.LOG))%0A raise%0A%0A# Data%0Ac = np.empty(shape=(NUM_VECTORS,), dtype=cl.array.vec.char16)%0A%0A# Create output buffer%0Ac_buff = cl.Buffer(context, cl.mem_flags.WRITE_ONLY, size=c.nbytes)%0A%0A# Enqueue kernel (with argument specified directly)%0Aglobal_size = (1,)%0Alocal_size = None%0A%0A# Execute the kernel repeatedly using enqueue_read%0Aread_time = 0.0%0Afor i in range(NUM_ITERATIONS):%0A # __call__(queue, global_size, local_size, *args, global_offset=None, wait_for=None, g_times_l=False)%0A # Store kernel execution event (return value)%0A kernel_event = prog.profile_read(queue, global_size, local_size, c_buff, np.int32(NUM_VECTORS))%0A%0A # Enqueue command to copy from buffers to host memory%0A # Store data transfer event (return value)%0A prof_event = cl.enqueue_copy(queue, dest=c, src=c_buff, is_blocking=True)%0A%0A read_time += prof_event.profile.end - prof_event.profile.start%0A%0A%0A# Execute the kernel repeatedly using enqueue_map_buffer%0Amap_time = 0.0%0Afor i in range(NUM_ITERATIONS):%0A # __call__(queue, global_size, local_size, *args, global_offset=None, wait_for=None, g_times_l=False)%0A # Store kernel execution event (return value)%0A kernel_event = prog.profile_read(queue, global_size, local_size, c_buff, np.int32(NUM_VECTORS))%0A%0A # Enqueue command to map from buffer two to host memory%0A (result_array, prof_event) = cl.enqueue_map_buffer(queue,%0A buf=c_buff,%0A flags=cl.map_flags.READ,%0A offset=0,%0A shape=(NUM_VECTORS,),%0A dtype=cl.array.vec.char16)%0A%0A map_time += prof_event.profile.end - prof_event.profile.start%0A%0A # Release the mapping (is this necessary?)%0A result_array.base.release(queue)%0A%0A# Print averaged results%0Aprint('Average read time (ms): %7B%7D'.format(read_time / ( NUM_ITERATIONS * 1000)))%0Aprint('Average map time (ms): %7B%7D'.format(map_time / ( NUM_ITERATIONS * 1000)))
8ecac8170a3f9323f76aa9252a9d3b2f57f7660c
Include duration in analysis output
ceam/analysis.py
ceam/analysis.py
# ~/ceam/ceam/analysis.py import argparse import pandas as pd import numpy as np def confidence(seq): mean = np.mean(seq) std = np.std(seq) runs = len(seq) interval = (1.96*std)/np.sqrt(runs) return mean, mean-interval, mean+interval def difference_with_confidence(a, b): mean_diff = np.mean(a) - np.mean(b) interval = 1.96*np.sqrt(np.std(a)**2/len(a)+np.std(b)**2/len(b)) return mean_diff, int(mean_diff-interval), int(mean_diff+interval) def analyze_results(results): intervention = results[results.intervention == True] non_intervention = results[results.intervention == False] i_dalys = intervention.ylds + intervention.ylls ni_dalys = non_intervention.ylds + non_intervention.ylls print('Total runs', len(intervention)) print('DALYs (intervention)', confidence(i_dalys), 'DALYs (non-intervention)', confidence(ni_dalys)) print('DALYs averted', difference_with_confidence(ni_dalys,i_dalys)) print('Total Intervention Cost', confidence(intervention.intervention_cost)) print('Cost per DALY', confidence(intervention.intervention_cost.values/(ni_dalys.values-i_dalys.values))) print('IHD Count (intervention)',confidence(intervention.ihd_count), 'IHD Count (non-intervention)', confidence(non_intervention.ihd_count)) print('Stroke Count (intervention)',confidence(intervention.hemorrhagic_stroke_count), 'Stroke Count (non-intervention)', confidence(non_intervention.hemorrhagic_stroke_count)) print('Healthcare Access Events per year (intervention):', confidence((intervention.general_healthcare_access+intervention.followup_healthcare_access)/20)) print('Healthcare Access Events per year (non-non_intervention):', confidence((non_intervention.general_healthcare_access+non_intervention.followup_healthcare_access)/20)) def dump_results(results, path): results.to_csv(path) def load_results(paths): results = pd.DataFrame() for path in paths: results = results.append(pd.read_csv(path)) return results def main(): import sys analyze_results(load_results(sys.argv[1:])) if __name__ == '__main__': main() # End.
Python
0.000012
@@ -777,16 +777,68 @@ ntion))%0A + print('Mean duration', results.duration.mean())%0A prin
0ee4afce4ba81cff6d13152ab082157afc4718f1
Create pyspark.py
pyspark.py
pyspark.py
Python
0.000009
@@ -0,0 +1,232 @@ +from pyspark import SparkConf, SparkContext%0A%0Aconf = SparkConf().setMaster(%22local%22).setAppName(%22MinTemperatures%22)%0Asc = SparkContext(conf = conf)%0A%0Alines = sc.textFile(%22file:///Users/Spark/1800.csv%22)%0AparsedLines = lines.map(parseLine)%0A
af495c7a69611f2c1fa744dce000c49033eb2dd7
Add test for sys.intern().
tests/basics/sys_intern.py
tests/basics/sys_intern.py
Python
0
@@ -0,0 +1,407 @@ +# test sys.intern() function%0A%0Aimport sys%0Atry:%0A sys.intern%0Aexcept AttributeError:%0A print('SKIP')%0A raise SystemExit%0A%0As1 = %22long long long long long long%22%0As2 = %22long long long%22 + %22 long long long%22%0A%0Aprint(id(s1) == id(s2))%0A%0Ai1 = sys.intern(s1)%0Ai2 = sys.intern(s2)%0A%0Aprint(id(i1) == id(i2))%0A%0Ai2_ = sys.intern(i2)%0A%0Aprint(id(i2_) == id(i2))%0A%0Atry:%0A sys.intern(1)%0Aexcept TypeError:%0A print(%22TypeError%22)%0A
7323565bdc2a290e97617857da475e8f41d5a43f
Add tee plugin
plugins/tee.py
plugins/tee.py
Python
0
@@ -0,0 +1,262 @@ +class Plugin:%0A def on_command(self, bot, msg, stdin, stdout, reply):%0A text = stdin.read().strip()%0A%0A reply(text)%0A print(text, file=stdout)%0A%0A def on_help(self):%0A return %22Copy standard input to reply, and also to standard output.%22%0A
b8ea356af5121ffd612ccf708fe2372fbae3cc3d
add custom hasher for crypt_sha512
daiquiri/core/hashers.py
daiquiri/core/hashers.py
Python
0.000001
@@ -0,0 +1,1347 @@ +# inspired by https://djangosnippets.org/snippets/10572/%0A%0Afrom collections import OrderedDict%0Afrom django.contrib.auth.hashers import CryptPasswordHasher, mask_hash%0Afrom django.utils.encoding import force_str%0Afrom django.utils.crypto import get_random_string, constant_time_compare%0Afrom django.utils.translation import ugettext_noop as _%0A%0A%0Aclass CrypdSHA512PasswordHasher(CryptPasswordHasher):%0A%0A algorithm = 'crypt_sha512'%0A%0A def salt(self):%0A return '$6$' + get_random_string(16)%0A%0A def encode(self, password, salt):%0A crypt = self._load_library()%0A data = crypt.crypt(force_str(password), salt)%0A return %22%25s%25s%22 %25 (self.algorithm, data)%0A%0A def verify(self, password, encoded):%0A crypt = self._load_library()%0A algorithm, rest = encoded.split('$', 1)%0A salt, hash = rest.rsplit('$', 1)%0A salt = '$' + salt%0A assert algorithm == self.algorithm%0A return constant_time_compare('%25s$%25s' %25 (salt, hash), crypt.crypt(force_str(password), salt))%0A%0A def safe_summary(self, encoded):%0A algorithm, prefix, salt, hash = encoded.split('$')%0A assert algorithm == self.algorithm%0A return OrderedDict(%5B%0A (_('algorithm'), algorithm),%0A (_('prefix'), prefix),%0A (_('salt'), mask_hash(salt)),%0A (_('hash'), mask_hash(hash)),%0A %5D)%0A
ede8d4db9f0a8b3331b299019ec67c92261b2a56
Make sure we don't blow up if BROKER_URL is None
src/sentry/monitoring/queues.py
src/sentry/monitoring/queues.py
""" sentry.monitoring.queues ~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2016 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function from urlparse import urlparse from django.conf import settings from django.utils.functional import cached_property class RedisBackend(object): def __init__(self, broker_url): self.broker_url = broker_url @cached_property def client(self): from redis import StrictRedis return StrictRedis.from_url(self.broker_url) def bulk_get_sizes(self, queues): return [(queue, self.get_size(queue)) for queue in queues] def get_size(self, queue): return self.client.llen(queue) def purge_queue(self, queue): # This is slightly inaccurate since things could be queued between calling # LLEN and DEL, but it's close enough for this use case. size = self.get_size(queue) self.client.delete(queue) return size class AmqpBackend(object): def __init__(self, broker_url): dsn = urlparse(broker_url) self.conn_info = dict( host=dsn.hostname, port=dsn.port, userid=dsn.username, password=dsn.password, virtual_host=dsn.path[1:], ) def get_conn(self): from librabbitmq import Connection return Connection(**self.conn_info) def _get_size_from_channel(self, channel, queue): # In AMQP, the way to do this is to attempt to create a queue passively. # which is basically checking for it's existence (passive=True), this also # returns back the queue size. try: _, size, _ = channel.queue_declare(queue, passive=True) except Exception: return 0 return size def bulk_get_sizes(self, queues): sizes = [] with self.get_conn() as conn: with conn.channel() as channel: for queue in queues: sizes.append((queue, self._get_size_from_channel(channel, queue))) print(sizes) return sizes def get_size(self, queue): with self.get_conn() as conn: with conn.channel() as channel: return self._get_size_from_channel(channel, queue) def purge_queue(self, queue): with self.get_conn() as conn: with conn.channel() as channel: return channel.queue_purge(queue) def get_backend_for_broker(broker_url): return backends[urlparse(broker_url).scheme](broker_url) def get_queue_by_name(name): "Lookup a celery Queue object by it's name" for queue in settings.CELERY_QUEUES: if queue.name == name: return queue backends = { 'redis': RedisBackend, 'amqp': AmqpBackend, 'librabbitmq': AmqpBackend, } try: backend = get_backend_for_broker(settings.BROKER_URL) except KeyError: backend = None
Python
0.999414
@@ -2559,24 +2559,74 @@ roker_url):%0A + if broker_url is None:%0A raise KeyError%0A return b
042d0d899896342e9f2e7b083f8543e8077bf19a
Add tests.py to app skeleton.
lib/rapidsms/skeleton/app/tests.py
lib/rapidsms/skeleton/app/tests.py
Python
0
@@ -0,0 +1,543 @@ +from rapidsms.tests.scripted import TestScript%0Afrom app import App%0A%0Aclass TestApp (TestScript):%0A apps = (App,)%0A%0A # define your test scripts here.%0A # e.g.:%0A #%0A # testRegister = %22%22%22%0A # 8005551212 %3E register as someuser%0A # 8005551212 %3C Registered new user 'someuser' for 8005551212!%0A # 8005551212 %3E tell anotheruser what's up??%0A # 8005550000 %3C someuser said %22what's up??%22%0A # %22%22%22%0A #%0A # You can also do normal unittest.TestCase methods:%0A #%0A # def testMyModel (self):%0A # self.assertEquals(...)%0A
27a7079f9edf01abce7912eb52c5091279bc85a1
ADD | 添加pygal path的变量设定源码
src/lib/PygalPath.py
src/lib/PygalPath.py
Python
0
@@ -0,0 +1,683 @@ +#-*- coding:UTF-8 -*-%0Aimport socket%0Aimport os%0A%0A__all__ = %5B'PYGAL_TOOLTIPS_PATH', 'SVG_JQUERY_PATH'%5D%0A%0ASERVER_WUHAN = '192.168.60.60'%0ASERVER_WUHAN_PRE = '192.168.6'%0ASERVER_BEIJING = '192.168.50.193'%0ASERVER_BEIJING_PRE = '192.168.5'%0ASERVER = '10.1.145.70'%0A%0A#%E6%A0%B9%E6%8D%AE%E6%9C%AC%E6%9C%BAIP%E8%8E%B7%E5%8F%96pygal%E6%A8%A1%E5%9D%97%E7%94%9F%E6%88%90svg%E6%96%87%E4%BB%B6%E6%89%80%E9%9C%80%E7%9A%84js%E6%96%87%E4%BB%B6%E8%B7%AF%E5%BE%84%0Asname=socket.gethostname()%0AipList = socket.gethostbyname_ex(sname)%5B2%5D%0Afor ip in ipList:%0A if SERVER_BEIJING_PRE in ip:%0A path = SERVER_BEIJING%0A break%0A elif SERVER_WUHAN_PRE in ip:%0A path = SERVER_WUHAN%0A break%0A else:%0A path = SERVER%0A break%0A%0APYGAL_TOOLTIPS_PATH = 'http://%25s/pygal-tooltips.js' %25 path%0ASVG_JQUERY_PATH = 'http://%25s/svg.jquery.js' %25 path
a3db0306133bc3da1cc00d3c745396539a152839
Add release script
release.py
release.py
Python
0.000001
@@ -0,0 +1,2092 @@ +#!/usr/bin/env python%0A%0Afrom collections import OrderedDict%0Afrom itertools import zip_longest%0Aimport json%0Aimport os%0Aimport re%0Afrom subprocess import check_output, CalledProcessError%0Aimport sys%0Afrom zipfile import ZipFile%0A%0A%0Adef sh(command, v=False):%0A if v:%0A print(command)%0A return check_output(command, text=True).strip()%0A%0A%0Adef parse_version(v):%0A return %5Bint(s) for s in v.split(%22.%22)%5D%0A%0A%0Adef dereference(link):%0A try:%0A return sh(f%22git rev-parse --verify -q %7Blink%7D%5E0%22)%0A except CalledProcessError:%0A return %22%22%0A%0A%0Aversion_string = sys.argv%5B1%5D%0Aprefixed_version = f%22v%7Bversion_string%7D%22%0Aversion = parse_version(version_string)%0Aos.chdir(os.path.dirname(os.path.realpath(__file__)))%0A%0Aassert not sh(%22git status --porcelain%22)%0Aassert sh(%22git branch%22) == %22* master%22%0A%0Awith open(%22manifest.json%22) as f:%0A manifest = json.load(f, object_pairs_hook=OrderedDict)%0Amanifest_version = parse_version(manifest%5B%22version%22%5D)%0Aif version != manifest_version:%0A delta = list(%0A vs%5B0%5D - vs%5B1%5D%0A for vs in zip_longest(version, manifest_version, fillvalue=0)%0A )%0A increment = delta.index(1)%0A assert all(i == 0 for i in delta%5B0:increment%5D)%0A assert all(i %3C= 0 for i in delta%5Bincrement + 1 :%5D)%0A manifest%5B%22version%22%5D = version_string%0A with open(%22manifest.json%22, %22w%22, newline=%22%5Cn%22) as f:%0A json.dump(manifest, f, indent=2)%0A print(%22%22, file=f)%0A sh(f%22git commit -a -m %7Bprefixed_version%7D%22, v=True)%0A%0Atag_commit = dereference(prefixed_version)%0Aif tag_commit:%0A assert tag_commit == dereference(%22HEAD%22)%0Aelse:%0A sh(f%22git tag %7Bprefixed_version%7D -m %7Bprefixed_version%7D%22, v=True)%0A%0Ash(%22git merge-base --is-ancestor origin/master master%22)%0A%0Aif dereference(%22master%22) != dereference(%22origin/master%22):%0A sh(%22git push --follow-tags%22, v=True)%0A%0Afiles = %5B%22manifest.json%22, %22config.js%22%5D%0Afor file in sh(%22git ls-files%22).splitlines():%0A m = lambda p: re.search(p, file)%0A if m(r%22%5C.(html%7Cjs)$%22) and not m(r%22%5Cbtest%5Cb%22):%0A files.append(file)%0A%0Awith ZipFile(%22ergometer.zip%22, %22w%22) as zip:%0A for file in files:%0A print(f%22zipping %7Bfile%7D%22)%0A zip.write(file)%0A
9ad9808b9bf7c202bc6dbbe8abd74e1c642982ae
structure migration
structure/migrations/0002_structure_refined.py
structure/migrations/0002_structure_refined.py
Python
0.000002
@@ -0,0 +1,445 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.11 on 2017-09-20 07:35%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations, models%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('structure', '0001_initial'),%0A %5D%0A%0A operations = %5B%0A migrations.AddField(%0A model_name='structure',%0A name='refined',%0A field=models.BooleanField(default=False),%0A ),%0A %5D%0A
ca1cb845f312ba295718084fa6c8a0d4e68d49e3
fix boolean parameter in config file
core/config.py
core/config.py
import argparse import appdirs import logging import os import configparser def defaultBackendRpcPort(config): if config.TESTNET: return 14000 else: return 4000 def defaultBackendRpc(config): protocol = 'https' if config.BACKEND_RPC_SSL else 'http' return '{}://{}:{}@{}:{}'.format(protocol, config.BACKEND_RPC_USER, config.BACKEND_RPC_PASSWORD, config.BACKEND_RPC_CONNECT, config.BACKEND_RPC_PORT) ARGS = [ {'name': 'data-dir', 'params': {'help': 'the directory in which to keep the config file and log file, by default'}}, {'name': 'config-file', 'params': {'help': 'the location of the configuration file'}}, {'name': 'testnet', 'params': {'action': 'store_true', 'help': 'use BTC testnet addresses and block numbers'}}, {'name': 'backend-rpc-connect', 'params': {'help': 'the hostname or IP of the backend bitcoind JSON-RPC server'}, 'default': 'localhost'}, {'name': 'backend-rpc-port', 'params': {'type': int, 'help': 'the backend JSON-RPC port to connect to'}, 'default': defaultBackendRpcPort}, {'name': 'backend-rpc-user', 'params': {'help': 'the username used to communicate with backend over JSON-RPC'}, 'default': 'rpc'}, {'name': 'backend-rpc-password', 'params': {'help': 'the password used to communicate with backend over JSON-RPC'}}, {'name': 'backend-rpc-ssl', 'params': {'action': 'store_true', 'help': 'use SSL to connect to backend (default: false)'}}, {'name': 'backend-rpc-ssl-verify', 'params': {'action': 'store_true', 'help':'verify SSL certificate of backend; disallow use of self‐signed certificates (default: false)'}}, {'name': 'backend-rpc', 'params': {'help': 'the complete RPC url used to communicate with backend over JSON-RPC'}, 'default': defaultBackendRpc}, {'name': 'plugins', 'params': {'action': 'append', 'help': 'active plugins'}, 'default': ['send', 'test']}, ] class Config: def __init__(self): # get args parser = argparse.ArgumentParser(prog="Conterpartyd GUI", description='the GUI for Counterpartyd') for arg in ARGS: parser.add_argument('--{}'.format(arg['name']), **arg['params']) self.args = vars(parser.parse_args()) # Data directory if self.args['data_dir']: dataDir = self.args.pop('data_dir') else: dataDir = appdirs.user_config_dir(appauthor='Counterparty', appname='counterpartygui', roaming=True) if not os.path.isdir(dataDir): os.mkdir(dataDir) # Configuration file if self.args['config_file']: configPath = self.args.pop('config_file') else: configPath = os.path.join(dataDir, 'counterpartygui.conf') configFile = configparser.ConfigParser() configFile.read(configPath) hasConfig = 'Default' in configFile # if `key` not in config file, return the default value evenually defined in ARGS. def getDefaultValue(key): if hasConfig and key in configFile['Default'] and configFile['Default'][key]: return configFile['Default'][key] else: for arg in ARGS: if arg['name'] == key and 'default' in arg: if callable(arg['default']): return arg['default'](self) else: return arg['default'] # Todo: `required` field and exception return None # set variables self.DATA_DIR = dataDir for arg in ARGS: argName = arg['name'].replace('-', '_') if self.args[argName] is None: self.args[argName] = getDefaultValue(arg['name']) setattr(self, argName.upper(), self.args[argName])
Python
0.000002
@@ -68,16 +68,27 @@ igparser +%0Aimport sys %0A%0Adef de @@ -3657,16 +3657,151 @@ is None + or (isinstance(self.args%5BargName%5D, bool) and '--%7B%7D'.format(arg%5B'name'%5D) not in sys.argv and '-%7B%7D'.format(arg%5B'name'%5D) not in sys.argv) :%0A
be01980afe4b1dbd5a1d5b07651cd7a54c771d01
Add unit tests for disk module
tests/modules/test_disk.py
tests/modules/test_disk.py
Python
0
@@ -0,0 +1,1579 @@ +# pylint: disable=C0103,C0111%0A%0Aimport mock%0Aimport unittest%0A%0Aimport tests.mocks as mocks%0A%0Afrom bumblebee.input import LEFT_MOUSE%0Afrom bumblebee.modules.disk import Module%0A%0Aclass MockVFS(object):%0A def __init__(self, perc):%0A self.f_blocks = 1024*1024%0A self.f_frsize = 1%0A self.f_bavail = self.f_blocks - self.f_blocks*(perc/100.0)%0A%0Aclass TestDiskModule(unittest.TestCase):%0A def setUp(self):%0A mocks.setup_test(self, Module)%0A self._os = mock.patch(%22bumblebee.modules.disk.os%22)%0A self.os = self._os.start()%0A self.config.set(%22disk.path%22, %22somepath%22)%0A%0A def tearDown(self):%0A self._os.stop()%0A mocks.teardown_test(self)%0A%0A def test_leftclick(self):%0A module = Module(engine=self.engine, config=%7B%22config%22:self.config%7D)%0A mocks.mouseEvent(stdin=self.stdin, button=LEFT_MOUSE, inp=self.input, module=module)%0A self.popen.assert_call(%22nautilus %7B%7D%22.format(self.module.parameter(%22path%22)))%0A%0A def test_warning(self):%0A self.config.set(%22disk.critical%22, %2280%22)%0A self.config.set(%22disk.warning%22, %2270%22)%0A self.os.statvfs.return_value = MockVFS(75.0)%0A self.module.update_all()%0A self.assertTrue(%22warning%22 in self.module.state(self.anyWidget))%0A%0A def test_critical(self):%0A self.config.set(%22disk.critical%22, %2280%22)%0A self.config.set(%22disk.warning%22, %2270%22)%0A self.os.statvfs.return_value = MockVFS(85.0)%0A self.module.update_all()%0A self.assertTrue(%22critical%22 in self.module.state(self.anyWidget))%0A%0A# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4%0A
da52f7c8c9280fe644a01a324eaad5512870dccb
add models.py
core/models.py
core/models.py
Python
0.000001
@@ -0,0 +1,2426 @@ +#!/usr/bin/env python%0A# coding = utf-8%0A%0A%22%22%22%0Acore.models%0A%22%22%22%0A%0A__author__ = 'Rnd495'%0A%0Aimport datetime%0A%0Aimport hashlib%0Afrom sqlalchemy import create_engine%0Afrom sqlalchemy import Column, Integer, Float, String, DateTime, Text, Index%0Afrom sqlalchemy.ext.declarative import declarative_base%0Afrom sqlalchemy.orm import sessionmaker%0A%0Afrom configs import Configs%0A%0Aconfigs = Configs.instance()%0ABase = declarative_base()%0A%0A%0Aclass User(Base):%0A __tablename__ = 'T_User'%0A%0A id = Column(Integer, primary_key=True, autoincrement=True)%0A name = Column(String(length=64), nullable=False, unique=True, index=Index('User_index_name'))%0A pwd = Column(String(length=128), nullable=False)%0A role_id = Column(Integer, nullable=False, index=Index('User_index_role_id'))%0A register_time = Column(DateTime, nullable=False)%0A header_url = Column(String(length=256), nullable=True)%0A%0A def __init__(self, name, pwd,%0A role_id=0,%0A header_url=None):%0A self.name = name%0A self.pwd = User.password_hash(pwd)%0A self.register_time = datetime.datetime.now()%0A self.role_id = role_id%0A self.header_url = header_url%0A%0A def __repr__(self):%0A return %22%3C%25s%5B%25s%5D: %25s%3E%22 %25 (type(self).__name__, self.id, self.name)%0A%0A def get_is_same_password(self, password):%0A return User.password_hash(password) == self.pwd%0A%0A def set_password(self, password):%0A self.pwd = hashlib.sha256(self.name + password)%0A%0A%0Aclass Role(Base):%0A __tablename__ = 'T_Role'%0A%0A id = Column(Integer, primary_key=True, autoincrement=True)%0A name = Column(String(length=64), nullable=False)%0A%0A def __init__(self, name, id=None):%0A self.name = name%0A if id is not None:%0A self.id = id%0A%0A def __repr__(self):%0A return %22%3C%25s%5B%25s%5D: %25s%3E%22 %25 (type(self).__name__, self.id, self.name)%0A%0A%0A_engine = None%0A_session_maker = None%0A_session = None%0A%0A%0Adef get_engine():%0A global _engine%0A if not _engine:%0A _engine = create_engine(configs.database_url, echo=False)%0A Base.metadata.create_all(_engine)%0A return _engine%0A%0A%0Adef get_session_maker():%0A global _session_maker%0A if not _session_maker:%0A _session_maker = sessionmaker(bind=get_engine())%0A return _session_maker%0A%0A%0Adef get_global_session():%0A global _session%0A if not _session:%0A _session = get_session_maker()()%0A return _session%0A%0A%0Adef get_new_session():%0A return get_session_maker()()%0A
2b3d9a7278220af765934cccf83bb1d470d6bfab
#tf-data-service Fix a typo.
tensorflow/python/data/experimental/kernel_tests/service/coordinated_read_ft_test.py
tensorflow/python/data/experimental/kernel_tests/service/coordinated_read_ft_test.py
# Copyright 2021 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Fault tolerance testst for tf.data service coordinated reads.""" from absl.testing import parameterized from tensorflow.python.data.experimental.kernel_tests.service import test_base as data_service_test_base from tensorflow.python.data.experimental.ops import data_service_ops from tensorflow.python.data.kernel_tests import test_base from tensorflow.python.framework import combinations from tensorflow.python.platform import test class CoordinatedReadFTTest(data_service_test_base.TestBase, parameterized.TestCase): @combinations.generate( combinations.times(test_base.eager_only_combinations(), combinations.combine(workers_to_add=[1, 3, 10]))) def testAddWorkers(self, workers_to_add): starting_workers = 3 cluster = data_service_test_base.TestCluster(num_workers=starting_workers) num_consumers = 7 ds = self.make_coordinated_read_dataset(cluster, num_consumers) get_next = self.getNext(ds, requires_initialization=True) results = [] zeros_seen = 0 for _ in range(25): results.append(self.evaluate(get_next())) if results[-1] == 0: zeros_seen += 1 for _ in range(workers_to_add): cluster.add_worker() # Read until all new workers have joined. while zeros_seen < starting_workers + workers_to_add: results.append(self.evaluate(get_next())) if results[-1] == 0: zeros_seen += 1 # Read some more. for _ in range(25): results.append(self.evaluate(get_next())) self.checkCoordinatedReadGroups(results, num_consumers) cluster.stop_workers() @combinations.generate(test_base.eager_only_combinations()) def testRestartWorker(self): num_workers = 3 # Set a shutdown quiet period to prevent workers from shutting down partway # through a round. cluster = data_service_test_base.TestCluster( num_workers, worker_shutdown_quiet_period_ms=2000) num_consumers = 5 ds = self.make_coordinated_read_dataset(cluster, num_consumers) get_next = self.getNext(ds, requires_initialization=True) results = [] self.read(get_next, results, 20) cluster.workers[1].stop() # Check that we can continue to read even with a worker stopped. self.read(get_next, results, 20) cluster.workers[1].restart() # Read until we get results from the restarted worker, then read some more. while results[-1] != 0: results.append(self.evaluate(get_next())) self.read(get_next, results, 20) self.checkCoordinatedReadGroups(results, num_consumers) cluster.stop_workers() @combinations.generate( combinations.times( test_base.eager_only_combinations(), combinations.combine(sharding_policy=[ data_service_ops.ShardingPolicy.OFF, data_service_ops.ShardingPolicy.DYNAMIC ]))) def testMultiStartStop(self, sharding_policy): num_workers = 3 # Set a shutdown quiet period to prevent workers from shutting down partway # through a round. cluster = data_service_test_base.TestCluster( num_workers, worker_shutdown_quiet_period_ms=2000) num_consumers = 5 ds = self.make_coordinated_read_dataset(cluster, num_consumers, sharding_policy) get_next = self.getNext(ds, requires_initialization=True) results = [] self.read(get_next, results, 20) for i in range(num_workers): cluster.workers[i].stop() self.read(get_next, results, 20) cluster.workers[i].restart() self.read(get_next, results, 20) cluster.add_worker() cluster.restart_dispatcher() for i in range(num_workers): cluster.workers[i].stop() self.read(get_next, results, 20) self.checkCoordinatedReadGroups(results, num_consumers) cluster.stop_workers() if __name__ == "__main__": test.main()
Python
0.999999
@@ -706,17 +706,16 @@ ce tests -t for tf.
4bf1a14f6b6d3b30f30732bb45f4e8a501dfcbf6
test github backup
tests/pkcli/github_test.py
tests/pkcli/github_test.py
Python
0.000003
@@ -0,0 +1,633 @@ +# -*- coding: utf-8 -*-%0Au%22%22%22test github%0A%0A:copyright: Copyright (c) 2019 Bivio Software, Inc. All Rights Reserved.%0A:license: http://www.apache.org/licenses/LICENSE-2.0.html%0A%22%22%22%0Afrom __future__ import absolute_import, division, print_function%0Aimport pytest%0A%0Adef test_backup():%0A from pykern import pkconfig%0A%0A pkconfig.reset_state_for_testing(%7B%0A 'PYKERN_PKCLI_GITHUB_TEST_MODE': '1',%0A 'PYKERN_PKCLI_GITHUB_API_PAUSE_SECONDS': '0',%0A %7D)%0A from pykern.pkcli import github%0A from pykern import pkunit%0A from pykern import pkio%0A%0A with pkunit.save_chdir_work():%0A github.backup()%0A github.backup()%0A
8fdaeea43e31a1c429703cd4f441a748bcfa8197
Create create_mask.py
create_mask.py
create_mask.py
Python
0.000017
@@ -0,0 +1,1380 @@ +%0Afrom __future__ import print_function%0A%0Aimport argparse%0Afrom PIL import ImageFont, ImageDraw, Image%0A%0A%0Adef create_mask(text, font_type, font_size=84):%0A '''%0A Creates an image with the given text in it.%0A '''%0A # initialize fond with given size%0A font = ImageFont.truetype(font_type, font_size)%0A dx, dy = font.getsize(text)%0A%0A # draw the text to the image%0A mask = Image.new('RGB', (dx, max(dy, font_size)))%0A draw = ImageDraw.Draw(mask)%0A draw.text((0,-int(0.15*font_size)), text, font=font) %0A %0A return mask%0A%0A%0Aif __name__ == '__main__':%0A parser = argparse.ArgumentParser(description='Create a mask for char repeat')%0A parser.add_argument('text', help='the text to print on the image')%0A parser.add_argument('font', help='select a font (e.g. SourceCodePro-Black.ttf)')%0A parser.add_argument('-s', dest='font_size', default=84, type=int,%0A help='size of the font')%0A parser.add_argument('-p', action='store_true', dest='plot', help='show image')%0A param = parser.parse_args()%0A %0A mask = create_mask(param.text, param.font, param.font_size)%0A mask.save('mask_%25s.png' %25 param.text)%0A%0A if param.plot:%0A dx, dy = mask.size%0A import matplotlib.pyplot as plt%0A plt.figure()%0A plt.imshow(mask)%0A plt.title('text: %25s (mask size = %25i x %25i)' %25 (param.text, dx, dy))%0A plt.show()%0A %0A%0A
79e55030736572608841bbdd3a6022fc2420be45
implement recursive permutation generation algorithm with switch
switch.py
switch.py
Python
0.000002
@@ -0,0 +1,943 @@ +###%0A# A permutation generation algorithm.%0A# this algorithm is implemented by switching neighboring number.%0A#%0A# Under here is two implementation recursive and iterative%0A###%0A%0A%0Adef recursive_PGA_with_switch(width):%0A '''%0A Recursive permutation generation algorithm with switch%0A '''%0A # condition%0A assert width %3E 0%0A assert type(width) is int%0A%0A # boundary%0A if width == 1:%0A yield '1'%0A return%0A%0A # recursion%0A left = True # direction to move%0A for sub_permutation in recursive_PGA_with_switch(width-1):%0A # positions to insert new number%0A positions = reversed(range(width)) if left else range(width)%0A left = not left%0A%0A for i in positions:%0A perm = %5Bsub_permutation%5B:i%5D, str(width), sub_permutation%5Bi:%5D%5D%0A #print(perm)%0A yield(''.join(perm))%0A%0A%0Aif __name__ == '__main__':%0A for permutation in recursive_PGA_with_switch(3):%0A print(permutation)%0A
dfab68c27b3f25f448c0a2a6d0cee347bae2b08f
Add tests for canonicalize
tests/test_canonicalize.py
tests/test_canonicalize.py
Python
0
@@ -0,0 +1,360 @@ +from intervals import Interval, canonicalize%0A%0A%0Adef test_canonicalize():%0A assert canonicalize(Interval(%5B1, 4%5D)).normalized == '%5B1, 5)'%0A assert canonicalize(%0A Interval((1, 7)), lower_inc=True, upper_inc=True%0A ).normalized == '%5B2, 6%5D'%0A assert canonicalize(%0A Interval(%5B1, 7%5D), lower_inc=False, upper_inc=True%0A ).normalized == '(0, 7%5D'%0A
76468926c1efe4d18477a70d767f91d4c6e38768
Add test for dotted circles in sample text
tests/test_dottedcircle.py
tests/test_dottedcircle.py
Python
0
@@ -0,0 +1,880 @@ +import uharfbuzz as hb%0Aimport gflanguages%0Aimport pytest%0A%0Alangs = gflanguages.LoadLanguages()%0A%0A%[email protected]%0Adef hb_font():%0A # Persuade Harfbuzz we have a font that supports%0A # every codepoint.%0A face = hb.Face(b%22%22)%0A font = hb.Font(face)%0A funcs = hb.FontFuncs.create()%0A funcs.set_nominal_glyph_func((lambda font,cp,data: cp), None)%0A font.funcs = funcs%0A return font%0A%0A%[email protected](%22lang%22, langs.keys())%0Adef test_dotted_circle(lang, hb_font):%0A item = langs%5Blang%5D%0A samples = %5Bx for (_,x) in item.sample_text.ListFields()%5D%0A for sample in sorted(samples, key=lambda x:len(x)):%0A buf = hb.Buffer()%0A buf.add_str(sample)%0A buf.guess_segment_properties()%0A hb.shape(hb_font, buf)%0A ok = not any(info.codepoint == 0x25CC for info in buf.glyph_infos)%0A assert ok, f%22Dotted circle found in %7Bsample%7D (%7Blang%7D)%22%0A
7c69ec08967dc38463cfc5e1323d69fd5f261333
Create config.py
config.py
config.py
Python
0
@@ -0,0 +1,738 @@ +#!/usr/bin/env python%0A%0Aimport pyvty%0A%0Auser = 'admin'%0Apassword = 'password'%0A%0Ahost = '10.36.65.227'%0Aconfig_file = 'config.txt' # name of text file containing config commands.%0Alogfile = 'config_' + host + '.log' # terminal output will be saved in this file.%0A%0A%0Atry:%0A input_file = open(config_file)%0A commands = input_file.readlines()%0A input_file.close()%0Aexcept IOError as e:%0A print(e)%0A exit()%0A%0A%0Aterm = pyvty.Terminal(host=host, username=user, password=password, logfile=logfile)%0A%0Aterm.send('config term')%0A%0Afor command in commands:%0A results = term.send(command.rstrip())%0A for line in results:%0A print(line.rstrip())%0A%0A# term.send('write mem') ''' save configuration to disk '''%0Aterm.send('end')%0Aterm.write('exit')%0A
7864c8e8591d1de14f18ecfaf880e79de6c7702e
add tests for placeholder class
tests/test_placeholders.py
tests/test_placeholders.py
Python
0
@@ -0,0 +1,1606 @@ +import re%0A%0Aimport pytest%0A%0Afrom notifications_utils.field import Placeholder%0A%0A%[email protected]('body, expected', %5B%0A ('((with-brackets))', 'with-brackets'),%0A ('without-brackets', 'without-brackets'),%0A%5D)%0Adef test_placeholder_returns_name(body, expected):%0A assert Placeholder(body).name == expected%0A%0A%[email protected]('body, is_conditional', %5B%0A ('not a conditional', False),%0A ('not? a conditional', False),%0A ('a?? conditional', True),%0A%5D)%0Adef test_placeholder_identifies_conditional(body, is_conditional):%0A assert Placeholder(body).is_conditional() == is_conditional%0A%0A%[email protected]('body, conditional_text', %5B%0A ('a??b', 'b'),%0A ('a?? b ', ' b '),%0A ('a??b??c', 'b??c'),%0A%5D)%0Adef test_placeholder_gets_conditional_text(body, conditional_text):%0A assert Placeholder(body).conditional_text == conditional_text%0A%0A%0Adef test_placeholder_raises_if_accessing_conditional_text_on_non_conditional():%0A with pytest.raises(ValueError):%0A Placeholder('hello').conditional_text%0A%0A%[email protected]('body, value, result', %5B%0A ('a??b', 'Yes', 'b'),%0A ('a??b', 'No', ''),%0A%5D)%0Adef test_placeholder_gets_conditional_body(body, value, result):%0A assert Placeholder(body).get_conditional_body(value) == result%0A%0A%0Adef test_placeholder_raises_if_getting_conditional_body_on_non_conditional():%0A with pytest.raises(ValueError):%0A Placeholder('hello').get_conditional_body('Yes')%0A%0A%0Adef test_placeholder_can_be_constructed_from_regex_match():%0A match = re.search(r'%5C(%5C(.*%5C)%5C)', 'foo ((bar)) baz')%0A assert Placeholder.from_match(match).name == 'bar'%0A
9b1f9e9abd2890bc3e4d9f38109f12de8b488b66
Create config.py
config.py
config.py
Python
0.000002
@@ -0,0 +1,128 @@ +username = %22facility_ai%22%0Apassword = %22UncloakIsADick%22%0Aclient_id = %22GORfUXQGjNIveA%22%0Aclient_secret = %22SzPFXaqgVbRxm_V9-IfGL05npPE%22%0A
17f71bfb81393241759e38fb9dce01561aeca3d5
Add tests to product tags
tests/test_product_tags.py
tests/test_product_tags.py
Python
0
@@ -0,0 +1,1131 @@ +from mock import Mock%0Afrom saleor.product.templatetags.product_images import get_thumbnail, product_first_image%0A%0A%0Adef test_get_thumbnail():%0A instance = Mock()%0A cropped_value = Mock(url='crop.jpg')%0A thumbnail_value = Mock(url='thumb.jpg')%0A instance.crop = %7B'10x10': cropped_value%7D%0A instance.thumbnail = %7B'10x10': thumbnail_value%7D%0A cropped = get_thumbnail(instance, '10x10', method='crop')%0A assert cropped == cropped_value.url%0A thumb = get_thumbnail(instance, '10x10', method='thumbnail')%0A assert thumb == thumbnail_value.url%0A%0A%0Adef test_get_thumbnail_no_instance():%0A output = get_thumbnail(instance=None, size='10x10', method='crop')%0A assert output == '/static/images/product-image-placeholder.png'%0A%0A%0Adef test_product_first_image():%0A mock_product_image = Mock()%0A mock_product_image.image = Mock()%0A mock_product_image.image.crop = %7B'10x10': Mock(url='crop.jpg')%7D%0A%0A mock_queryset = Mock()%0A mock_queryset.all.return_value = %5Bmock_product_image%5D%0A mock_product = Mock(images=mock_queryset)%0A out = product_first_image(mock_product, '10x10', method='crop')%0A assert out == 'crop.jpg'%0A
27444dfefa70759694b755185c2eb6f25216d326
Remove Node - migration.
devilry/apps/core/migrations/0037_auto_20170620_1515.py
devilry/apps/core/migrations/0037_auto_20170620_1515.py
Python
0
@@ -0,0 +1,781 @@ +# -*- coding: utf-8 -*-%0A# Generated by Django 1.9.9 on 2017-06-20 15:15%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import migrations%0A%0A%0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('core', '0036_auto_20170523_1748'),%0A %5D%0A%0A operations = %5B%0A migrations.AlterUniqueTogether(%0A name='node',%0A unique_together=set(%5B%5D),%0A ),%0A migrations.RemoveField(%0A model_name='node',%0A name='admins',%0A ),%0A migrations.RemoveField(%0A model_name='node',%0A name='parentnode',%0A ),%0A migrations.RemoveField(%0A model_name='subject',%0A name='parentnode',%0A ),%0A migrations.DeleteModel(%0A name='Node',%0A ),%0A %5D%0A
f1cb5af4f42ccf437cdd6ef06a2056993e54b604
Create sum13.py
Python/CodingBat/sum13.py
Python/CodingBat/sum13.py
Python
0.000132
@@ -0,0 +1,210 @@ +# http://codingbat.com/prob/p167025%0A%0Adef sum13(nums):%0A sum = 0%0A %0A i = 0%0A while i %3C len(nums):%0A if nums%5Bi%5D == 13:%0A i += 2%0A continue%0A else:%0A sum += nums%5Bi%5D%0A i += 1%0A %0A return sum%0A
d408ae00d2e5c0a0e7c5e90e98088d52815c5e49
Create WikiScrape.py
Python/WikiScrape.py
Python/WikiScrape.py
Python
0
@@ -0,0 +1,650 @@ +## This script was tested using Python 2.7.9%0A## The MWClient library was used to access the api. It can be found at:%0A## https://github.com/mwclient/mwclient%0A%0Aimport mwclient%0Asite = mwclient.Site(('https', 'en.wikipedia.org'))%0Asite.login('$user', '$pass') # credentials are sanitized from the script.%0Alistpage = site.Pages%5B'User:jebaile7964/World_of_Warcraft'%5D%0Atext = listpage.text()%0Afor page in site.Categories%5B'World_of_Warcraft'%5D:%0A text += %22* %5B%5B:%22 + page.name + %22%5D%5D%5Cn%22%0Alistpage.save(text, summary='Creating list from %5B%5BCategory:World_of_Warcraft%5D%5D')%0A%0A## results are found at:%0A## https://en.wikipedia.org/wiki/User:Jebaile7964/World_of_Warcraft%0A
e455d459590a4f2b16b9a9360b6e33640f5ec7bf
Add a script to check that __all__ in __init__.py is correct
python/allcheck.py
python/allcheck.py
Python
0.003175
@@ -0,0 +1,1414 @@ +#!/usr/bin/env python%0Aimport sys%0Aimport re%0Aimport glob%0A%0Aimport phonenumbers%0A%0AINTERNAL_FILES = %5B'phonenumbers/util.py',%0A 'phonenumbers/re_util.py',%0A 'phonenumbers/unicode_util.py'%5D%0ACLASS_RE = re.compile(r%22%5Eclass +(%5BA-Za-z%5D%5B_A-Za-z0-9%5D+)%5B %5C(:%5D%22)%0AFUNCTION_RE = re.compile(%22%5Edef +(%5BA-Za-z%5D%5B_A-Za-z0-9%5D+)%5B %5C(%5D%22)%0ACONSTANT_RE = re.compile(%22%5E(%5BA-Z%5D%5B_A-Z0-9%5D+) *= *%22)%0A%0Agrepped_all = set()%0Afor filename in glob.glob('phonenumbers/*.py'):%0A if filename in INTERNAL_FILES:%0A continue%0A with file(filename, %22r%22) as infile:%0A for line in infile:%0A m = CLASS_RE.match(line)%0A if m:%0A grepped_all.add(m.group(1))%0A m = FUNCTION_RE.match(line)%0A if m:%0A grepped_all.add(m.group(1))%0A m = CONSTANT_RE.match(line)%0A if m:%0A grepped_all.add(m.group(1))%0A%0Acode_all = set(phonenumbers.__all__)%0Acode_not_grepped = (code_all - grepped_all)%0Agrepped_not_code = (grepped_all - code_all)%0Aif len(code_not_grepped) %3E 0:%0A print %3E%3E sys.stderr, %22Found the following in __all__ but not in grepped code:%22%0A for identifier in code_not_grepped:%0A print %3E%3E sys.stderr, %22 %25s%22 %25 identifier%0Aif len(grepped_not_code) %3E 0:%0A print %3E%3E sys.stderr, %22Found the following in grepped code but not in__all__:%22%0A for identifier in grepped_not_code:%0A print %3E%3E sys.stderr, %22 %25s%22 %25 identifier%0A
0deec6fecb527f12ff6851c47820b76db8196a34
Add files via upload
rosette.py
rosette.py
Python
0
@@ -0,0 +1,760 @@ +# This is a basic program showing the functionality of the turtle module.%0D%0A# It generates a very pretty spiraling pattern.%0D%0A%0D%0Aimport turtle # import the turtle module so we can draw%0D%0Aimport math # import the math module, we need this for e and pi%0D%0A%0D%0At = turtle.Pen() # set a variable to draw with%0D%0A%0D%0At.reset() # clear the screen just in case of leftovers%0D%0A%0D%0Ax = 0 # set some variables to play with%0D%0Ay = 5%0D%0Az = 10%0D%0A%0D%0Awhile x %3C= 999: # the more repeats, the larger the pattern%0D%0A t.circle(x,13,2) # this basically sets up 3 arcs which can be varied%0D%0A t.circle(y,17,3)%0D%0A t.circle(z,19,5)%0D%0A x = x + 1 # increment or decrement the radius of each arc by an interesting value%0D%0A y = y / math.e%0D%0A z = z / math.pi%0D%0A
48c844e602eaa182c4efaaa0b977765f4248d0a0
Add a data migration tool
tools/network_migration.py
tools/network_migration.py
Python
0.000006
@@ -0,0 +1,1368 @@ +import argparse, shelve%0A%0Adef renameDictKeys(storageDict):%0A for key in storageDict.iterkeys():%0A if isinstance(storageDict%5Bkey%5D, dict):%0A renameDictKeys(storageDict%5Bkey%5D)%0A if key == options.oldnetwork:%0A storageDict%5Boptions.newnetwork%5D = storageDict%5Boptions.oldnetwork%5D%0A del storageDict%5Boptions.oldnetwork%5D%0A%0Aif __name__ == %22__main__%22:%0A # Parse the command line arguments%0A parser = argparse.ArgumentParser(description=%22A tool for PyHeufyBot to migrate all storage data from one network %22%0A %22to another.%22)%0A parser.add_argument(%22-s%22, %22--storage%22, help=%22The storage file to use%22, type=str, default=%22../heufybot.db%22)%0A parser.add_argument(%22-o%22, %22--oldnetwork%22, help=%22The name of the old network that the data should be migrated %22%0A %22from.%22, type=str, required=True)%0A parser.add_argument(%22-n%22, %22--newnetwork%22, help=%22The name of the new network that the data should be migrated to.%22,%0A type=str, required=True)%0A options = parser.parse_args()%0A%0A storage = shelve.open(options.storage)%0A d = dict(storage)%0A renameDictKeys(d)%0A storage.clear()%0A storage.update(d)%0A%0A storage.close()%0A print %22Data has been migrated from '%7B%7D' to '%7B%7D'.%22.format(options.oldnetwork, options.newnetwork)%0A
20269212705bdfd8748be468a50567ba290ad4a1
Bump PROVISION_VERSION for new APNS.
version.py
version.py
ZULIP_VERSION = "1.6.0+git" PROVISION_VERSION = '9.3'
Python
0
@@ -48,7 +48,7 @@ '9. -3 +4 '%0A
9cd494537ee51e092a8e8080f0e59bfd5a75eda4
Use cities1000 in test_project
test_project/test_project/settings.py
test_project/test_project/settings.py
# Django settings for test_project project. import os.path import posixpath PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '[email protected]'), ) FIXTURE_DIRS = [ os.path.join(PROJECT_ROOT, 'fixtures'), ] MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'db.sqlite', # Or path to database file if using sqlite3. 'USER': '', # Not used with sqlite3. 'PASSWORD': '', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } } # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set this to False, Django will not use timezone-aware datetimes. USE_TZ = True # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # Additional locations of static files STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = 'mzdvd*#0=$g(-!v_vj_7^(=zrh3klia(u&amp;cqd3nr7p^khh^ui#' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', # Uncomment the next line for simple clickjacking protection: # 'django.middleware.clickjacking.XFrameOptionsMiddleware', ) ROOT_URLCONF = 'test_project.urls' # Python dotted path to the WSGI application used by Django's runserver. WSGI_APPLICATION = 'test_project.wsgi.application' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(PROJECT_ROOT, 'templates'), ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', 'cities_light', 'south', ) # A sample logging configuration. The only tangible logging # performed by this configuration is to send an email to # the site admins on every HTTP 500 error when DEBUG=False. # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.request': { 'handlers':['console'], 'propagate': True, 'level':'DEBUG', }, 'cities_light': { 'handlers':['console'], 'propagate': True, 'level':'DEBUG', }, } }
Python
0.000001
@@ -150,16 +150,110 @@ '..'))%0A%0A +CITIES_LIGHT_CITY_SOURCES = %5B%0A 'http://download.geonames.org/export/dump/cities1000.zip'%5D%0A%0A DEBUG =
426f9c0b63adf7d7085a45bfe3520eb36a2ad6f7
Fix indents.
evelink/parsing/assets.py
evelink/parsing/assets.py
from evelink import api from evelink import constants def parse_assets(api_result): def handle_rowset(rowset, parent_location): results = [] for row in rowset.findall('row'): item = {'id': int(row.attrib['itemID']), 'item_type_id': int(row.attrib['typeID']), 'location_id': int(row.attrib.get('locationID', parent_location)), 'location_flag': int(row.attrib['flag']), 'quantity': int(row.attrib['quantity']), 'packaged': row.attrib['singleton'] == '0', } contents = row.find('rowset') if contents: item['contents'] = handle_rowset(contents, item['location_id']) results.append(item) return results result_list = handle_rowset(api_result.find('rowset'), None) # For convenience, key the result by top-level location ID. result_dict = {} for item in result_list: location = item['location_id'] result_dict.setdefault(location, {}) result_dict[location]['location_id'] = location result_dict[location].setdefault('contents', []) result_dict[location]['contents'].append(item) return result_dict
Python
0.000001
@@ -238,26 +238,40 @@ 'itemID'%5D),%0A -%09%09 + 'item_ty @@ -301,26 +301,40 @@ 'typeID'%5D),%0A -%09%09 + 'locatio @@ -392,18 +392,32 @@ tion)),%0A -%09%09 + 'loc @@ -450,26 +450,40 @@ b%5B'flag'%5D),%0A -%09%09 + 'quantit @@ -519,10 +519,24 @@ %5D),%0A -%09%09 + @@ -583,9 +583,16 @@ 0',%0A -%09 +
35076b373913381a90aa65e8052036eb51eece46
add unicode_literals in utils
simiki/utils.py
simiki/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import os import shutil import errno from os import path as osp RESET_COLOR = "\033[0m" COLOR_CODES = { "debug" : "\033[1;34m", # blue "info" : "\033[1;32m", # green "warning" : "\033[1;33m", # yellow "error" : "\033[1;31m", # red "critical" : "\033[1;41m", # background red } def color_msg(level, msg): return COLOR_CODES[level] + msg + RESET_COLOR def check_path_exists(path): """Check if the path(include file and directory) exists""" if osp.exists(path): return True return False def check_extension(filename): """Filter file by suffix If the file suffix not in the allowed suffixes, the return true and filter. The `fnmatch` module can also get the suffix: patterns = ["*.md", "*.mkd", "*.markdown"] fnmatch.filter(files, pattern) """ # Allowed suffixes ( aka "extensions" ) exts = {".md", ".mkd", ".mdown", ".markdown"} return osp.splitext(filename)[1] in exts #def copytree(src, dst): # try: # shutil.copytree(src, dst) # except OSError as exc: # python >2.5 # if exc.errno == errno.ENOTDIR: # shutil.copy(src, dst) # else: raise def copytree(src, dst, symlinks=False, ignore=None): # OSError: [Errno 17] File exists: '/home/tankywoo/simiki/html/css' if not osp.exists(dst): os.makedirs(dst) for item in os.listdir(src): s = osp.join(src, item) d = osp.join(dst, item) if osp.isdir(s): shutil.copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d) if __name__ == "__main__": print(color_msg("debug", "DEBUG")) print(color_msg("info", "DEBUG")) print(color_msg("warning", "WARNING")) print(color_msg("error", "ERROR")) print(color_msg("critical", "CRITICAL"))
Python
0.001148
@@ -77,16 +77,34 @@ function +, unicode_literals %0A%0Aimport
d72d2e38d177476470b22ded061dd06b2be3ee88
Add the quantity-safe allclose from spectral-cube
turbustat/tests/helpers.py
turbustat/tests/helpers.py
Python
0.000261
@@ -0,0 +1,2265 @@ +from __future__ import print_function, absolute_import, division%0A%0Afrom astropy import units as u%0A%0Afrom numpy.testing import assert_allclose as assert_allclose_numpy, assert_array_equal%0A%0A%0Adef assert_allclose(q1, q2, **kwargs):%0A %22%22%22%0A Quantity-safe version of Numpy's assert_allclose%0A%0A Copyright (c) 2014, spectral-cube developers%0A All rights reserved.%0A%0A Redistribution and use in source and binary forms, with or without%0A modification, are permitted provided that the following conditions are%0A met:%0A%0A 1. Redistributions of source code must retain the above copyright%0A notice, this list of conditions and the following disclaimer.%0A%0A 2. Redistributions in binary form must reproduce the above copyright%0A notice, this list of conditions and the following disclaimer in the%0A documentation and/or other materials provided with the distribution.%0A%0A 3. Neither the name of the copyright holder nor the names of its%0A contributors may be used to endorse or promote products derived from%0A this software without specific prior written permission.%0A%0A THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS %22AS%0A IS%22 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED%0A TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A%0A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT%0A HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,%0A SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED%0A TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR%0A PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF%0A LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING%0A NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS%0A SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.%0A%0A %22%22%22%0A if isinstance(q1, u.Quantity) and isinstance(q2, u.Quantity):%0A assert_allclose_numpy(q1.to(q2.unit).value, q2.value, **kwargs)%0A elif isinstance(q1, u.Quantity):%0A assert_allclose_numpy(q1.value, q2, **kwargs)%0A elif isinstance(q2, u.Quantity):%0A assert_allclose_numpy(q1, q2.value, **kwargs)%0A else:%0A assert_allclose_numpy(q1, q2, **kwargs)
6c3d92a2d3eb043e466e3d6ab8e303c025cc7e0a
add ColorPrinter.py
ColorPrinter.py
ColorPrinter.py
Python
0
@@ -0,0 +1,1443 @@ +class ColorPrinter:%0A %22%22%22%0A print message to terminal with colored header%0A %22%22%22%0A def __init__(self, header=''):%0A self.__header = header%0A self.__levels = %7B%0A 'log': '%5C033%5B0m', # terminal color header%0A 'info': '%5C033%5B1;32;40m', # green header%0A 'warn': '%5C033%5B1;33;40m', # yellow header%0A 'error': '%5C033%5B1;31;40m', # red header%0A %7D%0A%0A def setHeader(self, header=''):%0A self.__header = header%0A%0A def __format(self, message, level='log'):%0A header = self.__levels.get(level, self.__levels%5B'log'%5D) + self.__header + self.__levels%5B'log'%5D if self.__header else ''%0A body = ' ' + message if message else ''%0A return header + body%0A%0A # %60info%60 print the message with terminal color header%0A def log(self, message='', *others):%0A print self.__format(' '.join((message,) + others), 'log')%0A return self%0A%0A # %60info%60 print the message with green header%0A def info(self, message='', *others):%0A print self.__format(' '.join((message,) + others), 'info')%0A return self%0A%0A # %60warn%60 print the message with yellow header%0A def warn(self, message='', *others):%0A print self.__format(' '.join((message,) + others), 'warn')%0A return self%0A%0A # %60error%60 print the message with red header%0A def error(self, message='', *others):%0A print self.__format(' '.join((message,) + others), 'error')%0A return self%0A
b5972a5651ba1ace28ae54d5a1a4f31a07e97670
add server_costs table
migrations/versions/1e27c434bb14_create_server_costs.py
migrations/versions/1e27c434bb14_create_server_costs.py
Python
0.000001
@@ -0,0 +1,758 @@ +%22%22%22create server_costs table%0A%0ARevision ID: 1e27c434bb14%0ARevises: fa0f07475596%0ACreate Date: 2016-03-14 15:57:19.945327%0A%0A%22%22%22%0A%0A# revision identifiers, used by Alembic.%0Arevision = '1e27c434bb14'%0Adown_revision = 'fa0f07475596'%0A%0Afrom alembic import op%0Aimport sqlalchemy as sa%0Afrom sqlalchemy.dialects import postgresql%0A%0Adef upgrade():%0A op.create_table(%0A 'server_costs',%0A sa.Column('project_url', sa.String(length=255), sa.ForeignKey('projects.url'), nullable=False, primary_key=True),%0A sa.Column('value', sa.Numeric(precision=10, scale=2), nullable=True),%0A sa.Column('created_at', sa.DateTime(), nullable=True),%0A sa.Column('updated_at', sa.DateTime(), nullable=True)%0A )%0A%0A%0Adef downgrade():%0A op.drop_table('server_costs')%0A
7334b87e6d7a9ef495919a2b13cf926692619fcd
fix min/max typos
modularodm/tests/validators/test_iterable_validators.py
modularodm/tests/validators/test_iterable_validators.py
from modularodm import StoredObject from modularodm.exceptions import ValidationValueError from modularodm.fields import IntegerField, StringField from modularodm.tests import ModularOdmTestCase from modularodm.validators import MaxLengthValidator, MinLengthValidator class StringValidatorTestCase(ModularOdmTestCase): def define_test_objects(self): class Foo(StoredObject): _id = IntegerField() test_field = StringField( list=False, validate=[MaxLengthValidator(5), ] ) self.test_object = Foo(_id=0) return Foo, def test_max_length_string_validator(self): self.test_object.test_field = 'abc' self.test_object.save() self.test_object.test_field = 'abcdefg' with self.assertRaises(ValidationValueError): self.test_object.save() def test_min_length_string_validator(self): self.test_object.test_field = 'abc' with self.assertRaises(ValidationValueError): self.test_object.save() self.test_object.test_field = 'abcdefg' self.test_object.save() class ListValidatorTestCase(ModularOdmTestCase): def define_test_objects(self): class Foo(StoredObject): _id = IntegerField() test_field = IntegerField( list=True, list_validate=[MaxLengthValidator(5), ] ) self.test_object = Foo(_id=0) return Foo, def test_min_length_list_validator(self): # This test fails. self.test_object.test_field = [1, 2, 3] with self.assertRaises(ValidationValueError): self.test_object.save() self.test_object.test_field = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] self.test_object.save() def test_max_length_list_validator(self): # This test fails. self.test_object.test_field = [1, 2, 3] self.test_object.save() self.test_object.test_field = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] with self.assertRaises(ValidationValueError): self.test_object.save() class IterableValidatorCombinationTestCase(ModularOdmTestCase): def define_test_objects(self): class Foo(StoredObject): _id = IntegerField() test_field = StringField( list=True, validate=MaxLengthValidator(3), list_validate=MinLengthValidator(3) ) self.test_object = Foo(_id=0) return Foo, def test_child_pass_list_fail(self): self.test_object.test_field = ['ab', 'abc'] with self.assertRaises(ValidationValueError): self.test_object.save() def test_child_fail_list_pass(self): self.test_object.test_field = ['ab', 'abcd', 'adc'] with self.assertRaises(ValidationValueError): self.test_object.save() def test_child_fail_list_fail(self): self.test_object.test_field = ['ab', 'abdc'] with self.assertRaises(ValidationValueError): self.test_object.save()
Python
0.999987
@@ -430,32 +430,36 @@ test_field +_max = StringField(%0A @@ -543,32 +543,167 @@ %5D%0A )%0A + test_field_min = StringField(%0A list=False,%0A validate=%5BMinLengthValidator(5), %5D%0A )%0A self.tes @@ -829,32 +829,36 @@ bject.test_field +_max = 'abc'%0A @@ -910,32 +910,36 @@ bject.test_field +_max = 'abcdefg'%0A @@ -1106,24 +1106,28 @@ t.test_field +_min = 'abc'%0A @@ -1249,16 +1249,20 @@ st_field +_min = 'abcd @@ -1473,16 +1473,20 @@ st_field +_max = Integ @@ -1583,32 +1583,172 @@ %5D%0A )%0A + test_field_min = IntegerField(%0A list=True,%0A list_validate=%5BMinLengthValidator(3), %5D%0A )%0A self.tes @@ -1895,32 +1895,36 @@ t.test_field +_min = %5B1, 2 , 3%5D%0A @@ -1903,35 +1903,32 @@ ield_min = %5B1, 2 -, 3 %5D%0A with s @@ -2031,32 +2031,36 @@ bject.test_field +_min = %5B1, 2, 3, 4, @@ -2211,32 +2211,88 @@ bject.test_field +_min = %5B1, 2, 3%5D%0A self.test_object.test_field_max = %5B1, 2, 3%5D%0A @@ -2352,24 +2352,28 @@ t.test_field +_max = %5B1, 2, 3,
ff519b5145accbc10fcb7baa955bc1fe44774c27
Add browser/websocket.py
src/Lib/browser/websocket.py
src/Lib/browser/websocket.py
Python
0.000001
@@ -0,0 +1,100 @@ +from browser import window%0Aimport javascript%0A%0AWebSocket = javascript.JSConstructor(window.WebSocket)
126491288a532da08fb3923eae2635a84736798d
Add new package: libsamplerate (#16143)
var/spack/repos/builtin/packages/libsamplerate/package.py
var/spack/repos/builtin/packages/libsamplerate/package.py
Python
0
@@ -0,0 +1,899 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass Libsamplerate(AutotoolsPackage):%0A %22%22%22libsamplerate (also known as Secret Rabbit Code) is a library for%0A performing sample rate conversion of audio data.%22%22%22%0A%0A homepage = %22http://www.mega-nerd.com/libsamplerate/history.html%22%0A url = %22http://www.mega-nerd.com/libsamplerate/libsamplerate-0.1.9.tar.gz%22%0A%0A version('0.1.9', sha256='0a7eb168e2f21353fb6d84da152e4512126f7dc48ccb0be80578c565413444c1')%0A version('0.1.8', sha256='93b54bdf46d5e6d2354b7034395fe329c222a966790de34520702bb9642f1c06')%0A%0A depends_on('m4', type='build')%0A depends_on('autoconf', type='build')%0A depends_on('automake', type='build')%0A depends_on('libtool', type='build')%0A
4e6a6e4f2758bd616f0c2c2703160cbb9c539b63
add new package (#23843)
var/spack/repos/builtin/packages/py-kubernetes/package.py
var/spack/repos/builtin/packages/py-kubernetes/package.py
Python
0
@@ -0,0 +1,1896 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0A%0Afrom spack import *%0A%0A%0Aclass PyKubernetes(PythonPackage):%0A %22%22%22Official Python client library for kubernetes. %22%22%22%0A%0A homepage = %22https://kubernetes.io%22%0A git = %22https://github.com/kubernetes-client/python.git%22%0A pypi = %22kubernetes/kubernetes-17.17.0.tar.gz%22%0A%0A maintainers = %5B'vvolkl'%5D%0A%0A version('17.17.0', sha256='c69b318696ba797dcf63eb928a8d4370c52319f4140023c502d7dfdf2080eb79')%0A version('12.0.1', sha256='ec52ea01d52e2ec3da255992f7e859f3a76f2bdb51cf65ba8cd71dfc309d8daa')%0A version('12.0.0', sha256='72f095a1cd593401ff26b3b8d71749340394ca6d8413770ea28ce18efd5bcf4c')%0A version('11.0.0', sha256='1a2472f8b01bc6aa87e3a34781f859bded5a5c8ff791a53d889a8bd6cc550430')%0A version('10.1.0', sha256='85a767d04f17d6d317374b6c35e09eb168a6bfd9276f0b3177cc206376bad968')%0A version('10.0.1', sha256='3770a496663396ad1def665eeadb947b3f45217a08b64b10c01a57e981ac8592')%0A version('9.0.0', sha256='a8b0aed55ba946faea660712595a52ae53a8854df773d96f47a63fa0c9d4e3bf')%0A%0A depends_on('[email protected]:', type=('build', 'run'))%0A depends_on('[email protected]:', type=('build', 'run'))%0A depends_on('[email protected]:', type=('build', 'run'))%0A depends_on('[email protected]:', type=('build'))%0A depends_on('[email protected]:', type=('build', 'run'))%0A depends_on('[email protected]:', type=('build', 'run'))%0A depends_on('[email protected]:', when='%5Epython@:2.8', type=('build', 'run'))%0A depends_on('[email protected]:0.39,0.43:', type=('build', 'run'))%0A depends_on('py-requests', type=('build', 'run'))%0A depends_on('py-requests-oauthlib', type=('build', 'run'))%0A depends_on('[email protected]:', type=('build', 'run'))%0A
04d6fd6ceabf71f5f38fd7cf25cd4ac2bcb6b57f
Add simple web server to display measurements
server.py
server.py
Python
0
@@ -0,0 +1,1022 @@ +import sqlite3%0Afrom flask import Flask, g, render_template_string%0Aapp = Flask(__name__)%0A%0Adef get_db():%0A db = getattr(g, '_database', None)%0A if db is None:%0A db = g._database = sqlite3.connect('sensors.db')%0A return db%0A%0Aindex_tmpl = %22%22%22%0A%3C!doctype html%3E%0A%3Ctitle%3ESensors%3C/title%3E%0A%3Cbody%3E%0A%3Ch1%3ESenors%3C/h1%3E%0A%3Cdl%3E%0A%3Cdt%3EOutside Temperature%3C/dt%3E%0A%3Cdd%3E%7B%7B sensors%5B'ot'%5D %7D%7D%3C/dd%3E%0A%3Cdt%3EOutside Humidity%3C/dt%3E%0A%3Cdd%3E%7B%7B sensors%5B'oh'%5D %7D%7D%3C/dd%3E%0A%3Cdt%3EInside Temperature%3C/dt%3E%0A%3Cdd%3E%7B%7B sensors%5B'it'%5D %7D%7D%3C/dd%3E%0A%3Cdt%3EInside Humidity%3C/dt%3E%0A%3Cdd%3E%7B%7B sensors%5B'ih'%5D %7D%7D%3C/dd%3E%0A%3Cdt%3EBarometric Pressure%3C/dt%3E%0A%3Cdd%3E%7B%7B sensors%5B'bp'%5D %7D%7D%3C/dd%3E%0A%3Cdt%3ETime%3C/dt%3E%0A%3Cdd%3E%7B%7B ts %7D%7D UTC%3C/dd%3E%0A%3C/dl%3E%0A%22%22%22%0A%[email protected]('/')%0Adef index():%0A db = get_db()%0A sensors = db.execute('SELECT * FROM measurements GROUP BY sensor')%0A sensors = %5Bx for x in sensors%5D%0A ts = sensors%5B0%5D%5B0%5D%0A sensors = dict(%5B(x%5B1%5D, x%5B2%5D) for x in sensors%5D)%0A return render_template_string(index_tmpl, sensors=sensors, ts=ts)%0A%0Aif __name__ == '__main__':%0A app.debug = False%0A app.run(host='0.0.0.0')%0A
acc23fe67231f8b556b2de7bd19f0050cbe379e6
Add total calculation script
total_prices.py
total_prices.py
Python
0.000001
@@ -0,0 +1,376 @@ +prices = %7B%0A %22banana%22 : 4,%0A %22apple%22 : 2,%0A %22orange%22 : 1.5,%0A %22pear%22 : 3%0A%7D%0A%0Astock = %7B%0A %22banana%22 : 6,%0A %22apple%22 : 0,%0A %22orange%22 : 32,%0A %22pear%22 : 15,%0A%7D%0A%0A%0Atotal = 0%0A%0Afor key in prices:%0A print key%0A print %22price: %25s%22 %25 prices%5Bkey%5D%0A print %22stock: %25s%22 %25 stock%5Bkey%5D%0A print prices%5Bkey%5D * stock%5Bkey%5D%0A total += prices%5Bkey%5D * stock%5Bkey%5D%0A%0A%0Aprint total
31af4f92e97c83c42baff4e902cddf8184d84e4d
allow to run tox as 'python -m tox', which is handy on Windoze
tox/__main__.py
tox/__main__.py
Python
0
@@ -0,0 +1,38 @@ +from tox._cmdline import main%0A%0Amain()%0A
f86d07998a2a80fcf9e69cca9d89c2ca4d982e02
Fix windows dist script
src/etc/copy-runtime-deps.py
src/etc/copy-runtime-deps.py
#!/usr/bin/env python # xfail-license # Copies Rust runtime dependencies to the specified directory import snapshot, sys, os, shutil def copy_runtime_deps(dest_dir): for path in snapshot.get_winnt_runtime_deps(): shutil.copy(path, dest_dir) lic_dest = os.path.join(dest_dir, "third-party") shutil.rmtree(lic_dest) # copytree() won't overwrite existing files shutil.copytree(os.path.join(os.path.dirname(__file__), "third-party"), lic_dest) copy_runtime_deps(sys.argv[1])
Python
0
@@ -303,16 +303,53 @@ party%22)%0A + if os.path.exists(lic_dest):%0A shut
d206b02e12cf7f5418cd02987313bd7ddd807901
add geom_tile layer.
ggplot/geoms/geom_tile.py
ggplot/geoms/geom_tile.py
Python
0
@@ -0,0 +1,929 @@ +import matplotlib.pyplot as plt%0Aimport numpy as np%0Aimport pandas as pd%0A%0Afrom geom import geom%0A%0A%0Aclass geom_tile(geom):%0A VALID_AES = %5B'x', 'y', 'fill'%5D%0A%0A def plot_layer(self, layer):%0A layer = %7Bk: v for k, v in layer.iteritems() if k in self.VALID_AES%7D%0A layer.update(self.manual_aes)%0A%0A x = layer.pop('x')%0A y = layer.pop('y')%0A fill = layer.pop('fill')%0A X = pd.DataFrame(%7B'x': x,%0A 'y': y,%0A 'fill': fill%7D).set_index(%5B'x', 'y'%5D).unstack(0)%0A x_ticks = range(0, len(set(x)))%0A y_ticks = range(0, len(set(y)))%0A%0A plt.imshow(X, interpolation='nearest', **layer)%0A return %5B%0A %7B'function': 'set_xticklabels', 'args': %5Bx%5D%7D,%0A %7B'function': 'set_xticks', 'args': %5Bx_ticks%5D%7D,%0A %7B'function': 'set_yticklabels', 'args': %5By%5D%7D,%0A %7B'function': 'set_yticks', 'args': %5By_ticks%5D%7D%0A %5D%0A
d940ce7cbd92c0e886139eaec3faa75aabbce16a
add test models
singleactiveobject/tests/models.py
singleactiveobject/tests/models.py
Python
0
@@ -0,0 +1,125 @@ +from singleactiveobject.models import SingleActiveObjectMixin%0A%0A%0Aclass SingleActiveObject(SingleActiveObjectMixin):%0A pass%0A%0A
71d3375c4ca1acb106f8825d2f39ca602fa47e94
Test astroid trajectory implementation
src/test/trajectory/test_astroid_trajectory.py
src/test/trajectory/test_astroid_trajectory.py
Python
0.000001
@@ -0,0 +1,1117 @@ +#!/usr/bin/env python%0Aimport unittest%0A%0Afrom geometry_msgs.msg import Point%0A%0Afrom trajectory.astroid_trajectory import AstroidTrajectory%0A%0A%0Aclass AstroidTrajectoryTest(unittest.TestCase):%0A%0A def setUp(self):%0A self.delta = 0.000001%0A self.radius = 5%0A self.period = 4%0A self.expected_position = Point()%0A self.trajectory = AstroidTrajectory(self.radius, self.period)%0A%0A%0A def test_when_creating_trajectory_the_radius_and_period_are_set(self):%0A self.assertEqual(self.radius, self.trajectory.radius)%0A self.assertEqual(self.period, self.trajectory.period)%0A%0A def test_when_getting_position_after_1s_then_position_at_1s_is_returned(self):%0A self.expected_position.x = 0%0A self.expected_position.y = self.radius%0A self.assertAlmostEqual(self.expected_position, self.trajectory.get_position_at(1))%0A%0A def test_when_getting_position_after_2s_then_position_at_2s_is_returned(self):%0A self.expected_position.x = -self.radius%0A self.expected_position.y = 0%0A self.assertAlmostEqual(self.expected_position, self.trajectory.get_position_at(2))%0A
835b5f20061033b6fcf2a8b86203a42c5d4835ee
Add initial unit tests for parameter.py (List)
spotpy/unittests/test_parameter.py
spotpy/unittests/test_parameter.py
Python
0
@@ -0,0 +1,1156 @@ +import unittest%0Atry:%0A import spotpy%0Aexcept ImportError:%0A import sys%0A sys.path.append(%22.%22)%0A import spotpy%0Afrom spotpy import parameter%0Aimport numpy as np%0A%0A#https://docs.python.org/3/library/unittest.html%0A%0Aclass TestListParameterDistribution(unittest.TestCase):%0A%0A def setUp(self):%0A self.values = %5B1, 2, 3, 4, 5%5D%0A self.list_param = parameter.List('test', self.values)%0A self.list_param_repeat = parameter.List('test2', self.values, repeat=True)%0A%0A def test_list_is_callable(self):%0A self.assertTrue(callable(self.list_param), %22List instance should be callable%22)%0A%0A def test_list_gives_throwaway_value_on_first_call(self):%0A v = self.list_param()%0A self.assertNotEqual(self.values%5B0%5D, v)%0A%0A def test_list_gives_1_value_when_size_is_not_specified(self):%0A throwaway = self.list_param()%0A v = self.list_param()%0A self.assertEqual(self.values%5B0%5D, v)%0A%0A def test_list_gives_n_values_when_size_is_n(self):%0A throwaway = self.list_param()%0A v = self.list_param(len(self.values))%0A self.assertEqual(self.values, list(v))%0A%0A%0Aif __name__ == '__main__':%0A unittest.main()%0A
a759fee7b1cca1d3966100b480cac80ad4c9ece7
Iterate the stackexchange corpuses term vectors
termVectors.py
termVectors.py
Python
0.999848
@@ -0,0 +1,1470 @@ +%0Afrom elasticsearch import Elasticsearch%0Aes = Elasticsearch('http://localhost:9200')%0A%0A%0Adef scoredFingerprint(terms):%0A fp = %7B%7D%0A for term, value in terms.items():%0A fp%5Bterm%5D = float(value%5B'term_freq'%5D) / float(value%5B'doc_freq'%5D)%0A return fp%0A%0A%0Adef allCorpusDocs(index='stackexchange', doc_type='post', fields='Body.bigramed'):%0A query = %7B%0A %22sort%22: %5B%22_doc%22%5D,%0A %22size%22: 500%0A %7D%0A resp = es.search(index=index, doc_type=doc_type, scroll='1m', body=query)%0A while len(resp%5B'hits'%5D%5B'hits'%5D) %3E 0:%0A for doc in resp%5B'hits'%5D%5B'hits'%5D:%0A yield doc%5B'_id'%5D%0A scrollId = resp%5B'_scroll_id'%5D%0A resp = es.scroll(scroll_id=scrollId, scroll='1m')%0A%0A%0Adef termVectors(docIds, index='stackexchange', doc_type='post', field='Body.bigramed'):%0A tvs = es.mtermvectors(ids=docIds, index=index, doc_type=doc_type, fields=field, term_statistics=True)%0A for tv in tvs%5B'docs'%5D:%0A try:%0A yield (tv%5B'_id'%5D, scoredFingerprint(tv%5B'term_vectors'%5D%5Bfield%5D%5B'terms'%5D))%0A except KeyError:%0A pass%0A%0A%0Adef groupEveryN(l, n=10):%0A for i in range(0, len(l), n):%0A yield l%5Bi:i+n%5D%0A%0A%0Adef allTermVectors(docIds):%0A for docIdGroup in groupEveryN(docIds):%0A for tv in termVectors(docIds=docIdGroup):%0A yield tv%0A%0A%0Aif __name__ == %22__main__%22:%0A docIds = %5BdocId for docId in allCorpusDocs()%5D%0A print(%22Fetching %25s Term Vectors%22 %25 len(docIds))%0A%0A for tv in allTermVectors(docIds):%0A print(tv)%0A%0A
e9a5a0c22de92f3b5eb5df567475736b72c5067c
Add pa300_calc_coord.py
pa300_calc_coord.py
pa300_calc_coord.py
Python
0.001616
@@ -0,0 +1,1080 @@ +# Std libs%0Afrom itertools import product%0Aimport sqlite3%0A# My libs%0Aimport constants as c%0A%0Aconn_params = sqlite3.connect(c.sql_params_dropbox)%0Acur_params = conn_params.cursor()%0A%0Adats = cur_params.execute('''SELECT mask, mesa, xm_mesa, ym_mesa, xm_pad, ym_pad%0A FROM mesas''').fetchall()%0A%0Afor dat in dats:%0A mask, mesa, xm_mesa, ym_mesa, xm_pad, ym_pad = dat%0A dX, dY = cur_params.execute('SELECT d_X, d_Y FROM masks WHERE mask=?',%5C%0A (mask,)).fetchone()%0A for (X, Y) in product(range(1,21), range(1,21)):%0A x_mesa = (X-1)*dX + xm_mesa%0A y_mesa = (Y-1)*dY + ym_mesa%0A x_pad = (X-1)*dX + xm_pad%0A y_pad = (Y-1)*dY + ym_pad%0A print(mask, mesa, X, Y)%0A cur_params.execute('''INSERT OR REPLACE INTO%0A coord(mask, mesa, X, Y, xmesa, ymesa, xpad, ypad)%0A VALUES(?, ?, ?, ?, ?, ?, ?, ?)''',%0A (mask, mesa, X, Y, %0A x_mesa, y_mesa, x_pad, y_pad,))%0Aconn_params.commit()%0A
b3c89917895786bfab5d4fae9ce086767575a506
Add a deployment script
deploy.py
deploy.py
Python
0.000002
@@ -0,0 +1,1389 @@ +%22%22%22 This is a script that deploys Dogbot. %22%22%22%0A%0Aimport os%0Afrom pathlib import Path%0A%0Afrom ruamel.yaml import YAML%0Aimport requests%0A%0A# load the webhook url from the configuration%0Awith open('config.yml') as f:%0A webhook_url = YAML(typ='safe').load(f)%5B'monitoring'%5D%5B'health_webhook'%5D%0A%0A%0Adef info(text):%0A print('%5C033%5B32m%5Binfo%5D%5C033%5B0m', text)%0A%0A%0Adef post(content=None, *, embed=None, wait_for_server=True):%0A info('POSTing to %7B%7D: %7B%7D'.format(webhook_url, content or embed))%0A payload = %7B'content': content, 'embeds': %5Bembed%5D%7D%0A requests.post(webhook_url + ('?wait=true' if wait_for_server else ''), json=payload)%0A%0A%0Adef deploy():%0A %22%22%22 Deploys Dogbot. %22%22%22%0A%0A # resolve path to playbook%0A playbook = (Path.cwd() / 'deployment' / 'playbook.yml').resolve()%0A info('Path to Ansible playbook: %7B%7D'.format(playbook))%0A%0A # post!%0A post(embed=%7B'title': 'Deployment starting.', 'description': 'This shouldn%5C't take too long.', 'color': 0xe67e22%7D)%0A%0A # run the playbook%0A info('Running Ansible playbook.')%0A exit_code = os.system('ansible-playbook %7B%7D'.format(playbook))%0A if exit_code != 0:%0A info('Deployment failed.')%0A return%0A info('Finished running playbook.')%0A%0A # post!%0A post(embed=%7B'title': 'Deployment finished.', 'description': 'The bot is restarting. This can take a bit.',%0A 'color': 0x2ecc71%7D)%0A%0Aif __name__ == '__main__':%0A deploy()%0A
10b3ae6ab5009fe0c43b744dc655bd6512cec041
Include basic version of contract object
db/contract.py
db/contract.py
Python
0
@@ -0,0 +1,217 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Afrom .common import Base, session_scope%0A%0A%0Aclass Contract(Base):%0A __tablename__ = 'contracts'%0A __autoload__ = True%0A%0A%0Adef __init__(self, player_id, contract_data):%0A%0A%0A
aef7c25964883bae893913524bc9ff3dc0bdcde3
Add a docker helper script (#18)
docker.py
docker.py
Python
0.000022
@@ -0,0 +1,1705 @@ +#!/usr/bin/env python3%0A%0Aimport argparse%0Aimport subprocess%0A%0AIMAGE_NAME = 'cargo-sphinx'%0A%0A%0Adef has_image(name):%0A cmd = %22docker images %7C awk '%7B%7Bprint $1%7D%7D' %7C grep '%5E%7Bname%7D$' %3E /dev/null%22.format(%0A name=name),%0A proc = subprocess.run(cmd, shell=True)%0A return proc.returncode == 0%0A%0A%0Adef main():%0A parser = argparse.ArgumentParser()%0A parser.add_argument('action', nargs='?',%0A help=%22Either 'build', 'shell', or 'docs'%22)%0A parser.add_argument('--nocache', action='store_true',%0A help=%22When building containers, don't use cached images.%22)%0A%0A args = parser.parse_args()%0A action = args.action%0A%0A if not has_image(IMAGE_NAME) or action == 'build':%0A run_build(IMAGE_NAME, nocache=args.nocache)%0A%0A if action == 'build':%0A return%0A%0A if action == 'shell':%0A run_shell(IMAGE_NAME)%0A elif action == 'docs':%0A run_docs(IMAGE_NAME)%0A else:%0A print(%22Unknown action '%7B%7D' specified.%22)%0A%0Adef run_build(image, nocache=False):%0A nocache_arg = %22--no-cache%22 if nocache else %22%22%0A cmd = %22docker build --rm=true -t %7Bname%7D %7Bnocache%7D .%22.format(%0A name=image, nocache=nocache_arg)%0A subprocess.run(cmd, shell=True, check=True)%0A%0Adef run_shell(image):%0A cmd = %22%22%22docker run -it %5C%5C%0A -v %22$(pwd):/%7Bname%7D%22 %5C%5C%0A --workdir=/%7Bname%7D %5C%5C%0A %7Bname%7D %5C%5C%0A /bin/bash%22%22%22.format(name=image)%0A subprocess.run(cmd, shell=True)%0A%0Adef run_docs(image):%0A cmd = %22%22%22docker run -it %5C%5C%0A -v %22$(pwd):/%7Bname%7D%22 %5C%5C%0A --workdir=/%7Bname%7D/docs %5C%5C%0A %7Bname%7D %5C%5C%0A make clean html%22%22%22.format(name=image)%0A subprocess.run(cmd, shell=True)%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
647fd44f829a308dc16eb86a663dc1a3719476ab
add solution for Search a 2D Matrix II
algorithms/searchA2DMatrixII/searchA2DMatrixII.py
algorithms/searchA2DMatrixII/searchA2DMatrixII.py
Python
0.000005
@@ -0,0 +1,452 @@ +class Solution:%0A # @param %7Binteger%5B%5D%5B%5D%7D matrix%0A # @param %7Binteger%7D target%0A # @return %7Bboolean%7D%0A%0A def searchMatrix(self, matrix, target):%0A n = len(matrix)%0A m = len(matrix%5B0%5D)%0A x = n-1%0A y = 0%0A while x %3E= 0 and y %3C m:%0A if matrix%5Bx%5D%5By%5D == target:%0A return True%0A if matrix%5Bx%5D%5By%5D %3E target:%0A x -= 1%0A else:%0A y += 1%0A return False%0A
17183883d3b70c909aeacecb57669ca718fcfe41
Replace return with exit, add ssh call
docker.py
docker.py
#!/usr/bin/env python2 from __future__ import print_function import os import os.path import logging from os.path import exists, join from shlex import split from sys import argv, exit from subprocess import call, check_output def symlink_force(source, link_name): """Equivalent to adding -f flag to bash invocation of ln""" if exists(link_name): os.remove(link_name) logging.info("Symlinking {} to {}".format(source, link_name)) os.symlink(source, link_name) def link_or_generate_ssh_keys(): """Ensures that valid ssh keys are symlinked to /root/.ssh""" if 'MANTL_SSH_KEY' not in os.environ: os.environ['MANTL_SSH_KEY'] = 'id_rsa' ssh_key = join(os.environ['MANTL_CONFIG_DIR'], os.environ['MANTL_SSH_KEY']) if not exists(ssh_key): call(split('ssh-keygen -N "" -f {}'.format(ssh_key))) symlink_force(ssh_key, '/root/.ssh/id_rsa') ssh_key += '.pub' symlink_force(ssh_key, '/root/.ssh/id_rsa.pub') def link_ci_terraform_file(): symlink_force(os.environ['TERRAFORM_FILE'], 'terraform.tf') def link_user_defined_terraform_files(): """Ensures that provided/chosen terraform files are symlinked""" # Symlink tf files in the config dir cfg_d = os.environ['MANTL_CONFIG_DIR'] tfs = [join(cfg_d, f) for f in os.listdir(cfg_d) if f.endswith('.tf')] if len(tfs): for tf in tfs: base = os.path.basename(tf) symlink_force(tf, base) else: # Symlink tf files based on provider if 'MANTL_PROVIDER' not in os.environ: logging.critical("mantl.readthedocs.org for provider") exit(1) tf = 'terraform/{}.sample.tf'.format(os.environ['MANTL_PROVIDER']) symlink_force(tf, 'mantl.tf') def link_ansible_playbook(): """Ensures that provided/sample ansible playbook is symlinked""" ansible_playbook = join(os.environ['MANTL_CONFIG_DIR'], 'mantl.yml') if not exists(ansible_playbook): ansible_playbook = 'sample.yml' symlink_force(ansible_playbook, 'mantl.yml') def link_or_generate_security_file(): """Ensures that security file exists and is symlinked""" security_file = join(os.environ['MANTL_CONFIG_DIR'], 'security.yml') if not exists(security_file): logging.info("Generating {} via security-setup".format(security_file)) call(split('./security-setup --enable=false')) else: symlink_force(security_file, 'security.yml') def ci_setup(): """Run all setup commands, saving files to MANTL_CONFIG_DIR""" link_or_generate_ssh_keys() link_ansible_playbook() link_or_generate_security_file() def terraform(): """Run terraform commands. Assumes that setup has been run""" link_or_generate_ssh_keys() call(split("ssh-add")) call(split("terraform get")) call(split("terraform apply -state=$TERRAFORM_STATE")) def ansible(): """Run ansible playbooks. Assumes that setup and terraform have been run""" link_or_generate_ssh_keys() call(split("ssh-add")) call(split("ansible-playbook playbooks/upgrade-packages.yml -e @security.yml")) call(split("ansible-playbook mantl.yml -e @security.yml")) def ci_build(): """Kick off a Continuous Integration job""" link_or_generate_ssh_keys() link_ci_terraform_file() # Filter out commits that are documentation changes. logging.info(os.environ['TRAVIS_REPO_SLUG']) commit_range_cmd = 'git diff --name-only {}'.format(os.environ['TRAVIS_COMMIT_RANGE']) commit_range_str = str(check_output(split(commit_range_cmd))) commit_range = [] for commit in commit_range_str.split(): if commit.startswith('docs'): logging.info("Modified file in docs directory: %s", commit) elif commit.endswith('md'): logging.info("Modified file has markdown extension: %s", commit) elif commit.endswith('rst'): logging.info("Modified file has reST extension: %s", commit) else: logging.info("Modified file not marked as docfile: %s", commit) commit_range.append(commit) if len(commit_range) < 1: logging.info("All of the changes I found were in documentation files. Skipping build") exit(0) # Filter out commits that are pushes to non-master branches ci_branch = os.environ['TRAVIS_BRANCH'] ci_is_pr = os.environ['TRAVIS_PULL_REQUEST'] if ci_branch is not 'master' and ci_is_pr is False: logging.info("We don't want to build on pushes to branches that aren't master.") exit(0) # TODO: add in check for forks with TRAVIS_REPO_SLUG if os.environ['TERRAFORM_FILE'] == 'OPENSTACK': logging.critical("SSHing into jump host to test OpenStack is currently being implemented") ssh_cmd = 'ssh -i /root/.ssh/openstack -p {} shatfiel@{} "echo testing 123"'.format(os.environ['OS_PRT'], os.environ['OS_IP']) with open('/root/.ssh/openstack', 'w') as key: key.write(os.environ['OS_KEY']) exit(call(split(ssh_cmd))) else: logging.info("Starting cloud provider test") return call(split("python2 testing/build-cluster.py")) def ci_destroy(): """Cleanup after ci_build""" link_or_generate_ssh_keys() link_ci_terraform_file() for i in range(2): returncode = call(split("terraform destroy --force")) return returncode if __name__ == "__main__": logfmt = "%(levelname)s\t%(asctime)s\t%(message)s" logging.basicConfig(format=logfmt, level=logging.INFO) if 'MANTL_CONFIG_DIR' not in os.environ: logging.critical('mantl.readthedocs.org for mantl config dir') exit(1) #TODO: replace this with either click or pypsi if len(argv) > 1: if argv[1] == 'ci-setup': ci_setup() elif argv[1] == 'terraform': terraform() elif argv[1] == 'ansible': ansible() elif argv[1] == 'deploy': setup() terraform() ansible() elif argv[1] == 'ci-build': ci_build() elif argv[1] == 'ci-destroy': ci_destroy() else: logging.critical("Usage: docker.py [CMD]") exit(1) else: logging.critical("Usage: docker.py [CMD]") exit(1)
Python
0.001123
@@ -5116,23 +5116,21 @@ -return +exit( call(spl @@ -5168,16 +5168,17 @@ er.py%22)) +) %0A%0A%0Adef c @@ -5378,15 +5378,13 @@ -return +exit( retu @@ -5389,16 +5389,17 @@ turncode +) %0A%0A%0Aif __
ada6128817769886e2869944fac3a8cea0b5b109
Add a missing module
pykmer/timer.py
pykmer/timer.py
Python
0.000048
@@ -0,0 +1,999 @@ +%22%22%22%0AThis module provides a simple timer class for instrumenting code.%0A%22%22%22%0A%0Aimport time%0A%0Aclass timer(object):%0A def __init__(self):%0A self.start = time.time()%0A self.sofar = 0.0%0A self.paused = False%0A self.events = 0%0A%0A def pause(self):%0A now = time.time()%0A self.sofar += now - self.start%0A self.paused = True%0A%0A def resume(self):%0A self.start = time.time()%0A self.paused = False%0A%0A def stop(self):%0A if not self.paused:%0A now = time.time()%0A self.sofar += now - self.start%0A%0A def tick(self, n = 1):%0A self.events += n%0A%0A def reset(self):%0A self.start = time.time()%0A self.sofar = 0%0A self.paused = False%0A%0A def time(self):%0A sofar = self.sofar%0A if not self.paused:%0A now = time.time()%0A sofar += now - self.start%0A return sofar%0A%0A def rate(self, n = None):%0A if n is None:%0A n = self.events%0A return n / self.time()%0A
6e767e8f5b219d9883fb1a16846830efabac7d5b
Add python
python/hello.py
python/hello.py
Python
0.998925
@@ -0,0 +1,23 @@ +print(%22Hello, World!%22)%0A
01472504fc42137a05a85ae5ad6d4b7956865680
Add autosolver for regex.
quiz/5-regex.py
quiz/5-regex.py
Python
0
@@ -0,0 +1,2486 @@ +#!/usr/bin/env python3%0A%0A%0Adef make_array(text):%0A import re%0A regex = re.compile('(%5Cd+)-%3E(%5Cd+)')%0A pairs = regex.findall(text)%0A ret = list()%0A for (src, dst) in pairs:%0A src = int(src)%0A dst = int(dst)%0A ret.append((src, dst))%0A return ret%0A%0A%0Adef make_transitive_closure(states, eps_trans):%0A while True:%0A changed = False%0A for src in range(len(states)):%0A for dst in eps_trans%5Bsrc%5D:%0A if dst not in states:%0A states.add(dst)%0A changed = True%0A if not changed:%0A return states%0A%0A%0Adef make_epsilon_transition(regex):%0A trans = list(map(lambda x: set(), range(len(regex))))%0A stack = %5B%5D%0A%0A for i in range(len(regex)):%0A c = regex%5Bi%5D%0A group_begin = i%0A%0A if c == '(':%0A trans%5Bi%5D.add(i + 1)%0A stack.append(i)%0A elif c == '%7C':%0A stack.append(i)%0A elif c == ')':%0A trans%5Bi%5D.add(i + 1)%0A top = stack.pop()%0A if regex%5Btop%5D == '(':%0A group_begin = top%0A elif regex%5Btop%5D == '%7C':%0A group_begin = stack.pop()%0A trans%5Bgroup_begin%5D.add(top + 1)%0A trans%5Btop%5D.add(i)%0A elif c == '*':%0A trans%5Bi%5D.add(i + 1)%0A%0A if i + 1 %3C len(regex) and regex%5Bi + 1%5D == '*':%0A trans%5Bgroup_begin%5D.add(i + 1)%0A trans%5Bi + 1%5D.add(group_begin)%0A%0A return trans%0A%0A%0Adef solve_q1(regex, query):%0A eps_trans = make_epsilon_transition(regex)%0A states = set()%0A states.add(0)%0A make_transitive_closure(states, eps_trans)%0A%0A for i in query:%0A new_states = set()%0A for st in states:%0A if st == len(regex):%0A continue%0A if i == regex%5Bst%5D:%0A new_states.add(st + 1)%0A states = make_transitive_closure(new_states, eps_trans)%0A%0A for i in list(states):%0A print(i, end=' ')%0A print()%0A%0A%0Adef solve_q2(regex, queries):%0A eps_trans = make_epsilon_transition(regex)%0A for q in queries:%0A if q%5B1%5D in eps_trans%5Bq%5B0%5D%5D:%0A print('y', end=' ')%0A else:%0A print('n', end=' ')%0A print()%0A%0Aq1_regex = ' ( ( A %7C ( C * B ) ) * A ) '%0Aq1_query = ' A B B A B C '%0A%0Aq2_regex = ' ( A ( ( C D * ) * %7C B ) ) '%0Aq2_query = '''%0A%0A%0A%0A8-%3E3%0A%0A10-%3E12%0A%0A7-%3E5%0A%0A4-%3E9%0A%0A0-%3E1%0A%0A2-%3E10%0A%0A3-%3E8%0A%0A'''%0A%0Asolve_q1(q1_regex.replace(' ', ''),%0A q1_query.replace(' ', ''))%0Asolve_q2(q2_regex.replace(' ', ''), make_array(q2_query))%0A
2c1b5aedc5f4503a738ef7e9ffa0a7f969fecfef
add argparse example
Python/calculator_argp.py
Python/calculator_argp.py
Python
0.000032
@@ -0,0 +1,803 @@ +import argparse%0A%0A%0Adef main():%0A parser = argparse.ArgumentParser(description='Calculate two input numbers')%0A parser.add_argument(%0A 'first', metavar='int', type=int,%0A help='first number')%0A parser.add_argument(%0A 'oper', metavar='oper', type=str, %0A help='operator +, - or * ')%0A parser.add_argument(%0A 'second', metavar='int', type=int,%0A help='second number')%0A args = parser.parse_args()%0A%0A first = int(args.first)%0A second = int(args.second)%0A oper = args.oper%0A%0A res = ''%0A%0A if oper == '+':%0A res = first + second%0A elif oper == '-':%0A res = first - second%0A elif oper == '*':%0A res = first * second%0A else:%0A print %22Not supported%22%0A%0A print res%0A%0Aif __name__ == %22__main__%22:%0A main()%0A
ed5f68211e93df983a5e15c7f1ce812b810b49c0
Add ANTs package (#7717)
var/spack/repos/builtin/packages/ants/package.py
var/spack/repos/builtin/packages/ants/package.py
Python
0
@@ -0,0 +1,2207 @@ +##############################################################################%0A# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, [email protected], All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/llnl/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass Ants(CMakePackage):%0A %22%22%22ANTs extracts information from complex datasets that include imaging.%0A Paired with ANTsR (answer), ANTs is useful for managing, interpreting%0A and visualizing multidimensional data. ANTs is popularly considered a%0A state-of-the-art medical image registration and segmentation toolkit.%0A ANTs depends on the Insight ToolKit (ITK), a widely used medical image%0A processing library to which ANTs developers contribute.%0A %22%22%22%0A%0A homepage = %22http://stnava.github.io/ANTs/%22%0A url = %22https://github.com/ANTsX/ANTs/archive/v2.2.0.tar.gz%22%0A%0A version('2.2.0', '5661b949268100ac0f7baf6d2702b4dd')%0A%0A def install(self, spec, prefix):%0A with working_dir(join_path('spack-build', 'ANTS-build'), create=False):%0A make(%22install%22)%0A install_tree('Scripts', prefix.bin)%0A%0A def setup_environment(self, spack_env, run_env):%0A run_env.set('ANTSPATH', self.prefix.bin)%0A
744cedc7e999f96aa0646bb43c039882991228ae
Add Asio package (#24485)
var/spack/repos/builtin/packages/asio/package.py
var/spack/repos/builtin/packages/asio/package.py
Python
0
@@ -0,0 +1,2404 @@ +# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0Aimport os.path%0A%0A%0Aclass Asio(AutotoolsPackage):%0A %22%22%22C++ library for network and low-level I/O programming.%22%22%22%0A%0A homepage = %22http://think-async.com/Asio/%22%0A url = %22https://github.com/chriskohlhoff/asio/archive/1.18.2.tar.gz%22%0A git = %22https://github.com/chriskohlhoff/asio.git%22%0A maintainers = %5B%22msimberg%22%5D%0A%0A version(%0A %221.18.2%22,%0A sha256=%228d67133b89e0f8b212e9f82fdcf1c7b21a978d453811e2cd941c680e72c2ca32%22,%0A )%0A%0A depends_on(%22autoconf%22, type=%22build%22)%0A depends_on(%22automake%22, type=%22build%22)%0A depends_on(%22m4%22, type=%22build%22)%0A depends_on(%22libtool%22, type=%22build%22)%0A%0A stds = (%2211%22, %2214%22, %2217%22)%0A variant(%0A %22cxxstd%22,%0A default=%2211%22,%0A values=stds,%0A multi=False,%0A description=%22Use the specified C++ standard when building.%22,%0A )%0A%0A variant(%0A %22separate_compilation%22,%0A default=False,%0A description=%22Compile Asio sources separately%22,%0A )%0A%0A variant(%0A %22boost_coroutine%22,%0A default=False,%0A description=%22Enable support for Boost.Coroutine.%22,%0A )%0A depends_on(%22boost +context +coroutine%22, when=%22+boost_coroutine%22)%0A%0A variant(%22boost_regex%22, default=False, description=%22Enable support for Boost.Regex.%22)%0A depends_on(%22boost +regex%22, when=%22+boost_regex%22)%0A%0A for std in stds:%0A depends_on(%22boost cxxstd=%22 + std, when=%22cxxstd=%7B0%7D %5Eboost%22.format(std))%0A%0A def configure_args(self):%0A variants = self.spec.variants%0A%0A args = %5B%0A %22CXXFLAGS=-std=c++%7B0%7D%22.format(variants%5B%22cxxstd%22%5D.value),%0A %5D%0A%0A if variants%5B%22separate_compilation%22%5D.value:%0A args.append(%22--enable-separate-compilation%22)%0A%0A if variants%5B%22boost_coroutine%22%5D.value:%0A args.append(%22--enable-boost-coroutine%22)%0A%0A if variants%5B%22boost_coroutine%22%5D.value or variants%5B%22boost_regex%22%5D.value:%0A args.append(%22--with-boost=%7Bself.spec%5B'boost'%5D.prefix%7D%22)%0A%0A return args%0A%0A def url_for_version(self, version):%0A return %22https://github.com/chriskohlhoff/asio/archive/asio-%7B0%7D.tar.gz%22.format(%0A version.dashed%0A )%0A%0A @property%0A def configure_directory(self):%0A return os.path.join(self.stage.source_path, %22asio%22)%0A
b1feed0ced6d1328cc39bc9bba36331ec6da7803
Add ban for pgp/gpg private key blocks
pre_commit_hooks/detect_private_key.py
pre_commit_hooks/detect_private_key.py
from __future__ import print_function import argparse import sys BLACKLIST = [ b'BEGIN RSA PRIVATE KEY', b'BEGIN DSA PRIVATE KEY', b'BEGIN EC PRIVATE KEY', b'BEGIN OPENSSH PRIVATE KEY', b'BEGIN PRIVATE KEY', b'PuTTY-User-Key-File-2', b'BEGIN SSH2 ENCRYPTED PRIVATE KEY', ] def detect_private_key(argv=None): parser = argparse.ArgumentParser() parser.add_argument('filenames', nargs='*', help='Filenames to check') args = parser.parse_args(argv) private_key_files = [] for filename in args.filenames: with open(filename, 'rb') as f: content = f.read() if any(line in content for line in BLACKLIST): private_key_files.append(filename) if private_key_files: for private_key_file in private_key_files: print('Private key found: {}'.format(private_key_file)) return 1 else: return 0 if __name__ == '__main__': sys.exit(detect_private_key())
Python
0
@@ -294,16 +294,52 @@ E KEY',%0A + b'BEGIN PGP PRIVATE KEY BLOCK',%0A %5D%0A%0A%0Adef
6b9b9642ca09f3b33bdf61bb5dacbaa7c29de8fc
Create __main__.py
src/__main__.py
src/__main__.py
Python
0.000164
@@ -0,0 +1 @@ +%0A
a58a7f3206168ae98b952e804404c46b89e81640
Add a snippet (Pillow).
python/pil/python3_pillow_fork/show.py
python/pil/python3_pillow_fork/show.py
Python
0.000001
@@ -0,0 +1,1394 @@ +#!/usr/bin/env python3%0A# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2015 J%C3%A9r%C3%A9mie DECOCK (http://www.jdhp.org)%0A%0A# Permission is hereby granted, free of charge, to any person obtaining a copy%0A# of this software and associated documentation files (the %22Software%22), to deal%0A# in the Software without restriction, including without limitation the rights%0A# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell%0A# copies of the Software, and to permit persons to whom the Software is%0A# furnished to do so, subject to the following conditions:%0A%0A# The above copyright notice and this permission notice shall be included in%0A# all copies or substantial portions of the Software.%0A %0A# THE SOFTWARE IS PROVIDED %22AS IS%22, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR%0A# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,%0A# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE%0A# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER%0A# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,%0A# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN%0A# THE SOFTWARE.%0A%0Aimport PIL.Image as pil_img # PIL.Image is a module not a class...%0A%0Adef main():%0A %22%22%22Main function%22%22%22%0A%0A img = pil_img.open(%22lenna.png%22) # It works also with .jpg, ...%0A img.show()%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
21f789eb05788fcaf0be1960b3c1171437d8a299
Replace Dict by Mapping.
zerver/lib/session_user.py
zerver/lib/session_user.py
from __future__ import absolute_import from django.contrib.auth import SESSION_KEY, get_user_model from django.contrib.sessions.models import Session from typing import Dict, Optional from six import text_type def get_session_dict_user(session_dict): # type: (Dict[text_type, int]) -> Optional[int] # Compare django.contrib.auth._get_user_session_key try: return get_user_model()._meta.pk.to_python(session_dict[SESSION_KEY]) except KeyError: return None def get_session_user(session): # type: (Session) -> int return get_session_dict_user(session.get_decoded())
Python
0
@@ -164,20 +164,23 @@ import -Dict +Mapping , Option @@ -268,12 +268,15 @@ e: ( -Dict +Mapping %5Btex
7037762247bd40455eb1944dc21684561c5f97ba
add a __init__ file
dataScraping/__init__.py
dataScraping/__init__.py
Python
0.000342
@@ -0,0 +1,22 @@ +#!/usr/bin/env python%0A
2b4544820bf6549bc172f8d5b3532a9103190920
add utility I used to generate random ph and temp readings
utils/generate_random_values.py
utils/generate_random_values.py
Python
0
@@ -0,0 +1,320 @@ +import random%0Aph = %5Brandom.uniform(0, 14) for x in range(30000)%5D%0Atemp = %5Brandom.uniform(55, 90) for x in range(30000)%5D%0Atemp_file = open('temp.csv', 'w+')%0Aph_file = open('ph.csv', 'w+')%0Afor x in range(len(temp)):%0A temp_file.write(%22%25.2f,%22 %25 temp%5Bx%5D)%0A ph_file.write(%22%25.2f,%22 %25 ph%5Bx%5D)%0Atemp_file.close()%0Aph_file.close()%0A
4883bd13c6e07a0568c29fd26a141888b52292b7
Add retriever object for player draft information
utils/player_draft_retriever.py
utils/player_draft_retriever.py
Python
0
@@ -0,0 +1,1467 @@ +#!/usr/bin/env python%0A# -*- coding: utf-8 -*-%0A%0Aimport re%0A%0Aimport requests%0Afrom lxml import html%0A%0Afrom db.team import Team%0Afrom db.player_draft import PlayerDraft%0A%0Aclass PlayerDraftRetriever():%0A%0A NHL_PLAYER_DRAFT_PREFIX = %22https://www.nhl.com/player%22%0A DRAFT_INFO_REGEX = re.compile(%0A %22(%5Cd%7B4%7D)%5Cs(.+),%5Cs(%5Cd+).+%5Csrd,.+%5C((%5Cd+).+%5Csoverall%5C)%22)%0A%0A def __init__(self):%0A pass%0A%0A def retrieve_draft_information(self, player_id):%0A%0A url = %22/%22.join((self.NHL_PLAYER_DRAFT_PREFIX, str(player_id)))%0A r = requests.get(url)%0A doc = html.fromstring(r.text)%0A%0A raw_draft_info = doc.xpath(%0A %22//li%5B@class='player-bio__item'%5D/span%5Btext() = %22 +%0A %22'Draft:'%5D/parent::li/text()%22)%0A%0A if not raw_draft_info:%0A print(%22No draft information found%22)%0A return%0A%0A raw_draft_info = raw_draft_info.pop()%0A print(raw_draft_info)%0A%0A match = re.search(self.DRAFT_INFO_REGEX, raw_draft_info)%0A if match:%0A year = int(match.group(1))%0A team = Team.find_by_orig_abbr(match.group(2))%0A round = int(match.group(3))%0A overall = int(match.group(4))%0A draft_info = PlayerDraft(%0A player_id, team.team_id, year, round, overall)%0A%0A draft_info_db = PlayerDraft.find_by_player_id(player_id)%0A%0A if draft_info_db:%0A if draft_info_db != draft_info:%0A draft_info_db.update(draft_info)%0A
a5e18330ac84a93b9a3ffe7d8493c401d3ade11e
Create version.py
nilmtk/version.py
nilmtk/version.py
Python
0.000001
@@ -0,0 +1,18 @@ +version = '0.1.0'%0A
776350aaaed8a8e3f00a492c1a1735c24f595d89
add config_dialog.py
dialogs/config_dialog.py
dialogs/config_dialog.py
Python
0.000003
@@ -0,0 +1,1994 @@ +#-*- coding: utf-8 -*-%0Afrom win32ui import IDD_SET_TABSTOPS%0Afrom win32ui import IDC_EDIT_TABS%0Afrom win32ui import IDC_PROMPT_TABS%0Afrom win32con import IDOK%0Afrom win32con import IDCANCEL%0A%0Aimport win32ui%0Aimport win32con%0A%0Afrom pywin.mfc import dialog%0A%0AIDC_EDIT_USERNAME = 2000%0AIDC_EDIT_PASSWORD = 2001%0A%0A%0Adef ConfigDialogTemplate():%0A style = win32con.DS_SETFONT %7C win32con.DS_MODALFRAME %7C win32con.DS_FIXEDSYS %7C win32con.WS_POPUP %7C win32con.WS_VISIBLE %7C win32con.WS_CAPTION %7C win32con.WS_SYSMENU%0A cs = win32con.WS_CHILD %7C win32con.WS_VISIBLE%0A listCs = cs %7C win32con.LBS_NOINTEGRALHEIGHT %7C win32con.WS_VSCROLL %7C win32con.WS_TABSTOP%0A%0A dlg = %5B%5Bu'%E8%BE%93%E5%85%A5%E7%94%A8%E6%88%B7%E5%90%8D%E5%AF%86%E7%A0%81', (0, 0, 200, 75), style, None, (8, %22MS Sans Serif%22)%5D, %5D%0A s = cs %7C win32con.CBS_DROPDOWN %7C win32con.WS_VSCROLL %7C win32con.WS_TABSTOP%0A%0A dlg.append(%5B130, u%22%E8%B4%A6%E5%8F%B7:%22, -1, (30, 10, 50, 10), cs %7C win32con.SS_LEFT%5D)%0A dlg.append(%5B%22EDIT%22, %22%22, IDC_EDIT_USERNAME, (70, 8, 100, 12), cs%5D)%0A%0A dlg.append(%5B130, u%22%E5%AF%86%E7%A0%81:%22, -1, (30, 30, 50, 30), cs %7C win32con.SS_LEFT%5D)%0A dlg.append(%5B%22EDIT%22, %22%22, IDC_EDIT_PASSWORD, (70, 30, 100, 12), cs%5D)%0A%0A s = cs %7C win32con.WS_TABSTOP%0A dlg.append(%5B128, u%22%E7%A1%AE%E8%AE%A4%22, win32con.IDOK, (30, 50, 50, 15), s %7C win32con.BS_DEFPUSHBUTTON%5D)%0A%0A s = win32con.BS_PUSHBUTTON %7C s%0A dlg.append(%5B128, u%22%E5%8F%96%E6%B6%88%22, win32con.IDCANCEL, (120, 50, 50, 15), s%5D)%0A return dlg%0A%0A%0Aclass ConfigDialog(dialog.Dialog):%0A def __init__(self):%0A dialog.Dialog.__init__(self, ConfigDialogTemplate())%0A self.DoModal()%0A%0A def OnInitDialog(self):%0A self.username_control = self.GetDlgItem(IDC_EDIT_USERNAME)%0A self.password_control = self.GetDlgItem(IDC_EDIT_PASSWORD)%0A%0A def OnDestroy(self, msg):%0A del self.username_control%0A del self.password_control%0A%0A def OnOK(self):%0A if self.username_control.GetLine() and self.password_control.GetLine():%0A self.username = self.username_control.GetLine()%0A self.password = self.password_control.GetLine()%0A self._obj_.OnOK()%0A
42faf76ffe421802e628dd2a79f518765d43284b
Create recordsCheck.py
recordsCheck.py
recordsCheck.py
Python
0
@@ -0,0 +1,2282 @@ +import tensorflow as tf%0Aimport glob as glob%0Aimport getopt%0Aimport sys%0Aimport cPickle as pkl%0Aimport numpy as np%0Aimport time%0A%0Aopts, _ = getopt.getopt(sys.argv%5B1:%5D,%22%22,%5B%22input_dir=%22, %22input_file=%22, %22output_file=%22%5D)%0Ainput_dir = %22/data/video_level_feat_v3/%22%0Ainput_file = %22%22%0Aoutput_file = %22%22%0Aprint(opts)%0Afor opt, arg in opts:%0A if opt in (%22--input_dir%22):%0A input_dir = arg%0A if opt in (%22--input_file%22):%0A input_file = arg%0A if opt in (%22--output_file%22):%0A output_file = arg%0A%0Af = open(input_dir, 'rb')%0Afilepaths = pkl.load(f)%0Af.close()%0A%0Afilepaths = %5Binput_dir+x for x in filepaths%5D%0A%0Afeatures_format = %7B%7D%0Afeature_names = %5B%5D%0Afor x in %5B'q0', 'q1', 'q2', 'q3', 'q4', 'mean', 'stddv', 'skew', 'kurt', 'iqr', 'rng', 'coeffvar', 'efficiency'%5D:%0A features_format%5Bx + '_rgb_frame'%5D = tf.FixedLenFeature(%5B1024%5D, tf.float32)%0A features_format%5Bx + '_audio_frame'%5D = tf.FixedLenFeature(%5B128%5D, tf.float32)%0A feature_names.append(str(x + '_rgb_frame'))%0A feature_names.append(str(x + '_audio_frame'))%0A%0Afeatures_format%5B'video_id'%5D = tf.FixedLenFeature(%5B%5D, tf.string)%0Afeatures_format%5B'labels'%5D = tf.VarLenFeature(tf.int64)%0Afeatures_format%5B'video_length'%5D = tf.FixedLenFeature(%5B%5D, tf.float32)%0A%0Astart_time = time.time()%0Aerrors = %5B%5D%0Acounter = 0%0Afor filepath in filepaths:%0A print(counter)%0A counter += 1%0A filepaths_queue = tf.train.string_input_producer(%5Bfilepath%5D, num_epochs=1)%0A reader = tf.TFRecordReader()%0A _, serialized_example = reader.read(filepaths_queue)%0A %0A features = tf.parse_single_example(serialized_example,features=features_format)%0A%0A with tf.Session() as sess:%0A init_op = tf.group(tf.global_variables_initializer(),tf.local_variables_initializer())%0A sess.run(init_op)%0A coord = tf.train.Coordinator()%0A threads = tf.train.start_queue_runners(coord=coord)%0A try:%0A while True:%0A proc_features, = sess.run(%5Bfeatures%5D)%0A except tf.errors.OutOfRangeError, e:%0A coord.request_stop(e)%0A except:%0A print(%22ERROR : %22+filepath)%0A errors.append(filepath)%0A finally:%0A print(time.time() - start_time)%0A coord.request_stop()%0A coord.join(threads)%0A %0Af = open(output_file, 'wb')%0Apkl.dump(errors, f, protocol=pkl.HIGHEST_PROTOCOL)%0Apkl.dump(counter, f, protocol=pkl.HIGHEST_PROTOCOL)%0Af.close()%0A
f4bd76b7ebe376a2a0cea0ac1a44be4d741ce5c5
Create LeetCode-541.py
LeetCode-541.py
LeetCode-541.py
Python
0
@@ -0,0 +1,490 @@ +import math%0A%0Aclass Solution(object):%0A def ReverseStr(self, str, k):%0A ans=''%0A n = int (math.ceil(len(str) / (2.0*k) ))%0A for i in range(n):%0A ans += str%5B2*i*k:(2*i+1)*k%5D%5B::-1%5D #reverse k str%0A print '1',ans%0A ans += str%5B(2*i+1)*k:(2*i+2)*k%5D%0A print '2',ans%0A return ans%0A%0A%0A%0Ars=Solution()%0Aprint rs.ReverseStr('sjodfjoig',3)%0A%0As='sjodfjoig'%0Aprint s%5B0:1%5D%0A%0Aa=''%0Aa += s%5B8:20%5D%0Aprint s%5B10%5D #why???%0Aprint s%5B10:12%5D #%0Aprint 'a=',a%0A
ed1dd068e41138f1f3b18b028e20e542965d2c7f
add word_dictionary.py task from week7
Algo-1/week7/1-Word-Dictionary/word_dictionary.py
Algo-1/week7/1-Word-Dictionary/word_dictionary.py
Python
0.999988
@@ -0,0 +1,2362 @@ +class WordDictionary:%0A%0A class Node:%0A%0A def __init__(self, char):%0A # char is a substring of the phone number%0A self.char = char%0A # 10 digits%0A self.children_nodes = %5BNone for i in range(26)%5D%0A self.isTerminal = False%0A%0A def get_char(self):%0A return self.char%0A%0A def add_node(self, node):%0A index = ord(node.char%5B0%5D) - 97%0A self.children_nodes%5Bindex%5D = node%0A%0A def get_node(self, char):%0A index = ord(char) - 97%0A return self.children_nodes%5Bindex%5D%0A%0A def __repr__(self):%0A return self.char%0A%0A def insert(self, string):%0A current_node = self.root%0A%0A for index in range(len(string)):%0A char = string%5Bindex%5D%0A result_node = current_node.get_node(char)%0A%0A if result_node is None:%0A new_node = WordDictionary.Node(string%5Bindex:%5D)%0A if index == len(string) - 1:%0A new_node.isTerminal = True%0A%0A current_node.add_node(new_node)%0A current_node = new_node%0A else:%0A current_node = result_node%0A return self.root%0A%0A def contains(self, phone_number):%0A root = self.root%0A index = 1%0A phone_number = str(phone_number)%0A current_node = root.get_node(phone_number%5Bindex - 1%5D)%0A while current_node is not None and index %3C len(phone_number):%0A current_node = current_node.get_node(phone_number%5Bindex%5D)%0A index += 1%0A # print(current_node)%0A if current_node is not None:%0A return True%0A return False%0A%0A def __init__(self):%0A self.root = WordDictionary.Node('')%0A%0A%0Adef main():%0A w = WordDictionary()%0A # w.insert('alabala')%0A # w.insert('asdf')%0A # print(w.contains('alabala'))%0A # w.insert('aladin')%0A # print(w.contains('asdf'))%0A # print(w.contains('aladin'))%0A # w.insert('circle')%0A # print(w.contains('rectangle'))%0A # print(w.contains('square'))%0A%0A N = int(input())%0A%0A while N != 0:%0A c = input()%0A command = c.split()%0A%0A if command%5B0%5D == 'insert':%0A w.insert(command%5B1%5D)%0A elif command%5B0%5D == 'contains':%0A print(w.contains(command%5B1%5D))%0A else:%0A pass%0A%0A N -= 1%0A%0A%0Aif __name__ == '__main__':%0A main()%0A
a71b50f4b6a3bc1e760e3796f8c14f6c3e865a34
replace identity translators with None
modularodm/translators/__init__.py
modularodm/translators/__init__.py
from dateutil import parser as dateparser from bson import ObjectId class DefaultTranslator(object): null_value = None def to_default(self, value): return value def from_default(self, value): return value def to_ObjectId(self, value): return str(value) def from_ObjectId(self, value): return ObjectId(value) class JSONTranslator(DefaultTranslator): def to_datetime(self, value): return str(value) def from_datetime(self, value): return dateparser.parse(value) class StringTranslator(JSONTranslator): null_value = 'none' def to_default(self, value): return str(value) def from_int(self, value): return int(value) def from_float(self, value): return float(value) def from_bool(self, value): return bool(value)
Python
0.999999
@@ -119,28 +119,24 @@ = None%0A%0A -def to_default(s @@ -137,100 +137,81 @@ ault -(self, value):%0A return value%0A%0A def from_default(self, value):%0A return value + = None%0A from_default = None%0A%0Aclass JSONTranslator(DefaultTranslator): %0A%0A @@ -219,24 +219,24 @@ def to_ -ObjectId +datetime (self, v @@ -282,24 +282,24 @@ ef from_ -ObjectId +datetime (self, v @@ -324,65 +324,31 @@ urn -ObjectId(value)%0A%0Aclass JSONTranslator(DefaultTranslator): +dateparser.parse(value) %0A%0A @@ -352,32 +352,32 @@ %0A def to_ -datetime +ObjectId (self, value @@ -415,32 +415,32 @@ def from_ -datetime +ObjectId (self, value @@ -457,32 +457,24 @@ return -dateparser.parse +ObjectId (value)%0A
bb785321cbb9d372f2009a4577404ae75fbd889a
exclude TestApp from cppcheck script
Scripts/cppcheck/cppcheck.py
Scripts/cppcheck/cppcheck.py
# run from root sources directory: python Scripts/cppcheck/cppcheck.py import os ignoredEndings = ["is never used", "It is safe to deallocate a NULL pointer", "Throwing exception in destructor"] ignoredContent = ["MyGUI_UString"] def isIgnoredWarning(warning): for ignore in ignoredEndings: if warning.endswith(ignore): return True for ignore in ignoredContent: if warning.find(ignore) != -1: return True return False def parseOutput(): file = open("temp.cppcheck", 'r') line = file.readline() while line != "": line = line[0:len(line)-1] if (not isIgnoredWarning(line)): print line line = file.readline() file.close () def checkFolderSources(folder) : os.system("cppcheck --enable=all -I Scripts/cppcheck " + folder + " 2>temp.cppcheck") parseOutput() #checkFolderSources('MyGUIEngine') os.system("cppcheck --enable=all -I Scripts/cppcheck -I MyGUIEngine/include MyGUIEngine/src 2>temp.cppcheck") parseOutput() checkFolderSources('Demos') checkFolderSources('Tools') checkFolderSources('UnitTests') checkFolderSources('Common') #checkFolderSources('Platforms/OpenGL') # include temporary disabled due to cppcheck bug #os.system("cppcheck --enable=all -I Scripts/cppcheck -I Platforms/OpenGL/OpenGLPlatform/include Platforms/OpenGL/OpenGLPlatform/src 2>temp.cppcheck") os.system("cppcheck --enable=all -I Scripts/cppcheck Platforms/OpenGL/OpenGLPlatform/src 2>temp.cppcheck") parseOutput() #checkFolderSources('Platforms/Ogre') os.system("cppcheck --enable=all -I Scripts/cppcheck -I Platforms/Ogre/OgrePlatform/include Platforms/Ogre/OgrePlatform/src 2>temp.cppcheck") parseOutput() #checkFolderSources('Platforms/DirectX') os.system("cppcheck --enable=all -I Scripts/cppcheck -I Platforms/DirectX/DirectXPlatform/include Platforms/DirectX/DirectXPlatform/src 2>temp.cppcheck") parseOutput() checkFolderSources('Plugins') checkFolderSources('Wrapper')
Python
0.000001
@@ -1027,16 +1027,27 @@ nitTests +/UnitTest_* ')%0Acheck
bc34d530f4a21b5f06228d626f446c617b9c8876
Add example that mirrors defconfig and oldconfig.
examples/defconfig_oldconfig.py
examples/defconfig_oldconfig.py
Python
0
@@ -0,0 +1,838 @@ +# Produces exactly the same output as the following script:%0A#%0A# make defconfig%0A# echo CONFIG_ETHERNET=n %3E%3E .config%0A# make oldconfig%0A# echo CONFIG_ETHERNET=y %3E%3E .config%0A# yes n %7C make oldconfig%0A#%0A# This came up in https://github.com/ulfalizer/Kconfiglib/issues/15.%0A%0Aimport kconfiglib%0Aimport sys%0A%0Aconf = kconfiglib.Config(sys.argv%5B1%5D)%0A%0A# Mirrors defconfig%0Aconf.load_config(%22arch/x86/configs/x86_64_defconfig%22)%0Aconf.write_config(%22.config%22)%0A%0A# Mirrors the first oldconfig%0Aconf.load_config(%22.config%22)%0Aconf%5B%22ETHERNET%22%5D.set_user_value('n')%0Aconf.write_config(%22.config%22)%0A%0A# Mirrors the second oldconfig%0Aconf.load_config(%22.config%22)%0Aconf%5B%22ETHERNET%22%5D.set_user_value('y')%0Afor s in conf:%0A if s.get_user_value() is None and 'n' in s.get_assignable_values():%0A s.set_user_value('n')%0A%0A# Write the final configuration%0Aconf.write_config(%22.config%22)%0A
7c270e2fb5e3169f179e045cc58fdd4d58672859
add fixCAs.py to master
fixCAs.py
fixCAs.py
Python
0
@@ -0,0 +1,405 @@ +import sys%0Afrom valuenetwork.valueaccounting.models import *%0A%0Aagents = EconomicAgent.objects.all()%0A%0A#import pdb; pdb.set_trace()%0A%0Acount = 0%0Afor agent in agents:%0A agent.is_context = agent.agent_type.is_context%0A try:%0A agent.save()%0A count = count + 1%0A except:%0A print %22Unexpected error:%22, sys.exc_info()%5B0%5D%0A %0Aprint %22count = %22 + str(count)%0A %0A%0A %0A %0A%0A
38f90c31f6a0f4459a8ba2f96205d80588b384c5
Add CollectDict (incomplete dicts)
calvin/actorstore/systemactors/json/CollectDict.py
calvin/actorstore/systemactors/json/CollectDict.py
Python
0
@@ -0,0 +1,1500 @@ +# -*- coding: utf-8 -*-%0A%0A# Copyright (c) 2017 Ericsson AB%0A#%0A# Licensed under the Apache License, Version 2.0 (the %22License%22);%0A# you may not use this file except in compliance with the License.%0A# You may obtain a copy of the License at%0A#%0A# http://www.apache.org/licenses/LICENSE-2.0%0A#%0A# Unless required by applicable law or agreed to in writing, software%0A# distributed under the License is distributed on an %22AS IS%22 BASIS,%0A# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A# See the License for the specific language governing permissions and%0A# limitations under the License.%0A%0Afrom calvin.actor.actor import Actor, ActionResult, condition, manage%0A%0Afrom calvin.utilities.calvinlogger import get_actor_logger%0A_log = get_actor_logger(__name__)%0A%0Aclass CollectDict(Actor):%0A %22%22%22%0A Collect tokens from token port, forming a dict according to mapping. May produce%0A a partial dictionary.%0A%0A Inputs:%0A token(routing=%22collect-any-tagged%22): token%0A Outputs:%0A dict : Collected dictionary according to 'mapping' %0A %22%22%22%0A%0A @manage(%5B'mapping'%5D)%0A def init(self, mapping):%0A self.mapping = mapping%0A%0A def will_start(self):%0A self.inports%5B'token'%5D.set_config(%7B'port-mapping':self.mapping%7D)%0A%0A @condition(%5B'token'%5D, %5B'dict'%5D)%0A def collect_tokens(self, token):%0A _log.info(%22token: %25r%22 %25 (token,))%0A return ActionResult(production=(token,))%0A%0A action_priority = (collect_tokens, )%0A%0A test_args = %5B%5D%0A test_kwargs = %7B'select':%7B%7D%7D%0A
625139f9d3e5c06f4e5b355eaa070389f9a81954
Add utils module
website/addons/dropbox/utils.py
website/addons/dropbox/utils.py
Python
0.000001
@@ -0,0 +1,1041 @@ +# -*- coding: utf-8 -*-%0Aimport os%0Afrom website.project.utils import get_cache_content%0A%0Afrom website.addons.dropbox.client import get_node_addon_client%0A%0A%0Adef get_file_name(path):%0A return os.path.split(path.strip('/'))%5B1%5D%0A%0A%0A# TODO(sloria): TEST ME%0Adef render_dropbox_file(file_obj, client=None):%0A # Filename for the cached MFR HTML file%0A cache_name = file_obj.get_cache_filename(client=client)%0A node_settings = file_obj.node.get_addon('dropbox')%0A rendered = get_cache_content(node_settings, cache_name)%0A if rendered is None: # not in MFR cache%0A dropbox_client = client or get_node_addon_client(node_settings)%0A file_response, metadata = dropbox_client.get_file_and_metadata(file_obj.path)%0A rendered = get_cache_content(%0A node_settings=node_settings,%0A cache_file=cache_name,%0A start_render=True,%0A file_path=get_file_name(file_obj.path),%0A file_content=file_response.read(),%0A download_path=file_obj.download_url%0A )%0A return rendered%0A
821a3826110ecfc64ab431b7028af3aae8aa80db
Add 20150522 question.
LeetCode/house_robbers.py
LeetCode/house_robbers.py
Python
0.000001
@@ -0,0 +1,853 @@ +%22%22%22%0AYou are a professional robber planning to rob houses along a street. Each house%0Ahas a certain amount of money stashed, the only constraint stopping you from%0Arobbing each of them is that adjacent houses have security system connected and%0Ait will automatically contact the police if two adjacent houses were broken%0Ainto on the same night.%0A%0AGiven a list of non-negative integers representing the amount of money of each%0Ahouse, determine the maximum amount of money you can rob tonight without%0Aalerting the police.%0A%22%22%22%0A%0Aclass Solution:%0A # @param %7Binteger%5B%5D%7D nums%0A # @return %7Binteger%7D%0A def rob(self, nums):%0A if not nums:%0A return 0%0A%0A current, previous, result = 0, 0, 0%0A for x in nums:%0A temp = current%0A current = max(current, x + previous)%0A previous = temp%0A%0A return current%0A
06cd9e8e5006d68d7656b7f147442e54aaf9d7a1
Add female Public Health College and Club
clubs/migrations/0035_add_public_health_college.py
clubs/migrations/0035_add_public_health_college.py
Python
0
@@ -0,0 +1,1996 @@ +# -*- coding: utf-8 -*-%0Afrom __future__ import unicode_literals%0A%0Afrom django.db import models, migrations%0A%0Adef add_college(apps, schema_editor):%0A Club = apps.get_model('clubs', 'Club')%0A College = apps.get_model('clubs', 'College')%0A StudentClubYear = apps.get_model('core', 'StudentClubYear')%0A year_2015_2016 = StudentClubYear.objects.get(start_date__year=2015,%0A end_date__year=2016)%0A female_presidency = Club.objects.get(english_name=%22Presidency (Riyadh/Female)%22,%0A year=year_2015_2016)%0A r_i_f = College.objects.create(city='R', section='NG', name='I',%0A gender='F')%0A Club.objects.create(name=%22%D9%83%D9%84%D9%8A%D8%A9 %D8%A7%D9%84%D8%B5%D8%AD%D8%A9 %D8%A7%D9%84%D8%B9%D8%A7%D9%85%D8%A9 %D9%88%D8%A7%D9%84%D9%85%D8%B9%D9%84%D9%88%D9%85%D8%A7%D8%AA%D9%8A%D8%A9 %D8%A7%D9%84%D8%B5%D8%AD%D9%8A%D8%A9%22,%0A english_name=%22College of Public Health and Health Informatics%22,%0A description=%22%22,%0A email=%[email protected]%22,%0A parent=female_presidency,%0A gender=%22F%22,%0A year=year_2015_2016,%0A city=%22R%22,%0A college=r_i_f)%0A%0Adef remove_college(apps, schema_editor):%0A Club = apps.get_model('clubs', 'Club')%0A College = apps.get_model('clubs', 'College')%0A StudentClubYear = apps.get_model('core', 'StudentClubYear')%0A year_2015_2016 = StudentClubYear.objects.get(start_date__year=2015,%0A end_date__year=2016)%0A College.objects.get(city='R', section='NG', name='I',%0A gender='F').delete()%0A Club.objects.get(english_name=%22College of Public Health and Health Informatics%22,%0A city='R', gender='F', year=year_2015_2016)%0A %0Aclass Migration(migrations.Migration):%0A%0A dependencies = %5B%0A ('clubs', '0034_club_media_assessor'),%0A %5D%0A%0A operations = %5B%0A migrations.RunPython(%0A add_college,%0A reverse_code=remove_college),%0A %5D%0A
f4357343df1d13f5828c233e84d14586a1f786d0
add functools03.py
trypython/stdlib/functools03.py
trypython/stdlib/functools03.py
Python
0.000009
@@ -0,0 +1,1003 @@ +# coding: utf-8%0A%22%22%22%0Afunctools%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6%0Asingledispatch%E9%96%A2%E6%95%B0%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6%E3%81%AE%E3%82%B5%E3%83%B3%E3%83%97%E3%83%AB%E3%81%A7%E3%81%99.%0A%22%22%22%0Aimport functools%0Aimport html%0Aimport numbers%0A%0Afrom trypython.common.commoncls import SampleBase%0Afrom trypython.common.commonfunc import pr%0A%0A%0A# ---------------------------------------------%0A# singledispatch%E5%8C%96%E3%81%97%E3%81%9F%E3%81%84%E9%96%A2%E6%95%B0%E3%81%AB%E5%AF%BE%E3%81%97%E3%81%A6%0A# @functools.singledispatch %E3%83%87%E3%82%B3%E3%83%AC%E3%83%BC%E3%82%BF%E3%82%92%E9%81%A9%E7%94%A8%E3%81%99%E3%82%8B%0A# %E5%90%8C%E3%81%98%E5%91%BC%E3%81%B3%E5%87%BA%E3%81%97%E3%81%A7%E5%91%BC%E3%81%B3%E5%85%88%E3%82%92%E5%88%86%E5%B2%90%E3%81%95%E3%81%9B%E3%81%9F%E3%81%84%E9%96%A2%E6%95%B0%E3%81%AB%E5%AF%BE%E3%81%97%E3%81%A6%0A# @%E9%96%A2%E6%95%B0%E5%90%8D.register(%E5%9E%8B) %E3%82%92%E4%BB%98%E4%B8%8E%E3%81%99%E3%82%8B%E3%81%A8%E7%99%BB%E9%8C%B2%E3%81%95%E3%82%8C%E3%82%8B%E3%80%82%0A# ---------------------------------------------%[email protected]%0Adef htmlescape(obj):%0A content = html.escape(repr(obj))%0A return f'%3Cpre%3E%7Bcontent%7D%3C/pre%3E'%0A%0A%[email protected](str)%0Adef _(text):%0A return f'%3Cp%3E%7Btext%7D%3C/p%3E'%0A%0A%[email protected](numbers.Integral)%0Adef _(n):%0A return f'%3Cpre%3E0x%7Bn%7D%3C/pre%3E'%0A%0A%0Aclass Sample(SampleBase):%0A def exec(self):%0A pr('singledispatch(obj)', htmlescape((1, 2, 3)))%0A pr('singledispatch(str)', htmlescape('hello world'))%0A pr('singledispatch(int)', htmlescape(100))%0A%0A%0Adef go():%0A obj = Sample()%0A obj.exec()%0A%0A%0Aif __name__ == '__main__':%0A go()%0A
17cdae7f50a7ed15c4e8a84cdb0000a32f824c5f
Add an oauth example script.
examples/outh/getaccesstoken.py
examples/outh/getaccesstoken.py
Python
0
@@ -0,0 +1,751 @@ +import webbrowser%0A%0Aimport tweepy%0A%0A%22%22%22%0A Query the user for their consumer key/secret%0A then attempt to fetch a valid access token.%0A%22%22%22%0A%0Aif __name__ == %22__main__%22:%0A%0A consumer_key = raw_input('Consumer key: ').strip()%0A consumer_secret = raw_input('Consumer secret: ').strip()%0A auth = tweepy.OAuthHandler(consumer_key, consumer_secret)%0A%0A # Open authorization URL in browser%0A webbrowser.open(auth.get_authorization_url())%0A%0A # Ask user for verifier pin%0A pin = raw_input('Verification pin number from twitter.com: ').strip()%0A%0A # Get access token%0A token = auth.get_access_token(verifier=pin)%0A%0A # Give user the access token%0A print 'Access token:'%0A print ' Key: %25s' %25 token.key%0A print ' Secret: %25s' %25 token.secret%0A%0A
c4e8e6d73e70e568d4c4386d7c1bab07ade2b8f0
use DFS instead of BFS to do checking, it's simpler and results in more obvious message ordering
tc/checker.py
tc/checker.py
import logging from django.template import loader, base, loader_tags, defaulttags class TemplateChecker(object): registered_rules = [] def __init__(self): self.warnings = [] self.errors = [] def check_template(self, path): """ Checks the given template for badness. """ try: template = loader.get_template(path) except (base.TemplateSyntaxError, base.TemplateDoesNotExist), e: self.errors.append(e) return rules = [r(self, template) for r in self.registered_rules] # breadth-first search of the template nodes #TODO should probably use deque, since we're doing popleft() a lot? nodes = template.nodelist[:] # set parent nodes, so rules can traverse up the hierarchy if they want for n in nodes: n.parent = None while nodes: node = nodes.pop(0) children = [] if isinstance(node, base.TextNode): if not node.s.strip(): # skip further processing for blank text nodes continue elif getattr(node, 'nodelist', None): children = node.nodelist[:] for child in children: child.parent = node valid = True for rule in rules: if rule.visit_node(node) is False: valid = False rule.log(node) if valid: nodes.extend(children) def _log(self, level, node, message): # TODO get line number of node in template somehow logging.log(level, message) def info(self, node, message): self._log(logging.INFO, node, message) def warn(self, node, message): self.warnings.append(message) self._log(logging.WARN, node, message) def error(self, node, message): self.errors.append(message) self._log(logging.ERROR, node, message) ### RULES - base classes class RuleMeta(type): """ Automatically register rule classes with TemplateChecker """ def __new__(meta, className, bases, classDict): cls = type.__new__(meta, className, bases, classDict) try: Rule except NameError: pass else: TemplateChecker.registered_rules.append(cls) return cls class Rule(object): """ Determines when a node is legal and when it isn't. Nodes are visited in a breadth-first fashion. """ __metaclass__ = RuleMeta def __init__(self, checker, template): """ Create a Rule for the given checker and template. """ self._info = {} self.checker = checker self.template = template def visit_node(self, node): """ Returns whether a node is valid in the current context. If False, the node's children will not be processed. """ return None def log(self, node): """ Must be implemented to log an error or warning for the node. This is only called if visit_node() returns False. """ raise NotImplementedError ### RULES - actual rules class TextOutsideBlocksInExtended(Rule): """ No point having text nodes outside of blocks in extended templates. """ def visit_node(self, node): if isinstance(node, loader_tags.ExtendsNode): self._info['extends_node'] = node elif self._info.get('extends_node'): if not isinstance(node, (loader_tags.BlockNode, defaulttags.LoadNode, defaulttags.CommentNode)): if node.parent == self._info['extends_node']: return False def log(self, node): self.checker.warn(node, 'Non-empty text node outside of blocks in extended template')
Python
0
@@ -606,21 +606,19 @@ # -bread +dep th-first @@ -748,35 +748,32 @@ emplate.nodelist -%5B:%5D %0A %0A @@ -778,79 +778,109 @@ -# set parent +self._recursive_check( nodes, -so +%5B%5D, rules - can traverse up the hierarchy if they want +)%0A %0A def _recursive_check(self, nodes, ancestors, rules): %0A @@ -889,16 +889,19 @@ for n +ode in node @@ -916,16 +916,19 @@ n +ode .parent @@ -933,87 +933,44 @@ t = -None%0A %0A while nodes:%0A node = nodes.pop(0)%0A +ancestors%5B-1%5D if ancestors else None %0A @@ -989,18 +989,20 @@ ldren = -%5B%5D +None %0A @@ -1271,90 +1271,8 @@ list -%5B:%5D%0A for child in children:%0A child.parent = node %0A @@ -1477,16 +1477,29 @@ if valid + and children :%0A @@ -1512,29 +1512,63 @@ -nodes.extend(children +self._recursive_check(children, ancestors+%5Bnode%5D, rules )%0A @@ -3859,27 +3859,12 @@ e, ' -Non-empty text node +Text out
3898bec1a5470c79f93e7c69f6700a4af1801670
Create love6.py
Python/CodingBat/love6.py
Python/CodingBat/love6.py
Python
0
@@ -0,0 +1,121 @@ +# http://codingbat.com/prob/p100958%0A%0Adef love6(a, b):%0A return ( (a == 6) or (b == 6) or (a+b == 6) or (abs(a-b) == 6) )%0A
d27a9e09659a8d990b7b07963fb72fe2d25572c2
test. nothing important
shutdowntimer.py
shutdowntimer.py
Python
0.999986
@@ -0,0 +1,704 @@ +#!/usr/bin/python3%0A%0A# use python 3.x%0A# simple shutdown timer script for windows%0A%0A%0Aimport os%0A%0Aprint(%22-----SHUTDOWN TIMER-----%22)%0A%0Awhile(True):%0A%09a = input(%22Press S to schedule shutdown.%5CnPress C to cancel shutdown.%5Cn%22)%0A%09if(a == 's' or a == 'S'):%0A%0A%09%09try:%0A%09%09%09hours = int(input(%22%5Cn%5CnEnter hours: %22))%0A%09%09except ValueError:%0A%09%09%09hours = 0%0A%09%09%0A%09%09try:%0A%09%09%09minutes = int(input(%22Enter minutes: %22))%0A%09%09except ValueError:%0A%09%09%09minutes=0%0A%0A%09%09seconds = hours * 60 * 60 + minutes * 60%0A%0A%09%09os.system('shutdown -s -t %7B%7D'.format(seconds))%0A%09%09print(%22Your system will shutdown in %7B%7D hours and %7B%7D minutes%22.format(hours,minutes))%0A%09%09break%0A%0A%09elif(a=='C' or a=='c'):%0A%09%09os.system('shutdown -a')%0A%09%09break%0A%09%09%0A%09else:%0A%09%09print(%22Sorry. Try again.%22)%0A%0A
be095fdb2163575803020cefcfa0d86cff1d990f
Create new package (#6453)
var/spack/repos/builtin/packages/r-lars/package.py
var/spack/repos/builtin/packages/r-lars/package.py
Python
0
@@ -0,0 +1,1814 @@ +##############################################################################%0A# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, [email protected], All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/spack/spack%0A# Please also see the NOTICE and LICENSE files for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass RLars(RPackage):%0A %22%22%22Efficient procedures for fitting an entire lasso sequence with the cost%0A of a single least squares fit.%22%22%22%0A%0A homepage = %22https://cran.r-project.org/web/packages/lars/index.html%22%0A url = %22https://cran.r-project.org/src/contrib/lars_1.2.tar.gz%22%0A list_url = %22https://cran.rstudio.com/src/contrib/Archive/lars%22%0A%0A depends_on('[email protected]:3.4.9')%0A version('1.2', '2571bae325f6cba1ad0202ea61695b8c')%0A version('1.1', 'e94f6902aade09b13ec25ba2381384e5')%0A version('0.9-8', 'e6f9fffab2d83898f6d3d811f04d177f')%0A
4acf6d76bf7ec982573331835f7bcddd8487b18b
Add package for unison
var/spack/repos/builtin/packages/unison/package.py
var/spack/repos/builtin/packages/unison/package.py
Python
0
@@ -0,0 +1,2129 @@ +##############################################################################%0A# Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC.%0A# Produced at the Lawrence Livermore National Laboratory.%0A#%0A# This file is part of Spack.%0A# Created by Todd Gamblin, [email protected], All rights reserved.%0A# LLNL-CODE-647188%0A#%0A# For details, see https://github.com/llnl/spack%0A# Please also see the LICENSE file for our notice and the LGPL.%0A#%0A# This program is free software; you can redistribute it and/or modify%0A# it under the terms of the GNU Lesser General Public License (as%0A# published by the Free Software Foundation) version 2.1, February 1999.%0A#%0A# This program is distributed in the hope that it will be useful, but%0A# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF%0A# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and%0A# conditions of the GNU Lesser General Public License for more details.%0A#%0A# You should have received a copy of the GNU Lesser General Public%0A# License along with this program; if not, write to the Free Software%0A# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA%0A##############################################################################%0Afrom spack import *%0A%0A%0Aclass Unison(Package):%0A %22%22%22Unison is a file-synchronization tool for OSX, Unix, and%0A Windows. It allows two replicas of a collection of files and%0A directories to be stored on different hosts (or different disks%0A on the same host), modified separately, and then brought up to%0A date by propagating the changes in each replica to the%0A other.%22%22%22%0A%0A homepage = %22https://www.cis.upenn.edu/~bcpierce/unison/%22%0A url = %22https://www.seas.upenn.edu/~bcpierce/unison//download/releases/stable/unison-2.48.3.tar.gz%22%0A%0A version('2.48.4', '5334b78c7e68169df7de95f4c6c4b60f')%0A%0A depends_on('ocaml', type='build')%0A%0A parallel = False%0A def install(self, spec, prefix):%0A make('./mkProjectInfo')%0A make('UISTYLE=text')%0A%0A mkdirp(prefix.bin)%0A install('unison', prefix.bin)%0A set_executable(join_path(prefix.bin, 'unison'))%0A
77d3756d27758276c084cf20693202cfa645df3e
Add fptool.py that will replace flash_fp_mcu
util/fptool.py
util/fptool.py
Python
0.999999
@@ -0,0 +1,1647 @@ +#!/usr/bin/env python3%0A# Copyright 2021 The Chromium OS Authors. All rights reserved.%0A# Use of this source code is governed by a BSD-style license that can be%0A# found in the LICENSE file.%0A%0A%22%22%22A tool to manage the fingerprint system on Chrome OS.%22%22%22%0A%0Aimport argparse%0Aimport os%0Aimport shutil%0Aimport subprocess%0Aimport sys%0A%0A%0Adef cmd_flash(args: argparse.Namespace) -%3E int:%0A %22%22%22%0A Flash the entire firmware FPMCU using the native bootloader.%0A%0A This requires the Chromebook to be in dev mode with hardware write protect%0A disabled.%0A %22%22%22%0A%0A if not shutil.which('flash_fp_mcu'):%0A print('Error - The flash_fp_mcu utility does not exist.')%0A return 1%0A%0A cmd = %5B'flash_fp_mcu'%5D%0A if args.image:%0A if not os.path.isfile(args.image):%0A print(f'Error - image %7Bargs.image%7D is not a file.')%0A return 1%0A cmd.append(args.image)%0A%0A print(f'Running %7B%22 %22.join(cmd)%7D.')%0A sys.stdout.flush()%0A p = subprocess.run(cmd)%0A return p.returncode%0A%0A%0Adef main(argv: list) -%3E int:%0A parser = argparse.ArgumentParser(description=__doc__)%0A subparsers = parser.add_subparsers(dest='subcommand', title='subcommands')%0A # This method of setting required is more compatible with older python.%0A subparsers.required = True%0A%0A # Parser for %22flash%22 subcommand.%0A parser_decrypt = subparsers.add_parser('flash', help=cmd_flash.__doc__)%0A parser_decrypt.add_argument(%0A 'image', nargs='?', help='Path to the firmware image')%0A parser_decrypt.set_defaults(func=cmd_flash)%0A opts = parser.parse_args(argv)%0A return opts.func(opts)%0A%0A%0Aif __name__ == '__main__':%0A sys.exit(main(sys.argv%5B1:%5D))%0A
bc32b2bccc82caecea0cf936e13c3ae70d0e9486
Add script to remove broken images.
utils/check.py
utils/check.py
Python
0
@@ -0,0 +1,892 @@ +from pathlib import Path%0Afrom PIL import Image%0Afrom concurrent.futures import ProcessPoolExecutor%0Aimport os%0Aimport sys%0A%0Adef verify_or_delete(filename):%0A try:%0A Image.open(filename).load()%0A except OSError:%0A return False%0A return True%0A%0A%0Aif __name__ == '__main__':%0A if len(sys.argv) %3C 2:%0A print('Remove Broken Images%5CnUsage: python check.py %3Cdir%3E')%0A exit(-1)%0A filenames = list(Path(sys.args%5B1%5D).rglob('*.*'))%0A with ProcessPoolExecutor() as executor:%0A broken, total = 0, len(filenames)%0A jobs = executor.map(verify_or_delete, filenames)%0A for i, (filename, verified) in enumerate(zip(filenames, jobs)):%0A if not verified:%0A broken += 1%0A os.system('rm %22%25s%22' %25 filename)%0A print('Checking %25d/%25d, %25d deleted...' %25%0A (i + 1, total, broken), end='%5Cr')%0A print('%5CnDone.')%0A
388bbd915a5e40a2e096eb22ab294ffcbd3db936
Add a gmm, currently wrapping sklearn
bananas/model.py
bananas/model.py
Python
0
@@ -0,0 +1,2188 @@ +import numpy%0A# FIXME: copy the functions here%0A%0Afrom sklearn.mixture.gmm import log_multivariate_normal_density, logsumexp%0A%0Aclass GMM(object):%0A def __init__(self, weights, means, covs):%0A self.weights = numpy.array(weights)%0A self.means = numpy.array(means)%0A self.covs = numpy.array(covs)%0A%0A def score(self, X, return_responsibilities=False):%0A nc = len(self.weights)%0A X = numpy.array(X)%0A if X.ndim == 1:%0A X = X%5B:, None%5D%0A if X.size == 0:%0A return numpy.array(%5B%5D), numpy.empty((0, len(self.weights)))%0A%0A if X.shape%5B1%5D != self.means.shape%5B1%5D:%0A raise ValueError('The shape of X is not compatible with self')%0A%0A lpr = numpy.log(self.weights)) + %5C%0A log_multivariate_normal_density(X,%0A self.means,%0A self.covs, 'full')%0A%0A logprob = logsumexp(lpr, axis=1)%0A if return_responsibilities:%0A responsibilities = numpy.exp(lpr - logprob%5B:, None%5D)%0A return logprob, responsibilities%0A return logprob%0A%0A @classmethod%0A def fit(kls, nc, X):%0A # FIXME: get rid of this and add weights support%0A from sklearn import mixture%0A%0A model = mixture.GMM(nc, covariance_type='full', n_iter=100)%0A model.fit(X)%0A%0A if not model.converged_:%0A raise ValueError(%22Your data is strange. Gaussian mixture failed to converge%22)%0A%0A return kls(model.weights_, model.means_, model.covars_)%0A%0Aclass Confidence(object):%0A def __init__(self, model, confidence_table)%0A self.model = model%0A self.confidence_table = confidence_table%0A %0A def score(self, X):%0A x, y = self.confidence_table%0A sc = self.model.score(X)%0A return numpy.interp(sc, x, y, left=1., right=0.)%0A %0A @classmethod%0A def fit(kls, model, X, vmin=-5, vmax=0, nb=100):%0A sc = model.score(X)%0A confidence_levels = 1 - numpy.logspace(vmin, vmax, num=nb)%0A # FIXME: add weight support here%0A sc_cl = numpy.percentile(sc, 100. - confidence_levels * 100.)%0A confidence_table = numpy.array(%5Bsc_cl, confidence_levels%5D)%0A return kls(model, confidence_table)%0A%0A
b182e2334d3f5ffb38a0336f8c4fa91cbdfeea93
fix prefix (#5749)
var/spack/repos/builtin/packages/gettext/package.py
var/spack/repos/builtin/packages/gettext/package.py
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class Gettext(AutotoolsPackage): """GNU internationalization (i18n) and localization (l10n) library.""" homepage = "https://www.gnu.org/software/gettext/" url = "http://ftpmirror.gnu.org/gettext/gettext-0.19.7.tar.xz" version('0.19.8.1', 'df3f5690eaa30fd228537b00cb7b7590') version('0.19.7', 'f81e50556da41b44c1d59ac93474dca5') # Recommended variants variant('curses', default=True, description='Use libncurses') variant('libxml2', default=True, description='Use libxml2') variant('git', default=True, description='Enable git support') variant('tar', default=True, description='Enable tar support') variant('bzip2', default=True, description='Enable bzip2 support') variant('xz', default=True, description='Enable xz support') # Optional variants variant('libunistring', default=False, description='Use libunistring') # Recommended dependencies depends_on('ncurses', when='+curses') depends_on('libxml2', when='+libxml2') # Java runtime and compiler (e.g. GNU gcj or kaffe) # C# runtime and compiler (e.g. pnet or mono) depends_on('tar', when='+tar') # depends_on('gzip', when='+gzip') depends_on('bzip2', when='+bzip2') depends_on('xz', when='+xz') # Optional dependencies # depends_on('glib') # circular dependency? # depends_on('[email protected]:') depends_on('libunistring', when='+libunistring') # depends_on('cvs') patch('test-verify-parallel-make-check.patch', when='@:0.19.8.1') def configure_args(self): spec = self.spec config_args = [ '--disable-java', '--disable-csharp', '--with-included-glib', '--with-included-gettext', '--with-included-libcroco', '--without-emacs', '--with-lispdir=%s/emacs/site-lisp/gettext' % prefix.share, '--without-cvs' ] if '+curses' in spec: config_args.append('--with-ncurses-prefix={0}'.format( spec['ncurses'].prefix)) else: config_args.append('--disable-curses') if '+libxml2' in spec: config_args.append('--with-libxml2-prefix={0}'.format( spec['libxml2'].prefix)) else: config_args.append('--with-included-libxml') if '+bzip2' not in spec: config_args.append('--without-bzip2') if '+xz' not in spec: config_args.append('--without-xz') if '+libunistring' in spec: config_args.append('--with-libunistring-prefix={0}'.format( spec['libunistring'].prefix)) else: config_args.append('--with-included-libunistring') return config_args
Python
0.000045
@@ -3154,16 +3154,21 @@ text' %25 +self. prefix.s
b1bea70df1f62e4c0447a406b77266b804eec5df
add new Package (#15894)
var/spack/repos/builtin/packages/nanomsg/package.py
var/spack/repos/builtin/packages/nanomsg/package.py
Python
0
@@ -0,0 +1,665 @@ +# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass Nanomsg(CMakePackage):%0A %22%22%22The nanomsg library is a simple high-performance%0A implementation of several 'scalability protocols'%22%22%22%0A%0A homepage = %22https://nanomsg.org/%22%0A url = %22https://github.com/nanomsg/nanomsg/archive/1.0.0.tar.gz%22%0A%0A version('1.1.5', sha256='218b31ae1534ab897cb5c419973603de9ca1a5f54df2e724ab4a188eb416df5a')%0A version('1.0.0', sha256='24afdeb71b2e362e8a003a7ecc906e1b84fd9f56ce15ec567481d1bb33132cc7')%0A
f069a3feda43ebc436e404dad66dfaa06055e35a
Add h5sh python package (#14001)
var/spack/repos/builtin/packages/py-h5sh/package.py
var/spack/repos/builtin/packages/py-h5sh/package.py
Python
0
@@ -0,0 +1,900 @@ +# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other%0A# Spack Project Developers. See the top-level COPYRIGHT file for details.%0A#%0A# SPDX-License-Identifier: (Apache-2.0 OR MIT)%0A%0Afrom spack import *%0A%0A%0Aclass PyH5sh(PythonPackage):%0A %22%22%22Shell-like environment for HDF5.%22%22%22%0A%0A homepage = %22https://pypi.python.org/pypi/h5sh%22%0A url = %22https://github.com/sethrj/h5sh/archive/v0.1.1.tar.gz%22%0A%0A maintainers = %5B'sethrj'%5D%0A%0A version('0.1.1', sha256='111989d8200d1da8e150aee637a907e524ca0f98d5005a55587cba0d94d9c4a0')%0A%0A depends_on('py-setuptools', type=('build', 'run'))%0A depends_on('py-h5py', type=('build', 'run'))%0A depends_on('py-numpy', type=('build', 'run'))%0A depends_on('py-prompt-toolkit@2:', type=('build', 'run'))%0A depends_on('py-pygments', type=('build', 'run'))%0A depends_on('py-six', type=('build', 'run'))%0A depends_on('py-pytest', type='test')%0A