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
d84b0a0c882737971787b6a4da20733301de56b6
add weixin backend
social/backends/weixin.py
social/backends/weixin.py
#coding:utf8 # author:duoduo3369@gmail.com https://github.com/duoduo369 """ Weixin OAuth2 backend, docs at: """ from requests import HTTPError from social.backends.oauth import BaseOAuth2 from social.exceptions import AuthCanceled, AuthUnknownError class WeixinOAuth2(BaseOAuth2): """Weixin OAuth authentication ...
Python
0
238f62cadfe4514b116ffaa0b0c2206e31132d8e
Add poll.py, which polls an F5 load balancer for virtual service stats and sends them to Graphite
poll.py
poll.py
#!/usr/bin/env python from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.smi import builder import time import socket import struct import pickle hostname = socket.gethostname().split('.') colo = hostname[1] CARBON_SERVER = "" CARBON_PORT = 2004 COMMUNITY_STRING = "" cmdGen = cmdgen.CommandGenerator() m...
Python
0
013016bf533a91e7dceffd806a8a1db0e8b6a74c
add admin.py to device logs for text-based searching
corehq/ex-submodules/phonelog/admin.py
corehq/ex-submodules/phonelog/admin.py
from django.contrib import admin from .models import * class DeviceReportEntryAdmin(admin.ModelAdmin): model = DeviceReportEntry list_display = [ 'xform_id', 'msg', 'type', 'domain', 'date', 'username', ] search_fields = [ 'xform_id', '...
Python
0
717f3c5d4babe9feeb4e0d82fb2ea839d735c4b4
Test database.common for full coverage of database
test/backend/test_database/test_common.py
test/backend/test_database/test_common.py
import mock from linkr import db import database.common from test.backend.test_case import LinkrTestCase class TestCommon(LinkrTestCase): def test_create_tables(self): with mock.patch.object(db, 'create_all') as mock_create: database.common.create_tables() self.assertTrue(mock_cre...
Python
0
62962e852b24e9659b82615190cf184896fe08d7
Add account tasks
froide/account/tasks.py
froide/account/tasks.py
from django.conf import settings from django.utils import translation from froide.celery import app as celery_app from .models import User @celery_app.task def cancel_account_task(user_pk): from .utils import cancel_user translation.activate(settings.LANGUAGE_CODE) try: user = User.objects.get...
Python
0.000003
6ded4655ea71e9658cf53c6ca802251a6570d380
Copy of telegram notifier for customization (MD/HTML parser option)
custom_components/notify/mytelegram.py
custom_components/notify/mytelegram.py
# -*- coding: utf-8 -*- """ Telegram platform for notify component. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/notify.telegram/ """ import io import logging import urllib import requests import voluptuous as vol import homeassistant.helpers.config_...
Python
0
a5fdfa9fefa3b5c8d0df763b5e9435f42cdaf4fb
Implement base spell model with cooldown/cost/etc
game/spells/__init__.py
game/spells/__init__.py
# -*- coding: utf-8 -*- """ Spells - Spell.dbc """ from .. import * from .. import durationstring from ..globalstrings import * POWER_TYPE_HEALTH = -2 POWER_TYPE_MANA = 0 POWER_TYPE_RAGE = 1 POWER_TYPE_FOCUS = 2 POWER_TYPE_ENERGY = 3 POWER_TYPE_RUNES = 5 POWER_TYPE_RUNIC_POWER = 6...
Python
0
97c93e1c678c93dccb9a361bdffe5b1edd51f144
make ansi
make_ansi.py
make_ansi.py
#!/usr/bin/env python import re import math from pprint import pprint, pformat from colortrans import rgb2short from from pygments.styles import get_style_by_name, get_all_styles BASE_COLORS = { 'BLACK': (0, 0, 0), 'RED': (170, 0, 0), 'GREEN': (0, 170, 0), 'YELLOW': (170, 85, 0), 'BLUE': (0, 0, 170...
Python
0.000775
4316122225d2e523ff310f65479ea676e0aa02e3
Add methods for loading data sets
load_data_sets.py
load_data_sets.py
import os import numpy as np import sgf_wrapper def load_sgf_positions(*dataset_names): for dataset in dataset_names: dataset_dir = os.path.join(os.getcwd(), 'data', dataset) dataset_files = [os.path.join(dataset_dir, name) for name in os.listdir(dataset_dir)] all_datafiles = filter(os.pat...
Python
0.000001
263fb51df80a9da6efc567f7e6e3b26012e12a4c
Fix bug for url_to_s3
modules/data_source/url_to_s3/main.py
modules/data_source/url_to_s3/main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from specparser import get_settings_from_file import os import sys import boto import requests from StringIO import StringIO def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() def s3_multipart_upload(bucket, url, remote_filename): from ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from specparser import get_settings_from_file import os import sys import boto import requests from StringIO import StringIO def percent_cb(complete, total): sys.stdout.write('.') sys.stdout.flush() def s3_multipart_upload(bucket, url, remote_filename): from ...
Python
0.000001
02401c9cdccaa52cf933ffc16225dc6bcbc2a1c3
Create matrix.py
dasem/matrix.py
dasem/matrix.py
"""Matrix. Usage: dasem.docterm save-wikipedia-doc-term-matrix [options] <filename> Options: --output-filename Filename to write to -h --help Help message --max-n-pages=<int> Maximum number of pages -v --verbose Verbose debug messaging """ import json from scipy import io from ....
Python
0.000006
715e02da3f2bdf8bff6d18258295e0152c27acef
Add the procedure generator
src-backend/api/generator.py
src-backend/api/generator.py
from xml.etree import ElementTree from xml.dom import minidom from models import * class ProcedureGenerator: def __init__(self, procedure): self.name = 'Procedure' self.procedure = procedure def _get_properties(self): props = { 'title': self.procedure.title, 'a...
Python
0
b97c67277c049602b6a41d7222539ba459155cdb
Create imagebot.py
imagebot.py
imagebot.py
import urllib import time import json import requests import os TOKEN = "<your-bot-token>" URL = "https://api.telegram.org/bot{}/".format(TOKEN) IMAGE_URL = "https://api.telegram.org/file/bot{}/".format(TOKEN) DOWNLOADED_IMAGE_PATH = "/Telegram/" def get_url(url): """Downloads the content from a URL and gives us ...
Python
0.000002
9707ccdab7f51e61dda2ac290ffda882d3610ee8
Create retrieve_newest_file_from_nas.py
retrieve_newest_file_from_nas.py
retrieve_newest_file_from_nas.py
#!/bin/env python3 """ Copies the most recent datafile from a secure NAS to a local file. """ key_file = 'key_rsa' # NOT .pub import paramiko import sqlite3 from datetime import datetime host = 'hostname' port = 22 username = '' filecount = 15 localdir = r"C:/" remotedir = r"/nas/data/" # SSH Key my_key = paramiko....
Python
0
d88c53ba3dac62c361f60523196d3dc7b9bd90b1
Add spider for Einstein Bros. Closes #784
locations/spiders/einsteinbros.py
locations/spiders/einsteinbros.py
# -*- coding: utf-8 -*- import datetime import re import scrapy from locations.items import GeojsonPointItem from locations.hours import OpeningHours DAY_MAPPING = { 'Monday': 'Mo', 'Tuesday': 'Tu', 'Wednesday': 'We', 'Thursday': 'Th', 'Friday': 'Fr', 'Saturday': 'Sa', 'Sunday': 'Su' } cl...
Python
0
c57af132aa33f81c3c18c299ca37edbcc81b3dc4
Add unit tests for Tile
bayespy/inference/vmp/nodes/tests/test_deterministic.py
bayespy/inference/vmp/nodes/tests/test_deterministic.py
###################################################################### # Copyright (C) 2013 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
688d10d2d07648329766a867a8d601c06630a8fa
add Ruby/Topaz plugin
rsqueakvm/plugins/ruby_plugin.py
rsqueakvm/plugins/ruby_plugin.py
from rsqueakvm.error import PrimitiveFailedError from rsqueakvm.model.numeric import W_Float, W_SmallInteger from rsqueakvm.model.variable import W_BytesObject from rsqueakvm.model.base import W_AbstractObjectWithIdentityHash from rsqueakvm.model.compiled_methods import W_PreSpurCompiledMethod, W_SpurCompiledMethod fro...
Python
0
38587aa6c906b87e5a908a6b963d89cbc2fc5505
move manage.py into src folder
src/manage.py
src/manage.py
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
Python
0.000001
e8880307030922f1ab7b2445ee67179fe276f1b1
add trayicon test
netk/tests/testtrayicon.py
netk/tests/testtrayicon.py
#!/usr/bin/env python import pygtk pygtk.require("2.0") import xfce4 label = gtk.Label("Boo!") label.show() ti = xfce4.netk.TrayIcon(gtk.gdk.screen_get_default()) ti.add(label) ti.show() gtk.main()
Python
0
d9def2c4a7dd315df15725151945f30d7e48bace
Simplify odoo start. Make it work everywhere
openerp/cli/start.py
openerp/cli/start.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import glob import os import sys from . import Command from .server import main from openerp.modules.module import get_module_root, MANIFEST from openerp.service.db import _create_empty_database, DatabaseExists class Start(Command): """Quick start the...
#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import glob import os import sys from . import Command from .server import main from openerp.modules.module import get_module_root, MANIFEST from openerp.service.db import _create_empty_database, DatabaseExists class Start(Command): """Quick start the...
Python
0.000002
fd452b1bf95446e655743c4efdb00f118ca3e7bc
add integration test baseclass
mpf/integration/MpfIntegrationTest.py
mpf/integration/MpfIntegrationTest.py
import os os.environ["KIVY_NO_ARGS"] = "1" from queue import Queue import time from kivy import Config, Logger from kivy.base import runTouchApp, EventLoop from kivy.clock import Clock from kivy.uix.widget import Widget import mpfmc from mpf.core.utility_functions import Util from mpf.tests.MpfBcpTestCase import Moc...
Python
0
e4cd6dbd730f6a8a018cc5d987b3fb36d036cdd5
add random todo about misleading function override
corehq/apps/custom_data_fields/models.py
corehq/apps/custom_data_fields/models.py
from couchdbkit.ext.django.schema import (Document, StringProperty, BooleanProperty, SchemaListProperty, StringListProperty) from jsonobject import JsonObject from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ CUSTOM_DATA_FIELD_PREFIX = "data-field" # This list i...
from couchdbkit.ext.django.schema import (Document, StringProperty, BooleanProperty, SchemaListProperty, StringListProperty) from jsonobject import JsonObject from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ CUSTOM_DATA_FIELD_PREFIX = "data-field" # This list i...
Python
0
ca000b194397d314473040cd634d203b8aa0828a
add task generator for subtask 2
bigbench/benchmark_tasks/unit_conversion/2_novel_systems/task_generator.py
bigbench/benchmark_tasks/unit_conversion/2_novel_systems/task_generator.py
#!/usr/bin/env python # coding: utf-8 import json from math import floor, log10, sqrt import numpy as np import random def generate_question(q_type, amount1, amount2, q_ind1, q_ind2, conv_rate): # Generate question to ask model to convert $amount of unit1 into unit2. unit1 = base_quantity[q_ind1] unit2 = ...
Python
0.000027
b3265f241ad4c405bc56cc1b4a5154dc3a4098bd
Create settings.py
settings.py
settings.py
API_KEY = "API_KEY" API_SECRET = "API_SECRET" ACCESS_TOKEN="ACCESS_TOKEN" ACCESS_TOKEN_SECRET="ACCESS_TOKEN_SECRET"
Python
0.000001
52cd20e57b14d2d80a3bb6f1fe3c1391fcc69f64
Create the class `RequestWrapperBase` It can be used to generate package-dependent request_args() function.
flask_reqarg/base.py
flask_reqarg/base.py
# -*- coding: utf-8 -*- from abc import ABCMeta, abstractproperty from functools import wraps from inspect import isfunction, getargspec from itertools import izip __all__ = ( 'get', 'post', 'args', 'files', 'cookies', 'collection', 'RequestWrapperBase' ) def _extract_method(kwargs): ...
Python
0
97c149057bf68ef8063316acad2b4c86f6579452
Create maximum-vacation-days.py
Python/maximum-vacation-days.py
Python/maximum-vacation-days.py
# Time: O(n^2 * k) # Space: O(k) class Solution(object): def maxVacationDays(self, flights, days): """ :type flights: List[List[int]] :type days: List[List[int]] :rtype: int """ if not days or not flights: return 0 dp = [[0] * len(days) for _ in ...
Python
0.999174
612fb44b33c4f52488f3565c009188d61a8343c2
Add an auto join script
python/autojoin_on_invite.py
python/autojoin_on_invite.py
__module_name__ = "autojoin on invite" __module_version__ = "1.0" import hexchat def join(word, word_eol, userdata): hexchat.command('join ' + word[0]) hexchat.hook_print('Invited', join)
Python
0.000001
3fd3b376b1334dba0ffea3641dcbb32d788f4083
Add migration script to fix templated orphans.
scripts/fix_templated_orphans.py
scripts/fix_templated_orphans.py
# -*- coding: utf-8 -*- """Find orphaned templated nodes without parents, then attempt to identify and restore their parent nodes. Due to a bug in templating that has since been fixed, several templated nodes were not attached to the `nodes` lists of their parents. """ import logging from modularodm import Q from ...
Python
0
8f6bbbe30b77c2722c5ea0f03432e2c77b2eb4c6
add CLI stub for calendar service
quantrocket/cli/subcommands/calendar.py
quantrocket/cli/subcommands/calendar.py
# Copyright 2017 QuantRocket - 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 ...
Python
0
f18e500ff7eb1b73097786892673934346c9a94f
Create sign_rpm.py
sign_rpm.py
sign_rpm.py
+#!/bin/python + +import argparse, subprocess, shlex, os +defaults = {} +defaults['rpm_dir'] = '' + +def get_args(): + parser = argparse.ArgumentParser(description="Setup a GPG macro to be used in signing an rpm. Optionally you can provide the location of rpm's and sign them as well") + parser.add...
Python
0
8995e45946812f5cd982d52bd12a99915a8b03cc
Add script to migrate artifact references
scripts/migrate-artifact-refs.py
scripts/migrate-artifact-refs.py
import sys import logging from cPickle import loads from pylons import c from allura import model as M log = logging.getLogger('allura.migrate-artifact-refs') # Threads have artifact references that must be migrated to the new system def main(): test = sys.argv[-1] == 'test' all_projects = M.Project.query.f...
Python
0
e7394973e5383fc72c4f8004390a05bc91b9053e
Add a skeleton Python file that can be reused.
skeleton.py
skeleton.py
# Copyright 2017 Varun Khaneja # 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, distribute...
Python
0
4b44eec7bde92c77f513aac664fe5b52736b874c
Add test code.
burrahobbit/test/test_dict.py
burrahobbit/test/test_dict.py
# Copyright (C) 2011 by Florian Mayer <flormayer@aim.com> # # 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, modif...
Python
0.000001
cbfac58b830511f015539801024e92bc11696a09
add expected batches gradnet files
treeano/sandbox/nodes/expected_batches.py
treeano/sandbox/nodes/expected_batches.py
import theano import theano.tensor as T import treeano import treeano.nodes as tn fX = theano.config.floatX class BaseExpectedBatchesNode(treeano.NodeImpl): hyperparameter_names = ("expected_batches",) def init_state(self, network): expected_batches = network.find_hyperparameter(["expected_batches...
Python
0
df17f792faab74955f5e9573bf7dd9812b489bd3
Add a hybridization example using Slate manually
hybridization_solver.py
hybridization_solver.py
from __future__ import absolute_import, print_function, division from firedrake import * qflag = False degree = 1 mesh = UnitSquareMesh(8, 8, quadrilateral=qflag) n = FacetNormal(mesh) if qflag: RT = FiniteElement("RTCF", quadrilateral, degree) DG = FiniteElement("DQ", quadrilateral, degree - 1) Te = Fi...
Python
0.000001
efa84ed71e6804d71dd639715299a6438824fd64
add unit tests for nacelle's session handling
nacelle/tests/tests_session_handling.py
nacelle/tests/tests_session_handling.py
""" Test nacelle's session handling """ # third-party imports import webapp2 # local imports from nacelle.conf import settings from nacelle.test.testcases import NacelleTestCase # test fixtures: we need to set up a local wsgi app so we can test the login # decorators against real handlers def set_session_var(reques...
Python
0
3523879c9b67766a3d248c7c1260715534ee0671
add test_list
misc/test_list.py
misc/test_list.py
# -*- coding: utf-8 -*- # 可以看出这四种方式都可以向列表中添加一个新元素,除了"+"之外,其他三种方式都是在原列表上添加数据, # "+"则会创建一个新的列表,并且"+"只能连接两个列表,如果连接一个元素跟一个列表会报错 # 添加一个元素到列表中 a = ["a", "b", "c"] print ("append|添加前id:%s" % id(a)), a.append("d") print ("添加后id:%s, %s" % (id(a), a)) print ("-"*62) a = ["a", "b", "c"] print ("extend|添加前id:%s" % id(a)), a.ext...
Python
0.000002
ba2d1a707a0869ad0266380b818f88fe626e0267
Add alphabet_lstm.py
alphabet_lstm.py
alphabet_lstm.py
import numpy as np from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.utils import np_utils # http://machinelearningmastery.com/understanding-stateful-lstm-recurrent-neural-networks-python-keras/ if __name__ == "__main__": # fix random seed for reproducibil...
Python
0.999999
46e66f00ab8c340ca1f104c40c6b9a76762d7ec3
Add example script
examples/cluster/experimental_cloud.py
examples/cluster/experimental_cloud.py
# Licensed to Modin Development Team under one or more contributor license agreements. # See the NOTICE file distributed with this work for additional information regarding # copyright ownership. The Modin Development Team licenses this file to you under the # Apache License, Version 2.0 (the "License"); you may not u...
Python
0
3ddb3c93693822f0fdb3256a360754a4994a954e
add qutebrowser config
overlay/.config/qutebrowser/config.py
overlay/.config/qutebrowser/config.py
c.url.start_pages = ["https://start.duckduckgo.com"] c.content.javascript.enabled = False c.content.headers.accept_language = "en-US,en;q=0.5" c.content.headers.custom = {"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"} c.content.headers.user_agent = 'Mozilla/5.0 (Windows NT 6.1; rv:52.0) G...
Python
0
73a00c9ac8e237dbd317e3e81ab19521cd7942de
Add donorresponse types
iatidq/donorresponse.py
iatidq/donorresponse.py
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3...
Python
0
4107696d3605d600b09ebf1f0a5a2c97fbae0b10
Move wordcount with metrics to its own file.
sdks/python/apache_beam/examples/wordcount_with_metrics.py
sdks/python/apache_beam/examples/wordcount_with_metrics.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
Python
0
4ca364980441dc3f41339db62f774f077588be40
Add first version of the manager
dcclient/xml_manager/manager.py
dcclient/xml_manager/manager.py
""" Methos to create and manipulate the XML """ import data_structures class ManagedXml: def __init__(self): self.xml = data_structures.Cfg_data() def addVlan(self, vid, name='', ports=[]): """ This method adds a vlan to the XML an returns it's instance. """ vlan = data_struc...
Python
0.000001
8e982c72829574a00a97f389ac169e5760d53f3c
Create restartable_thread.py
restartable_thread.py
restartable_thread.py
import threading import time class ThreadRestartable(threading.Thread): def __init__(self, theName): threading.Thread.__init__(self, name=theName) def run(self): print "In ThreadRestartable\n" time.sleep(10) thd = ThreadRestartable("WORKER") thd.start() while(1): i = 0 for t ...
Python
0
8a844b78c5ded93ce7a75585a6ad2b86d8b4cb13
Add recognize decoding typedef or local type
pida_type_decoder.py
pida_type_decoder.py
from pida_types import IDA_TYPES from pida_tlocal_type import IdaTLocalType def decode_step(ida_type): # TODO : pass def decode_hybrid_type(ida_type): value = {'idt': None, 'value': None} rbyte = ord(ida_type[0]) if not (ida_type[1] == '#' and rbyte in [4, 5]): value = {'idt': IDA_TYPES[...
Python
0.000001
a8507ef2f4d3eaa4f3eeeebbb9dbeb5f008b2737
Add tmux-process-search.py
bin/tmux-process-search.py
bin/tmux-process-search.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Search the tmux process tree. """ import sys as _sys import argparse as _argparse import subprocess as sub import shlex as sh import psutil TMUX_LIST_CMD = 'tmux list-panes -a -F "#{pane_pid} #{session_name}" | grep {0}' def find_session(pid): """Return the tmu...
Python
0.000002
4e617fef31af8360985abed00da43223ef5cc015
Allow force installation of requirements
blues/application/tasks.py
blues/application/tasks.py
import os from fabric.decorators import task from fabric.state import env from fabric.utils import indent from refabric.utils import info from .deploy import * from .project import * from .providers import get_providers from .. import git from ..app import blueprint __all__ = [] @task def setup(): """ In...
import os from fabric.decorators import task from fabric.state import env from fabric.utils import indent from refabric.utils import info from .deploy import * from .project import * from .providers import get_providers from .. import git from ..app import blueprint __all__ = [] @task def setup(): """ In...
Python
0
f0c1263f1ca6d9a4f45eea3b19b9f818ed303d26
Add examples/tic_ql_tab_simple_selfplay.py
examples/tic_ql_tab_simple_selfplay.py
examples/tic_ql_tab_simple_selfplay.py
''' The Q-learning algorithm is used to estimate the state-action values for a simple Tic-Tac-Toe position by playing games against itself (self-play). ''' from capstone.game.games import TicTacToe from capstone.game.players import RandPlayer from capstone.game.utils import tic2pdf from capstone.rl import Environment, ...
Python
0.000001
6b00d2a2ca774bff57b523339c10759be4619da6
add cluster name to detected cluster
tendrl/node_agent/node_sync/sds_detect.py
tendrl/node_agent/node_sync/sds_detect.py
import etcd from tendrl.commons.event import Event from tendrl.commons.message import Message, ExceptionMessage from tendrl.node_agent.discovery.sds import manager as sds_manager def load_and_execute_sds_discovery_plugins(): Event( Message( priority="info", publisher=NS.publisher...
import etcd from tendrl.commons.event import Event from tendrl.commons.message import Message, ExceptionMessage from tendrl.node_agent.discovery.sds import manager as sds_manager def load_and_execute_sds_discovery_plugins(): Event( Message( priority="info", publisher=NS.publisher...
Python
0
0663a2f90870e0f8b902aa97a479ee9d8ab3b23c
Add usage example to tf.keras.utils.to_categorical
tensorflow/python/keras/utils/np_utils.py
tensorflow/python/keras/utils/np_utils.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Python
0.000019
8dc22c4c575b7c6931ab3ed14ef40b43dc03a685
TEST initiated
dipy/core/tests/test_stensor.py
dipy/core/tests/test_stensor.py
""" Testing qball """ import os from os.path import join as pjoin import numpy as np import dipy.core.stensor as ten from nose.tools import assert_true, assert_false, \ assert_equal, assert_raises from numpy.testing import assert_array_equal, assert_array_almost_equal from dipy.testing import parametric fr...
Python
0
45c836283232e48e13c139188dac0b11128cb0ac
Add drawcrowd support
plugins/drawcrowd.py
plugins/drawcrowd.py
# The MIT License (MIT) # Copyright (c) 2015 kupiakos # 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, me...
Python
0
775bca5465022e905a58859d72a970749973dba4
Create main.py
msort/src/main.py
msort/src/main.py
def split(L:list) -> list: ret = [] for i in L: ret.append([i]) while len(ret) > 1: ret[0] = merge(ret[0], ret[1]) del ret[1] return ret[0] def merge(L1:list, L2:list) -> list: for i in L2: for n, j in enumerate(L1): if i <= j: L1.insert(n, i) break else: L1.append(i) return L1 def mai...
Python
0
572e0174ca313a2c1faa906f989d92575e449f78
add cnn_model.py
dnlp/classifier/cnn_model.py
dnlp/classifier/cnn_model.py
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np class CNNModel(object): """ CNN for text classification. embedding layer, followed by convolutional, max-pooling and softmax layer """ def __init__( self, sequence_length, label_size, vocab_size, embedding_size, filter_...
Python
0.000011
ac8759778ba3bb9af64259685f4f9526b7a452e3
add shortcuts for number localization
gittip/utils/i18n.py
gittip/utils/i18n.py
from __future__ import print_function, unicode_literals import os from aspen.utils import utcnow from babel.dates import format_timedelta import babel.messages.pofile from babel.numbers import ( format_currency, format_decimal, format_number, format_percent ) def to_age(dt, loc): return format_timedelta(utc...
from __future__ import print_function, unicode_literals import os from aspen.utils import utcnow from babel.dates import format_timedelta import babel.messages.pofile def to_age(dt, loc): return format_timedelta(utcnow() - dt, add_direction=True, locale=loc) def load_langs(localeDir): langs = {} for f...
Python
0.000002
915dd2ca82bd42ed58768cb1139ceaceada42c84
add simple bmp station application
ryu/app/bmpstation.py
ryu/app/bmpstation.py
import socket import logging logging.basicConfig(level=logging.DEBUG) from ryu.base import app_manager from ryu.lib import hub from ryu.lib.hub import StreamServer from ryu.lib.packet.bmp import * SERVER_HOST = '0.0.0.0' SERVER_PORT = 11019 class BMPStation(app_manager.RyuApp): def __init__(self): supe...
Python
0
aa81979fb20cdfdd721e1e1fb99c72c6cfa93f7f
Add elevator.py
elevator.py
elevator.py
#!/usr/bin/python import unittest # TODO: add information sign to the elevator # TODO: generate persons class Simulation: def __init__(self, floors_count): self.floors = [Floor(x) for x in range(floors_count)] self.elevators = [] def add_elevator(self, elevator): self.elevators.appe...
Python
0.999142
ac154337f248ae71fda783acad0ea5373f4cee59
Initialize azure driver
cloudstorage/drivers/azure.py
cloudstorage/drivers/azure.py
"""Microsoft Azure Storage Driver.""" import logging try: from http import HTTPStatus except ImportError: # noinspection PyUnresolvedReferences from httpstatus import HTTPStatus from typing import Dict, Iterable, List, Union from azure.storage.blob import BlockBlobService from azure.storage.blob.models i...
Python
0.000002
b077fb6e577e013cf95b57b1ea7d42febc3b03e7
Add encoding module.
encoding.py
encoding.py
"""Script for encoding a payload into an image.""" from PIL import Image, ImageMath def encode(host, payload): # type: (PIL.Image, PIL.Image) -> PIL.Image """Encode a payload into an image.""" output_rgb_channels = [] for host_channel, payload_channel in zip(host.split(), payload.split()): # M...
Python
0
241a2820c90817be6dbabb6642b499cf1a224925
Add limb drawing example
examples/gallery/plot_AIA_limb_STEREO.py
examples/gallery/plot_AIA_limb_STEREO.py
# -*- coding: utf-8 -*- """ ================================= Drawing AIA Limb on STEREO Images ================================= In this example we use a STEREO-B and an SDO image to demonstrate how to overplot the limb as seen by AIA on an EUVI-B image. This makes use of functionality added in Astropy 1.3. """ ###...
Python
0
38b416453c0e0b64d86270232879fb73b2f67d36
Add async Api class
grapheneasync/api.py
grapheneasync/api.py
# -*- coding: utf-8 -*- import asyncio import logging from grapheneapi.exceptions import NumRetriesReached from grapheneapi.api import Api as OriginalApi from .websocket import Websocket from .http import Http log = logging.getLogger(__name__) class Api(OriginalApi): def __init__(self, *args, **kwargs): ...
Python
0.000001
0ad8d8665f064542346c3788cecaffdcb68f168a
Create tests for custom exceptions and warnings
plasmapy/utils/tests/test_exceptions.py
plasmapy/utils/tests/test_exceptions.py
import pytest import warnings from .. import (PlasmaPyError, PhysicsError, RelativityError, AtomicError) from .. import (PlasmaPyWarning, PhysicsWarning, RelativityWarning, AtomicWarning) plasmapy_exceptions = [ Plas...
Python
0
abedd32bfd5c8dba3802687372e97cd117a14f32
Create dt-robot.py
dt-robot.py
dt-robot.py
#!/usr/bin/env python #coding=utf-8 """ 钉钉群自定义机器人 author:疯狂的技术宅 github:https://github.com/magician000 学习python时做的练习,纯粹为了娱乐 如果存在bug请自行修改,不提供任何支持 官方文档 https://open-doc.dingtalk.com/docs/doc.htm?spm=a219a.7629140.0.0.z5MWoh&treeId=257&articleId=105735&docType=1 这个接口的消息格式命名风格不统一,坑爹呢? 所以不要迷信大公司就怎样规范。 """ import sys imp...
Python
0.000039
47bc22166213e50b4f5a2bc583752ff10babd188
add scripts/check_dict.py
scripts/check_dict.py
scripts/check_dict.py
#!/usr/bin/python import sys if len(sys.argv) == 1: print "usage : %s dict_file1 dict_file2 ..." exit(1) d = {} for fname in sys.argv[1:]: with open(fname, "r") as fin: for i, line in enumerate(fin): try: word, cnt, tag = line.strip().split(" ") if wor...
Python
0.000001
7a039a9c99e0a3fbd786de7794a798063b271b2f
Create parse_selected_language.py
parse_selected_language.py
parse_selected_language.py
# # Main idea: to extract only a particular "language" from text content containing words / characters from different language. # Using regex, we search for characters within particular unicode ranges and exclude the rest. # import re def parse_only_text(string, setting): ''' Available settings: * "alphab...
Python
0.000006
ad934a9abd973141434a12eb346a339d876b5baf
Add regression test for #693
spacy/tests/regression/test_issue693.py
spacy/tests/regression/test_issue693.py
# coding: utf8 from __future__ import unicode_literals import pytest @pytest.mark.xfail @pytest.mark.models def test_issue693(EN): """Test that doc.noun_chunks parses the complete sentence.""" text1 = "the TopTown International Airport Board and the Goodwill Space Exploration Partnership." text2 = "the ...
Python
0.000002
6cd12f2aaa6170daef88a913ee78b725b6450d61
Add check for 'not guilty beyond a reasonable doubt'
proselint/checks/garner/not_guilty.py
proselint/checks/garner/not_guilty.py
# -*- coding: utf-8 -*- """Not guilty beyond a reasonable doubt. --- layout: post source: Garner's Modern American Usage source_url: http://bit.ly/1T4alrY title: Not guilty beyond a reasonable doubt. date: 2016-03-09 15:50:31 categories: writing --- This phrasing is ambiguous. The standard by which...
Python
0.000001
5127914f6842e77e9a1613b58ff28fae420b0da8
Create chi_make_a_smoothie_bot.py
chi_make_a_smoothie_bot.py
chi_make_a_smoothie_bot.py
from asyncio import sleep import discord import subprocess import time from datetime import datetime import sys from pathlib import Path client = discord.Client() client.started = False @client.event async def on_ready(): if client.started: # @Hack: Properly deal with disconnection / reconnection ...
Python
0.000025
024280702c11d896195706b299767fdbd73d59f6
add script
scripts/map_filter.py
scripts/map_filter.py
#!/usr/bin/env python import pysam import argparse def avgmap(maptabix, chrom, start, end): ''' return average mappability across chrom:start-end region; maptabix = pysam.Tabixfile''' scores = [] if None in (start, end): return None if chrom in maptabix.contigs: for rec in maptabix.fetch(ch...
Python
0.000001
62dc9c91c277bc4755f81597adca030a43d0ce5f
Add async_apple_scanner example (#719)
examples/async_apple_scanner.py
examples/async_apple_scanner.py
#!/usr/bin/env python3 """ Scan for apple devices. """ import argparse import asyncio import logging from typing import Any, Optional, cast from zeroconf import DNSQuestionType, IPVersion, ServiceStateChange, Zeroconf from zeroconf.aio import AsyncServiceBrowser, AsyncServiceInfo, AsyncZeroconf HOMESHARING_SERVICE:...
Python
0
3740edf4488456e5b04d3943d47f9a2586f3b0e5
add a Riemann phase plot
compressible/riemann-phase.py
compressible/riemann-phase.py
# plot the Hugoniot loci for a compressible Riemann problem import numpy as np import pylab gamma = 1.4 class State: """ a simple container """ def __init__(self, p=1.0, u=0.0, rho=1.0): self.p = p self.u = u self.rho = rho def u_hugoniot(p, state, dir): c = np.sqrt(gamma*st...
Python
0.000076
3eb70001e175077b9f8e6a696f009ca2a2b76002
Add python solution to 001
001/001.py
001/001.py
print sum([a * b for a, b in zip(map(lambda n: sum(filter(lambda x: not x % n, range(1000))), (3, 5, 15)), (1, 1, -1))])
Python
0.999972
389f9709fad7a973d57d626e45e946d5ee1cc82e
Add documentation generation script
docs/autogen.py
docs/autogen.py
# -*- coding: utf-8 -*- from __future__ import print_function import re import inspect import os import shutil from keras.layers import convolutional from keras.layers import recurrent from keras.layers import core from keras.layers import noise from keras.layers import normalization from keras.layers import advanced_...
Python
0.000001
2c9760da48caaf9656c8b1e3f81e70671b7e7c5e
Add missing migration for audit app.
postgres/audit/migrations/0003_auditlog_app_session.py
postgres/audit/migrations/0003_auditlog_app_session.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('audit', '0002_auditlog'), ] operations = [ migrations.AddField( model_name='auditlog', name='app_ses...
Python
0
9198b5f153fa21a6a1134cbb3499b767f7780fb1
add the first version of enemy class
enemy.py
enemy.py
import entity class Enemy(entity.Entity): def __init__(self, health, damage): super().__init__(health, damage) def __str__(self): return "enemy:\n" + super().__str__()
Python
0
d138b826d1c26853ad9ec2cb49c39c2a11617b84
Add __init__.py to appease older python versions
wrangler/__init__.py
wrangler/__init__.py
Python
0.000013
b261a85300dfd6413bb436114b549b087aab211b
allow module execution (#184)
coveralls/__main__.py
coveralls/__main__.py
from .cli import main if __name__ == '__main__': main()
Python
0
a4be10de8f6b7ef59e73f6e5c81bb73a3d769145
Create fetchseq.py
fetchseq.py
fetchseq.py
# -*- coding: utf-8 -*- """ Created on Fri Jun 3 14:15:58 2016 @author: Ahmed """ """Fetch sequences in fasta format for given antiCRISPR protein accession numbers. Adapted from https://www.biostars.org/p/66921/ + acc2gb.py USAGE: cat <file> | python fetchseq.py <email> > <output> where: <file> is the name of a fil...
Python
0
b90b57adae8a5a32c3c914c880d8900bd008e9f3
Add fedjax/experimental/__init__.py
fedjax/experimental/__init__.py
fedjax/experimental/__init__.py
# Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Python
0.000008
7ada16150f5a77bf9578de40a2bd8390c0ddea7e
Add minimal Info cog
dog/ext/info.py
dog/ext/info.py
""" Information extension. """ import discord from discord.ext import commands from dog import Cog from dog.core import utils cm = lambda v: utils.commas(v) SERVER_INFO_MEMBERS = '''{} total member(s) {} online, {} offline {}% online''' SERVER_INFO_COUNT = '''{} role(s) {} text channel(s), {} voice channel(s) {} c...
Python
0.000001
9b0c3888912b6da4c4632da2623075c4eef9444d
Create fizzbuzz.py
fizzbuzz.py
fizzbuzz.py
# Python: fizzbuzz.py import sys for i in range(-50, 100): if i%3==0: sys.stdout.write('Fizz') if i%5==0: sys.stdout.write('Buzz') if (i%5<>0 and i%3<>0): print i, print
Python
0.000685
a466a89cd18252c6d90fd3b590148ca3268ff637
Add a couple of simple tests for LPD geometry
karabo_data/tests/test_lpd_geometry.py
karabo_data/tests/test_lpd_geometry.py
from matplotlib.figure import Figure import numpy as np from karabo_data.geometry2 import LPD_1MGeometry def test_inspect(): geom = LPD_1MGeometry.from_quad_positions([ (11.4, 299), (-11.5, 8), (254.5, -16), (278.5, 275) ]) # Smoketest fig = geom.inspect() assert is...
Python
0
de7fdc1d14db4cef3a01dd954d4e7107a168639a
Fix in_contest
judge/views/contests.py
judge/views/contests.py
from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from judge.comment...
from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render_to_response from django.template import RequestContext from judge.comment...
Python
0.000124
efac5a6167e2ac437072084f0e48147ccccab793
test read() on all examples
test/test_examples.py
test/test_examples.py
import icy import contextlib import os from datetime import datetime class DummyFile(object): def write(self): pass if __name__ == '__main__': print('running examples tests ...') t0 = datetime.now() results = [0, 0, 0, 0] for ex in sorted(icy.examples): t1 = datetime.now() try: ...
Python
0
796f000d3ba2fd2f289bb68ce817a81eb56dcb3d
Test for issue200
test/test_issue200.py
test/test_issue200.py
#!/usr/bin/env python import os, sys import rdflib import unittest try: from hashlib import md5 except ImportError: from md5 import md5 if sys.platform == 'Java': from nose import SkipTest raise SkipTest('No os.pipe() in Jython, skipping') # Adapted from http://icodesnip.com/snippet/python/simple-uni...
Python
0
defe99d80e102527140fb5742f4deedb6748f05e
add execute.
sc_spider/execute.py
sc_spider/execute.py
from scrapy.cmdline import execute execute()
Python
0.000001
80f35ad0d3a6a1f04eb0339bb1088ebe6eb27af5
Add result classes for update/insert/delete ops
mongomock/results.py
mongomock/results.py
try: from pymongo.results import InsertOneResult from pymongo.results import InsertManyResult from pymongo.results import UpdateResult from pymongo.results import DeleteResult except ImportError: class _WriteResult(object): def __init__(self, acknowledged=True): self.__acknowled...
Python
0
35b5ef2d39363e893796a8384209034093d8a11e
add import script for Burnley
polling_stations/apps/data_collection/management/commands/import_burnley.py
polling_stations/apps/data_collection/management/commands/import_burnley.py
from data_collection.management.commands import BaseXpressWebLookupCsvImporter class Command(BaseXpressWebLookupCsvImporter): council_id = 'E07000117' # note: extension is TSV, but file is actually comma seperated addresses_name = 'BurnleyPropertyPostCodePollingStationWebLookup-2017-03-10.TSV' st...
Python
0
6fce34ca55d4dfaee921480077b48e0984d8fe1c
Create max_of_three.py
09-revisao/practice_python/max_of_three.py
09-revisao/practice_python/max_of_three.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Exercise 28: Max Of Three Implement a function that takes as input three variables, and returns the largest of the three. Do this without using the Python max() function! The goal of this exercise is to think about some internals that Python normally takes care of for...
Python
0.000333
54940c2532d90e23b919031e948e4c7b608b1866
add import script for Wycombe
polling_stations/apps/data_collection/management/commands/import_wycombe.py
polling_stations/apps/data_collection/management/commands/import_wycombe.py
from django.contrib.gis.geos import Point from data_collection.management.commands import BaseCsvStationsShpDistrictsImporter from data_finder.helpers import geocode_point_only, PostcodeError class Command(BaseCsvStationsShpDistrictsImporter): srid = 27700 council_id = 'E07000007' districts_name = 'Polling...
Python
0
cd1ef40d7378078b9399a38aadfcce58fdac8677
Add Taxosaurus name resolution. Closes #8
pytaxize/taxo.py
pytaxize/taxo.py
import sys import requests import pandas as pd import json import time class NoResultException(Exception): pass def taxo_datasources(todf=True): ''' Get data sources for Taxosaurus. Retrieve data sources used in Global Names Index, see http://taxosaurus.org/ for information. Usage: #...
Python
0.000001
0c5c2dd033a4d586e24fc76a7f5398db52470ac6
Add python wrapper
python/camera.py
python/camera.py
""" A simple python wrapper around escapi Usage: from camera import Device device = Deveice.connect(0, 500, 500) image = device.get_image() """ import os from ctypes import * from PIL import Image def resolve(name): f = os.path.join(os.path.dirname(__file__), name) return f class CAPTURE_PROPETIES: C...
Python
0.000065
a877ba0845ea868a79d89965c419ec637bc85ff1
add python
python/python.py
python/python.py
from collections import namedtuple Point = namedtuple('Point',['x','y']) if __name__ == "__main__": main() import heapq heap = [] heapq.heapify(heap) heapq.heappush(heap,(1,2))
Python
0.998891
5ba42c79d777b8afad82a6dc120afc366643e9b8
Create test.py
test.py
test.py
import spacy nlp = spacy.load('en') doc5 = nlp(u"Timothy Spann is studying at Princeton University in New Jersey.") # Named Entity Recognizer (NER) for ent in doc5.ents: print ent, ent.label, ent.label_
Python
0.000005
e5f22aaf4de371df0b52a275dbebbd4cd6c1d980
add test file
test.py
test.py
import os import logging import redis import gevent from flask import Flask, render_template from flask_sockets import Sockets
Python
0.000001
50c3e9ffeacf7db5c002186e178ca24a6c14bf22
Add py-watchdog (#19167)
var/spack/repos/builtin/packages/py-watchdog/package.py
var/spack/repos/builtin/packages/py-watchdog/package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class PyWatchdog(PythonPackage): """Python library and shell utilities to monitor filesystem eve...
Python
0.000004
c151f843964408481a5f6569718537a786ff5722
range excluding script, still lacks some error checking
range-exclude.py
range-exclude.py
#! /usr/bin/env python3.4 import ipaddress import math supernet = False subnet = False while not supernet: inputRange = input('Input the IP range you would like remove a subrange from: ') try: supernet =ipaddress.ip_network(inputRange) except ValueError: print('Invalid input, try again') while not subnet: ...
Python
0
e639cea1f5264870e3f5f19fbd88345a23ef61a9
add timestamps to debug logging
lib/misc.py
lib/misc.py
import time import re import sys, os sentinel_options = [] def is_numeric(strin): import decimal # Decimal allows spaces in input, but we don't if strin.strip() != strin: return False try: value = decimal.Decimal(strin) except decimal.InvalidOperation as e: return False ...
import time import re import sys, os sentinel_options = [] def is_numeric(strin): import decimal # Decimal allows spaces in input, but we don't if strin.strip() != strin: return False try: value = decimal.Decimal(strin) except decimal.InvalidOperation as e: return False ...
Python
0.000002
9d44e4eb4c8d2c2f10152894f7c53d9feaae528c
Add ip-restriction plugin to declare ip whitelists/blacklists and restrict api access
api_bouncer/middlewares/ip_restriction.py
api_bouncer/middlewares/ip_restriction.py
import ipaddress from django.http import JsonResponse from ..models import Plugin def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip class...
Python
0
233459fbb39c8d5d13069a39ea85592e5b73a46b
Add unit tests
test.py
test.py
#!/usr/bin/env python """ Unit tests for the int module. """ import unittest import textwrap import int def parse(s): return int.parse_arg(s).strip() def prep(s): return textwrap.dedent(s).strip() class IntegerConversionTests(unittest.TestCase): def test_0(self): self.assertEqual( ...
Python
0.000001