commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
37170b156e6a284d5e5df671875070a3fcac9310 | commands/join.py | commands/join.py | from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['join']
helptext = "Makes me join another channel, if I'm allowed to at least"
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext = ""
if message.messagePartsL... | from CommandTemplate import CommandTemplate
from IrcMessage import IrcMessage
class Command(CommandTemplate):
triggers = ['join']
helptext = "Makes me join another channel, if I'm allowed to at least"
def execute(self, message):
"""
:type message: IrcMessage
"""
replytext = ""
if message.messagePartsL... | Check if we're already in the channel; Improved parameter parsing | [Join] Check if we're already in the channel; Improved parameter parsing
| Python | mit | Didero/DideRobot | ---
+++
@@ -15,11 +15,16 @@
if message.messagePartsLength < 1:
replytext = "Please provide a channel for me to join"
else:
- channel = message.messageParts[0]
- if channel.replace('#', '') not in message.bot.factory.settings['allowedChannels'] and not message.bot.factory.isUserAdmin(message.user, messag... |
29efb23b2edb46aed4be835787d461ee1ada96f6 | GitAutoDeploy.py | GitAutoDeploy.py | #!/usr/bin/env python
if __name__ == '__main__':
import sys
import os
import gitautodeploy
sys.stderr.write("\033[1;33m[WARNING]\033[0;33m GitAutoDeploy.py is deprecated. Please use \033[1;33m'python gitautodeploy%s'\033[0;33m instead.\033[0m\n" % (' ' + ' '.join(sys.argv[1:])).strip())
gitautodepl... | #!/usr/bin/env python
if __name__ == '__main__':
import sys
import os
import gitautodeploy
sys.stderr.write("\033[1;33m[WARNING]\033[0;33m GitAutoDeploy.py is deprecated. Please use \033[1;33m'python gitautodeploy%s'\033[0;33m instead.\033[0m\n" % (' ' + ' '.join(sys.argv[1:])).rstrip())
gitautodep... | Fix truncated command and options | Fix truncated command and options
Before:
```console
$ python GitAutoDeploy.py --daemon-mode
[WARNING] GitAutoDeploy.py is deprecated. Please use 'python gitautodeploy--daemon-mode' instead.
```
Now:
```console
$ python GitAutoDeploy.py --daemon-mode
[WARNING] GitAutoDeploy.py is deprecated. Please use '... | Python | mit | evoja/docker-Github-Gitlab-Auto-Deploy,evoja/docker-Github-Gitlab-Auto-Deploy | ---
+++
@@ -4,5 +4,5 @@
import sys
import os
import gitautodeploy
- sys.stderr.write("\033[1;33m[WARNING]\033[0;33m GitAutoDeploy.py is deprecated. Please use \033[1;33m'python gitautodeploy%s'\033[0;33m instead.\033[0m\n" % (' ' + ' '.join(sys.argv[1:])).strip())
+ sys.stderr.write("\033[1;33m[W... |
b282c54ebaaae13aa8b81f2380cdc20acaa9fc69 | lab/gendata.py | lab/gendata.py | import random
import time
from coverage.data import CoverageJsonData
from coverage.sqldata import CoverageSqliteData
NUM_FILES = 1000
NUM_LINES = 1000
def gen_data(cdata):
rnd = random.Random()
rnd.seed(17)
def linenos(num_lines, prob):
return (n for n in range(num_lines) if random.random() < pr... | # Run some timing tests of JsonData vs SqliteData.
import random
import time
from coverage.data import CoverageJsonData
from coverage.sqldata import CoverageSqliteData
NUM_FILES = 1000
NUM_LINES = 1000
def gen_data(cdata):
rnd = random.Random()
rnd.seed(17)
def linenos(num_lines, prob):
return ... | Make it run on PyPy for time tests there | Make it run on PyPy for time tests there
| Python | apache-2.0 | hugovk/coveragepy,nedbat/coveragepy,hugovk/coveragepy,nedbat/coveragepy,hugovk/coveragepy,nedbat/coveragepy,hugovk/coveragepy,hugovk/coveragepy,nedbat/coveragepy,nedbat/coveragepy | ---
+++
@@ -1,3 +1,5 @@
+# Run some timing tests of JsonData vs SqliteData.
+
import random
import time
@@ -16,7 +18,7 @@
start = time.time()
for i in range(NUM_FILES):
- filename = f"/src/foo/project/file{i}.py"
+ filename = "/src/foo/project/file{i}.py".format(i=i)
line_data =... |
711c35ce82479f0ced86ef7b3dff083c49f7ee09 | vidscraper/__init__.py | vidscraper/__init__.py | from vidscraper import errors
from vidscraper.sites import (
vimeo, google_video, youtube)
AUTOSCRAPE_SUITES = [
vimeo.SUITE, google_video.SUITE, youtube.SUITE,
blip.SUITE]
def scrape_suite(url, suite, fields=None):
scraped_data = {}
funcs_map = suite['funcs']
fields = fields or funcs_map.ke... | from vidscraper import errors
from vidscraper.sites import (
vimeo, google_video, youtube, blip)
AUTOSCRAPE_SUITES = [
vimeo.SUITE, google_video.SUITE, youtube.SUITE,
blip.SUITE]
def scrape_suite(url, suite, fields=None):
scraped_data = {}
funcs_map = suite['funcs']
fields = fields or funcs_... | Fix the blip autoscrape. Missed an import. | Fix the blip autoscrape. Missed an import.
Stupid stupid stupid. Should have tested before pushing.
| Python | bsd-3-clause | pculture/vidscraper,pculture/vidscraper | ---
+++
@@ -1,6 +1,6 @@
from vidscraper import errors
from vidscraper.sites import (
- vimeo, google_video, youtube)
+ vimeo, google_video, youtube, blip)
AUTOSCRAPE_SUITES = [
vimeo.SUITE, google_video.SUITE, youtube.SUITE, |
fc3e5201935653228a71d4a52eeffb94de284141 | vesper/external_urls.py | vesper/external_urls.py | """
Functions that return external URLs, for example for the Vesper documentation.
"""
import vesper.version as vesper_version
_USE_LATEST_DOCUMENTATION_VERSION = False
"""Set this `True` during development, `False` for release."""
def _create_documentation_url():
if _USE_LATEST_DOCUMENTATION_VERSION:
... | """
Functions that return external URLs, for example for the Vesper documentation.
"""
import vesper.version as vesper_version
_USE_LATEST_DOCUMENTATION_VERSION = True
"""Set this `True` during development, `False` for release."""
def _create_documentation_url():
if _USE_LATEST_DOCUMENTATION_VERSION:
... | Edit external URLs module for development. | Edit external URLs module for development. | Python | mit | HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper | ---
+++
@@ -6,7 +6,7 @@
import vesper.version as vesper_version
-_USE_LATEST_DOCUMENTATION_VERSION = False
+_USE_LATEST_DOCUMENTATION_VERSION = True
"""Set this `True` during development, `False` for release."""
|
ba9386fc7c14be6335896e1d888c822db972dfe1 | 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."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
... | """Handles all imports from jnius to prevent conflicts resulting from attempts
to set JVM options while the VM is already running."""
import os
import warnings
import jnius_config
if '-Xmx4g' not in jnius_config.get_options():
if not jnius_config.vm_running:
jnius_config.add_options('-Xmx4g')
else:
... | Remove messages from Java VM | Remove messages from Java VM
| Python | bsd-2-clause | bgyori/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,sorgerlab/indra,jmuhlich/indra,pvtodorov/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,jmuhlich/indra,sorgerlab/belpy,sorgerlab/belpy,pvtodorov/indra,johnbachman/belpy,sorgerlab/indra,jmuhlich/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,jo... | ---
+++
@@ -16,12 +16,10 @@
cp = path_here + '/biopax/jars/paxtools.jar'
cp_existing = os.environ.get('CLASSPATH')
-print 'before', os.environ.get('CLASSPATH')
if cp_existing is not None:
os.environ['CLASSPATH'] = cp + ':' + cp_existing
else:
os.environ['CLASSPATH'] = cp
-print 'after', os.environ.get... |
8d170381532228ffbef32534ca1217714b5f1594 | dataproperty/type/_typecode.py | dataproperty/type/_typecode.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_T... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
class Typecode(object):
NONE = 0
INT = 1 << 0
FLOAT = 1 << 1
STRING = 1 << 2
DATETIME = 1 << 3
INFINITY = 1 << 4
NAN = 1 << 5
BOOL = 1 << 6
DEFAULT_TYPENAME_T... | Change integer default type name | Change integer default type name
| Python | mit | thombashi/DataProperty | ---
+++
@@ -19,7 +19,7 @@
DEFAULT_TYPENAME_TABLE = {
NONE: "NONE",
- INT: "INT",
+ INT: "INTEGER",
FLOAT: "FLOAT",
STRING: "STRING",
DATETIME: "DATETIME", |
d66b4be946785d7b9223a0a3497d8ec4a4cebea9 | project/settings/production.py | project/settings/production.py | import os
from .common import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'singlepoint',
}
}
PUBLIC_ROOT = os.path.join(os.sep, 'var', 'www', 'singlepoint', 'public')
STATIC_ROOT = os.path.join(PUBLIC_ROOT, 'static')
MEDIA_ROOT = os.path.join(PUBLI... | import os
from .common import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'singlepoint',
}
}
PUBLIC_ROOT = os.path.join(os.sep, 'var', 'www', 'singlepoint', 'public')
STATIC_ROOT = os.path.join(PUBLIC_ROOT, 'static')
MEDIA_ROOT = os.path.join(PUBLI... | Add django celery to installed apps | Add django celery to installed apps
| Python | mit | xobb1t/ddash2013,xobb1t/ddash2013 | ---
+++
@@ -28,7 +28,7 @@
BROKER_URL = 'redis://localhost:6379/0'
-INSTALLED_APPS += ("djcelery_email",)
+INSTALLED_APPS += ("djcelery", "djcelery_email",)
EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend'
CELERYD_CONCURRENCY = 2
CELERYD_MAX_TASKS_PER_CHILD = 100 |
88fd32be09bc20ce734f272b7d3a54a71958e6b4 | energy/models.py | energy/models.py | from sqlalchemy import create_engine
from sqlalchemy.sql import text
import arrow
def get_energy_chart_data(meterId, start_date="2016-09-01",
end_date="2016-10-01"):
""" Return json object for flot chart
"""
engine = create_engine('sqlite:///../data/'+ str(meterId) + '.db', echo=... | from sqlalchemy import create_engine
from sqlalchemy import MetaData, Table, Column, DateTime, Float, between
from sqlalchemy.sql import select, text
import arrow
metadata = MetaData()
meter_readings = Table('interval_readings', metadata,
Column('reading_date', DateTime, primary_key=True),
Column('ch1', Float... | Use sqlalchemy to generate query | Use sqlalchemy to generate query
| Python | agpl-3.0 | aguinane/energyusage,aguinane/energyusage,aguinane/energyusage,aguinane/energyusage | ---
+++
@@ -1,7 +1,14 @@
from sqlalchemy import create_engine
-from sqlalchemy.sql import text
+from sqlalchemy import MetaData, Table, Column, DateTime, Float, between
+from sqlalchemy.sql import select, text
+
import arrow
+metadata = MetaData()
+meter_readings = Table('interval_readings', metadata,
+ Column... |
0b132427e5e81d7e502085d62177bc079cb9d6e8 | gaphor/misc/tests/test_gidlethread.py | gaphor/misc/tests/test_gidlethread.py | import pytest
from gaphor.misc.gidlethread import GIdleThread
def counter(count):
for x in range(count):
yield x
@pytest.fixture
def gidle_counter(request):
# Setup GIdle Thread with 0.01 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
wait_result =... | import pytest
from gaphor.misc.gidlethread import GIdleThread
def counter(count):
for x in range(count):
yield x
@pytest.fixture
def gidle_counter(request):
# Setup GIdle Thread with 0.02 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
wait_result =... | Fix test failing in macOS due to short GIdleThread timeout | Fix test failing in macOS due to short GIdleThread timeout
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor | ---
+++
@@ -10,11 +10,11 @@
@pytest.fixture
def gidle_counter(request):
- # Setup GIdle Thread with 0.01 sec timeout
+ # Setup GIdle Thread with 0.02 sec timeout
t = GIdleThread(counter(request.param))
t.start()
assert t.is_alive()
- wait_result = t.wait(0.01)
+ wait_result = t.wait(0.0... |
ea1389d6dfb0060cda8d194079aacc900bbf56ae | simple_graph.py | simple_graph.py | #!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
class Graph(object):
''' Create an empty graph. '''
def __init__(self):
self.graph = {}
return
def nodes():
return nodes
def edges():
return edges
def add_node(sel... | #!/usr/bin/env python
from __future__ import print_function
from __future__ import unicode_literals
class Graph(object):
''' Create an empty graph. '''
def __init__(self):
self.graph = {}
return
def nodes(self):
return self.graph.keys()
def edges(self):
edge_list = []... | Add functions for adding a node, an edge, and defining a node | Add functions for adding a node, an edge, and defining a node
| Python | mit | constanthatz/data-structures | ---
+++
@@ -9,18 +9,24 @@
self.graph = {}
return
- def nodes():
- return nodes
+ def nodes(self):
+ return self.graph.keys()
- def edges():
- return edges
+ def edges(self):
+ edge_list = []
+ for key, value in self.graph():
+ for item in... |
2d50e06c7e55c19e3055d555d78fac699c61104d | tests/integration/test_os_signals.py | tests/integration/test_os_signals.py | import os
import signal
import diesel
state = {'triggered':False}
def waiter():
diesel.signal(signal.SIGUSR1)
state['triggered'] = True
def test_can_wait_on_os_signals():
# Start our Loop that will wait on USR1
diesel.fork(waiter)
# Let execution switch to the newly spawned loop
diesel.slee... | import os
import signal
import diesel
from diesel.util.event import Countdown
state = {'triggered':False}
def waiter():
diesel.signal(signal.SIGUSR1)
state['triggered'] = True
def test_can_wait_on_os_signals():
# Start our Loop that will wait on USR1
diesel.fork(waiter)
# Let execution switch... | Test for multiple waiters on a signal | Test for multiple waiters on a signal
| Python | bsd-3-clause | dieseldev/diesel | ---
+++
@@ -2,6 +2,9 @@
import signal
import diesel
+
+from diesel.util.event import Countdown
+
state = {'triggered':False}
@@ -27,3 +30,17 @@
# Now that we're back, the waiter should have triggered the state
assert state['triggered']
+
+def test_multiple_signal_waiters():
+ N_WAITERS = 5
+ ... |
caa3b8a7c06f3e1fffb7ec6b957216bd6d147f23 | numbas_auth.py | numbas_auth.py | from django_auth_ldap.backend import LDAPBackend
class NumbasAuthBackend(LDAPBackend):
"""Authentication backend overriding LDAPBackend.
This could be used to override certain functionality within the LDAP authentication backend.
The example here overrides get_or_create_user() to alter the LDAP g... | from django_auth_ldap.backend import LDAPBackend
class NumbasAuthBackend(LDAPBackend):
"""Authentication backend overriding LDAPBackend.
This could be used to override certain functionality within the LDAP authentication backend.
The example here overrides get_or_create_user() to alter the LDAP g... | Fix case sensitive LDAP attributes | Fix case sensitive LDAP attributes
| Python | apache-2.0 | numbas/editor,numbas/editor,numbas/editor | ---
+++
@@ -15,5 +15,5 @@
def get_or_create_user(self, username, ldap_user):
"""Alter the LDAP givenName attribute to the familiar first name in displayName."""
- ldap_user.attrs['givenname'] = [ldap_user.attrs['displayname'][0].split()[0]]
+ ldap_user.attrs['givenName'] = [ldap_... |
c7d03f4f8d4d50ce837cf0df446a52b24e891cee | config/flask_prod.py | config/flask_prod.py | import os
from rmc.config.flask_base import *
import rmc.shared.secrets as s
JS_DIR = 'js_prod'
DEBUG = False
ENV = 'prod'
GA_PROPERTY_ID = 'UA-35073503-1'
LOG_DIR = '/home/rmc/logs'
LOG_PATH = os.path.join(LOG_DIR, 'server/server.log')
FB_APP_ID = '219309734863464'
FB_APP_SECRET = s.FB_APP_SECRET_PROD
| import os
from rmc.config.flask_base import *
import rmc.shared.secrets as s
JS_DIR = 'js'
DEBUG = False
ENV = 'prod'
GA_PROPERTY_ID = 'UA-35073503-1'
LOG_DIR = '/home/rmc/logs'
LOG_PATH = os.path.join(LOG_DIR, 'server/server.log')
FB_APP_ID = '219309734863464'
FB_APP_SECRET = s.FB_APP_SECRET_PROD
| Revert "Revert "do not use minified js on prod"" (=don't minify to fix things) | Revert "Revert "do not use minified js on prod"" (=don't minify to fix things)
This reverts commit 88f2886393991ac660ac382d48c65088eff56d52.
| Python | mit | sachdevs/rmc,MichalKononenko/rmc,sachdevs/rmc,ccqi/rmc,JGulbronson/rmc,MichalKononenko/rmc,JGulbronson/rmc,JGulbronson/rmc,sachdevs/rmc,rageandqq/rmc,MichalKononenko/rmc,JGulbronson/rmc,ccqi/rmc,shakilkanji/rmc,MichalKononenko/rmc,rageandqq/rmc,UWFlow/rmc,UWFlow/rmc,UWFlow/rmc,ccqi/rmc,rageandqq/rmc,UWFlow/rmc,duaayous... | ---
+++
@@ -3,7 +3,7 @@
from rmc.config.flask_base import *
import rmc.shared.secrets as s
-JS_DIR = 'js_prod'
+JS_DIR = 'js'
DEBUG = False
ENV = 'prod'
GA_PROPERTY_ID = 'UA-35073503-1' |
931ae68671abef1fedde46d585a4057b24ecbb04 | reinforcement-learning/play.py | reinforcement-learning/play.py | """Load the trained q table and make actions based on that.
"""
import time
import env
import rl
rl.load_q()
env.make("pygame")
while True:
env.reset()
for _ in range(15):
if env.done:
break
action = rl.choose_action(rl.table[env.object[0]])
env.action(action)
time... | """Load the trained q table and make actions based on that.
"""
import time
import env
import rl
rl.load_q()
env.make("pygame")
while True:
env.reset()
for _ in range(15):
if env.done:
break
action = rl.choose_action(env.player, "test")
env.action(action)
time.slee... | Update to newest version of rl.py. | Update to newest version of rl.py.
| Python | mit | danieloconell/Louis | ---
+++
@@ -13,7 +13,7 @@
for _ in range(15):
if env.done:
break
- action = rl.choose_action(rl.table[env.object[0]])
+ action = rl.choose_action(env.player, "test")
env.action(action)
time.sleep(0.03)
env.render() |
bb6b6b46860f6e03abc4ac9c47751fe4309f0e17 | md2pdf/core.py | md2pdf/core.py | # -*- coding: utf-8 -*-
from markdown2 import markdown, markdown_path
from weasyprint import HTML, CSS
from .exceptions import ValidationError
__title__ = 'md2pdf'
__version__ = '0.2.1'
__author__ = 'Julien Maupetit'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013 Julien Maupetit'
def md2pdf(pdf_file_path, md_... | # -*- coding: utf-8 -*-
from markdown2 import markdown, markdown_path
from weasyprint import HTML, CSS
from .exceptions import ValidationError
__title__ = 'md2pdf'
__version__ = '0.2.1'
__author__ = 'Julien Maupetit'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013 Julien Maupetit'
def md2pdf(pdf_file_path, md_... | Allow to add a base url to find media | Allow to add a base url to find media
| Python | mit | jmaupetit/md2pdf | ---
+++
@@ -13,7 +13,7 @@
def md2pdf(pdf_file_path, md_content=None, md_file_path=None,
- css_file_path=None):
+ css_file_path=None, base_url=None):
"""
Convert markdown file to pdf with styles
"""
@@ -30,7 +30,7 @@
raise ValidationError('Input markdown seems empty')
... |
0e19f960b2234fcd9711f123526f8de507ed2d99 | src/registry.py | src/registry.py | from .formatter import *
class FormatterRegistry():
def __init__(self):
self.__formatters = []
def populate(self):
self.__formatters = [
ClangFormat(), ElmFormat(), GoFormat(), JavaScriptFormat(),
JsonFormat(), PythonFormat(), RustFormat(), TerraformFormat()
]
... | from .formatter import *
class FormatterRegistry():
def __init__(self):
self.__formatters = []
self.__formatter_source_map = {}
def populate(self):
self.__formatters = [
ClangFormat(), ElmFormat(), GoFormat(), JavaScriptFormat(),
JsonFormat(), PythonFormat(), R... | Speed up lookup of formatter by source type | Speed up lookup of formatter by source type
| Python | mit | Rypac/sublime-format | ---
+++
@@ -4,12 +4,16 @@
class FormatterRegistry():
def __init__(self):
self.__formatters = []
+ self.__formatter_source_map = {}
def populate(self):
self.__formatters = [
ClangFormat(), ElmFormat(), GoFormat(), JavaScriptFormat(),
JsonFormat(), PythonF... |
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 | ---
+++
@@ -1,14 +1,19 @@
from cmdtree import group, argument, entry
-@group("docker")
-@argument("ip")
+@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
# ne... |
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 | ---
+++
@@ -28,5 +28,6 @@
file_format = models.ForeignKey('FileFormat')
description = models.TextField()
author = models.ForeignKey(User)
+ slug = models.SlugField(max_length=40)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True) |
d82588adaded8943543b9f0300e0d683925496ce | 01/server.py | 01/server.py |
from google.appengine.api import users
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.set_status(200)
self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
... |
import webapp2
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.set_status(200)
self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
self.response.out.write('Hello World')
application = webapp2.WSGIApplication([
('/', MainPage),
], debug=True)
| Simplify by removing user login. | Simplify by removing user login.
| Python | apache-2.0 | luisibanez/appengine-python-101 | ---
+++
@@ -1,5 +1,3 @@
-
-from google.appengine.api import users
import webapp2
@@ -11,14 +9,6 @@
self.response.set_status(200)
self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
- if users.get_current_user():
- url = users.create_logout_url(self.request.uri)
- ... |
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 | ---
+++
@@ -25,8 +25,5 @@
class MonolithRouter(object):
- def __init__(self):
- self.config = PartitionConfig()
-
def allow_migrate(self, db, app_label, model=None, **hints):
return app_label != PROXY_APP |
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 | ---
+++
@@ -1 +1,37 @@
# -*- 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:
+ la... |
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 | ---
+++
@@ -2,7 +2,11 @@
import sys
if 'egg' not in bdist.format_commands:
- bdist.format_command['egg'] = ('bdist_egg', "Python .egg file")
- bdist.format_commands.append('egg')
+ try:
+ bdist.format_commands['egg'] = ('bdist_egg', "Python .egg file")
+ except TypeError:
+ # For backwar... |
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 | ---
+++
@@ -1,7 +1,11 @@
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
@@ -15,7... |
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 | ---
+++
@@ -3,10 +3,9 @@
class Task(object):
- def __init__(self, taskID, sheetID, name, description, maxPoints, reachedPoints=0):
+ def __init__(self, taskID, sheetID, name, description, maxPoints):
self.id = taskID
self.sheetID = sheetID
self.name = name
self.descripti... |
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 | ---
+++
@@ -1,9 +1,14 @@
+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('/wor... |
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 | ---
+++
@@ -1,9 +1,5 @@
-import datetime
+import json
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 _
|
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 | ---
+++
@@ -4,6 +4,16 @@
class EmailAdmin(admin.ModelAdmin):
- exclude = ('targetted_users', 'is_sent')
+ readonly_fields = ('targetted_users', 'is_sent',)
+ add_fieldsets = (
+ (None, {
+ 'fields': ('subject', 'message', 'post'),
+ }),
+ )
+
+ def get_fieldsets(self, requ... |
d1f1664f7c15a156270dc7e506bb3edb37dc517d | dipy/reconst/__init__.py | dipy/reconst/__init__.py | #init for reconst aka the reconstruction module
# Test callable
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
del Tester
| # init for reconst aka the reconstruction module
# Test callable
from numpy.testing import Tester
test = Tester().test
bench = Tester().bench
del Tester
| Update code in dipy/reconst (PEP8) | Update code in dipy/reconst (PEP8)
Using `pycodestyle` output, the file `dipy/reconst/__init__.py` was
updated to pass `pycodestyle` check
Signed-off-by: Antonio Ossa <1ecf3d2f96b6e61cf9b68f0fc294cab57dc5d597@uc.cl>
| Python | bsd-3-clause | FrancoisRheaultUS/dipy,FrancoisRheaultUS/dipy,nilgoyyou/dipy,nilgoyyou/dipy | ---
+++
@@ -1,4 +1,4 @@
-#init for reconst aka the reconstruction module
+# init for reconst aka the reconstruction module
# Test callable
from numpy.testing import Tester
@@ -6,7 +6,3 @@
bench = Tester().bench
del Tester
-
-
-
- |
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 | ---
+++
@@ -21,19 +21,23 @@
@property
def address(self):
- return self.addr.address
+ return self.address
+
+ @address.setter
+ def address(self, value):
+ self.address = value
def __str__(self):
return self.address
def __eq__(self, other):
if isi... |
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 | ---
+++
@@ -14,8 +14,8 @@
class AuthJSONRPCResource(resource.Resource):
def __init__(self, protocol):
resource.Resource.__init__(self)
- self.putChild("", protocol)
- self.putChild(conf.settings['API_ADDRESS'], protocol)
+ self.putChild(b"", protocol)
+ self.putChild(conf.se... |
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... | ---
+++
@@ -26,6 +26,13 @@
self.fh.seek(0)
return i + 1
+ def parse_line(self, line):
+ """
+ Override this method if you need line
+ by line parsing of an Asset.
+ """
+ return line.replace('\n','')
+
def next_asset(self):
"""
Return th... |
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 | ---
+++
@@ -1,3 +1,4 @@
+from functools import wraps
import inspect
@@ -40,7 +41,10 @@
' {!s}')
.format(p, carg, ', '.join(fspec.args)))
+ @wraps(f)
def g(*a, **kw):
return f(*a, **kw)
+
+ g.nopre = f
return g
... |
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 | ---
+++
@@ -29,18 +29,24 @@
def deepExec():
for_closure = 3
- def execFunction():
- code = "f=2"
+ def deeper():
+ for_closure_as_well = 4
- # Can fool it to nest
- exec code in None, None
+ def execFunction():
+ code = "f=2"
- print "Locals now",... |
f6cfe079cadd545a27ad62ec416115d3bbcf357f | tests/test_between_correls.py | tests/test_between_correls.py | import pytest
import os
from SCNIC.general import simulate_correls
from SCNIC.between_correls import between_correls
@pytest.fixture()
def args():
class Arguments(object):
def __init__(self):
self.table1 = "table1.biom"
self.table2 = "table2.biom"
self.output = "out_dir... | import pytest
import os
from SCNIC.general import simulate_correls
from SCNIC.between_correls import between_correls
@pytest.fixture()
def args():
class Arguments(object):
def __init__(self):
self.table1 = "table1.biom"
self.table2 = "table2.biom"
self.output = "out_dir... | Add module.py test and modify some others for better coverage. Remove files not used. | Add module.py test and modify some others for better coverage.
Remove files not used.
| Python | bsd-3-clause | shafferm/SCNIC | ---
+++
@@ -16,7 +16,7 @@
self.min_sample = None
self.min_p = None
self.min_r = None
- self.sparcc_filter = False
+ self.sparcc_filter = True
self.force = False
self.procs = 1
|
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... | ---
+++
@@ -1,9 +1,6 @@
from sparkperf.cluster import Cluster
import json
-import re
import os
-import sys
-import time
import urllib2
|
13b9aff7c134d5783987ca578cd8664effbe78ef | codegen/templates/python.ejs.py | codegen/templates/python.ejs.py | <% if (showSetup) { -%>
from KalturaClient import *
from KalturaClient.Plugins.Core import *
<% plugins.forEach(function(p) { -%>
from KalturaClient.Plugins.<%- p.charAt(0).toUpperCase() + p.substring(1) %> import *
<% }) -%>
config = KalturaConfiguration(<%- answers.partnerId %>)
config.serviceUrl = "https://www.kalt... | <% if (showSetup) { -%>
from KalturaClient import *
from KalturaClient.Plugins.Core import *
<% plugins.forEach(function(p) { -%>
from KalturaClient.Plugins.<%- p.charAt(0).toUpperCase() + p.substring(1) %> import *
<% }) -%>
config = KalturaConfiguration(<%- answers.partnerId %>)
config.serviceUrl = "https://www.kalt... | Drop the ';' in the Python codegen as it's not necessary. | Drop the ';' in the Python codegen as it's not necessary.
| Python | agpl-3.0 | kaltura/developer-platform,kaltura/developer-platform,kaltura/developer-platform,kaltura/developer-platform,kaltura/developer-platform,kaltura/developer-platform,kaltura/developer-platform,kaltura/developer-platform,kaltura/developer-platform,kaltura/developer-platform | ---
+++
@@ -19,6 +19,6 @@
<% } -%>
<%- codegen.assignAllParameters(parameters, answers) -%>
-result = client.<%- service %>.<%- action %>(<%- parameterNames.join(', ') %>);
-print(result);
+result = client.<%- service %>.<%- action %>(<%- parameterNames.join(', ') %>)
+print(result)
<% -%> |
d5597911837967c1f34d1c904282f9464e38e767 | flask_controllers/GameModes.py | flask_controllers/GameModes.py | import logging
from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
# Import the Game Controller
from Game.GameController import GameController
class GameModes(MethodView):
def get(self):
logging.debug("GameModes: GET: Initializing GameObje... | import logging
from flask import request
from flask.views import MethodView
from flask_helpers.build_response import build_response
# Import the Game Controller
from Game.GameController import GameController
class GameModes(MethodView):
def get(self):
logging.debug("GameModes: GET: Initializing GameObje... | Update logging for message output and consistency. | Update logging for message output and consistency.
| Python | apache-2.0 | dsandersAzure/python_cowbull_server,dsandersAzure/python_cowbull_server | ---
+++
@@ -19,7 +19,7 @@
logging.debug("GameModes: GET: Responding with list of names")
response_data = game_object.game_mode_names
else:
- logging.debug("GameModes: GET: Responding with JSON object")
+ logging.debug("GameModes: GET: Responding with JSON objec... |
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 | ---
+++
@@ -33,8 +33,11 @@
path = os.path.join(os.path.dirname(__file__), '..', '..', 'setup.py')
proc = subprocess.Popen([sys.executable, path, 'bdist'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
+ stderr=subprocess.STDOUT, univers... |
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 | ---
+++
@@ -3,11 +3,11 @@
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... |
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 | ---
+++
@@ -12,7 +12,7 @@
# root imports will slowly be deprecated.
# please import from the relevant sub modules
split_version = get_version().split('.')
-if split_version[1][0] != '9' and split_version[1][:2] != '10':
+if split_version[1] not in ('9', '10', '11'):
from .tasks import async, schedule, result,... |
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 | ---
+++
@@ -1,8 +1,26 @@
__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):
+... |
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 | ---
+++
@@ -32,13 +32,8 @@
return modules
return []
-def savelist(system=LMOD_SYSTEM_NAME):
- names = module('savelist').split()
- if system:
- suffix = '.{}'.format(system)
- n = len(suffix)
- names = [name[:-n] for name in names if name.endswith(suffix)]
- return names
... |
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 | ---
+++
@@ -18,6 +18,10 @@
}
}
+# Disable logging
+import logging
+logging.disable(logging.CRITICAL)
+
env = get_secret("ENVIRONMENT")
import sys |
9e706341fafc8a931a662ea497df39fff6f9408b | wooey/migrations/0028_add_script_subparser.py | wooey/migrations/0028_add_script_subparser.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-04-25 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
class Migration(migrations.Migration):
dependencies = [
('wooey', '0027_parameter_order'),
... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-04-25 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
class Migration(migrations.Migration):
dependencies = [
('wooey', '0027_parameter_order'),
... | Add in shim nullable FK for initial scriptparameter update | Add in shim nullable FK for initial scriptparameter update
| Python | bsd-3-clause | wooey/Wooey,wooey/Wooey,wooey/Wooey,wooey/Wooey | ---
+++
@@ -26,7 +26,7 @@
migrations.AddField(
model_name='scriptparameter',
name='parser',
- field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'),
+ field=models.ForeignKey(null=True, on_delete=django.db.mode... |
255d4d551b9eb576c787396f67ca165addf99dbe | cropimg/thumbnail_processors.py | cropimg/thumbnail_processors.py | try:
from PIL import Image
except ImportError:
import Image
def crop_ci_box(im, size, ci_box=False, **kwargs):
"""
Crop image based on very specific pixel values (x,y,width,height)
ci_box
Crop the source image to exactly match the requested box
"""
if not ci_box:
return im... | try:
from PIL import Image
except ImportError:
import Image
def crop_box(im, size, ci_box=False, **kwargs):
"""
Crop image based on very specific pixel values (x,y,width,height)
ci_box
Crop the source image to exactly match the requested box
"""
if not ci_box:
return im
... | Rename the processor back to its original name, crop_box | Rename the processor back to its original name, crop_box
| Python | mit | rewardz/cropimg-django,rewardz/cropimg-django,rewardz/cropimg-django | ---
+++
@@ -4,7 +4,7 @@
import Image
-def crop_ci_box(im, size, ci_box=False, **kwargs):
+def crop_box(im, size, ci_box=False, **kwargs):
"""
Crop image based on very specific pixel values (x,y,width,height)
|
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 | ---
+++
@@ -23,8 +23,6 @@
'''This is a module for dealing with urls. In particular, sanitizing them.'''
-import sys
-
from six import text_type
if text_type == str:
from .url import UnicodeURL as URL |
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 | ---
+++
@@ -37,6 +37,13 @@
"--verbose",
],
)
+ api.step(
+ "Clippy windows crosvm",
+ [
+ "vpython3",
+ "./tools/clippy",
+ ],
+ )
def GenTests(api): |
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 | ---
+++
@@ -7,6 +7,6 @@
def parse(self, world, player, data, ev_man):
#If player is active
- if data[2] == 1:
+ if data[2] == 1 and player.logged_in:
#Raise event with player_id
ev_man.raise_event(Events.NewPlayer, data[1]) |
088295e7d4d81b5e2fb23564b49ddd08beb3f720 | chatterbot/__init__.py | chatterbot/__init__.py | """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot
__version__ = '0.5.4'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'
| """
ChatterBot is a machine learning, conversational dialog engine.
"""
from .chatterbot import ChatBot
__version__ = '0.5.5'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot'
| Update package version to 0.5.5 | Update package version to 0.5.5
| Python | bsd-3-clause | Reinaesaya/OUIRL-ChatBot,Gustavo6046/ChatterBot,gunthercox/ChatterBot,davizucon/ChatterBot,Reinaesaya/OUIRL-ChatBot,maclogan/VirtualPenPal,vkosuri/ChatterBot | ---
+++
@@ -3,7 +3,7 @@
"""
from .chatterbot import ChatBot
-__version__ = '0.5.4'
+__version__ = '0.5.5'
__author__ = 'Gunther Cox'
__email__ = 'gunthercx@gmail.com'
__url__ = 'https://github.com/gunthercox/ChatterBot' |
39ec7961bb3c4431bda67956f0208ab524a80213 | blo/DBControl.py | blo/DBControl.py | import sqlite3
class DBControl:
def __init__(self, db_name : str=":memory:"):
self.db_conn = sqlite3.connect(db_name)
def create_tables(self):
c = self.db_conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS Articles (
id INTEGER PRIMARY KEY AUTOIN... | import sqlite3
from .BloArticle import BloArticle
class DBControl:
def __init__(self, db_name : str=":memory:"):
self.db_conn = sqlite3.connect(db_name)
def create_tables(self):
c = self.db_conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS Articles (
... | Implement stab of insert article information method. | Implement stab of insert article information method.
| Python | mit | 10nin/blo,10nin/blo | ---
+++
@@ -1,5 +1,5 @@
import sqlite3
-
+from .BloArticle import BloArticle
class DBControl:
def __init__(self, db_name : str=":memory:"):
@@ -19,6 +19,15 @@
self.db_conn.close()
self.db_conn = None
+ def insert_article(self, article: BloArticle):
+ assert(article is not None)
... |
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 | ---
+++
@@ -23,5 +23,5 @@
@mock.patch('flask.Flask.run', create=True, return_value=True)
def test_start(self, new_app_run_func):
- result = self.cli_run('start')
+ result = self.cli_run('start', '--env', 'test')
self.assertEqual(0, result.exit_code, msg=str(result)) |
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 | ---
+++
@@ -4,7 +4,3 @@
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')) |
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 | ---
+++
@@ -17,6 +17,9 @@
def __init__(self, language, streamline=False):
self.language = language
+ #: The parser can hold an internal state of the current line
+ self.line_number = None
+
if streamline:
self.streamline()
@@ -28,13 +31,19 @@
"""
... |
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 | ---
+++
@@ -1,10 +1,24 @@
from django.contrib import admin
-from django.contrib.admin import register
-from . import models
+from django.contrib.auth.admin import UserAdmin
-@register(models.FalmerUser)
-class FalmerUserModelAdmin(admin.ModelAdmin):
+# @register(models.FalmerUser)
+# class FalmerUserModelAdmin(adm... |
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 | ---
+++
@@ -3,9 +3,11 @@
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")')
+key_file_path = 'flask_app/secret_key.py'... |
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 | ---
+++
@@ -1,12 +1,12 @@
# 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: ... |
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 | ---
+++
@@ -15,7 +15,10 @@
import wsgi, convergence
-forwarding_conditions = [lambda e : 'google.com/safebrowsing/downloads' not in e['reconstructed_url']]
+forwarding_conditions = [
+ lambda e : 'google.com/safebrowsing/downloads' not in e['reconstructed_url'],
+ lambda e : 'mozilla.org/en-US/firefox/live... |
1a77599911f26cf660e9d11693ab95aef38d44b7 | first_django/urls.py | first_django/urls.py | """first_django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | """first_django URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | Test use vcs plugin to commit. | Test use vcs plugin to commit.
| Python | apache-2.0 | wmh-demos/django-first-demo,wmh-demos/django-first-demo | ---
+++
@@ -22,3 +22,4 @@
url(r'^index/$', my_app_views.index, name='index'),
url(r'^$', my_app_views.func)
]
+ |
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 | ---
+++
@@ -30,8 +30,8 @@
try:
fas = fedora.client.AccountSystem(**config['fas_credentials'])
person = fas.person_by_username(username)
- if person.email:
- return person.email
+ if person.get('email'):
+ return person['email']
raise ValueError("No e... |
ef497d6bac0f60dee04e47a8ec742744c1ab9427 | poyo/patterns.py | poyo/patterns.py | # -*- coding: utf-8 -*-
INDENT = r"(?P<indent>^ *)"
VARIABLE = r"(?P<variable>.+):"
VALUE = r"(?P<value>((?P<q2>['\"]).*?(?P=q2))|[^#]+?)"
NEWLINE = r"$\n"
BLANK = r" +"
INLINE_COMMENT = r"( +#.*)?"
COMMENT = r"^ *#.*" + NEWLINE
BLANK_LINE = r"^[ \t]*" + NEWLINE
DASHES = r"^---" + NEWLINE
SECTION = INDENT + VARIABLE... | # -*- coding: utf-8 -*-
INDENT = r"(?P<indent>^ *)"
VARIABLE = r"(?P<variable>.+):"
VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)"
NEWLINE = r"$\n"
BLANK = r" +"
INLINE_COMMENT = r"(?: +#.*)?"
COMMENT = r"^ *#.*" + NEWLINE
BLANK_LINE = r"^[ \t]*" + NEWLINE
DASHES = r"^---" + NEWLINE
SECTION = INDENT + VARI... | Update to non-capturing groups in VALUE and INLINE_COMMENT | Update to non-capturing groups in VALUE and INLINE_COMMENT
| Python | mit | hackebrot/poyo | ---
+++
@@ -2,10 +2,10 @@
INDENT = r"(?P<indent>^ *)"
VARIABLE = r"(?P<variable>.+):"
-VALUE = r"(?P<value>((?P<q2>['\"]).*?(?P=q2))|[^#]+?)"
+VALUE = r"(?P<value>(?:(?P<q2>['\"]).*?(?P=q2))|[^#]+?)"
NEWLINE = r"$\n"
BLANK = r" +"
-INLINE_COMMENT = r"( +#.*)?"
+INLINE_COMMENT = r"(?: +#.*)?"
COMMENT = r"^ *#... |
12eea471fb50c229dff5627e1e97b7ddeceedd18 | TWLight/ezproxy/urls.py | TWLight/ezproxy/urls.py | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from . import views
urlpatterns = [
url(r'^u/(?P<url>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)$',
login_required(views.EZProxyAuth.as_view()),
name='ezproxy_auth_u'
... | from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from . import views
urlpatterns = [
url(r'^u/(?P<url>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)$',
login_required(views.EZProxyAuth.as_view()),
name='ezproxy_auth_u'
... | Use a more precise pattern to id ^R ezproxy url tokens. | Use a more precise pattern to id ^R ezproxy url tokens.
| Python | mit | WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight | ---
+++
@@ -8,7 +8,7 @@
login_required(views.EZProxyAuth.as_view()),
name='ezproxy_auth_u'
),
- url(r'^r/(?P<token>([a-zA-Z]|[0-9]|[$-_@.&+])+)$',
+ url(r'^r/(?P<token>(ezp\.[a-zA-Z]|[0-9]|[$-_@.&+])+)$',
login_required(views.EZProxyAuth.as_view()),
name='ezproxy_aut... |
f1941a96a08545ac83ff15675331939bc2beddcb | server/gauges.py | server/gauges.py | #!/usr/bin/env python3
import os
from flask import Flask, jsonify, send_from_directory, abort, Response, request
import psycopg2
app = Flask(__name__)
conn = psycopg2.connect("dbname='rivers' user='nelson' host='localhost' password='NONE'")
#@app.route('/')
#def index():
# return send_from_directory('.', 'index.htm... | #!/usr/bin/env python3
import os
from flask import Flask, jsonify, send_from_directory, abort, Response, request
import psycopg2
import psycopg2.extras
app = Flask(__name__)
conn = psycopg2.connect("dbname='rivers' user='nelson' host='localhost' password='NONE'")
#@app.route('/')
#def index():
# return send_from_di... | Return data in dict form | Return data in dict form
| Python | bsd-3-clause | r-barnes/waterviz,HydroLogic/waterviz,r-barnes/waterviz,HydroLogic/waterviz,r-barnes/waterviz,HydroLogic/waterviz,r-barnes/waterviz,HydroLogic/waterviz | ---
+++
@@ -2,6 +2,7 @@
import os
from flask import Flask, jsonify, send_from_directory, abort, Response, request
import psycopg2
+import psycopg2.extras
app = Flask(__name__)
@@ -13,8 +14,7 @@
@app.route('/gauges/list/<string:xmin>/<string:ymin>/<string:xmax>/<string:ymax>', methods=['GET'])
def show_gau... |
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 | ---
+++
@@ -40,6 +40,6 @@
packages = ['deep',
'deep.tools',
],
- scripts = [
+ scripts = ['scripts/clusterDb.py',
]
) |
43acbf596e615f68eef119fb828aff55df0586d5 | FlaskRequests.py | FlaskRequests.py | from flask import Request, Response
class RqRequest(Request):
def rq_headers(self):
headers = {}
if 'Authorization' in self.headers:
headers['Authorization'] = self.headers['Authorization']
if self.headers['Accept'] == 'application/xml':
headers['Accept'] = 'applicati... | from flask import Request, Response
class RqRequest(Request):
def rq_headers(self):
headers = {}
if 'Authorization' in self.headers:
headers['Authorization'] = self.headers['Authorization']
if self.headers.get('Accept') == 'application/xml':
headers['Accept'] = 'appli... | Fix KeyError when accessing non-existing header | Fix KeyError when accessing non-existing header | Python | mit | Timothee/Passeplat | ---
+++
@@ -4,7 +4,7 @@
headers = {}
if 'Authorization' in self.headers:
headers['Authorization'] = self.headers['Authorization']
- if self.headers['Accept'] == 'application/xml':
+ if self.headers.get('Accept') == 'application/xml':
headers['Accept'] = 'appli... |
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 | ---
+++
@@ -12,6 +12,9 @@
else:
raise PropertyMappingFailedException("property %s not found in source feature" %
(value))
+ elif type(value) == dict:
+ if "static" in value:
+ results[key] = value["static"]
else:
... |
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 | ---
+++
@@ -1,6 +1,11 @@
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.
@@ -15,7 +20,7 @@
src may be any glob to recognize files. dst must ... |
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 | ---
+++
@@ -25,6 +25,10 @@
Throws exception on trouble.
"""
+ if os.path.realpath(src) == os.path.realpath(dest):
+ # Copying a file onto itself is a no-op, never mind
+ return
+
parent = os.path.dirname(dest)
if not os.path.isdir(parent):
raise IOError("Destination par... |
c181c54ee749408401b47c9528e9ee085b582692 | timelapse.py | timelapse.py | import os
import datetime
import time
import picamera
from PIL import Image, ImageStat, ImageFont, ImageDraw
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
camera.rotation = 180
time.sleep(2) # camera warm-up time
for filename in camera.capture_continuous('images/img_{timesta... | import os
import datetime
import time
import picamera
from PIL import Image, ImageStat, ImageFont, ImageDraw
with picamera.PiCamera() as camera:
camera.resolution = (1024, 768)
camera.rotation = 180
time.sleep(2) # camera warm-up time
for filename in camera.capture_continuous('images/img_{timesta... | Revert "E arruma o alinhamento do texto" | Revert "E arruma o alinhamento do texto"
This reverts commit a7cb58ef323df97de537bb7cf0571c5ed26e113c.
| Python | mit | dvl/raspberry-pi_timelapse,dvl/raspberry-pi_timelapse | ---
+++
@@ -34,7 +34,7 @@
draw = ImageDraw.Draw(image)
font = ImageFont.truetype('/usr/share/fonts/truetype/roboto/Roboto-Regular.ttf', 24)
- draw.text((10, 700), annotate_text, (255, 255, 0), font=font)
+ draw.text((10, 730), annotate_text, (255, 255, 0), font=font)
... |
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... | ---
+++
@@ -7,6 +7,9 @@
from twisted.trial.unittest import SynchronousTestCase
from ..acceptance import IClusterRunner, ManagedRunner
+
+from flocker.provision import PackageSource
+from flocker.acceptance.testtools import DatasetBackend
class ManagedRunnerTests(SynchronousTestCase):
@@ -19,7 +22,15 @@
... |
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... | ---
+++
@@ -6,7 +6,7 @@
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'email', 'url', 'classification', 'topic', 'depth',)
- list_filter = ('classification', 'topic',)
+ list_filter = ('classification', 'topic', 'jurisdiction',)
search... |
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 | ---
+++
@@ -9,9 +9,17 @@
logger = logging.getLogger('java_vm')
-if '-Xmx4g' not in jnius_config.get_options():
+def _has_xmx(options):
+ for option in options:
+ if option.startswith('-Xmx'):
+ return True
+ return False
+
+default_mem_limit = '8g'
+
+if not _has_xmx(jnius_config.get_opti... |
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 | ---
+++
@@ -6,20 +6,42 @@
class W2VCorpus(Corpus):
- def __init__(self, dir, dict_loc, vec_loc):
+ def __init__(self, dict_loc, vec_loc, dir=None):
Corpus.__init__(self, dir)
- # Todo: Tweak the default paramaters
- self.model = models.Word2Vec(self.docs.get_texts(), size=100, window... |
c9c3a81187fa3fe21b08fca9b37c6a608e7b03b2 | sweettooth/extensions/feeds.py | sweettooth/extensions/feeds.py |
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from extensions.models import Extension
class LatestExtensionsFeed(Feed):
title = "Latest extensions in GNOME Shell Extensions"
link = "/"
description = "The latest extensions in GNOME Shell Extensions"
def... |
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from extensions.models import Extension
class LatestExtensionsFeed(Feed):
title = "Latest extensions in GNOME Shell Extensions"
link = "/"
description = "The latest extensions in GNOME Shell Extensions"
def... | Fix RSS feed some more. | Fix RSS feed some more.
| Python | agpl-3.0 | GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,magcius/sweettooth,magcius/sweettooth | ---
+++
@@ -9,7 +9,7 @@
description = "The latest extensions in GNOME Shell Extensions"
def items(self):
- return Extension.objects.visible().order_by('pk')[-10:]
+ return Extension.objects.visible().order_by('-pk')[:10]
def item_title(self, item):
return item.name |
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 | ---
+++
@@ -16,6 +16,7 @@
url(r'^tasks/$', AppView.as_view(), name='tasks'),
url(r'^reports/$', AppView.as_view(), name='reports'),
url(r'^invoices/$', AppView.as_view(), name='invoices'),
+ url(r'^invoices/([0-9]+)/$', AppView.as_view(), name='invoices'),
url(
r'^$', |
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 | ---
+++
@@ -10,12 +10,14 @@
prefix = prefix[0].rstrip()
+md5 = hashlib.md5()
+md5.update(prefix)
+
while True:
- md5 = hashlib.md5()
- md5.update('{0}{1}'.format(prefix, number))
+ m = md5.copy()
+ m.update(str(number))
- if md5.hexdigest()[:5] == '00000':
- #print md5.hexdigest()
+ if m.hexd... |
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 | ---
+++
@@ -29,12 +29,13 @@
os.environ["RANCHER_SECRET_KEY"] = vargs['secret_key']
try:
- rc_args = [
- "rancher-compose", "-f", compose_file, "-p", stack, "up", "-d",
+ rancher_compose_command = [
+ "rancher-compose", "-f", compose_file, "-p", stack, "up", "-d", "--for... |
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 | ---
+++
@@ -16,8 +16,8 @@
# create a sample of prior order products
order_products_prior_df = pd.read_csv('Data/order_products__prior.csv', index_col = 'order_id')
-order_products_prior_df.loc[orders_df.loc[i,:]['order_id'],:].to_csv("Data/order_products_prior_sample.csv", index = False)
+order_products_prior_df.... |
6eed42d2abbc458b7df4d06faf55a70e33404030 | docs/conf.py | docs/conf.py | # -*- coding: utf-8 -*-
AUTHOR = u'Adrian Sampson'
# General configuration
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.extlinks']
exclude_patterns = ['_build']
source_suffix = '.rst'
master_doc = 'index'
project = u'beets'
copyright = u'2012, Adrian Sampson'
version = '1.3'
release = '1.3.17'
pygments_style ... | # -*- coding: utf-8 -*-
AUTHOR = u'Adrian Sampson'
# General configuration
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.extlinks']
exclude_patterns = ['_build']
source_suffix = '.rst'
master_doc = 'index'
project = u'beets'
copyright = u'2016, Adrian Sampson'
version = '1.3'
release = '1.3.17'
pygments_style ... | Update documentation copyright year to 2016 | Update documentation copyright year to 2016
| Python | mit | mried/beets,SusannaMaria/beets,Freso/beets,madmouser1/beets,Freso/beets,ibmibmibm/beets,MyTunesFreeMusic/privacy-policy,jcoady9/beets,parapente/beets,ibmibmibm/beets,parapente/beets,beetbox/beets,Freso/beets,madmouser1/beets,SusannaMaria/beets,MyTunesFreeMusic/privacy-policy,beetbox/beets,mried/beets,xsteadfastx/beets,... | ---
+++
@@ -11,7 +11,7 @@
master_doc = 'index'
project = u'beets'
-copyright = u'2012, Adrian Sampson'
+copyright = u'2016, Adrian Sampson'
version = '1.3'
release = '1.3.17' |
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 | ---
+++
@@ -1,10 +1,18 @@
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]+', ... |
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 | ---
+++
@@ -12,9 +12,5 @@
if factor == 0:
return []
- multiples = set()
- for i in range(0, limit):
- if i % factor == 0:
- multiples.add(i)
- return multiples
+ return [multiple for multiple in range(limit) if multiple % factor == 0]
|
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 | ---
+++
@@ -47,6 +47,16 @@
"🖥️",
"🕹️",
"🎞️",
+ "🎛️",
+ "🎖️",
+ "↘️",
+ "⬇️",
+ "↙️",
+ "⬅️",
+ "↖️",
+ "⬆️",
+ "↗️",
+ "➡️",
]
for emoji in double... |
8de4fc98785f130c9b0fdb7d7f022aa2b0c4f389 | uchicagohvz/game/middleware.py | uchicagohvz/game/middleware.py | from django.core.urlresolvers import resolve, reverse, Resolver404
from django.http import HttpResponseRedirect
from django.utils import timezone
from datetime import datetime
class Feb262015Middleware(object):
self.target_url = 'feb-26-2015-charlie-hebdo'
def process_request(self, request):
try:
rm = resolve(r... | from django.core.urlresolvers import resolve, reverse, Resolver404
from django.http import HttpResponseRedirect
from django.utils import timezone
from datetime import datetime
class Feb262015Middleware(object):
target_url = 'feb-26-2015-charlie-hebdo'
def process_request(self, request):
try:
rm = resolve(requ... | Remove erroneous reference to self | Remove erroneous reference to self
| Python | mit | kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz | ---
+++
@@ -4,7 +4,8 @@
from datetime import datetime
class Feb262015Middleware(object):
- self.target_url = 'feb-26-2015-charlie-hebdo'
+ target_url = 'feb-26-2015-charlie-hebdo'
+
def process_request(self, request):
try:
rm = resolve(request.path) |
195138143ed9cb374175710369b2a77089cac593 | px/px_pager.py | px/px_pager.py | import os
import sys
import threading
import subprocess
from . import px_processinfo
if sys.version_info.major >= 3:
# For mypy PEP-484 static typing validation
from . import px_process # NOQA
from typing import List # NOQA
def _pump_info_to_fd(fileno, process, processes):
try:
px_process... | import os
import sys
import threading
import subprocess
from . import px_processinfo
if sys.version_info.major >= 3:
# For mypy PEP-484 static typing validation
from . import px_process # NOQA
from typing import List # NOQA
def _pump_info_to_fd(fileno, process, processes):
# type: (int, px_proces... | Move pager selection into its own function | Move pager selection into its own function
| Python | mit | walles/px,walles/px | ---
+++
@@ -12,6 +12,7 @@
def _pump_info_to_fd(fileno, process, processes):
+ # type: (int, px_process.PxProcess, List[px_process.PxProcess]) -> None
try:
px_processinfo.print_process_info(fileno, process, processes)
os.close(fileno)
@@ -23,11 +24,16 @@
pass
+def launch_pag... |
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 | ---
+++
@@ -1,5 +1,12 @@
def main():
- print ("Hello world!")
+ 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 ("... |
eac89e401d64079f4a3ef05ce7078cbefea271df | tests/system/shared/mainwin.py | tests/system/shared/mainwin.py |
def invokeMenuItem(menu, item):
menuObject = waitForObjectItem("{type='QMenuBar' visible='true'}", menu)
activateItem(menuObject)
activateItem(waitForObjectItem(menuObject, item))
def openQmakeProject(projectPath):
invokeMenuItem("File", "Open File or Project...")
waitForObject("{name='QFileDialog... |
def invokeMenuItem(menu, item):
menuObject = waitForObjectItem("{type='QMenuBar' visible='true'}", menu)
activateItem(menuObject)
activateItem(waitForObjectItem(menuObject, item))
def openQmakeProject(projectPath):
invokeMenuItem("File", "Open File or Project...")
waitForObject("{name='QFileDialog... | Fix openQmakeProject to match new combo value. | Fix openQmakeProject to match new combo value.
Change-Id: Ice0050bf1bb7af59eb57c1e9218d96b3114f4c08
Reviewed-on: http://codereview.qt.nokia.com/4129
Reviewed-by: Qt Sanity Bot <5581206bb7e0307f0d99eb71898ae6b694149ca5@ovi.com>
Reviewed-by: Christian Stenger <accbb51712d7b9c4fb108439d01e716148e5f9e6@nokia.com>
| Python | lgpl-2.1 | omniacreator/qtcreator,xianian/qt-creator,bakaiadam/collaborative_qt_creator,amyvmiwei/qt-creator,KDAB/KDAB-Creator,maui-packages/qt-creator,KDE/android-qt-creator,xianian/qt-creator,colede/qtcreator,darksylinc/qt-creator,Distrotech/qtcreator,azat/qtcreator,xianian/qt-creator,malikcjm/qtcreator,kuba1/qtcreator,kuba1/qt... | ---
+++
@@ -10,7 +10,7 @@
type(findObject("{name='fileNameEdit' type='QLineEdit'}"), projectPath)
clickButton(findObject("{text='Open' type='QPushButton'}"))
waitForObject("{type='Qt4ProjectManager::Internal::ProjectLoadWizard' visible='1' windowTitle='Project Setup'}")
- selectFromCombo(":scrollAre... |
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 | ---
+++
@@ -8,7 +8,7 @@
@api.multi
def compute_sheet(self):
- journal_id = False
if self.env.context.get('active_id'):
journal_id = self.env['hr.payslip.run'].browse(self.env.context.get('active_id')).journal_id.id
- return super(HrPayslipEmployees, self.with_context(jo... |
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 | ---
+++
@@ -18,7 +18,10 @@
def _make_request(self, verb, *args, **kwargs):
kwargs.update({
- 'auth': (self.username, self.token)
+ 'auth': (self.username, self.token),
+ 'headers': {
+ 'content-type': 'application/json',
+ },
})
... |
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... | ---
+++
@@ -1,7 +1,6 @@
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 |
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 | ---
+++
@@ -17,10 +17,10 @@
mid = (lft + rgt) // 2
if xs[mid] == x:
return mid
- elif x < xs[mid]:
+ if xs[mid] < x:
+ lft = mid + 1
+ else:
rgt = mid - 1
- elif x > xs[mid]:
- lft = mid + 1
return None
@@ -39,9 +39... |
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 | ---
+++
@@ -18,19 +18,21 @@
)
if args.client is not None:
mfhclient_process.start()
- trigger_process = Process(
- args=(update_event,),
- name="trigger_process",
- target=update.trigger,
- )
- trigger_process.start()
- trigger_process.join()
+ if args.up... |
8276c2548bd84c4318a2fff45625a08d2ab38fcd | tests/integration/shell/key.py | tests/integration/shell/key.py | # Import salt libs
import integration
class KeyTest(integration.CliCase):
'''
Test salt-key script
'''
def test_list(self):
'''
test salt-key -L
'''
data = self.run_key('-L')
expect = [
'\x1b[1;31mUnaccepted Keys:\x1b[0m',
'\x1b[1;... | # Import salt libs
import integration
class KeyTest(integration.ShellCase):
'''
Test salt-key script
'''
def test_list(self):
'''
test salt-key -L
'''
data = self.run_key('-L')
expect = [
'\x1b[1;31mUnaccepted Keys:\x1b[0m',
'\x1b[... | Change name of clicase to shellcase | Change name of clicase to shellcase
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | ---
+++
@@ -1,7 +1,7 @@
# Import salt libs
import integration
-class KeyTest(integration.CliCase):
+class KeyTest(integration.ShellCase):
'''
Test salt-key script
''' |
c99652b3992b1a4aa6f1ca44051cbfd66410505a | examples/generate-manager-file.py | examples/generate-manager-file.py | #!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
else:
manager_name = "haze"
service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name
object_path = "/org/freedesktop/Telepathy/ConnectionMana... | #!/usr/bin/python
import sys
import telepathy
from telepathy.interfaces import CONN_MGR_INTERFACE
if len(sys.argv) >= 2:
manager_name = sys.argv[1]
else:
manager_name = "haze"
service_name = "org.freedesktop.Telepathy.ConnectionManager.%s" % manager_name
object_path = "/org/freedesktop/Telepathy/ConnectionMana... | Sort the generated manager file by protocol name | Sort the generated manager file by protocol name
20070831193701-4210b-ede9decef118aba3937b0291512956927333dbe6.gz
| Python | lgpl-2.1 | detrout/telepathy-python,PabloCastellano/telepathy-python,max-posedon/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,detrout/telepathy-python,epage/telepathy-python,freedesktop-unofficial-mirror/telepathy__telepathy-python,epage/telepathy-python,PabloCastellano/telepathy-python,max-posedon/t... | ---
+++
@@ -18,7 +18,9 @@
print "ObjectPath=%s" % object_path
print
-for protocol in manager.ListProtocols():
+protocols = manager.ListProtocols()
+protocols.sort()
+for protocol in protocols:
print "[Protocol %s]" % protocol
for param in manager.GetParameters(protocol):
print "param-%s=%s" % (... |
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 | ---
+++
@@ -1,3 +1,3 @@
from .core import (CallbackBase, CallbackCounter, print_metadata, collector,
LiveMesh, LivePlot, LiveRaster, LiveTable, CollectThenCompute,
- _get_obj_fields)
+ LiveSpecFile, _get_obj_fields) |
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 | ---
+++
@@ -1,13 +1,29 @@
__author__ = "Raido Pahtma"
__license__ = "MIT"
+import re
+import os
+import sys
import glob
-import sys
-import os
+import serial
def _list_windows_serial_ports():
- raise NotImplementedError("windows support")
+ ports = []
+
+ for i in range(256):
+ try:
+ ... |
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 | ---
+++
@@ -1,11 +1,22 @@
+from pygame import Rect
+
class module:
- mod_name = "unnamed_module";
- mod_id = -1;
- mod_rect = None;
- mod_surface = None;
- mod_attribs = [];
+ mod_name = "unnamed_module"
+ mod_id = -1
+ mod_size = Rect(0,0,0,0)
- def __init__(self, _id):
- print("... |
56b84d3271ab2312a0bdbd27c6ee3ad60c139920 | search/urls.py | search/urls.py | __author__ = 'Nick'
from django.conf.urls import url
from search import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^query$', views.query, name='query')
] | __author__ = 'Nick'
from django.conf.urls import url
from search import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^query/$', views.query, name='query')
] | Make sure django doesn't mangle route | Make sure django doesn't mangle route
| Python | mit | nh0815/PySearch,nh0815/PySearch | ---
+++
@@ -5,5 +5,5 @@
urlpatterns = [
url(r'^$', views.index, name='index'),
- url(r'^query$', views.query, name='query')
+ url(r'^query/$', views.query, name='query')
] |
c035ee8273b3582133c78353259de026ce81d0b5 | app/assets.py | app/assets.py | from flask.ext.assets import Bundle
app_css = Bundle(
'app.scss',
filters='scss',
output='styles/app.css'
)
app_js = Bundle(
'app.js',
filters='jsmin',
output='scripts/app.js'
)
vendor_css = Bundle(
'vendor/semantic.min.css',
output='styles/vendor.css'
)
vendor_js = Bundle(
'vend... | from flask.ext.assets import Bundle
app_css = Bundle(
'*.scss',
filters='scss',
output='styles/app.css'
)
app_js = Bundle(
'app.js',
filters='jsmin',
output='scripts/app.js'
)
vendor_css = Bundle(
'vendor/semantic.min.css',
output='styles/vendor.css'
)
vendor_js = Bundle(
'vendor... | Generalize scss bundle to track all scss files | Generalize scss bundle to track all scss files
| Python | mit | hack4impact/flask-base,ColinHaley/Konsole,ColinHaley/Konsole,aharelick/netter-center,AsylumConnect/asylum-connect-catalog,AsylumConnect/asylum-connect-catalog,tobymccann/flask-base,AsylumConnect/asylum-connect-catalog,AsylumConnect/asylum-connect-catalog,hack4impact/flask-base,hack4impact/asylum-connect-catalog,tobymcc... | ---
+++
@@ -1,7 +1,7 @@
from flask.ext.assets import Bundle
app_css = Bundle(
- 'app.scss',
+ '*.scss',
filters='scss',
output='styles/app.css'
) |
1cd5126c90c87df1bfe10434aa850913aed560b4 | splice/default_settings.py | splice/default_settings.py | import os
class DefaultConfig(object):
"""
Configuration suitable for use for development
"""
DEBUG = True
APPLICATION_ROOT = None
JSONIFY_PRETTYPRINT_REGULAR = True
STATIC_ENABLED_ENVS = {"dev", "test"}
ENVIRONMENT = "dev"
SECRET_KEY = "moz-splice-development-key"
TEMPLATE_... | import os
class DefaultConfig(object):
"""
Configuration suitable for use for development
"""
DEBUG = True
APPLICATION_ROOT = None
JSONIFY_PRETTYPRINT_REGULAR = True
STATIC_ENABLED_ENVS = {"dev", "test"}
ENVIRONMENT = "dev"
SECRET_KEY = "moz-splice-development-key"
TEMPLATE_... | Revert "adding slot_index to impression_stats_daily" | Revert "adding slot_index to impression_stats_daily"
This reverts commit 71202d2f9e2cafa5bf8ef9e0c6a355a8d65d5c7a.
| Python | mpl-2.0 | tkiethanom/splice,mostlygeek/splice,tkiethanom/splice,rlr/splice,rlr/splice,mozilla/splice,mostlygeek/splice,tkiethanom/splice,tkiethanom/splice,rlr/splice,mozilla/splice,mozilla/splice,ncloudioj/splice,oyiptong/splice,oyiptong/splice,ncloudioj/splice,oyiptong/splice,ncloudioj/splice,oyiptong/splice,mostlygeek/splice,m... | ---
+++
@@ -21,7 +21,7 @@
COUNTRY_FIXTURE_PATH = os.path.join(FIXTURES_DIR, "iso3166.csv")
LOCALE_FIXTURE_PATH = os.path.join(FIXTURES_DIR, "all-locales.mozilla-aurora")
- SQLALCHEMY_DATABASE_URI = "postgres://postgres:p@ssw0rd66@localhost/mozsplice"
+ SQLALCHEMY_DATABASE_URI = "postgres://localhost... |
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 | ---
+++
@@ -18,3 +18,17 @@
assert "downloadRawJWT" in response
print(" But the response should not have a JWT for the processed file")
assert "downloadFileJWT" not in response
+
+ def test_recording_doesnt_include_file_key(self, helper):
+ print("If a new user uploads a recording... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.