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
fb16bb12e12fd820856ca0397a2cb4a857d2c7ca
chatbot function
src/tuling.py
src/tuling.py
# coding:utf-8 import requests def chatbot(body): resp = requests.post("http://www.tuling123.com/openapi/api", data={ # "key": "d59c41e816154441ace453269ea08dba", "key": "ff772ad12e0c421f98da2dd7f6a9289c", "info": body, "userid": "xiaopeng" }) resp = resp.json() ...
Python
0.999999
b090a41b42e82bb8cabd6fcde26ecdd8434e7757
Add a script to setup the DB auth for a simple scenario
setup/db_auth.py
setup/db_auth.py
# This script sets up authentication with the following setup # - one ADMIN_USER # - one RW_USER # - one RO_USER with createIndex privileges import sys import pymongo import argparse import traceback # Variables to change DB_HOST="localhost" ADMIN_USERNAME="test-admin" ADMIN_PASSWORD="test-admin-pw" RW_USERNAME="tes...
Python
0.999999
0a079e378fcb4994a2e1fd9bc8c71e22d4342901
Generate HTML snippet for Jekyll
kuveja-html.py
kuveja-html.py
#!/usr/bin/env python3 import json FILE = 'kuveja.json' PREFIX = 'http://joneskoo.kapsi.fi/kuveja/' HEADER = """--- layout: main title: joneskoon kuvafeedi ---""" HTML = """<div class="kuva"> <h3>%(title)s</h3> <img src="%(url)s" alt="%(title)s" /> </div>""" with open(FILE) as f: data = json.load(f) pri...
Python
0.999999
7303672fe9cf98c22afd83ae6c0dd7a136f4e5c8
Create hyperventilate.py
hyperventilate.py
hyperventilate.py
# -*- coding: utf-8 -*- """ Created on Fri Oct 02 14:39:39 2015 @author: William Herrera IMPORTANT: run as administrator Color breathing package for G20aj series PC """ import light_acpi as la from time import sleep def make_rgb(cred, cgreen, cblue): """ make rgb for components """ redval = int(ro...
Python
0.000254
e30f1c21363e96801f75ee6bf913d2ea3366d8f2
add browserid
settings.py
settings.py
LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale. USE_L10N = True # If you set ...
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 ...
Python
0.000001
260c7942b21329fd0190ebb0d0381283afa39afb
Add Nice Module
bitbots_common/src/bitbots_common/nice.py
bitbots_common/src/bitbots_common/nice.py
#-*- coding:utf-8 -*- """ Nice ^^^^ Dieses Modul vereinfacht die Manipulation des Nicelevels """ import os import time import multiprocessing import rospy class Nice(object): """ Diese Klasse stellt methoden bereit, um die relevanz des aktuellen Prozesses zu verändern. Wenn das runtersetzen des Nic...
Python
0
0ec3fd40c85f2a61eee5960031318c7f5ab06bc5
Allow whitelisted shell calls in transforms
humfrey/update/transform/shell.py
humfrey/update/transform/shell.py
import logging import subprocess import tempfile from django.conf import settings from .base import Transform, TransformException SHELL_TRANSFORMS = getattr(settings, 'SHELL_TRANSFORMS', {}) logger = logging.getLogger(__name__) class Shell(Transform): def __init__(self, name, extension, params): self.s...
Python
0.000001
eae844f96417ce0ec32fada7737a2d4ae8b03497
Add commandline tool
twitch.py
twitch.py
import re import argparse import urllib import json import os from twitchapi import TwitchAPI from twitchapi.twitch import TwitchToken TOKEN_FILE='.access_token' AUTH_SETTINGS_FILE='.auth_settings' args_pattern = re.compile(r'code=(?P<code>.*?)&scope=(?P<scopes>.*?)') def get_auth_settings(auth_settings_file): f...
Python
0.000005
2a1b46740c4cf14f7db4f344431aced9bf06d1e7
Add a little program that calls sync until is is done
scripts/sync_for_real.py
scripts/sync_for_real.py
#!/usr/bin/env python3 import subprocess import sys from time import time def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kwargs) def main(): nr_fast = 3 while nr_fast > 0: eprint('syncing... ', end='', flush=True) start_t = time() subprocess.Popen('/usr/bin/sync',...
Python
0.000001
5188a3b125d0a7479a95c15ba3ab3fe309d378a6
add xz2rpm.py
xz2rpm.py
xz2rpm.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' @author: mosquito @email: sensor.wen@gmail.com @project: xz2rpm @github: http://github.com/1dot75cm/repo-checker @description: xz(PKGBUILD) tranlate to rpm(spec). @version: 0.1 @history: 0.1 - Initial version (2016.03.15) ''' import os import sys import re import ...
Python
0
abdaa692977eb73b32a16d10936ae0254e8e48f5
Add an example for batch normalization.
batch_normalization/__init__.py
batch_normalization/__init__.py
"""Example of batch normalization tackling a difficult optimization. Running with --no-batch-normalize, we see that the algorithm makes very very slow progress in the same amount of time. """ import argparse from theano import tensor from blocks.algorithms import Adam, GradientDescent from blocks.bricks import MLP, B...
Python
0
3e2c4f19d1eb5d66430ea46abe18a6a7022e13ef
Create svg_filter.py
svg_filter.py
svg_filter.py
f = open("domusdomezones.svg", "r") svg = [] for line in f: line = line.strip() svg.append(line) f.close() vector_paths = [] for i in range(0, len(svg)): if svg[i] == "<path":# spot the paths location i = i+1 svg[i] = svg[i].replace(',', ' ')# remove the first 5 items in each path, replac...
Python
0.000006
353d717c425cca9941d650d715c3ed8caf0aae64
Reset tooltip timer also when cell editor is closed
src/robotide/editor/tooltips.py
src/robotide/editor/tooltips.py
# Copyright 2008-2009 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
# Copyright 2008-2009 Nokia Siemens Networks Oyj # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
Python
0
86434fb902caeea7bb740c35607dc6f9f7766d88
Fix searching for notes in the django admin
notes/admin.py
notes/admin.py
# # Copyright (c) 2009 Brad Taylor <brad@getcoded.net> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This...
# # Copyright (c) 2009 Brad Taylor <brad@getcoded.net> # # This program is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, either version 3 of the License, or (at your option) any # later version. # # This...
Python
0
75717747ffbc36f306e0f771a65ed101bd3ca9be
Create parser.py
parser.py
parser.py
from HTMLParser import HTMLParser # create a subclass and override the handler methods class Parser(HTMLParser): tag = "" doc = new Document() def handle_starttag(self, tag, attrs): tag = tag print "Encountered a start tag:", tag def handle_endtag(self, tag): tag = "" ...
Python
0.000011
ecde3b823724e612fd4e5cc575eb75f0d3652a4b
add script for running test
test/run-test.py
test/run-test.py
import imp import json import os mustache = imp.load_source('mustache', '../src/mustache.py') #test_files = ['comments.json', #'delimiters.json', #'interpolation.json', #'inverted.json', #'~lambdas.json', #'partials.json', #'sections.json'] test_files = ['interpolation.json', 'delimite...
Python
0.000001
0feb8f3ae65fadaf600e7681349cfa537b41a8c3
Add ParseBigCSV.py
parseBigCSV.py
parseBigCSV.py
import csv import json with open("evidata.csv", "r") as bigCSV: with open("file.json", "w") as outFile: reader = csv.DictReader(bigCSV) output = json.dumps(list(reader)) outFile.write(output)
Python
0.000001
31434ff2f5b208ae1d93b4340e1d28cfe5cb2e42
Add IMDB Mocked Unit Test (#1579)
test/datasets/test_imdb.py
test/datasets/test_imdb.py
import os import random import string import tarfile from collections import defaultdict from unittest.mock import patch from parameterized import parameterized from torchtext.datasets.imdb import IMDB from ..common.case_utils import TempDirMixin, zip_equal from ..common.torchtext_test_case import TorchtextTestCase ...
Python
0
29b09f283a2a62824a4e1f7ae05a5bb64db0a149
Create fire_th_trollius.py
django_th/management/commands/fire_th_trollius.py
django_th/management/commands/fire_th_trollius.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import datetime import time import arrow import trollius as asyncio from trollius import From from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django_th.services import...
Python
0.000005
3536b98a3adf5087c78b92432585654bec40d64e
add problem 045
problem_045.py
problem_045.py
#!/usr/bin/env python #-*-coding:utf-8-*- ''' ''' import math import timeit def is_pentagonal(n): if (1+math.sqrt(1+24*n)) % 6 == 0: return True else: return False def calc(): i = 143 while True: i += 1 n = i*(2*i-1) if is_pentagonal(n): return n...
Python
0.000294
ef95e8f3c9c9f12b7073b02e95c2a464ed26c8df
hard code the value of the service url
ceph_installer/cli/constants.py
ceph_installer/cli/constants.py
server_address = 'http://localhost:8181/'
Python
0.999698
91bb7506bd20ed22b8787e7a8b9975cc07e97175
Add owners client to depot_tools.
owners_client.py
owners_client.py
# Copyright (c) 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class OwnersClient(object): """Interact with OWNERS files in a repository. This class allows you to interact with OWNERS files in a repository both...
Python
0.000001
beae2bdc47949f78e95e3444d248ce035766e719
Add ascii table test
smipyping/_asciitable.py
smipyping/_asciitable.py
# (C) Copyright 2017 Inova Development Inc. # 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 appl...
Python
0.000007
672e4378421d2014644e23195706ef011934ffdb
test for fixes on #55
category_encoders/tests/test_basen.py
category_encoders/tests/test_basen.py
import category_encoders as ce import unittest import pandas as pd __author__ = 'willmcginnis' class TestBasen(unittest.TestCase): """ """ def test_basen(self): df = pd.DataFrame({'col1': ['a', 'b', 'c'], 'col2': ['d', 'e', 'f']}) df_1 = pd.DataFrame({'col1': ['a', 'b', 'd'], 'col2': ['d...
Python
0
a4c8818225941b84e6958dcf839fc78c2adc5cee
Create test_pxssh.py
test_pxssh.py
test_pxssh.py
# commandsshbotnet.py # author: @shipcod3 # # >> used for testing the pxssh module import pxssh import getpass try: s = pxssh.pxssh() hostname = raw_input('SET HOST: ') username = raw_input('SET USERNAME: ') password = getpass.getpass('SET PASSWORD: ') s.login (hostname, username, password) s....
Python
0.000005
1be4e6f97b3d062c4fa07f70b05305bf32593fd4
Add test cases for smudge
dotbriefs/tests/test_smudge.py
dotbriefs/tests/test_smudge.py
import unittest from dotbriefs.smudge import SmudgeTemplate class TestCleanSecret(unittest.TestCase): def setUp(self): self.secrets = {} self.secrets['password'] = 's3cr3t' self.secrets['question'] = 'h1dd3n 4g3nd4' self.template = [] self.template.append(SmudgeTemplate('...
Python
0.000002
aa2d97dfe52628e1bb7ab123890a895f7f630cda
add problem 070
problem_070.py
problem_070.py
#!/usr/bin/env python #-*-coding:utf-8-*- ''' ''' from fractions import Fraction import itertools import math import timeit primes = [2, 3, 5, 7] def is_prime(n): for p in primes: if n % p == 0: return False for i in range(max(primes), int(math.sqrt(n))+1): if n % i == 0: ...
Python
0.000962
16ccb2a670461e8ceb9934fd4ba8823b866c9d8e
Create plot.py
src/plot.py
src/plot.py
import pandas as pd from matplotlib import pyplot as plt from abc import ABCMeta, abstractmethod class Plot(metaclass=ABCMeta): @abstractmethod def show(self): plt.show() class CsvPlot(Plot): def __init__(self, parent_path): self.parent_path = parent_path def show(self, is_execute=F...
Python
0.000021
254239102955bb8916aab98530251b5cdd79ce50
Add script to write base signatures
cypher/siggen.py
cypher/siggen.py
#!/usr/bin/env python import argparse import subprocess import os import shutil import sys from util import write_signature parser = argparse.ArgumentParser() parser.add_argument( "-l", "--language", help="Source code language.", required=True ) TEMP_DIR = os.path.join(os.getcwd(), "cypher", "temp") ...
Python
0.000001
fe8d131a3cb9484cfe3f1b96102c0333077ffe89
Add some basic tests
tests/test_basic.py
tests/test_basic.py
from cider import Cider from mock import MagicMock, call import pytest import random @pytest.mark.randomize(formulas=[str], cask=bool, force=bool) def test_install(tmpdir, formulas, cask, force): cider = Cider(cider_dir=str(tmpdir), cask=cask) cider.brew = MagicMock() cider.install(*formulas, force=force...
Python
0.000012
19b13f0fb9b86ec99025bd1baf2c4d5fe757f809
Add a test to make sure exception is raised
tests/test_tests.py
tests/test_tests.py
import pytest def test_BeautifulSoup_methods_are_overridden( client_request, mock_get_service_and_organisation_counts, ): client_request.logout() page = client_request.get("main.index", _test_page_title=False) with pytest.raises(AttributeError) as exception: page.find("h1") assert st...
Python
0
1f4190a6d4ef002e75a8ac5ef80d326c712c749c
add test to verify the trace assignment
tests/test_trace.py
tests/test_trace.py
from __future__ import absolute_import import pytest from tchannel import TChannel, schemes from tchannel.errors import BadRequestError from tchannel.event import EventHook @pytest.mark.gen_test def test_error_trace(): tchannel = TChannel('test') class ErrorEventHook(EventHook): def __init__(self):...
Python
0
7fa8417cb7635e238f1e95971fa0a86a95b64dca
Migrate deleted_at fields away
aleph/migrate/versions/aa486b9e627e_hard_deletes.py
aleph/migrate/versions/aa486b9e627e_hard_deletes.py
"""Hard delete various model types. Revision ID: aa486b9e627e Revises: 9dcef7592cea Create Date: 2020-07-31 08:56:43.679019 """ from alembic import op import sqlalchemy as sa revision = "aa486b9e627e" down_revision = "9dcef7592cea" def upgrade(): meta = sa.MetaData() meta.bind = op.get_bind() meta.refl...
Python
0
c61d3d5b4b31912c48e86425fe7e4861fc2f8c28
test for read_be_array that fails in Python 2.x (see GH-6)
tests/test_utils.py
tests/test_utils.py
# -*- coding: utf-8 -*- from __future__ import absolute_import from io import BytesIO from psd_tools.utils import read_be_array def test_read_be_array_from_file_like_objects(): fp = BytesIO(b"\x00\x01\x00\x05") res = read_be_array("H", 2, fp) assert list(res) == [1, 5]
Python
0
eb82e816e4dece07aeebd7b9112156dacdb2d9bc
Add set_global_setting.py, not sure how this file dissapeared
commands/set_global_setting.py
commands/set_global_setting.py
from .command import CmakeCommand class CmakeSetGlobalSettingCommand(CmakeCommand): def run(self): self.server.global_settings()
Python
0.000002
96bea6812919067c28e0c28883226434d81f6e8d
add locusattrs class
locuspocus/locusattrs.py
locuspocus/locusattrs.py
class LocusAttrs(): # a restricted dict interface to attributes def __init__(self,attrs=None): self._attrs = attrs def __len__(self): if self.empty: return 0 else: return len(self._attrs) def __eq__(self, other): if self.empty and other.empty: ...
Python
0
cebb3a9cdbdee7c02b0c86e1879d0c20d36b4276
add example
examples/example_cityfynder.py
examples/example_cityfynder.py
# Which city would like to live? # Created by City Fynders - University of Washington import pandas as pd import numpy as np import geopy as gy from geopy.geocoders import Nominatim import data_processing as dp from plotly_usmap import usmap # import data (natural, human, economy, tertiary) = dp.read_data() # Ad...
Python
0.000002
9269afee9099ef172ac2ef55ea0af85b0c77587a
Add databases.py
py/database.py
py/database.py
import sqlalchemy import sqlalchemy.orm import uuid import configmanager class ConnectionManager(): _connections = {} @staticmethod def addConnection(self, connection, connectionName = uuid.uuid4().hex): if type(connectionName) == str: if type(connection) == DatabaseConnection: _connections[connectionName...
Python
0.000001
5dfb7ad67216b31544c5f4dc785930ef0d9ffd56
add faceAssigned tester
python/medic/plugins/Tester/faceAssigned.py
python/medic/plugins/Tester/faceAssigned.py
from medic.core import testerBase from maya import OpenMaya class FaceAssigned(testerBase.TesterBase): Name = "FaceAssigned" def __init__(self): super(FaceAssigned, self).__init__() def Match(self, node): return node.object().hasFn(OpenMaya.MFn.kDagNode) def Test(self, node): ...
Python
0
971570b4288c9ac7131a1756e17574acbe6d1b9a
Add script for converting a solarized dark file to solarized dark high contrast
python/misc/solarized-dark-high-contrast.py
python/misc/solarized-dark-high-contrast.py
#!/usr/bin/env python import sys if sys.version_info < (3, 4): sys.exit('ERROR: Requires Python 3.4') from enum import Enum def main(): Cases = Enum('Cases', 'lower upper') infile_case = None if len(sys.argv) < 2: sys.stderr.write('ERROR: Must provide a file to modify\n') sys.ex...
Python
0
b72c421696b5714d256b7ac461833bc692ca5354
Add an autonomous mode to strafe and shoot. Doesn't work
robot/robot/src/autonomous/hot_aim_shoot.py
robot/robot/src/autonomous/hot_aim_shoot.py
try: import wpilib except ImportError: from pyfrc import wpilib import timed_shoot class HotShootAutonomous(timed_shoot.TimedShootAutonomous): ''' Based on the TimedShootAutonomous mode. Modified to allow shooting based on whether the hot goal is enabled or not. ''' ...
Python
0.000002
3c046062af376603145545f37b917a5c927b3aba
Create mergesort_recursive.py
recursive_algorithms/mergesort_recursive.py
recursive_algorithms/mergesort_recursive.py
def merge_sort(array): temp = [] if( len(array) == 1): return array; half = len(array) / 2 lower = merge_sort(array[:half]) upper = merge_sort(array[half:]) lower_len = len(lower) upper_len = len(upper) i = 0 j = 0 while i != lower_len or j != upper_len: i...
Python
0.000004
06b0f93ecd5fac8eda02fce96c1e4ec0306a7989
Increase coverage
test/test_google.py
test/test_google.py
# -*- coding: utf8 -*- # This file is part of PyBossa. # # Copyright (C) 2013 SF Isle of Man Limited # # PyBossa is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at...
Python
0
17e2b9ecb67c8b1f3a6f71b752bc70b21584092e
Add initial tests for scriptserver.
tests/test_scriptserver.py
tests/test_scriptserver.py
import unittest from mock import patch, Mock import sys sys.path.append(".") from scriptserver import ZoneScriptRunner class TestZoneScriptRunner(unittest.TestCase): @classmethod def setUpClass(cls): cls.mongoengine_patch = patch('scriptserver.me') cls.mongoengine_patch.start() @classmeth...
Python
0
81eea6809f369ccabc55f7b53edbc1c2b961f146
Create get_random_generate_number_sendmessage.py
get_random_generate_number_sendmessage.py
get_random_generate_number_sendmessage.py
#!/usr/local/bin/python2.7 # -*- coding: utf-8 -*- __author__ = 'https://github.com/password123456/' import random import numpy as np import sys reload(sys) sys.setdefaultencoding('utf-8') import requests import urllib import urllib2 import json import datetime import time import dateutil.relativedelta as REL class b...
Python
0.000189
e5243d0fb792e82825633f1afdd6e799238a90f3
Add portable buildtools update script (#46)
tools/buildtools/update.py
tools/buildtools/update.py
#!/usr/bin/python # Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Pulls down tools required to build flutter.""" import os import subprocess import sys SRC_ROOT = (os.path.dirname(os.path.d...
Python
0
d1f02226fe805fb80a17f1d22b84b748b65b4e7f
add sam2fq.py
sam2fq.py
sam2fq.py
import sys from collections import namedtuple Read = namedtuple('Read', ['name','qual','seq']) read1 = None left = open('pe_1.fq', 'w') right = open('pe_2.fq', 'w') unpaired = open('unpaired.fq', 'w') for line in sys.stdin: items = line.split('\t') name, qual, seq = items[0], items[10], items[9] if not re...
Python
0.001125
dbdfb1b5a703e0392ca67a03113e607678015a66
add kattis/settlers2
Kattis/settlers2.py
Kattis/settlers2.py
""" Problem: settlers2 Link: https://open.kattis.com/problems/settlers2 Source: NWERC 2009 """ from collections import defaultdict import math MAXN = 10000 currentPosition = (0,0) currentNum = 1 counter = defaultdict() layers = 1 direction = 0 directionCounter = 0 limitDirectionCounter = [layers, layers-1, layers, la...
Python
0.001804
48443f8a8f5a15b3116ba7b4a842189f5e659f26
test script for pymatbridge
test_pymatbridge.py
test_pymatbridge.py
#!/usr/bin/python from pymatbridge import Matlab mlab = Matlab() mlab.start() print "Matlab started?", mlab.started print "Matlab is connected?", mlab.is_connected() mlab.run_code("conteo = 1:10") mlab.run_code("magica = magic(5)") mlab.stop()
Python
0
4d08d50d73e8d3d3a954c9ef8ddffc23444d7d28
Create script.py
script.py
script.py
#!/usr/bin/env python3 # première tentative de documenter l'API de coco.fr import random import requests pseudo = "caecilius" # doit être en minuscule et de plus de 4 caractères age = "22" # minimum "18" sexe = "1" # "1" pour homme, "2" pour femme codeville = "30929" # à récuperer ici http://co...
Python
0.000002
cc0d6a3b782c5646b9742ebe7308b42507ed2714
Add python API draft interface
python/kmr4py.py
python/kmr4py.py
class MapReduce(object): def reply_to_spawner(self): pass def get_spawner_communicator(self, index): pass def send_kvs_to_spawner(self, kvs): pass def concatenate_kvs(self, kvss): pass def map_once(self, mapfn, kvo_key_type=None, rank_zero_only=Fa...
Python
0.000001
dbacf8cd0c2bae394b6c67a810836668d510787d
test for index (re)generation
tests/test_index.py
tests/test_index.py
from cheeseprism.utils import resource_spec from itertools import count from path import path from pprint import pprint import unittest class IndexTestCase(unittest.TestCase): counter = count() base = "egg:CheesePrism#tests/test-indexes" def make_one(self, index_name='test-index'): from chees...
Python
0
554c6490330760690fbbd1cd5ece3da563e342eb
update queen4.py
python/queen4.py
python/queen4.py
f = lambda A, x, y: y < 0 or (not (A[y] in (A[x], A[x] + (x - y), A[x] - (x - y)))) g = lambda A, x, y: (not x) or (f(A, x, y) and ((y < 0) or g(A, x, y - 1))) h = lambda A, x: sum([ g(A, x, x - 1) and 1 or 0 for A[x] in range(len(A)) ]) q = lambda A, x: h(A, x) if (x == 7) else sum([ q(A, x + 1) for A[x] in range(8...
Python
0.000001
7d2c728cb121a0aefef11fd3c8ab7b7f700516e8
read grove pi sensors
readSensors.py
readSensors.py
import time import decimal import grovepi import math from grovepi import * from grove_rgb_lcd import * sound_sensor = 0 # port A0 light_sensor = 1 # port A1 temperature_sensor = 2 # port D2 led = 4 # port D3 lastTemp = 0.1 # initialize a floating point temp variable lastHum =...
Python
0.000001
076fcbb4876bd76887f7d64b533fec66f8366b70
Add tests for cancellation
openprocurement/tender/esco/tests/cancellation.py
openprocurement/tender/esco/tests/cancellation.py
# -*- coding: utf-8 -*- import unittest from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.tests.cancellation import ( TenderCancellationResourceTestMixin, TenderCancellationDocumentResourceTestMixin ) from openprocurement.tender.belowthreshold.tests.cancellation_blan...
Python
0
77c582939734866eee09b55e9db02437b42c5451
Create stemming.py
stemming.py
stemming.py
# -*- coding: utf-8 -*- # Портирован с Java по мотивам http://www.algorithmist.ru/2010/12/porter-stemmer-russian.html import re class Porter: PERFECTIVEGROUND = re.compile(u"((ив|ивши|ившись|ыв|ывши|ывшись)|((?<=[ая])(в|вши|вшись)))$") REFLEXIVE = re.compile(u"(с[яь])$") ADJECTIVE = re.compile(u"(ее|ие|ые|ое|ими|ы...
Python
0.000001
abe586ac1275901fc9d9cf1bde05b225a9046ab7
add admin tests
test/test_admin.py
test/test_admin.py
from werkzeug.exceptions import Unauthorized from flask import url_for from flask_login import current_user from .conftest import logged_in, assert_logged_in, assert_not_logged_in, create_user from app.user import random_string from app.form.login import ERROR_ACCOUNT_DISABLED USERNAME = 'cyberwehr87654321' PASSWORD...
Python
0
b63e65b1a41f809caf1c2dcd689955df76add20f
Add a plot just of backscatter phase vs. diameter.
test/test_delta.py
test/test_delta.py
import matplotlib.pyplot as plt import numpy as np import scattering import scipy.constants as consts def plot_csec(scatterer, d, var, name): plt.plot(d / consts.centi, var, label='%.1f cm' % (scatterer.wavelength / consts.centi)) plt.xlabel('Diameter (cm)') plt.ylabel(name) def plot_csecs(d, ...
Python
0
e1d8c17746497a46c864f352823cd86b2216781c
Add commit ID milestone helper script (#7100)
docs/_bin/get-milestone-prs.py
docs/_bin/get-milestone-prs.py
#!/usr/bin/env python3 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "Lic...
Python
0
55768b5133d8155b16e798a335cc0f46930aab12
create my own .py for question 5
totaljfb/Q5.py
totaljfb/Q5.py
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: Jason Zhang # # Created: 15/11/2017 # Copyright: (c) Jason Zhang 2017 # Licence: <your licence> #------------------------------------------------------------------------------- ...
Python
0.000092
3cb42b54fa8ed2cac6e05aa521a3a61a037a35ee
add rest cliant on python
rest/client.py
rest/client.py
# pip install requests import requests resp = requests.post("http://127.0.0.1:8008/api/v1/addrecord/3", json='{"id":"name"}') print resp.status_code print resp.text resp = requests.get("http://127.0.0.1:8008/api/v1/getrecord/3") print resp.status_code print resp.json() resp = requests.get("http://127.0.0.1:8008/api/v...
Python
0
d0f6167cb7e95c17997bc42af6cd1766b1ac7864
add related_name migration
paralapraca/migrations/0005_auto_20171204_1006.py
paralapraca/migrations/0005_auto_20171204_1006.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('paralapraca', '0004_contract_classes'), ] operations = [ migrations.AlterField( model_name='contract', ...
Python
0.000002
e84d19bdc580f4d392f5b7abdc4eb8eb30919cf5
add example: negative binomial maximum likelihood via newton's method
examples/negative_binomial_maxlike.py
examples/negative_binomial_maxlike.py
from __future__ import division, print_function import autograd.numpy as np import autograd.numpy.random as npr from autograd.scipy.special import gammaln from autograd import grad import scipy.optimize # The code in this example implements a method for finding a stationary point of # the negative binomial likelihoo...
Python
0.003656
6d96e9d67e50d7806be175577968ec8fed8393d7
Create libBase.py
test/libBase.py
test/libBase.py
# ./test/testCommon.py ''' There are some assumptions made by this unittest the directory structure + ./ | files -> lib*.py +----./local/* | | files -> *.ini | | files -> *.json | | files ->*.csv +----./log/* | | files -> *.log +----./test/* | files -> test*.py +----./test_input...
Python
0.000001
4172b35bfdd1b4b12592d81b07843ca2c902a732
solved 45
045/eul045.py
045/eul045.py
#! /usr/bin/python from __future__ import print_function from time import time from math import sqrt # Project Euler # 45 # Since an integer x is triangular if and only if 8x + 1 is a square def is_triangle(x): return sqrt(8 * x + 1).is_integer() def is_pentagonal(x): if x < 1: return False n =...
Python
0.999983
b209c45fe32ee7b73bddff5419c1931a16da0bbd
Test file request.py
test/request.py
test/request.py
#!/usr/bin/python # -*- coding: utf-8 -*- import urllib2 import threading def worker(): urllib2.urlopen('http://localhost:8080').read() if __name__ == '__main__': for i in xrange(1024): threading.Thread(target=worker).start() print 'Partiti...'
Python
0.000003
be544817908ba3f9377d24a61047496c3dbf4f7a
Add test
test_rlev_model.py
test_rlev_model.py
import os import unittest from click.testing import CliRunner from rlev_model import cli class TestCli(unittest.TestCase): def test_cli(self): runner = CliRunner() sample_filename = os.path.join('data', 'sample-data.txt') result = runner.invoke(cli, [sample_filename]) assert resu...
Python
0.000005
63e28f211d49a5f5d7be011071e5e16595f8b881
Create SixChannelReader.py
SixChannelReader.py
SixChannelReader.py
""" Interface between python and arduino for 6-channel data logger Author: James Keaveney 18/05/2015 """ import time import csv import serial import sys import cPickle as pickle import numpy as np import matplotlib.pyplot as plt nchannels = 7 # number of total channels (time axis + ADC channels) datalen = 200 # nu...
Python
0
f211fc4b0467c2d12d0ee60caed4c76910684f65
Create game.py
Source-Code/game.py
Source-Code/game.py
# ****************************************************************************** # Bingo # # @author: Elisha Lai # @desciption: Program that allows a player to play Bingo # @version: 1.3 12/03/2014 # ****************************************************************************** # negate_mini_bingo_card: (listof...
Python
0
da2a4fa9e618b212ddbb2fcbc079fa37970ae596
Add handler for concurrently logging to a file
tfd/loggingutil.py
tfd/loggingutil.py
''' Utilities to assist with logging in python ''' import logging class ConcurrentFileHandler(logging.Handler): """ A handler class which writes logging records to a file. Every time it writes a record it opens the file, writes to it, flushes the buffer, and closes the file. Perhaps this could cre...
Python
0
ba599deb23c75a6dbcbc0de897afedc287c2ea94
Create 02str_format.py
02str_format.py
02str_format.py
age = 38 name = 'Murphy Wan' print('{0} is {1} yeaers old'.format(name, age)) print('why is {0} playing with that python?'.format(name))
Python
0.000019
464f011b2a87d18ea3e8d16339898987cf190a72
Task2_1
test_example.py
test_example.py
import pytest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait #from selenium.webdriver.support import expected_conditions as EC @pytest.fixture def driver(request): wd = webdriver.Safari() print(wd.capabilities) request.addfinalizer(wd.quit) return wd def tes...
Python
0.999999
700db5c742be8a893b1c362ae0955a934b88c39b
Add test_learning_journal.py with test_app() for configuring the app for testing
test_journal.py
test_journal.py
# -*- coding: utf-8 -*- from contextlib import closing import pytest from journal import app from journal import connect_db from journal import get_database_connection from journal import init_db TEST_DSN = 'dbname=test_learning_journal' def clear_db(): with closing(connect_db()) as db: db.cursor().exec...
Python
0.000005
59d51e90203a20f9e0b01eda43afc268311009e7
Comment about JSON
firefox/src/py/extensionconnection.py
firefox/src/py/extensionconnection.py
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
Python
0
1f3c1af308be68393ac8f7caab17d04cdd632d2b
Add the get_arguments function in include
survey_creation/include/get_arguments.py
survey_creation/include/get_arguments.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import getopt """ Short script to parse the argments from the command line """ def get_arguments(argv): """ """ country = None year = None try: opts, args = getopt.getopt(argv, 'hc:y:', ['country=', 'year=']) except getopt.Geto...
Python
0.000027
0d1816fe41f0e380705fb156fd7b0cd175ad3552
Add a command to import some initial candidate data
elections/ar_elections_2015/management/commands/ar_elections_2015_import_candidates.py
elections/ar_elections_2015/management/commands/ar_elections_2015_import_candidates.py
# -*- coding: utf-8 -*- from datetime import date import dateutil.parser import json from os.path import dirname, join import re import requests from slumber.exceptions import HttpClientError from django.conf import settings from django.contrib.auth.models import User from django.core.files.storage import FileSystem...
Python
0.000002
4276e1b991ea923a2a3bdd227bb3d98ced1fd4e2
add alias function
thefuck/main.py
thefuck/main.py
from imp import load_source from pathlib import Path from os.path import expanduser from subprocess import Popen, PIPE import os import sys from psutil import Process, TimeoutExpired import colorama from . import logs, conf, types def setup_user_dir(): """Returns user config dir, create it when it doesn't exist."...
from imp import load_source from pathlib import Path from os.path import expanduser from subprocess import Popen, PIPE import os import sys from psutil import Process, TimeoutExpired import colorama from . import logs, conf, types def setup_user_dir(): """Returns user config dir, create it when it doesn't exist."...
Python
0.000005
fc103544a7fcd8506e4d1612f70ff4b5d3eb6dfe
add command to set prices and commissions of teacher levels
server/app/management/commands/set_level_price.py
server/app/management/commands/set_level_price.py
from django.core.management.base import BaseCommand from app.models import Region, Grade, Subject, Ability, Level, Price class Command(BaseCommand): help = "设置教师级别的价格和佣金比例\n" \ "例如: \n" \ " python manage.py set_level_price 郑州市 --percentages '20,20,20,20,20,20,20,20,20,20' --prices '2000,30...
Python
0
d7945d85dcce968d6430e079662b1ef9fc464c97
update ukvi org branding spelling
migrations/versions/0047_ukvi_spelling.py
migrations/versions/0047_ukvi_spelling.py
"""empty message Revision ID: 0047_ukvi_spelling Revises: 0046_organisations_and_branding Create Date: 2016-08-22 16:06:32.981723 """ # revision identifiers, used by Alembic. revision = '0047_ukvi_spelling' down_revision = '0046_organisations_and_branding' from alembic import op def upgrade(): op.execute(""" ...
Python
0
a2463270e6850b0e7df210c03946bfba449f29d7
Add a test for simultaneous device access
test/parallel_test.py
test/parallel_test.py
""" mbed CMSIS-DAP debugger Copyright (c) 2016 ARM Limited 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 o...
Python
0
be3acc4a869c9e45e4d1fdd563571da0d12ae85f
Add modify code Hello World code
HelloWorld.py
HelloWorld.py
print("HelloWorld") text="HelloWorld_Text" print(text)
Python
0.000857
f2864289f02a6e221d6fafbb1885d20aa26417fd
Add default conftest
test/unit/conftest.py
test/unit/conftest.py
# :coding: utf-8 import os import shutil import tempfile import uuid import pytest @pytest.fixture() def unique_name(): """Return a unique name.""" return "unique-{0}".format(uuid.uuid4()) @pytest.fixture() def temporary_file(request): """Return a temporary file path.""" file_handle, path = tempfi...
Python
0.000001
1dba0fb24f98bb09bd0c918439c0457c603e1386
Create ullman.py
ullman.py
ullman.py
import requests from multiprocessing import Pool import time startURL = 'http://i.stanford.edu/~ullman/focs/ch' extension = '.pdf' savePath = '' #enter the path for the pdfs to be stored on your system chapters = range(1,15) #chapters 1-14 def chapterStringManipulate(chapter): if chapter < 10 : download('0{}'.f...
Python
0.000001
9d3925c4809791d2366bc1d6fd6b04bc8a710c9b
add fmt to repo
toolshed/fmt.py
toolshed/fmt.py
import re def fmt2header(fmt): """ Turn a python format string into a usable header: >>> fmt = "{chrom}\t{start:d}\t{end:d}\t{pvalue:.4g}" >>> fmt2header(fmt) 'chrom start end pvalue' >>> fmt.format(chrom='chr1', start=1234, end=3456, pvalue=0.01232432) 'chr1 1234 3456 0.01232...
Python
0
dd9b683b24cea02c93a6e23a163065c0f26f6a68
Test manager
tests/test.manager.py
tests/test.manager.py
import opensim model_path = "../osim/models/arm2dof6musc.osim" model = opensim.Model(model_path) model.setUseVisualizer(True) state = model.initSystem() manager = opensim.Manager(model) muscleSet = model.getMuscles() stepsize = 0.01 for i in range(10): for j in range(muscleSet.getSize()): # muscleSet.get(j...
Python
0.000003
5d18f7c7145bf8d5e7248392d644e521222929b8
add tests for _extras
tests/test__extras.py
tests/test__extras.py
"""Tests for ``_extras`` module.""" import pytest from rstcheck import _compat, _extras class TestInstallChecker: """Test ``is_installed_with_supported_version``.""" @staticmethod @pytest.mark.skipif(_extras.SPHINX_INSTALLED, reason="Test for absence of sphinx.") def test_false_on_missing_sphinx_pac...
Python
0.000001
eb1c7d1c2bfaa063c98612d64bbe35dedf217143
Add initial tests for alerter class
tests/test_alerter.py
tests/test_alerter.py
import unittest import datetime import Alerters.alerter class TestAlerter(unittest.TestCase): def test_groups(self): config_options = {'groups': 'a,b,c'} a = Alerters.alerter.Alerter(config_options) self.assertEqual(['a', 'b', 'c'], a.groups) def test_times_always(self): conf...
Python
0
33658163b909073aae074b5b2cdae40a0e5c44e8
Add unit tests for asyncio coroutines
tests/test_asyncio.py
tests/test_asyncio.py
from trollius import test_utils from trollius import From, Return import trollius import unittest try: import asyncio except ImportError: from trollius.test_utils import SkipTest raise SkipTest('need asyncio') # "yield from" syntax cannot be used directly, because Python 2 should be able # to execute thi...
Python
0.000001
72ff3bfcbfb9e4144d43ca03c77f0692cccd0fc2
add small interface for DHT Adafruit lib (in rpi.py)
gsensors/rpi.py
gsensors/rpi.py
#-*- coding:utf-8 -*- """ Drivers for common sensors on a rPi """ import sys import gevent from gsensors import AutoUpdateValue class DHTTemp(AutoUpdateValue): def __init__(self, pin, stype="2302", name=None): update_freq = 10 #seconds super(DHTTemp, self).__init__(name=name, unit="°C", update_fr...
Python
0
3bc341036730ab8e9fd5ac61e10556af028813e2
Add migration -Remove dupes -Add index preventing dupe creation
osf/migrations/0044_basefilenode_uniqueness_index.py
osf/migrations/0044_basefilenode_uniqueness_index.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import logging from django.db import connection from django.db import migrations logger = logging.getLogger(__name__) def remove_duplicate_filenodes(*args): from osf.models.files import BaseFileNode sql = """ SELECT id FROM (SELE...
Python
0
e322daa6d92a9dad8db9b8c9b6085aded90bef39
add beta release script
scripts/release_beta.py
scripts/release_beta.py
import argparse import subprocess parser = argparse.ArgumentParser(description='Release Mixpanel Objective-C SDK') parser.add_argument('--old', help='old version number', action="store") parser.add_argument('--new', help='new version number for the release', action="store") args = parser.parse_args() def bump_versi...
Python
0
c783c26c6362cdd0702211552578a09f380e9dac
Add tags module.
src/pu/tags.py
src/pu/tags.py
# # Copyright (c) 2013 Joshua Hughes <kivhift@gmail.com> # import sys class Tag(object): _name = '' def __init__(self, *a, **kw): super(Tag, self).__init__() self.content = list(a) self.attributes = kw def __str__(self): name = self._name content = ''.join(str(c) fo...
Python
0
9c6130b5f9337b428f530cfae7036b7be2a9eea4
test commit
etk2/DefaultDocumentSelector.py
etk2/DefaultDocumentSelector.py
import json import jsonpath_rw import re from document import Document class DefaultDocumentSelector(DocumentSelector): def __init__(self): pass """ A concrete implementation of DocumentSelector that supports commonly used methods for selecting documents. """ """ Args: ...
Python
0.000001
e5f77ccc2f51fdcaa32c55b56f6b801b3ae2e0e2
Add triggered oscilloscope example
example/pyaudio_triggerscope.py
example/pyaudio_triggerscope.py
""" Simple demonstration of streaming data from a PyAudio device to a QOscilloscope viewer. Both device and viewer nodes are created locally without a manager. """ from pyacq.devices.audio_pyaudio import PyAudio from pyacq.viewers import QTriggeredOscilloscope import pyqtgraph as pg # Start Qt application app = pg....
Python
0.000001
5c5c2e9ae69b6543830975239068d34620205119
add context logger
logging/logger_reload_with_context.py
logging/logger_reload_with_context.py
import logging import traceback from yaml_config import yaml_config yaml_config('yaml.conf') class ContextLogger(object): def __init__(self, name): self.logger = logging.getLogger(name) def _context(self): stack = traceback.extract_stack() (filename, line, procname, text) = stack[-3]...
Python
0.000007
bc7f1363a7da1375b62f70caf441423af2718641
Create example.py
BMP085/example.py
BMP085/example.py
# Continuously polls the BMP180 Pressure Sensor import pyb import BMP085 # creating objects blue = pyb.LED(4) bmp180 = BMP085.BMP085(port=2,address=0x77,mode=3,debug=False) while 1: blue.toggle() temperature = bmp180.readTemperature() print("%f celcius" % temperature) pressure = bmp180.readPressure() pr...
Python
0.000001
91827cdbc202950d05053cd82147828e02b861c0
Add migration to backfill flowpathcounts
temba/flows/migrations/0076_auto_20161202_2114.py
temba/flows/migrations/0076_auto_20161202_2114.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.db.models import Func, Value, Count from temba.utils import chunk_list from django_redis import get_redis_connection from django.db import connection import time HIGHPOINT_KEY = 'flowpathcount_backfill...
Python
0
153d36cd0c9eb4229156ac944c2ba64f2f9e72d6
fix test
msmbuilder/tests/test_featurizer.py
msmbuilder/tests/test_featurizer.py
import numpy as np from mdtraj import compute_dihedrals, compute_phi from mdtraj.testing import eq from msmbuilder.example_datasets import fetch_alanine_dipeptide from msmbuilder.featurizer import get_atompair_indices, FunctionFeaturizer, \ DihedralFeaturizer, AtomPairsFeaturizer, SuperposeFeaturizer, \ RMSDFe...
import numpy as np from mdtraj import compute_dihedrals, compute_phi from mdtraj.testing import eq from msmbuilder.example_datasets import fetch_alanine_dipeptide from msmbuilder.featurizer import get_atompair_indices, FunctionFeaturizer, \ DihedralFeaturizer, AtomPairsFeaturizer, SuperposeFeaturizer, \ RMSDFe...
Python
0.000002
6c08209ee26210df07b9d80da45d815b595205ae
test for new Wigner function
test_wigner.py
test_wigner.py
from qutip import * from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from pylab import * N = 20; psi=(coherent(N,-2-2j)+coherent(N,2+2j)).unit() #psi = ket2dm(basis(N,0)) xvec = linspace(-5.,5.,200) yvec = xvec X,Y = meshgrid(xvec, yvec) W = wigner(psi,xvec,xvec); fig2 = plt.figure(figsize=(9, 6)) ax =...
Python
0.000001
1ffdfc3c7ae11c583b2ea4d45b50136996bcf3e3
Add mock HTTP server to respond to requests from web UI
tests/mocks.py
tests/mocks.py
from http.server import BaseHTTPRequestHandler, HTTPServer import json import socket from threading import Thread import requests # https://realpython.com/blog/python/testing-third-party-apis-with-mock-servers/ class MockHTTPServerRequestHandler(BaseHTTPRequestHandler): def do_OPTIONS(self): # add respo...
Python
0