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 |
|---|---|---|---|---|---|---|---|---|---|
439f57419d861b7e180453263e413ed2b3c56826 | restclients/catalyst/gradebook.py | restclients/catalyst/gradebook.py | """
This is the interface for interacting w/ Catalyst GradeBook
"""
from restclients.catalyst import Catalyst
from restclients.exceptions import DataFailureException
from restclients.dao import Catalyst_DAO
class GradeBook(object):
def get_grades_for_student_and_term(self, netid, year, quarter):
"""
... | """
This is the interface for interacting w/ Catalyst GradeBook
"""
from restclients.catalyst import Catalyst
from restclients.exceptions import DataFailureException
from restclients.dao import Catalyst_DAO
class GradeBook(object):
def get_grades_for_student_and_term(self, netid, year, quarter):
"""
... | Make sure quarters are in the format catalyst wants | Make sure quarters are in the format catalyst wants
git-svn-id: 24222aecec59d6833d1342da1ba59f27d6df2b08@636 3f86a6b1-f777-4bc2-bf3d-37c8dbe90857
| Python | apache-2.0 | uw-it-aca/uw-restclients,uw-it-aca/uw-restclients,UWIT-IAM/uw-restclients,UWIT-IAM/uw-restclients,uw-it-cte/uw-restclients,jeffFranklin/uw-restclients,UWIT-IAM/uw-restclients,jeffFranklin/uw-restclients,uw-it-cte/uw-restclients,jeffFranklin/uw-restclients,uw-it-cte/uw-restclients |
2b933faaf2f9aba9158d56c49367e423ea1a2ea3 | pelican/plugins/related_posts.py | pelican/plugins/related_posts.py | from pelican import signals
"""
Related posts plugin for Pelican
================================
Adds related_posts variable to article's context
"""
related_posts = []
def add_related_posts(generator, metadata):
if 'tags' in metadata:
for tag in metadata['tags']:
#print tag
for r... | from pelican import signals
"""
Related posts plugin for Pelican
================================
Adds related_posts variable to article's context
Settings
--------
To enable, add
from pelican.plugins import related_posts
PLUGINS = [related_posts]
to your settings.py.
Usage
-----
{% if article.re... | Add usage and intallation instructions | Add usage and intallation instructions
| Python | agpl-3.0 | alexras/pelican,HyperGroups/pelican,jvehent/pelican,11craft/pelican,51itclub/pelican,number5/pelican,avaris/pelican,treyhunner/pelican,number5/pelican,deved69/pelican-1,lazycoder-ru/pelican,Polyconseil/pelican,simonjj/pelican,ehashman/pelican,koobs/pelican,florianjacob/pelican,joetboole/pelican,sunzhongwei/pelican,Giov... |
755e4c5ca84072d9983de0b1a0e76419cde77f66 | lib/repo/git_hooks/update.d/02-block_change_top_level_master.py | lib/repo/git_hooks/update.d/02-block_change_top_level_master.py | #!/usr/bin/env python3
import os
import subprocess
import sys
if __name__ == '__main__':
ref_name = sys.argv[1]
old_commit = sys.argv[2]
new_commit = sys.argv[3]
# no need to check if old_commit or new_commit are 0, master can't be deleted or created
if ref_name == 'refs/heads/master' and os.envi... | #!/usr/bin/env python3
import os
import subprocess
import sys
if __name__ == '__main__':
ref_name = sys.argv[1]
old_commit = sys.argv[2]
new_commit = sys.argv[3]
# no need to check if old_commit or new_commit are 0, master can't be deleted or created
if ref_name == 'refs/heads/master' and os.envi... | Fix top level hook to not use renames | git: Fix top level hook to not use renames
| Python | mit | benjaminvialle/Markus,MarkUsProject/Markus,MarkUsProject/Markus,benjaminvialle/Markus,benjaminvialle/Markus,benjaminvialle/Markus,benjaminvialle/Markus,MarkUsProject/Markus,MarkUsProject/Markus,benjaminvialle/Markus,MarkUsProject/Markus,MarkUsProject/Markus,benjaminvialle/Markus,MarkUsProject/Markus,MarkUsProject/Marku... |
c43d58ac79d6144eb6252ff611cc9605f290006d | patches/1401/p01_move_related_property_setters_to_custom_field.py | patches/1401/p01_move_related_property_setters_to_custom_field.py | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import webnotes
from webnotes.model.meta import get_field
def execute():
webnotes.reload_doc("core", "doctype", "custom_field")
custom_fields = {}
for cf in webnotes.conn.sql("""selec... | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
import webnotes
def execute():
webnotes.reload_doc("core", "doctype", "custom_field")
cf_doclist = webnotes.get_doctype("Custom Field")
delete_list = []
for d in webnotes.conn.sql("... | Delete Property Setters for Custom Fields, and set them inside Custom Field | Delete Property Setters for Custom Fields, and set them inside Custom Field
| Python | agpl-3.0 | hatwar/buyback-erpnext,indictranstech/osmosis-erpnext,suyashphadtare/vestasi-erp-jan-end,Drooids/erpnext,gangadharkadam/saloon_erp_install,indictranstech/buyback-erp,suyashphadtare/gd-erp,geekroot/erpnext,gangadhar-kadam/verve_erp,anandpdoshi/erpnext,suyashphadtare/vestasi-update-erp,anandpdoshi/erpnext,sagar30051991/o... |
cc7319fa8ac99049b3fcc86c7f2f075ebd2e7124 | pylatex/base_classes/section.py | pylatex/base_classes/section.py | # -*- coding: utf-8 -*-
"""
This module implements the class that deals with sections.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
from . import Container, Command
class SectionBase(Container):
"""A class that is the base for all section type classes."""
... | # -*- coding: utf-8 -*-
"""
This module implements the class that deals with sections.
.. :copyright: (c) 2014 by Jelte Fennema.
:license: MIT, see License for more details.
"""
from . import Container, Command
class SectionBase(Container):
"""A class that is the base for all section type classes."""
... | Set end_paragraph to True by default | Section: Set end_paragraph to True by default
| Python | mit | bjodah/PyLaTeX,JelteF/PyLaTeX,bjodah/PyLaTeX,ovaskevich/PyLaTeX,ovaskevich/PyLaTeX,JelteF/PyLaTeX |
29aa1a440a9ff225d3f9a4773f9097a5efcbd0de | test/integration/test_output.py | test/integration/test_output.py | from ..helpers import *
def test_honcho_start_joins_stderr_into_stdout():
ret, out, err = get_honcho_output(['-f', 'Procfile.output', 'start'])
assert_equal(ret, 0)
assert_in('some normal output', out)
assert_in('and then write to stderr', out)
assert_equal(err, '')
def test_honcho_run_keeps_s... | from ..helpers import *
def test_honcho_start_joins_stderr_into_stdout():
ret, out, err = get_honcho_output(['-f', 'Procfile.output', 'start'])
assert_equal(ret, 0)
assert_regexp_matches(out, r'some normal output')
assert_regexp_matches(out, r'and then write to stderr')
assert_equal(err, '')
d... | Rewrite assertions for Python 2.6 compatibility | Rewrite assertions for Python 2.6 compatibility
| Python | mit | janusnic/honcho,xarisd/honcho,myyk/honcho,gratipay/honcho,nickstenning/honcho,nickstenning/honcho,gratipay/honcho |
26b2ed8c6f47eb87a2851c746e10f2bbe331dc4c | python/qibuild/actions/config.py | python/qibuild/actions/config.py | ## Copyright (C) 2011 Aldebaran Robotics
"""Display the current config """
import os
import qitools
def configure_parser(parser):
"""Configure parser for this action """
qitools.qiworktree.work_tree_parser(parser)
parser.add_argument("--edit", action="store_true",
help="edit the configuration")
... | ## Copyright (C) 2011 Aldebaran Robotics
"""Display the current config """
import os
import qitools
def configure_parser(parser):
"""Configure parser for this action """
qitools.qiworktree.work_tree_parser(parser)
parser.add_argument("--edit", action="store_true",
help="edit the configuration")
... | Check that editor exists when adding | Check that editor exists when adding
| Python | bsd-3-clause | dmerejkowsky/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild,aldebaran/qibuild,dmerejkowsky/qibuild |
2794f71e1a4c9ac8aa70f22ce3c9d01bf2d7737a | humanize/__init__.py | humanize/__init__.py | __version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = ['__version__', 'VERSION', 'naturalday', 'naturaltime', 'ordinal', 'intword',
'naturaldelta', 'intcomma', 'apnumber', 'fractional', '... | __version__ = VERSION = (0, 5, 1)
from humanize.time import *
from humanize.number import *
from humanize.filesize import *
from humanize.i18n import activate, deactivate
__all__ = [
"__version__",
"activate",
"apnumber",
"deactivate",
"fractional",
"intcomma",
"intword",
"naturaldate"... | Format with Black and sort | Format with Black and sort
| Python | mit | jmoiron/humanize,jmoiron/humanize |
88592970d58eeff43837a5e175bba95386a8491b | neutron/db/migration/alembic_migrations/versions/newton/expand/3d0e74aa7d37_add_flavor_id_to_routers.py | neutron/db/migration/alembic_migrations/versions/newton/expand/3d0e74aa7d37_add_flavor_id_to_routers.py | # Copyright 2016 Mirantis
#
# 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... | # Copyright 2016 Mirantis
#
# 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... | Remove erroneous newton milestone tag | Remove erroneous newton milestone tag
Change https://review.openstack.org/268941 inadvertently tagged
alembic migration 3d0e74aa7d37 with the newton milestone.
Remove it.
Change-Id: I46f98a824d2a190c29fb26b62025772de2e4e33e
Partial-Bug: #1623108
| Python | apache-2.0 | openstack/neutron,huntxu/neutron,cloudbase/neutron,sebrandon1/neutron,mahak/neutron,noironetworks/neutron,openstack/neutron,cloudbase/neutron,openstack/neutron,mahak/neutron,huntxu/neutron,noironetworks/neutron,mahak/neutron,eayunstack/neutron,eayunstack/neutron,sebrandon1/neutron |
e1068913bf56d9a8b3bc763eb15673c81d23c85b | openstack/common/report/utils.py | openstack/common/report/utils.py | # Copyright 2013 Red Hat, Inc.
#
# 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 agre... | # Copyright 2013 Red Hat, Inc.
#
# 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 agre... | Fix filter() usage due to python 3 compability | Fix filter() usage due to python 3 compability
Built-in method filter() returns a list in Python 2.x [1], but it
returns an iterator in Python 3.x [2]. To remove the difference (and
make code more readable, also), we use list comprehension instead of filer().
[1] http://docs.python.org/2/library/functions.html#filter... | Python | apache-2.0 | openstack/oslo.reports,citrix-openstack-build/oslo.reports,DirectXMan12/oslo.reports |
f1c414d91d9b1d9ed90a6b5c676cdc2fb60c4fe4 | mongotools/semaphore/semaphore.py | mongotools/semaphore/semaphore.py |
class Semaphore(object):
"""docstring for Semaphore"""
def __init__(self, db, id, counter, value, collection_name='mongotools.semaphore'):
self._db = db
self._name = collection_name
self._id = id
self._counter = counter
self._max = value
doc = self._db[self._nam... |
class Semaphore(object):
"""docstring for Semaphore"""
def __init__(self, db, id, counter, value, collection_name='mongotools.semaphore'):
self._db = db
self._name = collection_name
self._id = id
self._counter = counter
self._max = value
doc = self._db[self._na... | Add peek to get counter | Add peek to get counter
| Python | mit | rick446/MongoTools |
3bc8aa5499d111e66a6e71882a95bd6c357ac6f6 | src/python/tensorflow_cloud/core/tests/examples/multi_file_example/create_model.py | src/python/tensorflow_cloud/core/tests/examples/multi_file_example/create_model.py | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | Format code using black and remove comments | Format code using black and remove comments | Python | apache-2.0 | tensorflow/cloud,tensorflow/cloud |
3640a8c6057ffac8f8d0f7cd6af8954b4169543d | commands.py | commands.py | from runcommands import command
from runcommands.commands import local as _local
@command
def format_code(check=False):
_local(f"black . {'--check' if check else ''}")
@command
def lint():
_local("flake8 .")
@command
def test(with_coverage=True, check=True):
if with_coverage:
_local(
... | from runcommands import command
from runcommands.commands import local as _local
@command
def format_code(check=False):
_local(f"black . {'--check' if check else ''}")
@command
def lint():
_local("flake8 .")
@command
def test(with_coverage=True, check=True, fail_fast=False):
if with_coverage:
... | Add --fail-fast flag to test command | Add --fail-fast flag to test command
| Python | mit | wylee/django-local-settings |
53a3c61a9facf246810b8be7638b62eda5214a47 | djoauth2/conf.py | djoauth2/conf.py | # coding: utf-8
from django.conf import settings
from appconf import AppConf
class DJOAuth2Conf(AppConf):
class Meta:
prefix = 'djoauth2'
ACCESS_TOKEN_LENGTH = 30
ACCESS_TOKEN_LIFETIME = 3600
ACCESS_TOKENS_REFRESHABLE = True
AUTHORIZATION_CODE_LENGTH = 30
AUTHORIZATION_CODE_LIFETIME = 120
CLIENT_... | # coding: utf-8
from django.conf import settings
from appconf import AppConf
class DJOAuth2Conf(AppConf):
class Meta:
prefix = 'djoauth2'
ACCESS_TOKEN_LENGTH = 30
ACCESS_TOKEN_LIFETIME = 3600
ACCESS_TOKENS_REFRESHABLE = True
AUTHORIZATION_CODE_LENGTH = 30
# The specification ( http://tools.ietf.org/... | Update default authorization code lifetime. | Update default authorization code lifetime.
| Python | mit | Locu/djoauth2,vden/djoauth2-ng,Locu/djoauth2,seler/djoauth2,seler/djoauth2,vden/djoauth2-ng |
72ed5473c1b530357bd518149fcfafdea1bc3987 | murano_tempest_tests/tests/api/service_broker/test_service_broker_negative.py | murano_tempest_tests/tests/api/service_broker/test_service_broker_negative.py | # Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | # Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | Remove xfail in service broker negative tests | Remove xfail in service broker negative tests
After tempest-lib 0.14.0 release all fixes in tempest become present.
This patch removes xfail for negative test in service broker test
suite.
Change-Id: Ide900d53fd478885208e53c333d6759e938a960b
Closes-Bug: #1527949
| Python | apache-2.0 | NeCTAR-RC/murano,satish-avninetworks/murano,DavidPurcell/murano_temp,satish-avninetworks/murano,olivierlemasle/murano,olivierlemasle/murano,openstack/murano,DavidPurcell/murano_temp,DavidPurcell/murano_temp,NeCTAR-RC/murano,NeCTAR-RC/murano,openstack/murano,satish-avninetworks/murano,NeCTAR-RC/murano,satish-avninetwork... |
8fbc125eb242716873d5c8cb0420206077f6acc5 | stocks.py | stocks.py | #!/usr/bin/python
import sys
from pprint import pprint
import ystockquote
for quote in sys.argv[1:]:
print 'Finding quote for %s' % quote
# First thing we want is some basic information on the quote.
details = ystockquote.get_all(quote)
| #!/usr/bin/python
import sys
from pprint import pprint
import ystockquote
for quote in sys.argv[1:]:
print 'Finding quote for %s' % quote
# First thing we want is some basic information on the quote.
details = ystockquote.get_all(quote)
print 'Last Open: $%s' % details.get('today_open')
| Print out the last open price | Print out the last open price
| Python | mit | johndavidback/stock-picker |
d27f5e92d6a0fef27b903f75de59c1d85ca35430 | packages/Python/lldbsuite/test/lang/cpp/modules-import/TestCXXModulesImport.py | packages/Python/lldbsuite/test/lang/cpp/modules-import/TestCXXModulesImport.py | """Test that importing modules in C++ works as expected."""
from __future__ import print_function
from distutils.version import StrictVersion
import unittest2
import os
import time
import lldb
import platform
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import ll... | """Test that importing modules in C++ works as expected."""
from __future__ import print_function
from distutils.version import StrictVersion
import unittest2
import os
import time
import lldb
import platform
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import ll... | Add explicit language specifier to test. | Add explicit language specifier to test.
git-svn-id: 4c4cc70b1ef44ba2b7963015e681894188cea27e@354048 91177308-0d34-0410-b5e6-96231b3b80d8
| Python | apache-2.0 | apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb |
6ee135dc454b7ae13dbd4603de60b5eba12cc5c9 | saleor/graphql/core/decorators.py | saleor/graphql/core/decorators.py | from functools import wraps
from django.core.exceptions import PermissionDenied
def permission_required(permissions):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
info = args[1]
user = info.context.user
if not user.has_perm(permissions):
... | from functools import wraps
from django.core.exceptions import PermissionDenied
from graphql.execution.base import ResolveInfo
def permission_required(permissions):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
info = args[1]
assert isinstance(info, Resol... | Make sure decorator is being used with proper function signatures | Make sure decorator is being used with proper function signatures
| Python | bsd-3-clause | UITools/saleor,UITools/saleor,mociepka/saleor,mociepka/saleor,maferelo/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,UITools/saleor |
390fc84183c0f680c5fb1a980ee3c1227b187611 | HowLong/HowLong.py | HowLong/HowLong.py | #!/usr/bin/env python3
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
class HowLong(object):
def __init__(self):
parser = argparse.ArgumentParser(description='Ti... | from __future__ import print_function
import sys
import argparse
from datetime import timedelta
from subprocess import Popen
from time import time, sleep
def red(text):
RED = '\033[91m'
END = '\033[0m'
return RED + text + END
def log(*args):
print(*args, file=sys.stderr)
sys.stderr.flush()
cla... | Print debug info to stderr | MINOR: Print debug info to stderr
| Python | apache-2.0 | mattjegan/HowLong |
5086a41e9aae7da16e4b189285613c2dade2b95a | common_rg_bar.py | common_rg_bar.py | #!/usr/bin/env python3
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
def main():
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'x':
col_char = '3'
cols... | #!/usr/bin/env python3
'''
Given:
1. status code: (0 - OK, other value - BAD)
2. terminal window width
shows red/green bar to visualize return code of previous command
'''
import sys
def main():
if len(sys.argv) >= 2:
code = sys.argv[1]
if code == 'x':
col_char = '3'
cols... | Stop displaying x as the code | Stop displaying x as the code
| Python | mit | kwadrat/rgb_tdd |
b4aee8dc8e582940fa5a983ea0a90ab9b4e4f9e6 | torchtext/legacy/data/__init__.py | torchtext/legacy/data/__init__.py | from .batch import Batch
from .example import Example
from .field import RawField, Field, ReversibleField, SubwordField, NestedField, LabelField
from .iterator import (batch, BucketIterator, Iterator, BPTTIterator, pool)
from .pipeline import Pipeline
from .dataset import Dataset, TabularDataset
# Those are not in the ... | from .batch import Batch
from .example import Example
from .field import RawField, Field, ReversibleField, SubwordField, NestedField, LabelField
from .iterator import (batch, BucketIterator, Iterator, BPTTIterator, pool)
from .pipeline import Pipeline
from .dataset import Dataset, TabularDataset
# Those are not in the ... | Enable importing metrics/utils/functional from torchtext.legacy.data | Enable importing metrics/utils/functional from torchtext.legacy.data
| Python | bsd-3-clause | pytorch/text,pytorch/text,pytorch/text,pytorch/text |
5a252090eb8fe75a5faf058151009bccd3645e70 | upload.py | upload.py | import os
import re
import datetime
from trovebox import Trovebox
def main():
try:
client = Trovebox()
client.configure(api_version=2)
except IOError, e:
print
print '!! Could not initialize Trovebox connection.'
print '!! Check that ~/.config/trovebox/default exists a... | import os
import re
import datetime
from trovebox import Trovebox
def main():
try:
client = Trovebox()
client.configure(api_version=2)
except IOError, e:
print
print '!! Could not initialize Trovebox connection.'
print '!! Check that ~/.config/trovebox/default exists a... | Create albums for each folder instead of tags | Create albums for each folder instead of tags
| Python | mit | nip3o/trovebox-uploader |
89b23ce8abd259ace055c35b0da47428bdcbc37a | scripts/server/client_example.py | scripts/server/client_example.py | #!/usr/bin/env python
from __future__ import print_function, unicode_literals, division
import sys
import time
import argparse
from websocket import create_connection
def translate(batch, port=8080):
ws = create_connection("ws://localhost:{}/translate".format(port))
#print(batch.rstrip())
ws.send(batch... | #!/usr/bin/env python
from __future__ import print_function, unicode_literals, division
import sys
import time
import argparse
from websocket import create_connection
def translate(batch, port=8080):
ws = create_connection("ws://localhost:{}/translate".format(port))
#print(batch.rstrip())
ws.send(batch... | Fix decoding error with python2 | Fix decoding error with python2
| Python | mit | marian-nmt/marian-train,emjotde/amunn,amunmt/marian,emjotde/amunmt,emjotde/amunmt,emjotde/amunmt,marian-nmt/marian-train,marian-nmt/marian-train,marian-nmt/marian-train,amunmt/marian,amunmt/marian,emjotde/amunn,emjotde/amunn,marian-nmt/marian-train,emjotde/amunmt,emjotde/amunn,emjotde/Marian,emjotde/Marian |
929909513e71282de388cf4e93476ba614e6c0c5 | Malcom/feeds/malwaredomains.py | Malcom/feeds/malwaredomains.py | import urllib2
import re
from Malcom.model.datatypes import Hostname, Evil
from feed import Feed
import Malcom.auxiliary.toolbox as toolbox
class MalwareDomains(Feed):
def __init__(self, name):
super(MalwareDomains, self).__init__(name)
self.source = "http://mirror1.malwaredomains.com/files/domains.txt"
self.de... | import urllib2
import re
from Malcom.model.datatypes import Hostname, Evil
from feed import Feed
import Malcom.auxiliary.toolbox as toolbox
class MalwareDomains(Feed):
def __init__(self, name):
super(MalwareDomains, self).__init__(name)
self.source = "http://mirror1.malwaredomains.com/files/domains.txt"
self.de... | Deal with MalwareDomains non-ASCII characters | Deal with MalwareDomains non-ASCII characters
| Python | apache-2.0 | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti |
c9449516bc3bfd15873347d1233001c51939a5e6 | pipeline/utils/backend_helper.py | pipeline/utils/backend_helper.py | """One-line documentation for backend_helper module.
A detailed description of backend_helper.
"""
from taskflow.jobs import backends as job_backends
from taskflow.persistence import backends as persistence_backends
# Default host/port of ZooKeeper service.
ZK_HOST = '104.197.150.171:2181'
# Default jobboard config... | """One-line documentation for backend_helper module.
A detailed description of backend_helper.
"""
from taskflow.jobs import backends as job_backends
from taskflow.persistence import backends as persistence_backends
# Default host/port of ZooKeeper service.
ZK_HOST = '104.197.150.171:2181'
# Default jobboard config... | Fix the bad jobboard path. | Fix the bad jobboard path.
Change-Id: I3281babfa835d7d4b76f7f299887959fa5342e85
| Python | apache-2.0 | ethanbao/artman,ethanbao/artman,googleapis/artman,googleapis/artman,shinfan/artman,googleapis/artman |
df638a33d6f0812a22bb775fded2d1790bd1e409 | router/config/settings.py | router/config/settings.py | import os
import sys
from salmon.server import SMTPReceiver, LMTPReceiver
sys.path.append('..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
# where to listen for incoming messages
if settings.SALMON_SERVER["type"] == "lmtp":
receiver = LMTPReceiver(socket=settings.SALMON_S... | import os
import sys
from salmon.server import SMTPReceiver, LMTPReceiver
sys.path.append('..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
import django
django.setup()
# where to listen for incoming messages
if settings.SALMON_SERVER["type"] == "lmtp":
receiver = LMTPRec... | Call `django.setup()` in router app | Call `django.setup()` in router app
This should have been there before, but somehow we managed to get away
without it :)
fixes #99
| Python | agpl-3.0 | Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen |
6590f92c1423ab37570857e2c6cc726e1a7fede7 | _setup_database.py | _setup_database.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
from setup.create_player_seasons import create_player_seasons
from setup.create_player_seasons import create_player_data
from ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from setup.create_teams import migrate_teams
from setup.create_divisions import create_divisions
from setup.create_players import migrate_players
from setup.create_player_seasons import create_player_seasons
from setup.create_player_seasons import create_p... | Introduce command line parameters for database setup script | Introduce command line parameters for database setup script
| Python | mit | leaffan/pynhldb |
4a6ccb58bade2cefc7baa9424f1747275adaa166 | antxetamedia/archive/filtersets.py | antxetamedia/archive/filtersets.py | from django_filters import FilterSet
from antxetamedia.news.models import NewsPodcast
from antxetamedia.radio.models import RadioPodcast
from antxetamedia.projects.models import ProjectShow
# We do not want to accidentally discard anything, so be inclusive and always
# make gte and lte lookups instead of using gt or... | from django.utils.translation import ugettext_lazy as _
from django_filters import FilterSet, DateTimeFilter
from antxetamedia.news.models import NewsPodcast
from antxetamedia.radio.models import RadioPodcast
from antxetamedia.projects.models import ProjectShow
# We do not want to accidentally discard anything, so ... | Add labels to the pub_date__lte pub_date__gte filters | Add labels to the pub_date__lte pub_date__gte filters
| Python | agpl-3.0 | GISAElkartea/amv2,GISAElkartea/amv2,GISAElkartea/amv2 |
4375e1d72832f9672eaba87019be9b769eb69e78 | alg_hash_string.py | alg_hash_string.py | from __future__ import print_function
def hash_str(a_str, table_size):
"""Hash a string by the folding method.
- Get ordinal number for each char.
- Sum all of the ordinal numbers.
- Return the remainder of the sum with table_size.
"""
sum = 0
for c in a_str:
sum += ord(c)
return sum % table_siz... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
def hash_str(a_str, table_size):
"""Hash a string by the folding method.
- Get ordinal number for each char.
- Sum all of the ordinal numbers.
- Return the remainder of the sum with table_size. ... | Add importing absolute_import & division from Prague | Add importing absolute_import & division from Prague
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
9a49ce93428d6e7bdfeebbed906a1868dd844169 | anycluster/urls.py | anycluster/urls.py | from django.conf.urls import patterns, url
from anycluster import views
from django.conf import settings
urlpatterns = patterns('',
url(r'^grid/(\d+)/(\d+)/$', views.getGrid, name='getGrid'),
url(r'^kmeans/(\d+)/(\d+)/$', views.getPins, name='getPins'),
url(r'^getClusterContent/(\d+)/(\d+)/$', views.getClu... | from django.conf.urls import url
from anycluster import views
from django.conf import settings
urlpatterns = [
url(r'^grid/(\d+)/(\d+)/$', views.getGrid, name='getGrid'),
url(r'^kmeans/(\d+)/(\d+)/$', views.getPins, name='getPins'),
url(r'^getClusterContent/(\d+)/(\d+)/$', views.getClusterContent, name='ge... | Update url format to support Django 1.10 | Update url format to support Django 1.10 | Python | mit | biodiv/anycluster,biodiv/anycluster,biodiv/anycluster,biodiv/anycluster,biodiv/anycluster |
aa8611e43d31e07b9105cca13e4cb9c80479679b | tailor/listeners/mainlistener.py | tailor/listeners/mainlistener.py | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__veri... | from tailor.swift.swiftlistener import SwiftListener
from tailor.utils.charformat import isUpperCamelCase
class MainListener(SwiftListener):
def enterClassName(self, ctx):
self.__verify_upper_camel_case(ctx, 'Class names should be in UpperCamelCase')
def enterEnumName(self, ctx):
self.__veri... | Implement UpperCamelCase name check for structs | Implement UpperCamelCase name check for structs
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor |
fe0867e5499b627e776d132d300d17b40858dcab | line_profiler.py | line_profiler.py | from cProfile import label
import marshal
from _line_profiler import LineProfiler as CLineProfiler
class LineProfiler(CLineProfiler):
""" A subclass of the C version solely to provide a decorator since Cython
does not have closures.
"""
def __call__(self, func):
""" Decorate a function to st... | from cProfile import label
import marshal
from _line_profiler import LineProfiler as CLineProfiler
class LineProfiler(CLineProfiler):
""" A subclass of the C version solely to provide a decorator since Cython
does not have closures.
"""
def __call__(self, func):
""" Decorate a function to st... | Add the typical run/runctx/runcall methods. | ENH: Add the typical run/runctx/runcall methods.
| Python | bsd-3-clause | amegianeg/line_profiler,jstasiak/line_profiler,dreampuf/lprofiler,dreampuf/lprofiler,eblur/line_profiler,jstasiak/line_profiler,ymero/line_profiler,eblur/line_profiler,certik/line_profiler,certik/line_profiler,amegianeg/line_profiler,Doctorhoenikker/line_profiler,jsalva/line_profiler,Doctorhoenikker/line_profiler,ymero... |
117e8c717e4555aa9ee015336c36af186c1b0a85 | src/ocspdash/web/blueprints/ui.py | src/ocspdash/web/blueprints/ui.py | # -*- coding: utf-8 -*-
# import nacl.exceptions
# import nacl.signing
from flask import Blueprint, current_app, render_template
"""The OCSPdash homepage UI blueprint."""
# from nacl.encoding import URLSafeBase64Encoder
# from nacl.signing import VerifyKey
__all__ = [
'ui',
]
ui = Blueprint('ui', __name__)
@u... | # -*- coding: utf-8 -*-
"""The OCSPdash homepage UI blueprint."""
from flask import Blueprint, current_app, render_template
__all__ = [
'ui',
]
ui = Blueprint('ui', __name__)
@ui.route('/')
def home():
"""Show the user the home view."""
payload = current_app.manager.get_payload()
return render_tem... | Remove unused imports from UI blueprint | Remove unused imports from UI blueprint
| Python | mit | scolby33/OCSPdash,scolby33/OCSPdash,scolby33/OCSPdash |
5c0937993fdf34c96ccde3226c8e2a81efb381ce | troposphere/views/allocations.py | troposphere/views/allocations.py |
import logging
from django.conf import settings
from django.shortcuts import render, redirect, render_to_response
from django.template import RequestContext
logger = logging.getLogger(__name__)
def allocations(request):
"""
View that is shown if a community member has XSEDE/Globus access,
but is missin... |
import logging
from django.conf import settings
from django.shortcuts import render, redirect, render_to_response
from django.template import RequestContext
logger = logging.getLogger(__name__)
def allocations(request):
"""
View that is shown if a community member has XSEDE/Globus access,
but is missin... | Fix theme asset pathing in "no allocation" | Fix theme asset pathing in "no allocation"
| Python | apache-2.0 | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend |
a86ca24eba556580a68695f4e0c2a55c8f5f3df1 | s3authbasic/views.py | s3authbasic/views.py | from pyramid.httpexceptions import HTTPUnauthorized, HTTPNotFound
from pyramid.security import forget
from pyramid.response import Response
from pyramid.view import view_config, forbidden_view_config
@forbidden_view_config()
def basic_challenge(request):
response = HTTPUnauthorized()
response.headers.update(f... | from pyramid.httpexceptions import HTTPUnauthorized, HTTPNotFound
from pyramid.security import forget
from pyramid.response import Response
from pyramid.view import view_config, forbidden_view_config
@forbidden_view_config()
def basic_challenge(request):
response = HTTPUnauthorized()
response.headers.update(f... | Set the correct content type according to the amazon metadata | Set the correct content type according to the amazon metadata
| Python | mit | ant30/s3authbasic |
4ea0cb50353b3d7cb7ee3dd4d16397db95d75223 | salt/states/rsync.py | salt/states/rsync.py | # -*- coding: utf-8 -*-
'''
Operations with Rsync.
'''
import salt.utils
def __virtual__():
'''
Only if Rsync is available.
:return:
'''
return salt.utils.which('rsync') and 'rsync' or False
def synchronized(name, source, delete=False, force=False, update=False,
passwordfile=N... | # -*- coding: utf-8 -*-
#
# Copyright 2015 SUSE LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | Add license and SUSE copyright | Add license and SUSE copyright
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
1c057c8ea1e75909e90992784cff177ea1cb294b | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '9c654df782c77449e7d8fa741843143145260aeb'
| #!/usr/bin/env python
NODE_VERSION = 'v0.11.10'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '607907aed2c1dcdd3b5968a756a990ba3f47bca7'
| Update libchromiumcontent for iframe sandbox. | Update libchromiumcontent for iframe sandbox.
| Python | mit | leolujuyi/electron,Zagorakiss/electron,noikiy/electron,the-ress/electron,Neron-X5/electron,JussMee15/electron,Jacobichou/electron,iftekeriba/electron,webmechanicx/electron,michaelchiche/electron,bobwol/electron,mjaniszew/electron,aliib/electron,trankmichael/electron,saronwei/electron,xiruibing/electron,jjz/electron,lee... |
d874ba80db5bedb67b0b50cea431321c77b10f5d | script/lib/config.py | script/lib/config.py | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = 'ea1a7e85a3de1878e5656110c76f4d2d8af41c6e'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | #!/usr/bin/env python
import platform
import sys
NODE_VERSION = 'v0.11.13'
BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent'
LIBCHROMIUMCONTENT_COMMIT = '2cf80c1743e370c12eb7bf078eb425f3cc355383'
ARCH = {
'cygwin': '32bit',
'darwin': '64bit',
'linux2': platform.architecture()[... | Upgrade libchromiumcontent for gin headers. | Upgrade libchromiumcontent for gin headers.
| Python | mit | icattlecoder/electron,ervinb/electron,pandoraui/electron,jlord/electron,Rokt33r/electron,fireball-x/atom-shell,michaelchiche/electron,gamedevsam/electron,tonyganch/electron,noikiy/electron,nicobot/electron,leftstick/electron,bobwol/electron,maxogden/atom-shell,bobwol/electron,GoooIce/electron,soulteary/electron,jcblw/e... |
4953021eedbd73dc3d66455c5dff352a852d6474 | test/test_integration.py | test/test_integration.py | import unittest
import http.client
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connConfig = http.client.HTTPConnection("localhost", 8888)
connRouter.request("GET", "/google")
response = connRoute... | import unittest
import http.client
class TestStringMethods(unittest.TestCase):
def test_404NoConfig(self):
connRouter = http.client.HTTPConnection("localhost", 8666)
connRouter.request("GET", "/google")
response = connRouter.getresponse()
self.assertEqual(response.status, 404)
... | Add debug info to the test | Add debug info to the test | Python | apache-2.0 | dhiaayachi/dynx,dhiaayachi/dynx |
0ec2c192a3f8428bb487add6a70aef100f02c036 | segpy/portability.py | segpy/portability.py | import os
import sys
EMPTY_BYTE_STRING = b'' if sys.version_info >= (3, 0) else ''
if sys.version_info >= (3, 0):
long_int = int
else:
long_int = long
if sys.version_info >= (3, 0):
def byte_string(integers):
return bytes(integers)
else:
def byte_string(integers):
return EMPTY_BYTE_... | import os
import sys
EMPTY_BYTE_STRING = b'' if sys.version_info >= (3, 0) else ''
if sys.version_info >= (3, 0):
def byte_string(integers):
return bytes(integers)
else:
def byte_string(integers):
return EMPTY_BYTE_STRING.join(chr(i) for i in integers)
if sys.version_info >= (3, 0):
imp... | Remove Python 2.7 crutch for int/long | Remove Python 2.7 crutch for int/long
| Python | agpl-3.0 | hohogpb/segpy,abingham/segpy,kjellkongsvik/segpy,Kramer477/segpy,kwinkunks/segpy,stevejpurves/segpy,asbjorn/segpy |
da86340568ff03c6e612aa68a5cd9f275cbf3375 | coda/coda_replication/factories.py | coda/coda_replication/factories.py | """
Coda Replication Model factories for test fixtures.
"""
from datetime import datetime
import factory
from factory import fuzzy
from . import models
class QueueEntryFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.QueueEntry
ark = factory.Sequence(lambda n: 'ark:/00001/id{... | """
Coda Replication Model factories for test fixtures.
"""
from datetime import datetime
import factory
from factory import fuzzy
from . import models
class QueueEntryFactory(factory.django.DjangoModelFactory):
ark = factory.Sequence(lambda n: 'ark:/00001/id{0}'.format(n))
bytes = fuzzy.FuzzyInteger(100000... | Move the QueueEntryFactory Meta class definition below the attributes per the Django code style guide. | Move the QueueEntryFactory Meta class definition below the attributes per the Django code style guide.
| Python | bsd-3-clause | unt-libraries/coda,unt-libraries/coda,unt-libraries/coda,unt-libraries/coda |
72ec6a22f94ca1744d2241202f33c0bc777521ca | supplements/fixtures/factories.py | supplements/fixtures/factories.py | # making a bet that factory_boy will pan out as we get more data
import factory
from supplements.models import Ingredient, Measurement, IngredientComposition, Supplement
DEFAULT_INGREDIENT_NAME = 'Leucine'
DEFAULT_INGREDIENT_HL_MINUTE = 50
DEFAULT_MEASUREMENT_NAME = 'milligram'
DEFAULT_MEASUREMENT_SHORT_NAME = 'mg'
... | # making a bet that factory_boy will pan out as we get more data
import factory
from supplements.models import Ingredient, Measurement, IngredientComposition, Supplement
DEFAULT_INGREDIENT_NAME = 'Leucine'
DEFAULT_INGREDIENT_HL_MINUTE = 50
DEFAULT_MEASUREMENT_NAME = 'milligram'
DEFAULT_MEASUREMENT_SHORT_NAME = 'mg'
... | Swap out native factory.Factory with Django specific factory .... now all factory() calls actually save versus ... before nasty assumption | Swap out native factory.Factory with Django specific factory .... now all factory() calls actually save versus ... before nasty assumption
| Python | mit | jeffshek/betterself,jeffshek/betterself,jeffshek/betterself,jeffshek/betterself |
3e1f1e515b4392d98fe221ce4c14daefc531a1fe | tests/test_compatibility/tests.py | tests/test_compatibility/tests.py | """Backward compatible behaviour with primary key 'Id'."""
from __future__ import absolute_import
from django.conf import settings
from django.test import TestCase
from salesforce.backend import sf_alias
from tests.test_compatibility.models import Lead, User
current_user = settings.DATABASES[sf_alias]['USER']
class ... | """Backward compatible behaviour with primary key 'Id'."""
from __future__ import absolute_import
from django.conf import settings
from django.test import TestCase
from salesforce.backend import sf_alias
from tests.test_compatibility.models import Lead, User
current_user = settings.DATABASES[sf_alias]['USER']
class ... | Test for compatibility of primary key AutoField | Test for compatibility of primary key AutoField
| Python | mit | philchristensen/django-salesforce,hynekcer/django-salesforce,django-salesforce/django-salesforce,chromakey/django-salesforce,philchristensen/django-salesforce,django-salesforce/django-salesforce,hynekcer/django-salesforce,chromakey/django-salesforce,django-salesforce/django-salesforce,hynekcer/django-salesforce,chromak... |
20fce7b482fd11a65494014e14aabecbe4e87683 | src/cmt/standard_names/snbuild.py | src/cmt/standard_names/snbuild.py | #! /usr/bin/env python
"""
Example usage:
snbuild data/models.yaml data/scraped.yaml \
> standard_names/data/standard_names.yaml
"""
import os
from . import (from_model_file, FORMATTERS, Collection)
def main():
"""
Build a list of CSDMS standard names for YAML description files.
"""
i... | #! /usr/bin/env python
"""
Example usage:
snbuild data/models.yaml data/scraped.yaml \
> standard_names/data/standard_names.yaml
"""
import os
from . import (from_model_file, FORMATTERS, Collection)
from .io import from_list_file
def main():
"""
Build a list of CSDMS standard names for YAML d... | Read names line-by-line from a plain text file. | Read names line-by-line from a plain text file.
| Python | mit | csdms/standard_names,csdms/standard_names |
4b8fbe2914aec5ddcf7f63c6b7ca2244ec022084 | tests/test_crossbuild.py | tests/test_crossbuild.py | from mock import patch
from unittest import TestCase
from crossbuild import (
main,
)
class CrossBuildTestCase(TestCase):
def test_main_setup(self):
with patch('crossbuild.setup_cross_building') as mock:
main(['-d', '-v', 'setup', '--build-dir', './foo'])
args, kwargs = mock.call... | from mock import patch
from unittest import TestCase
from crossbuild import (
main,
)
class CrossBuildTestCase(TestCase):
def test_main_setup(self):
with patch('crossbuild.setup_cross_building') as mock:
main(['-d', '-v', 'setup', '--build-dir', './foo'])
args, kwargs = mock.call... | Add main osx-client command test. | Add main osx-client command test. | Python | agpl-3.0 | mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju,mjs/juju |
abdfef81c3146b720c561eaedf8592cd640262a0 | falcom/table.py | falcom/table.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.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
... | # 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.
class Table:
class InputStrContainsCarriageReturn (RuntimeError):
pass
def __init__ (self, tab_separated_text = None):
... | Split input text on init | Split input text on init
| Python | bsd-3-clause | mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation |
4d0e6265911199b1376d0f52e249625180a0500d | third_party/py/gflags/__init__.py | third_party/py/gflags/__init__.py | # gflags raises DuplicateFlagError when defining default flags from packages
# with different names, so this pseudo-package must mimic the core gflags
# package name.
__name__ += ".gflags" # i.e. "third_party.py.gflags.gflags"
from gflags import *
| from __future__ import absolute_import
from gflags import *
| Use PEP 328 absolute import for third_party python gflags. | Use PEP 328 absolute import for third_party python gflags.
Commit d926bc40260549b997a6a5a1e82d9e7999dbb65e fixed a bug (#4206, #4208) in
the third_party python gflags pseudo-package but added excessive runtime
warnings (see #4212). Using the python PEP 328 (absolute import) implementation
eliminates these warnings whi... | Python | apache-2.0 | meteorcloudy/bazel,perezd/bazel,meteorcloudy/bazel,ButterflyNetwork/bazel,akira-baruah/bazel,davidzchen/bazel,akira-baruah/bazel,ulfjack/bazel,twitter-forks/bazel,safarmer/bazel,aehlig/bazel,dslomov/bazel-windows,katre/bazel,bazelbuild/bazel,twitter-forks/bazel,bazelbuild/bazel,ButterflyNetwork/bazel,ButterflyNetwork/b... |
26ffa0cdd1389e2a364531cd20e9f37ee1565cce | base/view_utils.py | base/view_utils.py | # django
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# standard library
def paginate(request, objects, page_size=25):
paginator = Paginator(objects, page_size)
page = request.GET.get('p')
try:
paginated_objects = paginator.page(page)
except PageNotAnInteger:
... | # django
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
# standard library
def paginate(request, objects, page_size=25):
paginator = Paginator(objects, page_size)
page = request.GET.get('p')
try:
paginated_objects = paginator.page(page)
except PageNotAnInteger:
... | Use 'o' as the order by parameter in clean_query_string | Use 'o' as the order by parameter in clean_query_string
| Python | mit | magnet-cl/django-project-template-py3,Angoreher/xcero,Angoreher/xcero,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,Angoreher/xcero,Angoreher/xcero |
c83e2383ea38dc8a0b5ce8e24bdfc2e9c2ba62bd | concourse/scripts/build_with_orca.py | concourse/scripts/build_with_orca.py | #!/usr/bin/python2
import optparse
import subprocess
import sys
from gporca import GporcaCommon
def make():
return subprocess.call(["make",
"-j" + str(num_cpus())], cwd="gpdb_src")
def install(output_dir):
subprocess.call(["make", "install"], cwd="gpdb_src")
subprocess.call("m... | #!/usr/bin/python2
import optparse
import subprocess
import sys
from gporca import GporcaCommon
def make():
ciCommon = GporcaCommon()
return subprocess.call(["make",
"-j" + str(ciCommon.num_cpus())], cwd="gpdb_src")
def install(output_dir):
subprocess.call(["make", "install"],... | Fix councourse script for gpdb | Fix councourse script for gpdb
| Python | apache-2.0 | ashwinstar/gpdb,kaknikhil/gpdb,xuegang/gpdb,kaknikhil/gpdb,xinzweb/gpdb,lisakowen/gpdb,ahachete/gpdb,randomtask1155/gpdb,janebeckman/gpdb,CraigHarris/gpdb,kaknikhil/gpdb,Chibin/gpdb,tangp3/gpdb,lpetrov-pivotal/gpdb,janebeckman/gpdb,rvs/gpdb,royc1/gpdb,chrishajas/gpdb,ashwinstar/gpdb,0x0FFF/gpdb,50wu/gpdb,zaksoup/gpdb,g... |
d3bcd6426bc323a876ffab6ac46fe117f9e5ab13 | opps/__init__.py | opps/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.conf import settings
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"
__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googl... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__status__ = "Development"
__description__ = u"Opps CMS websites magazines and high-traffic"
__author__ = u"Thiago Avelino"
__credits__ = []
__email__ = u"opps-developers@googlegroups.com"
__license__ = u"BSD"... | Remove django installed apps init opps | Remove django installed apps init opps
| Python | mit | YACOWS/opps,opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,opps/opps |
b973c6abe4d325b08278822f85f72ebc1761a825 | changes/constants.py | changes/constants.py | from enum import Enum
class Status(Enum):
unknown = 0
queued = 1
in_progress = 2
finished = 3
collecting_results = 4
def __str__(self):
return STATUS_LABELS[self]
class Result(Enum):
unknown = 0
passed = 1
failed = 2
skipped = 3
errored = 4
aborted = 5
ti... | from enum import Enum
class Status(Enum):
unknown = 0
queued = 1
in_progress = 2
finished = 3
collecting_results = 4
def __str__(self):
return STATUS_LABELS[self]
class Result(Enum):
unknown = 0
passed = 1
failed = 2
skipped = 3
aborted = 5
timedout = 6
... | Remove errored state (lets rely on a single failure state) | Remove errored state (lets rely on a single failure state)
| Python | apache-2.0 | bowlofstew/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes |
b16e9e2f3a349b53505a3f60409b65e139c62356 | alg_prim_minimum_spanning_tree.py | alg_prim_minimum_spanning_tree.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ds_min_priority_queue_tuple import MinPriorityQueue
def prim():
"""Prim's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): (|V|+|E|)log(|V|... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from ds_min_priority_queue_tuple import MinPriorityQueue
def prim(w_graph_d):
"""Prim's algorithm for minimum spanning tree in weighted graph.
Time complexity for graph G(V, E): (|V|+|E... | Write init setting and pick a start | Write init setting and pick a start
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
31df2bef09c151479b53ed514c55a600a3862b46 | storage/elasticsearch_storage.py | storage/elasticsearch_storage.py | from storage import Storage
class ElasticSearchStorage(Storage):
def __init__(self, config_dict):
self.db = config_dict['database']
self.host = config_dict['host']
self.port = config_dict['port']
self.username = config_dict['username']
self.password = config_dict['password']... | import json
from storage import Storage
TASKS = [
{'task_id': 1, 'task_status': 'Complete', 'report_id': 1},
{'task_id': 2, 'task_status': 'Pending', 'report_id': None},
]
REPORTS = [
{'report_id': 1, 'report': {"/tmp/example.log": {"MD5": "53f43f9591749b8cae536ff13e48d6de", "SHA256": "815d310bdbc8684c1163... | Add mocks for es storage | Add mocks for es storage
| Python | mpl-2.0 | mitre/multiscanner,MITRECND/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,awest1339/multiscanner,mitre/multiscanner,mitre/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,awest1339/multiscanner |
294f5331a2a6d1f4cd55b87df4409672c6b2c652 | storage/elasticsearch_storage.py | storage/elasticsearch_storage.py | from storage import Storage
class ElasticSearchStorage(Storage):
def __init__(self, config_dict):
self.db = config_dict['database']
self.host = config_dict['host']
self.port = config_dict['port']
self.username = config_dict['username']
self.password = config_dict['password']... | import json
from storage import Storage
TASKS = [
{'task_id': 1, 'task_status': 'Complete', 'report_id': 1},
{'task_id': 2, 'task_status': 'Pending', 'report_id': None},
]
REPORTS = [
{'report_id': 1, 'report': {"/tmp/example.log": {"MD5": "53f43f9591749b8cae536ff13e48d6de", "SHA256": "815d310bdbc8684c1163... | Add mocks for es storage | Add mocks for es storage
| Python | mpl-2.0 | jmlong1027/multiscanner,awest1339/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,jmlong1027/multiscanner,mitre/multiscanner,mitre/multiscanner,awest1339/multiscanner,MITRECND/multiscanner,awest1339/multiscanner,mitre/multiscanner,MITRECND/multiscanner,awest1339/multiscanner |
0207b0ea61050d8728e084277b14015bd92a8beb | tests/integration/test_kinesis.py | tests/integration/test_kinesis.py | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | # Copyright 2012-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file ac... | Switch kinesis integ tests over to client interface | Switch kinesis integ tests over to client interface
| Python | apache-2.0 | pplu/botocore,boto/botocore |
fba94685ed3934196c4c36557578849aa2c7aeb0 | app.py | app.py | # -*- coding: utf-8 -*-
"""A Flask app to visualize the infection algorithm."""
from flask import Flask, request, abort, jsonify
from werkzeug.exceptions import BadRequest
from infection import User, total_infection, limited_infection
app = Flask(__name__)
def load_user_graph():
"""Get the JSON-encoded user gr... | # -*- coding: utf-8 -*-
"""A Flask app to visualize the infection algorithm."""
from flask import Flask, request, abort, jsonify
from werkzeug.exceptions import BadRequest
from infection import User, total_infection, limited_infection
app = Flask(__name__)
def load_user_graph():
"""Get the JSON-encoded user gr... | Convert all the ids to strings | Convert all the ids to strings
| Python | mit | nickfrostatx/infection,nickfrostatx/infection |
5c9b98319b3537ef6287bc28353cd72748f9e1a8 | profile_collection/startup/99-bluesky.py | profile_collection/startup/99-bluesky.py | # Configure bluesky default detectors with this:
# These are the new "default detectors"
gs.DETS = [em_ch1, em_ch2, em_ch3, em_ch4]
| # Configure bluesky default detectors with this:
# These are the new "default detectors"
gs.DETS = [em]
gs.TABLE_COLS.append('em_chan21')
gs.PLOT_Y = 'em_ch1'
gs.TEMP_CONTROLLER = cs700
gs.TH_MOTOR = th
gs.TTH_MOTOR = tth
import time as ttime
# We probably already have these imports, but we use them below
# so I'm im... | Add multiple settings for bluesky | Add multiple settings for bluesky
- Define a data validator to run at the end of a scan.
- Set up default detectors and plot and table settles for SPEC API.
| Python | bsd-2-clause | NSLS-II-XPD/ipython_ophyd,pavoljuhas/ipython_ophyd,NSLS-II-XPD/ipython_ophyd,pavoljuhas/ipython_ophyd |
55d0fa9b834e6400d48293c80e557c27f5cc4181 | yowsup/structs/protocolentity.py | yowsup/structs/protocolentity.py | from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, ... | from .protocoltreenode import ProtocolTreeNode
import unittest, time
class ProtocolEntity(object):
__ID_GEN = -1
def __init__(self, tag):
self.tag = tag
def getTag(self):
return self.tag
def isType(self, typ):
return self.tag == typ
def _createProtocolTreeNode(self, ... | Print protocoltreenode on assertion failure | Print protocoltreenode on assertion failure
| Python | mit | biji/yowsup,ongair/yowsup |
24c5497b0c91ce032fb4cf99e79fffc5fa27cb84 | push/management/commands/startbatches.py | push/management/commands/startbatches.py | # coding=utf-8
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from push.models import DeviceTokenModel, NotificationModel
from datetime import datetime
import push_notification
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Comma... | # coding=utf-8
from django.conf import settings
from django.core.management.base import BaseCommand, CommandError
from push.models import DeviceTokenModel, NotificationModel
from datetime import datetime
import push_notification
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Comma... | Update batch execute for conditions | Update batch execute for conditions
| Python | apache-2.0 | nnsnodnb/django-mbaas,nnsnodnb/django-mbaas,nnsnodnb/django-mbaas |
056cb6d5dff67fe029a080abeaba36faee5cff60 | lib/test_util.py | lib/test_util.py | from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
client = HTTPClient()
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
def fetch_documents_from_url(url):
'''
Retrieve newebe documents from a givent url
'''... | from lettuce import world
from tornado.escape import json_decode
from tornado.httpclient import HTTPClient
from newebe.settings import TORNADO_PORT
ROOT_URL = "http://localhost:%d/" % TORNADO_PORT
class NewebeClient(HTTPClient):
'''
Tornado client wrapper to write POST, PUT and delete request faster.
'''... | Make newebe HTTP client for easier requesting | Make newebe HTTP client for easier requesting
| Python | agpl-3.0 | gelnior/newebe,gelnior/newebe,gelnior/newebe,gelnior/newebe |
be0ca3d4a1759fd68f0360fb3b6fe06cdc4cf7ea | test/test_blacklist_integrity.py | test/test_blacklist_integrity.py | #!/usr/bin/env python3
from glob import glob
for bl_file in glob('bad_*.txt') + glob('blacklisted_*.txt'):
with open(bl_file, 'r') as lines:
for lineno, line in enumerate(lines, 1):
if line.endswith('\r\n'):
raise(ValueError('{0}:{1}:DOS line ending'.format(bl_file, lineno)))
... | #!/usr/bin/env python3
from glob import glob
def test_blacklist_integrity():
for bl_file in glob('bad_*.txt') + glob('blacklisted_*.txt'):
with open(bl_file, 'r') as lines:
seen = dict()
for lineno, line in enumerate(lines, 1):
if line.endswith('\r\n'):
... | Check blacklist against duplicate entries as well | Check blacklist against duplicate entries as well
Additionally, refactor into a def test_* to run like the other unit tests.
| Python | apache-2.0 | Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector |
c5e47e61a6b51da99126a9faa4064a621acf017c | tests/handhistory/speed_tests.py | tests/handhistory/speed_tests.py | from timeit import timeit, repeat
results, single_results = [], []
for handnr in range(1, 5):
single_results.append(
timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000,
setup="from handhistory import PokerStarsHandHistory; "
f"from stars_hands import HAND{hand... | from timeit import timeit, repeat
results, single_results = [], []
for handnr in range(1, 5):
single_results.append(
timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000,
setup="from poker.room.pokerstars import PokerStarsHandHistory; "
f"from tests.handhistory.... | Make handhistory speed test work from root dir | Make handhistory speed test work from root dir
| Python | mit | pokerregion/poker |
221bb27796036b348c5cf0fd06a0d57984b3591c | tests/integ/test_basic.py | tests/integ/test_basic.py | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine... | """Basic scenarios, symmetric tests"""
import pytest
from bloop import (
BaseModel,
Column,
GlobalSecondaryIndex,
Integer,
MissingObjects,
)
from .models import User
def test_crud(engine):
engine.bind(User)
user = User(email="user@domain.com", username="user", profile="first")
engine... | Rename integration test model names for debugging in console | Rename integration test model names for debugging in console
| Python | mit | numberoverzero/bloop,numberoverzero/bloop |
c33b876c664178de92099b6553a6030789bdaaa4 | app/v2/templates/get_templates.py | app/v2/templates/get_templates.py | from flask import jsonify, request
from jsonschema.exceptions import ValidationError
from app import api_user
from app.dao import templates_dao
from app.schema_validation import validate
from app.v2.templates import v2_templates_blueprint
from app.v2.templates.templates_schemas import get_all_template_request
@v2_te... | from flask import jsonify, request
from jsonschema.exceptions import ValidationError
from app import api_user
from app.dao import templates_dao
from app.schema_validation import validate
from app.v2.templates import v2_templates_blueprint
from app.v2.templates.templates_schemas import get_all_template_request
@v2_te... | Remove get all template print | Remove get all template print
| Python | mit | alphagov/notifications-api,alphagov/notifications-api |
f364b55a643c2768f80cb559eb0ec1988aa884c8 | tests/htmlgeneration_test.py | tests/htmlgeneration_test.py | from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
generator = HtmlGenerator()
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
do... | from nose.tools import istest, assert_equal
from lxml import etree
from wordbridge import openxml
from wordbridge.htmlgeneration import HtmlGenerator
from wordbridge.html import HtmlBuilder
html = HtmlBuilder()
@istest
def generating_html_for_document_concats_html_for_paragraphs():
document = openxml.document([
... | Add test just for paragraph HTML generation | Add test just for paragraph HTML generation
| Python | bsd-2-clause | mwilliamson/wordbridge |
f1dd26bfb449f8bba69f93cae02ab904e0a9cba0 | tasks/hello_world.py | tasks/hello_world.py | import json
import pystache
class HelloWorld():
def __init__(self):
with open('models/hello_world.json') as config_file:
self.config = json.load(config_file)
self.message = self.config['message']
def process(self):
renderer = pystache.Renderer(search_dirs='templates')
... | import json
import pystache
class HelloWorld():
def __init__(self):
with open('models/hello_world.json') as config_file:
# Map JSON properties to this object
self.__dict__.update(json.load(config_file))
def process(self):
renderer = pystache.Renderer(search_dirs='templ... | Copy config settings to task object automatically | Copy config settings to task object automatically
| Python | mit | wpkita/automation-station,wpkita/automation-station,wpkita/automation-station |
556054ecbaa265b8e734860f3393acf3bc3e840e | Lib/importlib/test/import_/util.py | Lib/importlib/test/import_/util.py | import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib._... | import functools
import importlib
import importlib._bootstrap
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib._... | Use the public API, not a private one. | Use the public API, not a private one.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator |
6dfed291a253174672d7003700ab770aabcacae4 | backend/breach/models/__init__.py | backend/breach/models/__init__.py | from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet
| __all__ = ['victim', 'target', 'round', 'sampleset']
from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet
| Add __all__ to models init file | Add __all__ to models init file
| Python | mit | dimriou/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dion... |
dc884cfd49133a9a25cc5ba6276b94dd44d18729 | test/test_general.py | test/test_general.py | import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hi... | import threading
import time
import sys
from busybees import worker
from busybees import hive
import pash
class ErrWorker(worker.Worker):
def work(self, command):
proc = pash.ShellProc()
proc.run(command)
return "Exit code: %s" % proc.get_val('exit_code')
def test_hive():
apiary = hi... | Add jobs to second test queen, add assertions | Add jobs to second test queen, add assertions
| Python | bsd-3-clause | iansmcf/busybees |
6d118fed4df334e093840d0bcaad98a06214793b | week1/the_real_deal/sum_matrix.py | week1/the_real_deal/sum_matrix.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def sum_matrix(n):
""" Returns a sum of all elements in a
given matrix """
p = [sum(x) for x in n]
print (len(p))
return sum(p)
if __name__ == '__main__':
print (sum_matrix([[0, 3, 0], [0, 4, 0], [0, 13, 0]]))
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def sum_matrix(n):
""" Returns a sum of all elements in a
given matrix """
return sum([sum(x) for x in n])
if __name__ == '__main__':
print (sum_matrix([[0, 3, 0], [0, 4, 0], [0, 13, 0]]))
| Make it look more pythonic | Make it look more pythonic
| Python | bsd-3-clause | sevgo/Programming101 |
b66d8c2d43a28ce6e0824543bd879dc3528e3509 | rest/available-phone-numbers/local-basic-example-1/local-get-basic-example-1.6.x.py | rest/available-phone-numbers/local-basic-example-1/local-get-basic-example-1.6.x.py | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
numbers = client.available_p... | # Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import Client
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "your_auth_token"
client = Client(account_sid, auth_token)
numbers = client.available_p... | Add a comment about purchasing the phone number | Add a comment about purchasing the phone number | Python | mit | TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets |
ca8600faac6b10f5e1bda42d74208f3189efe529 | bin/debug/load_timeline_for_day_and_user.py | bin/debug/load_timeline_for_day_and_user.py | import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representa... | import json
import bson.json_util as bju
import emission.core.get_database as edb
import argparse
import emission.core.wrapper.user as ecwu
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("timeline_filename",
help="the name of the file that contains the json representa... | Add option to print debug statements at regular intervals | Add option to print debug statements at regular intervals
Useful to track the progress of the load. This was a change copied from the
production server.
| Python | bsd-3-clause | shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server |
249a49d2f174571db22860ebfffc37637cacd9be | xmantissa/plugins/hyperbolaoff.py | xmantissa/plugins/hyperbolaoff.py | from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
import hyperbola
from hyperbola import hyperbola_model
from hyperbola.hyperbola_theme import HyperbolaTheme
hyperbolaer = provisioning.BenefactorFactory(
name = u'hyperbolaer',
description = u'A wonderful ready to use a... | from axiom import iaxiom, userbase
from xmantissa import website, offering, provisioning
import hyperbola
from hyperbola import hyperbola_model
from hyperbola.hyperbola_theme import HyperbolaTheme
hyperbolaer = provisioning.BenefactorFactory(
name = u'hyperbolaer',
description = u'A wonderful ready to use a... | Revert 5505 - introduced numerous regressions into the test suite | Revert 5505 - introduced numerous regressions into the test suite | Python | mit | twisted/hyperbola,twisted/hyperbola |
435cdbda7d93287db6dcd652a79324a86becd9b8 | bytecode.py | bytecode.py | class BytecodeBase:
def __init__(self):
# Eventually might want to add subclassed bytecodes here
# Though __subclasses__ works quite well
pass
def execute(self, machine):
pass
class Push(BytecodeBase):
def __init__(self, data):
self.data = data
def execute(sel... | class BytecodeBase:
def __init__(self):
# Eventually might want to add subclassed bytecodes here
# Though __subclasses__ works quite well
pass
def execute(self, machine):
pass
class Push(BytecodeBase):
def __init__(self, data):
self.data = data
def execute(sel... | Edit arithmetic operators to use the underlying vm directly | Edit arithmetic operators to use the underlying vm directly
| Python | bsd-3-clause | darbaga/simple_compiler |
3b14ed7d9ec092baaf10c9f81955dda28508db35 | tests/test_basics.py | tests/test_basics.py | import unittest
from phaseplot import phase_portrait
import matplotlib
class TestBasics(unittest.TestCase):
"""A collection of basic tests with no particular theme"""
def test_retval(self):
"""phase_portrait returns an AxesImage instance"""
def somefun(z): return z*z + 1
retval = p... | import unittest
from phaseplot import phase_portrait
import matplotlib
from matplotlib import pyplot as plt
class TestBasics(unittest.TestCase):
"""A collection of basic tests with no particular theme"""
def test_retval(self):
"""phase_portrait returns an AxesImage instance"""
def somefun(... | Add test for correct image extent | Add test for correct image extent
| Python | mit | rluce/python-phaseplot |
233e5b2f48ae567f50843dc3b8b4301a21c12b71 | cloud_notes/templatetags/markdown_filters.py | cloud_notes/templatetags/markdown_filters.py | from django import template
import markdown as md
import bleach
import copy
register = template.Library()
def markdown(value):
"""convert to markdown"""
allowed_tags = bleach.ALLOWED_TAGS + ['p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
return bleach.clean(md.markdown(value), tags = allowed_tags)
... | from django import template
import markdown as md
import bleach
import copy
register = template.Library()
def markdown(value):
"""convert to markdown"""
allowed_tags = bleach.ALLOWED_TAGS + ['blockquote', 'pre', 'p', 'br', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']
return bleach.clean(md.markdown(value), t... | Add pre tag to cloud notes | Add pre tag to cloud notes
| Python | apache-2.0 | kiwiheretic/logos-v2,kiwiheretic/logos-v2,kiwiheretic/logos-v2,kiwiheretic/logos-v2 |
7dacd28007097f83713b08d8b768d8ba8f6629d2 | src/unittest/python/stack_configuration/stack_configuration_tests.py | src/unittest/python/stack_configuration/stack_configuration_tests.py | import unittest2
from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException
class ConfigTests(unittest2.TestCase):
def test_properties_parsing(self):
config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'foo': {'template-url': 'foo.json'}}})
self.assertEqual('eu-w... | import unittest2
from cfn_sphere.stack_configuration import Config, StackConfig, NoConfigException
class ConfigTests(unittest2.TestCase):
def test_properties_parsing(self):
config = Config(config_dict={'region': 'eu-west-1', 'stacks': {'any-stack': {'template-url': 'foo.json', 'tags': {'any-tag': 'any-ta... | Make test variables more descriptive | refactor: Make test variables more descriptive
| Python | apache-2.0 | ImmobilienScout24/cfn-sphere,cfn-sphere/cfn-sphere,marco-hoyer/cfn-sphere,cfn-sphere/cfn-sphere,cfn-sphere/cfn-sphere |
5c60aad725b0b98008ee467c5130931339c12d48 | os_client_config/cloud_config.py | os_client_config/cloud_config.py | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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 appli... | # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
#
# 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 appli... | Add an equality method for CloudConfig | Add an equality method for CloudConfig
In order to track if a config has changed, we need to be able to compare
the CloudConfig objects for equality.
Change-Id: Icdd9acede81bc5fba60d877194048e24a62c9e5d
| Python | apache-2.0 | stackforge/python-openstacksdk,redhat-openstack/os-client-config,openstack/python-openstacksdk,dtroyer/python-openstacksdk,openstack/os-client-config,dtroyer/os-client-config,stackforge/python-openstacksdk,dtroyer/python-openstacksdk,openstack/python-openstacksdk,switch-ch/os-client-config |
f879bf6304fcd31e32b55c40462dce06ff859410 | turbasen/settings.py | turbasen/settings.py | import os
from .cache import DummyCache
class Settings:
ENDPOINT_URL = os.environ.get('ENDPOINT_URL', 'https://api.nasjonalturbase.no')
LIMIT = 20
CACHE = DummyCache()
CACHE_LOOKUP_PERIOD = 60 * 60 * 24
CACHE_GET_PERIOD = 60 * 60 * 24 * 30
ETAG_CACHE_PERIOD = 60 * 60
API_KEY = os.environ.g... | import os
from .cache import DummyCache
class MetaSettings(type):
"""Implements reprentation for the Settings singleton, displaying all settings and values"""
def __repr__(cls):
settings = [
'%s=%s' % (name, getattr(cls, name))
for name in dir(cls)
if not name.start... | Implement repr for Settings class | Implement repr for Settings class
| Python | mit | Turbasen/turbasen.py |
fbbe736b649a85cddf773548b895ccaa9ead8c67 | docker/nvidia/setup_nvidia_docker_compose.py | docker/nvidia/setup_nvidia_docker_compose.py | #!/usr/bin/env python
import requests
import yaml
# query nvidia docker plugin for the command-line parameters to use with the
# `docker run` command
response = requests.get('http://localhost:3476/docker/cli/json')
docker_cli_params = response.json()
devices = docker_cli_params['Devices']
volumes = docker_cli_params[... | #!/usr/bin/env python
import requests
import yaml
# query nvidia docker plugin for the command-line parameters to use with the
# `docker run` command
try:
response = requests.get('http://localhost:3476/docker/cli/json')
except requests.exceptions.ConnectionError, e:
print('Cannot connect to the nvidia docker ... | Add error handling in case nvidia plugin daemon is not running | Add error handling in case nvidia plugin daemon is not running
| Python | bsd-3-clause | ORNL-CEES/DataTransferKit,dalg24/DataTransferKit,amccaskey/DataTransferKit,dalg24/DataTransferKit,ORNL-CEES/DataTransferKit,Rombur/DataTransferKit,dalg24/DataTransferKit,Rombur/DataTransferKit,dalg24/DataTransferKit,amccaskey/DataTransferKit,ORNL-CEES/DataTransferKit,ORNL-CEES/DataTransferKit,Rombur/DataTransferKit,amc... |
4503294985c45e02e284dc3ab7dac4631856c126 | rainforest_makers/urls.py | rainforest_makers/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'rainforest_makers.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', ... | from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'rainforest_makers.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^', ... | Add Media url/root to settings | Add Media url/root to settings
| Python | mit | bjorncooley/rainforest_makers,bjorncooley/rainforest_makers |
7092293a569c382dac4f2f9ac69b879ea4b500d1 | django_prometheus/db/backends/mysql/base.py | django_prometheus/db/backends/mysql/base.py | from django_prometheus.db.common import DatabaseWrapperMixin
from django.db.backends.mysql import base
class DatabaseFeatures(base.DatabaseFeatures):
"""Our database has the exact same features as the base one."""
pass
class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseWrapper):
CURSOR_CLASS = bas... | from django_prometheus.db.common import (
DatabaseWrapperMixin, ExportingCursorWrapper)
from django.db.backends.mysql import base
class DatabaseFeatures(base.DatabaseFeatures):
"""Our database has the exact same features as the base one."""
pass
class DatabaseWrapper(DatabaseWrapperMixin, base.DatabaseW... | Use the proper API to Python-MySQL. | Use the proper API to Python-MySQL.
The common mixin used for other databases uses an API established
across databases, but Python-MySQL differs. This was broken during the
refactoring in 432f1874ffde0ad120aa79e568086a1731d22aeb.
Fixes #24
| Python | apache-2.0 | korfuri/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus,obytes/django-prometheus |
ed68f3f8961fd9cc212c2bc7700ba758af51d335 | mailchimp_manager/tests/test_list_manager.py | mailchimp_manager/tests/test_list_manager.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_list_manager.py - Integration test for list management of mailchimp_manager
"""
from mailchimp_manager import MailChimpManager
import unittest
TEST_EMAIL = u'john.doe@gmail.com'
class TestMailChimpListManager(unittest.TestCase):
def test_Subscribe_TestEma... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_list_manager.py - Integration test for list management of mailchimp_manager
"""
try:
from mailchimp_manager import MailChimpManager
except:
# Local module testing - assuming mailchimp_manager folder put in grandparent folder
import sys, os.path
... | Update test script for local testing | Update test script for local testing
| Python | bsd-3-clause | Kudo/mailchimp_manager |
959b5fd80a2eeb4ddb56dea07edd16c1aeabc4ff | userprofile/admin.py | userprofile/admin.py | from django.contrib import admin
from .models import Profile, Skill, DutyTime, Group
admin.site.register(Profile)
admin.site.register(Skill)
admin.site.register(DutyTime)
admin.site.register(Group)
| from django.contrib import admin
from .models import Profile, Skill, DutyTime, Group
class ProfileAdmin(admin.ModelAdmin):
list_filter = (
('tos_accepted', admin.BooleanFieldListFilter),
)
admin.site.register(Profile, ProfileAdmin)
admin.site.register(Skill)
admin.site.register(DutyTime)
admin.site.... | Add filtering option to see profiles that have not accepted new tos | Add filtering option to see profiles that have not accepted new tos
| Python | mit | hackerspace-ntnu/website,hackerspace-ntnu/website,hackerspace-ntnu/website |
a795274811b3df67a04593b1889d9c93fed40737 | examples/webhooks.py | examples/webhooks.py | from __future__ import print_function
import os
import stripe
from flask import Flask, request
stripe.api_key = os.environ.get('STRIPE_SECRET_KEY')
webhook_secret = os.environ.get('WEBHOOK_SECRET')
app = Flask(__name__)
@app.route('/webhooks', methods=['POST'])
def webhooks():
payload = request.data
recei... | from __future__ import print_function
import os
import stripe
from flask import Flask, request
stripe.api_key = os.environ.get('STRIPE_SECRET_KEY')
webhook_secret = os.environ.get('WEBHOOK_SECRET')
app = Flask(__name__)
@app.route('/webhooks', methods=['POST'])
def webhooks():
payload = request.data.decode('u... | Fix example for Python 3 compatibility | Fix example for Python 3 compatibility
| Python | mit | stripe/stripe-python |
8664741930e5a21bfbdcffe2fc0ca612b4b3e4ea | clburlison_scripts/dropbox_folder_location/dropbox_folder_location.py | clburlison_scripts/dropbox_folder_location/dropbox_folder_location.py | #!/usr/bin/python
"""H/t to eholtam for posting in slack"""
import json
import os
print("Personal: ")
f = open(os.path.expanduser('~/.dropbox/info.json'), 'r').read()
data = json.loads(f)
print(data.get('personal', {}).get('path', '').replace('', 'None'))
print("Business: ")
f = open(os.path.expanduser('~/.dropbox/i... | #!/usr/bin/python
import json, os, pprint
f = open(os.path.expanduser('~/.dropbox/info.json'), 'r').read()
data = json.loads(f)
# To list all dropbox data
pprint.pprint(data)
print('')
# Or to find just the paths
for i in ['personal', 'business']:
print('{}:'.format(i.capitalize()))
print(data.get(i, {}).ge... | Update dropbox folder location script | Update dropbox folder location script
| Python | mit | clburlison/scripts,clburlison/scripts,clburlison/scripts |
7a5fdf50f4a986336c577ce57ed73da1c445b6cd | db_mutex/models.py | db_mutex/models.py | from django.db import models
class DBMutex(models.Model):
"""
Models a mutex lock with a ``lock_id`` and a ``creation_time``.
:type lock_id: str
:param lock_id: A unique CharField with a max length of 256
:type creation_time: datetime
:param creation_time: The creation time of the mutex lock... | from django.db import models
class DBMutex(models.Model):
"""
Models a mutex lock with a ``lock_id`` and a ``creation_time``.
:type lock_id: str
:param lock_id: A unique CharField with a max length of 256
:type creation_time: datetime
:param creation_time: The creation time of the mutex lock... | Declare app_label in model Meta class to work with Django 1.9 | Declare app_label in model Meta class to work with Django 1.9
Fixes RemovedInDjango19Warning:
Model class db_mutex.models.DBMutex doesn't declare an explicit
app_label and either isn't in an application in INSTALLED_APPS or else
was imported before its application was loaded. This will no longer be
supported in Djan... | Python | mit | ambitioninc/django-db-mutex,minervaproject/django-db-mutex |
a89f2f52170ffbb238d01f58650bcb4e55f3253a | structure.py | structure.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# We are assuming, that there is an already configured logger present
logger = logging.getLogger(__name__)
class Structure(object):
"""Simple struct-like object.
members are controlled via the contents of the __slots__ list."""
__slots__ = []
"""Structur... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# We are assuming, that there is an already configured logger present
logger = logging.getLogger(__name__)
class Structure(object):
"""Simple struct-like object.
members are controlled via the contents of the __slots__ list."""
__slots__ = []
"""Structur... | Structure keyword get accepted now | Bugfix: Structure keyword get accepted now
| Python | mit | hastern/jelly |
91c3f218bdd5a660568238daa16c217501d39d05 | create_database.py | create_database.py | import author
import commit
import config
import os
import pygit2
import sqlalchemy
repo = pygit2.Repository(config.REPO_PATH)
# Probably want to completly reset the DB
if config.RESET_DB and os.path.exists(config.DB_PATH):
os.remove(config.DB_PATH)
engine = sqlalchemy.create_engine(config.DB_URL, echo=True)
conf... | from author import Author
from commit import Commit
import config
import os
import pygit2
import sqlalchemy
# If it exists and we want to reset the DB, remove the file
if config.RESET_DB and os.path.exists(config.DB_PATH):
os.remove(config.DB_PATH)
engine = sqlalchemy.create_engine(config.DB_URL, echo=False)
confi... | Create database now properly loads all authors and commits into the repository | Create database now properly loads all authors and commits into the repository
| Python | mit | mglidden/git-analysis,mglidden/git-analysis |
28681f8b2f88f818c2b5a0197a00df90d3065aaf | models/official/detection/configs/factory.py | models/official/detection/configs/factory.py | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | Fix shapemask_config import to handle copy.bara masking that allows cloud detection test to pass. | Fix shapemask_config import to handle copy.bara masking that allows cloud detection test to pass.
PiperOrigin-RevId: 267404830
| Python | apache-2.0 | tensorflow/tpu,tensorflow/tpu,tensorflow/tpu,tensorflow/tpu |
a51c8238ba61d213d089767ba38f18f29dacb08f | dakis/api/views.py | dakis/api/views.py | from rest_framework import serializers, viewsets
from rest_framework import filters
from django.contrib.auth.models import User
from dakis.core.models import Experiment, Task
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Experiment
exclude = ('author',)
... | from rest_framework import serializers, viewsets
from rest_framework import filters
from django.contrib.auth.models import User
from dakis.core.models import Experiment, Task
class ExperimentSerializer(serializers.HyperlinkedModelSerializer):
id = serializers.IntegerField(label='ID', read_only=True)
class ... | Add exp and task ids to API | Add exp and task ids to API
| Python | agpl-3.0 | niekas/dakis,niekas/dakis,niekas/dakis |
fedd90e80a6c56ab406e52b9b0ece14b324fa5d5 | aldryn_apphooks_config/fields.py | aldryn_apphooks_config/fields.py | # -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
class AppHookConfigField(models.ForeignKey):
def __init__(self, *args, **kwargs):
kwargs.update({'help_text': _(u'When selecting ... | # -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.utils.translation import ugettext_lazy as _
from .widgets import AppHookConfigWidget
class AppHookConfigFormField(forms.ModelChoiceField):
def __init__(self, queryset, empty_label="---------", required=True,
wi... | Improve the ability for developers to extend or modify | Improve the ability for developers to extend or modify
| Python | bsd-3-clause | aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config,aldryn/aldryn-apphooks-config |
16002b001a120410e4f993ad6fb93b123de183cb | astrodynamics/tests/test_util.py | astrodynamics/tests/test_util.py | # coding: utf-8
from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.... | # coding: utf-8
from __future__ import absolute_import, division, print_function
import pytest
from astropy import units as u
from astrodynamics.util import verify_unit
def test_verify_unit():
# Implicit dimensionless values are allowed, test that Quantity is returned.
assert verify_unit(0, u.one) == 0 * u.... | Test string form of verify_unit | Test string form of verify_unit
| Python | mit | python-astrodynamics/astrodynamics,python-astrodynamics/astrodynamics |
631bfc08a31477a81103cb83329ce4b29d977658 | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_rem... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scra... | Migrate correctly from scratch also | Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a se... | Python | agpl-3.0 | JioEducation/edx-platform,Lektorium-LLC/edx-platform,cecep-edu/edx-platform,jzoldak/edx-platform,eduNEXT/edunext-platform,chrisndodge/edx-platform,gsehub/edx-platform,shabab12/edx-platform,arbrandes/edx-platform,CredoReference/edx-platform,fintech-circle/edx-platform,miptliot/edx-platform,amir-qayyum-khan/edx-platform,... |
e8fb50e265d62086fa2501f55e7763e49b775440 | scripts/generate-s3-post-url-data.py | scripts/generate-s3-post-url-data.py | #!/usr/bin/env python
"""
This script will create a presigned url and fields for POSTING to an s3 bucket. This allows someone without permissions
on the bucket to upload a file.
This script must be run by an entity with the right permissions on the bucket.
The url will expire after 600 seconds.
Usage:
scripts/genera... | #!/usr/bin/env python
"""
This script will create a presigned url and fields for POSTING to an s3 bucket. This allows someone without permissions
on the bucket to upload a file.
This script must be run by an entity with the right permissions on the bucket.
The url will expire after 600 seconds.
Usage:
scripts/genera... | Apply bucket-owner-read acl to uploaded db dumps | Apply bucket-owner-read acl to uploaded db dumps
As per https://docs.aws.amazon.com/AmazonS3/latest/dev/crr-troubleshoot.html
> By default, the bucket owner does not have any permissions on the objects created by <another> account. And the replication configuration replicates only the objects for which the bucket own... | Python | mit | alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws,alphagov/digitalmarketplace-aws |
5d57c43ba7a01dc0f94ab41e4014484d1b78c1cb | django_polymorphic_auth/admin.py | django_polymorphic_auth/admin.py | from django.conf import settings
from django.contrib import admin
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmi... | from django.conf import settings
from django.contrib import admin
from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from poly... | Integrate `UserChangeForm` so we get nice password fields. | Integrate `UserChangeForm` so we get nice password fields.
| Python | mit | whembed197923/django-polymorphic-auth,ixc/django-polymorphic-auth |
998da5c8d68dff5ad612847a2d16fb6464e30bc2 | semillas_backend/users/models.py | semillas_backend/users/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import
from django.contrib.auth.models import AbstractUser
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy... | Test for uploading files to /media/ folder in S3 | Test for uploading files to /media/ folder in S3
| Python | mit | Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform |
bcf7d7eb689ec4e926a659bce3bf8301c23bd7e0 | test/utu_test.py | test/utu_test.py | import utu
import unittest
def run_test(test):
runner = unittest.runner.TextTestRunner()
loader = unittest.loader.defaultTestLoader
test = loader.loadTestsFromTestCase(test)
runner.run(test)
class UtuTest(unittest.TestCase):
def test_sanity(self):
# XXX should work out why I cannot use an ... | import utu
import unittest
def invoke(test):
runner = unittest.runner.TextTestRunner()
loader = unittest.loader.defaultTestLoader
test = loader.loadTestsFromTestCase(test)
runner.run(test)
class UtuTest(unittest.TestCase):
def test_sanity(self):
# XXX should work out why I cannot use an or... | Rename run_test to invoke to avoid confusing nosetests | Rename run_test to invoke to avoid confusing nosetests
| Python | bsd-2-clause | p/utu |
be093e7df91ca68e4e9c73e37d18042cc5029b87 | bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py | bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py | import pandas as pd
import sys
df = pd.read_csv(sys.argv[1])
df.columns = [c.lower() for c in df.columns]
from sqlalchemy import create_engine
engine = create_engine('postgresql://postgresql.service.consul:5432/germline_genotype_tracking')
try:
df.to_sql("pcawg_samples", engine)
except ValueError as e:
if s... | import pandas as pd
import sys
df = pd.read_csv(sys.argv[1])
df.columns = [c.lower() for c in df.columns]
from sqlalchemy import create_engine
engine = create_engine('postgresql://pcawg_admin:pcawg@postgresql.service.consul:5432/germline_genotype_tracking')
try:
df.to_sql("pcawg_samples", engine)
except ValueEr... | Add DB credentials to sqlalchemy connection. | Add DB credentials to sqlalchemy connection.
| Python | mit | llevar/germline-regenotyper,llevar/germline-regenotyper |
f313c9c476f6ae441f65567552ed835e96c62cb3 | avocado/tests/settings.py | avocado/tests/settings.py | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
MODELTREES = {
'default': {
'model': 'tests.Employee'
}
}
INSTALLED_APPS = (
'avocado',
'avocado.meta',
'avocado.tests',
)
COVERAGE_MODULES = (
'avocado.meta.formatters',
'avocado.meta.exporters... | DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
MODELTREES = {
'default': {
'model': 'tests.Employee'
}
}
INSTALLED_APPS = (
'avocado',
'avocado.meta',
'avocado.tests',
)
COVERAGE_MODULES = (
'avocado.meta.formatters',
'avocado.meta.exporters... | Add json exporter module to modules coveraged | Add json exporter module to modules coveraged | Python | bsd-2-clause | murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.