commit
stringlengths
40
40
subject
stringlengths
1
1.49k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
new_contents
stringlengths
1
29.8k
old_contents
stringlengths
0
9.9k
lang
stringclasses
3 values
proba
float64
0
1
0ee4afce4ba81cff6d13152ab082157afc4718f1
Create pyspark.py
pyspark.py
pyspark.py
from pyspark import SparkConf, SparkContext conf = SparkConf().setMaster("local").setAppName("MinTemperatures") sc = SparkContext(conf = conf) lines = sc.textFile("file:///Users/Spark/1800.csv") parsedLines = lines.map(parseLine)
Python
0.000009
af495c7a69611f2c1fa744dce000c49033eb2dd7
Add test for sys.intern().
tests/basics/sys_intern.py
tests/basics/sys_intern.py
# test sys.intern() function import sys try: sys.intern except AttributeError: print('SKIP') raise SystemExit s1 = "long long long long long long" s2 = "long long long" + " long long long" print(id(s1) == id(s2)) i1 = sys.intern(s1) i2 = sys.intern(s2) print(id(i1) == id(i2)) i2_ = sys.intern(i2) pri...
Python
0
7323565bdc2a290e97617857da475e8f41d5a43f
Add tee plugin
plugins/tee.py
plugins/tee.py
class Plugin: def on_command(self, bot, msg, stdin, stdout, reply): text = stdin.read().strip() reply(text) print(text, file=stdout) def on_help(self): return "Copy standard input to reply, and also to standard output."
Python
0
b8ea356af5121ffd612ccf708fe2372fbae3cc3d
add custom hasher for crypt_sha512
daiquiri/core/hashers.py
daiquiri/core/hashers.py
# inspired by https://djangosnippets.org/snippets/10572/ from collections import OrderedDict from django.contrib.auth.hashers import CryptPasswordHasher, mask_hash from django.utils.encoding import force_str from django.utils.crypto import get_random_string, constant_time_compare from django.utils.translation import u...
Python
0.000001
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.function...
""" 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.function...
Python
0.999414
042d0d899896342e9f2e7b083f8543e8077bf19a
Add tests.py to app skeleton.
lib/rapidsms/skeleton/app/tests.py
lib/rapidsms/skeleton/app/tests.py
from rapidsms.tests.scripted import TestScript from app import App class TestApp (TestScript): apps = (App,) # define your test scripts here. # e.g.: # # testRegister = """ # 8005551212 > register as someuser # 8005551212 < Registered new user 'someuser' for 8005551212! # 8005551...
Python
0
27a7079f9edf01abce7912eb52c5091279bc85a1
ADD | 添加pygal path的变量设定源码
src/lib/PygalPath.py
src/lib/PygalPath.py
#-*- coding:UTF-8 -*- import socket import os __all__ = ['PYGAL_TOOLTIPS_PATH', 'SVG_JQUERY_PATH'] SERVER_WUHAN = '192.168.60.60' SERVER_WUHAN_PRE = '192.168.6' SERVER_BEIJING = '192.168.50.193' SERVER_BEIJING_PRE = '192.168.5' SERVER = '10.1.145.70' #根据本机IP获取pygal模块生成svg文件所需的js文件路径 sname=socket.gethostname() ipList...
Python
0
a3db0306133bc3da1cc00d3c745396539a152839
Add release script
release.py
release.py
#!/usr/bin/env python from collections import OrderedDict from itertools import zip_longest import json import os import re from subprocess import check_output, CalledProcessError import sys from zipfile import ZipFile def sh(command, v=False): if v: print(command) return check_output(command, text=T...
Python
0.000001
9ad9808b9bf7c202bc6dbbe8abd74e1c642982ae
structure migration
structure/migrations/0002_structure_refined.py
structure/migrations/0002_structure_refined.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-09-20 07:35 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('structure', '0001_initial'), ] operations = [ migrations.AddField( ...
Python
0.000002
ca1cb845f312ba295718084fa6c8a0d4e68d49e3
fix boolean parameter in config file
core/config.py
core/config.py
import argparse import appdirs import logging import os import configparser import sys def defaultBackendRpcPort(config): if config.TESTNET: return 14000 else: return 4000 def defaultBackendRpc(config): protocol = 'https' if config.BACKEND_RPC_SSL else 'http' return '{}://{}:{}@{}:{}'....
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(prot...
Python
0.000002
be01980afe4b1dbd5a1d5b07651cd7a54c771d01
Add unit tests for disk module
tests/modules/test_disk.py
tests/modules/test_disk.py
# pylint: disable=C0103,C0111 import mock import unittest import tests.mocks as mocks from bumblebee.input import LEFT_MOUSE from bumblebee.modules.disk import Module class MockVFS(object): def __init__(self, perc): self.f_blocks = 1024*1024 self.f_frsize = 1 self.f_bavail = self.f_block...
Python
0
da52f7c8c9280fe644a01a324eaad5512870dccb
add models.py
core/models.py
core/models.py
#!/usr/bin/env python # coding = utf-8 """ core.models """ __author__ = 'Rnd495' import datetime import hashlib from sqlalchemy import create_engine from sqlalchemy import Column, Integer, Float, String, DateTime, Text, Index from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import session...
Python
0.000001
ecacda9bab83cd66f25a3ce85f36646c13a61f3f
put full example in its own module
docs/coordinates/sgr-example.py
docs/coordinates/sgr-example.py
# coding: utf-8 """ Astropy coordinate class for the Sagittarius coordinate system """ from __future__ import division, print_function __author__ = "adrn <adrn@astro.columbia.edu>" # Standard library import os, sys # Third-party import numpy as np from numpy import radians, degrees, cos, sin import astropy.coordi...
Python
0
4bf1a14f6b6d3b30f30732bb45f4e8a501dfcbf6
test github backup
tests/pkcli/github_test.py
tests/pkcli/github_test.py
# -*- coding: utf-8 -*- u"""test github :copyright: Copyright (c) 2019 Bivio Software, Inc. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import pytest def test_backup(): from pykern import pkconfig pkconfi...
Python
0.000003
8fdaeea43e31a1c429703cd4f441a748bcfa8197
Create create_mask.py
create_mask.py
create_mask.py
from __future__ import print_function import argparse from PIL import ImageFont, ImageDraw, Image def create_mask(text, font_type, font_size=84): ''' Creates an image with the given text in it. ''' # initialize fond with given size font = ImageFont.truetype(font_type, font_size) dx, dy = fon...
Python
0.000017
79e55030736572608841bbdd3a6022fc2420be45
implement recursive permutation generation algorithm with switch
switch.py
switch.py
### # A permutation generation algorithm. # this algorithm is implemented by switching neighboring number. # # Under here is two implementation recursive and iterative ### def recursive_PGA_with_switch(width): ''' Recursive permutation generation algorithm with switch ''' # condition assert width ...
Python
0.000002
dfab68c27b3f25f448c0a2a6d0cee347bae2b08f
Add tests for canonicalize
tests/test_canonicalize.py
tests/test_canonicalize.py
from intervals import Interval, canonicalize def test_canonicalize(): assert canonicalize(Interval([1, 4])).normalized == '[1, 5)' assert canonicalize( Interval((1, 7)), lower_inc=True, upper_inc=True ).normalized == '[2, 6]' assert canonicalize( Interval([1, 7]), lower_inc=False, uppe...
Python
0
76468926c1efe4d18477a70d767f91d4c6e38768
Add test for dotted circles in sample text
tests/test_dottedcircle.py
tests/test_dottedcircle.py
import uharfbuzz as hb import gflanguages import pytest langs = gflanguages.LoadLanguages() @pytest.fixture def hb_font(): # Persuade Harfbuzz we have a font that supports # every codepoint. face = hb.Face(b"") font = hb.Font(face) funcs = hb.FontFuncs.create() funcs.set_nominal_glyph_func((l...
Python
0
7c69ec08967dc38463cfc5e1323d69fd5f261333
Create config.py
config.py
config.py
#!/usr/bin/env python import pyvty user = 'admin' password = 'password' host = '10.36.65.227' config_file = 'config.txt' # name of text file containing config commands. logfile = 'config_' + host + '.log' # terminal output will be saved in this file. try: input_file = open(config_file) commands = input_f...
Python
0
7864c8e8591d1de14f18ecfaf880e79de6c7702e
add tests for placeholder class
tests/test_placeholders.py
tests/test_placeholders.py
import re import pytest from notifications_utils.field import Placeholder @pytest.mark.parametrize('body, expected', [ ('((with-brackets))', 'with-brackets'), ('without-brackets', 'without-brackets'), ]) def test_placeholder_returns_name(body, expected): assert Placeholder(body).name == expected @pyte...
Python
0
9b1f9e9abd2890bc3e4d9f38109f12de8b488b66
Create config.py
config.py
config.py
username = "facility_ai" password = "UncloakIsADick" client_id = "GORfUXQGjNIveA" client_secret = "SzPFXaqgVbRxm_V9-IfGL05npPE"
Python
0.000002
17f71bfb81393241759e38fb9dce01561aeca3d5
Add tests to product tags
tests/test_product_tags.py
tests/test_product_tags.py
from mock import Mock from saleor.product.templatetags.product_images import get_thumbnail, product_first_image def test_get_thumbnail(): instance = Mock() cropped_value = Mock(url='crop.jpg') thumbnail_value = Mock(url='thumb.jpg') instance.crop = {'10x10': cropped_value} instance.thumbnail = {'1...
Python
0
27444dfefa70759694b755185c2eb6f25216d326
Remove Node - migration.
devilry/apps/core/migrations/0037_auto_20170620_1515.py
devilry/apps/core/migrations/0037_auto_20170620_1515.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.9 on 2017-06-20 15:15 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0036_auto_20170523_1748'), ] operations = [ migrations.AlterUniqueTogether( ...
Python
0
f1cb5af4f42ccf437cdd6ef06a2056993e54b604
Create sum13.py
Python/CodingBat/sum13.py
Python/CodingBat/sum13.py
# http://codingbat.com/prob/p167025 def sum13(nums): sum = 0 i = 0 while i < len(nums): if nums[i] == 13: i += 2 continue else: sum += nums[i] i += 1 return sum
Python
0.000132
f8f38fde96ab166af6b899d3e841e6a46b7dddd1
switch to comparing sets of neighbors rather than lists
pysal/weights/tests/test_Wsets.py
pysal/weights/tests/test_Wsets.py
"""Unit test for Wsets module.""" import unittest import pysal class TestWsets(unittest.TestCase): """Unit test for Wsets module.""" def test_w_union(self): """Unit test""" w1 = pysal.lat2W(4, 4) w2 = pysal.lat2W(6, 4) w3 = pysal.weights.Wsets.w_union(w1, w2) self.asse...
"""Unit test for Wsets module.""" import unittest import pysal class TestWsets(unittest.TestCase): """Unit test for Wsets module.""" def test_w_union(self): """Unit test""" w1 = pysal.lat2W(4, 4) w2 = pysal.lat2W(6, 4) w3 = pysal.weights.Wsets.w_union(w1, w2) self.asse...
Python
0.000001
d408ae00d2e5c0a0e7c5e90e98088d52815c5e49
Create WikiScrape.py
Python/WikiScrape.py
Python/WikiScrape.py
## This script was tested using Python 2.7.9 ## The MWClient library was used to access the api. It can be found at: ## https://github.com/mwclient/mwclient import mwclient site = mwclient.Site(('https', 'en.wikipedia.org')) site.login('$user', '$pass') # credentials are sanitized from the script. listpage = site.Pag...
Python
0
e455d459590a4f2b16b9a9360b6e33640f5ec7bf
Add a script to check that __all__ in __init__.py is correct
python/allcheck.py
python/allcheck.py
#!/usr/bin/env python import sys import re import glob import phonenumbers INTERNAL_FILES = ['phonenumbers/util.py', 'phonenumbers/re_util.py', 'phonenumbers/unicode_util.py'] CLASS_RE = re.compile(r"^class +([A-Za-z][_A-Za-z0-9]+)[ \(:]") FUNCTION_RE = re.compile("^def +([A-Za-z][...
Python
0.003175
0deec6fecb527f12ff6851c47820b76db8196a34
Add files via upload
rosette.py
rosette.py
# This is a basic program showing the functionality of the turtle module. # It generates a very pretty spiraling pattern. import turtle # import the turtle module so we can draw import math # import the math module, we need this for e and pi t = turtle.Pen() # set a variable to draw with t.reset() ...
Python
0
48c844e602eaa182c4efaaa0b977765f4248d0a0
Add a data migration tool
tools/network_migration.py
tools/network_migration.py
import argparse, shelve def renameDictKeys(storageDict): for key in storageDict.iterkeys(): if isinstance(storageDict[key], dict): renameDictKeys(storageDict[key]) if key == options.oldnetwork: storageDict[options.newnetwork] = storageDict[options.oldnetwork] del...
Python
0.000006
20269212705bdfd8748be468a50567ba290ad4a1
Bump PROVISION_VERSION for new APNS.
version.py
version.py
ZULIP_VERSION = "1.6.0+git" PROVISION_VERSION = '9.4'
ZULIP_VERSION = "1.6.0+git" PROVISION_VERSION = '9.3'
Python
0
bd2cfd63ce51c55c695a12dc13e9ac52872cea5a
Add ternary_axes_subplot.py
ternary/ternary_axes_subplot.py
ternary/ternary_axes_subplot.py
""" Wrapper class for all ternary plotting functions. """ from matplotlib import pyplot import heatmapping import lines import plotting def figure(ax=None, scale=None): """ Wraps a Matplotlib AxesSubplot or generates a new one. Emulates matplotlib's > figure, ax = pyplot.subplot() Parameters --...
Python
0.999982
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']), ...
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': i...
Python
0.000001
35076b373913381a90aa65e8052036eb51eece46
add unicode_literals in utils
simiki/utils.py
simiki/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals 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 ...
#!/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...
Python
0.001148
d72d2e38d177476470b22ded061dd06b2be3ee88
Add the quantity-safe allclose from spectral-cube
turbustat/tests/helpers.py
turbustat/tests/helpers.py
from __future__ import print_function, absolute_import, division from astropy import units as u from numpy.testing import assert_allclose as assert_allclose_numpy, assert_array_equal def assert_allclose(q1, q2, **kwargs): """ Quantity-safe version of Numpy's assert_allclose Copyright (c) 2014, spectral...
Python
0.000261
6c3d92a2d3eb043e466e3d6ab8e303c025cc7e0a
add ColorPrinter.py
ColorPrinter.py
ColorPrinter.py
class ColorPrinter: """ print message to terminal with colored header """ def __init__(self, header=''): self.__header = header self.__levels = { 'log': '\033[0m', # terminal color header 'info': '\033[1;32;40m', # green header 'warn': '\033[1;33;40m...
Python
0
b5972a5651ba1ace28ae54d5a1a4f31a07e97670
add server_costs table
migrations/versions/1e27c434bb14_create_server_costs.py
migrations/versions/1e27c434bb14_create_server_costs.py
"""create server_costs table Revision ID: 1e27c434bb14 Revises: fa0f07475596 Create Date: 2016-03-14 15:57:19.945327 """ # revision identifiers, used by Alembic. revision = '1e27c434bb14' down_revision = 'fa0f07475596' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def up...
Python
0.000001
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):...
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):...
Python
0.999987
ff519b5145accbc10fcb7baa955bc1fe44774c27
Add browser/websocket.py
src/Lib/browser/websocket.py
src/Lib/browser/websocket.py
from browser import window import javascript WebSocket = javascript.JSConstructor(window.WebSocket)
Python
0.000001
126491288a532da08fb3923eae2635a84736798d
Add new package: libsamplerate (#16143)
var/spack/repos/builtin/packages/libsamplerate/package.py
var/spack/repos/builtin/packages/libsamplerate/package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Libsamplerate(AutotoolsPackage): """libsamplerate (also known as Secret Rabbit Code) is a ...
Python
0
4e6a6e4f2758bd616f0c2c2703160cbb9c539b63
add new package (#23843)
var/spack/repos/builtin/packages/py-kubernetes/package.py
var/spack/repos/builtin/packages/py-kubernetes/package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyKubernetes(PythonPackage): """Official Python client library for kubernetes. """ h...
Python
0
04d6fd6ceabf71f5f38fd7cf25cd4ac2bcb6b57f
Add simple web server to display measurements
server.py
server.py
import sqlite3 from flask import Flask, g, render_template_string app = Flask(__name__) def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect('sensors.db') return db index_tmpl = """ <!doctype html> <title>Sensors</title> <body> <h1>Senors</h1> <dl> <dt...
Python
0
acc23fe67231f8b556b2de7bd19f0050cbe379e6
Add total calculation script
total_prices.py
total_prices.py
prices = { "banana" : 4, "apple" : 2, "orange" : 1.5, "pear" : 3 } stock = { "banana" : 6, "apple" : 0, "orange" : 32, "pear" : 15, } total = 0 for key in prices: print key print "price: %s" % prices[key] print "stock: %s" % stock[key] print prices[key] * stock[...
Python
0.000001
31af4f92e97c83c42baff4e902cddf8184d84e4d
allow to run tox as 'python -m tox', which is handy on Windoze
tox/__main__.py
tox/__main__.py
from tox._cmdline import main main()
Python
0
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") if os....
#!/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...
Python
0
d206b02e12cf7f5418cd02987313bd7ddd807901
add geom_tile layer.
ggplot/geoms/geom_tile.py
ggplot/geoms/geom_tile.py
import matplotlib.pyplot as plt import numpy as np import pandas as pd from geom import geom class geom_tile(geom): VALID_AES = ['x', 'y', 'fill'] def plot_layer(self, layer): layer = {k: v for k, v in layer.iteritems() if k in self.VALID_AES} layer.update(self.manual_aes) x = layer...
Python
0
d940ce7cbd92c0e886139eaec3faa75aabbce16a
add test models
singleactiveobject/tests/models.py
singleactiveobject/tests/models.py
from singleactiveobject.models import SingleActiveObjectMixin class SingleActiveObject(SingleActiveObjectMixin): pass
Python
0
71d3375c4ca1acb106f8825d2f39ca602fa47e94
Test astroid trajectory implementation
src/test/trajectory/test_astroid_trajectory.py
src/test/trajectory/test_astroid_trajectory.py
#!/usr/bin/env python import unittest from geometry_msgs.msg import Point from trajectory.astroid_trajectory import AstroidTrajectory class AstroidTrajectoryTest(unittest.TestCase): def setUp(self): self.delta = 0.000001 self.radius = 5 self.period = 4 self.expected_position = P...
Python
0.000001
835b5f20061033b6fcf2a8b86203a42c5d4835ee
Add initial unit tests for parameter.py (List)
spotpy/unittests/test_parameter.py
spotpy/unittests/test_parameter.py
import unittest try: import spotpy except ImportError: import sys sys.path.append(".") import spotpy from spotpy import parameter import numpy as np #https://docs.python.org/3/library/unittest.html class TestListParameterDistribution(unittest.TestCase): def setUp(self): self.values = [1, ...
Python
0
a759fee7b1cca1d3966100b480cac80ad4c9ece7
Iterate the stackexchange corpuses term vectors
termVectors.py
termVectors.py
from elasticsearch import Elasticsearch es = Elasticsearch('http://localhost:9200') def scoredFingerprint(terms): fp = {} for term, value in terms.items(): fp[term] = float(value['term_freq']) / float(value['doc_freq']) return fp def allCorpusDocs(index='stackexchange', doc_type='post', fields=...
Python
0.999848
e9a5a0c22de92f3b5eb5df567475736b72c5067c
Add pa300_calc_coord.py
pa300_calc_coord.py
pa300_calc_coord.py
# Std libs from itertools import product import sqlite3 # My libs import constants as c conn_params = sqlite3.connect(c.sql_params_dropbox) cur_params = conn_params.cursor() dats = cur_params.execute('''SELECT mask, mesa, xm_mesa, ym_mesa, xm_pad, ym_pad FROM mesas''').fetchall() for dat...
Python
0.001616
a52ae7a34b9ec1dd03653c6c735b3930033ac830
add a sample of visitor pattern for resolving recursion limit problem using generator.
patterns/visitor.py
patterns/visitor.py
""" from python cookbook 3rd edition. PY3 only. Resolve the recursion limit problem. """ import types class Node: pass class NodeVisitor: def visit(self, node): stack = [node] last_result = None while stack: try: last = stack[-1] if isinsta...
Python
0
b3c89917895786bfab5d4fae9ce086767575a506
Add a deployment script
deploy.py
deploy.py
""" This is a script that deploys Dogbot. """ import os from pathlib import Path from ruamel.yaml import YAML import requests # load the webhook url from the configuration with open('config.yml') as f: webhook_url = YAML(typ='safe').load(f)['monitoring']['health_webhook'] def info(text): print('\033[32m[in...
Python
0.000002
10b3ae6ab5009fe0c43b744dc655bd6512cec041
Include basic version of contract object
db/contract.py
db/contract.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from .common import Base, session_scope class Contract(Base): __tablename__ = 'contracts' __autoload__ = True def __init__(self, player_id, contract_data):
Python
0
aef7c25964883bae893913524bc9ff3dc0bdcde3
Add a docker helper script (#18)
docker.py
docker.py
#!/usr/bin/env python3 import argparse import subprocess IMAGE_NAME = 'cargo-sphinx' def has_image(name): cmd = "docker images | awk '{{print $1}}' | grep '^{name}$' > /dev/null".format( name=name), proc = subprocess.run(cmd, shell=True) return proc.returncode == 0 def main(): parser =...
Python
0.000022
647fd44f829a308dc16eb86a663dc1a3719476ab
add solution for Search a 2D Matrix II
algorithms/searchA2DMatrixII/searchA2DMatrixII.py
algorithms/searchA2DMatrixII/searchA2DMatrixII.py
class Solution: # @param {integer[][]} matrix # @param {integer} target # @return {boolean} def searchMatrix(self, matrix, target): n = len(matrix) m = len(matrix[0]) x = n-1 y = 0 while x >= 0 and y < m: if matrix[x][y] == target: ret...
Python
0.000005
00e68a20d4691ae3172ae0bb11b8440387acc0d6
Add the server based on oslo.service.
pycom/server.py
pycom/server.py
# encoding: utf-8 from __future__ import absolute_import, print_function, unicode_literals import os import socket import logging import functools import greenlet import eventlet from oslo_service import service LOG = logging.getLogger(__name__) def listen_socket(host, port, backlog=1024, reuse=True): sock = s...
Python
0.000001
ada6128817769886e2869944fac3a8cea0b5b109
Add a missing module
pykmer/timer.py
pykmer/timer.py
""" This module provides a simple timer class for instrumenting code. """ import time class timer(object): def __init__(self): self.start = time.time() self.sofar = 0.0 self.paused = False self.events = 0 def pause(self): now = time.time() self.sofar += now - s...
Python
0.000048
6e767e8f5b219d9883fb1a16846830efabac7d5b
Add python
python/hello.py
python/hello.py
print("Hello, World!")
Python
0.998925
01472504fc42137a05a85ae5ad6d4b7956865680
Add autosolver for regex.
quiz/5-regex.py
quiz/5-regex.py
#!/usr/bin/env python3 def make_array(text): import re regex = re.compile('(\d+)->(\d+)') pairs = regex.findall(text) ret = list() for (src, dst) in pairs: src = int(src) dst = int(dst) ret.append((src, dst)) return ret def make_transitive_closure(states, eps_trans): ...
Python
0
2c1b5aedc5f4503a738ef7e9ffa0a7f969fecfef
add argparse example
Python/calculator_argp.py
Python/calculator_argp.py
import argparse def main(): parser = argparse.ArgumentParser(description='Calculate two input numbers') parser.add_argument( 'first', metavar='int', type=int, help='first number') parser.add_argument( 'oper', metavar='oper', type=str, help='operator +, - or...
Python
0.000032
ed5f68211e93df983a5e15c7f1ce812b810b49c0
Add ANTs package (#7717)
var/spack/repos/builtin/packages/ants/package.py
var/spack/repos/builtin/packages/ants/package.py
############################################################################## # Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
Python
0
744cedc7e999f96aa0646bb43c039882991228ae
Add Asio package (#24485)
var/spack/repos/builtin/packages/asio/package.py
var/spack/repos/builtin/packages/asio/package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * import os.path class Asio(AutotoolsPackage): """C++ library for network and low-level I/O progra...
Python
0
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', b'BEGIN PGP PRI...
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_priv...
Python
0
6b9b9642ca09f3b33bdf61bb5dacbaa7c29de8fc
Create __main__.py
src/__main__.py
src/__main__.py
Python
0.000164
a58a7f3206168ae98b952e804404c46b89e81640
Add a snippet (Pillow).
python/pil/python3_pillow_fork/show.py
python/pil/python3_pillow_fork/show.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including witho...
Python
0.000001
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 Mapping, Optional from six import text_type def get_session_dict_user(session_dict): # type: (Mapping[text_type, int]) -> Optional[int] # C...
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...
Python
0
7037762247bd40455eb1944dc21684561c5f97ba
add a __init__ file
dataScraping/__init__.py
dataScraping/__init__.py
#!/usr/bin/env python
Python
0.000342
2b4544820bf6549bc172f8d5b3532a9103190920
add utility I used to generate random ph and temp readings
utils/generate_random_values.py
utils/generate_random_values.py
import random ph = [random.uniform(0, 14) for x in range(30000)] temp = [random.uniform(55, 90) for x in range(30000)] temp_file = open('temp.csv', 'w+') ph_file = open('ph.csv', 'w+') for x in range(len(temp)): temp_file.write("%.2f," % temp[x]) ph_file.write("%.2f," % ph[x]) temp_file.close() ph_file.close()
Python
0
4883bd13c6e07a0568c29fd26a141888b52292b7
Add retriever object for player draft information
utils/player_draft_retriever.py
utils/player_draft_retriever.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import requests from lxml import html from db.team import Team from db.player_draft import PlayerDraft class PlayerDraftRetriever(): NHL_PLAYER_DRAFT_PREFIX = "https://www.nhl.com/player" DRAFT_INFO_REGEX = re.compile( "(\d{4})\s(.+),\s(\d+).+...
Python
0
a5e18330ac84a93b9a3ffe7d8493c401d3ade11e
Create version.py
nilmtk/version.py
nilmtk/version.py
version = '0.1.0'
Python
0.000001
776350aaaed8a8e3f00a492c1a1735c24f595d89
add config_dialog.py
dialogs/config_dialog.py
dialogs/config_dialog.py
#-*- coding: utf-8 -*- from win32ui import IDD_SET_TABSTOPS from win32ui import IDC_EDIT_TABS from win32ui import IDC_PROMPT_TABS from win32con import IDOK from win32con import IDCANCEL import win32ui import win32con from pywin.mfc import dialog IDC_EDIT_USERNAME = 2000 IDC_EDIT_PASSWORD = 2001 def ConfigDialogTem...
Python
0.000003
42faf76ffe421802e628dd2a79f518765d43284b
Create recordsCheck.py
recordsCheck.py
recordsCheck.py
import tensorflow as tf import glob as glob import getopt import sys import cPickle as pkl import numpy as np import time opts, _ = getopt.getopt(sys.argv[1:],"",["input_dir=", "input_file=", "output_file="]) input_dir = "/data/video_level_feat_v3/" input_file = "" output_file = "" print(opts) for opt, arg in opts: ...
Python
0
f4bd76b7ebe376a2a0cea0ac1a44be4d741ce5c5
Create LeetCode-541.py
LeetCode-541.py
LeetCode-541.py
import math class Solution(object): def ReverseStr(self, str, k): ans='' n = int (math.ceil(len(str) / (2.0*k) )) for i in range(n): ans += str[2*i*k:(2*i+1)*k][::-1] #reverse k str print '1',ans ans += str[(2*i+1)*k:(2*i+2)*k] print '2',ans ...
Python
0
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
class WordDictionary: class Node: def __init__(self, char): # char is a substring of the phone number self.char = char # 10 digits self.children_nodes = [None for i in range(26)] self.isTerminal = False def get_char(self): re...
Python
0.999988
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 to_default = None from_default = None class JSONTranslator(DefaultTranslator): def to_datetime(self, value): return str(value) def from_datetime(self, value): ...
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...
Python
0.999999
4cdeb6987910d4d5b33d37486ddeaafcde54bb2f
add classify_neuralnet script
hvc/classify_neuralnet.py
hvc/classify_neuralnet.py
#from standard library import glob import sys import os import shelve #from third-party import numpy as np import scipy.io as scio # to load matlab files import numpy as np from scipy.io import wavfile from sklearn.preprocessing import StandardScaler from sklearn.model_selection import StratifiedKFold from keras.utils...
Python
0.000782
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(igno...
# 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(igno...
Python
0.000001
bc34d530f4a21b5f06228d626f446c617b9c8876
Add example that mirrors defconfig and oldconfig.
examples/defconfig_oldconfig.py
examples/defconfig_oldconfig.py
# Produces exactly the same output as the following script: # # make defconfig # echo CONFIG_ETHERNET=n >> .config # make oldconfig # echo CONFIG_ETHERNET=y >> .config # yes n | make oldconfig # # This came up in https://github.com/ulfalizer/Kconfiglib/issues/15. import kconfiglib import sys conf = kconfiglib.Config(...
Python
0
7c270e2fb5e3169f179e045cc58fdd4d58672859
add fixCAs.py to master
fixCAs.py
fixCAs.py
import sys from valuenetwork.valueaccounting.models import * agents = EconomicAgent.objects.all() #import pdb; pdb.set_trace() count = 0 for agent in agents: agent.is_context = agent.agent_type.is_context try: agent.save() count = count + 1 except: print "Unexpected error:", sys.e...
Python
0
171d573082e528b1f103db7ea22022fdcb24d629
Create count-depth_true_false_unknown.py
binning/count-depth_true_false_unknown.py
binning/count-depth_true_false_unknown.py
#!/usr/bin/env python from sys import argv, stdout, stderr, exit from numpy import mean # simple dummy weight function counting each sequences as one class oneweight: __getitem__ = lambda self,key: 1 def usage(): print >> stderr, 'Usage: ', argv[0], '--labels lab.racol --predictions pred.racol [--with-unknown-labe...
Python
0.999989
42d1ec95b69c80a5d4e60af6e088f8d30f95f160
Create documentation of DataSource Settings
ibmcnx/test/objsExport.py
ibmcnx/test/objsExport.py
#----------------------------------------------------------------- # Configuration Objects Export Script # Exploits the AdminConfig component of wsadmin to export WAS configuration # objects (ie. DataSource, J2CConnetionFactory, etc) to an EXISTING folder. # You must specify the folder, the type of objects you...
Python
0
38f90c31f6a0f4459a8ba2f96205d80588b384c5
Add CollectDict (incomplete dicts)
calvin/actorstore/systemactors/json/CollectDict.py
calvin/actorstore/systemactors/json/CollectDict.py
# -*- coding: utf-8 -*- # Copyright (c) 2017 Ericsson AB # # 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 ...
Python
0
625139f9d3e5c06f4e5b355eaa070389f9a81954
Add utils module
website/addons/dropbox/utils.py
website/addons/dropbox/utils.py
# -*- coding: utf-8 -*- import os from website.project.utils import get_cache_content from website.addons.dropbox.client import get_node_addon_client def get_file_name(path): return os.path.split(path.strip('/'))[1] # TODO(sloria): TEST ME def render_dropbox_file(file_obj, client=None): # Filename for the ...
Python
0.000001
9ed712af79934be25de4b8166ab6c23d1111d024
Add MV powerflow db tables creation script
calc_ego_powerflow/setup_schema_tables.py
calc_ego_powerflow/setup_schema_tables.py
#!/usr/bin/env python3 # coding: utf-8 from oemof import db from oemof.db import tools def create_powerflow_schema(engine, schema, tables): """Creates new powerflow schema in database Parameters ---------- engine: SQLalchemy engine tables: dict Values are list of columns/constraints ...
Python
0
1cf4de645dd44269b01b7f57322a3edca8334fc8
Add another example script for MIDI output: a minimal drum pattern sequencer
mididrumbox.py
mididrumbox.py
from microbit import button_a, display from microbit import uart from microbit import running_time, sleep NOTE_ON = 0x90 CONTROLLER_CHANGE = 0xB0 PROGRAM_CHANGE = 0xC0 class MidiOut: def __init__(self, device, channel=1): if channel < 1 or channel > 16: raise ValueError('channel must be an int...
Python
0.000034
821a3826110ecfc64ab431b7028af3aae8aa80db
Add 20150522 question.
LeetCode/house_robbers.py
LeetCode/house_robbers.py
""" You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken int...
Python
0.000001
06cd9e8e5006d68d7656b7f147442e54aaf9d7a1
Add female Public Health College and Club
clubs/migrations/0035_add_public_health_college.py
clubs/migrations/0035_add_public_health_college.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def add_college(apps, schema_editor): Club = apps.get_model('clubs', 'Club') College = apps.get_model('clubs', 'College') StudentClubYear = apps.get_model('core', 'StudentClubYear') year_2015_2016 ...
Python
0
c2257a268662c4ea220c6c4d869d38c9f9ab55de
Create hcsr04.py
hcsr04.py
hcsr04.py
!/usr/bin/env python # # HC-SR04 interface code for the Raspberry Pi # # William Henning @ http://Mikronauts.com # # uses joan's excellent pigpio library # # Does not quite work in one pin mode, will be updated in the future # import time import pigpio import memcache mc = memcache.Client(['127.0.0.1:11211'], debug=0)...
Python
0
f4357343df1d13f5828c233e84d14586a1f786d0
add functools03.py
trypython/stdlib/functools03.py
trypython/stdlib/functools03.py
# coding: utf-8 """ functoolsモジュールについて singledispatch関数についてのサンプルです. """ import functools import html import numbers from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import pr # --------------------------------------------- # singledispatch化したい関数に対して # @functools.singledispatch デコレータ...
Python
0.000009
17cdae7f50a7ed15c4e8a84cdb0000a32f824c5f
Add an oauth example script.
examples/outh/getaccesstoken.py
examples/outh/getaccesstoken.py
import webbrowser import tweepy """ Query the user for their consumer key/secret then attempt to fetch a valid access token. """ if __name__ == "__main__": consumer_key = raw_input('Consumer key: ').strip() consumer_secret = raw_input('Consumer secret: ').strip() auth = tweepy.OAuthHandler(consu...
Python
0
62f44daaf325d94c7374836f3bb50fd5694c62c0
Add utilities/extract_scores.py
wikiclass/utilities/extract_scores.py
wikiclass/utilities/extract_scores.py
r""" Gathers the scores for a set of revisions and prints a TSV to stdout of the format: <page_id>\t<title>\n<rev_id>\t<prediction>\t<weighted_sum> See https://phabricator.wikimedia.org/T135684 for more information. Usage: extract_scores -h | --help extract_scores --dump=<dump-file>... --model=<model-file> ...
Python
0
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...
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...
Python
0
3898bec1a5470c79f93e7c69f6700a4af1801670
Create love6.py
Python/CodingBat/love6.py
Python/CodingBat/love6.py
# http://codingbat.com/prob/p100958 def love6(a, b): return ( (a == 6) or (b == 6) or (a+b == 6) or (abs(a-b) == 6) )
Python
0
d27a9e09659a8d990b7b07963fb72fe2d25572c2
test. nothing important
shutdowntimer.py
shutdowntimer.py
#!/usr/bin/python3 # use python 3.x # simple shutdown timer script for windows import os print("-----SHUTDOWN TIMER-----") while(True): a = input("Press S to schedule shutdown.\nPress C to cancel shutdown.\n") if(a == 's' or a == 'S'): try: hours = int(input("\n\nEnter hours: ")) except ValueError: ho...
Python
0.999986
be095fdb2163575803020cefcfa0d86cff1d990f
Create new package (#6453)
var/spack/repos/builtin/packages/r-lars/package.py
var/spack/repos/builtin/packages/r-lars/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, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
Python
0
4acf6d76bf7ec982573331835f7bcddd8487b18b
Add package for unison
var/spack/repos/builtin/packages/unison/package.py
var/spack/repos/builtin/packages/unison/package.py
############################################################################## # Copyright (c) 2013-2016, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
Python
0
77d3756d27758276c084cf20693202cfa645df3e
Add fptool.py that will replace flash_fp_mcu
util/fptool.py
util/fptool.py
#!/usr/bin/env python3 # Copyright 2021 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """A tool to manage the fingerprint system on Chrome OS.""" import argparse import os import shutil import subprocess import sys ...
Python
0.999999
bc32b2bccc82caecea0cf936e13c3ae70d0e9486
Add script to remove broken images.
utils/check.py
utils/check.py
from pathlib import Path from PIL import Image from concurrent.futures import ProcessPoolExecutor import os import sys def verify_or_delete(filename): try: Image.open(filename).load() except OSError: return False return True if __name__ == '__main__': if len(sys.argv) < 2: pri...
Python
0
388bbd915a5e40a2e096eb22ab294ffcbd3db936
Add a gmm, currently wrapping sklearn
bananas/model.py
bananas/model.py
import numpy # FIXME: copy the functions here from sklearn.mixture.gmm import log_multivariate_normal_density, logsumexp class GMM(object): def __init__(self, weights, means, covs): self.weights = numpy.array(weights) self.means = numpy.array(means) self.covs = numpy.array(covs) def s...
Python
0
b1bea70df1f62e4c0447a406b77266b804eec5df
add new Package (#15894)
var/spack/repos/builtin/packages/nanomsg/package.py
var/spack/repos/builtin/packages/nanomsg/package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Nanomsg(CMakePackage): """The nanomsg library is a simple high-performance implemen...
Python
0