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
182a4ceeeb8a9b9e3f5071427da1ca0ec847f368
Check in first cut at oban code. Taken directly from code used for class.
trunk/metpy/tools/oban.py
trunk/metpy/tools/oban.py
from itertools import izip import numpy as N from constants import * def rms(diffs): return N.sqrt(N.average(diffs**2)) def grid_point_dists(grid_x, grid_y, ob_x, ob_y): "Calculates distances for each grid point to every ob point" return N.hypot(grid_x[...,N.newaxis] - ob_x[N.newaxis,N.newaxis,...], grid_y[...
Python
0.000001
8a5f5fa11feefec2a81c3c1c2419b14e45a55bd0
Add dis01.py
trypython/stdlib/dis01.py
trypython/stdlib/dis01.py
# coding: utf-8 """ dis モジュールについてのサンプルです。 """ import dis from trypython.common.commoncls import SampleBase from trypython.common.commonfunc import hr # noinspection SpellCheckingInspection class Sample(SampleBase): def exec(self): ############################################## # dis モジュールは、python...
Python
0.000033
4835cac3b5ea15671f3da25cbc6e6db4bad725c9
Create crawl-twse.py
crawl/crawl-twse.py
crawl/crawl-twse.py
req=requests.get("http://www.twse.com.tw/ch/trading/fund/BFI82U/BFI82U.php?report1=day&input_date=105%2F05%2F31&mSubmit=%ACd%B8%DF&yr=2016&w_date=20160530&m_date=20160501") req.encoding='utf-8' html=req.text.encode('utf-8') soup=BeautifulSoup(html,"html.parser") for td in soup.findAll("td",{"class":"basic2"}): prin...
Python
0.000001
bd597a8f34d6f95bc445550bcc239ff67d0321f4
Add missing file.
tests/tests/utils.py
tests/tests/utils.py
from django.db import connection from django.utils import six def get_table_list(): with connection.cursor() as cursor: table_list = connection.introspection.get_table_list(cursor) if table_list and not isinstance(table_list[0], six.string_types): table_list = [table.name for table in table_li...
Python
0.000001
99d0c209024b1a2801892cadbe17456c9fbd3f57
Add tests for tools (work in progress)
tests/tests_tools.py
tests/tests_tools.py
""" SkCode tools test code. """ import unittest from skcode.tools import (escape_attrvalue, sanitize_url, slugify, unique_slugify) class ToolsTestCase(unittest.TestCase): """ Test suite for the tools module. """ def test_escape_a...
Python
0
66a23782438d9c16111c25c56090f4c92f54dde1
Add integration test for the trivial cycle simulation.
integration_tests/test_trivial_cycle.py
integration_tests/test_trivial_cycle.py
#! /usr/bin/python from nose.tools import assert_equal, assert_true from numpy.testing import assert_array_equal import os import tables import numpy as np from tools import check_cmd """ Tests """ def test_source_to_sink(): """ Tests simulations with a facilty that has a conversion factor. In future, may eli...
Python
0
1ba7850e57113e6b1ca1be5064cef5277a15598b
Add script: /Scripts/Others/test.py
Scripts/Others/test.py
Scripts/Others/test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # region Description """ test.py: Test new technique Author: Vladimir Ivanov License: MIT Copyright 2019, Raw-packet Project """ # endregion # region Import # region Add project root path from sys import path from os.path import dirname, abspath path.append(dirname(dirna...
Python
0.000008
be904e21db2012ac8f72a141afd9b93da2bfb262
Create http responses
monarch/base/http/responses.py
monarch/base/http/responses.py
# Copyright (C) 2015 David Barragán <bameda@dbarragan.com> # # 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. # # ...
Python
0
72fcb82d33c4a4317630b6f2c7985e69ff9d3ce3
add some simple tests for lru_cache
src/unittest/python/backport_tests.py
src/unittest/python/backport_tests.py
#!/usr/bin/env python from __future__ import print_function import sys import unittest from backports import functools_lru_cache class Test(unittest.TestCase): def test_with_bound_cache(self): @functools_lru_cache.lru_cache() def cachy(*args): return True self.assertTrue(cachy...
Python
0
75a2c6fb7074e316908d12cfd6f1e03d9e0a1ba6
add new tool to generate new pipeline easily (outside of sequana repository)
sequana/scripts/start_pipeline.py
sequana/scripts/start_pipeline.py
# -*- coding: utf-8 -*- # # This file is part of Sequana software # # Copyright (c) 2016 - Sequana Development Team # # File author(s): # Thomas Cokelaer <thomas.cokelaer@pasteur.fr> # Dimitri Desvillechabrol <dimitri.desvillechabrol@pasteur.fr>, # <d.desvillechabrol@gmail.com> # # Distributed u...
Python
0
48c139172e2eab43919ac9589ee58e3ff2009887
Work in progress
lexicon/providers/azure.py
lexicon/providers/azure.py
import json import requests from lexicon.providers.base import Provider as BaseProvider MANAGEMENT_URL = 'https://management.azure.com' API_VERSION = '2018-03-01-preview' NAMESERVER_DOMAINS = ['azure.com'] def provider_parser(subparser): subparser.add_argument('--auth-credentials') class Provider(BaseProvider...
Python
0.000003
4485e7dd4b6d5a6199d99cdc9a852ff551fc384b
bump version number
client/version.py
client/version.py
ELECTRUM_VERSION = "0.38" SEED_VERSION = 4 # bump this everytime the seed generation is modified
ELECTRUM_VERSION = "0.37" SEED_VERSION = 4 # bump this everytime the seed generation is modified
Python
0.000004
229d7e0385f3809267a2d930f93c7c8e17515a25
initialize final model - validation
code/final_val.py
code/final_val.py
# # Try different hyperparameters and network structure on validation set from sklearn.model_selection import TimeSeriesSplit, train_test_split from keras.utils.visualize_util import plot from keras.models import Sequential from keras.layers import GRU, Dense, Masking, Dropout, Activation, advanced_activations from ke...
Python
0.000001
93d444215e6ebea3088936b46f79bf335dcfd070
Create Pentester-Toolkit.py
Pentester-Toolkit.py
Pentester-Toolkit.py
#!/usr/bin/env python import requests,re,os,sys,time try: from termcolor import * except: print " -- install termcolor By using: 'sudo easy_install termcolor' -- " def banner(): os.system('clear') cprint(''' ____ __ __ ______ ____ __ _ __ / __ \___ ____ ...
Python
0
6486487dc1fc4972dcd18bc0e92bcae602f4d900
Create blacklist.py
cogs/blacklist.py
cogs/blacklist.py
Python
0.000006
b02e308dfc2993123486a5660b6d14c98f19b389
Create Hamel_ZipCode_API.py
Hamel_ZipCode_API.py
Hamel_ZipCode_API.py
def back_out_unicode(stringval): return str(stringval.encode('utf-8').decode('ascii', 'ignore')) def zip_info(zipcode): """ Takes a zip code and goes to www.uszip.com/zip/*zipcode and screen scrapes relevant information down. *zipcode is the 5-digit zipcode parameter input value zipcode must...
Python
0.000005
9ec957af0c3d57dff4c05c1b7ed3e66e1c033f6b
Add nagios check for idot snowplow ingest
nagios/check_idot_snowplows.py
nagios/check_idot_snowplows.py
""" Nagios check to see how much snowplow data we are currently ingesting """ import sys import os import psycopg2 POSTGIS = psycopg2.connect(database='postgis', host='iemdb', user='nobody') pcursor = POSTGIS.cursor() pcursor.execute(""" select count(*) from idot_snowplow_current WHERE valid > now() - '30 minutes...
Python
0
661e69ece73a609d230384874da9722de385d854
Change links to a dictionary, iterator instead of lambda
uoftscrapers/scrapers/libraries/__init__.py
uoftscrapers/scrapers/libraries/__init__.py
from ..utils import Scraper from bs4 import BeautifulSoup, NavigableString from datetime import datetime, date from collections import OrderedDict import urllib.parse as urlparse from urllib.parse import urlencode import re class Libraries: """A scraper for the Libraries at the University of Toronto.""" host =...
from ..utils import Scraper from bs4 import BeautifulSoup, NavigableString from datetime import datetime, date from collections import OrderedDict import urllib.parse as urlparse from urllib.parse import urlencode import re class Libraries: """A scraper for the Libraries at the University of Toronto.""" host =...
Python
0
717b20e298547685ed0685bd09a4fac541034910
Add an example map flow
example/map_flows.py
example/map_flows.py
from taskin import task def get_servers(data): return [ 'foo.example.com', 'bar.example.com', ] def create_something(data): servers, name = data for server in servers: print('Creating: https://%s/%s' % (server, name)) def main(): flow = [ get_servers, ta...
Python
0.000001
cd2df0032a3978444d6bd15e3b49a20bef495b75
add blastp
Modules/f10_blast.py
Modules/f10_blast.py
import subprocess,os def makeblastdb(fastaFile,datatype,outputname): """ this function build database given a fasta file * fastaFile: can be gzipped or not """ if fastaFile.endswith('.gz'): cmd = ('gunzip -c {input} | makeblastdb -in - -dbtype {type} -title {title} ' '-o...
Python
0.000433
7dac3075874a79d51d1b9d0c1551eec9a988f526
Create Roman_to_Integer.py
Array/Roman_to_Integer.py
Array/Roman_to_Integer.py
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999. class Solution: # @return an integer def romanToInt(self, s): numerals = { "M": 1000, "D": 500, "C": 100, "L": 50, ...
Python
0.000617
c810882385e034ca0e888ce093b227198dbb5f76
Create GPIOTutorialtempLogger.py
GPIOTutorialtempLogger.py
GPIOTutorialtempLogger.py
import RPi.GPIO as GPIO import time as time GPIO.setmode (GPIO.BCM) GPIO.setup (22, GPIO.IN ) GPIO.setup (17,GPIO.OUT ) while True: if GPIO.input(22): break print "start" datafile = open ("tempreading.log","w") while True: GPIO.output (17, GPIO.HIGH) tfile = open ("/sys/bus/w1/devices/28-0000056...
Python
0.000004
7b54ac1d1bf8cf6e9869e716940814d2d56cb1de
Create Watchers.py
examples/Watchers.py
examples/Watchers.py
los = [] url = 'https://stocktwits.com/symbol/' workbook = openpyxl.load_workbook('Spreadsheet.xlsx') worksheet = workbook.get_sheet_by_name(name = 'Sheet1') for col in worksheet['A']: los.append(col.value) los2 = [] print(los) for i in los: stocksite = url +i + '?q=' +i print(stocksite) with contextl...
Python
0.000001
66fa9698b40fa8365d91aef1ed16b620494052f0
Add CUDA + MPI example
examples/cuda_mpi.py
examples/cuda_mpi.py
# Demonstration of using MPI and Numba CUDA to perform parallel computation # using GPUs in multiple nodes. This example requires MPI4py to be installed. # # The root process creates an input data array that is scattered to all nodes. # Each node calls a CUDA jitted function on its portion of the input data. # Output d...
Python
0.000002
b44977653e57077118cb0eb0d549758f52beed35
Add basic example
examples/examples.py
examples/examples.py
from pyrho import * RhO = models['6']() Prot = protocols['step']() Prot.phis = [1e16, 1e15, 1e14] Sim = simulators['Python'](Prot, RhO) Sim.run() Sim.plot()
Python
0.000159
2d5366f455612373ca87ef4d2c8f890b1e6b255f
Add a compliance tool to export a subset of messages.
zerver/management/commands/export_search.py
zerver/management/commands/export_search.py
import os from argparse import ArgumentParser from datetime import datetime from email.headerregistry import Address from functools import lru_cache, reduce from operator import or_ from typing import Any from django.core.management.base import CommandError from django.db.models import Q from django.forms.models impor...
Python
0
61139332ce1bcfd145f16b8f3c411e178db4054c
Add some unit tests for the hashing protocol of dtype (fail currently).
numpy/core/tests/test_dtype.py
numpy/core/tests/test_dtype.py
import numpy as np from numpy.testing import * class TestBuiltin(TestCase): def test_run(self): """Only test hash runs at all.""" for t in [np.int, np.float, np.complex, np.int32, np.str, np.object, np.unicode]: dt = np.dtype(t) hash(dt) class TestRecord(Tes...
Python
0.000115
3d11000488ca20e7e34a9f7030a16e69a6b4052f
add examples for trainig 3
3-python-intermediate/examples/list_comprehension.py
3-python-intermediate/examples/list_comprehension.py
odd = [i for i in range(10) if i % 2] print(odd) # [1, 3, 5, 7, 9] odd_squares = [i ** 2 for i in odd] print(odd_squares) # [1, 9, 25, 49, 81] first_names = ['Bruce', 'James', 'Alfred'] last_names = ['Wayne', 'Gordon', 'Pennyworth'] heroes = ['{} {}'.format(f, l) for f, l in zip(first_names, last_names)] print(h...
Python
0
0886a4efd7b7703d72be4319d7b0295d3bc64151
Create Tensor_Case.py
Tensor_Case.py
Tensor_Case.py
import tensorflow as tf sess = tf.InteractiveSession() x = tf.random_uniform([]) y = tf.random_uniform([]) out1 = tf.cond(tf.greater(x,y), lambda:tf.add(x,y), lambda:(tf.subtract(x,y))) print(x.eval(), y.eval(), out1.eval()) x = tf.random_uniform([],-1,1) y = tf.random_uniform([],-1,1) def f1(): return tf.cast(tf.add...
Python
0.000039
dfa492ffc2148d8ffa5c14145e0092be60ef44eb
add an example for pipeline
examples/pipeline.py
examples/pipeline.py
import tornado import tornadis @tornado.gen.coroutine def pipeline_coroutine(): # Let's get a connected client client = tornadis.Client() yield client.connect() # Let's make a pipeline object to stack commands inside pipeline = tornadis.Pipeline() pipeline.stack_call("SET", "foo", "bar") ...
Python
0.000001
b75601e0c6bbb83dba4544f9d80b6f71c75fcdec
add missing ordered field to startup program interest
web/impact/impact/migrations/0003_add_ordered_field_to_startup_program_interest.py
web/impact/impact/migrations/0003_add_ordered_field_to_startup_program_interest.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2018-01-30 10:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('impact', '0002_set_models_to_managed'), ] operations = [ migrations.AlterFi...
Python
0
c3e7b563c3eeb24aa269f23672b8f469470908b7
Add an option to redirect user to a page if the key is already expired.
onetime/views.py
onetime/views.py
from datetime import datetime from django.http import HttpResponseRedirect, HttpResponseGone from django.shortcuts import get_object_or_404 from django.contrib.auth import login from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() def lo...
from datetime import datetime from django.http import HttpResponseRedirect, HttpResponseGone from django.shortcuts import get_object_or_404 from django.contrib.auth import login from django.conf import settings from onetime import utils from onetime.models import Key def cleanup(request): utils.cleanup() def lo...
Python
0
3922f75424308753dac5beadb75698971960843a
Write convenience functions in a separate file.
Kane1985/Chapter4/util.py
Kane1985/Chapter4/util.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """Convenient utility functions for exercises in Chapter 4 of Kane 1985. """ from __future__ import division from sympy import diff from sympy.physics.mechanics import ReferenceFrame, Point, Particle, RigidBody from sympy.physics.mechanics import cross, dot, Vector from sy...
Python
0
92077ecd268a6ca04f2b413fd3535d4cc358c97b
Create serializers.py
app/grandchallenge/algorithms/serializers.py
app/grandchallenge/algorithms/serializers.py
from rest_framework import serializers from grandchallenge.algorithms.models import Algorithm, Job, Result class AlgorithmSerializer(serializers.ModelSerializer): class Meta: model = Algorithm fields = ['pk'] class ResultSerializer(serializers.ModelSerializer): class Meta: model = Re...
Python
0.000002
b269ed70223591c81d13f97e48c74ced12cec661
Update 4-keys-keyboard.py
Python/4-keys-keyboard.py
Python/4-keys-keyboard.py
# Time: O(n) # Space: O(1) class Solution(object): def maxA(self, N): """ :type N: int :rtype: int """ if N < 7: return N dp = [i for i in xrange(N+1)] for i in xrange(7, N+1): dp[i % 6] = max(dp[(i-4) % 6]*3, dp[(i-5) % 6]*4) ...
# Time: O(n) # Space: O(1) class Solution(object): def maxA(self, N): """ :type N: int :rtype: int """ if N < 7: return N dp = [i for i in xrange(N+1)] for i in xrange(7, N+1): dp[i % 6] = max(dp[(i-4) % 6]*3,dp[(i-5) % 6]*4) ...
Python
0.000004
31f4479194239548bae6eff2650735ddf4279523
Add files via upload
DatabaseTest.py
DatabaseTest.py
import pygame import time import random import BattlePortDatabase pygame.init() display_width = 800 display_height = 600 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) block_color = (53, 115, 255) pid = 0 car_width = 73 gameDisplay = pygame.display.set_mode((display_width, display_he...
Python
0
1dd3e7436c19ba3146be6e34da39bd81dc1efd6e
Implement AES file encryption and decryption
file_crypto_tools.py
file_crypto_tools.py
############ Module with cryptographics functions for Storj GUI Client ########## ## Based on: <http://stackoverflow.com/questions/16761458/how-to-aes-encrypt-decrypt-files-using-python-pycrypto-in-an-openssl-compatible> ## from hashlib import md5 from Crypto.Cipher import AES from Crypto import Random class FileCry...
Python
0.005043
1633e8b286ddeec706d496931713e3ac7b93b780
Declare flaskext a namespace package
flaskext/__init__.py
flaskext/__init__.py
import pkg_resources pkg_resources.declare_namespace(__name__)
Python
0.000006
c69572c42da27357f8cb01299c309e47ff033e7f
Create docker-swarm-dns.py
docker-swarm-dns.py
docker-swarm-dns.py
#!/usr/bin/env python3.6 from time import sleep import docker, \ dns.resolver, \ dns.query, \ dns.tsigkeyring, \ dns.update, \ os, \ sys swnodes = ['192.168.15.201','192.168.15.202','192.168.15.203','192.168.15.204','192.168.15.205'] dnservers = {'master':{'ip':'192.168.2.6',...
Python
0.000006
52dbb4d1f34ef3d637e3d99813591bf12bfa4576
support for `python -m intelhex`. Let's provide some help on available "-m" executable points.
intelhex/__main__.py
intelhex/__main__.py
# Copyright (c) 2016, Alexander Belchenko # All rights reserved. # # Redistribution and use in source and binary forms, # with or without modification, are permitted provided # that the following conditions are met: # # * Redistributions of source code must retain # the above copyright notice, this list of co...
Python
0
e9e0a0eeaf985e5c8f74dc6cfb9110f7b3c152e4
test workers
myria/test/test_workers.py
myria/test/test_workers.py
from httmock import urlmatch, HTTMock from json import dumps as jstr import unittest from myria import MyriaConnection @urlmatch(netloc=r'localhost:8753') def local_mock(url, request): global query_counter if url.path == '/workers': return jstr({'1': 'localhost:9001', '2': 'localhost:9002'}) elif ...
Python
0.00001
2349d603ca887961441b5b3f436d6cffaaecb291
Add pyMetascanAPI class
pyMetascanAPI.py
pyMetascanAPI.py
import requests import os class pyMetascanAPI: API_ENDPOINT = 'https://api.metascan-online.com/v1/' API_KEY = '' FILE_EXT = 'file' DATA_EXT = 'file/' HASH_EXT = 'hash/' def __init__(self, api_key): self.API_KEY = api_key def fileUpload(self, file): r = self.makeRequest(se...
Python
0
feefc96050d3906730fe6d366430d7478204d168
Add solution to 121.
121/121.py
121/121.py
""" A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at random and its colour is noted. After each turn the disc is returned to the bag, an extra red disc is added, and another disc is taken at random. The player pays £1 to play and wins if they have taken more blue discs than r...
Python
0.000026
7abe3e8039162fcb1eb5a1c40c2b22a89122e103
Use LLDB in gypv8sh to debug random crashes.
tools/gypv8sh.py
tools/gypv8sh.py
#!/usr/bin/env python # Copyright (c) 2012 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. """This script is used by chrome_tests.gypi's js2webui action to maintain the argument lists and to generate inlinable tests. """ ...
#!/usr/bin/env python # Copyright (c) 2012 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. """This script is used by chrome_tests.gypi's js2webui action to maintain the argument lists and to generate inlinable tests. """ ...
Python
0.000004
5e220c5529ca7279979939716c28997876145b7b
Create ac_cover_pic_down.py
ac_cover_pic_down.py
ac_cover_pic_down.py
#coding=utf-8 import urllib import urllib2 import os cover='http://cover.acfunwiki.org/cover.php' face='http://cover.acfunwiki.org/face.php' now=1 local=os.getcwd()+'\\download\\' url_1=face#设置来源 exist=0 success=0 fail=0 all=0 def download(num,yes): global now global exist global success global fail ...
Python
0.00001
f6b720a2603cc597bdbe4124ad8e13b9a208274e
Create wordcloudtest.py
src/ml/wordcloudtest.py
src/ml/wordcloudtest.py
#encoding=utf8 from pyecharts import WordCloud from snownlp import SnowNLP import jieba ##词云 filename = "wdqbs.txt" with open(filename) as f: mytext = f.read() #print mytext s= SnowNLP(unicode(mytext,'utf8')) for word in s.keywords(10): print word.encode('utf8') seg_list = jieba.cut(mytext) punct = set(u''':!...
Python
0.000372
d062a109da7ba5cb6147fac90bb4c6466083c755
Create __init__.py
SlackBotFramework/utilities/__init__.py
SlackBotFramework/utilities/__init__.py
def send_card(client, channel, title, title_url, text, fields=None, bot_name="Bot", color="#36a64f", fallback="There was an error please try again"): attr = [{ "fallback": fallback, "color": color, "title": title, "title_link": title_url, "text": ...
Python
0.000429
e64dbcd16959078bc4df1b6a536ea3f36ae52411
add cli directory
ec2/cli/__init__.py
ec2/cli/__init__.py
# # Copyright (c) 2007 rPath, Inc. #
Python
0.000001
7bea9ba96c9d036692882fcbae5fcc1974567530
Add preprocessing.py
preprocessing/preprocessing.py
preprocessing/preprocessing.py
#! /usr/bin/env python # coding:utf-8 import re class Preprocess: def __init__(self): self.html_regex = re.compile( r'(http|https)://[a-zA-Z0-9-./"#$%&\':?=_]+') self.newline_regex = re.compile(r'\n') self.cont_spaces_regex = re.compile(r'\s+') def _subs(self, regex: "re...
Python
0.000359
c6ff3e3e67194499d1653d530a29e3856191fd1e
Create Grau.py
backend/Models/Grau/Grau.py
backend/Models/Grau/Grau.py
class Departamento(object): def __init__(self,departamento): self.id = departamento.getId() self.nome = departamento.getNome()
Python
0
8792e0f3f258c23713f1af7f4eab46eec796c9e3
Add primitive script for binary assets preparation
utils/convert.py
utils/convert.py
#!/usr/bin/env python import sys from PIL import Image, ImageFont, ImageDraw def write_in_c(data, name='data'): print('const uint8_t {0}[{1}] = {{\n\t'.format(name, len(data)), end="") for index, byte in enumerate(data): print('{0}'.format(byte), end="") if index != len(data)-1: print(', ', end="") if n...
Python
0
a136eeefdd6cf276a0d4815fa39453737ed04727
Add py solution for 556. Next Greater Element III
py/next-greater-element-iii.py
py/next-greater-element-iii.py
class Solution(object): def nextGreaterElement(self, n): """ :type n: int :rtype: int """ s = str(n) for i, n in enumerate(reversed(s[:-1]), 1): if n < s[-i]: x, j = min((x, k) for k, x in enumerate(s[-i:]) if x > n) ans = s...
Python
0.000001
1c2eebe236dcfcc607749ebcba7a769bb27b5176
test creation of blank CounterJournal item
pycounter/test/test_classes.py
pycounter/test/test_classes.py
import unittest from pycounter import report class TestJournalClass(unittest.TestCase): def test_counter_journal(self): journal = report.CounterJournal() self.assertEqual(journal.issn, "")
Python
0
feb47562d45294cb4e9c3ae2d0bc80b7b766bcc8
Create pKaKs3.py
Modules/pKaKs3.py
Modules/pKaKs3.py
#This short script uses the output values of KaKs.pl & SnpEff to calculate mutational load using Nei-Gojobori: pKa/Ks = [-3/4ln(1-4pn/3)] / [-3/4ln(1-4ps/3)], where ps = syn SNPs / syn sites and pn = nonsyn SNPs / nonsyn sites from math import log #If for some reason you need to calculate the logarithm of a negative n...
Python
0.000001
ed611e9f9c3470712b296188e5ee6e2432cb04b5
Add scanner
PyARPScanner.py
PyARPScanner.py
#!/usr/bin/env python import netifaces import commands import sys from scapy.all import * def scanner(): # default = "route | grep 'default' | awk '{print $8}'" gws = netifaces.gateways() default = gws['default'][netifaces.AF_INET] print 'Default Interface -- '+default[1]+' Gateway -- '+default[0] ...
Python
0.000001
843083b9469362ee3ef1c2e2259f1ce3e1e966d0
Add ELF "loader"/parser in Python
tools/pseudo_elf_loader.py
tools/pseudo_elf_loader.py
import sys if sys.version_info[0] != 3: exit("Py3 required.") import ast class MockRam(dict): def __missing__(self, addr): return None def b2i(l): return sum([a*0x100**i for i,a in enumerate(l)]) def i2b(i): b = [] while i: b.append(i%0x100) i //= 0x100 return b def...
Python
0.000028
0d90e90b496c4ba69220c5ca225e99eec85cc18f
add ParticleFilter function
ParticleFilter.py
ParticleFilter.py
import numpy as np import math import cv2 import operator ''' old_im = cv2.imread('old_image.jpg') old_im_compensate = cv2.imread('affine_frame.jpg') #old_gray = cv2.cvtColor(old_im, cv2.COLOR_BGR2GRAY) new_im = cv2.imread('new_image.jpg') #new_gray = cv2.cvtColor(new_im, cv2.COLOR_BGR2GRAY) diff = np.absolute(new_im ...
Python
0.000001
ba8eb16640a40f9c2f361251adecb8c91d1c9a07
create stream.py
PhloxAR/stream.py
PhloxAR/stream.py
# -*- coding: utf-8 -*- from __future__ import division, print_function from __future__ import absolute_import, unicode_literals # TODO: more detailed from PhloxAR.base import *
Python
0.000001
d8dc3b1696ce9e8b64bb2eea55e718553789cfc1
Add Time.Timeout.TimeoutAbsMono class, which is like Timeout.TimeoutAbs but is taking MonoTime instead of realtime as an argument.
Time/Timeout.py
Time/Timeout.py
# Copyright (c) 2003-2005 Maxim Sobolev. All rights reserved. # Copyright (c) 2006-2014 Sippy Software, Inc. All rights reserved. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistrib...
Python
0
e4b108fa5c0221eb2b585550b04be14ff56d26e5
Add Toy playlist creation
Toy_Playlist.py
Toy_Playlist.py
''' Written by Paul Lamere 06/05/2015 Accessed 10/23/2016 https://github.com/plamere/spotipy/blob/master/examples/create_playlist.py Modified by Stephen Longofono 10/23/2016 ''' import sys import os import subprocess import spotipy import spotipy.util as util if len(sys.argv) > 2: username = sys.argv[1] pl...
Python
0
32d46fe3e080b13ab9ae9dc3d868e9a724cccda9
Add unit test for IosBrowserFinder.
tools/telemetry/telemetry/core/backends/chrome/ios_browser_finder_unittest.py
tools/telemetry/telemetry/core/backends/chrome/ios_browser_finder_unittest.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest from telemetry.core import browser_options from telemetry.core.backends.chrome import ios_browser_finder from telemetry.unittest import test ...
Python
0.000013
f753711c502b54ad8bf2c992336a5ad002e069bb
Create bearing.py
server/traffic_calc/bearing.py
server/traffic_calc/bearing.py
#!/usr/bin/python ''' /*************************************************************************************** Name : bearng Description : calculates the bearing(angle) between given two lattitude and longitude points Parameters : l_lat1 and l_lng1 are point one lattitude and longitude r...
Python
0
99fd5661e976dfc3bf8968f171b41af83ff5f034
add plot for percentage
plot/microbench/percentage/cpr_email.py
plot/microbench/percentage/cpr_email.py
import sys import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plot import matplotlib.ticker as ticker import numpy as np import csv NUM_LINES = 4 LINE_NAMES = ["Single-Char", "Double-Char", "ALM", "3-Grams", "4-Grams", "ALM-Improved"] NUM_3_POINTS = 7 NUM_4_EXTRA_POINTS = 2 #COLORS = ['#fef0d9', '#fd...
Python
0.000017
0f00e710f3a2239024d6a2f0efd539d32b5c8aaf
Add taxonomy loader
components/taxonomy/scripts/load_taxonomy.py
components/taxonomy/scripts/load_taxonomy.py
""" Created on Wed Aug 22 19:55:11 PDT 2018 @author: rickpr Requirements: - toml, pymongo need to be installed - mongodb needs to be running Installation: pip3 install pymomgo pip3 install toml """ import sys from pymongo import MongoClient import toml #!/usr/bin/env python3 # ...
Python
0.000001
9ec883040abbdc91c1eef7884b514d45adbf809a
Add Slave file
assignment2/slave.py
assignment2/slave.py
''' ################################## server.py ############################# # Lab1 gRPC RocksDB Server ################################## server.py ############################# ''' import time import grpc import replicator_pb2 import replicator_pb2_grpc import uuid import rocksdb import encodings class Slave: ...
Python
0.000001
4eb8a1e2e3b9618806bf9a1108dbd2043fa88724
add twitter mod
appartbot/twitter.py
appartbot/twitter.py
import twython import logging class twytbot: def __init__(self, key, secret, acctok, sectok): self.KEY = key self.SECRET = secret self.ACCESS_TOKEN = acctok self.SECRET_TOKEN = sectok self.twitter = None def authentificate(self): self.twitter = twython.Twython(...
Python
0
6be45a83ccccff440f4a4590cc19fe1fa498f8d0
Add a basic integration test
integration_tests.py
integration_tests.py
"""Integration tests for ckanext-deadoralive and deadoralive. ckanext-deadoralive and deadoralive both have their own detailed tests, but these don't test whether the two work together: do they agree on the protocol, e.g. the URLs to send requests to and the params to send and receive back? This module just adds an e...
Python
0.000005
bc35e89d04e541f75fc12788893b21a3b876aaf9
Create test case for tail from file
tail/tests/test_tail.py
tail/tests/test_tail.py
""" Tests for the tail implementation """ from tail import FileTail def test_tail_from_file(): """Tests that tail works as advertised from a file""" from unittest.mock import mock_open, patch # The mock_data we are using for our test mock_data = """A B C D E F """ mocked_open = mock_open(read_da...
Python
0.000001
f956b2ce8e8e2ef87be0dc11aac48dce54e57088
Test Logger
pelicangit/log.py
pelicangit/log.py
import logging def setup_logging(): home_dir = os.path.expanduser("~") log_file = os.path.join(home_dir, 'pelicangit.log') logger = logging.getLogger('pelicangit') logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(levelname)s %(asctime)s :: %(message)s') logger.setFormat...
Python
0.000001
d08c619b8ea6063f8a414c69c8d38226719e292b
Correct super call in DatabaseIntrospection subclass
src/olympia/core/db/mysql/base.py
src/olympia/core/db/mysql/base.py
from django.db.backends.mysql.base import ( DatabaseWrapper as MySQLDBWrapper, DatabaseIntrospection as MySQLDBIntrospection, DatabaseSchemaEditor as MySQLDBSchemeEditor) class DatabaseIntrospection(MySQLDBIntrospection): def get_field_type(self, data_type, description): field_type = super(Dat...
from django.db.backends.mysql.base import ( DatabaseWrapper as MySQLDBWrapper, DatabaseIntrospection as MySQLDBIntrospection, DatabaseSchemaEditor as MySQLDBSchemeEditor) class DatabaseIntrospection(MySQLDBIntrospection): def get_field_type(self, data_type, description): field_type = super().g...
Python
0.000001
87a79b2c3e43a5408aa89880f5b0f65dcfb810d9
solve 11909
UVA/vol-119/11909.py
UVA/vol-119/11909.py
from sys import stdin, stdout from itertools import zip_longest import math for l,w,h,t in zip_longest(*[iter(map(int, stdin.read().split()))]*4): r = math.pi * t / 180 o = l * math.tan(r) if o <= h: s = l*h - l*o/2 else: r = math.pi/2 - r o = h * math.tan(r) s = h * o / 2 stdout.write('{:.3...
Python
0.999999
e6898282c82dfe890c02f702da6dd46c00adc0f3
Add tests for multishuffle
tests/test_utilities.py
tests/test_utilities.py
import math import tempfile import pathlib import numpy as np import h5py import scri import pytest def generate_bit_widths(bit_width): possible_widths = 2 ** np.arange(0, int(np.log2(bit_width))) bit_widths = [] while np.sum(bit_widths) < bit_width: next_width = np.random.choice(possible_widths) ...
Python
0
9f031861b75d7b99b0ab94d5272d378a8c3fba2e
Convert stickBreakingDemo.m to python (#613)
scripts/stick_breaking_demo.py
scripts/stick_breaking_demo.py
# Generates from stick-breaking construction import pyprobml_utils as pml import numpy as np import matplotlib.pyplot as plt alphas = [2, 5] nn = 20 # From MATLAB's random generator. match_matlab = True # Set True to match MATLAB's figure. beta1 = [0.4428, 0.0078, 0.1398, 0.5018, 0.0320, 0.3614, 0.8655, 0....
Python
0.999997
584e9597bf40a3c738071db1f2c7f1671bad1efa
Create 3sum_closet.py
Array/3sum_closet.py
Array/3sum_closet.py
#Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. #Return the sum of the three integers. You may assume that each input would have exactly one solution. class Solution: # @return an integer def threeSumClosest(self, num, target): num.sort...
Python
0.000083
7399645c7fb3d704f3e44b3113cf38efc32c85e8
add archive tool
tools/archive_models.py
tools/archive_models.py
import os import sys import json import glob paths = sys.argv[1:] models = {} for name in paths: with open(name, mode='r') as f: m = json.load(f) key, _ = os.path.splitext(os.path.basename(name)) models[key] = m print(json.dumps(models))
Python
0.000001
38414cd66365768d4bef9e28d56282d5b66886e5
Add resnet101 inference code for the oid-v2 trained image classification model.
tools/classify_oidv2.py
tools/classify_oidv2.py
#!/usr/bin/env python # # Copyright 2017 The Open Images 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 # # U...
Python
0
11fe39e743019ef7fdaadc0ae4f8782add0dc918
update aoj
aoj/11/aoj1142.py
aoj/11/aoj1142.py
m = int(input()) for i in range(m): d = input() trains = [d] for j in range(1, len(d)): f, b = d[:j], d[j:] rf, rb = f[::-1], b[::-1] trains.extend([rf+b, f+rb, rf+rb, b+f, rb+f, b+rf, rb+rf]) print(len(set(trains)))
Python
0.000002
2c2694d4c9ef3fdd51039b45951223708cbef3b9
Add nbsp template tag
base/templatetags/nbsp.py
base/templatetags/nbsp.py
# templatetags/nbsp.py from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter() def nbsp(value): return mark_safe("&nbsp;".join(str(value).split(' ')))
Python
0
5b80553b05b2c9df3818b815a2b156ad2f9f6437
add SQS plugin to match diamond
structured_metrics/plugins/sqs.py
structured_metrics/plugins/sqs.py
from . import Plugin class SqsPlugin(Plugin): targets = [ { 'match': '^servers\.(?P<server>[^\.]+)\.sqs\.(?P<region>[^\.]+)\.(?P<queue>[^\.]+)\.(?P<type>ApproximateNumberOfMessages.*)$', 'target_type': 'gauge', 'configure': [ lambda self, target: self.ad...
Python
0
f0c0027750aab6b116c553707edc7b1ebde5ce44
Create allsites_LST.py
allsites_LST.py
allsites_LST.py
# -*- coding: utf-8 -*- """ Created on Thu Jun 18 10:30:22 2015 Last updated on Tue Jul 30 02:12 2015 @author: O. B. Alam @email: oba3@cornell.edu """ import numpy as np import matplotlib.pyplot as plt import shlex ############################################################################### content = [] # li...
Python
0.000001
e2ad0b6bfa01e0aa263dd401a29ad60c24c755b0
Create bf4-server-status.py
bf4-server-status.py
bf4-server-status.py
#!/usr/bin/env python # debian deps: # python-django '''Get BF4 server data and output to HTML Usage: bf4_server_status.py [--debug] ''' import urllib import json import os import socket import sys import time from django.template import Template, Context from django.conf import settings from django.utils.datastruct...
Python
0.000002
6619bbff82f9a74a1de6c8cb569ea5cc639557d0
Refresh access token after user signs in #44
datalab/context/_context.py
datalab/context/_context.py
# Copyright 2014 Google 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 applicable law or agre...
# Copyright 2014 Google 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 applicable law or agre...
Python
0
0f80b1d304eb0d4443498c94557b0ef96d098c15
Add version
ernest/version.py
ernest/version.py
import os VERSION = '0.1a1' VERSION_RAW = os.environ.get('ERNEST_VERSION', VERSION)
Python
0
32cf7ab02ecb8f1dbd02b8a78001f8c15a97f794
Create population.py
analysis/population.py
analysis/population.py
import pandas as pd import matplotlib.pyplot as plt import urllib2 """ This program reads in a csv file containing census data on Northamptonshire county in the UK. It then plots the population data according to gender, gender by age range, and total population by age range. Two figure files will be output to the dir...
Python
0
139c7e2ac5b5c702cd32f4e014d8f3f654855c32
Add ping pong python script
nRF51/examples/ping_pong/scripts/ping_pong.py
nRF51/examples/ping_pong/scripts/ping_pong.py
from threading import Thread import subprocess import sys import os import time import datetime import serial import serial.tools.list_ports SEGGER_VID = 1366 BAUDRATE = 460800; verbose = False flow_control = True startTime = datetime.datetime.now() central = None snr_max = 0 def printUsage(): print "Usage: ping_...
Python
0.000004
97b9e370d31e2e7abb3d9d56c046f61e2723dc90
Create 1-helloworld.py
Code/1-helloworld.py
Code/1-helloworld.py
#Print Hello World! print "Hello World!"
Python
0.999994
0fbaaddf7cffd97ae162f24b8ae22fe88dbfa055
Add a node class for binomial random variables
bayespy/inference/vmp/nodes/binomial.py
bayespy/inference/vmp/nodes/binomial.py
###################################################################### # Copyright (C) 2014 Jaakko Luttinen # # This file is licensed under Version 3.0 of the GNU General Public # License. See LICENSE for a text of the license. ###################################################################### ####################...
Python
0
50f6792de9b8dce54492b897fcffae33d1cb75ba
create test url as an optional setting
authorize/conf.py
authorize/conf.py
from django.conf import settings from appconf import AppConf class authorizeConf(AppConf): TEST_URL = False class Meta: prefix = 'authorize'
Python
0
6edd782d39fd64fceca86c8edb224ae3f2378083
Create new package (#6477)
var/spack/repos/builtin/packages/r-seurat/package.py
var/spack/repos/builtin/packages/r-seurat/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
0a80cf698a26abdf17aeeb01e21cb9910e6463d0
add a test suite
booger_test.py
booger_test.py
#!/usr/bin/python ################################################################################ # "THE BEER-WARE LICENSE" (Revision 42): # <thenoviceoof> wrote this file. As long as you retain this notice # you can do whatever you want with this stuff. If we meet some day, # and you think this stuff is worth it, you...
Python
0.000001
771773cd3451dc04340e4a4856f7346841349772
Add cross bicoherence
bicoherencex.py
bicoherencex.py
#!/usr/bin/env python from __future__ import division import numpy as np from scipy.linalg import hankel import scipy.io as sio import matplotlib.pyplot as plt from tools import * def bicoherencex(w, x, y, nfft=None, wind=None, nsamp=None, overlap=None): """ Direct (FD) method for estimating cross-bicoherence ...
Python
0.998832
edf7c8c1d3ea1f85c6c9888dd5ee759443f1db1c
add billing urls
billing/urls.py
billing/urls.py
from django.conf.urls import url from . import views urlpatterns = [ url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf, name='generate-pdf') ]
Python
0.000001
e3a750dcca3727d576833351bfc09bbd858871f6
Fix indent on test code for test/assembly broken in r1220 Review URL: https://chromiumcodereview.appspot.com/9429007
test/assembly/gyptest-assembly.py
test/assembly/gyptest-assembly.py
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ A basic test of compiling assembler files. """ import sys import TestGyp if sys.platform != 'win32': # TODO(bradnelson): get this wo...
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ A basic test of compiling assembler files. """ import sys import TestGyp if sys.platform != 'win32': # TODO(bradnelson): get this wo...
Python
0.001074
e4e52abb5654804f847fb3894293de58f97c7c91
Add new control test for Front-End
Front-End/src/swig/Siconos/tests/test_smc.py
Front-End/src/swig/Siconos/tests/test_smc.py
#!/usr/bin/env python # this test is taken almost verbatim from RelayBiSimulation_OT2_noCplugin.py def test_smc_1(): from Siconos.Kernel import FirstOrderLinearDS, Model, TimeDiscretisation,\ TimeStepping, Moreau, ControlManager, linearSensor, linearSMC_OT2,\ getMatrix, SimpleMatrix from matplo...
Python
0.000001
1197f5885b2e7275d9a4f108c62bd2506816c8b1
Create test_madagascar.py
test/countries/test_madagascar.py
test/countries/test_madagascar.py
# -*- coding: utf-8 -*- # python-holidays # --------------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: dr-prodigy <maurizio....
Python
0.000005
d21743f2543f8d953a837d75bff0fcdb0105f4db
Add page extension for tracking page creation and modification dates.
feincms/module/page/extensions/changedate.py
feincms/module/page/extensions/changedate.py
""" Track the modification date for pages. """ from datetime import datetime from django.db import models from django.db.models import Q from django.utils.translation import ugettext_lazy as _ from django.conf import settings def register(cls, admin_cls): cls.add_to_class('creation_date', models.DateTimeField(_...
Python
0
1411daac4efd06b1208e19c3fce1a126230583cb
Use a proper mechanism for catching warnings
tinydb/utils.py
tinydb/utils.py
""" Utility functions. """ from contextlib import contextmanager import warnings class LRUCache(dict): """ A simple LRU cache. """ def __init__(self, *args, **kwargs): """ :param capacity: How many items to store before cleaning up old items or ``None`` for a...
""" Utility functions. """ from contextlib import contextmanager import warnings class LRUCache(dict): """ A simple LRU cache. """ def __init__(self, *args, **kwargs): """ :param capacity: How many items to store before cleaning up old items or ``None`` for a...
Python
0
bcb9437fb99c2577c9ca9628c60b80becc2a24b3
Add media_tags and a new filter for photo alignment normalization
organization/media/templatetags/media_tags.py
organization/media/templatetags/media_tags.py
# -*- coding: utf-8 -*- from mezzanine.template import Library register = Library() @register.filter def get_photo_alignment(value): if value == 'left': return 0 elif value == 'center': return 0.5 return 1
Python
0
ed0d0f913b209bf6ea8ec32d0aa10c31bc97e2c9
create index on vote.mandate_id
alembic/versions/33f79ee8632_vote_mandate_id_inde.py
alembic/versions/33f79ee8632_vote_mandate_id_inde.py
revision = '33f79ee8632' down_revision = '3abf407e34a' from alembic import op def upgrade(): op.create_index('vote_mandate_id_index', 'vote', ['mandate_id']) def downgrade(): op.drop_index('vote_mandate_id_index')
Python
0.000001
0676a5d8fb7ffeb9f1b84848fd849a181a8c1176
renamed to gadgets
analytics/gadgets.py
analytics/gadgets.py
from analytics import settings from analytics import models from analytics.sites import gadgets class BaseWidget(object): def __init__(self, title, metrics, value_type, frequency, samples, width, height): self.title = title self.metrics = metrics self.value_type = value_type self.fr...
Python
0.9994