commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
27c3972a57e09faf35f86b82b35eb815dadc4688 | mediachain/reader/dynamo.py | mediachain/reader/dynamo.py | import boto3
def get_table(name):
dynamo = boto3.resource('dynamo')
return dynamo.Table(name)
def get_object(reference):
table = get_table('mediachain')
obj = table.get_item(Key={'multihash': reference})
byte_string = obj['Item']['data']
if byte_string is None:
raise KeyError('Could n... | import boto3
import cbor
def get_table(name):
dynamo = boto3.resource('dynamodb',
endpoint_url='http://localhost:8000',
region_name='us-east-1',
aws_access_key_id='',
aws_secret_access_key='')
return... | Make get_object pull appropriate fields | Make get_object pull appropriate fields
Temporarily set up dynamo to work internally
| Python | mit | mediachain/mediachain-client,mediachain/mediachain-client |
3f764874dbb805d661d38719bb4e78b6a52f9f79 | parser/timestamp.py | parser/timestamp.py | from datetime import datetime
DT_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
def get_timestamp():
"""
Serialize actual datetime provided as simplified ISO 8601 (without timezone)
string
:type datetime: datetime
:param datetime: datetime object to convert to string
:return: serialized datetime
:rtype... | from datetime import datetime
DT_FORMAT = "%Y-%m-%dT%H:%M:%S.%f"
def get_timestamp():
"""
Serialize actual datetime provided as simplified ISO 8601 (without timezone)
string
:return: serialized datetime
:rtype: str
"""
return datetime.now().strftime(DT_FORMAT)
| Remove docs for non-existing function parameters | Remove docs for non-existing function parameters
| Python | mit | m4tx/techswarm-receiver |
9c36417af3364b77853b62d9a924d5693e44dce0 | fabfile.py | fabfile.py | # -*- coding: UTF-8 -*-
from fabric.api import *
#def dev()
#def prod()
#def setup_host()
def hello():
print("Hello world!")
def clean_db():
local("rm -rf database/fst_demo.db;python manage.py syncdb --noinput;python manage.py loaddata fs_doc/fixtures/exempeldata.json")
def test():
local("python ma... | # -*- coding: UTF-8 -*-
from fabric.api import *
def clean_db():
local("rm -rf database/fst_demo.db;python manage.py syncdb --noinput;python manage.py loaddata fs_doc/fixtures/exempeldata.json")
def test():
local("python manage.py test")
def clean_test():
clean_db()
test()
| Remove noob fab method :-) | Remove noob fab method :-)
| Python | bsd-3-clause | rinfo/fst,kamidev/autobuild_fst,kamidev/autobuild_fst,rinfo/fst,kamidev/autobuild_fst,rinfo/fst,kamidev/autobuild_fst,rinfo/fst |
c94598b8ce59b98213367b54164b1051d56a28da | scene.py | scene.py | import bpy
class Scene:
"""Scene object"""
def __init__(self, filepath, render_engine='CYCLES'):
self.filepath = filepath
self.render_engine = 'CYCLES'
def setup(self):
self._cleanup()
bpy.context.scene.render.filepath = self.filepath
bpy.context.scene.render.engi... | import bpy
class Scene:
"""Scene object"""
def __init__(self, filepath, render_engine='CYCLES'):
self.filepath = filepath
self.render_engine = 'CYCLES'
def setup(self):
self._cleanup()
bpy.context.scene.render.filepath = self.filepath
bpy.context.scene.render.engi... | Allow to set render samples | Allow to set render samples
| Python | mit | josuemontano/blender_wrapper |
de3f474502e781dacc0b182ee8d50d729468c576 | setup.py | setup.py | from distutils.core import setup
setup(
name = 'pycolors2',
py_modules = ['colors',],
version = '0.0.3',
author = 'Chris Gilmer',
author_email = 'chris.gilmer@gmail.com',
maintainer = 'Chris Gilmer',
maintainer_email = 'chris.gilmer@gmail.com',
url = 'http://github.com/chrisgilmerproj/... | from distutils.core import setup
setup(
name = 'pycolors2',
py_modules = ['colors',],
version = '0.0.3',
author = 'Chris Gilmer',
author_email = 'chris.gilmer@gmail.com',
maintainer = 'Chris Gilmer',
maintainer_email = 'chris.gilmer@gmail.com',
url = 'http://github.com/chrisgilmerproj/... | Add trove classifiers for language support | Add trove classifiers for language support
| Python | mit | chrisgilmerproj/pycolors2 |
d73ff1c66925613646495a22018e8c8a6ce139a7 | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup, Command
from distutils.extension import Extension
import os
import numpy as np
from Cython.Distutils import build_ext
os.environ['TEST_DATA_ROOT'] = os.path.abspath("tests/data")
class CramTest(Command):
user_options = [ ]
def initialize_options(self... | #!/usr/bin/env python
from distutils.core import setup, Command
from distutils.extension import Extension
import os
import numpy as np
from Cython.Distutils import build_ext
from unittest import TextTestRunner, TestLoader
os.environ['TEST_DATA_ROOT'] = os.path.abspath("tests/data")
class UnitTest(Command):
def... | Fix broken unit test command. | Fix broken unit test command.
| Python | mit | echlebek/15puzz,echlebek/15puzz |
df0efa079afbda84b1c09bc4895c84c0ec70861d | setup.py | setup.py | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | import importlib
from cx_Freeze import setup, Executable
backend_path = importlib.import_module("bcrypt").__path__[0]
backend_path = backend_path.replace("bcrypt", ".libs_cffi_backend")
# Dependencies are automatically detected, but it might need
# fine tuning.
build_exe_options = {
"include_files": [
("... | Add SSL to cx-freeze packages | Add SSL to cx-freeze packages
| Python | mit | igboyes/virtool,virtool/virtool,igboyes/virtool,virtool/virtool |
720bd5b2f3c422af6bd1c70850fb2f67a773def0 | slack.py | slack.py | #!/usr/bin/env python
import requests
import calendar
from datetime import datetime, timedelta
from settings import _token, _domain, _user, _time, _pretty
if __name__ == '__main__':
while 1:
files_list_url = 'https://slack.com/api/files.list'
date = str(calendar.timegm((datetime.now() + timedelta... | #!/usr/bin/env python
import requests
import calendar
from datetime import datetime, timedelta
from settings import _token, _domain, _user, _time, _pretty
def delete_my_files():
while 1:
files_list_url = 'https://slack.com/api/files.list'
date = str(calendar.timegm((datetime.now() + timedelta(-_t... | Move the main items into a function | Move the main items into a function
| Python | mit | marshallhumble/slack_app,marshallhumble/slack_app |
16516b1ec44e3e44d2dc96a6f3d021268ce4e71d | osgtest/tests/test_84_xrootd.py | osgtest/tests/test_84_xrootd.py | import os
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
import unittest
class TestStopXrootd(osgunittest.OSGTestCase):
def test_01_stop_xrootd(self):
if (core.config['xrootd.gsi'] == "ON") and (core.state['xrootd.backups-exist']... | import os
import osgtest.library.core as core
import osgtest.library.files as files
import osgtest.library.osgunittest as osgunittest
import unittest
class TestStopXrootd(osgunittest.OSGTestCase):
def test_01_stop_xrootd(self):
if (core.config['xrootd.gsi'] == "ON") and (core.state['xrootd.backups-exist']... | Fix test if server started in xrootd cleanup code | Fix test if server started in xrootd cleanup code
git-svn-id: 884a03e47e2adb735d896e55bb5ad6bc3421ba19@17920 4e558342-562e-0410-864c-e07659590f8c
| Python | apache-2.0 | efajardo/osg-test,efajardo/osg-test |
75b02b3cafcc34dca143de9143f14c3c7c29c97c | transmutagen/tests/test_coefficients.py | transmutagen/tests/test_coefficients.py | import pytest
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
TOTAL_DEGREES = 30
from .crv_coeffs import coeffs as correct_coeffs
from ..cram import get_CRAM_from_cache, CRAM_coeffs
# @slow
@pytest.mark.parametrize('degree', range(1, TOTAL_DEGREES... | import decimal
import pytest
from sympy import re
slow = pytest.mark.skipif(
not pytest.config.getoption("--runslow"),
reason="need --runslow option to run"
)
TOTAL_DEGREES = 30
from .crv_coeffs import coeffs as correct_coeffs
from .partfrac_coeffs import part_frac_coeffs
from ..cram import get_CRAM_from_ca... | Add test against Pusa coefficients (skipped for now, as they don't pass) | Add test against Pusa coefficients (skipped for now, as they don't pass)
| Python | bsd-3-clause | ergs/transmutagen,ergs/transmutagen |
f468a26893c44411dc1f865b208788373f993918 | asciibooth/camera.py | asciibooth/camera.py | import io
# import time
import picamera
from . import config
class Camera:
def __init__(self):
self.camera = picamera.PiCamera(resolution=config.CAPTURE_RESOLUTION)
self.preview_alpha = 200
def capture(self):
stream = io.BytesIO()
self.camera.capture(stream, 'rgb', resize=confi... | import io
# import time
import picamera
from . import config
class Camera:
def __init__(self):
self.camera = picamera.PiCamera(resolution=config.CAPTURE_RESOLUTION)
self.camera.hflip = True
self.preview_alpha = 200
def capture(self):
stream = io.BytesIO()
self.camera.ca... | Enable hflip for capture and preview | Enable hflip for capture and preview
| Python | cc0-1.0 | jnv/asciibooth,jnv/asciibooth |
6f213f17fab236e1222f4e691015dfd867073ae2 | dbaas/workflow/steps/build_database.py | dbaas/workflow/steps/build_database.py | # -*- coding: utf-8 -*-
import logging
from base import BaseStep
from logical.models import Database
LOG = logging.getLogger(__name__)
class BuildDatabase(BaseStep):
def __unicode__(self):
return "Creating logical database..."
def do(self, workflow_dict):
try:
if not workflow_... | # -*- coding: utf-8 -*-
import logging
from base import BaseStep
from logical.models import Database
LOG = logging.getLogger(__name__)
class BuildDatabase(BaseStep):
def __unicode__(self):
return "Creating logical database..."
def do(self, workflow_dict):
try:
if not workflow_... | Check if there is an project key on workflow_dict | Check if there is an project key on workflow_dict
| Python | bsd-3-clause | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service |
84f9c189f62c6ab81de952cb9a7e9942237465ec | tasks.py | tasks.py | from invoke import task, Collection
from invocations.packaging import release
# TODO: once this stuff is stable and I start switching my other projects to be
# pytest-oriented, move this into invocations somehow.
@task
def test(c):
"""
Run verbose pytests.
"""
c.run("pytest --verbose --color=yes")
@t... | from invoke import task, Collection
from invocations.packaging import release
from invocations import pytest as pytests
@task
def coverage(c, html=True):
"""
Run coverage with coverage.py.
"""
# NOTE: this MUST use coverage itself, and not pytest-cov, because the
# latter is apparently unable to p... | Use new invocations pytest helper | Use new invocations pytest helper
| Python | bsd-2-clause | bitprophet/pytest-relaxed |
87ea6fbc07c547a0c92f0b85811edc0645cb4303 | pysyte/oss/linux.py | pysyte/oss/linux.py | """Linux-specific code"""
import os
from pysyte.types import paths
def xdg_home():
"""path to $XDG_CONFIG_HOME
>>> assert xdg_home() == os.path.expanduser('~/.config')
"""
return paths.environ_path('XDG_CONFIG_HOME', '~/.config')
def xdg_home_config(filename):
"""path to that file in $XDG_CON... | """Linux-specific code"""
from pysyte.types import paths
def xdg_home():
"""path to $XDG_CONFIG_HOME
>>> assert xdg_home() == paths.path('~/.config').expand()
"""
return paths.environ_path('XDG_CONFIG_HOME', '~/.config')
def xdg_home_config(filename):
"""path to that file in $XDG_CONFIG_HOME
... | Remove unused import of "os" | Remove unused import of "os"
| Python | mit | jalanb/dotsite |
b12418acf3883024be965f42ec8d3a16e76d384f | special/special_relativity.py | special/special_relativity.py | # -*- coding: utf-8 -*-
from __future__ import division
import math
class LorentzFactor(object):
SPEED_OF_LIGHT = 299792458
@staticmethod
def get_beta(velocity, is_percent):
if is_percent:
return velocity
return velocity / SPEED_OF_LIGHT
@staticmethod
... | # -*- coding: utf-8 -*-
from __future__ import division
import math
class LorentzFactor(object):
SPEED_OF_LIGHT = 299792458
@staticmethod
def get_beta(velocity, is_percent):
if is_percent:
return velocity
return velocity / SPEED_OF_LIGHT
@staticmethod
... | Fix error in calculation on lorentz factor | Fix error in calculation on lorentz factor
| Python | mit | tdsymonds/relativity |
eb31775a7dbbb2064cf64d85c2bb0912a92f4028 | train.py | train.py | import data
import argparse
from model import EDSR
parser = argparse.ArgumentParser()
parser.add_argument("--dataset",default="data/General-100")
parser.add_argument("--imgsize",default=100,type=int)
parser.add_argument("--scale",default=2,type=int)
parser.add_argument("--layers",default=32,type=int)
parser.add_argumen... | import data
import argparse
from model import EDSR
parser = argparse.ArgumentParser()
parser.add_argument("--dataset",default="data/General-100")
parser.add_argument("--imgsize",default=100,type=int)
parser.add_argument("--scale",default=2,type=int)
parser.add_argument("--layers",default=32,type=int)
parser.add_argumen... | Add warning for mismatched image size and scale | Add warning for mismatched image size and scale | Python | mit | jmiller656/EDSR-Tensorflow |
d604d17e8286b1c95a0faafd6d4fd79af11441ab | nn/util.py | nn/util.py | import functools
import numpy
import tensorflow as tf
def static_shape(tensor):
return tf.convert_to_tensor(tensor).get_shape().as_list()
def static_rank(tensor):
return len(static_shape(tf.convert_to_tensor(tensor)))
def funcname_scope(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with... | import functools
import numpy
import tensorflow as tf
def static_shape(tensor):
return tf.convert_to_tensor(tensor).get_shape().as_list()
def static_rank(tensor):
return len(static_shape(tf.convert_to_tensor(tensor)))
def funcname_scope(func_or_name):
if isinstance(func_or_name, str):
def wrapper(func)... | Extend funcname_scope so that it accepts funcnames | Extend funcname_scope so that it accepts funcnames
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten |
f3e3b43abebfad0fcaa20df8eac20e3cb8c099d6 | imgproc.py | imgproc.py | from SimpleCV import *
import numpy
import cv2
def process_image(obj, img, config):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:return: Mask with candidates surrounded in a green rectangle
"""
hsv_image = img.toHSV()
segmented = Image(cv2.inRa... | from SimpleCV import *
import numpy
import cv2
def process_image(obj, img, config, each_blob=None):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:param each_blob: function, taking a SimpleCV.Blob as an argument, that is called for every candidate blob
:... | Allow a function to be called whenever a candidate blob is found during image processing | Allow a function to be called whenever a candidate blob is found during
image
processing
| Python | mit | mstojcevich/Flash-Vision |
0eb7e6b9a8e4e38793b1e045ab5f0f0a4d4e6777 | synapse/metrics/resource.py | synapse/metrics/resource.py | # -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
#
# 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 la... | # -*- coding: utf-8 -*-
# Copyright 2015 OpenMarket Ltd
#
# 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 la... | Delete unused import of NOT_READY_YET | Delete unused import of NOT_READY_YET
| Python | apache-2.0 | matrix-org/synapse,illicitonion/synapse,iot-factory/synapse,TribeMedia/synapse,iot-factory/synapse,howethomas/synapse,matrix-org/synapse,matrix-org/synapse,matrix-org/synapse,rzr/synapse,howethomas/synapse,illicitonion/synapse,rzr/synapse,howethomas/synapse,illicitonion/synapse,matrix-org/synapse,howethomas/synapse,Tri... |
8ef5b15c62960fb9abc43c9b30550faa0c0d7227 | cactusbot/handler.py | cactusbot/handler.py | """Handle handlers."""
import logging
class Handlers(object):
"""Handlers."""
def __init__(self, *handlers):
self.logger = logging.getLogger(__name__)
self.handlers = handlers
def handle(self, event, packet):
"""Handle incoming data."""
for handler in self.handlers:
... | """Handle handlers."""
import logging
from .packet import Packet
class Handlers(object):
"""Handlers."""
def __init__(self, *handlers):
self.logger = logging.getLogger(__name__)
self.handlers = handlers
def handle(self, event, packet):
"""Handle incoming data."""
for ... | Add support for multiple return `Packet`s from `Handler`s | Add support for multiple return `Packet`s from `Handler`s
| Python | mit | CactusDev/CactusBot |
51cdd71cbcbcfd80105cc5ccb5b95f4d79dc593e | src/service_deployment_tools/paasta_cli/utils/cmd_utils.py | src/service_deployment_tools/paasta_cli/utils/cmd_utils.py | #!/usr/bin/env python
"""
Contains helper functions common to all paasta commands or the client
"""
import glob
import os
# List of commands the paasta client can execute
CMDS = None
def paasta_commands():
"""
Read the files names in the cmds directory to determine the various commands
the paasta clien... | #!/usr/bin/env python
"""
Contains helper functions common to all paasta commands or the client
"""
import glob
import os
def paasta_commands():
"""
Read the files names in the cmds directory to determine the various commands
the paasta client is able to execute
:return: a list of string such as ['l... | Clean up directory parsing code | Clean up directory parsing code
| Python | apache-2.0 | gstarnberger/paasta,Yelp/paasta,somic/paasta,Yelp/paasta,gstarnberger/paasta,somic/paasta |
b81ace397887cb6d0fc7db21d623667223adbfbf | python/frequency_queries.py | python/frequency_queries.py | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the freqQuery function below.
def freqQuery(queries):
output = []
occurences = Counter()
frequencies = Counter()
for operation, value in queries:
if (operation == 1):
frequencies[occur... | #!/bin/python3
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the freqQuery function below.
def freqQuery(queries):
output = []
array = []
occurences = Counter()
frequencies = Counter()
for operation, value in queries:
if (operation == 1):
freq... | Fix bug with negative counts | Fix bug with negative counts
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
fdc0bb75271b90a31072f79b95283e1156d50181 | waffle/decorators.py | waffle/decorators.py | from functools import wraps
from django.http import Http404
from django.utils.decorators import available_attrs
from waffle import is_active
def waffle(flag_name):
def decorator(view):
if flag_name.startswith('!'):
active = is_active(request, flag_name[1:])
else:
active =... | from functools import wraps
from django.http import Http404
from django.utils.decorators import available_attrs
from waffle import is_active
def waffle(flag_name):
def decorator(view):
@wraps(view, assigned=available_attrs(view))
def _wrapped_view(request, *args, **kwargs):
if flag_n... | Make the decorator actually work again. | Make the decorator actually work again.
| Python | bsd-3-clause | isotoma/django-waffle,TwigWorld/django-waffle,rlr/django-waffle,webus/django-waffle,groovecoder/django-waffle,JeLoueMonCampingCar/django-waffle,crccheck/django-waffle,safarijv/django-waffle,paulcwatts/django-waffle,JeLoueMonCampingCar/django-waffle,11craft/django-waffle,festicket/django-waffle,styleseat/django-waffle,m... |
6c578b67753e7a3fd646e5d91259b50c0b39bec6 | tests/test_add_target.py | tests/test_add_target.py | """
Tests for helper function for adding a target to a Vuforia database.
"""
import io
from vws import VWS
class TestSuccess:
"""
Tests for successfully adding a target.
"""
def test_add_target(
self,
client: VWS,
high_quality_image: io.BytesIO,
) -> None:
"""
... | """
Tests for helper function for adding a target to a Vuforia database.
"""
import io
from mock_vws import MockVWS
from vws import VWS
class TestSuccess:
"""
Tests for successfully adding a target.
"""
def test_add_target(
self,
client: VWS,
high_quality_image: io.BytesIO,... | Add test for custom base URL | Add test for custom base URL
| Python | mit | adamtheturtle/vws-python,adamtheturtle/vws-python |
b6711f27146279ee419143b560cf32d3b3dfc80c | tools/conan/conanfile.py | tools/conan/conanfile.py | from conans import ConanFile, CMake, tools
class VarconfConan(ConanFile):
name = "varconf"
version = "1.0.3"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/varconf"
description = "Configuration li... | from conans import ConanFile, CMake, tools
class VarconfConan(ConanFile):
name = "varconf"
version = "1.0.3"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/varconf"
description = "Configuration li... | Include binaries when importing (for Windows). | Include binaries when importing (for Windows).
| Python | lgpl-2.1 | worldforge/varconf,worldforge/varconf,worldforge/varconf,worldforge/varconf |
4307fa24a27a2c623836a7518e3aceb4546abcf6 | scholrroles/behaviour.py | scholrroles/behaviour.py | from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, ob... | from collections import defaultdict
from .utils import get_value_from_accessor
class RoleBehaviour(object):
ids = []
object_accessors = {}
def __init__(self, user, request):
self.user = user
self.request = request
def has_role(self):
return False
def has_role_for(self, ob... | Validate Model function to allow permission | Validate Model function to allow permission
| Python | bsd-3-clause | Scholr/scholr-roles |
bdd842f55f3a234fefee4cd2a701fa23e07c3789 | scikits/umfpack/setup.py | scikits/umfpack/setup.py | #!/usr/bin/env python
# 05.12.2005, c
from __future__ import division, print_function, absolute_import
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, dict_append
config = Configuration('umfpack', par... | #!/usr/bin/env python
# 05.12.2005, c
from __future__ import division, print_function, absolute_import
import sys
def configuration(parent_package='',top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, dict_append
config = Configuration('um... | Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies. | Add handling for building scikit-umfpack on the Mac, which doesn't have the librt file added to the umfpack dependencies.
| Python | bsd-3-clause | scikit-umfpack/scikit-umfpack,scikit-umfpack/scikit-umfpack,rc/scikit-umfpack-rc,rc/scikit-umfpack,rc/scikit-umfpack,rc/scikit-umfpack-rc |
6c4a2d6f80d7ee5f9c06c3d678bb86661c94a793 | tools/np_suppressions.py | tools/np_suppressions.py | suppressions = [
[ ".*/multiarray/mapping\.", "PyArray_MapIterReset" ],
# PyArray_Std trivially forwards to and appears to be superceded by
# __New_PyArray_Std, which is exercised by the test framework.
[ ".*/multiarray/calculation\.", "PyArray_Std" ],
# PyCapsule_Check is declared in a header, an... | suppressions = [
# This one cannot be covered by any Python language test because there is
# no code pathway to it. But it is part of the C API, so must not be
# excised from the code.
[ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ],
# PyArray_Std trivially forwards to and appears to be sup... | Add documentation on one assertion, convert RE's to raw strings. | Add documentation on one assertion, convert RE's to raw strings.
| Python | bsd-3-clause | numpy/numpy-refactor,numpy/numpy-refactor,numpy/numpy-refactor,numpy/numpy-refactor,numpy/numpy-refactor |
dcba8b90b84506a7325f8e576d10ccb8d2e9a415 | setuptools/py24compat.py | setuptools/py24compat.py | """
Forward-compatibility support for Python 2.4 and earlier
"""
# from jaraco.compat 1.2
try:
from functools import wraps
except ImportError:
def wraps(func):
"Just return the function unwrapped"
return lambda x: x
| """
Forward-compatibility support for Python 2.4 and earlier
"""
# from jaraco.compat 1.2
try:
from functools import wraps
except ImportError:
def wraps(func):
"Just return the function unwrapped"
return lambda x: x
try:
import hashlib
except ImportError:
from setuptools._backport imp... | Add a shim for python 2.4 compatability with hashlib | Add a shim for python 2.4 compatability with hashlib
--HG--
extra : rebase_source : 5f573e600aadbe9c95561ee28c05cee02c7db559
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
03977d24d5862373a881b7098bc78adc30fe8256 | make_src_bem.py | make_src_bem.py | from __future__ import print_function
import mne
from my_settings import *
subject = sys.argv[1]
# make source space
src = mne.setup_source_space(subject, spacing='oct6',
subjects_dir=subjects_dir,
add_dist=False, overwrite=True)
# save source space
mne.writ... | from __future__ import print_function
import mne
import subprocess
from my_settings import *
subject = sys.argv[1]
cmd = "/usr/local/common/meeg-cfin/configurations/bin/submit_to_isis"
# make source space
src = mne.setup_source_space(subject, spacing='oct6',
subjects_dir=subjects_dir,
... | Change to make BEM solution from mne-C | Change to make BEM solution from mne-C
| Python | bsd-3-clause | MadsJensen/RP_scripts,MadsJensen/RP_scripts,MadsJensen/RP_scripts |
27c614b30eda339ca0c61f35e498be6456f2280f | scoring/__init__.py | scoring/__init__.py | import numpy as np
from sklearn.cross_validation import cross_val_score
from sklearn.externals import joblib as pickle
class scorer(object):
def __init__(self, model, descriptor_generator, model_opts = {}, desc_opts = {}):
self.model = model()
self.descriptor_generator = descriptor_generator(**desc... | import numpy as np
from sklearn.cross_validation import cross_val_score
from sklearn.externals import joblib as pickle
class scorer(object):
def __init__(self, model_instance, descriptor_generator_instance):
self.model = model_instance
self.descriptor_generator = descriptor_generator_instance
... | Make scorer accept instances of model and desc. gen. | Make scorer accept instances of model and desc. gen.
| Python | bsd-3-clause | mwojcikowski/opendrugdiscovery |
b5477239d7b1ee9e73265b023355e8e83826ec49 | scrapy_rss/items.py | scrapy_rss/items.py | # -*- coding: utf-8 -*-
import scrapy
from scrapy.item import BaseItem
from scrapy_rss.elements import *
from scrapy_rss import meta
import six
@six.add_metaclass(meta.ItemMeta)
class RssItem:
title = TitleElement()
link = LinkElement()
description = DescriptionElement()
author = AuthorElement()
... | # -*- coding: utf-8 -*-
import scrapy
from scrapy.item import BaseItem
from scrapy_rss.elements import *
from scrapy_rss import meta
import six
@six.add_metaclass(meta.ItemMeta)
class RssItem(BaseItem):
title = TitleElement()
link = LinkElement()
description = DescriptionElement()
author = AuthorElem... | Fix RssItem when each scraped item is instance of RssItem | Fix RssItem when each scraped item is instance of RssItem
| Python | bsd-3-clause | woxcab/scrapy_rss |
ee69971832120f4492e8f41abfbcb9c87e398d6a | DeepFried2/utils.py | DeepFried2/utils.py | import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param ... | import theano as _th
import numpy as _np
def create_param(shape, init, fan=None, name=None, type=_th.config.floatX):
return _th.shared(init(shape, fan).astype(type), name=name)
def create_param_and_grad(shape, init, fan=None, name=None, type=_th.config.floatX):
val = init(shape, fan).astype(type)
param ... | Add utility to save/load parameters, i.e. models. | Add utility to save/load parameters, i.e. models.
Also adds a utility to compute the number of parameters, because that's
always interesting and often reported in papers.
| Python | mit | yobibyte/DeepFried2,lucasb-eyer/DeepFried2,elPistolero/DeepFried2,Pandoro/DeepFried2 |
9e7e61256eb2ca2b4f4f19ce5b926709a593a28b | vispy/app/tests/test_interactive.py | vispy/app/tests/test_interactive.py | from nose.tools import assert_equal, assert_true, assert_false, assert_raises
from vispy.testing import assert_in, run_tests_if_main
from vispy.app import set_interactive
from vispy.ext.ipy_inputhook import inputhook_manager
# Expect the inputhook_manager to set boolean `_in_event_loop`
# on instances of this class ... | from nose.tools import assert_equal, assert_true, assert_false
from vispy.testing import assert_in, run_tests_if_main
from vispy.app import set_interactive
from vispy.ext.ipy_inputhook import inputhook_manager
# Expect the inputhook_manager to set boolean `_in_event_loop`
# on instances of this class when enabled.
c... | Fix for flake8 checks on new test file. | Fix for flake8 checks on new test file.
| Python | bsd-3-clause | jay3sh/vispy,ghisvail/vispy,hronoses/vispy,kkuunnddaannkk/vispy,michaelaye/vispy,dchilds7/Deysha-Star-Formation,sh4wn/vispy,QuLogic/vispy,srinathv/vispy,sh4wn/vispy,QuLogic/vispy,julienr/vispy,kkuunnddaannkk/vispy,drufat/vispy,Eric89GXL/vispy,jay3sh/vispy,jdreaver/vispy,RebeccaWPerry/vispy,RebeccaWPerry/vispy,jay3sh/vi... |
efc0f438e894fa21ce32665ec26c19751ec2ce10 | ureport_project/wsgi_app.py | ureport_project/wsgi_app.py | # wsgi_app.py
import sys, os
filedir = os.path.dirname(__file__)
sys.path.append(os.path.join(filedir))
#print sys.path
os.environ["CELERY_LOADER"] = "django"
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import sys
print sys.path
from django.core.handlers.wsgi import WSGIHandler
application = WSGIHandler()
| # wsgi_app.py
import sys, os
filedir = os.path.dirname(__file__)
sys.path.append(os.path.join(filedir))
#print sys.path
os.environ["CELERY_LOADER"] = "django"
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
import sys
print sys.path
from django.core.handlers.wsgi import WSGIHandler
from linesman.middleware import... | Apply linesman profiler to the wsgi app | Apply linesman profiler to the wsgi app
I fully expect this commit to be backed out when we get the profiling
stuff sorted out, but thankfully, this profiler can be disabled for a
live site.
check out http://<site>/__profiler__ after installing linesman, and
running the uwsgi server
| Python | bsd-3-clause | unicefuganda/ureport,unicefuganda/ureport,unicefuganda/ureport,mbanje/ureport_uganda,mbanje/ureport_uganda |
5ba9888d267d663fb0ab0dfbfd9346dc20f4c0c1 | test/test_turtle_serialize.py | test/test_turtle_serialize.py | import rdflib
from rdflib.py3compat import b
def testTurtleFinalDot():
"""
https://github.com/RDFLib/rdflib/issues/282
"""
g = rdflib.Graph()
u = rdflib.URIRef("http://ex.org/bob.")
g.bind("ns", "http://ex.org/")
g.add( (u, u, u) )
s=g.serialize(format='turtle')
assert b("ns:bob."... | from rdflib import Graph, URIRef, BNode, RDF, Literal
from rdflib.collection import Collection
from rdflib.py3compat import b
def testTurtleFinalDot():
"""
https://github.com/RDFLib/rdflib/issues/282
"""
g = Graph()
u = URIRef("http://ex.org/bob.")
g.bind("ns", "http://ex.org/")
g.add( (... | Test boolean list serialization in Turtle | Test boolean list serialization in Turtle
| Python | bsd-3-clause | RDFLib/rdflib,ssssam/rdflib,armandobs14/rdflib,yingerj/rdflib,RDFLib/rdflib,ssssam/rdflib,ssssam/rdflib,avorio/rdflib,marma/rdflib,marma/rdflib,RDFLib/rdflib,ssssam/rdflib,dbs/rdflib,armandobs14/rdflib,dbs/rdflib,dbs/rdflib,marma/rdflib,avorio/rdflib,marma/rdflib,yingerj/rdflib,RDFLib/rdflib,yingerj/rdflib,dbs/rdflib,a... |
8126ca21bcf8da551906eff348c92cb71fe79e6e | readthedocs/doc_builder/base.py | readthedocs/doc_builder/base.py | import os
def restoring_chdir(fn):
def decorator(*args, **kw):
try:
path = os.getcwd()
return fn(*args, **kw)
finally:
os.chdir(path)
return decorator
class BaseBuilder(object):
"""
The Base for all Builders. Defines the API for subclasses.
"""... | import os
from functools import wraps
def restoring_chdir(fn):
@wraps(fn)
def decorator(*args, **kw):
try:
path = os.getcwd()
return fn(*args, **kw)
finally:
os.chdir(path)
return decorator
class BaseBuilder(object):
"""
The Base for all Builder... | Call wraps on the restoring_chdir decorator. | Call wraps on the restoring_chdir decorator. | Python | mit | alex/readthedocs.org,safwanrahman/readthedocs.org,royalwang/readthedocs.org,VishvajitP/readthedocs.org,safwanrahman/readthedocs.org,alex/readthedocs.org,tddv/readthedocs.org,dirn/readthedocs.org,takluyver/readthedocs.org,nikolas/readthedocs.org,LukasBoersma/readthedocs.org,mhils/readthedocs.org,royalwang/readthedocs.or... |
76bf8966a25932822fca1c94586fccfa096ee02b | tests/misc/test_base_model.py | tests/misc/test_base_model.py | # -*- coding: UTF-8 -*-
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_repr(self):
self.generate_fixture_project_status()
self.generate_fixture_project()
self.assertEqual(str(self.project), "<Project Cosmos Landromat>")
self.project.name = u"... | # -*- coding: UTF-8 -*-
from tests.base import ApiDBTestCase
class BaseModelTestCase(ApiDBTestCase):
def test_repr(self):
self.generate_fixture_project_status()
self.generate_fixture_project()
self.assertEqual(str(self.project), "<Project %s>" % self.project.id)
def test_query(self):... | Change base model string representation | Change base model string representation
| Python | agpl-3.0 | cgwire/zou |
c908edadadb866292a612103d2854bef4673efab | shinken/__init__.py | shinken/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can r... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009-2012:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can r... | Remove superfluous import of shinken.objects in shinken/_init__.py. | Remove superfluous import of shinken.objects in shinken/_init__.py.
Every script or test-case importing shinken has all the objects loaded,
even if they are not required by the script or test-case at all.
Also see <http://sourceforge.net/mailarchive/message.php?msg_id=29553474>.
| Python | agpl-3.0 | naparuba/shinken,claneys/shinken,naparuba/shinken,tal-nino/shinken,mohierf/shinken,titilambert/alignak,lets-software/shinken,KerkhoffTechnologies/shinken,Simage/shinken,mohierf/shinken,gst/alignak,lets-software/shinken,Aimage/shinken,Aimage/shinken,geektophe/shinken,Aimage/shinken,staute/shinken_package,savoirfairelinu... |
85f759a9446cf988cc859d3b74d11e6b224bbd16 | request/managers.py | request/managers.py | from datetime import timedelta, datetime
from django.db import models
from django.contrib.auth.models import User
class RequestManager(models.Manager):
def active_users(self, **options):
"""
Returns a list of active users.
Any arguments passed to this method will be
given t... | from datetime import timedelta, datetime
from django.db import models
from django.contrib.auth.models import User
class RequestManager(models.Manager):
def active_users(self, **options):
"""
Returns a list of active users.
Any arguments passed to this method will be
given t... | Use a list comprehension and set() to make the active_users query simpler and faster. | Use a list comprehension and set() to make the active_users query simpler and faster.
| Python | bsd-2-clause | kylef/django-request,gnublade/django-request,Derecho/django-request,kylef/django-request,gnublade/django-request,gnublade/django-request,kylef/django-request |
11583cfca501164c5c08af70f66d430cd180dbc5 | examples/basic_nest/make_nest.py | examples/basic_nest/make_nest.py | #!/usr/bin/env python
import collections
import os
import os.path
import sys
from nestly import nestly
wd = os.getcwd()
input_dir = os.path.join(wd, 'inputs')
ctl = collections.OrderedDict()
ctl['strategy'] = nestly.repeat_iterable(('exhaustive', 'approximate'))
ctl['run_count'] = nestly.repeat_iterable([10**(i + 1... | #!/usr/bin/env python
import glob
import os
import os.path
from nestly import Nest
wd = os.getcwd()
input_dir = os.path.join(wd, 'inputs')
nest = Nest()
nest.add_level('strategy', ('exhaustive', 'approximate'))
nest.add_level('run_count', [10**i for i in xrange(3)])
nest.add_level('input_file', glob.glob(os.path.joi... | Update basic_nest for new API | Update basic_nest for new API
| Python | mit | fhcrc/nestly |
978b41a29eda295974ed5cf1a7cd5b79b148f479 | coverage/execfile.py | coverage/execfile.py | """Execute files of Python code."""
import imp, os, sys
def run_python_file(filename, args):
"""Run a python source file as if it were the main program on the python
command line.
`filename` is the path to the file to execute, must be a .py file.
`args` is the argument array to present as sys.arg... | """Execute files of Python code."""
import imp, os, sys
def run_python_file(filename, args):
"""Run a python source file as if it were the main program on the python
command line.
`filename` is the path to the file to execute, must be a .py file.
`args` is the argument array to present as sys.arg... | Move the open outside the try, since the finally is only needed once the file is successfully opened. | Move the open outside the try, since the finally is only needed once the file is successfully opened.
| Python | apache-2.0 | 7WebPages/coveragepy,blueyed/coveragepy,blueyed/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,hugovk/coveragepy,larsbutler/coveragepy,jayhetee/coveragepy,jayhetee/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,hugovk/coveragepy,larsbutler/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,7WebPages/coveragepy,ne... |
84d3738d2eb8a24dcb66cb329994f88bd55128c0 | tests/test_utils.py | tests/test_utils.py |
import pytest
def test_scrub_doi():
from vdm.utils import scrub_doi
d = 'http://dx.doi.org/10.1234'
scrubbed = scrub_doi(d)
assert(scrubbed == '10.1234')
d = '10.123 4'
assert(
scrub_doi(d) == '10.1234'
)
d = '<p>10.1234</p>'
assert(
scrub_doi(d) == '10.1234'
... |
import pytest
def test_scrub_doi():
from vdm.utils import scrub_doi
d = 'http://dx.doi.org/10.1234'
scrubbed = scrub_doi(d)
assert(scrubbed == '10.1234')
d = '10.123 4'
assert(
scrub_doi(d) == '10.1234'
)
d = '<p>10.1234</p>'
assert(
scrub_doi(d) == '10.1234'
... | Add utils tests. Rework pull. | Add utils tests. Rework pull.
| Python | mit | Brown-University-Library/vivo-data-management,Brown-University-Library/vivo-data-management |
c34840a7ac20d22e650be09a515cee9dbfcf6043 | tests/test_views.py | tests/test_views.py | from django.http import HttpResponse
from djproxy.views import HttpProxy
DOWNSTREAM_INJECTION = lambda x: x
class LocalProxy(HttpProxy):
base_url = "http://sitebuilder.qa.yola.net/en/ide/Yola/Yola.session.jsp"
class SBProxy(HttpProxy):
base_url = "http://sitebuilder.qa.yola.net/en/APIController"
def ind... | from django.http import HttpResponse
from djproxy.views import HttpProxy
class LocalProxy(HttpProxy):
base_url = "http://localhost:8000/some/content/"
def index(request):
return HttpResponse('Some content!', status=200)
class BadTestProxy(HttpProxy):
pass
class GoodTestProxy(HttpProxy):
base_ur... | Remove accidentally committed test code | Remove accidentally committed test code
| Python | mit | thomasw/djproxy |
ab418734f432691ec4a927be32364ee85baab35c | __init__.py | __init__.py | import inspect
import python2.httplib2 as httplib2
globals().update(inspect.getmembers(httplib2))
| import inspect
import sys
if sys.version_info[0] == 2:
from .python2 import httplib2
else:
from .python3 import httplib2
globals().update(inspect.getmembers(httplib2))
| Use python version dependent import | Use python version dependent import
Change-Id: Iae6bc0cc8d526162b91d0c18cf1fba1461aa9f98
| Python | mit | wikimedia/pywikibot-externals-httplib2,wikimedia/pywikibot-externals-httplib2,jayvdb/httplib2,jayvdb/httplib2 |
9ab7efa44a8e7267b2902b6e23ff61381d31692c | profile_collection/startup/85-robot.py | profile_collection/startup/85-robot.py | from ophyd import Device, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
class Robot(Device):
robot_sample_number = C(EpicsSignal, 'ID:Tgt-SP')
robot_load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC')
robot_unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC')
robot_execute_cmd = C(EpicsSignal, ... | from ophyd import Device, EpicsSignal, EpicsSignalRO
from ophyd import Component as C
from ophyd.utils import set_and_wait
class Robot(Device):
sample_number = C(EpicsSignal, 'ID:Tgt-SP')
load_cmd = C(EpicsSignal, 'Cmd:Load-Cmd.PROC')
unload_cmd = C(EpicsSignal, 'Cmd:Unload-Cmd.PROC')
execute_cmd = C(E... | Add sample loading logic to Robot. | WIP: Add sample loading logic to Robot.
| Python | bsd-2-clause | NSLS-II-XPD/ipython_ophyd,NSLS-II-XPD/ipython_ophyd |
2c6f5cfb2e90e815d74dca11c395e25875d475be | corehq/ex-submodules/phonelog/tasks.py | corehq/ex-submodules/phonelog/tasks.py | from datetime import datetime, timedelta
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from phonelog.models import DeviceReportEntry, UserErrorEntry, ForceCloseEntry, UserEntry
@periodic_task(run_every=crontab(minute=0, hour=0), queue=getattr(settings, 'CE... | from datetime import datetime, timedelta
from celery.schedules import crontab
from celery.task import periodic_task
from django.conf import settings
from django.db import connection
from phonelog.models import UserErrorEntry, ForceCloseEntry, UserEntry
@periodic_task(run_every=crontab(minute=0, hour=0), queue=getattr... | Drop table for device report logs. | Drop table for device report logs.
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
5025bff2ca9a4f31a371ecbd9255b1fb92b9cc4d | kafka_influxdb/encoder/echo_encoder.py | kafka_influxdb/encoder/echo_encoder.py | class Encoder(object):
@staticmethod
def encode(msg):
"""
Don't change the message at all
:param msg:
"""
return msg
| try:
# Test for mypy support (requires Python 3)
from typing import Text
except:
pass
class Encoder(object):
@staticmethod
def encode(msg):
# type: (bytes) -> List[bytes]
"""
Don't change the message at all
:param msg:
"""
return [msg]
| Return a list of messages in echo encoder and add mypy type hints | Return a list of messages in echo encoder and add mypy type hints
| Python | apache-2.0 | mre/kafka-influxdb,mre/kafka-influxdb |
2722a59aad0775f1bcd1e81232ff445b9012a2ae | ssim/compat.py | ssim/compat.py | """Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError... | """Compatibility routines."""
from __future__ import absolute_import
import sys
try:
import Image # pylint: disable=import-error,unused-import
except ImportError:
from PIL import Image # pylint: disable=unused-import
try:
import ImageOps # pylint: disable=import-error,unused-import
except ImportError... | Add pylint to disable redefined variable. | Add pylint to disable redefined variable.
| Python | mit | jterrace/pyssim |
659659270ef067baf0edea5de5bb10fdab532eaa | run-tests.py | run-tests.py | #!/usr/bin/env python
from __future__ import print_function
from optparse import OptionParser
from subprocess import Popen
import os
import sys
def run_command(cmdline):
proc = Popen(cmdline, shell=True)
proc.communicate()
return proc.returncode
def main():
parser = OptionParser()
parser.add_o... | #!/usr/bin/env python
from __future__ import print_function
from optparse import OptionParser
from subprocess import Popen
import os
import sys
def run_command(cmdline):
proc = Popen(cmdline, shell=True)
proc.communicate()
return proc.returncode
def main():
parser = OptionParser()
parser.add_o... | Remove SALADIR from environment if present | tests: Remove SALADIR from environment if present
| Python | mit | akheron/sala,akheron/sala |
431720194c20dde7b19236d2302c0f9910fd7ea4 | pseudorandom.py | pseudorandom.py | import os
from flask import Flask, render_template
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html', name=get_full_name())
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| import os
from flask import Flask, render_template, request
from names import get_full_name
app = Flask(__name__)
@app.route("/")
def index():
if request.headers.get('User-Agent', '')[:4].lower() == 'curl':
return u"{0}\n".format(get_full_name())
else:
return render_template('index.html', na... | Send just plaintext name if curl is used | Send just plaintext name if curl is used
| Python | mit | treyhunner/pseudorandom.name,treyhunner/pseudorandom.name |
411ae98889d3611151a6f94d661b86b1bbc5e026 | apis/Google.Cloud.Speech.V1/synth.py | apis/Google.Cloud.Speech.V1/synth.py | import os
from synthtool import shell
from pathlib import Path
# Parent of the script is the API-specific directory
# Parent of the API-specific directory is the apis directory
# Parent of the apis directory is the repo root
root = Path(__file__).parent.parent.parent
package = Path(__file__).parent.name
shell.run(
... | import sys
from synthtool import shell
from pathlib import Path
# Parent of the script is the API-specific directory
# Parent of the API-specific directory is the apis directory
# Parent of the apis directory is the repo root
root = Path(__file__).parent.parent.parent
package = Path(__file__).parent.name
bash = '/bin... | Use the right bash command based on platform | Use the right bash command based on platform
| Python | apache-2.0 | googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet |
a1f26386bec0c4d39bce77d0fd3975ae4b0930d0 | apps/package/tests/test_handlers.py | apps/package/tests/test_handlers.py | from django.test import TestCase
class TestRepoHandlers(TestCase):
def test_repo_registry(self):
from package.handlers import get_repo, supported_repos
g = get_repo("github")
self.assertEqual(g.title, "Github")
self.assertEqual(g.url, "https://github.com")
self.assertTrue("... | from django.test import TestCase
class TestRepoHandlers(TestCase):
def test_repo_registry(self):
from package.handlers import get_repo, supported_repos
g = get_repo("github")
self.assertEqual(g.title, "Github")
self.assertEqual(g.url, "https://github.com")
self.assertTrue("... | Test what get_repo() does for unsupported repos | Test what get_repo() does for unsupported repos
| Python | mit | nanuxbe/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,QLGu/djangopackages,miketheman/opencomparison,benracine/opencomparison,QLGu/djangopackages,cartwheelweb/packaginator,miketheman/opencomparison,audreyr/opencomparison,benracine/opencomparison,audreyr/opencomparison,QLGu/djangopackages,cartwheelweb/pack... |
ab91d525abb5bb1ef476f3aac2c034e50f85617a | src/apps/contacts/mixins.py | src/apps/contacts/mixins.py | from apps.contacts.models import BaseContact
class ContactMixin(object):
"""
Would be used for adding contacts functionality to models with contact data.
"""
def get_contacts(self, is_primary=False):
"""
Returns dict with all contacts.
Example:
>> obj.get_contacts()
... | from apps.contacts.models import BaseContact
class ContactMixin(object):
"""
Would be used for adding contacts functionality to models with contact data.
"""
def get_contacts(self, is_primary=False):
"""
Returns dict with all contacts.
Example:
>> obj.get_contacts()
... | Fix description for contact mixin | Fix description for contact mixin
| Python | mit | wis-software/office-manager |
b05eacfa7f2a3fb653ec4a9653780d211245bfb1 | pyvac/helpers/calendar.py | pyvac/helpers/calendar.py | import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:... | import logging
import caldav
from dateutil.relativedelta import relativedelta
log = logging.getLogger(__file__)
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:... | Use now 'oop' method from creating principal object, prevent 'path handling error' with baikal caldav server | Use now 'oop' method from creating principal object, prevent 'path handling error' with baikal caldav server
| Python | bsd-3-clause | doyousoft/pyvac,sayoun/pyvac,doyousoft/pyvac,sayoun/pyvac,doyousoft/pyvac,sayoun/pyvac |
d51d9cc67eca9566673e963e824dc335eb47a9af | recipy/utils.py | recipy/utils.py | import sys
from .log import log_input, log_output
def open(*args, **kwargs):
"""Built-in open replacement that logs input and output
Workaround for issue #44. Patching `__builtins__['open']` is complicated,
because many libraries use standard open internally, while we only want to
log inputs and out... | import six
from .log import log_input, log_output
def open(*args, **kwargs):
"""Built-in open replacement that logs input and output
Workaround for issue #44. Patching `__builtins__['open']` is complicated,
because many libraries use standard open internally, while we only want to
log inputs and out... | Use six instead of sys.version_info | Use six instead of sys.version_info
| Python | apache-2.0 | recipy/recipy,recipy/recipy |
9e1cf6ecf8104b38c85a00e973873cbfa7d78236 | bytecode.py | bytecode.py | class BytecodeBase:
def __init__(self):
# Eventually might want to add subclassed bytecodes here
# Though __subclasses__ works quite well
pass
def execute(self, machine):
pass
class Push(BytecodeBase):
def __init__(self, data):
self.data = data
def execute(sel... | class BytecodeBase:
autoincrement = True # For jump
def __init__(self):
# Eventually might want to add subclassed bytecodes here
# Though __subclasses__ works quite well
pass
def execute(self, machine):
pass
class Push(BytecodeBase):
def __init__(self, data):
... | Add autoincrement for jump in the future | Add autoincrement for jump in the future
| Python | bsd-3-clause | darbaga/simple_compiler |
2034c8280800291227232435786441bfb0edace0 | tests/cli.py | tests/cli.py | import os
from spec import eq_
from invoke import run
from _utils import support
# Yea, it's not really object-oriented, but whatever :)
class CLI(object):
"Command-line interface"
# Yo dogfood, I heard you like invoking
def basic_invocation(self):
os.chdir(support)
result = run("invok... | import os
from spec import eq_, skip
from invoke import run
from _utils import support
# Yea, it's not really object-oriented, but whatever :)
class CLI(object):
"Command-line interface"
# Yo dogfood, I heard you like invoking
def basic_invocation(self):
os.chdir(support)
result = run(... | Add common CLI invocation test stubs. | Add common CLI invocation test stubs.
Doesn't go into positional args.
| Python | bsd-2-clause | frol/invoke,alex/invoke,mkusz/invoke,mattrobenolt/invoke,mattrobenolt/invoke,kejbaly2/invoke,kejbaly2/invoke,pyinvoke/invoke,pfmoore/invoke,sophacles/invoke,pfmoore/invoke,mkusz/invoke,tyewang/invoke,pyinvoke/invoke,singingwolfboy/invoke,frol/invoke |
2e0286632b9120fe6a788db4483911513a39fe04 | fabfile.py | fabfile.py | from fabric.api import * # noqa
env.hosts = [
'104.131.30.135',
]
env.user = "root"
env.directory = "/home/django/api.freemusic.ninja"
env.deploy_path = "/home/django/django_project"
def deploy():
with cd(env.directory):
run("git pull --rebase")
sudo("pip3 install -r requirements.txt")
... | from fabric.api import * # noqa
env.hosts = [
'104.131.30.135',
]
env.user = "root"
env.directory = "/home/django/api.freemusic.ninja"
env.deploy_path = "/home/django/django_project"
def deploy():
with cd(env.directory):
run("git reset --hard origin/master")
sudo("pip3 install -r requiremen... | Reset to upstream master instead of rebasing during deployment | Reset to upstream master instead of rebasing during deployment
| Python | bsd-3-clause | FreeMusicNinja/api.freemusic.ninja |
caf94786ca8c0bc9e3995da0a160c84921a3bfc6 | fabfile.py | fabfile.py | from fabric.api import task, sudo, env, local
from fabric.contrib.project import rsync_project
from fabric.contrib.console import confirm
@task
def upload_docs():
target = "/var/www/paramiko.org"
staging = "/tmp/paramiko_docs"
sudo("mkdir -p %s" % staging)
sudo("chown -R %s %s" % (env.user, staging))
... | from fabric.api import task, sudo, env, local, hosts
from fabric.contrib.project import rsync_project
from fabric.contrib.console import confirm
@task
@hosts("paramiko.org")
def upload_docs():
target = "/var/www/paramiko.org"
staging = "/tmp/paramiko_docs"
sudo("mkdir -p %s" % staging)
sudo("chown -R ... | Update doc upload task w/ static hostname | Update doc upload task w/ static hostname
| Python | lgpl-2.1 | torkil/paramiko,redixin/paramiko,SebastianDeiss/paramiko,fvicente/paramiko,zpzgone/paramiko,mirrorcoder/paramiko,reaperhulk/paramiko,jaraco/paramiko,rcorrieri/paramiko,paramiko/paramiko,CptLemming/paramiko,anadigi/paramiko,digitalquacks/paramiko,ameily/paramiko,selboo/paramiko,remram44/paramiko,varunarya10/paramiko,dav... |
e0b7b6ccdd947324ac72b48a28d6c68c7e980d96 | ibmcnx/doc/DataSources.py | ibmcnx/doc/DataSources.py | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Appli... | Create documentation of DataSource Settings | 8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
c6275896adb429fad7f8bebb74ce932739ecfb63 | edx_shopify/views.py | edx_shopify/views.py | import copy, json
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .utils import hmac_is_valid
from .models import Order
from .tasks import ProcessOrder
@csrf_exempt
@require_POST
def ... | import copy, json
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .utils import hmac_is_valid
from .models import Order
from .tasks import ProcessOrder
@csrf_exempt
@require_POST
def ... | Use get_or_create correctly on Order | Use get_or_create correctly on Order
| Python | agpl-3.0 | hastexo/edx-shopify,fghaas/edx-shopify |
cfdbe06da6e35f2cb166374cf249d51f18e1224e | pryvate/blueprints/packages/packages.py | pryvate/blueprints/packages/packages.py | """Package blueprint."""
import os
import magic
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('packages', __name__, url_prefix='/packages')
@blueprint.route('')
def foo():
return 'ok'
@blueprint.route('/<package_type>/<letter>/<name>/<version>',
... | """Package blueprint."""
import os
import magic
from flask import Blueprint, current_app, make_response, render_template
blueprint = Blueprint('packages', __name__, url_prefix='/packages')
@blueprint.route('')
def foo():
return 'ok'
@blueprint.route('/<package_type>/<letter>/<name>/<version>',
... | Return a 404 if the package was not found | Return a 404 if the package was not found
| Python | mit | Dinoshauer/pryvate,Dinoshauer/pryvate |
e1b0222c8a3ed39bf76af10484a94aa4cfe5adc8 | googlesearch/templatetags/search_tags.py | googlesearch/templatetags/search_tags.py | import math
from django import template
from ..conf import settings
register = template.Library()
@register.inclusion_tag('googlesearch/_pagination.html', takes_context=True)
def show_pagination(context, pages_to_show=10):
max_pages = int(math.ceil(context['total_results'] /
setting... | import math
from django import template
from ..conf import settings
register = template.Library()
@register.inclusion_tag('googlesearch/_pagination.html', takes_context=True)
def show_pagination(context, pages_to_show=10):
max_pages = int(math.ceil(context['total_results'] /
setting... | Remove last_page not needed anymore. | Remove last_page not needed anymore.
| Python | mit | hzdg/django-google-search,hzdg/django-google-search |
451a435ca051305517c79216d7ab9441939f4004 | src/amr.py | src/amr.py | import dolfin as df
def amr(mesh, m, DirichletBoundary, g, d):
V = df.FunctionSpace(mesh, "CG", 1)
# Define boundary condition
bc = df.DirichletBC(V, g, DirichletBoundary())
# Define variational problem
u = df.Function(V)
v = df.TestFunction(V)
E = df.grad(u)
costheta = df.dot(m, E)
... | import dolfin as df
def amr(mesh, m, DirichletBoundary, g, d, s0=1, alpha=1):
V = df.FunctionSpace(mesh, "CG", 1)
# Define boundary condition
bc = df.DirichletBC(V, g, DirichletBoundary())
# Define variational problem
u = df.Function(V)
v = df.TestFunction(V)
E = -df.grad(u)
costheta ... | Add sigma0 and alpha AMR parameters to the function. | Add sigma0 and alpha AMR parameters to the function.
| Python | bsd-2-clause | fangohr/fenics-anisotropic-magneto-resistance |
9a2169e38374429db7792537e2c4c1a78281200d | src/application/models.py | src/application/models.py | """
models.py
App Engine datastore models
"""
from google.appengine.ext import ndb
class ExampleModel(ndb.Model):
"""Example Model"""
example_name = ndb.StringProperty(required=True)
example_description = ndb.TextProperty(required=True)
added_by = ndb.UserProperty()
timestamp = ndb.DateTimePro... | """
models.py
App Engine datastore models
"""
from google.appengine.ext import ndb
class SchoolModel(ndb.Model):
""""Basic Model""""
name = ndb.StringProperty(required=True)
place = ndb.StringProperty(required=True)
added_by = ndb.UserProperty()
timestamp = ndb.DateTimeProperty(auto_now_add=Tru... | Add Docstrings and fix basic model | Add Docstrings and fix basic model | Python | mit | shashisp/reWrite-SITA,shashisp/reWrite-SITA,shashisp/reWrite-SITA |
08ae805a943be3cdd5e92c050512374180b9ae35 | indra/sources/geneways/geneways_api.py | indra/sources/geneways/geneways_api.py | """
This module provides a simplified API for invoking the Geneways input processor
, which converts extracted information collected with Geneways into INDRA
statements.
See publication:
Rzhetsky, Andrey, Ivan Iossifov, Tomohiro Koike, Michael Krauthammer, Pauline
Kra, Mitzi Morris, Hong Yu et al. "GeneWays: a system ... | """
This module provides a simplified API for invoking the Geneways input processor
, which converts extracted information collected with Geneways into INDRA
statements.
See publication:
Rzhetsky, Andrey, Ivan Iossifov, Tomohiro Koike, Michael Krauthammer, Pauline
Kra, Mitzi Morris, Hong Yu et al. "GeneWays: a system ... | Update API to look at one folder and return processor | Update API to look at one folder and return processor
| Python | bsd-2-clause | pvtodorov/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/indra,bgyori/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,bgyori/indra,johnbachman/belpy |
69aa0ec7c79139167e7a2adce1e0effac960755a | flaskrst/__init__.py | flaskrst/__init__.py | # -*- coding: utf-8 -*-
"""
flask-rstblog
~~~~~~~~~~~~~
:copyright: (c) 2011 by Christoph Heer.
:license: BSD, see LICENSE for more details.
"""
from flask import Flask, url_for
app = Flask("flaskrst")
@app.context_processor
def inject_navigation():
navigation = []
for item in app.config.get... | # -*- coding: utf-8 -*-
"""
flask-rstblog
~~~~~~~~~~~~~
:copyright: (c) 2011 by Christoph Heer.
:license: BSD, see LICENSE for more details.
"""
from flask import Flask, url_for
app = Flask("flaskrst")
@app.context_processor
def inject_navigation():
navigation = []
for item in app.config.get... | Rename navigation config key name to label and add support for links to external sites over the url key name | Rename navigation config key name to label and add support for links to external sites over the url key name
| Python | bsd-3-clause | jarus/flask-rst |
5c21f105057f8c5d10721b6de2c5cf698668fd3c | src/events/admin.py | src/events/admin.py | from django.contrib import admin
from .models import SponsoredEvent
@admin.register(SponsoredEvent)
class SponsoredEventAdmin(admin.ModelAdmin):
fields = [
'host', 'title', 'slug', 'category', 'language',
'abstract', 'python_level', 'detailed_description',
'recording_policy', 'slide_link'... | from django.contrib import admin
from .models import SponsoredEvent
@admin.register(SponsoredEvent)
class SponsoredEventAdmin(admin.ModelAdmin):
fields = [
'host', 'title', 'slug', 'category', 'language',
'abstract', 'python_level', 'detailed_description',
'recording_policy', 'slide_link'... | Make host field raw ID instead of select | Make host field raw ID instead of select
| Python | mit | pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016 |
74e8bf6574ce3658e1b276479c3b6ebec36844a4 | kuhn_poker/agents/kuhn_random_agent.py | kuhn_poker/agents/kuhn_random_agent.py | import random
import sys
import acpc_python_client as acpc
class KuhnRandomAgent(acpc.Agent):
def __init__(self):
super().__init__()
def on_game_start(self, game):
pass
def on_next_turn(self, game, match_state, is_acting_player):
if not is_acting_player:
return
... | import random
import sys
import acpc_python_client as acpc
class KuhnRandomAgent(acpc.Agent):
def __init__(self):
super().__init__()
def on_game_start(self, game):
pass
def on_next_turn(self, game, match_state, is_acting_player):
if not is_acting_player:
return
... | Remove unnecessary log from random agent | Remove unnecessary log from random agent
| Python | mit | JakubPetriska/poker-cfr,JakubPetriska/poker-cfr |
fe76abc03f7152f318712e1a233aad42f2e9870a | jsonfield/widgets.py | jsonfield/widgets.py | from django import forms
from django.utils import simplejson as json
import staticmedia
class JSONWidget(forms.Textarea):
def render(self, name, value, attrs=None):
if value is None:
value = ""
if not isinstance(value, basestring):
value = json.dumps(value, indent=2)
... | from django import forms
from django.utils import simplejson as json
from django.conf import settings
class JSONWidget(forms.Textarea):
def render(self, name, value, attrs=None):
if value is None:
value = ""
if not isinstance(value, basestring):
value = json.dumps(value, ind... | Use staticfiles instead of staticmedia | Use staticfiles instead of staticmedia
| Python | bsd-3-clause | SideStudios/django-jsonfield,chrismeyersfsu/django-jsonfield |
c13208dcc4fe1715db10d86e4dfd584c18f396fa | sympy/calculus/singularities.py | sympy/calculus/singularities.py | from sympy.solvers import solve
from sympy.simplify import simplify
def singularities(expr, sym):
"""
Finds singularities for a function.
Currently supported functions are:
- univariate real rational functions
Examples
========
>>> from sympy.calculus.singularities import singularities
... | from sympy.solvers import solve
from sympy.solvers.solveset import solveset
from sympy.simplify import simplify
def singularities(expr, sym):
"""
Finds singularities for a function.
Currently supported functions are:
- univariate real rational functions
Examples
========
>>> from sympy.c... | Replace solve with solveset in sympy.calculus | Replace solve with solveset in sympy.calculus
| Python | bsd-3-clause | skidzo/sympy,chaffra/sympy,pandeyadarsh/sympy,VaibhavAgarwalVA/sympy,abhiii5459/sympy,jbbskinny/sympy,aktech/sympy,lindsayad/sympy,kevalds51/sympy,Titan-C/sympy,hargup/sympy,yukoba/sympy,farhaanbukhsh/sympy,moble/sympy,emon10005/sympy,bukzor/sympy,sahmed95/sympy,mafiya69/sympy,kaushik94/sympy,VaibhavAgarwalVA/sympy,jbb... |
b71f3c726aa6bde4ab0e2b471c5cb9064abfb3fa | apps/webdriver_testing/api_v2/test_user_resources.py | apps/webdriver_testing/api_v2/test_user_resources.py | from apps.webdriver_testing.webdriver_base import WebdriverTestCase
from apps.webdriver_testing import data_helpers
from apps.webdriver_testing.data_factories import UserFactory
class WebdriverTestCaseSubtitlesUpload(WebdriverTestCase):
"""TestSuite for uploading subtitles via the api.
"""
def setUp(s... | from apps.webdriver_testing.webdriver_base import WebdriverTestCase
from apps.webdriver_testing import data_helpers
from apps.webdriver_testing.data_factories import UserFactory
class WebdriverTestCaseSubtitlesUpload(WebdriverTestCase):
"""TestSuite for uploading subtitles via the api.
"""
def setUp(s... | Fix webdriver user creation bug | Fix webdriver user creation bug
| Python | agpl-3.0 | eloquence/unisubs,ofer43211/unisubs,eloquence/unisubs,eloquence/unisubs,pculture/unisubs,norayr/unisubs,pculture/unisubs,norayr/unisubs,wevoice/wesub,pculture/unisubs,ujdhesa/unisubs,ofer43211/unisubs,ujdhesa/unisubs,pculture/unisubs,ReachingOut/unisubs,ofer43211/unisubs,wevoice/wesub,ujdhesa/unisubs,wevoice/wesub,Reac... |
236ad637e05ab8ff48b7c169dd54228e48470e1b | mediacloud/mediawords/util/test_sql.py | mediacloud/mediawords/util/test_sql.py | from mediawords.util.sql import *
import time
import datetime
def test_get_sql_date_from_epoch():
assert get_sql_date_from_epoch(int(time.time())) == datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
def test_sql_now():
assert sql_now() == datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
def... | from mediawords.util.sql import *
import time
import datetime
def test_get_sql_date_from_epoch():
assert get_sql_date_from_epoch(int(time.time())) == datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S')
assert get_sql_date_from_epoch(0) == datetime.datetime.fromtimestamp(0).strftime('%Y-%m-%d %H:%M:%S')
... | Add some more unit tests for get_sql_date_from_epoch() | Add some more unit tests for get_sql_date_from_epoch()
| Python | agpl-3.0 | berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud |
d2991a6385be74debf71eb8404e362c6027e6d50 | molecule/default/tests/test_default.py | molecule/default/tests/test_default.py | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_command(host):
assert host.command('i3 --version').rc == 0
assert host.command('pactl --version').rc == 0
assert host.comma... | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_command(host):
assert host.command('i3 --version').rc == 0
assert host.command('pactl --version').rc == 0
| Remove redundant xorg command test | Remove redundant xorg command test
| Python | mit | nephelaiio/ansible-role-i3,nephelaiio/ansible-role-i3 |
325902c169424ec76307efa71a2e4885180e5cbb | tests/integration/shell/call.py | tests/integration/shell/call.py | # -*- coding: utf-8 -*-
"""
tests.integration.shell.call
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: © 2012 UfSoft.org - :email:`Pedro Algarvio (pedro@algarvio.me)`
:license: Apache 2.0, see LICENSE for more details.
"""
import sys
# Import salt libs
from saltunittest import TestLoader, TextTestRunner
i... | # -*- coding: utf-8 -*-
"""
tests.integration.shell.call
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: © 2012 UfSoft.org - :email:`Pedro Algarvio (pedro@algarvio.me)`
:license: Apache 2.0, see LICENSE for more details.
"""
import sys
# Import salt libs
from saltunittest import TestLoader, TextTestRunner, ... | Test to make sure we're outputting kwargs on the user.delete documentation. | Test to make sure we're outputting kwargs on the user.delete documentation.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
981bac39056584ec9c16e5a8d0f7a972d7365a3f | tests/test_module_dispatcher.py | tests/test_module_dispatcher.py | import pytest
from conftest import (POSITIVE_HOST_PATTERNS, NEGATIVE_HOST_PATTERNS)
@pytest.mark.parametrize("host_pattern, num_hosts", POSITIVE_HOST_PATTERNS)
def test_len(host_pattern, num_hosts, hosts):
assert len(getattr(hosts, host_pattern)) == num_hosts
@pytest.mark.parametrize("host_pattern, num_hosts", ... | import pytest
from conftest import (POSITIVE_HOST_PATTERNS, NEGATIVE_HOST_PATTERNS)
@pytest.mark.parametrize("host_pattern, num_hosts", POSITIVE_HOST_PATTERNS)
def test_len(host_pattern, num_hosts, hosts):
assert len(getattr(hosts, host_pattern)) == num_hosts
@pytest.mark.parametrize("host_pattern, num_hosts", ... | Use more prefered exc_info inspection technique | Use more prefered exc_info inspection technique
| Python | mit | jlaska/pytest-ansible |
ba564c7e2cacc8609d52f03e501786be3c7c8f44 | tests/config.py | tests/config.py | import sys
sys.path.append("../ideascaly")
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import ConfigParser
import unittest
config = ConfigParser.ConfigParser()
config.read('config')
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = create_auth()
s... | import sys
sys.path.append('../ideascaly')
from ideascaly.auth import AuthNonSSO
from ideascaly.api import API
import unittest
testing_community = 'fiveheads.ideascale.com'
testing_token = '5b3326f8-50a5-419d-8f02-eef6a42fd61a'
class IdeascalyTestCase(unittest.TestCase):
def setUp(self):
self.auth = c... | Change the way used to read the testing information | Change the way used to read the testing information
| Python | mit | joausaga/ideascaly |
d07109e07e4d9fab488dfbbcf56fdfe18baa56ab | lib/python/plow/test/test_static.py | lib/python/plow/test/test_static.py | import unittest
import manifest
import plow
class StaticModuletests(unittest.TestCase):
def testFindJobs(self):
plow.findJobs()
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(StaticModuletests)
unittest.TextTestRunner(verbosity=2).run(suite)
| import unittest
import manifest
import plow
class StaticModuletests(unittest.TestCase):
def testFindJobs(self):
plow.getJobs()
def testGetGroupedJobs(self):
result = [
{"id": 1, "parent":0, "name": "High"},
{"id": 2, "parent":1, "name": "Foo"}
]
for... | Set the column count value based on size of header list. | Set the column count value based on size of header list.
| Python | apache-2.0 | Br3nda/plow,Br3nda/plow,chadmv/plow,Br3nda/plow,chadmv/plow,chadmv/plow,Br3nda/plow,Br3nda/plow,chadmv/plow,chadmv/plow,chadmv/plow,chadmv/plow |
189c7a7c982739cd7a3026e34a9969ea9278a12b | api/data/src/lib/middleware.py | api/data/src/lib/middleware.py | import os
import re
class SetBaseEnv(object):
"""
Figure out which port we are on if we are running and set it.
So that the links will be correct.
Not sure if we need this always...
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request... | import os
class SetBaseEnv(object):
"""
Figure out which port we are on if we are running and set it.
So that the links will be correct.
Not sure if we need this always...
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
... | Fix so we can do :5000 queries from api container | Fix so we can do :5000 queries from api container
| Python | mit | xeor/hohu,xeor/hohu,xeor/hohu,xeor/hohu |
e0c70b2b20349b8f1c0f6df8cc641c3267a63a06 | crypto.py | crypto.py | """
Sending a message:
Encrypt your plaintext with encrypt_message
Your id will serve as your public key
Reading a message
Use decrypt_message and validate contents
"""
from Crypto.PublicKey import RSA
# Generates and writes byte string with object of RSA key object
def create_key():
key = RSA.genera... | """
Sending a message:
Encrypt your plaintext with encrypt_message
Your id will serve as your public key
Reading a message
Use decrypt_message and validate contents
"""
from Crypto.PublicKey import RSA
# Generates and writes byte string with object of RSA key object
def create_key():
key = RSA.genera... | Use 'with ... as ...' for file opening. Standardize variable names. | Use 'with ... as ...' for file opening. Standardize variable names.
| Python | mit | Tribler/decentral-market |
f75e245f461e57cc868ee5452c88aea92b6681bf | chainer/functions/parameter.py | chainer/functions/parameter.py | import numpy
from chainer import function
class Parameter(function.Function):
"""Function that outputs its weight array.
This is a parameterized function that takes no input and returns a variable
holding a shallow copy of the parameter array.
Args:
array: Initial parameter array.
"""... | import numpy
from chainer import function
from chainer.utils import type_check
class Parameter(function.Function):
"""Function that outputs its weight array.
This is a parameterized function that takes no input and returns a variable
holding a shallow copy of the parameter array.
Args:
arr... | Add typecheck to Parameter function | Add typecheck to Parameter function
| Python | mit | t-abe/chainer,chainer/chainer,pfnet/chainer,jnishi/chainer,sou81821/chainer,ikasumi/chainer,tigerneil/chainer,delta2323/chainer,1986ks/chainer,chainer/chainer,yanweifu/chainer,ronekko/chainer,muupan/chainer,truongdq/chainer,chainer/chainer,muupan/chainer,okuta/chainer,jnishi/chainer,anaruse/chainer,hvy/chainer,cupy/cup... |
3cf9473bdf1714460478b4cd36a54b09b2a57173 | lib/feedeater/validate.py | lib/feedeater/validate.py | """Validate GTFS"""
import os
import mzgtfs.feed
import mzgtfs.validation
import task
class FeedEaterValidate(task.FeedEaterTask):
def run(self):
# Validate feeds
self.log("===== Feed: %s ====="%self.feedid)
feed = self.registry.feed(self.feedid)
filename = self.filename or os.path.join(self.workdi... | """Validate GTFS"""
import os
import mzgtfs.feed
import mzgtfs.validation
import task
class FeedEaterValidate(task.FeedEaterTask):
def __init__(self, *args, **kwargs):
super(FeedEaterValidate, self).__init__(*args, **kwargs)
self.feedvalidator = kwargs.get('feedvalidator')
def parser(self):
parser =... | Add --feedvaldiator option to validator | Add --feedvaldiator option to validator
| Python | mit | transitland/transitland-datastore,transitland/transitland-datastore,transitland/transitland-datastore,brechtvdv/transitland-datastore,brechtvdv/transitland-datastore,brechtvdv/transitland-datastore |
d1174017c6b282aa1d808b784ffde8a3d3190472 | fabfile.py | fabfile.py | # -*- coding: utf-8 -*-
"""Generic Fabric-commands which should be usable without further configuration"""
from fabric.api import *
from os.path import dirname, split, abspath
import os
import sys
import glob
# Hacking our way into __init__.py of current package
current_dir = dirname(abspath(__file__))
sys_path, pack... | # -*- coding: utf-8 -*-
"""Generic Fabric-commands which should be usable without further configuration"""
from fabric.api import *
from os.path import dirname, split, abspath
import os
import sys
import glob
# Hacking our way into __init__.py of current package
current_dir = dirname(abspath(__file__))
sys_path, pack... | Allow running tasks even if roledefs.pickle is missing | Allow running tasks even if roledefs.pickle is missing
Signed-off-by: Samuli Seppänen <be49b59234361de284476e9a2215fb6477f46673@openvpn.net>
| Python | bsd-2-clause | mattock/fabric,mattock/fabric |
3f394e47841b2d9e49554b21c67b06a46f99f25c | celery_app.py | celery_app.py | # -*- encoding: utf-8 -*-
import config
import logging
from celery.schedules import crontab
from lazyblacksmith.app import create_app
from lazyblacksmith.extension.celery_app import celery_app
# disable / enable loggers we want
logging.getLogger('pyswagger').setLevel(logging.ERROR)
app = create_app(config)
app.app... | # -*- encoding: utf-8 -*-
import config
import logging
from celery.schedules import crontab
from lazyblacksmith.app import create_app
from lazyblacksmith.extension.celery_app import celery_app
# disable / enable loggers we want
logging.getLogger('pyswagger').setLevel(logging.ERROR)
app = create_app(config)
app.app... | Add corporation task in celery data | Add corporation task in celery data
| Python | bsd-3-clause | Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith |
9d94a753c4824df210753996edaa9f7910df5fa8 | tests/test_sample_app.py | tests/test_sample_app.py | import pytest
@pytest.fixture
def app():
import sys
sys.path.append('.')
from sample_app import create_app
return create_app()
@pytest.fixture
def client(app):
return app.test_client()
def test_index(client):
client.get('/')
| import pytest
@pytest.fixture
def app():
import sys
sys.path.append('.')
from sample_app import create_app
return create_app()
@pytest.fixture
def client(app):
return app.test_client()
def test_index(client):
resp = client.get('/')
assert resp.status == 200
| Check for status code of 200 in sample app. | Check for status code of 200 in sample app.
| Python | apache-2.0 | JingZhou0404/flask-bootstrap,scorpiovn/flask-bootstrap,suvorom/flask-bootstrap,BeardedSteve/flask-bootstrap,ser/flask-bootstrap,suvorom/flask-bootstrap,victorbjorklund/flask-bootstrap,BeardedSteve/flask-bootstrap,ser/flask-bootstrap,livepy/flask-bootstrap,victorbjorklund/flask-bootstrap,dingocuster/flask-bootstrap,Coxi... |
f48afc99a7e7aa076aa27b33deda824b5509bab2 | test_qt_helpers_qt5.py | test_qt_helpers_qt5.py | from __future__ import absolute_import, division, print_function
import os
import sys
import pytest
from mock import MagicMock
# At the moment it is not possible to have PyQt5 and PyQt4 installed
# simultaneously because one requires the Qt4 libraries while the other
# requires the Qt5 libraries
class TestQT5(obj... | from __future__ import absolute_import, division, print_function
import os
import sys
import pytest
from mock import MagicMock
# At the moment it is not possible to have PyQt5 and PyQt4 installed
# simultaneously because one requires the Qt4 libraries while the other
# requires the Qt5 libraries
class TestQT5(obje... | Comment out problematic test for now | Comment out problematic test for now
| Python | bsd-3-clause | glue-viz/qt-helpers |
15fe43d0be3c665c09c898864bd2815b39fbc8a5 | toolbox/config/common.py | toolbox/config/common.py | CURRENT_MIN_VERSION = 'v3.0'
CURRENT_MAX_VERSION = 'v3.1'
ACTIVE_REMOTE_BRANCHES = ['master', 'staging', 'demo']
DEFAULT_COMMAND_TIMEOUT = 60 * 60
CONTROLLER_PROTOCOL = 'controller'
PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL}
CRP_TYPES = {'docker', 'gce', 'static'}
| CURRENT_MIN_VERSION = 'v3.0'
CURRENT_MAX_VERSION = 'v3.1'
# Once the Next platform supports challenge versions this can be extended.
ACTIVE_REMOTE_BRANCHES = ['master']
DEFAULT_COMMAND_TIMEOUT = 60 * 60
CONTROLLER_PROTOCOL = 'controller'
PROTOCOLS = {'udp', 'tcp', 'ssh', 'http', 'ws', CONTROLLER_PROTOCOL}
CRP_TYPES =... | Change v3 active branches to | Change v3 active branches to [master]
Extend the list when it becomes relevant.
The old platform shall use the legacy branch.
| Python | apache-2.0 | avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox,avatao-content/challenge-toolbox |
6bcc15b6d018560ebc368efcfc2c2c7d435c7dcc | strictify-coqdep.py | strictify-coqdep.py | #!/usr/bin/env python2
import sys, subprocess
import re
if __name__ == '__main__':
p = subprocess.Popen(sys.argv[1:], stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
reg = re.compile(r'''Warning(: in file .*?,\s*required library .*? matches several files in path)''')
if reg.search(stderr):
... | #!/usr/bin/env python3
import sys, subprocess
import re
if __name__ == '__main__':
p = subprocess.Popen(sys.argv[1:], stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
stderr = stderr.decode('utf-8')
reg = re.compile(r'''Warning(: in file .*?,\s*required library .*? matches several files in pa... | Switch from python2 to python3 | Switch from python2 to python3
Closes #6
| Python | mit | JasonGross/coq-scripts,JasonGross/coq-scripts |
0415bc9e4a174b7cebb634a449473131fe16b3b2 | bulbs/content/management/commands/reindex_content.py | bulbs/content/management/commands/reindex_content.py | from django.core.management.base import NoArgsCommand
from bulbs.content.models import Content
class Command(NoArgsCommand):
help = 'Runs Content.index on all content.'
def handle(self, **options):
num_processed = 0
content_count = Content.objects.all().count()
chunk_size = 10
... | from django.core.management.base import NoArgsCommand
from bulbs.content.models import Content
class Command(NoArgsCommand):
help = 'Runs Content.index on all content.'
def handle(self, **options):
num_processed = 0
content_count = Content.objects.all().count()
chunk_size = 10
... | Add ordering to queryset in reindex admin command | Add ordering to queryset in reindex admin command
| Python | mit | theonion/django-bulbs,theonion/django-bulbs,pombredanne/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,pombredanne/django-bulbs,theonion/django-bulbs |
a9a55f87abc0a26d41e3fa3091f2f2efad7a2543 | autoencoder/encode.py | autoencoder/encode.py | import numpy as np
from .network import autoencoder, get_encoder
from .io import read_records, load_model
def encode(input_file, output_file, log_dir):
X = read_records(input_file)
size = X.shape[1]
model = load_model(log_dir)
encoder = get_encoder(model)
predictions = encoder.predict(X)
np.... | import numpy as np
from .network import autoencoder, get_encoder
from .io import read_records, load_model
def encode(input_file, output_file, log_dir):
X = read_records(input_file)
size = X.shape[1]
model = load_model(log_dir)
assert model.input_shape[1] == size, \
'Input size of data and... | Check input dimensions of pretrained model and input file | Check input dimensions of pretrained model and input file
| Python | apache-2.0 | theislab/dca,theislab/dca,theislab/dca |
68d7b3995c49abd8f7096f9498bdbddf6b696d81 | back_office/models.py | back_office/models.py | from django.db import models
from django.utils.translation import ugettext as _
from Django.contrib.auth.models import User
FEMALE = 'F'
MALE = 'M'
class Teacher(models.Model):
"""
halaqat teachers informations
"""
GENDET_CHOICES = (
(MALE, _('Male')),
(FEMALE, _('Female')),
)
... | from django.db import models
from django.utils.translation import ugettext as _
from Django.contrib.auth.models import User
FEMALE = 'F'
MALE = 'M'
class Teacher(models.Model):
"""
halaqat teachers informations
"""
GENDET_CHOICES = (
(MALE, _('Male')),
(FEMALE, _('Female')),
)
... | Add enabled field to teacher model | Add enabled field to teacher model
| Python | mit | EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat |
7bdd06f568856c010a4eacb1e70c262fa4c3388c | bin/trigger_upload.py | bin/trigger_upload.py | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. Useful for
manually triggering Fedimg jobs. """
import logging
import logging.config
import multiprocessing.pool
import sys
import fedmsg
import fedmsg.config
import fedimg
import fedimg.services
from fedimg.s... | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import logging
import logging.config
import multiprocessing.pool
import sys
import fedmsg
import fedmsg.config
import fedimg
import fedimg.services
from fedimg.services.ec2 import EC2Service, EC2ServiceExceptio... | Fix the manual upload trigger script | scripts: Fix the manual upload trigger script
Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>
| Python | agpl-3.0 | fedora-infra/fedimg,fedora-infra/fedimg |
b503a6e893d71b96b3737e567dde16f110db5fc7 | src/prepare_turk_batch.py | src/prepare_turk_batch.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
import os
import sys
import csv
import json
import html
def do_command(args):
assert os.path.exists(args.input)
writer = csv.writer(args.output)
writer.writerow(["document"])
for fname in os.listdir(args.input):
if not fname.endswith('.j... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
"""
import os
import sys
import csv
import json
import html
def do_command(args):
assert os.path.exists(args.input)
writer = csv.writer(args.output)
writer.writerow(["document"])
for i, fname in enumerate(os.listdir(args.input)):
if not fnam... | Prepare data with the new fiields and prompts | Prepare data with the new fiields and prompts
| Python | mit | arunchaganty/briefly,arunchaganty/briefly,arunchaganty/briefly,arunchaganty/briefly |
dfb79b9f148663617048a3c2a310b2a66a1c7103 | marxbot.py | marxbot.py | from errbot import BotPlugin, botcmd, webhook
class MarxBot(BotPlugin):
"""Your daily dose of Marx"""
min_err_version = '1.6.0'
@botcmd(split_args_with=None)
def marx(self, message, args):
return "what a guy"
| from errbot import BotPlugin, botcmd, webhook
import pytumblr
class MarxBot(BotPlugin):
"""Your daily dose of Marx"""
min_err_version = '1.6.0'
tumblr_client = None
def activate(self):
super().activate()
if self.config is None or self.config["consumer_key"] == "" or self.config["consu... | Use the Tumblr API to get Marx quotes | Use the Tumblr API to get Marx quotes
| Python | mit | AbigailBuccaneer/err-dailymarx |
19354bd82a89383d795cdada8d6af78e8f12eed8 | src/server/test_client.py | src/server/test_client.py | #!/usr/bin/env python
# Echo client program
import socket
import sys
from RemoteFunctionCaller import *
from SocketNetworker import SocketNetworker
HOST = 'localhost' # The remote host
PORT = 8553 # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, so... | #!/usr/bin/env python
# Echo client program
import socket
import sys
from RemoteFunctionCaller import *
from SocketNetworker import SocketNetworker
HOST = 'localhost' # The remote host
PORT = 8553 # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, so... | Update call method in test client | Update call method in test client
| Python | mit | cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim,cnlohr/bridgesim |
d097f773260d06b898ab70e99596a07b056a7cb3 | ccdproc/__init__.py | ccdproc/__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The ccdproc package is a collection of code that will be helpful in basic CCD
processing. These steps will allow reduction of basic CCD data as either a
stand-alone processing or as part of a pipeline.
"""
# Affiliated packages may add whatever they l... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
The ccdproc package is a collection of code that will be helpful in basic CCD
processing. These steps will allow reduction of basic CCD data as either a
stand-alone processing or as part of a pipeline.
"""
# Affiliated packages may add whatever they l... | Add ImageFileCollection to ccdproc namespace | Add ImageFileCollection to ccdproc namespace
| Python | bsd-3-clause | indiajoe/ccdproc,mwcraig/ccdproc,astropy/ccdproc,evertrol/ccdproc,crawfordsm/ccdproc,pulsestaysconstant/ccdproc |
16b21e6e3ddf0e26cb1412bffbe2be4acca1deb6 | app/readers/basereader.py | app/readers/basereader.py | from lxml import etree
from app import formatting
def get_namespace_from_top(fn, key='xmlns'):
ac, el = next(etree.iterparse(fn))
return {'xmlns': el.nsmap[key]}
def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
"""
Calls xmltag generator for multiple files.
"""
# Dep... | from lxml import etree
import itertools
from app import formatting
def get_namespace_from_top(fn, key='xmlns'):
ac, el = next(etree.iterparse(fn))
return {'xmlns': el.nsmap[key]}
def generate_tags_multiple_files(input_files, tag, ignore_tags, ns=None):
"""
Calls xmltag generator for multiple files.
... | Return chained iterators instead of only first of multiple iterators | Return chained iterators instead of only first of multiple iterators
| Python | mit | glormph/msstitch |
7d8f291dea725c28e4d904a3195fde46a3418925 | parafermions/tests/test_peschel_emery.py | parafermions/tests/test_peschel_emery.py | #!/usr/bin/env python
"""
Test the MPS class
"""
import unittest
import numpy as np
import parafermions as pf
class Test(unittest.TestCase):
def test_pe_degeneracy(self):
# should initialise with all zeros
N, l = 8, 0.2
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
... | #!/usr/bin/env python
"""
Test the MPS class
"""
import unittest
import numpy as np
import parafermions as pf
class Test(unittest.TestCase):
def test_pe_degeneracy(self):
# should initialise with all zeros
N, l = 8, 0.0
pe = pf.PeschelEmerySpinHalf(N, l, dtype=np.dtype('float64'))
... | Update slicing so that array sizes match | Update slicing so that array sizes match
| Python | bsd-2-clause | nmoran/pf_resonances |
5bc1731288b76978fa66acab7387a688cea76b4c | wallabag/wallabag_add.py | wallabag/wallabag_add.py | """
Module for adding new entries
"""
import re
import api
import conf
def add(target_url, title=None, star=False, read=False):
conf.load()
valid_url = False
if not re.compile("(?i)https?:\\/\\/.+").match(target_url):
for protocol in "https://", "http://":
if api.is_vali... | """
Module for adding new entries
"""
import re
import api
import conf
import json
def add(target_url, title=None, star=False, read=False):
conf.load()
valid_url = False
if not re.compile("(?i)https?:\\/\\/.+").match(target_url):
for protocol in "https://", "http://":
i... | Check if an anetry already exists before adding it | Check if an anetry already exists before adding it
| Python | mit | Nepochal/wallabag-cli |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.