commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
0a0d55a2a9aa07b0841b2a221e8b7bc9b844b976 | update version numbers and project details | arkaitzj/python-butter,wdv4758h/butter,dasSOZO/python-butter | butter/__init__.py | butter/__init__.py | #!/usr/bin/env python
"""Butter: library to give python access to linux's more lower level features"""
__author__ = "Da_Blitz"
__version__ = "0.2"
__email__ = "code@pocketnix.org"
__license__ = "BSD (3 Clause)"
__url__ = "http://code.pocketnix.org/butter"
| #!/usr/bin/env python
"""Butter: library to give python access to linux's more lower level features"""
__author__ = "Da_Blitz"
__version__ = "0.1"
__email__ = "code@pocketnix.org"
__license__ = "BSD (3 Clause)"
__url__ = "http://code.pocketnix.org/"
__testsuite__ = "tests.testall"
| bsd-3-clause | Python |
39d4f9c0df535c13c6f37eaaccaaeabb0b92b8e0 | Bump version number | fabric-colors/fabric-colors,fabric-colors/fabric-colors | fabric_colors/_version.py | fabric_colors/_version.py | __version__ = "0.9.42"
| __version__ = "0.9.41"
| bsd-2-clause | Python |
4e09200b83f986ce333f5b1143e13a4b2d7df2ce | determine site activity on process_view | Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server,Kegbot/kegbot-server | pykeg/src/pykeg/web/middleware.py | pykeg/src/pykeg/web/middleware.py | # Copyright 2011 Mike Wakerly <opensource@hoho.com>
#
# This file is part of the Pykeg package of the Kegbot project.
# For more information on Pykeg or Kegbot, see http://kegbot.org/
#
# Pykeg is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by... | # Copyright 2011 Mike Wakerly <opensource@hoho.com>
#
# This file is part of the Pykeg package of the Kegbot project.
# For more information on Pykeg or Kegbot, see http://kegbot.org/
#
# Pykeg is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by... | mit | Python |
7b21270ca893e90790a0a60c8417df12052ea9a0 | Add alternate MDP-ID aleph API if the first fails | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation | falcom/api/reject_list.py | falcom/api/reject_list.py | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from os import environ
from urllib.request import urlopen
from .uri import URI, APIQuerier
from .marc import get_marc_data_from_xml
from .wor... | # Copyright (c) 2017 The Regents of the University of Michigan.
# All Rights Reserved. Licensed according to the terms of the Revised
# BSD License. See LICENSE.txt for details.
from os import environ
from urllib.request import urlopen
from .uri import URI, APIQuerier
from .marc import get_marc_data_from_xml
from .wor... | bsd-3-clause | Python |
fae13bf07e3b336f52911cb23291c6db029922cb | fix timing issues with new test | commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot,commaai/openpilot | selfdrive/controls/tests/test_startup.py | selfdrive/controls/tests/test_startup.py | #!/usr/bin/env python3
import time
import unittest
from parameterized import parameterized
from cereal import log, car
import cereal.messaging as messaging
from common.params import Params
from selfdrive.boardd.boardd_api_impl import can_list_to_can_capnp # pylint: disable=no-name-in-module,import-error
from selfdrive... | #!/usr/bin/env python3
import time
import unittest
from parameterized import parameterized
from cereal import log, car
import cereal.messaging as messaging
from common.params import Params
from selfdrive.boardd.boardd_api_impl import can_list_to_can_capnp # pylint: disable=no-name-in-module,import-error
from selfdrive... | mit | Python |
22fed955ddab3ccb222148917a369002405aef5b | Reduce FPS | moggers87/isdabizda | isdabizda/__init__.py | isdabizda/__init__.py | import pygame
import sys
from pygame.locals import *
from isdabizda.grid import Grid, SMALL
pygame.init()
grid = Grid(SMALL)
## options
RES = grid.sizes[0] * grid.sizes[1]
RES = (RES,RES)
TITLE = "Isdabizda!"
FPS = 15
DISPLAY_SURF = pygame.display.set_mode(RES)
pygame.display.set_caption(TITLE)
clock = pygame.ti... | import pygame
import sys
from pygame.locals import *
from isdabizda.grid import Grid, SMALL
pygame.init()
grid = Grid(SMALL)
## options
RES = grid.sizes[0] * grid.sizes[1]
RES = (RES,RES)
TITLE = "Isdabizda!"
FPS = 30
DISPLAY_SURF = pygame.display.set_mode(RES)
pygame.display.set_caption(TITLE)
clock = pygame.ti... | isc | Python |
8b78463ac8d8953dffb3c3ecd5e9e1e4396da106 | Make sure set_mpl_backend works if qtpy is not installed | stscieisenhamer/glue,saimn/glue,saimn/glue,stscieisenhamer/glue | glue/_mpl_backend.py | glue/_mpl_backend.py | class MatplotlibBackendSetter(object):
"""
Import hook to make sure the proper Qt backend is set when importing
Matplotlib.
"""
enabled = True
def find_module(self, mod_name, pth):
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backen... | class MatplotlibBackendSetter(object):
"""
Import hook to make sure the proper Qt backend is set when importing
Matplotlib.
"""
enabled = True
def find_module(self, mod_name, pth):
if self.enabled and 'matplotlib' in mod_name:
self.enabled = False
set_mpl_backen... | bsd-3-clause | Python |
eb1fdf3419bdfd1d5920d73a877f707162b783b0 | Drop unused and dangerous entrypoint `open_fileindex` | ecmwf/cfgrib | cfgrib/__init__.py | cfgrib/__init__.py | #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... | #
# Copyright 2017-2021 European Centre for Medium-Range Weather Forecasts (ECMWF).
#
# 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... | apache-2.0 | Python |
ad8036e5a21fd29885dc7ebf201e599a0ca79563 | add charliecloud 0.9.7 (#10661) | iulian787/spack,LLNL/spack,iulian787/spack,iulian787/spack,LLNL/spack,iulian787/spack,LLNL/spack,iulian787/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/charliecloud/package.py | var/spack/repos/builtin/packages/charliecloud/package.py | # Copyright 2013-2019 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 Charliecloud(MakefilePackage):
"""Lightweight user-defined software stacks for HPC."""
... | # Copyright 2013-2019 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 Charliecloud(MakefilePackage):
"""Lightweight user-defined software stacks for HPC."""
... | lgpl-2.1 | Python |
c7322a1ff37c7f2d4c3dfb149c2e36daafae6043 | Bump to version 0.11.3 | reubano/ckanny,reubano/ckanny | ckanny/__init__.py | ckanny/__init__.py | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
ckanny
~~~~~~
Miscellaneous CKAN utility scripts
Examples:
literal blocks::
python example_google.py
Attributes:
module_level_variable1 (int): Module level variables may be documented in
"""
from __future__ import (
absolute_import, divisi... | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
ckanny
~~~~~~
Miscellaneous CKAN utility scripts
Examples:
literal blocks::
python example_google.py
Attributes:
module_level_variable1 (int): Module level variables may be documented in
"""
from __future__ import (
absolute_import, divisi... | mit | Python |
07a74375fabddc9b6fa4de0c345949bfadb54504 | Revert silly change | lkishline/expyfun,LABSN/expyfun,Eric89GXL/expyfun,rkmaddox/expyfun,drammock/expyfun | examples/sync_test.py | examples/sync_test.py | """
=============
A-V sync test
=============
This example tests synchronization between the screen and the audio playback.
"""
# Author: Dan McCloy <drmccloy@uw.edu>
#
# License: BSD (3-clause)
print __doc__
import numpy as np
from expyfun import ExperimentController
rng = np.random.RandomState(0)
with Experiment... | """
=============
A-V sync test
=============
This example tests synchronization between the screen and the audio playback.
"""
# Author: Dan McCloy <drmccloy@uw.edu>
#
# License: BSD (3-clause)
print __doc__
import numpy as np
from expyfun import ExperimentController
rng = np.random.RandomState(0)
with Experiment... | bsd-3-clause | Python |
85880dbf68718737fa52535326163d9b40adf7f9 | Add tags to event serializer | fuziontech/sentry,Kryz/sentry,ngonzalvez/sentry,pauloschilling/sentry,vperron/sentry,ewdurbin/sentry,wong2/sentry,mvaled/sentry,jokey2k/sentry,llonchj/sentry,JTCunning/sentry,wong2/sentry,jean/sentry,pauloschilling/sentry,BayanGroup/sentry,gencer/sentry,beeftornado/sentry,mvaled/sentry,Natim/sentry,imankulov/sentry,vpe... | src/sentry/api/serializers/models/event.py | src/sentry/api/serializers/models/event.py | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import Event
@register(Event)
class EventSerializer(Serializer):
def _get_entries(self, event, user):
# XXX(dcramer): These are called entries for future-proofing
interface_list = []
... | from __future__ import absolute_import
from sentry.api.serializers import Serializer, register
from sentry.models import Event
@register(Event)
class EventSerializer(Serializer):
def _get_entries(self, event, user):
# XXX(dcramer): These are called entries for future-proofing
interface_list = []
... | bsd-3-clause | Python |
71636292d089f16485691f242edf74fcbd72ff2b | Enforce PEP8 on readpdf.py | sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis | jarviscli/plugins/readpdf.py | jarviscli/plugins/readpdf.py | # importing the modules
import PyPDF2
import pyttsx3
from plugin import plugin
"""
A tool for reading out the pdf files using the jarvis.Uses PyPDF2 and pyttsx3 libraries
"""
@plugin('readpdf')
class readpdfjarvis():
def __init__(self):
self.path = None
def __call__(self, jarvis, s):
self.r... | # importing the modules
import PyPDF2
import pyttsx3
from plugin import plugin
"""
A tool for reading out the pdf files using the jarvis.Uses PyPDF2 and pyttsx3 libraries
"""
@plugin('readpdf')
class readpdfjarvis():
def __init__(self):
self.path = None
def __call__(self, jarvis, s):
... | mit | Python |
bb7fa507a31901819dbc7712b13c4223fe6d3585 | Correct p tags on system message output | wong2/sentry,1tush/sentry,boneyao/sentry,zenefits/sentry,fuziontech/sentry,camilonova/sentry,vperron/sentry,JamesMura/sentry,imankulov/sentry,JamesMura/sentry,mvaled/sentry,mvaled/sentry,drcapulet/sentry,fotinakis/sentry,rdio/sentry,mvaled/sentry,ifduyue/sentry,hongliang5623/sentry,Kryz/sentry,fotinakis/sentry,beeftorn... | src/sentry/templatetags/sentry_activity.py | src/sentry/templatetags/sentry_activity.py | """
sentry.templatetags.sentry_activity
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django import template
from django.utils.html import escape, linebreaks
from django.utils.safestring import mark_... | """
sentry.templatetags.sentry_activity
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django import template
from django.utils.html import escape, linebreaks
from django.utils.safestring import mark_... | bsd-3-clause | Python |
736e1f7f4de56a57df3b51058c5b45455e577cf0 | Fix flake8 | jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,jclgoodwin/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk,stev-0/bustimes.org.uk | busstops/management/commands/import_areas.py | busstops/management/commands/import_areas.py | """
Import administrative areas from the NPTG.
Usage:
import_areas < AdminAreas.csv
"""
from ..import_from_csv import ImportFromCSVCommand
from ...models import AdminArea
class Command(ImportFromCSVCommand):
def handle_row(self, row):
AdminArea.objects.update_or_create(
id=row['Adminis... | """
Import administrative areas from the NPTG.
Usage:
import_areas < AdminAreas.csv
"""
from ..import_from_csv import ImportFromCSVCommand
from ...models import AdminArea
class Command(ImportFromCSVCommand):
def handle_row(self, row):
AdminArea.objects.update_or_create(
id=row['Adminis... | mpl-2.0 | Python |
8a870c6faf8aa50ad7f8c58458c4af9ddef7cfdc | Make authbind check graceful. | alex/braid,alex/braid | braid/authbind.py | braid/authbind.py | import os
from fabric.api import sudo, run, abort, quiet
from braid import package, hasSudoCapabilities
def install():
package.install('authbind')
def allow(user, port):
path = os.path.join('/etc/authbind/byport', str(port))
needsUpdate = True
with quiet():
state = run('stat -c %U:%a {}'.f... | import os
from fabric.api import sudo, run, abort
from braid import package, hasSudoCapabilities
def install():
package.install('authbind')
def allow(user, port):
path = os.path.join('/etc/authbind/byport', str(port))
state = run('stat -c %U:%a {}'.format(path))
if state.strip().split(':') != (use... | mit | Python |
ad2087daae138d3897fc47f0713c8955352ed6ae | add SecretBallotUserIdMiddleware | jamesturk/django-secretballot,jamesturk/django-secretballot | secretballot/middleware.py | secretballot/middleware.py | # -*- coding: utf-8 -*-
from hashlib import md5
from django.utils.deprecation import MiddlewareMixin
class SecretBallotMiddleware(MiddlewareMixin):
def process_request(self, request):
request.secretballot_token = self.generate_token(request)
def generate_token(self, request):
raise NotImpleme... | # -*- coding: utf-8 -*-
from hashlib import md5
from django.utils.deprecation import MiddlewareMixin
class SecretBallotMiddleware(MiddlewareMixin):
def process_request(self, request):
request.secretballot_token = self.generate_token(request)
def generate_token(self, request):
raise NotImpleme... | bsd-2-clause | Python |
112cb1eb06034f5afb24f9f1c20052a87d8a6374 | Update pir_test.py | wikkii/raspluonto,wikkii/raspluonto,wikkii/raspluonto,wikkii/raspluonto,wikkii/raspluonto | sensor_testing/pir_test.py | sensor_testing/pir_test.py | # parallax_pir_reva.py - write to screen when movement detected
# (c) BotBook.com - Karvinen, Karvinen, Valtokari
# 22.9.2017 modified from original
import time
import botbook_gpio as gpio
learningPeriod = 30
def main():
pirPin = 7
gpio.mode(pirPin,"in")
#Learning period
print ("learning... " + str(learningPerio... | # parallax_pir_reva.py - write to screen when movement detected
# (c) BotBook.com - Karvinen, Karvinen, Valtokari
# 22.9.2017 modified by Vesa Valli
import time
import botbook_gpio as gpio
learningPeriod = 30
def main():
pirPin = 7
gpio.mode(pirPin,"in")
#Learning period
print ("learning... " + str(learningPeri... | mit | Python |
6c17a81685f4f1b24cefb4760b26e9a33298742c | Bump to v1.10.0 | Cal-CS-61A-Staff/ok-client | client/__init__.py | client/__init__.py | __version__ = 'v1.10.0'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| __version__ = 'v1.9.6'
FILE_NAME = 'ok'
import os
import sys
sys.path.insert(0, '')
# Add directory in which the ok.zip is stored to sys.path.
sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
| apache-2.0 | Python |
4b54488dd2b40254f6217d98c37690dcb37cf783 | fix false origin on replies | Halibot/halibot,Halibot/halibot | halibot/halmodule.py | halibot/halmodule.py | from .halobject import HalObject
from .message import Message
class HalModule(HalObject):
def reply(self, msg0=None, **kwargs):
# Create the reply message
body = kwargs.get('body', msg0.body)
mtype = kwargs.get('type', msg0.type)
author = kwargs.get('author', msg0.author)
origin = kwargs.get('origin', self... | from .halobject import HalObject
from .message import Message
class HalModule(HalObject):
def reply(self, msg0=None, **kwargs):
# Create the reply message
body = kwargs.get('body', msg0.body)
mtype = kwargs.get('type', msg0.type)
author = kwargs.get('author', msg0.author)
origin = kwargs.get('origin', msg0... | bsd-3-clause | Python |
c802426e1c7e45ed456ad92a8b88ab18fba59aa3 | 更新 modules ELOs 中的 management command 'clone_metadata', 新增函式功能宣告註解 | yrchen/CommonRepo,yrchen/CommonRepo,yrchen/CommonRepo,yrchen/CommonRepo | commonrepo/elos/management/commands/clone_metadata.py | commonrepo/elos/management/commands/clone_metadata.py | # -*- coding: utf-8 -*-
#
# Copyright 2016 edX PDR Lab, National Central University, Taiwan.
#
# http://edxpdrlab.ncu.cc/
#
# 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://w... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from commonrepo.elos.models import ELO, ELOMetadata
class Command(BaseCommand):
help = 'Clone Metadata of ELOs'
def add_argument... | apache-2.0 | Python |
c01c97583e11bfe1c41dd41e7b39d19be22fbb7c | use the real paths | christopherjwang/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,cp16net/virgo-base,AlphaStaxLLC/rackspace-monitoring-agent,cp16net/virgo-base,virgo-agent-toolkit/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/rackspace-monitoring-agent,cp16net/virgo-base,kaustavha/... | tools/build.py | tools/build.py | #!/usr/bin/env python
import os
import subprocess
import sys
# TODO: release/debug
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
build_dir = os.path.join(root, 'out')
def build():
if sys.platform != "win32":
cmd = 'make -C %s' % build_dir
else:
cmd = 'tools\win_build.bat'
pri... | #!/usr/bin/env python
import os
import subprocess
import sys
# TODO: release/debug
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
build_dir = os.path.join(root, 'out')
def build():
if sys.platform != "win32":
cmd = 'make -C %s' % build_dir
else:
cmd = 'tools\win_build.bat'
pri... | apache-2.0 | Python |
1edac6151b4a730039e0782a5cb9777fe7f4a21d | Implement basic teste | arcosta/sci-synergy,arcosta/sci-synergy,arcosta/sci-synergy | code/web/scisynergy_flask/tests/test_basic.py | code/web/scisynergy_flask/tests/test_basic.py | import os
import unittest
from scisynergy_flask import app
class BasicTests(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.app.testing = True
def test_main_page(self):
response = self.app.get('/', follow_redirects=True)
self.assertEqual(response.statu... | import os
import unittest
from scisynergy import app
class BasicTests(unittest.TestCase):
def test_main_page(self):
response = self.app.get('/', follow_redirects=True)
self.assertEqual(response.status_code, 200)
| mit | Python |
492ab05637b92f2decbd8fe60e25783ce63f9733 | remove ignore from staging | Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok,Cal-CS-61A-Staff/ok | server/settings/staging.py | server/settings/staging.py | """ Do not put secrets in this file. This file is public.
For staging environment (Using Dokku)
"""
import os
import sys
import binascii
from server.settings import RAVEN_IGNORE_EXCEPTIONS
default_secret = binascii.hexlify(os.urandom(24))
ENV = 'staging'
PREFERRED_URL_SCHEME = 'https'
SECRET_KEY = os.getenv('SE... | """ Do not put secrets in this file. This file is public.
For staging environment (Using Dokku)
"""
import os
import sys
import binascii
from server.settings import RAVEN_IGNORE_EXCEPTIONS
default_secret = binascii.hexlify(os.urandom(24))
ENV = 'staging'
PREFERRED_URL_SCHEME = 'https'
SECRET_KEY = os.getenv('SE... | apache-2.0 | Python |
352583af500746b431d46d7efc3a0d3f931b43a0 | Fix context processors | TamiaLab/PySkCodeOnlineTester,TamiaLab/PySkCodeOnlineTester,TamiaLab/PySkCodeOnlineTester,TamiaLab/PySkCodeOnlineTester | skcodeonlinetester/context_processors.py | skcodeonlinetester/context_processors.py | """
Extra context processors for the SkCodeOnlineTester app.
"""
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.shortcuts import get_current_site
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants... | """
Extra context processors for the SkCodeOnlineTester app.
"""
from django.utils.translation import ugettext_lazy as _
from django.contrib.sites.shortcuts import get_current_site
def app_constants(request):
"""
Constants context processor.
:param request: the current request.
:return: All constants... | agpl-3.0 | Python |
e3548d62aa67472f291f6d3c0c8beca9813d6032 | Make it possible to step() in a newly created env, rather than throwing AttributeError | d1hotpep/openai_gym,Farama-Foundation/Gymnasium,dianchen96/gym,machinaut/gym,dianchen96/gym,d1hotpep/openai_gym,machinaut/gym,Farama-Foundation/Gymnasium | gym/envs/toy_text/discrete.py | gym/envs/toy_text/discrete.py | from gym import Env
from gym import spaces
import numpy as np
def categorical_sample(prob_n):
"""
Sample from categorical distribution
Each row specifies class probabilities
"""
prob_n = np.asarray(prob_n)
csprob_n = np.cumsum(prob_n)
return (csprob_n > np.random.rand()).argmax()
class Di... | from gym import Env
from gym import spaces
import numpy as np
def categorical_sample(prob_n):
"""
Sample from categorical distribution
Each row specifies class probabilities
"""
prob_n = np.asarray(prob_n)
csprob_n = np.cumsum(prob_n)
return (csprob_n > np.random.rand()).argmax()
class Di... | mit | Python |
92737e3f95ff94129e52e1fab1f40a0f70550d46 | Update the ParticleFilterSetOperations | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue | hoomd/filter/set_.py | hoomd/filter/set_.py | from hoomd.filter.filter_ import ParticleFilter
from hoomd import _hoomd
class ParticleFilterSetOperations(ParticleFilter):
def __init__(self, f, g):
if f == g:
raise ValueError("Cannot use same filter for {}"
"".format(self.__class__.__name__))
else:
... | from hoomd.filter.filter_ import ParticleFilter
from hoomd import _hoomd
class ParticleFilterSetOperations(ParticleFilter):
def __init__(self, f, g):
if f == g:
raise ValueError("Cannot use same filter for {}"
"".format(self.__class__.__name__))
else:
... | bsd-3-clause | Python |
8d98fe5570ce37512128d46853000dc860f798b2 | Update jupyterhub_config.py | simphony/simphony-remote,simphony/simphony-remote,simphony/simphony-remote,simphony/simphony-remote | jupyterhub/jupyterhub_config.py | jupyterhub/jupyterhub_config.py | # Configuration file for jupyterhub.
from jupyter_client.localinterfaces import public_ips
c = get_config() # noqa
c.JupyterHub.ssl_key = 'test.key'
c.JupyterHub.ssl_cert = 'test.crt'
c.JupyterHub.hub_ip = public_ips()[0]
# Choose between system-user mode and virtual-user mode
setting_mode = ('system_user', 'virtu... | # Configuration file for jupyterhub.
from jupyter_client.localinterfaces import public_ips
c = get_config() # noqa
c.JupyterHub.ssl_key = 'test.key'
c.JupyterHub.ssl_cert = 'test.crt'
c.JupyterHub.hub_ip = public_ips()[0]
# Choose between system-user mode and virtual-user mode
setting_mode = ('system_user', 'virtu... | bsd-3-clause | Python |
bca7f7f6ae870a0a307566ee1735e899596d3f99 | Simplify the brightness calculation, in preparation for multi-LED drips | claremacrae/raspi_code,claremacrae/raspi_code,claremacrae/raspi_code | hardware/mote/mote_icicles.py | hardware/mote/mote_icicles.py | import time
from random import randint
from mote import Mote
mote = Mote()
mote.configure_channel(1, 16, False)
mote.configure_channel(2, 16, False)
mote.configure_channel(3, 16, False)
mote.configure_channel(4, 16, False)
full_brightness = 40
class Icicle:
def __init__(self, channel):
self.channel = ch... | import time
from random import randint
from mote import Mote
mote = Mote()
mote.configure_channel(1, 16, False)
mote.configure_channel(2, 16, False)
mote.configure_channel(3, 16, False)
mote.configure_channel(4, 16, False)
max_brightness = 40
class Icicle:
def __init__(self, channel):
self.channel = cha... | mit | Python |
9718e6c216b8d5205a19f095593ec099004785a6 | add app | qisanstudio/qstudio-launch,qisanstudio/qstudio-launch | src/studio/launch/commands/app_commands.py | src/studio/launch/commands/app_commands.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import json
import importlib
from sh import pip
from termcolor import colored
from studio.frame.config import common as common_config
from studio.launch.base import manager
app_manager = manager.... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import print_function
import os
import sys
import importlib
from sh import pip
from termcolor import colored
from studio.frame.config import common as common_config
from studio.launch.base import manager
app_manager = manager.subcommand('... | mit | Python |
6380aabe25e38d198b6c4e10d126d6fd97860c85 | remove Simple.validate function | kolodziej/Flask-PAM,KujiraProject/Flask-PAM,KujiraProject/Flask-PAM,kolodziej/Flask-PAM | flask_pam/token/simple.py | flask_pam/token/simple.py | # -*- coding: utf-8 -*-
from hashlib import sha256
from token import Token
class Simple(Token):
"""Simple token implementation. It's not safe. Only for testing purposes!"""
def generate(self):
return sha256(self.username).hexdigest()
| # -*- coding: utf-8 -*-
from hashlib import sha256
from token import Token
class Simple(Token):
"""Simple token implementation. It's not safe. Only for testing purposes!"""
def generate(self):
return sha256(self.username).hexdigest()
def validate(self, token):
return sha256(self.username)... | mit | Python |
eb57a07277f86fc90b7845dc48fb5cde1778c8d4 | Test cut_by_number with words and normal chunk numbers | WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos | test/unit_test/test_cut_number.py | test/unit_test/test_cut_number.py | from lexos.processors.prepare.cutter import split_keep_whitespace, \
count_words, cut_by_number
class TestCutByNumbers:
def test_split_keep_whitespace(self):
assert split_keep_whitespace("Test string") == ["Test", " ", "string"]
assert split_keep_whitespace("Test") == ["Test"]
assert s... | from lexos.processors.prepare.cutter import split_keep_whitespace, \
count_words, cut_by_number
class TestCutByNumbers:
def test_split_keep_whitespace(self):
assert split_keep_whitespace("Test string") == ["Test", " ", "string"]
assert split_keep_whitespace("Test") == ["Test"]
assert s... | mit | Python |
c05d0f2dd77678133af1bbf49915aeaf24efbedc | simplify line counting method | Max00355/HTTPLang | httplang/httplang.py | httplang/httplang.py | import parse
import sys
import utils
import repl
def main():
if len(sys.argv) < 2:
repl.enterREPL()
sys.exit()
inputFile = sys.argv[1]
run(inputFile)
def run(file_):
with open(file_, 'rb') as file:
#pass enumerated file so we can get line numbers starting at 1
parse.pre... | import parse
import sys
import utils
import repl
def main():
if len(sys.argv) < 2:
repl.enterREPL()
sys.exit()
inputFile = sys.argv[1]
run(inputFile)
def run(file_):
with open(file_, 'rb') as file:
#pass enumerated file so we can get line numbers
parse.preParse(enumerat... | mit | Python |
cf84dfda73032a276b2d6f63f2c70f69e61f89fe | Check validity of the config to avoid silent errors. | delftrobotics/keras-retinanet | keras_retinanet/utils/config.py | keras_retinanet/utils/config.py | """
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 w... | """
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 w... | apache-2.0 | Python |
91e916cb67867db9ce835be28b31904e6efda832 | Add comment to new test | aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,aikramer2/spaCy,explosion/spaCy,spacy-io/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/s... | spacy/tests/regression/test_issue1727.py | spacy/tests/regression/test_issue1727.py | '''Test that models with no pretrained vectors can be deserialized correctly
after vectors are added.'''
from __future__ import unicode_literals
import numpy
from ...pipeline import Tagger
from ...vectors import Vectors
from ...vocab import Vocab
from ..util import make_tempdir
def test_issue1727():
data = numpy.... | from __future__ import unicode_literals
import numpy
from ...pipeline import Tagger
from ...vectors import Vectors
from ...vocab import Vocab
from ..util import make_tempdir
def test_issue1727():
data = numpy.ones((3, 300), dtype='f')
keys = [u'I', u'am', u'Matt']
vectors = Vectors(data=data, keys=keys)
... | mit | Python |
3826140004b0686f9f262756da20c5163fc5b80d | update icinga_simple format string handling | tobes/py3status,valdur55/py3status,vvoland/py3status,Andrwe/py3status,Spirotot/py3status,guiniol/py3status,docwalter/py3status,ultrabug/py3status,valdur55/py3status,ultrabug/py3status,ultrabug/py3status,Shir0kamii/py3status,tobes/py3status,Andrwe/py3status,guiniol/py3status,alexoneill/py3status,valdur55/py3status | py3status/modules/icinga_simple.py | py3status/modules/icinga_simple.py | # -*- coding: utf-8 -*-
"""
Display Icinga2 service status information
Configuration Parameters:
- cache_timeout: how often the data should be updated
- base_url: the base url to the icinga-web2 services list
- disable_acknowledge: enable or disable counting of acknowledged service problems
- user: use... | # -*- coding: utf-8 -*-
"""
Display Icinga2 service status information
Configuration Parameters:
- cache_timeout: how often the data should be updated
- base_url: the base url to the icinga-web2 services list
- disable_acknowledge: enable or disable counting of acknowledged service problems
- user: use... | bsd-3-clause | Python |
30e984a0517e6443835f113c3a479aa8302ef14f | Update profile url on amazon tests | python-social-auth/social-core,python-social-auth/social-core | social_core/tests/backends/test_amazon.py | social_core/tests/backends/test_amazon.py | import json
from .oauth import OAuth2Test
class AmazonOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.amazon.AmazonOAuth2'
user_data_url = 'https://api.amazon.com/user/profile'
expected_username = 'FooBar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_... | import json
from .oauth import OAuth2Test
class AmazonOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.amazon.AmazonOAuth2'
user_data_url = 'https://www.amazon.com/ap/user/profile'
expected_username = 'FooBar'
access_token_body = json.dumps({
'access_token': 'foobar',
'tok... | bsd-3-clause | Python |
a85019e7c5e117467d0ce3bf30b9a7589cd17958 | Update create_test_cutout | seung-lab/Julimaps,seung-lab/Julimaps | src/tasks/python/create_test_cutout.py | src/tasks/python/create_test_cutout.py | from cloudvolume import CloudVolume
image_in = 'gs://neuroglancer/pinky100_v0/image_single_slices'
image_out = 'gs://neuroglancer/pinky100_v0/test_image'
image_mip = 0
roi_in = 'gs://neuroglancer/pinky100_v0/image_single_slices/roicc'
roi_out = 'gs://neuroglancer/pinky100_v0/test_image/roicc'
roi_mip = 6
cfsplit_in = ... | from cloudvolume import CloudVolume
image_in = 'gs://neuroglancer/pinky100_v0/image_single_slices'
image_out = 'gs://neuroglancer/pinky100_v0/test_image'
image_mip = 0
roi_in = 'gs://neuroglancer/pinky100_v0/image_single_slices/roicc'
roi_out = 'gs://neuroglancer/pinky100_v0/test_image/roicc'
roi_mip = 6
cfsplit_in = ... | mit | Python |
6ae4f3a71a80d7fe5bb1abe6925a05c4fe811f3c | bump version | simas/django-forms-builder,simas/django-forms-builder | forms_builder/__init__.py | forms_builder/__init__.py | __version__ = "9.7.16"
| __version__ = "0.12.2"
| bsd-2-clause | Python |
a58646ee72fc894a2f2b885b242cc283a0addd7c | remove args | derwolfe/teiler,derwolfe/teiler | src/app.py | src/app.py | import argparse
import os
from actions import server, client
# the main entry point for the application
# for simplicity, let's decide that the user decides at runtime to listen
# and the server decides to serve
# location from which files should be served
app_directory = '/home/chris/blaster'
def main():
# get ... | import argparse
import os
from actions import server, client
# the main entry point for the application
# for simplicity, let's decide that the user decides at runtime to listen
# and the server decides to serve
# location from which files should be served
app_directory = '/home/chris/blaster'
def main():
# get ... | mit | Python |
0f216b43f42ebabedda701fafefe271a223798cb | Fix mcscf example | gkc1000/pyscf,gkc1000/pyscf,gkc1000/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,gkc1000/pyscf,sunqm/pyscf,gkc1000/pyscf | examples/mcscf/41-mcscf_with_given_densityfit_ints.py | examples/mcscf/41-mcscf_with_given_densityfit_ints.py | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import tempfile
import h5py
from pyscf import gto, df, scf, mcscf
'''
Input Cholesky decomposed integrals for CASSCF
'''
mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz')
#
# Integrals in memory. The size of the integral array is (M,N*(N+1)/2)... | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import tempfile
import h5py
from pyscf import gto, df, scf, mcscf
'''
Input Cholesky decomposed integrals for CASSCF
'''
mol = gto.M(atom='H 0 0 0; F 0 0 1', basis='ccpvdz')
#
# Integrals in memory. The size of the integral array is (M,N*(N+1)/2)... | apache-2.0 | Python |
9a4f1da48e72627aa0ff358a3dafe8bb5639482a | refresh access token on each verification | rjw57/componentsdb,rjw57/componentsdb,rjw57/componentsdb | componentsdb/ui.py | componentsdb/ui.py | """
Traditional Web UI.
"""
from functools import wraps
from flask import (
Blueprint, redirect, url_for, render_template, request, session, g
)
from werkzeug.exceptions import BadRequest, Unauthorized
from componentsdb.app import set_current_user_with_token
from componentsdb.auth import user_for_google_id_token... | """
Traditional Web UI.
"""
from functools import wraps
from flask import (
Blueprint, redirect, url_for, render_template, request, session
)
from werkzeug.exceptions import BadRequest, Unauthorized
from componentsdb.app import set_current_user_with_token
from componentsdb.auth import user_for_google_id_token
u... | mit | Python |
becef09e0680786343c581d984e7de5dcb961d16 | Fix for handle failed html parse | yashodhank/frappe,frappe/frappe,frappe/frappe,almeidapaulopt/frappe,vjFaLk/frappe,adityahase/frappe,frappe/frappe,mhbu50/frappe,adityahase/frappe,saurabh6790/frappe,adityahase/frappe,saurabh6790/frappe,mhbu50/frappe,StrellaGroup/frappe,yashodhank/frappe,saurabh6790/frappe,vjFaLk/frappe,almeidapaulopt/frappe,almeidapaul... | frappe/utils/xlsxutils.py | frappe/utils/xlsxutils.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import openpyxl
import re
from openpyxl.styles import Font
from openpyxl import load_workbook
from six import BytesIO, string_types
ILLEGAL_CHARACTERS_RE = re.comp... | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import openpyxl
import re
from openpyxl.styles import Font
from openpyxl import load_workbook
from six import BytesIO, string_types
ILLEGAL_CHARACTERS_RE = re.comp... | mit | Python |
f5a1e7f8e350a5f1b29c0e60caf178208946a2b1 | Add more samples. | precompiler/python-101 | learning-python/ch02/Looping.py | learning-python/ch02/Looping.py | for i in [1, 2, 3, 4]:
print(i)
for i in range(5):
print(i)
colors = ["red", "green", "blue"]
for i in range(len(colors)):
print(i, colors[i])
for color in colors:
print(color)
for idx, color in enumerate(colors):
print(idx, color)
people = ["Scott", "John", "Mike"]
ages = [50, 30, 25]
for pers... | for i in [1, 2, 3, 4]:
print(i)
for i in range(5):
print(i)
colors = ["red", "green", "blue"]
for i in range(len(colors)):
print(i, colors[i])
for color in colors:
print(color)
for idx, color in enumerate(colors):
print(idx, color)
people = ["Scott", "John", "Mike"]
ages = [50, 30, 25]
for pers... | apache-2.0 | Python |
c0da9801f726ab3ac5c360f77598f1d14c615c2e | make sure windrose_utils._make_plot gets exercised! | akrherz/pyIEM | pyiem/tests/test_windrose_utils.py | pyiem/tests/test_windrose_utils.py | import unittest
import datetime
import psycopg2
from pyiem.windrose_utils import windrose, _get_timeinfo
class Test(unittest.TestCase):
def test_timeinfo(self):
"""Exercise the _get_timeinfo method"""
res = _get_timeinfo(range(1, 10), 'hour', 24)
self.assertEquals(res['labeltext'], '(1, 2... | import unittest
import datetime
import psycopg2
from pyiem.windrose_utils import windrose, _get_timeinfo
class Test(unittest.TestCase):
def test_timeinfo(self):
"""Exercise the _get_timeinfo method"""
res = _get_timeinfo(range(1, 10), 'hour', 24)
self.assertEquals(res['labeltext'], '(1, 2... | mit | Python |
cf35695481b703e49fbc00e286ef6380a8aec394 | Remove invalid test | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/apps/notifications/tests/test_views.py | corehq/apps/notifications/tests/test_views.py | from unittest.mock import patch
from corehq.apps.accounting.models import Subscription
from corehq.apps.groups.models import Group
from ..views import NotificationsServiceRMIView
def test_should_hide_feature_notifs_for_pro_with_groups():
with case_sharing_groups_patch(['agroupid']):
hide = Notifications... | from unittest.mock import patch
from corehq.apps.accounting.models import Subscription
from corehq.apps.groups.models import Group
from ..views import NotificationsServiceRMIView
def test_should_hide_feature_notifs_for_pro_with_groups():
with case_sharing_groups_patch(['agroupid']):
hide = Notifications... | bsd-3-clause | Python |
9df00bbfa829006396c2a6718e4540410b27c4c6 | Clear the job queue upon kolibri initialization. | MingDai/kolibri,mrpau/kolibri,benjaoming/kolibri,DXCanas/kolibri,lyw07/kolibri,learningequality/kolibri,rtibbles/kolibri,mrpau/kolibri,mrpau/kolibri,rtibbles/kolibri,DXCanas/kolibri,indirectlylit/kolibri,MingDai/kolibri,lyw07/kolibri,mrpau/kolibri,christianmemije/kolibri,DXCanas/kolibri,learningequality/kolibri,jonbois... | kolibri/tasks/apps.py | kolibri/tasks/apps.py | from __future__ import absolute_import, print_function, unicode_literals
from django.apps import AppConfig
class KolibriTasksConfig(AppConfig):
name = 'kolibri.tasks'
label = 'kolibritasks'
verbose_name = 'Kolibri Tasks'
def ready(self):
from kolibri.tasks.api import client
client.cl... | from __future__ import absolute_import, print_function, unicode_literals
from django.apps import AppConfig
class KolibriTasksConfig(AppConfig):
name = 'kolibri.tasks'
label = 'kolibritasks'
verbose_name = 'Kolibri Tasks'
def ready(self):
pass
| mit | Python |
6a6cb75ad2c29435d74768aa88c5d925570a6ad0 | Add some meta | ligthyear/flask-environments,mattupstate/flask-environments | flask_environments.py | flask_environments.py | # -*- coding: utf-8 -*-
"""
flask_environments
~~~~~~~~~~~~~~~~~~
Environment tools and configuration for Flask applications
:copyright: (c) 2012 by Matt Wright.
:license: MIT, see LICENSE for more details.
"""
import os
import yaml
from flask import current_app
class Environments(object):
... |
import os
import yaml
from flask import current_app
class Environments(object):
def __init__(self, app=None, var_name=None, default_env=None):
self.app = app
self.var_name = var_name or 'FLASK_ENV'
self.default_env = default_env or 'DEVELOPMENT'
self.env = os.environ.get(self.va... | mit | Python |
bb5cbae79ef8efb8d0b7dd3ee95e76955317d3d7 | Fix for broken container security test | tenable/Tenable.io-SDK-for-Python | tests/integration/api/test_sc_test_jobs.py | tests/integration/api/test_sc_test_jobs.py | from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].j... | from tests.base import BaseTest
from tenable_io.api.models import ScTestJob
class TestScTestJobsApi(BaseTest):
def test_status(self, client, image):
jobs = client.sc_test_jobs_api.list()
assert len(jobs) > 0, u'At least one job exists.'
test_job = client.sc_test_jobs_api.status(jobs[0].j... | mit | Python |
6594bb843998ee22b0a12036a0e16c1fd625fd03 | Revert "Catch Validation error" | khchine5/django-shop,khchine5/django-shop,jrief/django-shop,rfleschenberg/django-shop,jrief/django-shop,nimbis/django-shop,nimbis/django-shop,divio/django-shop,awesto/django-shop,rfleschenberg/django-shop,jrief/django-shop,divio/django-shop,nimbis/django-shop,jrief/django-shop,rfleschenberg/django-shop,nimbis/django-sh... | shop/context_processors.py | shop/context_processors.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from shop.models.customer import CustomerModel
def customer(request):
"""
Add the customer to the RequestContext
"""
msg = "The request object does not contain a customer. Edit your MIDDLEWARE_CLASSES sett... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.forms.utils import ValidationError
from shop.models.customer import CustomerModel
def customer(request):
"""
Add the customer to the RequestContext
"""
msg = "The request object does not conta... | bsd-3-clause | Python |
0cb7f9c41c7ae0a7f487188721f56adf2ff9999d | add type hints. | jonhadfield/acli,jonhadfield/acli | lib/acli/services/route53.py | lib/acli/services/route53.py | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, print_function, unicode_literals)
from boto3.session import Session
from acli.output.route53 import (output_route53_list, output_route53_info)
import botocore.exceptions
def get_boto3_session(aws_config):
"""
@type aws_config: Config
"""
... | # -*- coding: utf-8 -*-
from __future__ import (absolute_import, print_function, unicode_literals)
from boto3.session import Session
from acli.output.route53 import (output_route53_list, output_route53_info)
import botocore.exceptions
def get_boto3_session(aws_config):
return Session(region_name=aws_config.region... | mit | Python |
b747391c748c94cd8433dfacd935d131b484a29c | Improve error handling and refactor base path | github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql | java/ql/src/utils/model-generator/RegenerateModels.py | java/ql/src/utils/model-generator/RegenerateModels.py | #!/usr/bin/python3
# Tool to regenerate existing framework CSV models.
from pathlib import Path
import json
import os
import requests
import shutil
import subprocess
import tempfile
import sys
defaultModelPath = "java/ql/lib/semmle/code/java/frameworks"
lgtmSlugToModelFile = {
# "apache/commons-beanutils": "apa... | #!/usr/bin/python3
# Tool to regenerate existing framework CSV models.
from pathlib import Path
import json
import os
import requests
import shutil
import subprocess
import tempfile
import sys
lgtmSlugToModelFile = {
# "apache/commons-beanutils": "java/ql/lib/semmle/code/java/frameworks/apache/BeanUtilsGenerate... | mit | Python |
7dffc7115b5e91ba13de8cb3e306832be7f8e185 | print result in show components | matiasbargas/jiraffe,matiasbargas/jiraffe | client/jiraffe.py | client/jiraffe.py | import urllib
import os
SERVICE_URL = "http://jiraffe.cloudhub.io/api"
CREATE_SERVICE = SERVICE_URL + "/issues"
DEFAULT_SERVICE = SERVICE_URL + "/defaults"
COMPONENT_SERVICE = SERVICE_URL + "/components"
def get_valid_reporter(reporter):
if reporter == "":
return os.environ['JIRA_ID']
return reporter
def cre... | import urllib
import os
SERVICE_URL = "http://jiraffe.cloudhub.io/api"
CREATE_SERVICE = SERVICE_URL + "/issues"
DEFAULT_SERVICE = SERVICE_URL + "/defaults"
COMPONENT_SERVICE = SERVICE_URL + "/components"
def get_valid_reporter(reporter):
if reporter == "":
return os.environ['JIRA_ID']
return reporter
def cre... | mit | Python |
f6be438e01a499dc2bde6abfa5a00fb281db7b83 | Add account_id as the element of this class | henrysher/kamboo,henrysher/kamboo | kamboo/core.py | kamboo/core.py |
import botocore
from kotocore.session import Session
class KambooConnection(object):
"""
Kamboo connection with botocore session initialized
"""
session = botocore.session.get_session()
def __init__(self, service_name="ec2", region_name="us-east-1",
account_id=None,
... |
import botocore
from kotocore.session import Session
class KambooConnection(object):
"""
Kamboo connection with botocore session initialized
"""
session = botocore.session.get_session()
def __init__(self, service_name="ec2", region_name="us-east-1",
credentials=None):
se... | apache-2.0 | Python |
a76b866862874ce52c762b4e0381b233917a977a | Increment version | johnwlockwood/karl_data,johnwlockwood/stream_tap,johnwlockwood/iter_karld_tools,johnwlockwood/stream_tap | karld/_meta.py | karld/_meta.py | version_info = (0, 2, 7)
version = '.'.join(map(str, version_info))
| version_info = (0, 2, 6)
version = '.'.join(map(str, version_info))
| apache-2.0 | Python |
31d7df470dbaf996f4f3c7639107ec04afda1ec4 | Update runcount.py | suzannerohrback/somaticCNVpipeline,suzannerohrback/somaticCNVpipeline | bin/runcount.py | bin/runcount.py | #!/usr/bin/python
import os
from count import countfile
import common
def runAll(args):
print('\n\n\nYou have requested to count unique sam files')
print('\tWARNING:')
print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CANNOT GUARANTEE RESULT ACCURACY')
print('\n')
#set up environm... | #!/usr/bin/python
import os
from count import countfile
import common
def runAll(args):
print('\n\n\nYou have requested to count unique sam files')
print('\tWARNING:')
print('\t\tIF USING ANY REFERENCES OTHER THAN THOSE I PROVIDE I CANNOT GUARANTEE RESULT ACCURACY')
print('\n')
#set up environm... | mit | Python |
c4a0a83fe4a028b1d571058aed755be5b4714531 | fix logging | koteq/hlstats_inviter | includes/SteamGroupMembers.py | includes/SteamGroupMembers.py | import logging
import urllib2
import xml.etree.ElementTree as ElementTree
logger = logging.getLogger()
class SteamGroupMembers(object):
"""
Retrives all members of the specified group.
"""
_members = None
def __init__(self, group_id):
self._group_id = group_id
def __len__(self):
... | import logging
import urllib2
import xml.etree.ElementTree as ElementTree
logger = logging.getLogger()
class SteamGroupMembers(object):
"""
Retrives all members of the specified group.
"""
_members = None
def __init__(self, group_id):
self._group_id = group_id
def __len__(self):
... | unlicense | Python |
0b7a5929208bddb9e850f10ff40f1521363283fd | decrease map_stats precision | therewillbecode/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea,mozilla/ichnaea,mozilla/ichnaea,mozilla/ichnaea,therewillbecode/ichnaea | ichnaea/map_stats.py | ichnaea/map_stats.py | import csv
from cStringIO import StringIO
from ichnaea.db import Measure
def map_stats_request(request):
session = request.database.session()
query = session.query(Measure.lat, Measure.lon)
unique = set()
for lat, lon in query:
unique.add(((lat // 100000) / 1000.0, (lon // 100000) / 1000.0))
... | import csv
from cStringIO import StringIO
from ichnaea.db import Measure
def map_stats_request(request):
session = request.database.session()
query = session.query(Measure.lat, Measure.lon)
unique = set()
for lat, lon in query:
unique.add(((lat // 10000) / 1000.0, (lon // 10000) / 1000.0))
... | apache-2.0 | Python |
3def5ee6b6ffbb60260130deedee65cfc0e186f0 | add missing super() constructor in IosAccelerometer | johnbolia/plyer,kostyll/plyer,cleett/plyer,inclement/plyer,kostyll/plyer,kivy/plyer,kivy/plyer,KeyWeeUsr/plyer,KeyWeeUsr/plyer,cleett/plyer,kivy/plyer,johnbolia/plyer,KeyWeeUsr/plyer,kived/plyer,kived/plyer | plyer/platforms/ios/accelerometer.py | plyer/platforms/ios/accelerometer.py | '''
iOS accelerometer
-----------------
Taken from: https://pyobjus.readthedocs.org/en/latest/pyobjus_ios.html#accessing-accelerometer
'''
from plyer.facades import Accelerometer
from pyobjus import autoclass
class IosAccelerometer(Accelerometer):
def __init__(self):
super(IosAccelerometer, self).__ini... | '''
iOS accelerometer
-----------------
Taken from: https://pyobjus.readthedocs.org/en/latest/pyobjus_ios.html#accessing-accelerometer
'''
from plyer.facades import Accelerometer
from pyobjus import autoclass
class IosAccelerometer(Accelerometer):
def __init__(self):
self.bridge = autoclass('bridge').a... | mit | Python |
a536da0d925201fc652b08ad27985f37c5bd4b6c | Fix relative_urls helper for call from initialization code | liqd/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,DanielNeugebauer/adhocracy,SysTheron/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,SysTheron/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,phihag/adhocracy,alkadis/vcv,phihag/adhocr... | src/adhocracy/lib/helpers/site_helper.py | src/adhocracy/lib/helpers/site_helper.py | from pylons import config, app_globals as g
from pylons.i18n import _
from paste.deploy.converters import asbool
from adhocracy.model import instance_filter as ifilter
CURRENT_INSTANCE = object()
def get_domain_part(domain_with_port):
return domain_with_port.split(':')[0]
def domain():
return get_domain_p... | from pylons import config, app_globals as g
from pylons.i18n import _
from paste.deploy.converters import asbool
from adhocracy.model import instance_filter as ifilter
CURRENT_INSTANCE = object()
def get_domain_part(domain_with_port):
return domain_with_port.split(':')[0]
def domain():
return get_domain_p... | agpl-3.0 | Python |
3f8a29efa3128f8167306b46e47e7ac18cf592ab | set broker pool limit | total-impact/total-impact-core,Impactstory/total-impact-core,Impactstory/total-impact-core,Impactstory/total-impact-core,total-impact/total-impact-core,total-impact/total-impact-core,Impactstory/total-impact-core,total-impact/total-impact-core | celeryconfig.py | celeryconfig.py | import os
import sys
import urlparse
from kombu import Exchange, Queue
sys.path.append('.')
redis_url = os.environ.get('REDIS_URL', "redis://127.0.0.1:6379/")
if not redis_url.endswith("/"):
redis_url += "/"
BROKER_URL = redis_url + "1" # REDIS_CELERY_TASKS_DATABASE_NUMBER = 1
CELERY_RESULT_BACKEND = redis_url... | import os
import sys
import urlparse
from kombu import Exchange, Queue
sys.path.append('.')
redis_url = os.environ.get('REDIS_URL', "redis://127.0.0.1:6379/")
if not redis_url.endswith("/"):
redis_url += "/"
BROKER_URL = redis_url + "1" # REDIS_CELERY_TASKS_DATABASE_NUMBER = 1
CELERY_RESULT_BACKEND = redis_url... | mit | Python |
3abbba864df16e06a768b761baefd3d705008114 | Update vigenereCipher: fixed typo | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | books/CrackingCodesWithPython/Chapter18/vigenereCipher.py | books/CrackingCodesWithPython/Chapter18/vigenereCipher.py | # Vigenere Cipher (Polyalphabetic Substitution Cipher)
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
from books.CrackingCodesWithPython.pyperclip import copy
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
# This text can be downloaded from https://www.nostarch.com/crackingcodes/:
myMessage = "... | # Vigenere Cipher (Polyalphabetic Substitution Cipher)
# https://www.nostarch.com/crackingcodes/ (BSD Licensed)
from books.CrackingCodesWithPython.pyperclip import copy
LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def main():
# This text can be downloaded from https://www.nostarch.com/crackingcodes/:
myMessage = "... | mit | Python |
ae92abffcbe792d41ee7aafb08e59ba874f3a4c4 | Fix migration dependencies | JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw | longclaw/basket/migrations/0003_auto_20170207_2053.py | longclaw/basket/migrations/0003_auto_20170207_2053.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-07 20:53
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('basket', '0001_initial'),
]
operations = [
migrations.RenameField(
mode... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-02-07 20:53
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('basket', '0002_basketitem_product'),
]
operations = [
migrations.RenameField(
... | mit | Python |
20003796eb8f3949d931a4b8752fb07f2be39136 | Update utils.py | lk-geimfari/mimesis,lk-geimfari/elizabeth,lk-geimfari/mimesis,lk-geimfari/church,wikkiewikkie/elizabeth | church/utils.py | church/utils.py | from functools import lru_cache
from os.path import (
join,
dirname,
abspath
)
PATH = abspath(join(dirname(__file__), 'data'))
@lru_cache(maxsize=None)
def pull(filename, lang='en_us'):
"""
Function for getting data from text files in data/
1. de_de - Folder for Germany.
2. en_us - Folde... | from functools import lru_cache
from os.path import (
join,
dirname,
abspath
)
PATH = abspath(join(dirname(__file__), 'data'))
__all__ = ['priest']
@lru_cache(maxsize=None)
def pull(filename, lang='en_us'):
"""
Function for getting data from text files in data/
1. de_de - Folder for Germany.... | mit | Python |
3c978eab962ed8a6158df2266852a1b1a47c4ec7 | add more terminal nodes | NCI-GDC/gdcdatamodel,NCI-GDC/gdcdatamodel | gdcdatamodel/query.py | gdcdatamodel/query.py | from psqlgraph import Node, Edge
traversals = {}
terminal_nodes = ['annotations', 'centers', 'archives', 'tissue_source_sites',
'files', 'related_files', 'describing_files',
'clinical_metadata_files', 'experiment_metadata_files', 'run_metadata_files',
'analysis_met... | from psqlgraph import Node, Edge
traversals = {}
terminal_nodes = ['annotations', 'centers', 'archives', 'tissue_source_sites',
'files', 'related_files', 'describing_files']
def construct_traversals(root, node, visited, path):
recurse = lambda neighbor: (
neighbor
# no backtrack... | apache-2.0 | Python |
7c6c8e9ed2b89c7fa15992b5b68c793a53b327d8 | fix test case to run on_commit hook before assertion | RegioHelden/django-datawatch,RegioHelden/django-datawatch | django_datawatch/tests/test_trigger_update.py | django_datawatch/tests/test_trigger_update.py | # -*- coding: UTF-8 -*-
from __future__ import unicode_literals, print_function
try:
from unittest import mock
except ImportError:
import mock
from django.db import transaction
from django.test.testcases import TestCase, override_settings
from django_datawatch.backends.base import BaseBackend
from django_dat... | # -*- coding: UTF-8 -*-
from __future__ import unicode_literals, print_function
from django_datawatch.backends.base import BaseBackend
try:
from unittest import mock
except ImportError:
import mock
from django.test.testcases import TestCase, override_settings
from django_datawatch.datawatch import datawatch... | mit | Python |
2323699ae6b266823b30784293b2d1d900d94700 | Bump aioTV version. | aioTV/django-rest-swagger,aioTV/django-rest-swagger,aioTV/django-rest-swagger | rest_framework_swagger/__init__.py | rest_framework_swagger/__init__.py | VERSION = '0.3.5-aio-v3'
DEFAULT_SWAGGER_SETTINGS = {
'exclude_namespaces': [],
'api_version': '',
'api_key': '',
'token_type': 'Token',
'enabled_methods': ['get', 'post', 'put', 'patch', 'delete'],
'is_authenticated': False,
'is_superuser': False,
'permission_denied_handler': None,
... | VERSION = '0.3.5-aio-v2'
DEFAULT_SWAGGER_SETTINGS = {
'exclude_namespaces': [],
'api_version': '',
'api_key': '',
'token_type': 'Token',
'enabled_methods': ['get', 'post', 'put', 'patch', 'delete'],
'is_authenticated': False,
'is_superuser': False,
'permission_denied_handler': None,
... | bsd-2-clause | Python |
00bf40ba386d7d1ffebcc1a41766250e0fc975ac | Add related name fields | DavidJFelix/hatchit,DavidJFelix/hatchit,DavidJFelix/hatchit | src/core/models/base.py | src/core/models/base.py | from django.db import models
from django.contrib.auth.models import User
class Location(models.Model):
class Meta:
app_label = "core"
x = models.DecimalField(max_digits=10, decimal_places=5)
y = models.DecimalField(max_digits=10, decimal_places=5)
def __str__(self):
return "x:" + str(self.x) + ", y:" + str... | from django.db import models
from django.contrib.auth.models import User
class Location(models.Model):
class Meta:
app_label = "core"
x = models.DecimalField(max_digits=10, decimal_places=5)
y = models.DecimalField(max_digits=10, decimal_places=5)
def __str__(self):
return "x:" + str(self.x) + ", y:" + str... | agpl-3.0 | Python |
2edb2145f6f7447a7c659d7eeb51c7b75aa0c6d4 | Add generate username signal | allanlei/rhinocloud-utils | rhinocloud/contrib/auth/signals.py | rhinocloud/contrib/auth/signals.py | from django.contrib.auth.models import User
from rhinocloud.utils import random_generator
def generate_username_from_email(sender, instance, **kwargs):
if sender == User:
username = instance.email
if len(username) > 30:
username = random_generator(username[:25])
instance.userna... | from django.contrib.auth.models import User
from rhinocloud.utils import random_generator
def username_shorten(sender, instance, **kwargs):
if sender == User:
if len(instance.username) > 30:
instance.username = random_generator(instance.username[:25])
def first_name_shorten(sender, instance, ... | bsd-3-clause | Python |
a390800d3ee510a7e8d2d26bf1b44d1b735808cf | sort import | nansencenter/DAPPER,nansencenter/DAPPER | dapper/mods/VL20/demo.py | dapper/mods/VL20/demo.py | """Demonstrate the Vissio-Lucarini-20 model.
Reproduce Hovmoller diagram Fig 4. in `bib.vissio2020mechanics`.
"""
import numpy as np
from matplotlib import pyplot as plt
import dapper.mods as modelling
from dapper.mods.VL20 import model_instance
VL20 = model_instance(nX=36, F=10, G=0)
step = modelling.with_rk4(VL20.... | """Demonstrate the Vissio-Lucarini-20 model.
Reproduce Hovmoller diagram Fig 4. in `bib.vissio2020mechanics`.
"""
import numpy as np
from matplotlib import pyplot as plt
import dapper.mods as modelling
from dapper.mods.VL20 import model_instance
VL20 = model_instance(nX=36, F=10, G=0)
step = modelling.with_rk4(VL20... | mit | Python |
916638e11ef20e2976c81f0e8230079cf96a3c3a | Set DJANGO_SETTINGS_MODULE env variable. | parksandwildlife/ibms,parksandwildlife/ibms,parksandwildlife/ibms | ibms_project/wsgi.py | ibms_project/wsgi.py | """
WSGI config for IBMS project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import dotenv
from django.core.wsgi import get_wsgi_application
import os
from pathlib import Path
# These lines are required for interoperability between local and container environments.
d = Path(__fi... | """
WSGI config for IBMS project.
It exposes the WSGI callable as a module-level variable named ``application``.
"""
import dotenv
from django.core.wsgi import get_wsgi_application
import os
from pathlib import Path
# These lines are required for interoperability between local and container environments.
d = Path(__fi... | apache-2.0 | Python |
2636d76fa4d9dd820fd673bc6044f4c3ccdfd0b1 | Fix permissions fixture problem. | 4dn-dcic/fourfront,kidaa/encoded,T2DREAM/t2dream-portal,ClinGen/clincoded,ENCODE-DCC/encoded,4dn-dcic/fourfront,philiptzou/clincoded,philiptzou/clincoded,hms-dbmi/fourfront,kidaa/encoded,kidaa/encoded,hms-dbmi/fourfront,ENCODE-DCC/snovault,philiptzou/clincoded,kidaa/encoded,ENCODE-DCC/encoded,T2DREAM/t2dream-portal,phi... | src/encoded/tests/test_permissions.py | src/encoded/tests/test_permissions.py | import pytest
@pytest.fixture
def users(testapp):
from .sample_data import URL_COLLECTION
url = '/labs/'
for item in URL_COLLECTION[url]:
res = testapp.post_json(url, item, status=201)
url = '/awards/'
for item in URL_COLLECTION[url]:
res = testapp.post_json(url, item, status=201)
... | import pytest
@pytest.datafixture
def users(app):
from webtest import TestApp
environ = {
'HTTP_ACCEPT': 'application/json',
'REMOTE_USER': 'TEST',
}
testapp = TestApp(app, environ)
from .sample_data import URL_COLLECTION
url = '/labs/'
for item in URL_COLLECTION[url]:
... | mit | Python |
d51a13ed70c157d90c2d77461ad1747f7ce12e7c | Improve comment syntax | openfisca/country-template,openfisca/country-template | openfisca_country_template/variables/taxes.py | openfisca_country_template/variables/taxes.py | # -*- coding: utf-8 -*-
# This file defines the variables of our legislation.
# A variable is property of a person, or an entity (e.g. a household).
# See http://openfisca.org/doc/variables.html
# Import from openfisca-core the common python objects used to code the legislation in OpenFisca
from openfisca_core.model_... | # -*- coding: utf-8 -*-
# This file defines the variables of our legislation.
# A variable is property of a person, or an entity (e.g. a household).
# See http://openfisca.org/doc/variables.html
# Import from openfisca-core the common python objects used to code the legislation in OpenFisca
from openfisca_core.model_... | agpl-3.0 | Python |
da1df870f5d5b7703c4c4c3a6b8cb7d140778469 | Set default task target to 100. | VISTAS-IVES/pyvistas | source/vistas/core/task.py | source/vistas/core/task.py | from threading import RLock
class Task:
STOPPED = 'stopped'
RUNNING = 'running'
INDETERMINATE = 'indeterminate'
COMPLETE = 'complete'
SHOULD_STOP = 'should_stop'
tasks = []
def __init__(self, name, description=None, target=100, progress=0):
self.name = name
self.descripti... | from threading import RLock
class Task:
STOPPED = 'stopped'
RUNNING = 'running'
INDETERMINATE = 'indeterminate'
COMPLETE = 'complete'
SHOULD_STOP = 'should_stop'
tasks = []
def __init__(self, name, description=None, target=0, progress=0):
self.name = name
self.description... | bsd-3-clause | Python |
285d5f43b112354f1d5c05f9dd6b050e30f517e4 | Remove country=DE parameter | DenisCarriere/geocoder | geocoder/gisgraphy.py | geocoder/gisgraphy.py | #!/usr/bin/python
# coding: utf8
from __future__ import absolute_import
import logging
from geocoder.location import BBox
from geocoder.base import OneResult, MultipleResultsQuery
class GisgraphyResult(OneResult):
@property
def lat(self):
return self.raw.get('lat')
@property
def lng(se... | #!/usr/bin/python
# coding: utf8
from __future__ import absolute_import
import logging
from geocoder.location import BBox
from geocoder.base import OneResult, MultipleResultsQuery
class GisgraphyResult(OneResult):
@property
def lat(self):
return self.raw.get('lat')
@property
def lng(se... | mit | Python |
6d9efe005e346aaef359f369c89d007da1b83189 | add more untested changes for slack integration | nuxis/lamper,nuxis/lamper | lampeflaske.py | lampeflaske.py | #!/usr/bin/env python3
import pprint
import os
import lamper
from flask import Flask, request, jsonify
from flask_api import status
app = Flask(__name__)
@app.route("/", methods=['POST', 'GET'])
def hello():
pprint.pprint(request.form)
if request.form.get('command') != '/lamper':
return "wrong com... | #!/usr/bin/env python3
import pprint
import os
import lamper
from flask import Flask, request
from flask_api import status
app = Flask(__name__)
@app.route("/", methods=['POST', 'GET'])
def hello():
pprint.pprint(request.form)
if request.form.get('command') != '/lamper':
return "wrong command" , s... | mit | Python |
1f9dea20b433e5b2a69f348d1a842d71a99bc56e | Modify tests | chainer/chainer,hvy/chainer,hvy/chainer,niboshi/chainer,chainer/chainer,wkentaro/chainer,hvy/chainer,niboshi/chainer,hvy/chainer,wkentaro/chainer,wkentaro/chainer,pfnet/chainer,wkentaro/chainer,niboshi/chainer,niboshi/chainer,chainer/chainer,chainer/chainer | tests/chainerx_tests/unit_tests/routines_tests/test_evaluation.py | tests/chainerx_tests/unit_tests/routines_tests/test_evaluation.py | import chainer
from chainer import functions as F
import numpy
import chainerx
from chainerx_tests import dtype_utils
from chainerx_tests import op_utils
_in_out_eval_dtypes = [
(('float16', 'int16'), 'float32'),
(('float32', 'int32'), 'float32'),
(('float64', 'int64'), 'float64'),
(('float32', 'int... | import chainer
from chainer import functions as F
import numpy
import chainerx
from chainerx_tests import dtype_utils
from chainerx_tests import op_utils
_in_out_eval_dtypes = dtype_utils._permutate_dtype_mapping([
(('float16', 'float16'), 'float16'),
(('float32', 'float32'), 'float32'),
(('float64', 'f... | mit | Python |
9963642c1cc05fb6d9dfe397b9ed811d4f7e3d26 | add 4.6.1 and 3.10.1 (#24701) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/py-importlib-metadata/package.py | var/spack/repos/builtin/packages/py-importlib-metadata/package.py | # Copyright 2013-2021 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 PyImportlibMetadata(PythonPackage):
"""Read metadata from Python packages."""
homepag... | # Copyright 2013-2021 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 PyImportlibMetadata(PythonPackage):
"""Read metadata from Python packages."""
homepag... | lgpl-2.1 | Python |
a2749190545a6765a479777b1ea97d2f9090593f | clean up project config a bit | propublica/cookcountyjail2,propublica/cookcountyjail2,propublica/cookcountyjail2 | jailscraper/project_config.py | jailscraper/project_config.py | """ProPublica specific configuration and utilities"""
import boto3
import botocore
import os
### Helpers
def get_secrets():
"""Get all environment variables associated with this project.
Reads environment variables that start with PROJECT_SLUG, strips out the slug
and adds them to a dictionary.
"""
... | """ProPublica specific configuration and utilities"""
import os
PROJECT_SLUG = 'cookcountyjail2'
INMATE_URL_TEMPLATE = 'http://www2.cookcountysheriff.org/search2/details.asp?jailnumber={0}'
"""Sets the maximum jail number to scan for by default.
If the subsequent jail number returns a 2xx status code, it will be inc... | mit | Python |
9f531eec31e141b458c4c7896bebb16611cc7b00 | Refactor calories plugin (#503) | sukeesh/Jarvis,sukeesh/Jarvis,sukeesh/Jarvis,appi147/Jarvis,sukeesh/Jarvis,appi147/Jarvis | jarviscli/plugins/calories.py | jarviscli/plugins/calories.py | from plugin import plugin
from colorama import Back, Fore, Style
@plugin("calories")
class calories:
"""
Tells the recommended daily calorie intake, also recommends
calories for weight add and loss.(Source 1)
It is based on gender, age, height and weight.
Uses the Miffin-St Jeor Equation as it is ... | from plugin import plugin
@plugin("calories")
def calories(jarvis, s):
"""
Tells the recommended daily calorie intake, also recommends
calories for weight add and loss.(Source 1)
It is based on gender, age, height and weight.
Uses the Miffin-St Jeor Equation as it is considered the
most accura... | mit | Python |
dde62362955ca4b10f3c1fec4e3b7777b03141f5 | remove ContextDict since std has ChainMap | Jasily/jasily-python,Cologler/py.jasily.cologler | jasily/collection/__init__.py | jasily/collection/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com>
# ----------
#
# ----------
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com>
# ----------
#
# ----------
from collections import KeysView, ValuesView, ItemsView, MutableMapping
_NO_VALUE = object()
class ContextDict(MutableMapping):
'''context dict can override base_dict.'''
def ... | mit | Python |
bca2ea9c72669c4877d6c9be74a2c58f8341ce61 | Update Portuguese lexical attributes | spacy-io/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,honnibal/spaCy,explosion/spaCy,recognai/spaCy,recognai/spaCy,explosion/spaCy,aikramer2/spaCy,spacy-io/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,aikramer2/sp... | spacy/lang/pt/lex_attrs.py | spacy/lang/pt/lex_attrs.py | # coding: utf8
from __future__ import unicode_literals
from ...attrs import LIKE_NUM
_num_words = ['zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete',
'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'catorze',
'quinze', 'dezasseis', 'dezassete', 'dezoito', 'dezanove', 'vinte'... | # coding: utf8
from __future__ import unicode_literals
# Number words
NUM_WORDS = set("""
zero um dois três quatro cinco seis sete oito nove dez onze doze treze catorze
quinze dezasseis dezassete dezoito dezanove vinte trinta quarenta cinquenta
sessenta setenta oitenta noventa cem mil milhão bilião trilião quadriliã... | mit | Python |
e635d6a1c4ca8c138a5bd288250f94bcd82bb8a8 | Remove unnecessary imports. | hjanime/VisTrails,Nikea/VisTrails,hjanime/VisTrails,hjanime/VisTrails,VisTrails/VisTrails,celiafish/VisTrails,celiafish/VisTrails,minesense/VisTrails,hjanime/VisTrails,minesense/VisTrails,Nikea/VisTrails,minesense/VisTrails,celiafish/VisTrails,VisTrails/VisTrails,VisTrails/VisTrails,Nikea/VisTrails,VisTrails/VisTrails,... | vistrails/tests/resources/upgrades/init.py | vistrails/tests/resources/upgrades/init.py | from vistrails.core.modules.vistrails_module import Module
from vistrails.core.modules.config import IPort, OPort
from vistrails.core.upgradeworkflow import UpgradeModuleRemap
class TestUpgradeA(Module):
_input_ports = [IPort("aaa", "basic:String")]
_output_ports = [OPort("zzz", "basic:Integer")]
class TestU... | from vistrails.core.modules.vistrails_module import Module
from vistrails.core.modules.config import IPort, OPort
from vistrails.core.upgradeworkflow import UpgradeWorkflowHandler, \
UpgradePackageRemap, UpgradeModuleRemap
class TestUpgradeA(Module):
_input_ports = [IPort("aaa", "basic:String")]
_output_po... | bsd-3-clause | Python |
a2b19e7fd6b0004e4fa18b6d1b20f7347ca1964c | Fix wrong indentation | kelwang/pan-baidu-download,banbanchs/pan-baidu-download | command/export.py | command/export.py | #!/usr/bin/env python2
# coding=utf-8
import json
import urllib2
import logging
import base64
from config import global_config
from bddown_core import Pan, GetFilenameError
def export(links):
for link in links:
pan = Pan(link)
count = 1
while count != 0:
link, filename, count... | #!/usr/bin/env python2
# coding=utf-8
import json
import urllib2
import logging
import base64
from config import global_config
from bddown_core import Pan, GetFilenameError
def export(links):
for link in links:
pan = Pan(link)
count = 1
while count != 0:
link, filename, count... | mit | Python |
920872db456987e5bd5002b3bf3fc2168dcbdff4 | fix name | tomi77/python-t77-django | django_extra_tools/conf/defaults.py | django_extra_tools/conf/defaults.py | """Default configuration"""
# auth.backends.ThroughSuperuserModelBackend username separator
AUTH_BACKEND_USERNAME_SEPARATOR = ':'
XHR_MIDDLEWARE_ALLOWED_ORIGINS = '*'
XHR_MIDDLEWARE_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
XHR_MIDDLEWARE_ALLOWED_HEADERS = ['Content-Type', 'Authorization', 'Locati... | """Default configuration"""
# auth.backends.SuperUserAuthenticateMixin username separator
AUTH_BACKEND_USERNAME_SEPARATOR = ':'
XHR_MIDDLEWARE_ALLOWED_ORIGINS = '*'
XHR_MIDDLEWARE_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
XHR_MIDDLEWARE_ALLOWED_HEADERS = ['Content-Type', 'Authorization', 'Location... | mit | Python |
a4a01c466c916f5c4ff44d40bc5e052e98951f1d | Bump version | thombashi/sqlitebiter,thombashi/sqlitebiter | sqlitebiter/__version__.py | sqlitebiter/__version__.py | __author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016, {}".format(__author__)
__license__ = "MIT License"
__version__ = "0.29.1"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| __author__ = "Tsuyoshi Hombashi"
__copyright__ = "Copyright 2016, {}".format(__author__)
__license__ = "MIT License"
__version__ = "0.29.0"
__maintainer__ = __author__
__email__ = "tsuyoshi.hombashi@gmail.com"
| mit | Python |
05458457f12618cc69970cd2bda87e25e29384a4 | simplify the code (Thx Stefan) | Midafi/scikit-image,bsipocz/scikit-image,michaelpacer/scikit-image,SamHames/scikit-image,keflavich/scikit-image,ofgulban/scikit-image,juliusbierk/scikit-image,vighneshbirodkar/scikit-image,emon10005/scikit-image,warmspringwinds/scikit-image,dpshelio/scikit-image,robintw/scikit-image,SamHames/scikit-image,ofgulban/sciki... | doc/examples/plot_peak_local_max.py | doc/examples/plot_peak_local_max.py | """
====================
Finding local maxima
====================
The ``peak_local_max`` function returns the coordinates of local peaks (maxima)
in an image. A maximum filter is used for finding local maxima. This operation
dilates the original image and merges neighboring local maxima closer than the
size of the di... | """
====================
Finding local maxima
====================
The ``peak_local_max`` function returns the coordinates of local peaks (maxima)
in an image. A maximum filter is used for finding local maxima. This operation
dilates the original image and merges neighboring local maxima closer than the
size of the di... | bsd-3-clause | Python |
e00a82a31de820f28474cb5de47c5715dafd8d18 | use the largest remainder method for distributing change in ratio_split() | adamcharnock/django-hordak,adamcharnock/django-hordak | hordak/utilities/money.py | hordak/utilities/money.py | from decimal import Decimal
from hordak.defaults import DECIMAL_PLACES
def ratio_split(amount, ratios):
""" Split in_value according to the ratios specified in `ratios`
This is special in that it ensures the returned values always sum to
in_value (i.e. we avoid losses or gains due to rounding errors). As... | from decimal import Decimal
def ratio_split(amount, ratios):
""" Split in_value according to the ratios specified in `ratios`
This is special in that it ensures the returned values always sum to
in_value (i.e. we avoid losses or gains due to rounding errors). As a
result, this method returns a list o... | mit | Python |
29d151366d186ed75da947f2861741ed87af902b | Add missing import to settings | samchrisinger/osf.io,himanshuo/osf.io,jinluyuan/osf.io,chrisseto/osf.io,zachjanicki/osf.io,njantrania/osf.io,chrisseto/osf.io,reinaH/osf.io,billyhunt/osf.io,RomanZWang/osf.io,aaxelb/osf.io,arpitar/osf.io,mattclark/osf.io,sbt9uc/osf.io,jolene-esposito/osf.io,rdhyee/osf.io,amyshi188/osf.io,kwierman/osf.io,njantrania/osf.... | website/addons/badges/settings/__init__.py | website/addons/badges/settings/__init__.py | # -*- coding: utf-8 -*-
import logging
from .defaults import * # noqa
logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
logger.warn('No local.py settings file found')
| from .defaults import * # noqa
logger = logging.getLogger(__name__)
try:
from .local import * # noqa
except ImportError as error:
logger.warn('No local.py settings file found')
| apache-2.0 | Python |
6c64674447bd988eef80a4a927acde2eabe04236 | Modify error messag | googkit/googkit,googkit/googkit,googkit/googkit | googkit/lib/plugin.py | googkit/lib/plugin.py | import os
import googkit.lib.path
from googkit.lib.error import GoogkitError
INIT_FILE = '__init__.py'
COMMAND_FILE = 'command.py'
def load(tree):
base_dir = googkit.lib.path.plugin()
for filename in os.listdir(base_dir):
plugin_dir = os.path.join(base_dir, filename)
if not os.path.isdir(p... | import os
import googkit.lib.path
from googkit.lib.error import GoogkitError
INIT_FILE = '__init__.py'
COMMAND_FILE = 'command.py'
def load(tree):
base_dir = googkit.lib.path.plugin()
for filename in os.listdir(base_dir):
plugin_dir = os.path.join(base_dir, filename)
if not os.path.isdir(p... | mit | Python |
1b84cc660848fdee7ed68c17772542956f47e89d | Add `lower` parameter to grab.tools.russian::slugify method | kevinlondon/grab,alihalabyah/grab,liorvh/grab,kevinlondon/grab,giserh/grab,lorien/grab,giserh/grab,huiyi1990/grab,DDShadoww/grab,huiyi1990/grab,subeax/grab,codevlabs/grab,DDShadoww/grab,shaunstanislaus/grab,shaunstanislaus/grab,raybuhr/grab,istinspring/grab,codevlabs/grab,lorien/grab,istinspring/grab,liorvh/grab,pombre... | grab/tools/russian.py | grab/tools/russian.py | # coding: utf-8
from __future__ import absolute_import
from ..tools.encoding import smart_unicode
from pytils.translit import translify
import re
MONTH_NAMES = u'января февраля марта апреля мая июня июля августа '\
u'сентября октября ноября декабря'.split()
RE_NOT_ENCHAR = re.compile(u'[^-a-zA-Z0-9]', ... | # coding: utf-8
from __future__ import absolute_import
from ..tools.encoding import smart_unicode
from pytils.translit import translify
import re
MONTH_NAMES = u'января февраля марта апреля мая июня июля августа '\
u'сентября октября ноября декабря'.split()
RE_NOT_ENCHAR = re.compile(u'[^-a-zA-Z0-9]', ... | mit | Python |
959897478bbda18f02aa6e38f2ebdd837581f1f0 | Fix test for changed SctVerificationResult | theno/ctutlz,theno/ctutlz | tests/test_sct_verify_signature.py | tests/test_sct_verify_signature.py | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signa... | from os.path import join, dirname
from utlz import flo
from ctutlz.sct.verification import verify_signature
def test_verify_signature():
basedir = join(dirname(__file__), 'data', 'test_sct_verify_signature')
signature_input = \
open(flo('{basedir}/signature_input_valid.bin'), 'rb').read()
signa... | mit | Python |
9cb554c13ae3cec85fd2a3bf0afd9ae2b6cca96a | Refactor target.py | lstephen/construi | construi/target.py | construi/target.py |
import construi.console as console
from compose.project import Project
from compose.cli.docker_client import docker_client
import dockerpty
import sys
class Target(object):
def __init__(self, config):
self.config = config
self.project = Project.from_dicts(
'construi', config.service... |
import construi.console as console
from compose.project import Project
from compose.cli.docker_client import docker_client
import dockerpty
import sys
class Target(object):
def __init__(self, config):
self.config = config
self.project = Project.from_dicts(
'construi', config.service... | apache-2.0 | Python |
6b6d3779cd23c188c808387b9f4095ea75da3284 | Add a way to get the resources depended on by an output | openstack/heat,noironetworks/heat,openstack/heat,noironetworks/heat | heat/engine/output.py | heat/engine/output.py | #
# 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, software
# ... | #
# 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, software
# ... | apache-2.0 | Python |
74e4d69a6ab501e11ff266d1ad77992d0203729f | Include os stuff | CodingNinja/thumbor_rackspace | thumbor_rackspace/loaders/cloudfiles_loader.py | thumbor_rackspace/loaders/cloudfiles_loader.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2013 theiconic.com.au development@theiconic.com.au
from os.path import join, expanduser
import pyrax
def l... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2013 theiconic.com.au development@theiconic.com.au
import pyrax
def load(context, path, callback):
if(... | mit | Python |
d55210495fde133b8b76ee1f55e593dd43389e0e | Update to use new HTTP APIs. | wolftankk/livestreamer,mmetak/streamlink,wlerin/streamlink,jtsymon/livestreamer,Masaz-/livestreamer,streamlink/streamlink,melmorabity/streamlink,javiercantero/streamlink,Masaz-/livestreamer,chhe/livestreamer,Klaudit/livestreamer,wlerin/streamlink,caorong/livestreamer,ethanhlc/streamlink,fishscene/streamlink,caorong/liv... | src/livestreamer/plugins/ongamenet.py | src/livestreamer/plugins/ongamenet.py | from livestreamer.exceptions import NoStreamsError
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http
from livestreamer.stream import RTMPStream
import re
class Ongamenet(Plugin):
StreamURL = "http://dostream.lab.so/stream.php"
SWFURL = "http://www.ongamenet.com/front/ongame/live... | from livestreamer.compat import str, bytes
from livestreamer.exceptions import PluginError, NoStreamsError
from livestreamer.plugin import Plugin
from livestreamer.stream import RTMPStream
from livestreamer.utils import urlget
import re
class Ongamenet(Plugin):
StreamURL = "http://dostream.lab.so/stream.php"
... | bsd-2-clause | Python |
e78d613f66df5f10b59e47b6cfce619182d1297f | Update run.py | Terradue/dcs-python-ndvi | src/main/app-resources/py-ndvi/run.py | src/main/app-resources/py-ndvi/run.py | #!/usr/bin/env python
import site
import os
import sys
site.addsitedir('/application/share/python/lib/python2.6/site-packages')
#print sys.path
#os.environ['PYTHONUSERBASE'] = '/application/share/python'
#print 'Base:', site.USER_BASE
#print 'Site:', site.USER_SITE
import ndvi
sys.path.append('/usr/lib/ciop/python/... | #!/usr/bin/env python
import site
import os
import sys
site.addsitedir('/application/share/python/lib/python2.6/site-packages')
#print sys.path
#os.environ['PYTHONUSERBASE'] = '/application/share/python'
#print 'Base:', site.USER_BASE
#print 'Site:', site.USER_SITE
import ndvi
sys.path.append('/usr/lib/ciop/python/... | apache-2.0 | Python |
0048794fd6e71f58bf88d84ddefb1e9a0194efca | Fix the mock-image used in test-steps unittests. | transientskp/tkp,mkuiack/tkp,mkuiack/tkp,transientskp/tkp,bartscheers/tkp,bartscheers/tkp | tests/test_steps/test_source_extraction.py | tests/test_steps/test_source_extraction.py | import unittest
import numpy as np
from tkp.testutil import db_subs, data
from ConfigParser import SafeConfigParser
from tkp.config import parse_to_dict
from tkp.testutil.data import default_job_config
from tkp.testutil import Mock
import tkp.steps.source_extraction
import tkp.accessors
class MockImage(Mock):
def... | import unittest
from tkp.testutil import db_subs, data
from ConfigParser import SafeConfigParser
from tkp.config import parse_to_dict
from tkp.testutil.data import default_job_config
from tkp.testutil import Mock
import tkp.steps.source_extraction
import tkp.accessors
class MockImage(Mock):
def extract(self, *args... | bsd-2-clause | Python |
edf1e96e56272a10ad767f13e6e8cc886f98055c | Test consecutive Coordinator.heartbeat calls #17 | numberoverzero/bloop,numberoverzero/bloop | tests/unit/test_stream/test_coordinator.py | tests/unit/test_stream/test_coordinator.py | import functools
from bloop.stream.shard import Shard
from . import build_get_records_responses
def test_coordinator_repr(coordinator):
coordinator.stream_arn = "repr-stream-arn"
assert repr(coordinator) == "<Coordinator[repr-stream-arn]>"
def test_heartbeat(coordinator, session):
find_records_id = "id-... | import functools
from bloop.stream.shard import Shard
from . import build_get_records_responses
def test_coordinator_repr(coordinator):
coordinator.stream_arn = "repr-stream-arn"
assert repr(coordinator) == "<Coordinator[repr-stream-arn]>"
def test_heartbeat_latest(coordinator, session):
find_records_id... | mit | Python |
213d6a42d505fb7ca320873cafdc187cf65d10ed | add unit tests for escaping curlies | pypyr/pypyr-cli,pypyr/pypyr-cli | tests/unit/pypyr/format/string_test.py | tests/unit/pypyr/format/string_test.py | """"string.py unit tests."""
import pypyr.format.string
import pytest
def test_string_interpolate_works():
context = {'key1': 'down', 'key2': 'valleys', 'key3': 'value3'}
input_string = 'Piping {key1} the {key2} wild'
output = pypyr.format.string.get_interpolated_string(input_string, context)
assert ... | """"string.py unit tests."""
import pypyr.format.string
import pytest
def test_string_interpolate_works():
context = {'key1': 'down', 'key2': 'valleys', 'key3': 'value3'}
input_string = 'Piping {key1} the {key2} wild'
output = pypyr.format.string.get_interpolated_string(input_string, context)
assert ... | apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.