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
ad54db707004dd2b6e445c72462c1e937417d046
test viz lib on fibonacci numbers
algopy/fib_gcd.py
algopy/fib_gcd.py
from rcviz import viz, callgraph @viz def fib1(num): assert num >= 0 if num <= 1: return num fb1 = fib1(num - 1) fb2 = fib1(num - 2) res = fb1 + fb2 return res @viz def fib2(num): assert num >= 0 return num if num <= 1 else fib2(num - 1) + fib2(num - 2) def gcd(a, b): ...
Python
0
8510352580ac6f39d706b6a4ace8426f9b45ca6c
Add unit tests for security_group_rules_client
tempest/tests/services/compute/test_security_group_rules_client.py
tempest/tests/services/compute/test_security_group_rules_client.py
# Copyright 2015 NEC Corporation. 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 ...
Python
0.000001
0d32be58f5145c067e012a9d314be3f688bcbc2a
Add tests for view
go/scheduler/tests/test_views.py
go/scheduler/tests/test_views.py
import datetime from go.vumitools.tests.helpers import djangotest_imports with djangotest_imports(globals()): from django.core.urlresolvers import reverse from django.template import defaultfilters from django.conf import settings from go.base.tests.helpers import GoDjangoTestCase, DjangoVumiApiHelper ...
Python
0
c39b95eebb402d1d0137448b3f0efd9b6d7ec169
Test if repository manager if retrieving a repository when we lookup after one
tests/managers/test_repository.py
tests/managers/test_repository.py
from unittest import TestCase from mock import MagicMock, patch from nose.tools import eq_ from pyolite.managers.repository import RepositoryManager class TestRepositoryManager(TestCase): def test_get_repository(self): mocked_repository = MagicMock() mocked_repository.get_by_name.return_value = 'my_repo' ...
Python
0
9ad755263fe12fa16c0b27381893c380626c85d8
Add unittest for string_view conversion
bindings/pyroot/test/conversions.py
bindings/pyroot/test/conversions.py
import unittest import ROOT cppcode = """ void stringViewConv(std::string_view) {}; """ class ListInitialization(unittest.TestCase): @classmethod def setUpClass(cls): ROOT.gInterpreter.Declare(cppcode) def test_string_view_conv(self): ROOT.stringViewConv("pyString") if __name__ == '__mai...
Python
0
8f02faec76c9b8cb7468934a4981fe1fe3ed30b5
add client
jsonrpc_http/Client.py
jsonrpc_http/Client.py
import tabular_predDB.python_utils.api_utils as au from tabular_predDB.jsonrpc_http.MiddlewareEngine import MiddlewareEngine middleware_engine = MiddlewareEngine() class Client(object): def __init__(self, hostname='localhost', port=8008): if hostname == None: self.online = False else: ...
Python
0.000001
6cfca819bbefab1f38904fc73b46dae80e03b32e
Create __init__.py
knockoutpy/__init__.py
knockoutpy/__init__.py
Python
0.000429
9eb5f67a954888c4e14789b5b8acc785c789a77c
Add a command for creating rsa key.
oidc_provider/management/commands/creatersakey.py
oidc_provider/management/commands/creatersakey.py
from Crypto.PublicKey import RSA from django.conf import settings from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): help = 'Randomly generate a new RSA key for the OpenID server' def handle(self, *args, **options): try: key = RSA.generate(1024)...
Python
0
aaddd474b8e17164c59f445d14b75b9f20a95948
add post install
setup_post_install.py
setup_post_install.py
import urllib2 import zipfile import re import sys from glob import glob from os import chdir, mkdir, rename, getcwd from os.path import exists from resample_all import resample_all def run_post_install(): # Double check modules modules = set(['numpy', 'scipy', 'librosa', 'sklearn']) for module in modules: try...
Python
0
11c4fe68be160caba706fab05767238396e8d25b
Add files via upload
SocketProgrammingAssignment/作业3-邮件客户端/TSL和发送混合类型email.py
SocketProgrammingAssignment/作业3-邮件客户端/TSL和发送混合类型email.py
from socket import * import base64 endmsg = ".\r\n" mail_t='1254516725@qq.com' #chose qq mail smtp server mailserver = 'smtp.qq.com' fromaddr='2634081011@qq.com' toaddr='galliumwang@163.com' user='MjYzNDA4MTAxMUBxcS5jb20=' passw='aXFvcm1ncGd2aHp2ZWNnaQ==' serverPort=25 serverPort_TLS=587 clientSocke...
Python
0
45140f281ac8df0a8f325e99d2cc17385eabbcf4
Create fizzbuzz.py
solutions/fizzbuzz.py
solutions/fizzbuzz.py
def fizzbuzz(number): for i in range(number): if i%15 == 0: print "FizzBuzz" elif i%5 == 0: print "Buzz" elif i%3 == 0: print "Fizz" else: print i def main(): fizzbuzz(101) if __name__ == '__main__': main()
Python
0.00001
0610f510e28f275c67f8c64eb6cd5020d4071531
Add spider for providence health & services
locations/spiders/providence_health_services.py
locations/spiders/providence_health_services.py
# -*- coding: utf-8 -*- import json import re import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours class ProvidenceHealthServicesSpider(scrapy.Spider): name = "providence_health_services" allowed_domains = ["providence.org"] def start_requests(self): ...
Python
0
feb7b6c627c05412176fd070abd8d5116d30f227
:sparkles:find smallest letter greater than target
python/problems/find_smallest_letter_greater_than_target.py
python/problems/find_smallest_letter_greater_than_target.py
""" https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/ https://leetcode.com/submissions/detail/131676021/ """ class Solution: def nextGreatestLetter(self, letters, target): """ :type letters: List[str] :type target: str :rtype: str """ ...
Python
0.999505
2ea891fd99eb50f58abb6cf1dba55950916742ab
Clear solution for roman-numerals.
roman-numerals.py
roman-numerals.py
# I 1 (unus) # V 5 (quinque) # X 10 (decem) # L 50 (quinquaginta) # C 100 (centum) # D 500 (quingenti) # M 1,000 (mille) place2symbol = { 0: "I", 1: "X", 2: "C", 3: "M", } replacements = [ ("I" * 9, "IX"), ("I" * 5, "V"), ("I" * 4, "IV"), ("X" * 9, "XC"), ("X" * 5, "L"), ("X" *...
Python
0
d0c4ff9461144e9608c30c8d5a43381282912cc0
Add builtin/github/writer.py
anchorhub/builtin/github/writer.py
anchorhub/builtin/github/writer.py
""" File that initializes a Writer object designed for GitHub style markdown files. """ from anchorhub.writer import Writer from anchorhub.builtin.github.wstrategies import MarkdownATXWriterStrategy, \ MarkdownSetextWriterStrategy, MarkdownInlineLinkWriterStrategy import anchorhub.builtin.github.switches as ghswit...
Python
0
ed19693800bbe50121fead603a3c645fdc1ed81a
Add migration
services/migrations/0059_add_unit_count_related_name.py
services/migrations/0059_add_unit_count_related_name.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2018-05-17 11:34 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('services', '0058_add_servicenodeunitcount'), ] op...
Python
0.000002
b1ac692447b2ca3a6b24183df436304db94f2c68
test for filter window polar
wradlib/tests/test_util.py
wradlib/tests/test_util.py
import numpy as np import wradlib.util as util import unittest #------------------------------------------------------------------------------- # testing the filter helper function #------------------------------------------------------------------------------- class TestUtil(unittest.TestCase): def img...
Python
0
c83cc4a60c719cf07d5ee3fe14556f8bb9542d22
check zmq version in ProxyDevice
zmq/devices/proxydevice.py
zmq/devices/proxydevice.py
"""Proxy classes and functions. Authors ------- * MinRK * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (c) 2013 Brian Granger, Min Ragan-Kelley # # This file is part of pyzmq # # Distributed under the terms of the New BSD License. The full license is...
"""Proxy classes and functions. Authors ------- * MinRK * Brian Granger """ #----------------------------------------------------------------------------- # Copyright (c) 2013 Brian Granger, Min Ragan-Kelley # # This file is part of pyzmq # # Distributed under the terms of the New BSD License. The full license is...
Python
0
d46374388596fee83be8aa850afc961579b71a22
add basic settings.py
uiautomator2/settings.py
uiautomator2/settings.py
# coding: utf-8 # from typing import Any import uiautomator2 as u2 class Settings(object): def __init__(self, d: u2.Device = None): self._d = d self._defaults = { "post_delay": 0, "implicitly_wait": 20.0, } self._props = { "post_delay": [float, ...
Python
0.000001
9327b5f0836652c4225af2c4e10cda592ce15a09
Distinct subsequence
DP/distinct_subsequences.py
DP/distinct_subsequences.py
import unittest """ Given two sequences A and B, find out number of distinct subsequences in A which are equal to B. Input: A: rabbbit, B: rabbit Output: 2 [One subsequence which includes first b and one excludes first b] """ """ Approach: 1. Following optimal substructure exists: If A[i] != B[j]: distinct(A,B,i,...
Python
0.99897
4dac5069084e90a0c4b0fd12e763e92df79f31c5
rename ds_justification_reason to justification_reason - add migration
backend/unpp_api/apps/project/migrations/0017_auto_20170915_0734.py
backend/unpp_api/apps/project/migrations/0017_auto_20170915_0734.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-09-15 07:34 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('project', '0016_remove_application_agency'), ] operations = [ migrations.RenameFiel...
Python
0
d7f024bc47c362afc6930510dea3bc425d5b554a
create example_fabfile
pg_fabrep/example_fabfile.py
pg_fabrep/example_fabfile.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from fabric.api import env, task from pg_fabrep.tasks import * @task def example_cluster(): # name of your cluster - no spaces, no special chars env.cluster_name = 'example_cluster' # always ask user for confirmation when run any tasks # default: True ...
Python
0.000002
c4243483052ec7eec2f1f88ea72fafc953d35648
Add ptxgen sample
samples/ptxgen.py
samples/ptxgen.py
# Copyright (c) 2013 NVIDIA Corporation # # 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 without limitation the rights # to use, copy, modify, merge, publish, ...
Python
0
ebc417be95bcec7b7a25dc1ad587f17b1bfa521d
Add download_student_forms
scripts/download_student_forms.py
scripts/download_student_forms.py
#!/usr/bin/env python2.5 # # Copyright 2011 the Melange authors. # # 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 applic...
Python
0
3b67d7919affb47e79a8b7cd5dab5f226e96eb86
Update IDTools (#1547)
src/dashboard/src/fpr/migrations/0033_update_idtools.py
src/dashboard/src/fpr/migrations/0033_update_idtools.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def data_migration_up(apps, schema_editor): """Update identification tools FIDO and Siegfried to current versions, allowing for integration of PRONOM 96. """ idtool = apps.get_model("fpr", "IDTool") ...
Python
0
95bfebab310628f1074f943790f04cda876e8ab2
Fork off a custom workspace_status.py with more heuristics
tools/workspace_status_release.py
tools/workspace_status_release.py
#!/usr/bin/env python # This is a variant of the `workspace_status.py` script that in addition to # plain `git describe` implements a few heuristics to arrive at more to the # point stamps for directories. But due to the implemented heuristics, it will # typically take longer to run (especially if you use lots of plug...
Python
0.999969
013d793c6ebe7a4d426d6c2d823510f90b84d19e
Add a landmine to get rid of obselete test netscape plugins
build/get_landmines.py
build/get_landmines.py
#!/usr/bin/env python # Copyright 2013 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 file emits the list of reasons why a particular build needs to be clobbered (or a list of 'landmines'). """ import optparse i...
#!/usr/bin/env python # Copyright 2013 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 file emits the list of reasons why a particular build needs to be clobbered (or a list of 'landmines'). """ import optparse i...
Python
0.000001
5401eb7b463dfd9a807b86b7bdfa4079fc0cb2ac
Define basic regular expressions
autoload/vimwiki_pytasks.py
autoload/vimwiki_pytasks.py
import vim import re from tasklib.task import TaskWarrior, Task # Building blocks BRACKET_OPENING = re.escape('* [') BRACKET_CLOSING = re.escape('] ') EMPTY_SPACE = r'(?P<space>\s*)' TEXT = r'(?P<text>.+)' UUID = r'(?P<uuid>[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})' DUE = r'(?P<due>...
import vim import re from tasklib import task """ How this plugin works: 1.) On startup, it reads all the tasks and syncs info TW -> Vimwiki file. Task is identified by their uuid. 2.) When saving, the opposite sync is performed (Vimwiki -> TW direction). a) if task is marked as subtask by ind...
Python
0.000304
b9fbc458ed70e6bffdfc5af9d9f0ad554b6c0cec
Decrease memory usage of LSTM text gen example
examples/lstm_text_generation.py
examples/lstm_text_generation.py
from __future__ import print_function from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.datasets.data_utils import get_file import numpy as np import random, sys ''' Example script to generate text from Nietzsche's writin...
from __future__ import print_function from keras.models import Sequential from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.datasets.data_utils import get_file import numpy as np import random, sys ''' Example script to generate text from Nietzsche's writin...
Python
0
08402e98f9eb56ab3b103e5bf36004638461f903
Add koi7-to-utf8 script.
languages/python/koi7-to-utf8.py
languages/python/koi7-to-utf8.py
#!/usr/bin/python # -*- encoding: utf-8 -*- # # Перекодировка из семибитного кода КОИ-7 Н2 # (коды дисплея Videoton-340) в кодировку UTF-8. # Copyright (C) 2016 Serge Vakulenko <vak@cronyx.ru> # import sys if len(sys.argv) != 2: print "Usage: koi7-to-utf8 file" sys.exit (1) translate = { '`':'Ю', 'a':'А',...
Python
0
815845fd98627fe9df0b0444ee31fe337d1c63da
Add celery worker module
utils/celery_worker.py
utils/celery_worker.py
import os import sys # Append .. to sys path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import multiscanner from celery import Celery from celery.contrib.batches import Batches app = Celery('celery_worker', broker='pyamqp://guest@localhost//') @app.task(base=Batches, flush_every=100...
Python
0.000001
60e37ece40e96ecd9bba16b72cdb64e1eb6f8f77
Fix purge_cluster script
utils/purge_cluster.py
utils/purge_cluster.py
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- """...
# encoding: utf-8 # --------------------------------------------------------------------------- # Copyright (C) 2008-2014, IPython Development Team and Enthought, Inc. # Distributed under the terms of the BSD License. See COPYING.rst. # --------------------------------------------------------------------------- """...
Python
0.000001
43629166927a0e6e7f4648a165ce12e22b32508d
Add missing migration for DiscoveryItem (#15913)
src/olympia/discovery/migrations/0010_auto_20201104_1424.py
src/olympia/discovery/migrations/0010_auto_20201104_1424.py
# Generated by Django 2.2.16 on 2020-11-04 14:24 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('discovery', '0009_auto_20201027_1903'), ] operations = [ migrations.RemoveField( model_name='discoveryitem', name='custom_a...
Python
0
c5f91aa604ccca0966be3076c46385d6019b65f2
Add utils refresh_db
APITaxi/utils/refresh_db.py
APITaxi/utils/refresh_db.py
# -*- coding: utf-8 -*- #Source: http://dogpilecache.readthedocs.org/en/latest/usage.html from sqlalchemy import event from sqlalchemy.orm import Session def cache_refresh(session, refresher, *args, **kwargs): """ Refresh the functions cache data in a new thread. Starts refreshing only after the session w...
Python
0.000001
4fbba7e581b9ba4f98a3be4d09fbf929b32a6a87
add test_load.py
openprocurement/search/test_load.py
openprocurement/search/test_load.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import logging import simplejson as json import urllib, urllib2 from random import choice from multiprocessing import Process from time import time FORMAT='%(asctime)-15s %(levelname)s %(processName)s %(message)s' g_args=None g_dict={} def worker(): l...
Python
0.000009
c3364acdd1b2a14faa25895c8fa3d08218e5d31d
Update migration to sync with push'd ocd-django
upload/migrations/0001_initial.py
upload/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('opencivicdata', '0002_aut...
Python
0
90e613063495dee9af8fefc7e682b15344eabc0d
Add an initial find missing translations script
util/find_missing_translations.py
util/find_missing_translations.py
import argparse import os import re # Directory names to ignore when looking for JavaScript files. ignore_dirs = [ ".git", "publish", "ThirdParty", ] # All valid two letter locale names. all_locales = set(["en", "cn", "de", "fr", "ja", "ko"]) # Locales that are in zoneRegex object blocks. zoneregex_local...
Python
0.998735
4cba006f440ebf219eb2cb64dd322e0168bdc3bb
Was cat_StartdLogs.py
factory/tools/find_StartdLogs.py
factory/tools/find_StartdLogs.py
#!/bin/env python # # cat_StartdLogs.py # # Print out the StartdLogs for a certain date # # Usage: cat_StartdLogs.py <factory> YY/MM/DD [hh:mm:ss] # import sys,os,os.path,time sys.path.append("lib") sys.path.append("..") sys.path.append("../../lib") import gWftArgsHelper,gWftLogParser import glideFactoryConfig USAGE=...
Python
0.998194
fd97b0e0edffa331d11ba7961637eb03ea5b8881
Save an RPC call on each request, make sure we have a django_user before trying to update it
djangae/contrib/gauth/middleware.py
djangae/contrib/gauth/middleware.py
from django.contrib.auth import authenticate, login, logout, get_user, BACKEND_SESSION_KEY, load_backend from django.contrib.auth.middleware import AuthenticationMiddleware as DjangoMiddleware from django.contrib.auth.models import BaseUserManager, AnonymousUser from djangae.contrib.gauth.backends import AppEngineUser...
from django.contrib.auth import authenticate, login, logout, get_user, BACKEND_SESSION_KEY, load_backend from django.contrib.auth.middleware import AuthenticationMiddleware as DjangoMiddleware from django.contrib.auth.models import BaseUserManager, AnonymousUser from djangae.contrib.gauth.backends import AppEngineUser...
Python
0
38bfc1a536f43ece367a49a62501b57c89f689a1
Add script to delete tables.
django-server/feel/core/db/reset.py
django-server/feel/core/db/reset.py
from django.db.models.base import ModelBase from quiz.models import Quiz, ShortAnswer, Choice, QuizAttempt from codequiz.models import CodeQuiz, CodeQuizAttempt from concept.models import Concept, ConceptSection from course.models import Course, CourseSlug, CourseConcept, ConceptDependency def reset(): for key,...
Python
0
4b3c3fb315c0f7450dd87a98e3d7f928408a8ab4
add documentation for do_layout() method
kivy/uix/layout.py
kivy/uix/layout.py
''' Layout ====== Layouts are used to calculate and assign widget positions. The :class:`Layout` class itself cannot be used directly. You must use one of: - Anchor layout : :class:`kivy.uix.anchorlayout.AnchorLayout` - Box layout : :class:`kivy.uix.boxlayout.BoxLayout` - Float layout : :class:`kivy.uix.floatlayout....
''' Layout ====== Layouts are used to calculate and assign widget positions. The :class:`Layout` class itself cannot be used directly. You must use one of: - Anchor layout : :class:`kivy.uix.anchorlayout.AnchorLayout` - Box layout : :class:`kivy.uix.boxlayout.BoxLayout` - Float layout : :class:`kivy.uix.floatlayout....
Python
0.000001
586c047cebd679f6a736c2dfec9b6df762938b12
Add command line tool.
simulate_packs.py
simulate_packs.py
#!/usr/local/bin/python3 import argparse import Panini from Panini import StickerCollection from Accumulator import Accumulator parser = argparse.ArgumentParser('Simulate creating a Panini sticker collection') parser.add_argument('runs', metavar='N', type= int) runs = parser.parse_args().runs results = Accumulator....
Python
0.000001
7cb5e7b7ea65841e3eea11e337fe64e578cec2ce
Create buzzer.py
buzzer.py
buzzer.py
#!/usr/bin/env python import RPi.GPIO as GPIO import os import smbus from time import sleep b = smbus.SMBus(1) address = 0x20 GPIOA = 0x12 GPIOB = 0x13 b.write_byte_data(address,0x0C,0xFF) b.write_byte_data(address,0x0D,0xFF) if os.path.exists('ranking.txt'): os.remove('ranking.txt') if os.path.exists('stop-script')...
Python
0.000011
bad6bc988f09bf1f135d81eb654c5fc6c1de9a28
add standalone gene report script. It will be used in the NDEx server as the GSEA exporter.
cx2grp.py
cx2grp.py
#!/usr/bin/python ''' This script takes a CX network from stdin and print out a set of gene symbols found in node names, represents, alias and function terms. Gene Symbols are normallized to human genes using mygene.info services. ''' import sys,json import requests def terms_from_function_term(function_term, term_...
Python
0
9008d6e3d14a5a582f0ddbd6b4a113386b639f26
Add Pyramid parser module
webargs/pyramidparser.py
webargs/pyramidparser.py
# -*- coding: utf-8 -*- """Pyramid request argument parsing. Example usage: :: from wsgiref.simple_server import make_server from pyramid.config import Configurator from pyramid.response import Response from webargs import Arg from webargs.pyramidparser import use_args hello_args = { ...
Python
0.000002
5149d86c7e787eff46f21669d448158ba0905a41
Add dbck.py: a database check tool
dbck.py
dbck.py
#!/usr/bin/python # # dbck.py # # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import sys import Log import MemPool import ChainDb import cStringIO from bitcoin.coredefs import NETWORKS from bitcoin.core import CBlock fro...
Python
0.000004
48bc3bfa4ab6648d3599af15cfe7a2dd69abdb40
make gsid ctable schedule run hourly
custom/apps/gsid/ctable_mappings.py
custom/apps/gsid/ctable_mappings.py
from ctable.fixtures import CtableMappingFixture from ctable.models import ColumnDef, KeyMatcher class PatientSummaryMapping(CtableMappingFixture): name = 'patient_summary' domains = ['gsid'] couch_view = 'gsid/patient_summary' schedule_active = True @property def columns(self): colum...
from ctable.fixtures import CtableMappingFixture from ctable.models import ColumnDef, KeyMatcher class PatientSummaryMapping(CtableMappingFixture): name = 'patient_summary' domains = ['gsid'] couch_view = 'gsid/patient_summary' schedule_active = True @property def columns(self): colum...
Python
0.000001
94ebfd057eb5a7c7190d981b26c027573578606d
validate using validator module
modularodm/fields/StringField.py
modularodm/fields/StringField.py
from ..fields import Field from ..validators import StringValidator class StringField(Field): default = '' validate = StringValidator() def __init__(self, *args, **kwargs): super(StringField, self).__init__(*args, **kwargs)
from ..fields import Field import weakref class StringField(Field): default = '' def __init__(self, *args, **kwargs): super(StringField, self).__init__(*args, **kwargs) def validate(self, value): if isinstance(value, unicode): return True else: try: ...
Python
0.000001
5748666a1f2c6cd307be79c33117252e10d6df01
Add matchup script
mzalendo/kenya/management/commands/kenya_matchup_coords_to_place.py
mzalendo/kenya/management/commands/kenya_matchup_coords_to_place.py
import re import csv import sys from optparse import make_option from django.core.management.base import LabelCommand from django.contrib.gis.geos import Point from mapit.models import Area, Generation, Type, NameType, Country class Command(LabelCommand): """Read a file in, extract coordinates and lookup the c...
Python
0.000001
9386236d41298ed8888a6774f40a15d44b7e53fe
Create command for Data Log Report fixtures
data_log/management/commands/generate_report_fixture.py
data_log/management/commands/generate_report_fixture.py
from django.core.management.base import BaseCommand from django.core import serializers from data_log import models import json class Command(BaseCommand): help = 'Create Data Log Report fixtures' def handle(self, *args, **kwargs): self.stdout.write('Creating fixtures for Data Log Reports...') ...
Python
0
ebf790c6c94131b79cb5da4de6cb665f97e54799
Add viewset permission class for checking image permissions
app/grandchallenge/cases/permissions.py
app/grandchallenge/cases/permissions.py
from rest_framework import permissions from grandchallenge.serving.permissions import user_can_download_image class ImagePermission(permissions.BasePermission): """ Permission class for APIViews in retina app. Checks if user is in retina graders or admins group """ def has_object_permission(self...
Python
0
496754c54005cf7e1b49ada8e612207f5e2846ff
Add dead letter SQS queue example
python/example_code/sqs/dead_letter_queue.py
python/example_code/sqs/dead_letter_queue.py
# Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file ac...
Python
0.000002
95e1516eab93d50c53246fd90a97d95d581037c6
add module for plex control
client/modules/plex.py
client/modules/plex.py
""" Plex module Name: plex.py Description: responds to the word "plex" controls plex client (play,pause,stop) Dependencies: Plex DB (located at /var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Plug-in Support/Databases/com.plexapp.plugins.library....
Python
0
085a9aa05dfda6348d0e7e2aa6ac7f0c6ce6d63b
add some basic client-server tests
client_server_tests.py
client_server_tests.py
import pyopentxs # this is defined by the sample data SERVER_ID = "r1fUoHwJOWCuK3WBAAySjmKYqsG6G2TYIxdqY6YNuuG" def test_check_server_id(): nym_id = pyopentxs.create_pseudonym() assert pyopentxs.check_server_id(SERVER_ID, nym_id) def test_register_nym(): nym_id = pyopentxs.create_pseudonym() pyopent...
Python
0.000001
55f11f5952ad7c53267ec31c60196dd329eb09c0
add one-off service
htdocs/json/vtec_events_bywfo.py
htdocs/json/vtec_events_bywfo.py
"""Pidgin-holed service for some WFO data... """ import json from io import BytesIO, StringIO import datetime from paste.request import parse_formvars from pyiem.util import get_sqlalchemy_conn, html_escape import pandas as pd from sqlalchemy import text EXL = "application/vnd.openxmlformats-officedocument.spreadshee...
Python
0.000001
7fc64847ed45229220e9bdfe20c25f3c83f10a80
Add isup.py
isup.py
isup.py
#!/usr/bin/env python import re import sys from urllib.request import urlopen def isup(domain): request = urlopen("http://www.isup.me/" + domain).read() if type(request) != type(''): request = request.decode('utf-8') return domain + " " + ("UP" if "It's just you" in request else "DOWN") def main(c...
Python
0.000001
9c7935ebbd4d995c44526c91fdb3b647a15eb877
Create API tasks.py with update_char_data
evewspace/API/tasks.py
evewspace/API/tasks.py
# Eve W-Space # Copyright 2014 Andrew Austin and contributors # # 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 requi...
Python
0.000003
1d1a37ad6f0aedbf18a72b551fdee4d96c92ea11
Update RICA example.
examples/mnist-rica.py
examples/mnist-rica.py
#!/usr/bin/env python import climate import matplotlib.pyplot as plt import numpy as np import theanets from utils import load_mnist, plot_layers, plot_images logging = climate.get_logger('mnist-rica') climate.enable_default_logging() class RICA(theanets.Autoencoder): def J(self, weight_inverse=0, **kwargs): ...
#!/usr/bin/env python import climate import matplotlib.pyplot as plt import numpy as np import theanets from utils import load_mnist, plot_layers, plot_images logging = climate.get_logger('mnist-rica') climate.enable_default_logging() class RICA(theanets.Autoencoder): def J(self, weight_inverse=0, **kwargs): ...
Python
0
57cf0e1d153c2d06e722329ac35f2093a1d1c17c
use .py file to make for setup.py
Docs/city_fynder.py
Docs/city_fynder.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 # import data (natural, human, economy, tertiary) = dp.read_data() # Add ranks in the DataFrame (natura...
Python
0.000001
64b321f1815c17562e4e8c3123b5b7fbbe23ce0b
Add logging test
pubres/tests/logging_test.py
pubres/tests/logging_test.py
import logging import logging.handlers import multiprocessing import pubres from pubres.pubres_logging import setup_logging from .base import * class MultiprocessingQueueStreamHandler(logging.handlers.BufferingHandler): """A logging handler that pushes the getMessage() of every LogRecord into a multiprocess...
Python
0.000001
b52bad82bafed23d3db5a0e73c22a056d1753174
add card parsers
pypeerassets/card_parsers.py
pypeerassets/card_parsers.py
'''parse cards according to deck issue mode''' def none_parser(cards): '''parser for NONE [0] issue mode''' return None def custom_parser(cards, parser=None): '''parser for CUSTOM [1] issue mode, please provide your custom parser as argument''' if not parser: return cards else: ...
Python
0
a5b28834bb5e52857720139a1fbe6dfd1d1ea266
create a new string helper that concatenates arguments
radosgw_agent/util/string.py
radosgw_agent/util/string.py
def concatenate(*a, **kw): """ helper function to concatenate all arguments with added (optional) newlines """ newline = kw.get('newline', False) string = '' for item in a: if newline: string += item + '\n' else: string += item return string
Python
0.000023
68c66c397f11637f650131ef69f4f16ebe6f43e4
Create luhn.py
luhn.py
luhn.py
# Luhn algorithm check # From https://en.wikipedia.org/wiki/Luhn_algorithm def luhn_checksum(card_number): def digits_of(n): return [int(d) for d in str(n)] digits = digits_of(card_number) odd_digits = digits[-1::-2] even_digits = digits[-2::-2] checksum = 0 checksum += sum(odd_digits) ...
Python
0.000001
7655170c50b3e7d3af0a34c82478696b6b8f3d39
Disable Session Keepalives in the Request Library
rightscale/httpclient.py
rightscale/httpclient.py
from functools import partial import requests DEFAULT_ROOT_RES_PATH = '/' class HTTPResponse(object): """ Wrapper around :class:`requests.Response`. Parses ``Content-Type`` header and makes it available as a list of fields in the :attr:`content_type` member. """ def __init__(self, raw_resp...
from functools import partial import requests DEFAULT_ROOT_RES_PATH = '/' class HTTPResponse(object): """ Wrapper around :class:`requests.Response`. Parses ``Content-Type`` header and makes it available as a list of fields in the :attr:`content_type` member. """ def __init__(self, raw_respo...
Python
0.000001
9e6c2d1601170657fb0516e5c2addde65761b8fe
support grayscale + 8-bit alpha channel
rinoh/backend/pdf/png.py
rinoh/backend/pdf/png.py
# This file is part of RinohType, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from io import BytesIO import png from .cos import Name...
# This file is part of RinohType, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. import png from .cos import Name, XObjectImage, Array, I...
Python
0.000005
1718926c99692fefb90627c55589990cd0e0225b
Make migrations in project_template home app reversible
wagtail/project_template/home/migrations/0002_create_homepage.py
wagtail/project_template/home/migrations/0002_create_homepage.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') Home...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations def create_homepage(apps, schema_editor): # Get models ContentType = apps.get_model('contenttypes.ContentType') Page = apps.get_model('wagtailcore.Page') Site = apps.get_model('wagtailcore.Site') Home...
Python
0.000005
889b322261384c90ac165ddd1e8bf2944b3e7785
Add machine types people use as host for TF builds.
third_party/remote_config/remote_platform_configure.bzl
third_party/remote_config/remote_platform_configure.bzl
"""Repository rule to create a platform for a docker image to be used with RBE.""" def _remote_platform_configure_impl(repository_ctx): platform = repository_ctx.attr.platform if platform == "local": os = repository_ctx.os.name.lower() if os.startswith("windows"): platform = "window...
"""Repository rule to create a platform for a docker image to be used with RBE.""" def _remote_platform_configure_impl(repository_ctx): platform = repository_ctx.attr.platform if platform == "local": os = repository_ctx.os.name.lower() if os.startswith("windows"): platform = "window...
Python
0.000004
c06ed61909cc9320b42c60fb435e4381f60e8b2e
Create Input-OutputNeuronGroup.py
examples/Input-OutputNeuronGroup.py
examples/Input-OutputNeuronGroup.py
''' Example of a spike bridge (receives and sends spikes) In this example spikes are received, processed and sent by UDP creating a raster plot at the end of the simulation. ''' from brian import * import numpy from brian_multiprocess_udp import BrianConnectUDP # The main function with the NeuronGroup(s) and Synap...
Python
0
2dea3ee1e50d5365ca190ee894536faea3148c7d
Add ChromiumTestShell activity and socket to constants.
build/android/pylib/constants.py
build/android/pylib/constants.py
# 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. """Defines a set of constants shared by test runners and other scripts.""" import os CHROME_PACKAGE = 'com.google.android.apps.chrome' CHROME_ACTIVITY...
# 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. """Defines a set of constants shared by test runners and other scripts.""" import os CHROME_PACKAGE = 'com.google.android.apps.chrome' CHROME_ACTIVITY...
Python
0.000002
8bd51ccea4c59d998691a71a14e868f622faeb7d
Add a basic python script to generate checks.
clang-tidy/add_new_check.py
clang-tidy/add_new_check.py
#!/usr/bin/env python # #===- add_new_check.py - clang-tidy check generator ----------*- python -*--===# # # The LLVM Compiler Infrastructure # # This file is distributed under the University of Illinois Open Source # License. See LICENSE.TXT for details. # #===--------------------------------------...
Python
0.000001
4ab784d9526b2a4555e288038df0490269b17683
完成1题
已完成/ToLeetSpeak.py
已完成/ToLeetSpeak.py
#!/usr/bin/python # -*- coding: UTF-8 -*- ''' # ToLeetSpeak题目地址:https://www.codewars.com/kata/57c1ab3949324c321600013f/train/python ''' import unittest class TestCases(unittest.TestCase): def setUp(self): pass def test1(self):self.assertEqual(to_leet_speak("LEET"), "1337") def test2(self):self.as...
Python
0.000004
988b56b4348ec8be3127cfd6576779de4367d488
Add pywikibot user-config file
.pywikibot/user-config.py
.pywikibot/user-config.py
family = 'wikipedia' mylang = 'en' usernames['wikipedia']['en'] = u'ExampleBot' console_encoding = 'utf-8' textfile_encoding = 'unicode_escape'
Python
0
d808d55b5ca9ae2e45418aca718ee21a9beb84f9
Create a custom reverse() function (not implemented yet)
djangorestframework/urlresolvers.py
djangorestframework/urlresolvers.py
from django.core.urlresolvers import reverse def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): raise NotImplementedError
Python
0
631faacaf077c2b4d0d446e42076fd4e4f27ed37
Add tests for template tags
djlotrek/tests/test_templatetags.py
djlotrek/tests/test_templatetags.py
import os import mock from django.test import TestCase from djlotrek.templatetags.djlotrek_tags import absolute_url from django.test import RequestFactory class TemplateTagsTestCase(TestCase): def setUp(self): pass def test_absolute_url(self): """Our beloved get_host_url utility""" ...
Python
0
e812029c03cb6a7a6e474546fb686342e6d2c064
Add test for `wsgiref.simple_server`
python/ql/test/library-tests/frameworks/stdlib/wsgiref_simple_server_test.py
python/ql/test/library-tests/frameworks/stdlib/wsgiref_simple_server_test.py
# This test file demonstrates how to use an application with a wsgiref.simple_server # see https://docs.python.org/3/library/wsgiref.html#wsgiref.simple_server.WSGIServer import sys import wsgiref.simple_server def ignore(*arg, **kwargs): pass ensure_tainted = ensure_not_tainted = ignore ADDRESS = ("localhost", 8000)...
Python
0
f2028ab194fe7c1c1497ee9320ddddbbece6406a
Add eventlet backdoor to facilitate troubleshooting.
nova/common/eventlet_backdoor.py
nova/common/eventlet_backdoor.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 Openstack, LLC. # Administrator of the National Aeronautics and Space Administration. # 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 ...
Python
0.000002
d81ba7d656f11e817eb610b1c65a4880fddc9004
Fix getting money from arcade games.
saylua/modules/arcade/api.py
saylua/modules/arcade/api.py
from saylua import db from saylua.wrappers import api_login_required from flask import g, request from models.db import Game, GameLog from saylua.utils import int_or_none import json # Send a score to the API. @api_login_required() def api_send_score(game_id): try: gameName = Game(game_id) except I...
from saylua.wrappers import api_login_required from flask import g, request from models.db import Game, GameLog from saylua.utils import int_or_none import json # Send a score to the API. @api_login_required() def api_send_score(game_id): try: gameName = Game(game_id) except IndexError: retu...
Python
0
43d7160272511107528a33d7dff932ed274d9b58
add sitemaps
fluent_faq/sitemaps.py
fluent_faq/sitemaps.py
from django.contrib.sitemaps import Sitemap from fluent_faq.models import FaqCategory, FaqQuestion from fluent_faq.urlresolvers import faq_reverse class FaqQuestionSitemap(Sitemap): """ Sitemap for FAQ questions """ def items(self): return FaqQuestion.objects.published() def lastmod(self,...
Python
0.000001
23f4e54ea84a23af55e29ead27a38af12672aa43
Create multi_currency_prices.py
examples/multi_currency_prices.py
examples/multi_currency_prices.py
from pyoanda import Client, PRACTICE client = Client(environment=PRACTICE,account_id="Your Oanda account ID",access_token="Your Oanda access token") # Get prices for a list of instruments pair_list = ['AUD_JPY','EUR_JPY','GBP_JPY','AUD_USD'] dataset = client.get_prices(instruments=','.join(pair...
Python
0
22b04a8a6a014ee4e077f2dc03338bdc9479cc5c
package module for handling wavelength calib
comoving_rv/longslit/wavelength.py
comoving_rv/longslit/wavelength.py
# Third-party import numpy as np from scipy.optimize import minimize, leastsq from scipy.stats import scoreatpercentile # Project from .models import voigt_polynomial __all__ = ['fit_emission_line'] def errfunc(p, pix, flux, flux_ivar): amp, x_0, std_G, fwhm_L, *bg_coef = p return (voigt_polynomial(pix, amp,...
Python
0
21e411171e811e1b68ad3674567ecb05f6f7a7ad
add migrations
cmsplugin_contact_plus/migrations/0004_auto_20170410_1553.py
cmsplugin_contact_plus/migrations/0004_auto_20170410_1553.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cmsplugin_contact_plus', '0003_auto_20161102_1927'), ] operations = [ migrations.AddField( model_name='extrafiel...
Python
0.000001
fe18d3387f7f8072b4f23990e5108f646729a860
Create pKaKs2.7.py
Modules/pKaKs2.7.py
Modules/pKaKs2.7.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.000002
61e56ad3feecef6fe422db8fb5d7b9b26dc03d6a
Add day 3 part 2.
day3-2.py
day3-2.py
"""This module checks how many valid triangles are in the input data.""" def main(): """Run main function.""" with open('data/day3data.txt', 'r') as f: input = f.readlines() dataList = [map(int, i.strip('\n').split()) for i in input] # Transpose the data. dataList = [list(i) for i in zip...
Python
0.000227
047541a111e9da5d59b47d40a528bc990bae6927
add scope expression
compiler/eLisp/eLisp/expr/scope.py
compiler/eLisp/eLisp/expr/scope.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- # # Copyright (c) 2015 ASMlover. 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 copyrig...
Python
0.000002
2d05a12a9b9534ad1925e7d543e6f66d8a79d3f8
Initialize P02_deleteBigFiles
books/AutomateTheBoringStuffWithPython/Chapter09/PracticeProjects/P02_deleteBigFiles.py
books/AutomateTheBoringStuffWithPython/Chapter09/PracticeProjects/P02_deleteBigFiles.py
# t’s not uncommon for a few unneeded but humongous files or folders to take up the # bulk of the space on your hard drive. If you’re trying to free up room on your # computer, you’ll get the most bang for your buck by deleting the most massive of # the unwanted files. But first you have to find them. # # Write a progr...
Python
0.000014
cee924604f070bd1bbca33dda53c5783e2678c5d
Add tests for sagepay
payments/sagepay/test_sagepay.py
payments/sagepay/test_sagepay.py
from __future__ import unicode_literals from unittest import TestCase from mock import patch, MagicMock from . import SagepayProvider VENDOR = 'abcd1234' ENCRYPTION_KEY = '1234abdd1234abcd' class Payment(MagicMock): id = 1 variant = 'sagepay' currency = 'USD' total = 100 status = 'waiting' ...
Python
0
2528be1179355a9fcce40f283be18e87d682fede
add rpn creat tools
example/rcnn/rcnn/tools/proposal.py
example/rcnn/rcnn/tools/proposal.py
import argparse import pprint import mxnet as mx from ..config import config, default, generate_config from ..symbol import * from ..dataset import * from ..core.loader import TestLoader from ..core.tester import Predictor, generate_proposals from ..utils.load_model import load_param def test_rpn(network, dataset, i...
Python
0
a07e4d08b475e0d921265f9da104f109943901bc
Add lammps wrapper tests with cuds
simlammps/tests/cuds_test.py
simlammps/tests/cuds_test.py
"""Tests for running lammps using CUDS and Simulation classes.""" import unittest from simphony.core.cuba import CUBA from simphony import CUDS, Simulation from simphony.engine import EngineInterface from simphony.testing.utils import create_particles_with_id from simphony.cuds.particles import Particle, Particles c...
Python
0
257c5bffe1804d694510f5a4638de8e6ae6a1470
Create lstm_gan_mnist.py
lstm_gan_mnist.py
lstm_gan_mnist.py
import tensorflow as tf
Python
0.000004
7a813d21043c394ab10e1ddb687d7827a8b7e761
add slideshare plugin
plugins/slideshare/slideshare.py
plugins/slideshare/slideshare.py
#!/usr/bin/env python import urllib2 import re import urllib import time import sha import BeautifulSoup from BeautifulSoup import BeautifulStoneSoup from optparse import OptionParser TOTALIMPACT_SLIDESHARE_KEY = "nyHCUoNM" TOTALIMPACT_SLIDESHARE_SECRET = "z7sRiGCG" MENDELEY_DOI_URL = "http://www.slideshare.net/api...
Python
0
de2d21316ca47d1839584a7cccbe8026489ace7d
Change Schema.schema to a property
iati/core/schemas.py
iati/core/schemas.py
"""A module containing a core representation of IATI Schemas.""" from lxml import etree import iati.core.exceptions import iati.core.resources import iati.core.utilities class Schema(object): """Represenation of a Schema as defined within the IATI SSOT. Attributes: name (str): The name of the Schema....
"""A module containing a core representation of IATI Schemas.""" from lxml import etree import iati.core.exceptions import iati.core.resources import iati.core.utilities class Schema(object): """Represenation of a Schema as defined within the IATI SSOT. Attributes: name (str): The name of the Schema....
Python
0
f015f04bf05e6e58efd5fd0f90bbe72745eb60b2
add experimental blas/lapack waf tool.
bento/backends/waf_tools/blas_lapack.py
bento/backends/waf_tools/blas_lapack.py
"""Experimental ! This will very likely change""" import collections import sys from bento.commands.options \ import \ Option from bento.backends.waf_backend \ import \ WAF_TOOLDIR import waflib from waflib import Options _PLATFORM_TO_DEFAULT = collections.defaultdict(lambda: "atlas") _PLATF...
Python
0
c388e6a4143b3646df5947cb5f596ec137488513
Add minimal skeleton for plotting script
plot.py
plot.py
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse import matplotlib.pyplot as plt import pandas as pd parser = argparse.ArgumentParser(description='Plot data from output of the n-body simulation.') parser.add_argument('--output', type=str, default='output_int.dat', help='The output file (d...
Python
0
a7ad8f2075e7661ad9ed539083a8785f7a628b95
test 1
dashsniffer/sniff.py
dashsniffer/sniff.py
def greet(name): print 'Hello', name greet('Jack') greet('Jill') greet('Bob')
Python
0.000201
faf13ff99fd47424c4fb93f1c2a6b3b80c81e0d1
replace bin<->text converters for ipv6
ryu/lib/ip.py
ryu/lib/ip.py
from ryu.lib import addrconv def ipv4_arg_to_bin(w, x, y, z): """Generate unsigned int from components of IP address returns: w << 24 | x << 16 | y << 8 | z""" return (w << 24) | (x << 16) | (y << 8) | z def ipv4_to_bin(ip): ''' Parse an IP address and return an unsigned int. The ...
import struct def ipv4_arg_to_bin(w, x, y, z): """Generate unsigned int from components of IP address returns: w << 24 | x << 16 | y << 8 | z""" return (w << 24) | (x << 16) | (y << 8) | z def ipv4_to_bin(ip): ''' Parse an IP address and return an unsigned int. The IP address is i...
Python
0
f189137d52b9f44db0e82723b0e7a16a602c6523
Create duplicate_encoder.py
duplicate_encoder.py
duplicate_encoder.py
#Kunal Gautam #Codewars : @Kunalpod #Problem name: Duplicate Encoder #Problem level: 6 kyu def duplicate_encode(word. st=""): for char in word.lower(): if word.lower().count(char)>1: st = st + ')' else: st = st + '(' return st
Python
0.001774
488717ab6c84c771737a3b2ccfe8cbf4d270c9b7
Implement dragon class
mugloar/dragon.py
mugloar/dragon.py
import json class Dragon: # By default, stay home. scaleThickness = 0 clawSharpness = 0 wingStrength = 0 fireBreath = 0 def __init__(self, weather_code): if weather_code == 'T E': # Draught requires a 'balanced' dragon, ha ha self.scaleThickness = 5 ...
Python
0.000027
5f092edf48828f61042c78878474b8c85b62fbdd
Bump version to turn on SET_MAX_FPS.
o3d/installer/win/o3d_version.py
o3d/installer/win/o3d_version.py
#!/usr/bin/python2.4 # Copyright 2008-9 Google Inc. All Rights Reserved. # version = (major, minor, trunk, patch) plugin_version = (0, 1, 43, 2) sdk_version = plugin_version
#!/usr/bin/python2.4 # Copyright 2008-9 Google Inc. All Rights Reserved. # version = (major, minor, trunk, patch) plugin_version = (0, 1, 43, 1) sdk_version = plugin_version
Python
0.000001
beeb3065e2d366dd68021eb5f55c94e2c61684e4
add experiment script
ftrl/single_feature_experiment.py
ftrl/single_feature_experiment.py
import subprocess for i in range(3, 23): print "\n\n\nrun field " + str(i) + "\n" subprocess.call("python ftrl/ftrl.py train.raw.csv test.raw.csv submission.csv {0}".format(i).split(" "), shell=True)
Python
0.000001
e5f130c1f006d2b96ca81be5a9f66c15b97b8793
Create sol2.py
project_euler/problem_12/sol2.py
project_euler/problem_12/sol2.py
def triangle_number_generator(): for n in range(1,1000000): yield n*(n+1)//2 def count_divisors(n): return sum([2 for i in range(1,int(n**0.5)+1) if n%i==0 and i*i != n]) print(next(i for i in triangle_number_generator() if count_divisors(i) > 500))
Python
0.000044