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 |
|---|---|---|---|---|---|---|---|---|---|
82756e5314c2768bb3acf03cf542929d23b73f82 | bot/logger/message_sender/synchronized.py | bot/logger/message_sender/synchronized.py | import threading
from bot.logger.message_sender import MessageSender, IntermediateMessageSender
class SynchronizedMessageSender(IntermediateMessageSender):
"""
Thread-safe message sender.
Wrap your `MessageSender` with this class and its :func:`send` function will be called in a synchronized way,
on... | import threading
from bot.logger.message_sender import MessageSender, IntermediateMessageSender
class SynchronizedMessageSender(IntermediateMessageSender):
"""
Thread-safe message sender.
Wrap your `MessageSender` with this class and its :func:`send` function will be called in a synchronized way,
on... | Use reentrant lock on SynchronizedMessageSender | Use reentrant lock on SynchronizedMessageSender
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot |
721703801654af88e8b5064d1bc65569ce1555cf | thumbnails/engines/__init__.py | thumbnails/engines/__init__.py | # -*- coding: utf-8 -*-
def get_current_engine():
return None
| # -*- coding: utf-8 -*-
from thumbnails.engines.pillow import PillowEngine
def get_current_engine():
return PillowEngine()
| Set pillow engine as default | Set pillow engine as default
| Python | mit | python-thumbnails/python-thumbnails,relekang/python-thumbnails |
4c1b96865f3e5e6660fc41f9170939a02f9b7735 | fabfile.py | fabfile.py | from fabric.api import *
from fabric.contrib.console import confirm
cfg = dict(
appengine_dir='appengine-web/src',
goldquest_dir='src',
appengine_token='',
)
def update():
# update to latest code from repo
local('git pull')
def test():
local("nosetests -m 'Test|test_' -w %(goldquest_dir)s" %... | from fabric.api import *
from fabric.contrib.console import confirm
import simplejson
cfg = dict(
appengine_dir='appengine-web/src',
goldquest_dir='src',
oauth_cfg_path='/Users/olle/.appcfg_oauth2_tokens',
appengine_refresh_token='',
)
def read_appcfg_oauth():
fp = open(cfg['oauth_cfg_path'])
... | Read appengine refresh_token from oauth file automatically. | NEW: Read appengine refresh_token from oauth file automatically.
| Python | mit | ollej/GoldQuest,ollej/GoldQuest,ollej/GoldQuest,ollej/GoldQuest |
670227590ceaf6eb52d56809f8bcc1b1f6ae6f7f | prettyplotlib/_eventplot.py | prettyplotlib/_eventplot.py | __author__ = 'jgosmann'
from matplotlib.cbook import iterable
from prettyplotlib.utils import remove_chartjunk, maybe_get_ax
from prettyplotlib.colors import set2
def eventplot(*args, **kwargs):
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
show_ticks = kwargs.pop('show_ticks', False)
if len(args) >... | __author__ = 'jgosmann'
from matplotlib.cbook import iterable
from prettyplotlib.utils import remove_chartjunk, maybe_get_ax
from prettyplotlib.colors import set2
def eventplot(*args, **kwargs):
ax, args, kwargs = maybe_get_ax(*args, **kwargs)
show_ticks = kwargs.pop('show_ticks', False)
alpha = kwargs.... | Add alpha argument to eventplot(). | Add alpha argument to eventplot().
| Python | mit | olgabot/prettyplotlib,olgabot/prettyplotlib |
c814fe264c93dfa09276474960aa83cdb26e7754 | polyaxon/api/searches/serializers.py | polyaxon/api/searches/serializers.py | from rest_framework import serializers
from db.models.searches import Search
class SearchSerializer(serializers.ModelSerializer):
class Meta:
model = Search
fields = ['id', 'name', 'query', 'meta']
| from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from api.utils.serializers.names import NamesMixin
from db.models.searches import Search
class SearchSerializer(serializers.ModelSerializer, NamesMixin):
class Meta:
model = Search
fields = ['id', 'name',... | Add graceful handling for creating search with similar names | Add graceful handling for creating search with similar names
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
e459a42af1c260986c7333047efd40294dbd23d3 | akaudit/clidriver.py | akaudit/clidriver.py | #!/usr/bin/env python
# Copyright 2015 Chris Fordham
#
# 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 ... | #!/usr/bin/env python
# Copyright 2015 Chris Fordham
#
# 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 ... | Use __description__ with parser instantiation. | Use __description__ with parser instantiation.
| Python | apache-2.0 | flaccid/akaudit |
d90f249e0865dab0cc9a224f413ea90df8a648ed | srsly/util.py | srsly/util.py | from pathlib import Path
from typing import Union, Dict, Any, List, Tuple
from collections import OrderedDict
# fmt: off
FilePath = Union[str, Path]
# Superficial JSON input/output types
# https://github.com/python/typing/issues/182#issuecomment-186684288
JSONOutput = Union[str, int, float, bool, None, Dict[str, Any]... | from pathlib import Path
from typing import Union, Dict, Any, List, Tuple
from collections import OrderedDict
# fmt: off
FilePath = Union[str, Path]
# Superficial JSON input/output types
# https://github.com/python/typing/issues/182#issuecomment-186684288
JSONOutput = Union[str, int, float, bool, None, Dict[str, Any]... | Fix typing for JSONInput and JSONInputBin. | Fix typing for JSONInput and JSONInputBin.
| Python | mit | explosion/srsly,explosion/srsly,explosion/srsly,explosion/srsly |
20e096ac5261cb7fd4197f6cdeb8b171753c82a7 | landlab/values/tests/conftest.py | landlab/values/tests/conftest.py | import pytest
from landlab import NetworkModelGrid, RasterModelGrid
@pytest.fixture
def four_by_four_raster():
mg = RasterModelGrid((4, 4))
return mg
@pytest.fixture
def simple_network():
y_of_node = (0, 1, 2, 2)
x_of_node = (0, 0, -1, 1)
nodes_at_link = ((1, 0), (2, 1), (3, 1))
mg = Networ... | import pytest
from landlab import NetworkModelGrid, RasterModelGrid
from landlab.values.synthetic import _STATUS
@pytest.fixture
def four_by_four_raster():
mg = RasterModelGrid((4, 4))
return mg
@pytest.fixture
def simple_network():
y_of_node = (0, 1, 2, 2)
x_of_node = (0, 0, -1, 1)
nodes_at_li... | Add parametrized fixture for at, node_bc, link_bc. | Add parametrized fixture for at, node_bc, link_bc.
| Python | mit | landlab/landlab,cmshobe/landlab,landlab/landlab,cmshobe/landlab,amandersillinois/landlab,landlab/landlab,amandersillinois/landlab,cmshobe/landlab |
bcde8104bd77f18d7061f7f4d4831ad49644a913 | common/management/commands/build_index.py | common/management/commands/build_index.py | from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
acti... | from django.core.management import BaseCommand
from django.db.models import get_app, get_models
from django.conf import settings
from common.utilities.search_utils import index_instance
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
'--test',
acti... | Check the model beig indexed | Check the model beig indexed
| Python | mit | urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,MasterFacilityList/mfl_api,urandu/mfl_api,urandu/mfl_api |
ccb1759a205a4cdc8f5eb2c28adcf49503221135 | ecpy/tasks/api.py | ecpy/tasks/api.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015 by Ecpy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------------... | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015 by Ecpy Authors, see AUTHORS for more details.
#
# Distributed under the terms of the BSD license.
#
# The full license is in the file LICENCE, distributed with this software.
# ---------------------... | Add tasks/build_from_config to the public API. | Add tasks/build_from_config to the public API.
| Python | bsd-3-clause | Ecpy/ecpy,Ecpy/ecpy |
7e15896c14cbbab36862c8000b0c25c6a48fedcd | cref/structure/__init__.py | cref/structure/__init__.py | # import porter_paleale
def write_pdb(aa_sequence, fragment_angles, gap_length, filepath):
"""
Generate pdb file with results
:param aa_sequence: Amino acid sequence
:param fragment_angles: Backbone torsion angles
:param gap_length: Length of the gap at the sequence start and end
:param fil... | from peptide import PeptideBuilder
import Bio.PDB
def write_pdb(aa_sequence, fragment_angles, gap_length, filepath):
"""
Generate pdb file with results
:param aa_sequence: Amino acid sequence
:param fragment_angles: Backbone torsion angles
:param gap_length: Length of the gap at the sequence star... | Write pdb result to disk | Write pdb result to disk
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 |
810a43c859264e3d5e1af8b43888bf89c06bee1d | ipybind/stream.py | ipybind/stream.py | # -*- coding: utf-8 -*-
import contextlib
import sys
try:
import fcntl
except ImportError:
fcntl = None
from ipybind.common import is_kernel
from ipybind.ext.wurlitzer import Wurlitzer
_fwd = None
class Forwarder(Wurlitzer):
def __init__(self, handler=None):
self._data_handler = handler if han... | # -*- coding: utf-8 -*-
import contextlib
import sys
try:
import fcntl
except ImportError:
fcntl = None
from ipybind.common import is_kernel
from ipybind.ext.wurlitzer import Wurlitzer
_fwd = None
class Forwarder(Wurlitzer):
def __init__(self, handler=None):
self._data_handler = handler if han... | Remove suppress() as it's no longer required | Remove suppress() as it's no longer required
| Python | mit | aldanor/ipybind,aldanor/ipybind,aldanor/ipybind |
db19dfa17261c3d04de0202b2809ba8abb70326b | tests/unit/test_moxstubout.py | tests/unit/test_moxstubout.py | # Copyright 2014 IBM Corp.
#
# 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 t... | # Copyright 2014 IBM Corp.
#
# 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 t... | Fix build break with Fixtures 1.3 | Fix build break with Fixtures 1.3
Our explicit call to cleanUp messes things up in latest
fixture, so we need to call _clear_cleanups to stop
the test from breaking
Change-Id: I8ce2309a94736b47fb347f37ab4027857e19c8a8
| Python | apache-2.0 | openstack/oslotest,openstack/oslotest |
5ac84c4e9d8d68b7e89ebf344d2c93a5f7ef4c4c | notebooks/galapagos_to_pandas.py | notebooks/galapagos_to_pandas.py | # coding: utf-8
def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits',
out_filename=None):
"""Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file"""
from astropy.io import fits
import pandas as pd
import re
... | # coding: utf-8
def galapagos_to_pandas(in_filename='/home/ppzsb1/quickdata/GAMA_9_all_combined_gama_only_bd6.fits',
out_filename=None, bands='RUGIZYJHK'):
"""Convert a GALAPAGOS multi-band catalogue to a pandas-compatible HDF5 file"""
from astropy.io import fits
import pandas as pd... | Allow specification of GALAPAGOS bands | Allow specification of GALAPAGOS bands
| Python | mit | MegaMorph/megamorph-analysis |
3136f7e37b339252d4c1f5642974e180070c452d | kirppu/signals.py | kirppu/signals.py | # -*- coding: utf-8 -*-
from django.db.models.signals import pre_save, pre_delete
from django.dispatch import receiver
@receiver(pre_save)
def save_handler(sender, instance, using, **kwargs):
# noinspection PyProtectedMember
if instance._meta.app_label in ("kirppu", "kirppuauth") and using != "default":
... | # -*- coding: utf-8 -*-
from django.db.models.signals import pre_migrate, post_migrate
from django.dispatch import receiver
ENABLE_CHECK = True
@receiver(pre_migrate)
def pre_migrate_handler(*args, **kwargs):
global ENABLE_CHECK
ENABLE_CHECK = False
@receiver(post_migrate)
def post_migrate_handler(*args, ... | Allow migrations to be run on extra databases. | Allow migrations to be run on extra databases.
- Remove duplicate registration of save and delete signals. Already
registered in apps.
| Python | mit | jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,jlaunonen/kirppu |
a5baa5f333625244c1e0935745dadedb7df444c3 | setup.py | setup.py | #!/usr/bin/env python
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README... | #!/usr/bin/env python
import os
from distutils.core import setup
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='whack',
version='0.3.0',
description='Utility for installing binaries from source with a single command',
long_description=read("README... | Update install_requires to be more accurate | Update install_requires to be more accurate
| Python | bsd-2-clause | mwilliamson/whack |
fc6042cf57752ca139c52889ec5e00c02b618d0d | setup.py | setup.py | from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
... | from distutils.core import setup, Command
class PyTest(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py'])
... | Add api and model to packages | Add api and model to packages
| Python | mit | yamaneko1212/webpay-python |
a4cacaba81dda523fb6e24f8a4382a334cc549a8 | textinator.py | textinator.py | from PIL import Image
from os import get_terminal_size
default_palette = list('░▒▓█')
print(get_terminal_size())
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
"""
return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0]
def value_to_char(... | import click
from PIL import Image
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
"""
return ((val - src[0]) / (src[1]-src[0])) * (dst[1]-dst[0]) + dst[0]
def value_to_char(value, palette, value_range=(0, 256)):
palette_range = (0, len(palette))
... | Add commandline interface with Click. | Add commandline interface with Click.
| Python | mit | ijks/textinator |
1e68f5f1fd565a812ef3fdf10c4c40649e3ef398 | foundation/organisation/search_indexes.py | foundation/organisation/search_indexes.py | from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup
class PersonIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
url = indexes.CharField(model_attr='url')
... | from haystack import indexes
from .models import Person, Project, WorkingGroup, NetworkGroup
class PersonIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
twitter = indexes.CharField(model_attr='twitter')
url = indexes.CharField(model_attr='url')
... | Fix references to old model fields | organisation: Fix references to old model fields
| Python | mit | okfn/foundation,okfn/foundation,okfn/foundation,okfn/website,MjAbuz/foundation,okfn/website,okfn/foundation,okfn/website,okfn/website,MjAbuz/foundation,MjAbuz/foundation,MjAbuz/foundation |
82239a844462e721c7034ec42cb4905662f4efb4 | bin/mergeSegToCtm.py | bin/mergeSegToCtm.py | #!/usr/bin/python
# vim : set fileencoding=utf-8 :
#
# mergeSegToCtm.py
#
# Enhance the Bck file by adding extra fields with the diarisation
# information
#
import sys
with open(sys.argv[1], 'r', encoding='iso-8859-1') as seg:
with open(sys.argv[2], 'r', encoding='iso-8859-1') as ctm:
# For each frame, ... | #!/usr/bin/python
# vim : set fileencoding=utf-8 :
#
# mergeSegToCtm.py
#
# Enhance the CTM file by adding extra fields with the diarisation
# information
#
# First argument is the seg file
# Second argument is the ctm file
#
import sys
with open(sys.argv[1], 'r', encoding='iso-8859-1') as seg:
with open(sys.arg... | Fix typo in the script | Fix typo in the script
| Python | mit | SG-LIUM/SGL-SpeechWeb-Demo,SG-LIUM/SGL-SpeechWeb-Demo,bsalimi/speech-recognition-api,SG-LIUM/SGL-SpeechWeb-Demo,bsalimi/speech-recognition-api,bsalimi/speech-recognition-api,bsalimi/speech-recognition-api |
0ee59d04cb2cbe93a3f4f87a34725fbcd1a66fc0 | core/Reader.py | core/Reader.py | # coding: utf8
from io import StringIO
from collections import deque
class StreamReader:
def __init__(self, *args, stream_class=StringIO, **kwargs):
self.streamClass = stream_class
self.args = args
self.kwargs = kwargs
def read(self, parsing_pipeline):
parsing_pipeline.reset(... | # coding: utf8
from io import StringIO
from collections import deque
class StreamReader:
def __init__(self, *args, stream_class=StringIO, **kwargs):
self.streamClass = stream_class
self.args = args
self.kwargs = kwargs
def read(self, parsing_pipeline):
parsing_pipeline.reset(... | Add not enough characters condition | Add not enough characters condition
| Python | mit | JCH222/matriochkas |
6d32f609379febe2fdad690adc75a90e26b8d416 | backend/backend/serializers.py | backend/backend/serializers.py | from rest_framework import serializers
from .models import Animal
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = ('id', 'name', 'dob', 'gender', 'active', 'own', 'father', 'mother') | from rest_framework import serializers
from .models import Animal
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = ('id', 'name', 'dob', 'gender',
'active', 'own', 'father', 'mother')
def validate_father(self, father):
if (father... | Add validator that selected father is male and mother is female. Validate that the animal is younger than it's parents. | Add validator that selected father is male and mother is female.
Validate that the animal is younger than it's parents.
| Python | apache-2.0 | mmlado/animal_pairing,mmlado/animal_pairing |
f2cd1d531a1cefdc5da4b418c866be0d76aa349b | basil_common/str_support.py | basil_common/str_support.py |
def as_int(value):
try:
return int(value)
except ValueError:
return None
|
def as_int(value):
try:
return int(value)
except ValueError:
return None
def urljoin(*parts):
url = parts[0]
for p in parts[1:]:
if url[-1] != '/':
url += '/'
url += p
return url
| Add url join which serves our needs | Add url join which serves our needs
Existing functions in common libraries add extra slashes.
| Python | apache-2.0 | eve-basil/common |
a40c617ea605bd667a9906f6c9400fc9562d7c0a | salt/daemons/flo/reactor.py | salt/daemons/flo/reactor.py | # -*- coding: utf-8 -*-
'''
Start the reactor!
'''
# Import salt libs
import salt.utils.reactor
# Import ioflo libs
import ioflo.base.deeding
@ioflo.base.deeding.deedify(
'SaltRaetReactorFork',
ioinit={
'opts': '.salt.opts',
'proc_mgr': '.salt.usr.proc_mgr'})
def reactor_fork(s... | # -*- coding: utf-8 -*-
'''
Start the reactor!
'''
# Import salt libs
import salt.utils.reactor
import salt.utils.event
# Import ioflo libs
import ioflo.base.deeding
@ioflo.base.deeding.deedify(
'SaltRaetReactorFork',
ioinit={
'opts': '.salt.opts',
'proc_mgr': '.salt.usr.proc_m... | Add event return fork behavior | Add event return fork behavior
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
14e9bda5de10ef5a1c6dd96692d083f4e0f16025 | python/ql/test/experimental/library-tests/frameworks/yaml/Decoding.py | python/ql/test/experimental/library-tests/frameworks/yaml/Decoding.py | import yaml
from yaml import SafeLoader
yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.load(payload, SafeLoader) # $ decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML
yaml.load(payload, Loader=SafeLoader) # $decodeInput=payload decodeOutp... | import yaml
# Unsafe:
yaml.load(payload) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.load(payload, yaml.Loader) # $decodeInput=payload decodeOutput=Attribute() decodeFormat=YAML decodeMayExecuteInput
yaml.unsafe_load(payload) # $ decodeInput=payload decodeOutput=Attri... | Refactor PyYAML tests a bit | Python: Refactor PyYAML tests a bit
| Python | mit | 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 |
0997055c591d7bd4ad4334874292f8977ba778bf | cashew/exceptions.py | cashew/exceptions.py | class CashewException(Exception):
pass
class InternalCashewException(CashewException):
pass
class UserFeedback(CashewException):
pass
class InactivePlugin(UserFeedback):
def __init__(self, plugin_instance_or_alias):
if isinstance(plugin_instance_or_alias, basestring):
self.message... | class CashewException(Exception):
pass
class InternalCashewException(CashewException):
pass
class UserFeedback(CashewException):
pass
class InactivePlugin(UserFeedback):
def __init__(self, plugin_instance_or_alias):
if isinstance(plugin_instance_or_alias, basestring):
self.alias =... | Improve error message when alias not available. | Improve error message when alias not available.
| Python | mit | dexy/cashew |
2d82280460c50d50f6be8d8c8405506b4706cd8a | securethenews/blog/tests.py | securethenews/blog/tests.py | from django.test import TestCase
# Create your tests here.
| import datetime
from django.test import TestCase
from wagtail.wagtailcore.models import Page
from .models import BlogIndexPage, BlogPost
class BlogTest(TestCase):
def setUp(self):
home_page = Page.objects.get(slug='home')
blog_index_page = BlogIndexPage(
title='Blog',
s... | Add unit test to verify that blog posts are ordered by most recent | Add unit test to verify that blog posts are ordered by most recent
Verifies that blog posts are ordered by most recent first even if
the blog posts are posted on the same day.
| Python | agpl-3.0 | freedomofpress/securethenews,freedomofpress/securethenews,freedomofpress/securethenews,freedomofpress/securethenews |
42221c7b858951376ba59385fa42cac11d542fdd | plugin/script/sphinxexampleae.py | plugin/script/sphinxexampleae.py |
def process( node_name, handle ):
handle.editorTemplate( beginScrollLayout=True )
handle.editorTemplate( beginLayout="Float Attributes" )
handle.editorTemplate( "floatAttr", addControl=True )
handle.editorTemplate( endLayout=True )
handle.editorTemplate( addExtraControls=True )
handle.edito... |
float_attr_help = """
This is the *annotation* for the floatAttr attribute
Here are some bullet points pertaining to this attribute
- The help is written in rst
- I don't know what else to put in the list
"""
string_attr_help = """
This is the *annotation* for the stringAttr attribute
"""
def process( node_name, ... | Add another attribute and some annotations | Add another attribute and some annotations
We write the annotations in rst for the moment.
| Python | bsd-3-clause | michaeljones/sphinx-maya-node |
59030daa60a4d2006cae6192219071e2a8017364 | test/conftest.py | test/conftest.py | from os.path import join, dirname, abspath
default_base_dir = join(dirname(abspath(__file__)), 'completion')
import run
def pytest_addoption(parser):
parser.addoption(
"--base-dir", default=default_base_dir,
help="Directory in which integration test case files locate.")
parser.addoption(
... | from os.path import join, dirname, abspath
default_base_dir = join(dirname(abspath(__file__)), 'completion')
import run
def pytest_addoption(parser):
parser.addoption(
"--base-dir", default=default_base_dir,
help="Directory in which integration test case files locate.")
parser.addoption(
... | Add --test-files option to py.test | Add --test-files option to py.test
At this point, py.test should be equivalent to test/run.py
| Python | mit | tjwei/jedi,jonashaag/jedi,mfussenegger/jedi,jonashaag/jedi,dwillmer/jedi,WoLpH/jedi,tjwei/jedi,mfussenegger/jedi,dwillmer/jedi,flurischt/jedi,WoLpH/jedi,flurischt/jedi |
4aa1623e08519127a06f49060d546c5ef18e906c | vcs/models.py | vcs/models.py | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | from django.db import models
class Activity(models.Model):
group = models.CharField(max_length=4)
grouptype = models.TextField()
groupdetail = models.TextField()
details = models.TextField()
disabled = models.BooleanField()
time = models.DecimalField(decimal_places=2, max_digits=10)
unique_... | Use a OneToMany field for the activity joiner. | Use a OneToMany field for the activity joiner.
| Python | bsd-3-clause | AeroNotix/django-timetracker,AeroNotix/django-timetracker,AeroNotix/django-timetracker |
98e824af43b729eb5b5737597506a5ca87312814 | apps/polls/tests.py | apps/polls/tests.py | """
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 a... | import datetime
from django.test import TestCase
from django.utils import timezone
from apps.polls.models import Poll
class PollMethoTests(TestCase):
def test_was_published_recently_with_future_poll(self):
"""
was_published_recently() should return False for polls whose
pub_date is in the future
"""
futu... | Create a test to expose the bug | Create a test to expose the bug
| Python | bsd-3-clause | hoale/teracy-tutorial,hoale/teracy-tutorial |
990008a6fb2788d25445ee9ec21375515527bdc8 | nodeconductor/backup/utils.py | nodeconductor/backup/utils.py | import pkg_resources
from django.utils import six
from django.utils.lru_cache import lru_cache
@lru_cache()
def get_backup_strategies():
entry_points = pkg_resources.get_entry_map('nodeconductor').get('backup_strategies', {})
strategies = dict((name.upper(), entry_point.load()) for name, entry_point in entry... | import pkg_resources
from django.utils import six
from django.utils.lru_cache import lru_cache
@lru_cache()
def get_backup_strategies():
entry_points = pkg_resources.get_entry_map('nodeconductor').get('backup_strategies', {})
strategies = {name.upper(): entry_point.load() for name, entry_point in six.iterite... | Use new comprehension syntax and six (nc-263) | Use new comprehension syntax and six (nc-263)
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor |
f376eb478783448b5e372c2c4a7f7ee0e4891e88 | examples/python/values.py | examples/python/values.py | #! /usr/bin/env python
#
# values.py
#
"""
An example of using values via Python API
"""
from opencog.atomspace import AtomSpace, TruthValue
from opencog.type_constructors import *
a = AtomSpace()
set_type_ctor_atomspace(a)
a = FloatValue([1.0, 2.0, 3.0])
b = FloatValue([1.0, 2.0, 3.0])
c = FloatValue(1.0)
print('{}... | #! /usr/bin/env python
#
# values.py
#
"""
An example of using values via Python API
"""
from opencog.atomspace import AtomSpace, TruthValue
from opencog.type_constructors import *
from opencog.scheme_wrapper import scheme_eval_v
atomspace = AtomSpace()
set_type_ctor_atomspace(atomspace)
a = FloatValue([1.0, 2.0, 3.... | Add example of scheme_eval_v usage | Add example of scheme_eval_v usage
| Python | agpl-3.0 | rTreutlein/atomspace,rTreutlein/atomspace,rTreutlein/atomspace,AmeBel/atomspace,rTreutlein/atomspace,AmeBel/atomspace,AmeBel/atomspace,AmeBel/atomspace,rTreutlein/atomspace,AmeBel/atomspace |
385d7a5734e91217e9d8c0464327dedb30a69621 | profile_python.py | profile_python.py | # coding: utf8
# Copyright 2013-2015 Vincent Jacques <vincent@vincent-jacques.net>
import cProfile as profile
import pstats
import cairo
from DrawTurksHead import TurksHead
stats_filename = "profiling/profile_python.stats"
img = cairo.ImageSurface(cairo.FORMAT_RGB24, 3200, 2400)
ctx = cairo.Context(img)
ctx.set_s... | # coding: utf8
# Copyright 2013-2015 Vincent Jacques <vincent@vincent-jacques.net>
import cProfile as profile
import pstats
import cairo
from DrawTurksHead import TurksHead
stats_filename = "/tmp/profile.stats"
img = cairo.ImageSurface(cairo.FORMAT_RGB24, 3200, 2400)
ctx = cairo.Context(img)
ctx.set_source_rgb(1,... | Change name of stats file | Change name of stats file
| Python | mit | jacquev6/DrawTurksHead,jacquev6/DrawTurksHead,jacquev6/DrawTurksHead |
dcd36fab023ac2530cbfa17449e3ce8f61ad6bdc | ssl-cert-parse.py | ssl-cert-parse.py | #!/usr/bin/env python3
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
print(str(Cert.get_subject())[18:-2])
prin... | #!/usr/bin/env python3
import datetime
import ssl
import OpenSSL
def GetCert(SiteName, Port):
return ssl.get_server_certificate((SiteName, Port))
def ParseCert(CertRaw):
Cert = OpenSSL.crypto.load_certificate(
OpenSSL.crypto.FILETYPE_PEM, CertRaw)
CertSubject = str(Cert.get_subject())[18:-2]
... | Fix ParseCert() function, add variables, add a return statement | Fix ParseCert() function, add variables, add a return statement
| Python | apache-2.0 | ivuk/ssl-cert-parse |
572dca82aab583e91e5b8402d1334bae55244d16 | hs_tracking/middleware.py | hs_tracking/middleware.py | from .models import Session
class Tracking(object):
"""The default tracking middleware logs all successful responses as a 'visit' variable with
the URL path as its value."""
def process_response(self, request, response):
if response.status_code == 200:
session = Session.objects.for_re... | from .models import Session
class Tracking(object):
"""The default tracking middleware logs all successful responses as a 'visit' variable with
the URL path as its value."""
def process_response(self, request, response):
if request.path.startswith('/heartbeat/'):
return response
... | Disable use tracking of all heartbeat app urls. | Disable use tracking of all heartbeat app urls.
| Python | bsd-3-clause | RENCI/xDCIShare,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,RENCI/xDCIShare,FescueFungiShare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,FescueFungiShare/hydroshare,ResearchSoftwareInstitute/MyHPOM,FescueFungiShare/hydroshare,hydroshare/hydroshare,RENCI/xDCIShare,RENCI/xDCIShare,ResearchSoft... |
93d3a2f19cfb3ef9ae62d04ce24901df81bafc3e | luigi/rfam/families_csv.py | luigi/rfam/families_csv.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 requir... | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 requir... | Fix typo and use correct name | Fix typo and use correct name
We want to use the pretty name, not the standard one for import. In
addition, I fix a typo in the name of the the is_suppressed column.
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline |
49155373b9eea3812c295c9d89c40a7c9c1c1c13 | migrations/versions/20170214191843_pubmed_rename_identifiers_list_to_article_ids.py | migrations/versions/20170214191843_pubmed_rename_identifiers_list_to_article_ids.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from alembic import op
# revision identifiers, used by Alembic.
revision = '3dbb46f23ed7'
down_revision = u'0087dc1eb534'
branch_labels = None
d... | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from alembic import op
# revision identifiers, used by Alembic.
revision = '3dbb46f23ed7'
down_revision = u'b32475938a2d'
branch_labels = None
d... | Fix migrations to have a single path | Fix migrations to have a single path
As it took us a while to merge some PRs, the migrations ended branching in two
parts. This commit fixes to use a single path. It shouldn't cause any issues, as
we're only messing with the `down` migrations and the migrations aren't
dependent on each other.
| Python | mit | opentrials/scraper,opentrials/collectors |
60f9acad7610ee8bed324d1e142cc4801a9e3713 | 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 script to save documentation to a file | 4: Create script to save documentation to a file
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4 | Python | apache-2.0 | stoeps13/ibmcnx2,stoeps13/ibmcnx2 |
2cbffa60c0b12a268e0347a6a4ecfc6d5acb29e3 | lamor_flexbe_states/src/lamor_flexbe_states/detect_person_state.py | lamor_flexbe_states/src/lamor_flexbe_states/detect_person_state.py | #!/usr/bin/env python
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxySubscriberCached
from geometry_msgs.msg import PoseStamped
class DetectPersonState(EventState):
'''
Detects the nearest person and provides their pose.
-- wait_timeout float Time (seconds) to wait for a person ... | #!/usr/bin/env python
from flexbe_core import EventState, Logger
from flexbe_core.proxy import ProxySubscriberCached
from geometry_msgs.msg import PoseStamped
class DetectPersonState(EventState):
'''
Detects the nearest person and provides their pose.
-- wait_timeout float Time (seconds) to wait for a person ... | Set person pose to None if no person is present | [lamor_flexbe_state] Set person pose to None if no person is present
| Python | mit | marinaKollmitz/lamor15,pschillinger/lamor15,pschillinger/lamor15,marinaKollmitz/lamor15,pschillinger/lamor15,marinaKollmitz/lamor15,pschillinger/lamor15,marinaKollmitz/lamor15,marinaKollmitz/lamor15,pschillinger/lamor15 |
206a59c838623aae5e0b0f91f8089ffc13e2cfd0 | pipenv/vendor/pythonfinder/environment.py | pipenv/vendor/pythonfinder/environment.py | # -*- coding=utf-8 -*-
from __future__ import print_function, absolute_import
import os
import platform
import sys
def is_type_checking():
from typing import TYPE_CHECKING
return TYPE_CHECKING
PYENV_INSTALLED = bool(os.environ.get("PYENV_SHELL")) or bool(
os.environ.get("PYENV_ROOT")
)
ASDF_INSTALLED = ... | # -*- coding=utf-8 -*-
from __future__ import print_function, absolute_import
import os
import platform
import sys
def is_type_checking():
try:
from typing import TYPE_CHECKING
except ImportError:
return False
return TYPE_CHECKING
PYENV_INSTALLED = bool(os.environ.get("PYENV_SHELL")) or ... | Fix typing check for pythonfinder | Fix typing check for pythonfinder
Signed-off-by: Dan Ryan <2591e5f46f28d303f9dc027d475a5c60d8dea17a@danryan.co>
| Python | mit | kennethreitz/pipenv |
c8a1b25c1579eba5cb68c1a4cdd60116b3496429 | pre_commit_robotframework_tidy/rf_tidy.py | pre_commit_robotframework_tidy/rf_tidy.py | from __future__ import print_function
import argparse
from robot.errors import DataError
from robot.tidy import Tidy
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to run')
parser.add_argument('--use-pipes', action='store_true', dest='... | from __future__ import print_function
import argparse
from robot.errors import DataError
from robot.tidy import Tidy
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to run')
parser.add_argument('--use-pipes', action='store_true', dest='... | Format results as robot files | Format results as robot files
| Python | mit | guykisel/pre-commit-robotframework-tidy |
ff011f280f6f6aaf74dd2f4ff3cdfb3831aa147c | ideskeleton/builder.py | ideskeleton/builder.py | def build(source_path, overwrite = True):
pass | import os.path
def build(source_path, overwrite = True):
if not os.path.exists(source_path):
raise IOError("source_path does not exist so not skeleton can be built")
'''
for root, dirs, files in os.walk("."):
path = root.split('/')
print (len(path) - 1) *'---' , os.path.basename(root) ... | Make the first test pass by checking if source_path argument exists | Make the first test pass by checking if source_path argument exists
| Python | mit | jruizaranguren/ideskeleton |
3bbe101f609349c2475079f052d5400e77822237 | common/my_filters.py | common/my_filters.py | from google.appengine.ext import webapp
import re
# More info on custom Django template filters here:
# https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#registering-custom-filters
register = webapp.template.create_template_register()
@register.filter
def digits(value):
return re.sub('[^0-9]', '... | from google.appengine.ext import webapp
from helpers.youtube_video_helper import YouTubeVideoHelper
import re
# More info on custom Django template filters here:
# https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#registering-custom-filters
register = webapp.template.create_template_register()
@regi... | Fix video suggestion review showing wrong time | Fix video suggestion review showing wrong time
| Python | mit | nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,tsteward/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/th... |
34575124ea6b16f7a7d4f2ae5e073a87709843d2 | engine/meta.py | engine/meta.py | registered = {}
class GObjectMeta(type):
def __new__(cls, name, bases, dict):
c = super().__new__(cls, name, bases, dict)
qualname = '{}.{}'.format(c.__module__, c.__qualname__)
if qualname in registered:
print(cls, qualname)
c = type(name, (registered[qualname], c),... | registered = {}
created = {}
class GObjectMeta(type):
def __new__(cls, name, bases, dict):
c = super().__new__(cls, name, bases, dict)
# Do not handle classes that are already decorated
if c.__module__.startswith('<meta>'):
return c
# Fullname of the class (base module... | Add __fullname__ attribute on all game classes | Add __fullname__ attribute on all game classes
| Python | bsd-3-clause | entwanne/NAGM |
95ccab69cfff30c24932c4cd156983a29639435d | nginxauthdaemon/crowdauth.py | nginxauthdaemon/crowdauth.py | import crowd
from auth import Authenticator
class CrowdAuthenticator(Authenticator):
"""Atlassian Crowd authenticator. Requires configuration options CROWD_URL, CROWD_APP_NAME, CROWD_APP_PASSWORD"""
def __init__(self, config):
super(CrowdAuthenticator, self).__init__(config)
app_url = config[... | import crowd
from auth import Authenticator
class CrowdAuthenticator(Authenticator):
"""Atlassian Crowd authenticator. Requires configuration options CROWD_URL, CROWD_APP_NAME, CROWD_APP_PASSWORD"""
def __init__(self, config):
super(CrowdAuthenticator, self).__init__(config)
app_url = config[... | Fix 500 error when Crowd auth is failed | Fix 500 error when Crowd auth is failed
| Python | mit | akurdyukov/nginxauthdaemon,akurdyukov/nginxauthdaemon |
6c2a154bf902b5f658b2c2cbf4b65c6ed33e6c1b | pywineds/utils.py | pywineds/utils.py |
"""
Exposes utility functions.
"""
from contextlib import contextmanager
import logging
import timeit
log = logging.getLogger("wineds")
@contextmanager
def time_it(task_desc):
"""
A context manager for timing chunks of code and logging it.
Arguments:
task_desc: task description for logging pur... |
"""
Exposes utility functions.
"""
from contextlib import contextmanager
import logging
import timeit
REPORTING_TYPE_ALL = ""
REPORTING_TYPE_ELD = "TC-Election Day Reporting"
REPORTING_TYPE_VBM = "TC-VBM Reporting"
REPORTING_KEYS_SIMPLE = (REPORTING_TYPE_ALL, )
REPORTING_KEYS_COMPLETE = (REPORTING_TYPE_ELD, REPOR... | Add some reporting_type global variables. | Add some reporting_type global variables.
| Python | bsd-3-clause | cjerdonek/wineds-converter |
21e9254abeebb7260f74db9c94e480cc2b5bbcc9 | tests/conftest.py | tests/conftest.py | import pytest
@pytest.fixture(scope='session')
def base_url(base_url, request):
return base_url or 'https://developer.allizom.org'
| import pytest
VIEWPORT = {
'large': {'width': 1201, 'height': 1024}, # also nav-break-ends
'desktop': {'width': 1025, 'height': 1024},
'tablet': {'width': 851, 'height': 1024}, # also nav-block-ends
'mobile': {'width': 481, 'height': 1024},
'small': {'width': 320, 'height': 480}}
@pytest.fixture(s... | Add viewport sizes fixture to tests. | Add viewport sizes fixture to tests.
| Python | mpl-2.0 | safwanrahman/kuma,Elchi3/kuma,mozilla/kuma,jwhitlock/kuma,SphinxKnight/kuma,SphinxKnight/kuma,Elchi3/kuma,mozilla/kuma,SphinxKnight/kuma,a2sheppy/kuma,safwanrahman/kuma,Elchi3/kuma,mozilla/kuma,yfdyh000/kuma,yfdyh000/kuma,SphinxKnight/kuma,safwanrahman/kuma,a2sheppy/kuma,yfdyh000/kuma,yfdyh000/kuma,safwanrahman/kuma,Sp... |
534633d078fe6f81e67ead075ac31faac0c3c60d | tests/__init__.py | tests/__init__.py | import pycurl
def setup_package():
print('Testing %s' % pycurl.version)
| def setup_package():
# import here, not globally, so that running
# python -m tests.appmanager
# to launch the app manager is possible without having pycurl installed
# (as the test app does not depend on pycurl)
import pycurl
print('Testing %s' % pycurl.version)
| Make it possible to run test app without pycurl being installed | Make it possible to run test app without pycurl being installed
| Python | lgpl-2.1 | pycurl/pycurl,pycurl/pycurl,pycurl/pycurl |
1b9622cedecef0c6c45c11a84bd178adcff752e2 | squadron/exthandlers/download.py | squadron/exthandlers/download.py | import urllib
from extutils import get_filename
from template import render
import requests
import yaml
import jsonschema
SCHEMA = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'Describes the extract extension handler input',
'type':'object',
'properties': {
'url': {
... | import urllib
from extutils import get_filename
from template import render
import requests
import yaml
import jsonschema
SCHEMA = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'Describes the extract extension handler input',
'type':'object',
'properties': {
'url': {
... | Raise Exception when there's an HTTP error | Raise Exception when there's an HTTP error
| Python | mit | gosquadron/squadron,gosquadron/squadron |
7e51d073952d10d3994fb93458e60c03b6746099 | app/services/g6importService.py | app/services/g6importService.py | import json
import jsonschema
from flask import current_app
from jsonschema import validate
with open("schemata/g6-scs-schema.json") as json_file1:
G6_SCS_SCHEMA = json.load(json_file1)
with open("schemata/g6-saas-schema.json") as json_file2:
G6_SAAS_SCHEMA = json.load(json_file2)
with open("schemata/g6-iaas... | import json
import jsonschema
from jsonschema import validate
with open("schemata/g6-scs-schema.json") as json_file1:
G6_SCS_SCHEMA = json.load(json_file1)
with open("schemata/g6-saas-schema.json") as json_file2:
G6_SAAS_SCHEMA = json.load(json_file2)
with open("schemata/g6-iaas-schema.json") as json_file3:
... | Improve code by avoiding flow through exception handling | Improve code by avoiding flow through exception handling
| Python | mit | RichardKnop/digitalmarketplace-api,mtekel/digitalmarketplace-api,mtekel/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,RichardKnop/digitalmarketplace-api,alphagov/digitalmarketplace-api,RichardKnop/digitalmarketplace-api,mtekel/digitalmarketplace-api,RichardKnop/digitalmarketplac... |
135d4ff79a9a650442548fa5acf44f2dbcd20c0e | voltron/common.py | voltron/common.py | import os
import logging
import logging.config
LOG_CONFIG = {
'version': 1,
'formatters': {
'standard': {'format': 'voltron: [%(levelname)s] %(message)s'}
},
'handlers': {
'default': {
'class': 'logging.StreamHandler',
'formatter': 'standard'
}
},
... | import os
import logging
import logging.config
LOG_CONFIG = {
'version': 1,
'formatters': {
'standard': {'format': 'voltron: [%(levelname)s] %(message)s'}
},
'handlers': {
'default': {
'class': 'logging.StreamHandler',
'formatter': 'standard'
}
},
... | Create some shims for py3k | Create some shims for py3k
| Python | mit | snare/voltron,snare/voltron,snare/voltron,snare/voltron |
05ed4d54d48ddf6540f8dc0d162e4fc95337dbb6 | blah/commands.py | blah/commands.py | import os
import subprocess
import sys
def find_command(name):
return commands[name]
def what_is_this_command():
repository = find_current_repository()
if repository is None:
print "Could not find source control repository"
else:
print "{0}+file://{1}".format(repository.type, repositor... | import os
import subprocess
import sys
def find_command(name):
return commands[name]
def what_is_this_command():
directory = sys.argv[2] if len(sys.argv) > 2 else os.getcwd()
repository = find_repository(directory)
if repository is None:
print "Could not find source control repository"
els... | Allow path to be explicitly set when using what-is-this | Allow path to be explicitly set when using what-is-this
| Python | bsd-2-clause | mwilliamson/mayo |
675364683c5415f1db7a5599d8ad97f72f69aaf0 | buckets/utils.py | buckets/utils.py | import string
import random
from django.conf import settings
def validate_settings():
assert settings.AWS, \
"No AWS settings found"
assert settings.AWS.get('ACCESS_KEY'), \
"AWS access key is not set in settings"
assert settings.AWS.get('SECRET_KEY'), \
"AWS secret key is not set ... | import string
import random
from django.conf import settings
def validate_settings():
assert settings.AWS, \
"No AWS settings found"
assert settings.AWS.get('ACCESS_KEY'), \
"AWS access key is not set in settings"
assert settings.AWS.get('SECRET_KEY'), \
"AWS secret key is not set ... | Make random IDs start with a letter | Make random IDs start with a letter
| Python | agpl-3.0 | Cadasta/django-buckets,Cadasta/django-buckets,Cadasta/django-buckets |
c3e2fccbc2a7afa0d146041c0b3392dd89aa5deb | analysis/plot-marker-trajectories.py | analysis/plot-marker-trajectories.py | import climate
import lmj.plot
import numpy as np
import source
import plots
@climate.annotate(
root='load experiment data from this directory',
pattern=('plot data from files matching this pattern', 'option'),
markers=('plot traces of these markers', 'option'),
spline=('interpolate data with a splin... | import climate
import lmj.plot
import numpy as np
import source
import plots
@climate.annotate(
root='load experiment data from this directory',
pattern=('plot data from files matching this pattern', 'option'),
markers=('plot traces of these markers', 'option'),
spline=('interpolate data with a splin... | Add SVT options to plotting script. | Add SVT options to plotting script.
| Python | mit | lmjohns3/cube-experiment,lmjohns3/cube-experiment,lmjohns3/cube-experiment |
d06adea5117eb3ebfddd8592889346089c7391f7 | dictlearn/wordnik_api_demo.py | dictlearn/wordnik_api_demo.py | from wordnik import swagger, WordApi, AccountApi
client = swagger.ApiClient(
'dd3d32ae6b4709e1150040139c308fb77446e0a8ecc93db31',
'https://api.wordnik.com/v4')
word_api = WordApi.WordApi(client)
words = ['paint', 'mimic', 'mimics', 'francie', 'frolic', 'funhouse']
for word in words:
print('=== {} ==='.for... | import nltk
from wordnik import swagger, WordApi, AccountApi
client = swagger.ApiClient(
'dd3d32ae6b4709e1150040139c308fb77446e0a8ecc93db31',
'https://api.wordnik.com/v4')
word_api = WordApi.WordApi(client)
toktok = nltk.ToktokTokenizer()
words = ['paint', 'mimic', 'mimics', 'francie', 'frolic', 'funhouse']
f... | Add tokenization to the WordNik demo | Add tokenization to the WordNik demo
| Python | mit | tombosc/dict_based_learning,tombosc/dict_based_learning |
062e65a161f9c84e5cd18b85790b195eec947b99 | social_website_django_angular/social_website_django_angular/urls.py | social_website_django_angular/social_website_django_angular/urls.py | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home,... | """social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home,... | Set up url for index page | Set up url for index page
| Python | mit | tomaszzacharczuk/social-website-django-angular,tomaszzacharczuk/social-website-django-angular,tomaszzacharczuk/social-website-django-angular |
6fd1305f2a4a2e08b51c421b1c2cfdd33b407119 | src/puzzle/problems/problem.py | src/puzzle/problems/problem.py | from data import meta
class Problem(object):
def __init__(self, name, lines):
self.name = name
self.lines = lines
self._solutions = None
self._constraints = []
@property
def kind(self):
return str(type(self)).strip("'<>").split('.').pop()
@property
def solution(self):
return self.s... | from data import meta
_THRESHOLD = 0.01
class Problem(object):
def __init__(self, name, lines, threshold=_THRESHOLD):
self.name = name
self.lines = lines
self._threshold = threshold
self._solutions = None
self._constraints = [
lambda k, v: v > self._threshold
]
@property
def kind... | Set a threshold on Problem and enforce it. | Set a threshold on Problem and enforce it.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge |
d44fee53020470e2d9a8cd2393f5f0125dbd1fab | python/client.py | python/client.py | import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)
# ideally, you should have try catch block here too
response = stub.SayHello(hello_pb2.HelloReq(Name='Euler'))
print(response.Result)
... | import grpc
import hello_pb2
import hello_pb2_grpc
def run():
channel = grpc.insecure_channel('localhost:50051')
stub = hello_pb2_grpc.HelloServiceStub(channel)
# ideally, you should have try catch block here too
response = stub.SayHello(hello_pb2.HelloReq(Name='Euler'))
print(response.Result)
... | Update python version for better error handling | Update python version for better error handling
| Python | mit | avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors,avinassh/grpc-errors |
97229a7e51279906254a7befa0456a4c89a9b0ea | planner/models.py | planner/models.py | from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
origin = models.CharField(max_length=63)
destination = models.CharField(max_length=63)
class Waypoint(models.Model):
waypoint = models.CharField(max_length=63)
route = models.Fo... | from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
origin = models.CharField(max_length=63)
destination = models.CharField(max_length=63)
def __unicode__(self):
return "{} to {}".format(
self.origin,
s... | Add unicode methods to model classes | Add unicode methods to model classes
| Python | apache-2.0 | jwarren116/RoadTrip,jwarren116/RoadTrip,jwarren116/RoadTrip |
1aef29a64886522d81d2f6a15bd4e48419a66545 | ziggy/__init__.py | ziggy/__init__.py | # -*- coding: utf-8 -*-
"""
Ziggy
~~~~~~~~
:copyright: (c) 2012 by Rhett Garber
:license: ISC, see LICENSE for more details.
"""
__title__ = 'ziggy'
__version__ = '0.0.1'
__build__ = 0
__author__ = 'Rhett Garber'
__license__ = 'ISC'
__copyright__ = 'Copyright 2012 Rhett Garber'
import logging
from . import utils
... | # -*- coding: utf-8 -*-
"""
Ziggy
~~~~~~~~
:copyright: (c) 2012 by Rhett Garber
:license: ISC, see LICENSE for more details.
"""
__title__ = 'ziggy'
__version__ = '0.0.1'
__build__ = 0
__author__ = 'Rhett Garber'
__license__ = 'ISC'
__copyright__ = 'Copyright 2012 Rhett Garber'
import logging
from . import utils
... | Allow unsetting of configuration (for testing) | Allow unsetting of configuration (for testing)
| Python | isc | rhettg/Ziggy,rhettg/BlueOx |
168a7c9b9f5c0699009d8ef6eea0078c2a6a19cc | oonib/handlers.py | oonib/handlers.py | import types
from cyclone import escape
from cyclone import web
class OONIBHandler(web.RequestHandler):
def write_error(self, status_code, exception=None, **kw):
self.set_status(status_code)
if exception:
self.write({'error': exception.log_message})
def write(self, chunk):
... | import types
from cyclone import escape
from cyclone import web
class OONIBHandler(web.RequestHandler):
def write_error(self, status_code, exception=None, **kw):
self.set_status(status_code)
if hasattr(exception, 'log_message'):
self.write({'error': exception.log_message})
else... | Handle writing exceptions that don't have log_exception attribute | Handle writing exceptions that don't have log_exception attribute
| Python | bsd-2-clause | dstufft/ooni-backend,dstufft/ooni-backend |
8c90485e5cab6294a38cfc9332eda6fe8ca15483 | project/config.py | project/config.py | import os
config = {}
system_mongo_host = os.environ.get('MONGODB_PORT_27017_TCP_ADDR')
system_elastic_host = os.environ.get('ELASTIC_PORT_9300_TCP_ADDR')
config['HOST'] = ''
config['PORT'] = 5000
config['MONGODB_HOST'] = system_mongo_host if system_mongo_host else 'localhost'
config['MONGODB_PORT'] = 27017
config['... | import os
config = {}
system_mongo_host = os.environ.get('MONGODB_PORT_27017_TCP_ADDR')
system_elastic_host = os.environ.get('ELASTIC_PORT_9300_TCP_ADDR')
config['HOST'] = ''
config['PORT'] = 5000
config['MONGODB_HOST'] = system_mongo_host if system_mongo_host else 'localhost'
config['MONGODB_PORT'] = 27017
config['... | Add two new domains to whitelist for CORS. | Add two new domains to whitelist for CORS.
| Python | apache-2.0 | AustinStoneProjects/Founderati-Server,AustinStoneProjects/Founderati-Server |
616bd7c5ff8ba5fe5dd190a459b93980613a3ad4 | myuw_mobile/restclients/dao_implementation/hfs.py | myuw_mobile/restclients/dao_implementation/hfs.py | from os.path import dirname
from restclients.dao_implementation.mock import get_mockdata_url
from restclients.dao_implementation.live import get_con_pool, get_live_url
class File(object):
"""
This implementation returns mock/static content.
Use this DAO with this configuration:
RESTCLIENTS_HFS_DAO_C... | from os.path import dirname
from restclients.dao_implementation.mock import get_mockdata_url
from restclients.dao_implementation.live import get_con_pool, get_live_url
import logging
from myuw_mobile.logger.logback import log_info
class File(object):
"""
This implementation returns mock/static content.
U... | Fix bug: must specify the port number. | Fix bug: must specify the port number.
| Python | apache-2.0 | uw-it-aca/myuw,uw-it-aca/myuw,fanglinfang/myuw,uw-it-aca/myuw,fanglinfang/myuw,fanglinfang/myuw,uw-it-aca/myuw |
882175afea0e2c35e2b223e15feb195a005f7d42 | common/config.py | common/config.py | #
# Poet Configurations
#
# client authentication token
AUTH = 'b9c39a336bb97a9c9bda2b82bdaacff3'
# directory to save output files to
ARCHIVE_DIR = 'archive'
#
# The below configs let you bake in the server IP and beacon interval
# into the final executable so it can simply be executed without supplying
# command li... | #
# Poet Configurations
#
# default client authentication token. change this to whatever you want!
AUTH = 'b9c39a336bb97a9c9bda2b82bdaacff3'
# directory to save output files to
ARCHIVE_DIR = 'archive'
#
# The below configs let you bake in the server IP and beacon interval
# into the final executable so it can simply... | Add comment about changing auth token | Add comment about changing auth token
| Python | mit | mossberg/poet |
0e99654d606038098d45fb83cc40405742e43ae8 | readthedocs/builds/filters.py | readthedocs/builds/filters.py | from django.utils.translation import ugettext_lazy as _
import django_filters
from builds import constants
from builds.models import Build, Version
ANY_REPO = (
('', _('Any')),
)
BUILD_TYPES = ANY_REPO + constants.BUILD_TYPES
class VersionFilter(django_filters.FilterSet):
project = django_filters.CharFil... | from django.utils.translation import ugettext_lazy as _
import django_filters
from builds import constants
from builds.models import Build, Version
ANY_REPO = (
('', _('Any')),
)
BUILD_TYPES = ANY_REPO + constants.BUILD_TYPES
class VersionFilter(django_filters.FilterSet):
project = django_filters.CharFil... | Remove version from Build filter. | Remove version from Build filter.
| Python | mit | agjohnson/readthedocs.org,fujita-shintaro/readthedocs.org,GovReady/readthedocs.org,nyergler/pythonslides,Tazer/readthedocs.org,techtonik/readthedocs.org,takluyver/readthedocs.org,nyergler/pythonslides,GovReady/readthedocs.org,nikolas/readthedocs.org,gjtorikian/readthedocs.org,cgourlay/readthedocs.org,d0ugal/readthedocs... |
0b7636422c632172dfc68ea2a5f21ec649248c8c | nimp/commands/vs_build.py | nimp/commands/vs_build.py | # -*- coding: utf-8 -*-
from nimp.commands._command import *
from nimp.utilities.build import *
#-------------------------------------------------------------------------------
class VsBuildCommand(Command):
def __init__(self):
Command.__init__(self, 'vs-build', 'Builds a Visual Studio project')
#--... | # -*- coding: utf-8 -*-
from nimp.commands._command import *
from nimp.utilities.build import *
#-------------------------------------------------------------------------------
class VsBuildCommand(Command):
def __init__(self):
Command.__init__(self, 'vs-build', 'Builds a Visual Studio project')
#--... | Use separate variable names for Visual Studio config/platform. | Use separate variable names for Visual Studio config/platform.
| Python | mit | dontnod/nimp |
84b01f0015163dc016293162f1525be76329e602 | pythonforandroid/recipes/cryptography/__init__.py | pythonforandroid/recipes/cryptography/__init__.py | from pythonforandroid.recipe import CompiledComponentsPythonRecipe, Recipe
class CryptographyRecipe(CompiledComponentsPythonRecipe):
name = 'cryptography'
version = '2.4.2'
url = 'https://github.com/pyca/cryptography/archive/{version}.tar.gz'
depends = ['openssl', 'idna', 'asn1crypto', 'six', 'setupto... | from pythonforandroid.recipe import CompiledComponentsPythonRecipe, Recipe
class CryptographyRecipe(CompiledComponentsPythonRecipe):
name = 'cryptography'
version = '2.4.2'
url = 'https://github.com/pyca/cryptography/archive/{version}.tar.gz'
depends = ['openssl', 'idna', 'asn1crypto', 'six', 'setupto... | Move libraries from LDFLAGS to LIBS for cryptography recipe | Move libraries from LDFLAGS to LIBS for cryptography recipe
Because this is how you are supposed to do it, you must use LDFLAGS for linker flags and LDLIBS (or the equivalent LOADLIBES) for the libraries
| Python | mit | kronenpj/python-for-android,rnixx/python-for-android,PKRoma/python-for-android,germn/python-for-android,PKRoma/python-for-android,kronenpj/python-for-android,rnixx/python-for-android,germn/python-for-android,rnixx/python-for-android,kivy/python-for-android,PKRoma/python-for-android,rnixx/python-for-android,germn/python... |
72301067306d6baf4aab0315a769c75dd585b46d | pi_setup/boot_config.py | pi_setup/boot_config.py | #!/usr/bin/env python
from utils import file_templates
from utils.validation import is_valid_gpu_mem
def main():
gpu_mem = 0
while gpu_mem == 0:
user_input = raw_input("Enter GPU memory in MB (16/32/64/128/256): ")
if is_valid_gpu_mem(user_input):
gpu_mem = user_input
else:
print("Acceptable memory valu... | #!/usr/bin/env python
from utils import file_templates
from utils.validation import is_valid_gpu_mem
def main():
user_input = raw_input("Want to change the GPU memory split? (Y/N): ")
if user_input == 'Y':
gpu_mem = 0
while gpu_mem == 0:
mem_split = raw_input("Enter GPU memory in MB (16/32/64/128/256): ")
... | Make GPU mem split optional | Make GPU mem split optional
| Python | mit | projectweekend/Pi-Setup,projectweekend/Pi-Setup |
2fe5f960f4998a0337bceabd7db930ac5d5a4fd1 | qipipe/qiprofile/helpers.py | qipipe/qiprofile/helpers.py | import re
from datetime import datetime
TRAILING_NUM_REGEX = re.compile("(\d+)$")
"""A regular expression to extract the trailing number from a string."""
DATE_REGEX = re.compile("(0?\d|1[12])/(0?\d|[12]\d|3[12])/((19|20)?\d\d)$")
class DateError(Exception):
pass
def trailing_number(s):
"""
:param s: ... | import re
from datetime import datetime
TRAILING_NUM_REGEX = re.compile("(\d+)$")
"""A regular expression to extract the trailing number from a string."""
DATE_REGEX = re.compile("(0?\d|1[12])/(0?\d|[12]\d|3[12])/((19|20)?\d\d)$")
class DateError(Exception):
pass
def trailing_number(s):
"""
:param s: ... | Change lambda to function in doc. | Change lambda to function in doc.
| Python | bsd-2-clause | ohsu-qin/qipipe |
2f360d9986c13adaaf670b80b27dad995823b849 | bandstructure/system/tightbindingsystem.py | bandstructure/system/tightbindingsystem.py | import numpy as np
from .system import System
class TightBindingSystem(System):
def setDefaultParams(self):
self.params.setdefault('t', 1) # nearest neighbor tunneling strength
self.params.setdefault('t2', 0) # next-nearest neighbor ..
def tunnelingRate(self, dr):
t = self.get("t"... | import numpy as np
from .system import System
class TightBindingSystem(System):
def setDefaultParams(self):
self.params.setdefault('t', 1) # nearest neighbor tunneling strength
self.params.setdefault('t2', 0) # next-nearest neighbor ..
def tunnelingRate(self, dr):
t = self.get("t"... | Use new functions for getting (next) nearest neighbors | Use new functions for getting (next) nearest neighbors
| Python | mit | sharkdp/bandstructure,sharkdp/bandstructure |
611f95b0c72e436ebf056329349216625c61e133 | wagtail/tests/testapp/migrations/0009_defaultstreampage.py | wagtail/tests/testapp/migrations/0009_defaultstreampage.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-21 11:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtailimages.blocks
class Migration(migrations... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-21 11:37
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wagtail.wagtailcore.blocks
import wagtail.wagtailcore.fields
import wagtail.wagtailimages.blocks
class Migration(migrations... | Adjust testapp migration dependency to be valid on 1.6.x | Adjust testapp migration dependency to be valid on 1.6.x
| Python | bsd-3-clause | mixxorz/wagtail,nutztherookie/wagtail,rsalmaso/wagtail,torchbox/wagtail,chrxr/wagtail,gasman/wagtail,zerolab/wagtail,Toshakins/wagtail,takeflight/wagtail,FlipperPA/wagtail,iansprice/wagtail,takeflight/wagtail,wagtail/wagtail,nilnvoid/wagtail,nealtodd/wagtail,FlipperPA/wagtail,nilnvoid/wagtail,chrxr/wagtail,takeflight/w... |
c5946e378147f6d4d42c7a3e531388e6203f29e4 | fantasyStocks/static/stockCleaner.py | fantasyStocks/static/stockCleaner.py | import json
with open("stocks.json") as f:
| from pprint import pprint
import json
import re
REGEXP = re.compile("(?P<symbol>[A-Z]{1,4}).*")
with open("stocks.json") as f:
l = json.loads(f.read())
out = []
for i in l:
if not "^" in i["symbol"]:
out.append(i)
with open("newStocks.json", "w") as w:
w.write(json.dumps(out)... | Write script to remove duplicates from stocks.json | Write script to remove duplicates from stocks.json
| Python | apache-2.0 | ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks,ddsnowboard/FantasyStocks |
d1c3f195e455b926429aadf84cfd9fc51db2802f | fluent_contents/tests/test_models.py | fluent_contents/tests/test_models.py | from django.contrib.contenttypes.models import ContentType
from fluent_contents.models import ContentItem
from fluent_contents.tests.utils import AppTestCase
class ModelTests(AppTestCase):
"""
Testing the data model.
"""
def test_stale_model_str(self):
"""
No matter what, the Content... | import django
from django.contrib.contenttypes.models import ContentType
from fluent_contents.models import ContentItem
from fluent_contents.tests.utils import AppTestCase
class ModelTests(AppTestCase):
"""
Testing the data model.
"""
def test_stale_model_str(self):
"""
No matter wha... | Improve tests for older Django versions | Improve tests for older Django versions
| Python | apache-2.0 | edoburu/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents |
2c8b60569d20a350b33f3c5e8ba00bdc3d9bbee4 | ask_sweden/lambda_function.py | ask_sweden/lambda_function.py | import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from ask import alexa
def lambda_handler(request_obj, context=None):
return alexa.route_request(request_obj)
@alexa.default
def default_handler(request):
logger.info('default_handler')
return alexa.respond('There were 42 accidents ... | import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from ask import alexa
def lambda_handler(request_obj, context=None):
return alexa.route_request(request_obj)
@alexa.default
def default_handler(request):
logger.info('default_handler')
return alexa.respond('There were 42 accidents ... | Use respond instead of create_response | Use respond instead of create_response
| Python | mit | geoaxis/ask-sweden,geoaxis/ask-sweden |
aa82f91d220e8985c7f6dc68433ad65e70a71d15 | froide/foirequest/tests/test_mail.py | froide/foirequest/tests/test_mail.py | # -*- coding: utf-8 -*-
from __future__ import with_statement
from django.test import TestCase
from foirequest.tasks import _process_mail
from foirequest.models import FoiRequest
class MailTest(TestCase):
fixtures = ['publicbodies.json', "foirequest.json"]
def test_working(self):
with file("foirequ... | # -*- coding: utf-8 -*-
from __future__ import with_statement
from django.test import TestCase
from foirequest.tasks import _process_mail
from foirequest.models import FoiRequest
class MailTest(TestCase):
fixtures = ['publicbodies.json', "foirequest.json"]
def test_working(self):
with file("foirequ... | Test for attachment in mail test | Test for attachment in mail test | Python | mit | catcosmo/froide,okfse/froide,fin/froide,stefanw/froide,catcosmo/froide,fin/froide,LilithWittmann/froide,LilithWittmann/froide,okfse/froide,LilithWittmann/froide,ryankanno/froide,stefanw/froide,LilithWittmann/froide,catcosmo/froide,catcosmo/froide,ryankanno/froide,CodeforHawaii/froide,okfse/froide,ryankanno/froide,ryank... |
20f0d90f5c64322864ad5fda4b4c9314e6c1cb11 | run.py | run.py | #!/usr/bin/env python
# coding=utf-8
import sys
from kitchen.text.converters import getwriter
from utils.log import getLogger, open_log, close_log
from utils.misc import output_exception
from system.factory_manager import Manager
sys.stdout = getwriter('utf-8')(sys.stdout)
sys.stderr = getwriter('utf-8')(sys.stderr)... | #!/usr/bin/env python
# coding=utf-8
import os
import sys
from kitchen.text.converters import getwriter
from utils.log import getLogger, open_log, close_log
from utils.misc import output_exception
from system.factory_manager import Manager
sys.stdout = getwriter('utf-8')(sys.stdout)
sys.stderr = getwriter('utf-8')(s... | Create logs folder if it doesn't exist (to prevent errors) | Create logs folder if it doesn't exist (to prevent errors)
| Python | artistic-2.0 | UltrosBot/Ultros,UltrosBot/Ultros |
80215a593c2fdcf0a0ae8b1c61c4342faffd6dac | run.py | run.py | import bb2gh
import time
config_yaml = 'config.yaml'
for issue_id in range(1, 500):
while True:
try:
bb2gh.migrate(config_yaml, verbose=True, issue_ids=[issue_id])
except Exception as inst:
print 'issue_id',issue_id
print type(inst)
print inst.data['... | import bb2gh
import time
config_yaml = 'config.yaml'
for issue_id in range(190, 500):
while True:
try:
bb2gh.migrate(config_yaml, verbose=True, issue_ids=[issue_id])
except Exception as inst:
print 'issue_id',issue_id
print type(inst)
print inst
... | Fix bug, 'message' key throwing error. | Fix bug, 'message' key throwing error.
| Python | mit | wd15/bb2gh |
ba983dea1e20409d403a86d62c300ea3d257b58a | parserscripts/phage.py | parserscripts/phage.py | import re
class Phage:
supported_databases = {
# European Nucleotide Archive phage database
"ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$",
# National Center for Biotechnology Information phage database
"NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$",
# Actinobact... | import re
class Phage:
SUPPORTED_DATABASES = {
# European Nucleotide Archive phage database
"ENA": r"^gi\|[0-9]+\|ref\|([^\|]+)\|\ ([^,]+)[^$]*$",
# National Center for Biotechnology Information phage database
"NCBI": r"^ENA\|([^\|]+)\|[^\ ]+\ ([^,]+)[^$]*$",
# Actinobact... | Rename to follow constant naming conventions | Rename to follow constant naming conventions
| Python | mit | mbonsma/phageParser,mbonsma/phageParser,phageParser/phageParser,mbonsma/phageParser,phageParser/phageParser,goyalsid/phageParser,goyalsid/phageParser,phageParser/phageParser,phageParser/phageParser,mbonsma/phageParser,goyalsid/phageParser |
8c05cb85c47db892dd13abbd91b3948c09b9a954 | statsmodels/tools/__init__.py | statsmodels/tools/__init__.py | from tools import add_constant, categorical
from datautils import Dataset
from statsmodels import NoseWrapper as Tester
test = Tester().test
| from tools import add_constant, categorical
from statsmodels import NoseWrapper as Tester
test = Tester().test
| Remove import of moved file | REF: Remove import of moved file
| Python | bsd-3-clause | josef-pkt/statsmodels,adammenges/statsmodels,saketkc/statsmodels,DonBeo/statsmodels,edhuckle/statsmodels,saketkc/statsmodels,wkfwkf/statsmodels,wzbozon/statsmodels,huongttlan/statsmodels,kiyoto/statsmodels,astocko/statsmodels,musically-ut/statsmodels,bsipocz/statsmodels,wwf5067/statsmodels,jstoxrocky/statsmodels,cbmoor... |
b090c7ae0f5407562e3adc818d2f65ccd4ea7e02 | src/arc_utilities/listener.py | src/arc_utilities/listener.py | from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
... | from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False, callback=None):
"""
Listener is a wrapper around a subscriber where the callback simply records the late... | Allow optional callbacks for Listeners | Allow optional callbacks for Listeners
| Python | bsd-2-clause | WPI-ARC/arc_utilities,UM-ARM-Lab/arc_utilities,UM-ARM-Lab/arc_utilities,UM-ARM-Lab/arc_utilities,WPI-ARC/arc_utilities,WPI-ARC/arc_utilities |
7fc62edee40ecedc49b0529e17ac04e4d7bf6865 | door/models.py | door/models.py | from django.db import models
from django.utils import timezone
class DoorStatus(models.Model):
datetime = models.DateTimeField()
status = models.BooleanField(default=False)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
@staticmethod
def get_door_by_name(n... | from django.db import models
from django.utils import timezone
class DoorStatus(models.Model):
datetime = models.DateTimeField()
status = models.BooleanField(default=False)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
@staticmethod
def get_door_by_name(n... | Change plural name of DoorStatus model | Change plural name of DoorStatus model
| Python | mit | hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website |
4e727b52828122c37b8c398f16ad914898968e83 | examples/rmg/minimal/input.py | examples/rmg/minimal/input.py | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='et... | # Data sources
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='et... | Remove solvent(water) from minimal example. | Remove solvent(water) from minimal example.
Minimal should be just that - minimal.
This hides issue #165 | Python | mit | enochd/RMG-Py,nickvandewiele/RMG-Py,faribas/RMG-Py,comocheng/RMG-Py,nyee/RMG-Py,chatelak/RMG-Py,pierrelb/RMG-Py,faribas/RMG-Py,comocheng/RMG-Py,pierrelb/RMG-Py,nyee/RMG-Py,enochd/RMG-Py,nickvandewiele/RMG-Py,KEHANG/RMG-Py,chatelak/RMG-Py,KEHANG/RMG-Py |
f8b8f3a223f195704f8cc9753963fbe82f1e4674 | feincms/content/rss/models.py | feincms/content/rss/models.py | from datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
link = models.URLField(_('link'))
rendered_co... | from datetime import datetime
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django.template.loader import render_to_string
import feedparser
class RSSContent(models.Model):
title = models.CharField(help_text=_('The rss fie... | Add a title field to the RSSContent | Add a title field to the RSSContent
| Python | bsd-3-clause | hgrimelid/feincms,joshuajonah/feincms,michaelkuty/feincms,matthiask/feincms2-content,nickburlett/feincms,michaelkuty/feincms,nickburlett/feincms,matthiask/django-content-editor,michaelkuty/feincms,nickburlett/feincms,hgrimelid/feincms,feincms/feincms,feincms/feincms,joshuajonah/feincms,matthiask/django-content-editor,m... |
fae3e55b1c472cd314676431a34fe6e160418626 | tests/test_command_line.py | tests/test_command_line.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import subprocess
class TestCommandLine(object):
def setup(self):
"""Set up the environment by moving to the demos directory."""
os.chdir("demos")
def teardown(self):
os.chdir("..")
def add(self, *args):
self.db.add_all... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import subprocess
from dallinger.command_line import heroku_id
class TestCommandLine(object):
def setup(self):
"""Set up the environment by moving to the demos directory."""
os.chdir("demos")
def teardown(self):
os.chdir("..")
... | Test for Heroku app name length | Test for Heroku app name length
| Python | mit | jcpeterson/Dallinger,Dallinger/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger,jcpeterson/Dallinger,Dallinger/Dallinger |
ccc6c983411f951ef3906d55d6a0946c7ef93c75 | app/brief_utils.py | app/brief_utils.py | from flask import abort
from .models import Service
from .validation import get_validation_errors
from .service_utils import filter_services
def validate_brief_data(brief, enforce_required=True, required_fields=None):
errs = get_validation_errors(
'briefs-{}-{}'.format(brief.framework.slug, brief.lot.slu... | from flask import abort
from .models import Service
from .validation import get_validation_errors
from .service_utils import filter_services
def validate_brief_data(brief, enforce_required=True, required_fields=None):
errs = get_validation_errors(
'briefs-{}-{}'.format(brief.framework.slug, brief.lot.slu... | Add criteria weighting 100% total validation | Add criteria weighting 100% total validation
Checks the criteria weighting sum if all criteria fields are set.
This relies on all three fields being required.
If the fields don't add up to a 100 an error is added for each field
that doesn't have any other validation errors.
| Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api |
e378902b85bf865e0b020bd4afe0e12d593a95a8 | github-keys-check.py | github-keys-check.py | #!/usr/bin/python3
import urllib.request
import argparse
import pwd
import sys
def key_for_user(user):
url = 'https://github.com/%s.keys' % user
with urllib.request.urlopen(url) as f:
return f.read().decode('utf-8')
def validate_user(username, min_uid):
"""
Validates that a given username is... | #!/usr/bin/python3
import urllib.request
import argparse
import pwd
import grp
import sys
def key_for_user(user):
url = 'https://github.com/%s.keys' % user
with urllib.request.urlopen(url) as f:
return f.read().decode('utf-8')
def validate_user(username, min_uid, in_group):
"""
Validates tha... | Add --in-group parameter to validate users | Add --in-group parameter to validate users
Allows github login only for users in a certain group. This
can be used to whitelist users who are allowed to ssh in
| Python | apache-2.0 | yuvipanda/github-ssh-auth |
d5eccc801634f1b841fbc31de545e530b6d4bd54 | startup.py | startup.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from collections import Counter
import pandas as pd
XLS_NAME = 'startup.xls'
SHEET_NAME = 'STARTUP_15092014'
COL_NAME = 'nat.giuridica'
def main():
xls = pd.ExcelFile(XLS_NAME)
sheet = xls.parse(SHEET_NAME, index_col=None)
for k,v in Counter(sheet[COL_NAME]... | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from collections import Counter
import pandas as pd
XLS_NAME = 'startup.xls'
SHEET_NAME = 'STARTUP_15092014'
def main():
xls = pd.ExcelFile(XLS_NAME)
sheet = xls.parse(SHEET_NAME, index_col=None, convert_float=False)
data = [el for el in sheet['nat.giuridi... | Add pretty output for two more fields. | Add pretty output for two more fields.
| Python | mit | jacquerie/italian-startups-report |
34db881007bf0dad3b7e870d36ab4e4a68b0fd3d | emcee/run_emcee.py | emcee/run_emcee.py | #! /usr/bin/python
from os.path import abspath, join as pathjoin
from shutil import copy
from subprocess import call
from tempfile import mkdtemp
install_dir = mkdtemp(prefix='emcee.')
games_dir = abspath(pathjoin('..', 'games'))
libraries_dir = abspath('libraries')
infra_dir = abspath('infra')
print 'Installing emce... | #! /usr/bin/python
from os.path import abspath, join as pathjoin
from shutil import copy
from subprocess import Popen
from tempfile import mkdtemp
install_dir = mkdtemp(prefix='emcee.')
games_dir = abspath(pathjoin('..', 'games'))
libraries_dir = abspath('libraries')
infra_dir = abspath('infra')
print 'Installing emc... | Deploy pubsub_ws along with emcee | Deploy pubsub_ws along with emcee
| Python | mit | douglassquirrel/alexandra,douglassquirrel/alexandra,douglassquirrel/alexandra |
d5a2a11d23b9f5393b0b39ca2f90978276311f52 | app/slot/routes.py | app/slot/routes.py | from app import app
from app.slot import controller as con
import config
from auth import requires_auth
from flask import render_template
from flask.ext.login import login_required
@app.route('/dashboard')
# @requires_auth
@login_required
def index():
return con.index()
@app.route('/new', methods=['GET', 'POST... | from app import app
from app.slot import controller as con
import config
from auth import requires_auth
from flask import render_template
from flask.ext.login import login_required
@app.route('/')
@app.route('/dashboard')
@login_required
def index():
return con.index()
@app.route('/new', methods=['GET', 'POST']... | Add / route to index. Remove old requires_auth decorator. | Add / route to index.
Remove old requires_auth decorator.
| Python | mit | nhshd-slot/SLOT,nhshd-slot/SLOT,nhshd-slot/SLOT |
ecc816295154a3756e87349b4cff397ebd17b95f | sipa/base.py | sipa/base.py | # -*- coding: utf-8 -*-
"""
Basic utilities for the Flask app
These are basic utilities necessary for the Flask app which are
disjoint from any blueprint.
"""
from flask import request, session
from flask_login import AnonymousUserMixin, LoginManager
from werkzeug.routing import IntegerConverter as BaseIntegerConverte... | # -*- coding: utf-8 -*-
"""
Basic utilities for the Flask app
These are basic utilities necessary for the Flask app which are
disjoint from any blueprint.
"""
from flask import request, session
from flask_login import AnonymousUserMixin, LoginManager
from flask_babel import gettext
from werkzeug.routing import Integer... | Set up flask to handle login redirects. | Set up flask to handle login redirects.
Fix #147.
| Python | mit | lukasjuhrich/sipa,agdsn/sipa,agdsn/sipa,lukasjuhrich/sipa,lukasjuhrich/sipa,agdsn/sipa,agdsn/sipa,lukasjuhrich/sipa,MarauderXtreme/sipa,MarauderXtreme/sipa,MarauderXtreme/sipa |
4bf614e072a603f4b46038e2f59459c305844553 | ReversiTest.py | ReversiTest.py | import unittest
import reversi
class TestUM(unittest.TestCase):
def setUp(self):
self.board = reversi.ReversiBoard().set_default_board()
def tearDown(self):
self.board = None
def test_up(self):
tuple = (4, 3)
result = self.board.up(tuple)
self.assertEqual(result,... | #!/usr/bin/python
import unittest
import reversi
class ReversiTest(unittest.TestCase):
def setUp(self):
self.board = reversi.ReversiBoard().set_default_board()
def tearDown(self):
self.board = None
def test_up(self):
tuple = (4, 3)
result = self.board.up(tuple)
s... | Update class name in the unit tester | Update class name in the unit tester
| Python | mit | dmitrym0/reversi-py |
38603c8b35c15c134a0499ac92a7c1f7dee4f526 | send_test_data.py | send_test_data.py | #!/usr/bin/env python
import requests
import datetime
import time
import json
import random
from random import choice
random.seed(datetime.datetime.now())
names = ("vehicle_speed", "fuel_consumed_since_restart", "latitude",
"longitude")
while True:
data = {"records": [
{"timestamp": time.time() ... | #!/usr/bin/env python
import requests
import datetime
import time
import json
import sys
from util import massage_record
names = ("vehicle_speed", "fuel_consumed_since_restart", "latitude",
"longitude")
def send_records(records):
data = {"records": records}
print "Sending %s" % data
headers = {'... | Send test data from actual trace files. | Send test data from actual trace files.
| Python | bsd-3-clause | openxc/web-logging-example,openxc/web-logging-example |
b9ac30b0e428038986de64e069954ee340b991a9 | integration/group.py | integration/group.py | from spec import Spec, eq_
from fabric import ThreadingGroup as Group
class Group_(Spec):
def simple_command_on_multiple_hosts(self):
"""
Run command on localhost...twice!
"""
group = Group('localhost', 'localhost')
result = group.run('echo foo', hide=True)
# NOTE:... | from spec import Spec, eq_
from fabric import ThreadingGroup as Group
class Group_(Spec):
def simple_command(self):
group = Group('localhost', '127.0.0.1')
result = group.run('echo foo', hide=True)
eq_(
[x.stdout.strip() for x in result.values()],
['foo', 'foo'],
... | Tidy up existing integration test | Tidy up existing integration test
| Python | bsd-2-clause | fabric/fabric |
58a96c65f1e9868fb607cd3ce56dbf60905f62a7 | autoencoder/api.py | autoencoder/api.py | from .io import preprocess
from .train import train
from .network import mlp
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epo... | from .io import preprocess
from .train import train
from .network import mlp
def autoencode(count_matrix, kfold=None, dimreduce=True, reconstruct=True,
mask=None, type='normal', activation='relu', testset=False,
learning_rate=1e-2, hidden_size=(256,64,256), l2_coef=0.,
epo... | Add optimizer to the API | Add optimizer to the API
Former-commit-id: 3e06c976ad6a7d4409817fb0fa1472237bfa28b7 | Python | apache-2.0 | theislab/dca,theislab/dca,theislab/dca |
1ed040f9d64e12adf964e9f86cc1e18bd8d21593 | scripts/rename.py | scripts/rename.py | import logging
from scripts.util import documents
from scrapi import settings
from scrapi.linter import RawDocument
from scrapi.processing.elasticsearch import es
from scrapi.tasks import normalize, process_normalized, process_raw
logger = logging.getLogger(__name__)
def rename(source, target, dry=True):
asser... | import logging
from scripts.util import documents
from scrapi import settings
from scrapi.linter import RawDocument
from scrapi.processing.elasticsearch import es
from scrapi.tasks import normalize, process_normalized, process_raw
logger = logging.getLogger(__name__)
def rename(source, target, dry=True):
asser... | Stop cassandra from deleting documents, delete documents from old index as well | Stop cassandra from deleting documents, delete documents from old index as well
| Python | apache-2.0 | erinspace/scrapi,mehanig/scrapi,alexgarciac/scrapi,felliott/scrapi,fabianvf/scrapi,icereval/scrapi,jeffreyliu3230/scrapi,CenterForOpenScience/scrapi,erinspace/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,ostwald/scrapi,fabianvf/scrapi,felliott/scrapi |
473121ce5a3caa20576d02c79669408fd4177a43 | features/steps/interactive.py | features/steps/interactive.py | import time, pexpect, re
import nose.tools as nt
import subprocess as spr
PROMPT = "root@\w+:[^\r]+"
UP_ARROW = "\x1b[A"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), ''... | import time, pexpect, re
import nose.tools as nt
import subprocess as spr
PROMPT = "root@\w+:[^\r]+"
ENTER = "\n"
def type(process, input_):
process.send(input_.encode())
process.expect(PROMPT)
# Remove the typed input from the returned standard out
return re.sub(re.escape(input_.strip()), '', proce... | Use "\n" to fix waiting for prompt in feature tests on CI | Use "\n" to fix waiting for prompt in feature tests on CI
| Python | mit | michaelbarton/command-line-interface,pbelmann/command-line-interface,bioboxes/command-line-interface,pbelmann/command-line-interface,michaelbarton/command-line-interface,bioboxes/command-line-interface |
624276b80b6d69b788b2f48691941cd89847237b | software/Pi/ui.py | software/Pi/ui.py | """
Handles LED output for the Raspberry Pi 3
Image tracking software. Imported using 'import ui'
Version: 5/06/17
Dependencies: RPi.GPIO
Note: will only work on a Raspberry Pi!
"""
import RPi.GPIO as gpio
import time
ledPin = 16 #GPIO23
#Set up RPi GPIO
def setup():
gpio.setmode(gpio.BOARD)
gpio.setup(ledPin... | """
Handles LED output for the Raspberry Pi 3
Image tracking software. Imported using 'import ui'
Version: 5/06/17
Dependencies: RPi.GPIO
Note: will only work on a Raspberry Pi!
"""
import RPi.GPIO as gpio
import time
ledPin = 16 #GPIO23
#Set up RPi GPIO
def setup():
gpio.setmode(gpio.BOARD)
gpio.setwarnings(... | Disable warnings for GPIO channels... | Disable warnings for GPIO channels...
| Python | mit | AdlerFarHorizons/eclipse-tracking,AdlerFarHorizons/eclipse-tracking,AdlerFarHorizons/eclipse-tracking,AdlerFarHorizons/eclipse-tracking |
c266fbd7a3478d582dc0d6c88fc5e3d8b7a8f62f | survey/views/survey_result.py | survey/views/survey_result.py | # -*- coding: utf-8 -*-
import datetime
import os
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404
from survey.management.survey2csv import Survey2CSV
from survey.models import Survey
def serve_result_csv(request, pk):
survey = get_object_or_404(Survey, pk=pk)
tr... | # -*- coding: utf-8 -*-
import datetime
import os
from django.http.response import HttpResponse
from django.shortcuts import get_object_or_404
from survey.management.survey2csv import Survey2CSV
from survey.models import Survey
def serve_result_csv(request, pk):
survey = get_object_or_404(Survey, pk=pk)
tr... | Fix - Apache error AH02429 | Fix - Apache error AH02429
Response header name 'mimetype=' contains invalid characters, aborting request
| Python | agpl-3.0 | Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey |
9a121f309ded039f770339d51b43d0933a98d982 | app/main/views.py | app/main/views.py | from flask import render_template, current_app, flash, redirect, url_for
from . import main
from forms import ContactForm
from ..email import send_email
@main.route('/')
def index():
return render_template('index.html')
@main.route('/about')
def about():
return render_template('about.html')
@main.route('/men... | from flask import render_template, current_app, flash, redirect, url_for, send_from_directory
from . import main
from forms import ContactForm
from ..email import send_email
@main.route('/<path:filename>')
def static_from_root(filename):
return send_from_directory(current_app.static_folder, filename)
@main.route(... | Add additional view for sitemap.xml | Add additional view for sitemap.xml
| Python | mit | jordandietch/workforsushi,jordandietch/workforsushi,jordandietch/workforsushi,jordandietch/workforsushi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.