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 |
|---|---|---|---|---|---|---|---|---|---|
22cb22dfdb5ec4c19e8a90f65483cf372c5731a0 | src/examples/command_group.py | src/examples/command_group.py | from cmdtree import group, argument, entry
@group("docker")
@argument("ip")
def docker():
pass
# nested command
@docker.command("run")
@argument("container-name")
def run(ip, container_name):
print(
"container [{name}] on host [{ip}]".format(
ip=ip,
name=container_name,
... | from cmdtree import group, argument, entry
@group("fake-docker", "fake-docker command binds")
def fake_docker():
pass
@group("docker", "docker command binds")
@argument("ip", help="docker daemon ip addr")
def docker():
pass
# nested command
@docker.command("run", help="run docker command")
@argument("cont... | Update examples for multiple group | Update: Update examples for multiple group
| Python | mit | winkidney/cmdtree,winkidney/cmdtree |
934acb38906b9b6e42620d2e8153dbfd129f01e4 | src/damis/models.py | src/damis/models.py | from django.db import models
from django.contrib.auth.models import User
class DatasetLicence(models.Model):
title = models.CharField(max_length=255)
short_title = models.CharField(max_length=30)
url = models.URLField()
summary = models.TextField()
updated = models.DateTimeField(auto_now=True)
... | from django.db import models
from django.contrib.auth.models import User
class DatasetLicence(models.Model):
title = models.CharField(max_length=255)
short_title = models.CharField(max_length=30)
url = models.URLField()
summary = models.TextField()
updated = models.DateTimeField(auto_now=True)
... | Add slug field to Dataset model. Using slugs for API looks better than pk. | Add slug field to Dataset model. Using slugs for API looks better than pk.
| Python | agpl-3.0 | InScience/DAMIS-old,InScience/DAMIS-old |
6b1ad76140741fd29d8a0d0a0e057b59cd312587 | corehq/sql_db/routers.py | corehq/sql_db/routers.py | from .config import PartitionConfig
PROXY_APP = 'sql_proxy_accessors'
SQL_ACCESSORS_APP = 'sql_accessors'
FORM_PROCESSING_GROUP = 'form_processing'
PROXY_GROUP = 'proxy'
MAIN_GROUP = 'main'
class PartitionRouter(object):
def __init__(self):
self.config = PartitionConfig()
def allow_migrate(self, d... | from .config import PartitionConfig
PROXY_APP = 'sql_proxy_accessors'
SQL_ACCESSORS_APP = 'sql_accessors'
FORM_PROCESSING_GROUP = 'form_processing'
PROXY_GROUP = 'proxy'
MAIN_GROUP = 'main'
class PartitionRouter(object):
def __init__(self):
self.config = PartitionConfig()
def allow_migrate(self, d... | Remove unnecessary call to PartitionConfig | Remove unnecessary call to PartitionConfig
| Python | bsd-3-clause | dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq |
8a0ce66150bb4e1147f5fb88fdd8fd0d391c7daa | dask_ndmeasure/_utils.py | dask_ndmeasure/_utils.py | # -*- coding: utf-8 -*-
| # -*- coding: utf-8 -*-
import numpy
import dask.array
from . import _compat
def _norm_input_labels_index(input, labels=None, index=None):
"""
Normalize arguments to a standard form.
"""
input = _compat._asarray(input)
if labels is None:
labels = (input != 0).astype(numpy.int64)
... | Add arg normalizing function for labels and index | Add arg normalizing function for labels and index
Refactored from code in `center_of_mass`, the `_norm_input_labels_index`
function handles the normalization of `input`, `labels`, and `index`
arguments. As these particular arguments will show up repeatedly in the
API, it will be very helpful to have normalize them in ... | Python | bsd-3-clause | dask-image/dask-ndmeasure |
b8d50cf4f7431ed617957e7d6e432a1729656524 | setuptools/command/__init__.py | setuptools/command/__init__.py | from distutils.command.bdist import bdist
import sys
if 'egg' not in bdist.format_commands:
bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
bdist.format_commands.append('egg')
del bdist, sys
| from distutils.command.bdist import bdist
import sys
if 'egg' not in bdist.format_commands:
try:
bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
except TypeError:
# For backward compatibility with older distutils (stdlib)
bdist.format_command['egg'] = ('bdist_egg', "Pyt... | Update 'bdist' format addition to assume a single 'format_commands' as a dictionary, but fall back to the dual dict/list model for compatibility with stdlib. | Update 'bdist' format addition to assume a single 'format_commands' as a dictionary, but fall back to the dual dict/list model for compatibility with stdlib.
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools |
e392998022ec41b82276464ffecbd859d5e13c63 | src/models/facility_monitoring.py | src/models/facility_monitoring.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
class facility(object):
""" A Facility currently under monitoring
"""
def __init__(self , data) :
self.validated_data = data
def monitor_new_report(self) :
out = np.random.choice(['Validate' , 'Supervise - Data' ... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from reports_monitoring import *
store = pd.HDFStore('../../data/processed/orbf_benin.h5')
data_orbf = store['data']
store.close()
class facility(object):
""" A Facility currently under monitoring
"""
def __init__(self , data) :
... | Add report making for facility | Add report making for facility
| Python | mit | grlurton/orbf_data_validation,grlurton/orbf_data_validation |
7c47a2960d644b34ce3ff569042fb5e965270e8c | netsecus/task.py | netsecus/task.py | from __future__ import unicode_literals
class Task(object):
def __init__(self, taskID, sheetID, name, description, maxPoints, reachedPoints=0):
self.id = taskID
self.sheetID = sheetID
self.name = name
self.description = description
self.maxPoints = maxPoints
self.r... | from __future__ import unicode_literals
class Task(object):
def __init__(self, taskID, sheetID, name, description, maxPoints):
self.id = taskID
self.sheetID = sheetID
self.name = name
self.description = description
self.maxPoints = maxPoints
| Remove unneeded 'reachedPoints' variable from Task class | Remove unneeded 'reachedPoints' variable from Task class
| Python | mit | hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem,hhucn/netsec-uebungssystem |
fac2335ddbd0b3924ab5fe899ce547734b286471 | spec/data/fixtures/__init__.py | spec/data/fixtures/__init__.py | from data import anagram_index, crossword, warehouse
from spec.data.fixtures import tries
def _get_unigram_anagram_index():
return anagram_index.AnagramIndex(warehouse.get('/words/unigram/trie'))
def _get_unigram_trie():
return tries.kitchen_sink()
def _get_crossword():
connection = crossword.init(':memory:')... | import collections
from data import anagram_index, crossword, warehouse
from spec.data.fixtures import tries
def _get_unigram():
return collections.OrderedDict(tries.kitchen_sink_data())
def _get_unigram_anagram_index():
return anagram_index.AnagramIndex(warehouse.get('/words/unigram'))
def _get_unigram_trie()... | Introduce unigram data to warehouse module. | Introduce unigram data to warehouse module.
| Python | mit | PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge,PhilHarnish/forge |
c20a0eb932f99ee4d1336560f25e3e46f86d9d17 | oembed/models.py | oembed/models.py | import datetime
from django.db import models
try:
import json
except ImportError:
from django.utils import simplejson as json
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
JSON = 1
XML = 2
FORMAT_CHOICES = (
(JSON, "JSON"),
(XML, "XML"),
)
class Provider... | import json
from django.db import models
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
JSON = 1
XML = 2
FORMAT_CHOICES = (
(JSON, "JSON"),
(XML, "XML"),
)
class ProviderRule(models.Model):
name = models.CharField(_("name"), max_length=128, null=True, blank=T... | Update imports (json in Py2.6+); removed unused datetime import | Update imports (json in Py2.6+); removed unused datetime import
| Python | bsd-3-clause | JordanReiter/django-oembed,JordanReiter/django-oembed |
4283aa4bc2c831dc99968929c24b11496078fd26 | nightreads/emails/admin.py | nightreads/emails/admin.py | from django.contrib import admin
from .models import Email
class EmailAdmin(admin.ModelAdmin):
exclude = ('targetted_users', 'is_sent')
admin.site.register(Email, EmailAdmin)
| from django.contrib import admin
from .models import Email
class EmailAdmin(admin.ModelAdmin):
readonly_fields = ('targetted_users', 'is_sent',)
add_fieldsets = (
(None, {
'fields': ('subject', 'message', 'post'),
}),
)
def get_fieldsets(self, request, obj=None):
... | Customize how fields on Email are displayed while adding & editing | Customize how fields on Email are displayed while adding & editing
- Hide fields `targetted_users`, `is_sent` while adding a new
Email object
- Display all fields but make `targetted_users`, `is_sent` fields
read only when editing an Email object
| Python | mit | avinassh/nightreads,avinassh/nightreads |
dd89173cc177f7130eca426eb4fa5737ec59c91d | test/vpp_mac.py | test/vpp_mac.py | """
MAC Types
"""
from util import mactobinary
class VppMacAddress():
def __init__(self, addr):
self.address = addr
def encode(self):
return {
'bytes': self.bytes
}
@property
def bytes(self):
return mactobinary(self.address)
@property
def addr... | """
MAC Types
"""
from util import mactobinary
class VppMacAddress():
def __init__(self, addr):
self.address = addr
def encode(self):
return {
'bytes': self.bytes
}
@property
def bytes(self):
return mactobinary(self.address)
@property
def addr... | Fix L2BD arp termination Test Case | Fix L2BD arp termination Test Case
==============================================================================
L2BD arp termination Test Case
==============================================================================
12:02:21,850 Couldn't stat : /tmp/vpp-unittest-TestL2bdArpTerm-_h44qo/stats.sock
L2BD arp term ... | Python | apache-2.0 | chrisy/vpp,vpp-dev/vpp,FDio/vpp,FDio/vpp,FDio/vpp,FDio/vpp,chrisy/vpp,FDio/vpp,chrisy/vpp,vpp-dev/vpp,chrisy/vpp,vpp-dev/vpp,vpp-dev/vpp,vpp-dev/vpp,FDio/vpp,chrisy/vpp,chrisy/vpp,chrisy/vpp,vpp-dev/vpp,vpp-dev/vpp,FDio/vpp,chrisy/vpp,FDio/vpp |
3f7091cbf22c483672aa6c07ad640ee2c3d18e5b | lbrynet/daemon/auth/factory.py | lbrynet/daemon/auth/factory.py | import logging
import os
from twisted.web import server, guard, resource
from twisted.cred import portal
from lbrynet import conf
from .auth import PasswordChecker, HttpPasswordRealm
from .util import initialize_api_key_file
log = logging.getLogger(__name__)
class AuthJSONRPCResource(resource.Resource):
def __... | import logging
import os
from twisted.web import server, guard, resource
from twisted.cred import portal
from lbrynet import conf
from .auth import PasswordChecker, HttpPasswordRealm
from .util import initialize_api_key_file
log = logging.getLogger(__name__)
class AuthJSONRPCResource(resource.Resource):
def __... | Make curl work in py3 again | Make curl work in py3 again
| Python | mit | lbryio/lbry,lbryio/lbry,lbryio/lbry |
74f25eccd2153bd63eff338fff19721dc1488b5c | plugoo/assets.py | plugoo/assets.py | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self... | class Asset:
"""
This is an ooni-probe asset. It is a python
iterator object, allowing it to be efficiently looped.
To create your own custom asset your should subclass this
and override the next_asset method and the len method for
computing the length of the asset.
"""
def __init__(self... | Add a line by line parser | Add a line by line parser
| Python | bsd-2-clause | kdmurray91/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,hackerberry/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,lordappsec/oon... |
1455b0a77d323812417e561e50dbd69a219cc9e6 | preconditions.py | preconditions.py | import inspect
class PreconditionError (TypeError):
pass
def preconditions(*precs):
precinfo = []
for p in precs:
spec = inspect.getargspec(p)
if spec.varargs or spec.keywords:
raise PreconditionError(
'Precondition {!r} must not accept * nor ** args.'.format... | from functools import wraps
import inspect
class PreconditionError (TypeError):
pass
def preconditions(*precs):
precinfo = []
for p in precs:
spec = inspect.getargspec(p)
if spec.varargs or spec.keywords:
raise PreconditionError(
'Precondition {!r} must not a... | Implement the interface specification in two easy lines (plus an import). | Implement the interface specification in two easy lines (plus an import).
| Python | mit | nejucomo/preconditions |
519ab89b892a3caead4d1d56a2bf017ef97c135d | tests/basics/OverflowFunctions.py | tests/basics/OverflowFunctions.py | #
# Kay Hayen, mailto:kayhayen@gmx.de
#
# Python test originally created or extracted from other peoples work. The
# parts from me are in the public domain. It is at least Free Software
# where it's copied from other people. In these cases, it will normally be
# indicated.
#
# If you submit Kay ... | #
# Kay Hayen, mailto:kayhayen@gmx.de
#
# Python test originally created or extracted from other peoples work. The
# parts from me are in the public domain. It is at least Free Software
# where it's copied from other people. In these cases, it will normally be
# indicated.
#
# If you submit Kay ... | Cover an even deeper nesting of closures for the overflow function, still commented out though. | Cover an even deeper nesting of closures for the overflow function, still commented out though.
| Python | apache-2.0 | wfxiang08/Nuitka,tempbottle/Nuitka,kayhayen/Nuitka,kayhayen/Nuitka,tempbottle/Nuitka,tempbottle/Nuitka,kayhayen/Nuitka,tempbottle/Nuitka,wfxiang08/Nuitka,wfxiang08/Nuitka,kayhayen/Nuitka,wfxiang08/Nuitka |
792a4c92c9718e202fb8b180f76c8a08b374e223 | lib/sparkperf/mesos_cluster.py | lib/sparkperf/mesos_cluster.py | from sparkperf.cluster import Cluster
import json
import re
import os
import sys
import time
import urllib2
class MesosCluster(Cluster):
"""
Functionality for interacting with a already running Mesos Spark cluster.
All the behavior for starting and stopping the cluster is not supported.
"""
def _... | from sparkperf.cluster import Cluster
import json
import os
import urllib2
class MesosCluster(Cluster):
"""
Functionality for interacting with a already running Mesos Spark cluster.
All the behavior for starting and stopping the cluster is not supported.
"""
def __init__(self, spark_home, mesos_m... | Remove unused imports in mesos cluster | Remove unused imports in mesos cluster
| Python | apache-2.0 | arijitt/spark-perf,jkbradley/spark-perf,feynmanliang/spark-perf,mengxr/spark-perf,XiaoqingWang/spark-perf,databricks/spark-perf,mengxr/spark-perf,nchammas/spark-perf,zsxwing/spark-perf,XiaoqingWang/spark-perf,zsxwing/spark-perf,arijitt/spark-perf,Altiscale/spark-perf,Altiscale/spark-perf,nchammas/spark-perf,jkbradley/s... |
2c02816c05f3863ef76b3a412ac5bad9eecfafdd | testrepository/tests/test_setup.py | testrepository/tests/test_setup.py | #
# Copyright (c) 2009 Testrepository Contributors
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two lic... | #
# Copyright (c) 2009 Testrepository Contributors
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two lic... | Make setup.py smoke test more specific again as requested in review | Make setup.py smoke test more specific again as requested in review | Python | apache-2.0 | masayukig/stestr,masayukig/stestr,mtreinish/stestr,mtreinish/stestr |
6ab508d67d5e178abbf961479cab25beb0b6dc32 | tests/integration/aiohttp_utils.py | tests/integration/aiohttp_utils.py | import aiohttp
async def aiohttp_request(loop, method, url, output='text', **kwargs): # NOQA: E999
async with aiohttp.ClientSession(loop=loop) as session: # NOQA: E999
response = await session.request(method, url, **kwargs) # NOQA: E999
if output == 'text':
content = await response.... | import aiohttp
async def aiohttp_request(loop, method, url, output='text', **kwargs): # NOQA: E999
async with aiohttp.ClientSession(loop=loop) as session: # NOQA: E999
async with session.request(method, url, **kwargs) as response: # NOQA: E999
if output == 'text':
content = ... | Fix aiohttp_request to properly perform aiohttp requests | Fix aiohttp_request to properly perform aiohttp requests
| Python | mit | kevin1024/vcrpy,kevin1024/vcrpy,graingert/vcrpy,graingert/vcrpy |
81b3e9c6ec89123eedaf53931cfa9c9bc6817d3c | django_q/__init__.py | django_q/__init__.py | import os
import sys
from django import get_version
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath)
VERSION = (0, 7, 18)
default_app_config = 'django_q.apps.DjangoQConfig'
# root imports will slowly be deprecated.
# please import from the relevant sub modules
split_version = get_versi... | import os
import sys
from django import get_version
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath)
VERSION = (0, 7, 18)
default_app_config = 'django_q.apps.DjangoQConfig'
# root imports will slowly be deprecated.
# please import from the relevant sub modules
split_version = get_versi... | Add django 1.11 to the import check | Add django 1.11 to the import check | Python | mit | Koed00/django-q |
b2cbc41f0ba422bfa666022e93be135899441430 | tohu/cloning.py | tohu/cloning.py | __all__ = ['CloneableMeta']
class CloneableMeta(type):
def __new__(metacls, cg_name, bases, clsdict):
new_cls = super(CloneableMeta, metacls).__new__(metacls, cg_name, bases, clsdict)
return new_cls | __all__ = ['CloneableMeta']
def attach_new_init_method(cls):
"""
Replace the existing cls.__init__() method with a new one which
also initialises the _clones attribute to an empty list.
"""
orig_init = cls.__init__
def new_init(self, *args, **kwargs):
orig_init(self, *args, **kwargs)... | Add _clones attribute in new init method | Add _clones attribute in new init method
| Python | mit | maxalbert/tohu |
ed658354ebfa068441b974fe61056ed74aa4254d | lmod/__init__.py | lmod/__init__.py | import os # require by lmod output evaluated by exec()
from functools import partial
from os import environ
from subprocess import Popen, PIPE
LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '')
def module(command, *args):
cmd = (environ['LMOD_CMD'], 'python', '--terse', command)
result = Popen(cmd + arg... | import os # require by lmod output evaluated by exec()
from functools import partial
from os import environ
from subprocess import Popen, PIPE
LMOD_SYSTEM_NAME = environ.get('LMOD_SYSTEM_NAME', '')
def module(command, *args):
cmd = (environ['LMOD_CMD'], 'python', '--terse', command)
result = Popen(cmd + arg... | Remove system name from savelist in lmod | Remove system name from savelist in lmod | Python | mit | cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod,cmd-ntrf/jupyter-lmod |
9d162a2919a1c9b56ded74d40963fa022fc7943b | src/config/settings/testing.py | src/config/settings/testing.py | """Django configuration for testing and CI environments."""
from .common import *
# Use in-memory file storage
DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
# Speed!
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
# Database
DATABASES = {
'default': {
'ENGINE': 'dj... | """Django configuration for testing and CI environments."""
from .common import *
# Use in-memory file storage
DEFAULT_FILE_STORAGE = 'inmemorystorage.InMemoryStorage'
# Speed!
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
# Database
DATABASES = {
'default': {
'ENGINE': 'dj... | Disable logging in test runs | Disable logging in test runs
SPEED!
| Python | agpl-3.0 | FlowFX/unkenmathe.de,FlowFX/unkenmathe.de,FlowFX/unkenmathe.de,FlowFX/unkenmathe.de |
2033c71a84f03e7e8d40c567e632afd2e013aad3 | url/__init__.py | url/__init__.py | #!/usr/bin/env python
#
# Copyright (c) 2012-2013 SEOmoz, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, m... | #!/usr/bin/env python
#
# Copyright (c) 2012-2013 SEOmoz, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, m... | Drop unused import of sys. | Drop unused import of sys.
| Python | mit | seomoz/url-py,seomoz/url-py |
a10e21a8fe811e896998ba510255592a966f0782 | infra/recipes/build_windows.py | infra/recipes/build_windows.py | # Copyright 2022 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine.post_process import Filter
PYTHON_VERSION_COMPATIBILITY = "PY3"
DEPS = [
"crosvm",
"recipe_engine/buildbucket",
"recipe_engine/context",
"re... | # Copyright 2022 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine.post_process import Filter
PYTHON_VERSION_COMPATIBILITY = "PY3"
DEPS = [
"crosvm",
"recipe_engine/buildbucket",
"recipe_engine/context",
"re... | Enable clippy in windows LUCI | crosvm: Enable clippy in windows LUCI
For linux based systems, clippy continues to run in health_check
BUG=b:257249038
TEST=CQ
Change-Id: I39d3d45a0db72c61e79fd2c51b195b82c067a244
Reviewed-on: https://chromium-review.googlesource.com/c/crosvm/crosvm/+/3993934
Reviewed-by: Dennis Kempin <cd09796fb571bec2782819dbfd333... | Python | bsd-3-clause | google/crosvm,google/crosvm,google/crosvm,google/crosvm |
fbdf73e3e9fb5f2801ec11637caa6020095acfdf | terrabot/packets/packetE.py | terrabot/packets/packetE.py | from terrabot.util.streamer import Streamer
from terrabot.events.events import Events
class PacketEParser(object):
def parse(self, world, player, data, ev_man):
#If player is active
if data[2] == 1:
#Raise event with player_id
ev_man.raise_event(Events.NewPlayer, data[1])... | from terrabot.util.streamer import Streamer
from terrabot.events.events import Events
class PacketEParser(object):
def parse(self, world, player, data, ev_man):
#If player is active
if data[2] == 1 and player.logged_in:
#Raise event with player_id
ev_man.raise_event(Event... | Fix with 'newPlayer' event triggering on load | Fix with 'newPlayer' event triggering on load
| Python | mit | flammified/terrabot |
5dcb2564653e4b38359ca6f3e55195839d32ae67 | tests/test_cmd.py | tests/test_cmd.py | import unittest
from unittest import mock
from click.testing import CliRunner
from scuevals_api.cmd import cli
class CmdsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.runner = CliRunner()
def cli_run(self, *cmds):
return self.runner.invoke(cli, cmds)
... | import unittest
from unittest import mock
from click.testing import CliRunner
from scuevals_api.cmd import cli
class CmdsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.runner = CliRunner()
def cli_run(self, *cmds):
return self.runner.invoke(cli, cmds)
... | Set test for start cmd to test env | Set test for start cmd to test env
| Python | agpl-3.0 | SCUEvals/scuevals-api,SCUEvals/scuevals-api |
0ccb85a45e56438a5e4b7c0566634587624f0ce4 | tests/test_log.py | tests/test_log.py | # -*- coding: utf-8 -*-
from flask import url_for
def test_view_build_log(test_client):
test_client.get(url_for('log.build_log', sha='123456'))
def test_view_lint_log(test_client):
test_client.get(url_for('log.lint_log', sha='123456'))
| # -*- coding: utf-8 -*-
from flask import url_for
def test_view_build_log(test_client):
test_client.get(url_for('log.build_log', sha='123456'))
| Remove lint_log view test case | Remove lint_log view test case
| Python | mit | bosondata/badwolf,bosondata/badwolf,bosondata/badwolf |
aa008a13d9d10107f440dca71085f21d9622cd95 | src/pybel/parser/baseparser.py | src/pybel/parser/baseparser.py | # -*- coding: utf-8 -*-
import logging
import time
log = logging.getLogger(__name__)
__all__ = ['BaseParser']
class BaseParser:
"""This abstract class represents a language backed by a PyParsing statement
Multiple parsers can be easily chained together when they are all inheriting from this base class
... | # -*- coding: utf-8 -*-
import logging
import time
log = logging.getLogger(__name__)
__all__ = ['BaseParser']
class BaseParser:
"""This abstract class represents a language backed by a PyParsing statement
Multiple parsers can be easily chained together when they are all inheriting from this base class
... | Add line state to base parser | Add line state to base parser
References #155
| Python | mit | pybel/pybel,pybel/pybel,pybel/pybel |
0edc91468c5f424a57be80675422723f9bac4a89 | falmer/auth/admin.py | falmer/auth/admin.py | from django.contrib import admin
from django.contrib.admin import register
from . import models
@register(models.FalmerUser)
class FalmerUserModelAdmin(admin.ModelAdmin):
list_display = ('name_or_email', 'identifier', 'authority')
list_filter = ('authority', )
search_fields = ('name', 'identifier')
| from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
# @register(models.FalmerUser)
# class FalmerUserModelAdmin(admin.ModelAdmin):
# list_display = ('name_or_email', 'identifier', 'authority')
# list_filter = ('authority', )
# search_fields = ('name', 'identifier')
from falmer.... | Replace FalmerUserAdmin with extention of base | Replace FalmerUserAdmin with extention of base
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer |
ea54f0a306c6defa4edc58c50794da0083ed345d | setup_app.py | setup_app.py |
import os
from flask_app.database import init_db
# Generate new secret key
secret_key = os.urandom(24).encode('hex').strip()
with open('flask_app/secret_key.py', 'w') as key_file:
key_file.write('secret_key = """' + secret_key + '""".decode("hex")')
# Initialize database
init_db()
|
import os
from flask_app.database import init_db
# Generate new secret key
key_file_path = 'flask_app/secret_key.py'
if not os.path.isfile(key_file_path):
secret_key = os.urandom(24).encode('hex').strip()
with open(key_file_path, 'w') as key_file:
key_file.write('secret_key = """' + secret_key + '""".... | Check if keyfile exists before generating new key | Check if keyfile exists before generating new key
| Python | mit | szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft |
0451d8e1ee2ad136e3b0f69c43dca9658fdbb85c | 16B/spw_setup.py | 16B/spw_setup.py |
# Line SPW setup for 16B projects
linespw_dict = {0: ["HI", "1.420405752GHz"],
3: ["OH1612", "1.612231GHz"],
5: ["OH1665", "1.6654018GHz"],
6: ["OH1667", "1.667359GHz"],
7: ["OH1720", "1.72053GHz"],
9: ["H152alp", "1.85425GHz"],
... |
# Line SPW setup for 16B projects
linespw_dict = {0: ["HI", "1.420405752GHz", 4096],
3: ["OH1612", "1.612231GHz", 256],
5: ["OH1665", "1.6654018GHz", 256],
6: ["OH1667", "1.667359GHz", 256],
7: ["OH1720", "1.72053GHz", 256],
9: ["H152alp"... | Add channel numbers to 16B spectral setup | Add channel numbers to 16B spectral setup
| Python | mit | e-koch/VLA_Lband,e-koch/VLA_Lband |
e4b516f612d60eac8cb278d1c8675b3fdbad8652 | windmill/server/__init__.py | windmill/server/__init__.py | # Copyright (c) 2006-2007 Open Source Applications Foundation
# Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | # Copyright (c) 2006-2007 Open Source Applications Foundation
# Copyright (c) 2008-2009 Mikeal Rogers <mikeal.rogers@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | Fix for [ticket:281]. Do not forward livebookmarks request. | Fix for [ticket:281]. Do not forward livebookmarks request.
git-svn-id: 87d19257dd11500985d055ec4730e446075a5f07@1261 78c7df6f-8922-0410-bcd3-9426b1ad491b
| Python | apache-2.0 | ept/windmill,ept/windmill,ept/windmill |
6c891692c5595f4cf9822bee6b42a33f141af5ed | fmn/consumer/util.py | fmn/consumer/util.py | import fedora.client
import logging
log = logging.getLogger("fmn")
def new_packager(topic, msg):
""" Returns a username if the message is about a new packager in FAS. """
if '.fas.group.member.sponsor' in topic:
group = msg['msg']['group']
if group == 'packager':
return msg['msg']... | import fedora.client
import logging
log = logging.getLogger("fmn")
def new_packager(topic, msg):
""" Returns a username if the message is about a new packager in FAS. """
if '.fas.group.member.sponsor' in topic:
group = msg['msg']['group']
if group == 'packager':
return msg['msg']... | Use dict interface to bunch. | Use dict interface to bunch.
I'm not sure why, but we got this error on the server::
Traceback (most recent call last):
File "fmn/consumer/util.py", line 33, in get_fas_email
if person.email:
AttributeError: 'dict' object has no attribute 'email'
This should fix that.
| Python | lgpl-2.1 | jeremycline/fmn,jeremycline/fmn,jeremycline/fmn |
349b0ca88a85a8e9f234debe35807d2c9bc93544 | src/setup.py | src/setup.py | from distutils.core import setup
from distutils.command.install import install
import os
import shutil
class issue(Exception):
def __init__(self, errorStr):
self.errorStr = errorStr
def __str__(self):
return repr(self.errorStr)
class post_install(install):
def copyStuff(self, dataDir, des... | from distutils.core import setup
from distutils.command.install import install
import os
import shutil
class issue(Exception):
def __init__(self, errorStr):
self.errorStr = errorStr
def __str__(self):
return repr(self.errorStr)
class post_install(install):
def copyStuff(self, dataDir, des... | Add clusterDB to python egg | Add clusterDB to python egg
| Python | apache-2.0 | deepgrant/deep-tools |
a2776a5cfcad7e9957eb44ab5882d36878026b1e | property_transformation.py | property_transformation.py | from types import UnicodeType, StringType
class PropertyMappingFailedException(Exception):
pass
def get_transformed_properties(source_properties, prop_map):
results = {}
for key, value in prop_map.iteritems():
if type(value) in (StringType, UnicodeType):
if value in source_properties:
... | from types import UnicodeType, StringType
class PropertyMappingFailedException(Exception):
pass
def get_transformed_properties(source_properties, prop_map):
results = {}
for key, value in prop_map.iteritems():
if type(value) in (StringType, UnicodeType):
if value in source_properties:
... | Add option to include static values in properties | Add option to include static values in properties
| Python | mit | OpenBounds/Processing |
eb698848c67a5f2ffe1b47c2b4620946f3133c3f | pyautoupdate/_move_glob.py | pyautoupdate/_move_glob.py | import glob
import shutil
import os
def move_glob(src,dst):
"""Moves files from src to dest.
src may be any glob to recognize files. dst must be a folder."""
for obj in glob.iglob(src):
shutil.move(obj,dst)
def copy_glob(src,dst):
"""Copies files from src to dest.
src may be any glob to ... | import glob
import shutil
import os
if os.name == "nt":
from .ntcommonpath import commonpath
else:
from .posixcommonpath import commonpath
def move_glob(src,dst):
"""Moves files from src to dest.
src may be any glob to recognize files. dst must be a folder."""
for obj in glob.iglob(src):
... | Use backported commonpath instead of built in os.path.commonpath | Use backported commonpath instead of built in os.path.commonpath
The built in one is only available for Python 3.5
| Python | lgpl-2.1 | rlee287/pyautoupdate,rlee287/pyautoupdate |
397e4b3841dde6f82ad7f1d3f6458f99da69d678 | px/px_install.py | px/px_install.py | import sys
import shutil
import os
def install(src, dest):
"""
Copy src (file) into dest (file) and make dest executable.
On trouble, prints message and exits with an error code.
"""
try:
_install(src, dest)
except Exception as e:
sys.stderr.write("Installing {} failed, pleas... | import sys
import shutil
import os
def install(src, dest):
"""
Copy src (file) into dest (file) and make dest executable.
On trouble, prints message and exits with an error code.
"""
try:
_install(src, dest)
except Exception as e:
sys.stderr.write("Installing {} failed, pleas... | Handle installing px on top of itself | Handle installing px on top of itself
| Python | mit | walles/px,walles/px |
0c3ed07548cd196ceac2641a38f4d20a1e104d11 | admin/test/test_acceptance.py | admin/test/test_acceptance.py | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for ``admin.acceptance``.
"""
from zope.interface.verify import verifyObject
from twisted.trial.unittest import SynchronousTestCase
from ..acceptance import IClusterRunner, ManagedRunner
class ManagedRunnerTests(SynchronousTestCase):
"""
... | # Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""
Tests for ``admin.acceptance``.
"""
from zope.interface.verify import verifyObject
from twisted.trial.unittest import SynchronousTestCase
from ..acceptance import IClusterRunner, ManagedRunner
from flocker.provision import PackageSource
from flocker.ac... | Create the ManagedRunner with all the new args. | Create the ManagedRunner with all the new args.
| Python | apache-2.0 | jml/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,AndyHuu/flocker,adamtheturtle/flocker,mbrukman/flocker,lukemarsden/flocker,hackday-profilers/flocker,achanda/flocker,w4ngyi/flocker,1d4Nf6/flocker,Azulinho/flocker,mbrukman/flocker,LaynePeng/flocker,w4ngyi/flocker,moypray/flocker,w4ngyi/flocker,LaynePeng/floc... |
fb82b4f77379ddd1525947cc61f1c46c34674da4 | froide/publicbody/admin.py | froide/publicbody/admin.py | from django.contrib import admin
from froide.publicbody.models import (PublicBody, FoiLaw, PublicBodyTopic,
Jurisdiction)
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'email', 'url', 'classification', 'topic', 'depth',)
list_filter = ('... | from django.contrib import admin
from froide.publicbody.models import (PublicBody, FoiLaw, PublicBodyTopic,
Jurisdiction)
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'email', 'url', 'classification', 'topic', 'depth',)
list_filter = ('... | Add list filter by jurisdiction for public bodies | Add list filter by jurisdiction for public bodies | Python | mit | LilithWittmann/froide,fin/froide,ryankanno/froide,CodeforHawaii/froide,okfse/froide,stefanw/froide,ryankanno/froide,okfse/froide,stefanw/froide,catcosmo/froide,fin/froide,ryankanno/froide,CodeforHawaii/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,okfse/froide,okfse/froide,LilithWittmann/froide,fin/f... |
6c49d28370cdcd96917286cf68e6a8218db4b8a5 | indra/java_vm.py | indra/java_vm.py | """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import logging
import jnius_config
logger = logging.getLogger('java_vm... | """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import logging
import jnius_config
logger = logging.getLogger('java_vm... | Increase default maximum java heap size | Increase default maximum java heap size
| Python | bsd-2-clause | johnbachman/indra,johnbachman/belpy,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,sorgerlab/indra,pvtodorov/indra,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,bgyori/indra,bgyori/indra,bgyori/indra,sorgerlab/belpy |
f1f500488197a40a007af67c2c8dcc0aaef60dd3 | src/project/word2vec_corpus.py | src/project/word2vec_corpus.py | import sys
from os.path import isdir, isfile
from corpus import Corpus
from gensim import models
class W2VCorpus(Corpus):
def __init__(self, dir, dict_loc, vec_loc):
Corpus.__init__(self, dir)
# Todo: Tweak the default paramaters
self.model = models.Word2Vec(self.docs.get_texts(), size=10... | import sys
from os.path import isdir, isfile
from corpus import Corpus
from gensim import models
class W2VCorpus(Corpus):
def __init__(self, dict_loc, vec_loc, dir=None):
Corpus.__init__(self, dir)
self.dict_loc = dict_loc
self.vec_loc = vec_loc
self.model = None
if dir:
... | Add functionality to load/save w2v model | Add functionality to load/save w2v model
| Python | mit | PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project,PinPinIre/Final-Year-Project |
87c5f39d5cb072a778bb145e6e5fc49c8d4b350d | core/urls.py | core/urls.py | from django.conf.urls import url
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
from .views import AppView, reports_export
# Instead of using a wildcard for our app views we insert them one at a time
# for naming purposes. This is so that users can change urls if they... | from django.conf.urls import url
from django.views.generic import RedirectView
from django.core.urlresolvers import reverse_lazy
from .views import AppView, reports_export
# Instead of using a wildcard for our app views we insert them one at a time
# for naming purposes. This is so that users can change urls if they... | Add ability to go to individual invoice page | Add ability to go to individual invoice page
| Python | bsd-2-clause | cdubz/timestrap,overshard/timestrap,overshard/timestrap,cdubz/timestrap,cdubz/timestrap,overshard/timestrap |
3b7e9d42db8ba0f4f3330544d3789427e7e3858c | python/04-1.py | python/04-1.py | #!/usr/bin/env python
import hashlib
prefix = ''
number = 1
with open('../inputs/04.txt') as f:
prefix = f.readlines()
prefix = prefix[0].rstrip()
while True:
md5 = hashlib.md5()
md5.update('{0}{1}'.format(prefix, number))
if md5.hexdigest()[:5] == '00000':
#print md5.hexdigest()
print num... | #!/usr/bin/env python
import hashlib
prefix = ''
number = 1
with open('../inputs/04.txt') as f:
prefix = f.readlines()
prefix = prefix[0].rstrip()
md5 = hashlib.md5()
md5.update(prefix)
while True:
m = md5.copy()
m.update(str(number))
if m.hexdigest()[:5] == '00000':
print number
break
... | Use md5.copy() to be more efficient. | Use md5.copy() to be more efficient.
The hash.copy() documentation says this is more efficient given a common
initial substring.
| Python | mit | opello/adventofcode |
b179423a7678aef0a8e286977055b25b9b0aac99 | plugin/main.py | plugin/main.py | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_pa... | #!/usr/bin/env python
"""
Deploy builds to a Rancher orchestrated stack using rancher-compose
"""
import os
import drone
import subprocess
def main():
"""The main entrypoint for the plugin."""
payload = drone.plugin.get_input()
vargs = payload["vargs"]
# Change directory to deploy path
deploy_pa... | Print rancher-compose command to help debug/confirmation | Print rancher-compose command to help debug/confirmation
| Python | apache-2.0 | dangerfarms/drone-rancher |
39ed9fecd03f837c1ca7436b4695734b1602a356 | create_sample.py | create_sample.py | # importing modules/ libraries
import pandas as pd
import random
import numpy as np
# create a sample of prior orders
orders_df = pd.read_csv("Data/orders.csv")
s = round(3214874 * 0.1)
i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s))
orders_df.loc[i,:].to_csv("Data/orders_prior_samp... | # importing modules/ libraries
import pandas as pd
import random
import numpy as np
# create a sample of prior orders
orders_df = pd.read_csv("Data/orders.csv")
s = round(3214874 * 0.1)
i = sorted(random.sample(list(orders_df[orders_df["eval_set"]=="prior"].index), s))
orders_df.loc[i,:].to_csv("Data/orders_prior_samp... | Remove index argument while creating order products sample | fix: Remove index argument while creating order products sample
| Python | mit | rjegankumar/instacart_prediction_model |
21f74472d8e229d6e662eff39f90886f4357d8c3 | been/source/markdown.py | been/source/markdown.py | from been.core import DirectorySource, source_registry
class MarkdownDirectory(DirectorySource):
kind = 'markdown'
def process_event(self, event):
lines = event['content'].splitlines()
event['title'] = lines[0]
event['content'] = "\n".join(lines[1:])
event['summary'] = event['co... | from been.core import DirectorySource, source_registry
import re
import unicodedata
def slugify(value):
value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return re.sub('[-\s]+', '-', value)
class MarkdownDirectory... | Add slug generation to Markdown source. | Add slug generation to Markdown source.
| Python | bsd-3-clause | chromakode/been |
54d55ada152338cc038a4249e03ee25c4739c68f | python/sum-of-multiples/sum_of_multiples.py | python/sum-of-multiples/sum_of_multiples.py | def sum_of_multiples(limit, factors):
return sum(all_multiples(limit, factors))
def all_multiples(limit, factors):
multiples = set()
for factor in factors:
multiples = multiples.union(get_multiples(limit, factor))
return multiples
def get_multiples(limit, factor):
if factor == 0:
... | def sum_of_multiples(limit, factors):
return sum(all_multiples(limit, factors))
def all_multiples(limit, factors):
multiples = set()
for factor in factors:
multiples = multiples.union(get_multiples(limit, factor))
return multiples
def get_multiples(limit, factor):
if factor == 0:
... | Refactor to use list comprehension | Refactor to use list comprehension
| Python | mit | rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism,rootulp/exercism |
4ca388ca6ef21d8e93de71e783ea5175a223980e | seleniumbase/console_scripts/rich_helper.py | seleniumbase/console_scripts/rich_helper.py | from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
... | from rich.console import Console
from rich.markdown import Markdown
from rich.syntax import Syntax
def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap):
syntax = Syntax(
code,
lang,
theme=theme,
line_numbers=line_numbers,
code_width=code_width,
... | Update double-width emoji list to improve "sbase print FILE" | Update double-width emoji list to improve "sbase print FILE"
| Python | mit | seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase |
63fbbd36bc9123fc8fe9ed41481dd36373959549 | Helper/Helper/Helper.py | Helper/Helper/Helper.py | def main():
print ("Hello world!")
if __name__ == '__main__':
main() | def main():
try:
fileName = "MengZi_Traditional.md"
filePath = "../../source/" + fileName
with open(filePath, 'r') as file:
for line in file:
print line
except IOError:
print ("The file (" + filePath + ") does not exist.")
if __name__ == '__main__':
... | Read a file from Python | Read a file from Python
| Python | mit | fan-jiang/Dujing |
07bec7db879aee92316570770316857417636207 | addons/hr_payroll_account/wizard/hr_payroll_payslips_by_employees.py | addons/hr_payroll_account/wizard/hr_payroll_payslips_by_employees.py | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class HrPayslipEmployees(models.TransientModel):
_inherit = 'hr.payslip.employees'
@api.multi
def compute_sheet(self):
journal_id = False
if self.env.context.get... | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models
class HrPayslipEmployees(models.TransientModel):
_inherit = 'hr.payslip.employees'
@api.multi
def compute_sheet(self):
if self.env.context.get('active_id'):
... | Remove journal_id: False in context | [FIX] hr_payroll_account: Remove journal_id: False in context
If the wizard to generate payslip was launched without an ´active_id´ in the context.
A ´journal_id´ entry was set to False in the context later leading to a crash at payslip creation.
The crash happens because, at creation time, the journal_id of a ´hr.pay... | Python | agpl-3.0 | ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo |
6487c04c85f890a8d767216efac24bf42fb9e387 | spare5/client.py | spare5/client.py | import requests
from .resources.batches import Batches
from .resources.jobs import Jobs
DEFAULT_API_ROOT = 'http://app.spare5.com/partner/v2'
class Spare5Client(object):
def __init__(self, username, token, api_root=DEFAULT_API_ROOT):
super(Spare5Client, self).__init__()
self.api_root = api_root... | import requests
from .resources.batches import Batches
from .resources.jobs import Jobs
DEFAULT_API_ROOT = 'http://app.spare5.com/partner/v2'
class Spare5Client(object):
def __init__(self, username, token, api_root=DEFAULT_API_ROOT):
super(Spare5Client, self).__init__()
self.api_root = api_root... | Update to specify content-type header | Update to specify content-type header
| Python | mit | roverdotcom/spare5-python |
3d5093b46763acca9e3b3309073f73a7ca8daf73 | src/clients/lib/python/xmmsclient/consts.py | src/clients/lib/python/xmmsclient/consts.py |
from xmmsapi import VALUE_TYPE_NONE
from xmmsapi import VALUE_TYPE_ERROR
from xmmsapi import VALUE_TYPE_UINT32
from xmmsapi import VALUE_TYPE_INT32
from xmmsapi import VALUE_TYPE_STRING
from xmmsapi import VALUE_TYPE_COLL
from xmmsapi import VALUE_TYPE_BIN
from xmmsapi import VALUE_TYPE_LIST
from xmmsapi import VALUE_... |
from xmmsapi import VALUE_TYPE_NONE
from xmmsapi import VALUE_TYPE_ERROR
from xmmsapi import VALUE_TYPE_INT32
from xmmsapi import VALUE_TYPE_STRING
from xmmsapi import VALUE_TYPE_COLL
from xmmsapi import VALUE_TYPE_BIN
from xmmsapi import VALUE_TYPE_LIST
from xmmsapi import VALUE_TYPE_DICT
from xmmsapi import PLAYBACK... | Remove import of nonexistant UINT32 type in python bindings | BUG(2151): Remove import of nonexistant UINT32 type in python bindings
| Python | lgpl-2.1 | mantaraya36/xmms2-mantaraya36,theeternalsw0rd/xmms2,oneman/xmms2-oneman-old,mantaraya36/xmms2-mantaraya36,xmms2/xmms2-stable,theefer/xmms2,theeternalsw0rd/xmms2,six600110/xmms2,chrippa/xmms2,oneman/xmms2-oneman,chrippa/xmms2,xmms2/xmms2-stable,xmms2/xmms2-stable,theeternalsw0rd/xmms2,mantaraya36/xmms2-mantaraya36,theef... |
99ab527550b91d17342ef3112e35f3cdb1be9867 | src/binsearch.py | src/binsearch.py | """
Binary search
"""
def binary_search0(xs, x):
"""
Perform binary search for a specific value in the given sorted list
:param xs: a sorted list
:param x: the target value
:return: an index if the value was found, or None if not
"""
lft, rgt = 0, len(xs) - 1
while lft <= rgt:
... | """
Binary search
"""
def binary_search0(xs, x):
"""
Perform binary search for a specific value in the given sorted list
:param xs: a sorted list
:param x: the target value
:return: an index if the value was found, or None if not
"""
lft, rgt = 0, len(xs) - 1
while lft <= rgt:
... | Fix the "no else after return" lint | Fix the "no else after return" lint
| Python | mit | all3fox/algos-py |
f9926da62fc50c8602797cb12ac80264140c8028 | mfh.py | mfh.py | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import update
from arguments import parse
from settings import HONEYPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfhclient_process",
t... | import os
import sys
import time
from multiprocessing import Process, Event
import mfhclient
import update
from arguments import parse
from settings import HONEYPORT
def main():
update_event = Event()
mfhclient_process = Process(
args=(args, update_event,),
name="mfhclient_process",
t... | Add condition to only launch updater if -u or --updater is specified | Add condition to only launch updater if -u or --updater is specified
| Python | mit | Zloool/manyfaced-honeypot |
967b8cd4d11e8619a8da2b6f9935846559df7347 | bluesky/callbacks/__init__.py | bluesky/callbacks/__init__.py | from .core import (CallbackBase, CallbackCounter, print_metadata, collector,
LiveMesh, LivePlot, LiveRaster, LiveTable, CollectThenCompute,
_get_obj_fields)
| from .core import (CallbackBase, CallbackCounter, print_metadata, collector,
LiveMesh, LivePlot, LiveRaster, LiveTable, CollectThenCompute,
LiveSpecFile, _get_obj_fields)
| Add LiveSpecFile to callbacks API. | API: Add LiveSpecFile to callbacks API.
| Python | bsd-3-clause | ericdill/bluesky,ericdill/bluesky |
788f9a920fdafe6d341432f46295bb737c57cccd | moteconnection/serial_ports.py | moteconnection/serial_ports.py | __author__ = "Raido Pahtma"
__license__ = "MIT"
import glob
import sys
import os
def _list_windows_serial_ports():
raise NotImplementedError("windows support")
def _list_unix_serial_ports(additional=None):
ports = []
port_list = glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyAMA*') + glob.glob('/dev/t... | __author__ = "Raido Pahtma"
__license__ = "MIT"
import re
import os
import sys
import glob
import serial
def _list_windows_serial_ports():
ports = []
for i in range(256):
try:
s = serial.Serial(i)
ports.append(s.portstr)
s.close()
except serial.SerialExcep... | Support for Windows serial ports. | Support for Windows serial ports.
| Python | mit | proactivity-lab/python-moteconnection,proactivity-lab/py-moteconnection |
8fb958821cd58016c56b5eee2c6531827e4c57b8 | modules/juliet_module.py | modules/juliet_module.py | class module:
mod_name = "unnamed_module";
mod_id = -1;
mod_rect = None;
mod_surface = None;
mod_attribs = [];
def __init__(self, _id):
print("Initializing generic module (This shouldn't happen...)");
| from pygame import Rect
class module:
mod_name = "unnamed_module"
mod_id = -1
mod_size = Rect(0,0,0,0)
def __init__(self, _id = -1):
print("Initializing generic module (This shouldn't happen...)")
def draw(self, surf):
"Takes a surface object and blits its data onto it"
pr... | Change module class to use Rect for size and take a surface as an argument to draw() | Change module class to use Rect for size and take a surface as an argument to draw()
| Python | bsd-2-clause | halfbro/juliet |
a5b750b9800b60242e72d9d066a46f98b8a0325e | test/test_recordings.py | test/test_recordings.py | import pytest
import json
class TestRecordings:
def test_unprocessed_recording_doesnt_return_processed_jwt(self, helper):
print("If a new user uploads a recording")
bob = helper.given_new_user(self, "bob_limit")
bobsGroup = helper.make_unique_group_name(self, "bobs_group")
bob.crea... | import pytest
import json
class TestRecordings:
def test_unprocessed_recording_doesnt_return_processed_jwt(self, helper):
print("If a new user uploads a recording")
bob = helper.given_new_user(self, "bob_limit")
bobsGroup = helper.make_unique_group_name(self, "bobs_group")
bob.crea... | Add test to make sure fileKey(s) aren't returned | Add test to make sure fileKey(s) aren't returned
| Python | agpl-3.0 | TheCacophonyProject/Full_Noise |
9442338d329e7f87d6265e0b0d3728a0df18d945 | viper/lexer/reserved_tokens.py | viper/lexer/reserved_tokens.py | RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
| RESERVED_NAMES = {
'def',
'pass',
'return',
'class',
'interface',
'data',
'static',
'public',
'private',
'protected',
'module',
'if',
'elif',
'else',
'or',
'and',
'not',
'for',
'true',
'false',
}
RESERVED_CLASSES = set()
| Update list of reserved tokens | Update list of reserved tokens
| Python | apache-2.0 | pdarragh/Viper |
53fb42f275050986072060a550e4fee09ab418f6 | wagtail/wagtailadmin/checks.py | wagtail/wagtailadmin/checks.py | import os
from django.core.checks import Error, register
@register()
def css_install_check(app_configs, **kwargs):
errors = []
css_path = os.path.join(
os.path.dirname(__file__), 'static', 'wagtailadmin', 'css', 'normalize.css'
)
if not os.path.isfile(css_path):
error_hint = """
... | import os
from django.core.checks import Warning, register
@register()
def css_install_check(app_configs, **kwargs):
errors = []
css_path = os.path.join(
os.path.dirname(__file__), 'static', 'wagtailadmin', 'css', 'normalize.css'
)
if not os.path.isfile(css_path):
error_hint = """
... | Throw warning on missing CSS rather than error, so that tests can still run on Dj1.7 | Throw warning on missing CSS rather than error, so that tests can still run on Dj1.7
| Python | bsd-3-clause | nilnvoid/wagtail,gasman/wagtail,wagtail/wagtail,nutztherookie/wagtail,thenewguy/wagtail,rsalmaso/wagtail,kurtw/wagtail,nilnvoid/wagtail,nutztherookie/wagtail,iansprice/wagtail,thenewguy/wagtail,nimasmi/wagtail,nealtodd/wagtail,Toshakins/wagtail,FlipperPA/wagtail,nilnvoid/wagtail,iansprice/wagtail,zerolab/wagtail,mikedi... |
ae4a13da2857a5826fa701f25b242c95d56995d9 | string_length.py | string_length.py | #!/usr/bin/env python2
#encoding: UTF-8
# Define a function that computes the length of a given list or string.
# (It is true that Python has the len() function built in,
# but writing it yourself is nevertheless a good exercise.)
def string_length(string):
if string == None:
return False
... | #!/usr/bin/env python2
#encoding: UTF-8
# Define a function that computes the length of a given list or string.
# (It is true that Python has the len() function built in,
# but writing it yourself is nevertheless a good exercise.)
def string_length(string):
if string == None:
return False
... | Add support for list input | Add support for list input
| Python | mit | giantas/minor-python-tests |
c45881530694488c5ef139e89c05aa24ddb671ff | djlint/analyzers/context_processors.py | djlint/analyzers/context_processors.py | import ast
from .base import BaseAnalyzer, ModuleVisitor, Result
class ContextProcessorsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.core.context_processors.auth':
'django.contrib.auth.context_processors.auth',
'django.core.cont... | import ast
from .base import BaseAnalyzer, ModuleVisitor, Result
class ContextProcessorsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
deprecated_items = {
'django.core.context_processors.auth':
'django.contrib.auth.context_processors.auth',
'django.core.c... | Fix context processors analyzer: deprecated processors will be removed in Django 1.5 | Fix context processors analyzer: deprecated processors will be removed in Django 1.5
| Python | isc | alfredhq/djlint |
83a086b865c2db791a208d3854c15963ed3fc693 | plum/tests/service_test.py | plum/tests/service_test.py | from unittest import TestCase
from docker import Client
from plum import Service
class ServiceTestCase(TestCase):
def setUp(self):
self.client = Client('http://127.0.0.1:4243')
self.client.pull('ubuntu')
for c in self.client.containers():
self.client.kill(c['Id'])
sel... | from unittest import TestCase
from docker import Client
from plum import Service
class ServiceTestCase(TestCase):
def setUp(self):
self.client = Client('http://127.0.0.1:4243')
self.client.pull('ubuntu')
for c in self.client.containers(all=True):
self.client.kill(c['Id'])
... | Delete all containers on the Docker daemon before running test | Delete all containers on the Docker daemon before running test
| Python | apache-2.0 | phiroict/docker,xydinesh/compose,unodba/compose,shin-/docker.github.io,bdwill/docker.github.io,bsmr-docker/compose,KevinGreene/compose,Katlean/fig,screwgoth/compose,bobphill/compose,aanand/fig,zhangspook/compose,GM-Alex/compose,KevinGreene/compose,saada/compose,docker-zh/docker.github.io,ekristen/compose,jrabbit/compos... |
83a5688181ed3fac058cd1b9b15f885e47578409 | testsuite/E20.py | testsuite/E20.py | #: E201
spam( ham[1], {eggs: 2})
#: E201
spam(ham[ 1], {eggs: 2})
#: E201
spam(ham[1], { eggs: 2})
#: Okay
spam(ham[1], {eggs: 2})
#:
#: E202
spam(ham[1], {eggs: 2} )
#: E202
spam(ham[1], {eggs: 2 })
#: E202
spam(ham[1 ], {eggs: 2})
#: Okay
spam(ham[1], {eggs: 2})
result = func(
arg1='some value',
arg2='anot... | #: E201:1:6
spam( ham[1], {eggs: 2})
#: E201:1:10
spam(ham[ 1], {eggs: 2})
#: E201:1:15
spam(ham[1], { eggs: 2})
#: Okay
spam(ham[1], {eggs: 2})
#:
#: E202:1:23
spam(ham[1], {eggs: 2} )
#: E202:1:22
spam(ham[1], {eggs: 2 })
#: E202:1:11
spam(ham[1 ], {eggs: 2})
#: Okay
spam(ham[1], {eggs: 2})
result = func(
arg1... | Add some tests with row and column | Add some tests with row and column
| Python | mit | jayvdb/pep8,pedros/pep8,fabioz/pep8,MeteorAdminz/pep8,ojengwa/pep8,PyCQA/pep8,codeclimate/pep8,reinout/pep8,ABaldwinHunter/pep8,jayvdb/pep8,reinout/pep8,asandyz/pep8,ABaldwinHunter/pep8-clone-classic,pandeesh/pep8,doismellburning/pep8,fabioz/pep8,zevnux/pep8 |
3c86abb5d2a728604b97a33c3f989039231205b0 | ooni/tests/test_utils.py | ooni/tests/test_utils.py | import unittest
from ooni.utils import pushFilenameStack
class TestUtils(unittest.TestCase):
def test_pushFilenameStack(self):
f = open("dummyfile", "w+")
f.write("0\n")
f.close()
for i in xrange(1, 5):
f = open("dummyfile.%s" % i, "w+")
f.write("%s\n" % i)
... | import os
import unittest
from ooni.utils import pushFilenameStack
basefilename = os.path.abspath('dummyfile')
class TestUtils(unittest.TestCase):
def test_pushFilenameStack(self):
f = open(basefilename, "w+")
f.write("0\n")
f.close()
for i in xrange(1, 5):
f = open(basef... | Use absolute filepath instead of relative | Use absolute filepath instead of relative
| Python | bsd-2-clause | lordappsec/ooni-probe,lordappsec/ooni-probe,Karthikeyan-kkk/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,kdmurray91/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,kdmurray91/ooni-pro... |
6aee8af90e5c09fb56d5d9194f0d0db5ce8b38f8 | tmpl/__init__.py | tmpl/__init__.py | """
All class templated which can be derivated.
List:
Platform
Prompt
"""
| """
All class templated which can be derivated.
List:
Platform
Prompt
"""
import Platform
import Prompt
| Make a new entry to import all modules. | Make a new entry to import all modules.
| Python | mit | nday-dev/Spider-Framework |
b013e96cb1762f46f3281ac61b5e1b53e07ede18 | prime-factors/prime_factors.py | prime-factors/prime_factors.py | import sieve
def prime_factors(n):
primes = sieve.sieve(n)
factors = []
for p in primes:
while n % p == 0:
factors += [p]
n //= p
return factors
| def prime_factors(n):
factors = []
factor = 2
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 1
return factors
| Fix memory issues by just trying every number | Fix memory issues by just trying every number
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
df98c8bd70f25727810e6eb9d359cf1e14fd6645 | update_prices.py | update_prices.py | import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
ITEMS = [
34, # Tritanium
35, # Pyerite
36, # Mexallon
37, # Isogen
38, # Nocxium
39, # Zydrine
40, # Megacyte
11399, # Morphite
]
def main():
conn = sq... | import sqlite3
import urllib2
import xml.etree.ElementTree as ET
MARKET_URL = 'http://api.eve-central.com/api/marketstat?hours=24&%s'
def main():
conn = sqlite3.connect('everdi.db')
cur = conn.cursor()
# Get all items used in current BlueprintInstances
cur.execute("""
SELECT DISTINCT c.item_id
... | Update prices for all BlueprintInstances we currently have | Update prices for all BlueprintInstances we currently have
| Python | bsd-2-clause | madcowfred/evething,Gillingham/evething,cmptrgeekken/evething,madcowfred/evething,cmptrgeekken/evething,cmptrgeekken/evething,cmptrgeekken/evething,madcowfred/evething,Gillingham/evething,madcowfred/evething,cmptrgeekken/evething,Gillingham/evething,Gillingham/evething |
b1a33b1a89c00ee6de7949c529ecd4bcf2d38578 | python/helper/asset_loading.py | python/helper/asset_loading.py | # Defining a function to load images
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# depending on the player's resolution settings
if not fade_enabled:... | # Defining a function to load images
def load_image(image_name, fade_enabled=False):
"""fade_enabled should be True if you want images to be able to fade"""
try:
#! Add stuff for loading images of the correct resolution
# depending on the player's resolution settings
if not fade_enabled:... | Fix error in file path of where images are loaded from in load_image() | Fix error in file path of where images are loaded from in load_image()
| Python | mit | AndyDeany/pygame-template |
3103bba12ee3580b3f707e88dd23e853af7b47e0 | calc.py | calc.py | #!/usr/bin/env python
"""A Python calculator"""
import sys
command = sys.argv[1]
numbers = [float(a) for a in sys.argv[2:]]
a = float(sys.argv[2])
b = float(sys.argv[3])
if command == 'add':
print sum(numbers)
elif command == 'multiply':
product = 1
for num in numbers:
product *= num
print p... | #!/usr/bin/env python
"""A Python calculator"""
import sys
command = sys.argv[1]
numbers = [float(a) for a in sys.argv[2:]]
a = float(sys.argv[2])
b = float(sys.argv[3])
if command == 'add':
print sum(numbers)
elif command == 'multiply':
product = 1
for num in numbers:
product *= num
print p... | Add smiley face to output | Add smiley face to output
| Python | bsd-3-clause | mkuiper/calc |
54f70d759b2e0d384d626f4b55016166f9b26f16 | camelot/roundtable/migrations/0002_add_knight_data.py | camelot/roundtable/migrations/0002_add_knight_data.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.core.management import call_command
def add_knight_data(apps, schema_editor):
call_command('loaddata', 'knight_data.json')
def remove_knight_data(apps, schema_editor):
pass
class Migration(... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
def add_knight_data(apps, schema_editor):
Knight = apps.get_model('roundtable', 'Knight')
Knight.objects.bulk_create([
Knight(name='Arthur'),
Knight(name='Bedevere'),
Knight(name='B... | Implement add_knight_data to generate data directly. | Implement add_knight_data to generate data directly.
| Python | bsd-2-clause | jambonrose/djangocon2014-updj17 |
8f0d56334243fa51b401b18139cefeefd26b6a9d | core/cb.project/python/sample/app.py | core/cb.project/python/sample/app.py | import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(
port=int(os.environ.get('PORT', 5000))
)
| import os
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(
host="0.0.0.0",
port=int(os.environ.get('PORT', 5000))
)
| Fix error when running python sample on codebox.io | Fix error when running python sample on codebox.io
| Python | apache-2.0 | nobutakaoshiro/codebox,indykish/codebox,blubrackets/codebox,lcamilo15/codebox,rodrigues-daniel/codebox,rodrigues-daniel/codebox,Ckai1991/codebox,smallbal/codebox,code-box/codebox,rajthilakmca/codebox,fly19890211/codebox,ronoaldo/codebox,quietdog/codebox,LogeshEswar/codebox,listepo/codebox,indykish/codebox,CodeboxIDE/co... |
8b46628656e0e649a9c973c911c01e44222906b7 | anchor/models.py | anchor/models.py | # Copyright 2014 Dave Kludt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | # Copyright 2014 Dave Kludt
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Remove token from being stored | Remove token from being stored
| Python | apache-2.0 | oldarmyc/anchor,oldarmyc/anchor,oldarmyc/anchor |
70a97ab38d2b30652c41d1e058ef4447fdd54863 | test_settings.py | test_settings.py | import os
SECRET_KEY = "h_ekayhzss(0lzsacd5cat7d=pu#51sh3w&uqn#tz26vuq4"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
INSTALLED_APPS = [
"django.contrib.sites",
"django.contrib.sessions",
"django.contrib.contenttypes",
"tz_detect",
]
MIDDLEWARE_CLASSES = [... | import os
SECRET_KEY = "h_ekayhzss(0lzsacd5cat7d=pu#51sh3w&uqn#tz26vuq4"
DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}
INSTALLED_APPS = [
"django.contrib.sites",
"django.contrib.sessions",
"django.contrib.contenttypes",
"tz_detect",
]
MIDDLEWARE_CLASSES = [... | Fix Django 5.0 deprecation warning. | Fix Django 5.0 deprecation warning.
| Python | mit | adamcharnock/django-tz-detect,adamcharnock/django-tz-detect,adamcharnock/django-tz-detect |
dcc309f0634eac6d7461d506cac4bc5b9cfbc311 | experiments/T1T2/RamseySequence.py | experiments/T1T2/RamseySequence.py | import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('qubit', help='qubit name')
parser.add_argument('stop', help='longest delay in ns', type = int)
parser.add_argument('step', help='delay step in ns', type = int)
args ... | import argparse
import sys, os
parser = argparse.ArgumentParser()
parser.add_argument('pyqlabpath', help='path to PyQLab directory')
parser.add_argument('qubit', help='qubit name')
parser.add_argument('stop', help='longest delay in ns', type = int)
parser.add_argument('step', help='delay step in ns', type = int)
args ... | Remove unnecessary (and py2) print | Remove unnecessary (and py2) print
| Python | apache-2.0 | BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab,BBN-Q/Qlab |
3d48b9b976603ea8c13937a0c6eac8a74d62b72d | calexicon/calendars/other.py | calexicon/calendars/other.py | from datetime import date as vanilla_date, timedelta
from .base import Calendar
class JulianDayNumber(Calendar):
first_ce_day = vanilla_date(1, 1, 1)
first_ce_day_number = 1721423
display_name = "Julian Day Number"
@staticmethod
def date_display_string(d):
n = JulianDayNumber._day_number(... | from datetime import date as vanilla_date, timedelta
from .base import Calendar
from ..dates.bce import BCEDate
class JulianDayNumber(Calendar):
first_ce_day = vanilla_date(1, 1, 1)
first_ce_day_number = 1721423
display_name = "Julian Day Number"
@staticmethod
def date_display_string(d):
... | Make a BCEDate for the dates before CE day 1. | Make a BCEDate for the dates before CE day 1.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual |
a31103d5001c7c6ebebddd25f9d1bb4ed0e0c2e9 | polling_stations/apps/data_importers/management/commands/import_gosport.py | polling_stations/apps/data_importers/management/commands/import_gosport.py | from data_importers.management.commands import BaseDemocracyCountsCsvImporter
class Command(BaseDemocracyCountsCsvImporter):
council_id = "GOS"
addresses_name = "2022-05-05/2022-03-07T15:47:28.644792/2022 Borough of Gosport - Democracy Club - Polling Districts v1 (07 03 2022).csv"
stations_name = "2022-05... | from data_importers.management.commands import BaseDemocracyCountsCsvImporter
class Command(BaseDemocracyCountsCsvImporter):
council_id = "GOS"
addresses_name = "2022-05-05/2022-03-07T15:47:28.644792/2022 Borough of Gosport - Democracy Club - Polling Districts v1 (07 03 2022).csv"
stations_name = "2022-05... | Fix Gosport import script error | Fix Gosport import script error
| Python | bsd-3-clause | DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations |
5d9eabe588231444083d13dc50371ea6952d445e | mirrit/web/models.py | mirrit/web/models.py | from bson.objectid import ObjectId
from humbledb import Mongo, Document
class ClassProperty (property):
"""Subclass property to make classmethod properties possible"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class User(Document):
username = ''
password = ''
... | from bson.objectid import ObjectId
from humbledb import Mongo, Document
class ClassProperty (property):
"""Subclass property to make classmethod properties possible"""
def __get__(self, cls, owner):
return self.fget.__get__(None, owner)()
class User(Document):
username = ''
password = ''
... | Add github token to model | Add github token to model
| Python | bsd-3-clause | 1stvamp/mirrit |
85748ff761ef1373a9828829a447c7b83db246de | coliziune/teste/generate_ok.py | coliziune/teste/generate_ok.py | from sh import cp, rm
import sh
import os
SURSA_CPP = 'main.cpp'
PROBLEMA = 'coliziune'
cp('../' + SURSA_CPP, '.')
os.system('g++ ' + SURSA_CPP)
for i in range(1, 11):
print 'Testul ', i
cp(PROBLEMA + str(i) + '.in', PROBLEMA + '.in')
os.system('./a.out')
cp(PROBLEMA + '.out', PROBLEMA + str(i) + '.ok')
for... | import subprocess
from sh import cp, rm
import sh
import os
SURSA_CPP = 'medie.cpp'
PROBLEMA = 'coliziune'
cp('../' + SURSA_CPP, '.')
os.system('g++ ' + SURSA_CPP)
for i in range(1, 11):
print 'Testul ', i
cp(PROBLEMA + str(i) + '.in', PROBLEMA + '.in')
print subprocess.check_output('time ./a.out', shell=True)... | Print time it took to run the source | Print time it took to run the source
| Python | mit | palcu/rotopcoder,palcu/rotopcoder |
87978c2b72777f3ef97cf1ae16f14797977bc34d | morenines/ignores.py | morenines/ignores.py | import os
from fnmatch import fnmatchcase
import click
class Ignores(object):
@classmethod
def read(cls, path):
ignores = cls()
with click.open_file(path, 'r') as stream:
ignores.patterns = [line.strip() for line in stream]
return ignores
def __init__(self):
... | import os
from fnmatch import fnmatchcase
import click
class Ignores(object):
def __init__(self, default_patterns=[]):
self.patterns = default_patterns
def read(cls, path):
with open(path, 'r') as stream:
self.patterns.extend([line.strip() for line in stream])
def match(s... | Make Ignores init accept default patterns | Make Ignores init accept default patterns
This also makes read() an instance method instead of a class method.
| Python | mit | mcgid/morenines,mcgid/morenines |
c3838132d3a4622ab4c9660f574e8219ac5e164b | mysite/core/tasks.py | mysite/core/tasks.py | from intercom.client import Client
from django.conf import settings
from celery import shared_task
intercom = Client(personal_access_token=settings.INTERCOM_ACCESS_TOKEN)
@shared_task
def intercom_event(event_name, created_at, email, metadata):
intercom.events.create(
event_name=event_name,
crea... | import logging
from intercom.client import Client
from django.conf import settings
from celery import shared_task
log = logging.getLogger(__name__)
intercom = Client(personal_access_token=settings.INTERCOM_ACCESS_TOKEN)
@shared_task
def intercom_event(event_name, created_at, email, metadata):
intercom.even... | Add logging for Intercom event generation | Add logging for Intercom event generation
| Python | apache-2.0 | raccoongang/socraticqs2,raccoongang/socraticqs2,cjlee112/socraticqs2,raccoongang/socraticqs2,cjlee112/socraticqs2,cjlee112/socraticqs2,raccoongang/socraticqs2,cjlee112/socraticqs2 |
702217fee6e332b3d08902bb67f0725626f0c88d | test_defuzz.py | test_defuzz.py | from defuzz import Defuzzer
def test_it():
dfz = Defuzzer()
assert dfz.defuzz((1, 2)) == (1, 2)
assert dfz.defuzz((1, 3)) == (1, 3)
assert dfz.defuzz((1.00000001, 2)) == (1, 2)
assert dfz.defuzz((1, 2, 3, 4, 5)) == (1, 2, 3, 4, 5)
assert dfz.defuzz((2.00000001, 3)) == (2.00000001, 3)
asser... | import itertools
import math
from defuzz import Defuzzer
from hypothesis import given
from hypothesis.strategies import floats, lists, tuples
from hypo_helpers import f
def test_it():
dfz = Defuzzer()
assert dfz.defuzz((1, 2)) == (1, 2)
assert dfz.defuzz((1, 3)) == (1, 3)
assert dfz.defuzz((1.00000... | Add a Hypothesis test for Defuzzer | Add a Hypothesis test for Defuzzer
| Python | apache-2.0 | nedbat/zellij |
12209289ebbdd5d7b93e6eb671582a36bec1d6c2 | wdom/__init__.py | wdom/__init__.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
if sys.version_info < (3, 5):
import warnings
warnings.warn(
'Next version of WDOM will not support python 3.4. Please update to version 3.6+.' # noqa: E501
)
| Raise warning when python version is < 3.5 | Raise warning when python version is < 3.5
| Python | mit | miyakogi/wdom,miyakogi/wdom,miyakogi/wdom |
c9868c56ca2aa4e5cfe2c9bad595b4d46d3a0137 | bcbiovm/__init__.py | bcbiovm/__init__.py | """Run bcbio-nextgen installations inside of virtual machines and containers.
"""
| """Run bcbio-nextgen installations inside of virtual machines
and containers.
"""
class Config(object):
"""Container for global config values."""
def __init__(self, config=None):
self._data = {}
if config:
self.update(config)
def __str__(self):
"""String representat... | Add container for global configurations | Add container for global configurations
| Python | mit | alexandrucoman/bcbio-nextgen-vm,alexandrucoman/bcbio-nextgen-vm |
8d5658ac5fa12381797b8c5f5fcd7f010aa3af0d | azure-cognitiveservices-vision-customvision/azure/cognitiveservices/vision/customvision/__init__.py | azure-cognitiveservices-vision-customvision/azure/cognitiveservices/vision/customvision/__init__.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | Fix incorrect CustomVision base init.py | Fix incorrect CustomVision base init.py | Python | mit | Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,Azure/azure-sdk-for-python |
d25d5569f51bf78d58eb461d16e9283b920b3fd7 | skylines/api/views/__init__.py | skylines/api/views/__init__.py | from flask import request
from werkzeug.exceptions import Forbidden
from werkzeug.useragents import UserAgent
from .errors import register as register_error_handlers
from .airports import airports_blueprint
from .airspace import airspace_blueprint
from .mapitems import mapitems_blueprint
from .waves import waves_bluepr... | from flask import request
from werkzeug.exceptions import Forbidden
from werkzeug.useragents import UserAgent
def register(app):
"""
:param flask.Flask app: a Flask app
"""
from .errors import register as register_error_handlers
from .airports import airports_blueprint
from .airspace import a... | Move blueprint imports into register() function | api/views: Move blueprint imports into register() function
| Python | agpl-3.0 | TobiasLohner/SkyLines,shadowoneau/skylines,skylines-project/skylines,RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,snip/skylines,snip/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,shadowoneau/skylines,TobiasLohner/SkyLines,Harry-R/skylines,TobiasLohner/SkyLines,Turb... |
34d895499f9e2a9fe35937ad511fc1adbfd8c12d | tailor/main.py | tailor/main.py | import os
import sys
PARENT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(PARENT_PATH)
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from tailor.listeners.mainlistener import MainListener
from tailor.output.printer import Printer
from tailor.swift.swiftlexe... | """Perform static analysis on a Swift source file."""
import argparse
import os
import sys
PARENT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(PARENT_PATH)
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from tailor.listeners.mainlistener import MainListene... | Set up argparse to accept params and display usage | Set up argparse to accept params and display usage
| Python | mit | sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor,sleekbyte/tailor |
cae249ff553083e3546e26b08779baf6abc69a69 | active_link/templatetags/active_link_tags.py | active_link/templatetags/active_link_tags.py | from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=T... | from django import VERSION as DJANGO_VERSION
from django import template
from django.conf import settings
if DJANGO_VERSION[0] == 1 and DJANGO_VERSION[1] <= 9:
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
register = template.Library()
@register.simple_tag(takes_context=T... | Improve how the active link is checked | Improve how the active link is checked
| Python | bsd-3-clause | valerymelou/django-active-link |
2036b054a57cade23e513877e1dff9455c3d74c7 | meetup/models.py | meetup/models.py | from django.db import models
from pizzaplace.models import PizzaPlace
from django.core.validators import RegexValidator
from meetup.services.meetup_api_lookup_agent import MeetupApiLookupAgent
from django.core.exceptions import ValidationError
def validate_urlname(link):
validator = RegexValidator(
regex='meetu... | from django.db import models
from pizzaplace.models import PizzaPlace
from django.core.validators import RegexValidator
from meetup.services.meetup_api_lookup_agent import MeetupApiLookupAgent
from django.core.exceptions import ValidationError
from model_utils.models import TimeStampedModel
def validate_urlname(link):... | Improve meetup's validation error messages | Improve meetup's validation error messages
| Python | mit | nicole-a-tesla/meetup.pizza,nicole-a-tesla/meetup.pizza |
494bfbd5f189cb0f61eecc7e86df53fb9f9a8203 | src/ggrc/migrations/versions/20150911131818_29dca3ce0556_change_conclusion_dropdowns_options_in_.py | src/ggrc/migrations/versions/20150911131818_29dca3ce0556_change_conclusion_dropdowns_options_in_.py |
"""Change conclusion dropdowns options in control assessment
Revision ID: 29dca3ce0556
Revises: 2d8a46b1e4a4
Create Date: 2015-09-11 13:18:18.269109
"""
# revision identifiers, used by Alembic.
revision = '29dca3ce0556'
down_revision = '2d8a46b1e4a4'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.d... | # Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: jost@reciprocitylabs.com
# Maintained By: jost@reciprocitylabs.com
"""Change conclusion dropdowns options in control assessment
Revision ID: 29dca... | Add copyright header to migration | Add copyright header to migration
| Python | apache-2.0 | NejcZupec/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,josthkko/ggrc-core,hyperNURb/ggrc-core,NejcZupec/ggrc-core,jmakov/ggrc-core,hyperNURb/ggrc-core,kr41/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,hasanalom/ggrc-core,andrei-karalionak/ggrc-core,j... |
1d0c6389cc7d67acb5123555568d83f17f6b0ff0 | templatetags/generic_markup.py | templatetags/generic_markup.py | """
A filter which can perform many types of text-to-HTML conversion.
"""
from django.template import Library
from template_utils.markup import markup_filter
def apply_markup(value):
"""
Applies text-to-HTML conversion.
"""
return markup_filter(value)
register = Library()
register.filter(apply_mark... | """
A filter which can perform many types of text-to-HTML conversion.
"""
from django.template import Library
from template_utils.markup import markup_filter
def apply_markup(value, arg=None):
"""
Applies text-to-HTML conversion.
Takes an optional argument to specify the name of a filter to use.
""... | Make markup template filter take filter_name argument | Make markup template filter take filter_name argument
| Python | bsd-3-clause | dongpoliu/django-template-utils |
27d40996f0912a1b9b16afa0884f10b1504acce2 | scoring_engine/web/__init__.py | scoring_engine/web/__init__.py | import os
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, about
app.register_blueprint(welcome.mod)
app.register_blueprint(scoreboard.mod)
ap... | import os
import logging
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('settings.cfg')
app.secret_key = os.urandom(128)
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
from scoring_engine.web.views import welcome, scoreboard, overview, services, admin, auth, profile, api, ab... | Use error severity for flask output | Use error severity for flask output
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine |
a22b1019b8bcea2f6bdaf90635165d8d8968dee1 | scripts/parse-include-paths.py | scripts/parse-include-paths.py | #!/usr/bin/env python3
"""
Deploys the website to a target directory supplied as an argument.
"""
import json
import os
import sys
def iterate_over(dict_or_list, result):
"""
Iterates recursively over nested lists and dictionaries
keeping track of all "path" values with the key "includePath"
within n... | #!/usr/bin/env python3
"""
Parses .vscode/.cmaketools.json to obtain a list of include paths.
These can then be subsequently pasted into .vscode/c_cpp_properties.json
to make intellisense work. This is script exists purely for convenience
and only needs to be used when the include paths change (e.g. when a new
depende... | Fix incorrect global comment in include path script | Fix incorrect global comment in include path script
| Python | bsd-3-clause | Tom94/tev,Tom94/tev,Tom94/tev,Tom94/tev |
06d9ada18ef8d201383317e6e0fac078a01ab206 | tests/test_vector2_equality.py | tests/test_vector2_equality.py | from hypothesis import given
from ppb_vector import Vector2
from utils import vectors
def test_equal():
test_vector_1 = Vector2(50, 800)
test_vector_2 = Vector2(50, 800)
assert test_vector_1 == test_vector_2
@given(x=vectors(), y=vectors())
def test_not_equal_equivalent(x: Vector2, y: Vector2):
assert (x !=... | from hypothesis import assume, given
from ppb_vector import Vector2
from utils import vectors
@given(x=vectors())
def test_equal_self(x: Vector2):
assert x == x
@given(x=vectors())
def test_non_zero_equal(x: Vector2):
assume(x != (0, 0))
assert x != 1.1 * x
@given(x=vectors(), y=vectors())
def test_not_equal_... | Replace test for == with an Hypothesis test | tests/equality: Replace test for == with an Hypothesis test
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
2f7551b953bb225b68880cdeec87236ea6453b12 | tohu/v6/set_special_methods.py | tohu/v6/set_special_methods.py | """
This module is not meant to be imported directly.
Its purpose is to patch the TohuBaseGenerator class
so that its special methods __add__, __mul__ etc.
support other generators as arguments.
"""
from operator import add, mul, gt, ge, lt, le, eq
from .base import TohuBaseGenerator
from .primitive_generators import... | """
This module is not meant to be imported directly.
Its purpose is to patch the TohuBaseGenerator class
so that its special methods __add__, __mul__ etc.
support other generators as arguments.
"""
from .base import TohuBaseGenerator
from .primitive_generators import GeoJSONGeolocation, as_tohu_generator
from .derive... | Set special methods on TohuBaseGenerator to allow e.g. adding two generators | Set special methods on TohuBaseGenerator to allow e.g. adding two generators
| Python | mit | maxalbert/tohu |
abd7987e698e9102a7d737f3b32296d703ae0a7c | scripts/buildAll.py | scripts/buildAll.py | #! /usr/bin/python
#
# Build the entire ISAAC Project
#
#
#
import subprocess
import os
import sys
projects = ['va-ochre',
'va-isaac-metadata',
'va-isaac-mojo',
'va-newtons-cradle',
'va-logic',
'va-query-service',
'va-isaac-gui',
'va-solor-goods',
'va-expression-service',
'va-isaac-gui-pa']... | #! /usr/bin/python
#
# Build the entire ISAAC Project
#
#
#
import subprocess
import os
import sys
projects = ['va-isaac-parent',
'va-ochre',
'va-isaac-metadata',
'va-isaac-mojo',
'va-newtons-cradle',
'va-logic',
'va-query-service',
'va-isaac-gui',
'va-solor-goods',
'va-expression-service',... | Revert "Fixed a windows bug that prevented run locating the Maven batch file to run mvn commands. This will need to be modified to run on Linux" | Revert "Fixed a windows bug that prevented run locating the Maven batch file to run mvn commands. This will need to be modified to run on Linux"
This reverts commit b9dfad50415d6f7d90d66da30a1a55cbe62a07ef.
| Python | apache-2.0 | Apelon-VA/va-isaac-docs |
62d7924f6f5097845a21408e975cae1dfff01c1c | android/app/src/main/assets/python/enamlnative/widgets/analog_clock.py | android/app/src/main/assets/python/enamlnative/widgets/analog_clock.py | '''
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on May 20, 2017
@author: jrm
'''
from atom.api import (
Typed, ForwardTyped, Unicode, observe
)
from enaml.core.declarative import d_
from... | '''
Copyright (c) 2017, Jairus Martin.
Distributed under the terms of the MIT License.
The full license is in the file COPYING.txt, distributed with this software.
Created on May 20, 2017
@author: jrm
'''
from atom.api import (
Typed, ForwardTyped, Unicode, observe
)
from enaml.core.declarative import d_
from... | Use correct parent class for clock | Use correct parent class for clock
| Python | mit | codelv/enaml-native,codelv/enaml-native,codelv/enaml-native,codelv/enaml-native |
634f718aa4fe4052a8dc9be1f82078ebcd2338df | build-release.py | build-release.py | import sys
import glob
import re
NEW_VERSION = sys.argv[1]
with open('VERSION') as f:
VERSION=f.read()
print NEW_VERSION
print VERSION
def set_assemblyinfo_version(version):
aLineRe = "AssemblyVersion|AssemblyFileVersion\(\"([\.0-9]+)\"\)"
aVersionRe = "(\d\.\d\.\d)"
print "Changing versi... | import sys
import glob
import re
NEW_VERSION = sys.argv[1]
with open('VERSION') as f:
VERSION=f.read()
print NEW_VERSION
print VERSION
def set_assemblyinfo_version(version):
aLineRe = "AssemblyVersion|AssemblyFileVersion\(\"([\.0-9]+)\"\)"
aVersionRe = "(\d\.\d\.\d)"
print "Changing versi... | Revert "working on version file" | Revert "working on version file"
This reverts commit cb159cd3d907aeaa65f6a293d95a0aa7d7f2fee8.
| Python | mit | psistats/windows-client,psistats/windows-client,psistats/windows-client |
d4c5e7a9d9b6fb795c5a16cf6a7d12f5ec32b160 | peas-demo/plugins/pythonhello/pythonhello.py | peas-demo/plugins/pythonhello/pythonhello.py | # -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:
import gobject
from gi.repository import Peas
from gi.repository import Gtk
LABEL_STRING="Python Says Hello!"
class PythonHelloPlugin(gobject.GObject, Peas.Activatable):
__gtype_name__ = 'PythonHelloPlugin'
def do_activate(self, window):
print "Pytho... | # -*- coding: utf-8 -*-
# ex:set ts=4 et sw=4 ai:
import gobject
from gi.repository import Peas
from gi.repository import PeasUI
from gi.repository import Gtk
LABEL_STRING="Python Says Hello!"
class PythonHelloPlugin(gobject.GObject, Peas.Activatable):
__gtype_name__ = 'PythonHelloPlugin'
def do_activate(se... | Add a configure dialog to the python plugin. | peas-demo: Add a configure dialog to the python plugin.
| Python | lgpl-2.1 | chergert/libpeas,chergert/libpeas,GNOME/libpeas,Distrotech/libpeas,GNOME/libpeas,Distrotech/libpeas,gregier/libpeas,Distrotech/libpeas,gregier/libpeas,gregier/libpeas,chergert/libpeas,gregier/libpeas |
aeafebbb2bb5ddf4e2d2ddd47cd16d8ed515ac1b | portal/models.py | portal/models.py | from django.db import models
from common.util.generator import get_random_id
class Student(models.Model):
# ToDo: Make username unique
username = models.CharField(max_length=7)
magic_id = models.CharField(max_length=8)
child = models.BooleanField()
def __str__(self):
return self.username... | from django.db import models
from common.util.generator import get_random_id
class Student(models.Model):
username = models.CharField(max_length=7,unique=True)
magic_id = models.CharField(max_length=8)
child = models.BooleanField()
def __str__(self):
return self.username
def save(self, ... | Enforce unique user names in the database model | Enforce unique user names in the database model
Set unique=TRUE and deleted TODO comment line
| Python | mit | martinzlocha/mad,martinzlocha/mad,martinzlocha/mad |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.