commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
37bccb59874dd2e50a0ace482461e156ee5b7240 | pytips/util.py | pytips/util.py | # -*- coding: utf-8 -*-
"""Utility functions for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import html5lib
from dateutil.parser import parse as parse_date
def extract_publication_date(html):
"""... | # -*- coding: utf-8 -*-
"""Utility functions for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import signal
from decorator import decorator
import html5lib
from dateutil.parser import parse as parse_da... | Add a decorator to time out long-running functions. | Add a decorator to time out long-running functions.
| Python | isc | gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips |
0762dbb9b0a43eb6bd01f43d88ac990e90da2303 | chandra_suli/filter_reg.py | chandra_suli/filter_reg.py |
"""
Take evt3 file and use region files to subtract off sources that are already known - image will have lots of holes
Goals by Friday 6/31 - Get script working for one image at a time
below = code used by Giacomo to create filtered image
ftcopy 'acisf00635_000N001_evt3.fits[EVENTS][regfilter("my_source.reg")]' test... | #!/usr/bin/env python
"""
Take evt3 file and use region files to subtract off sources that are already known - image will have lots of holes
Goals by Friday 6/31 - Get script working for one image at a time
below = code used by Giacomo to create filtered image
ftcopy 'acisf00635_000N001_evt3.fits[EVENTS][regfilter("m... | Copy reg file names into text file | Copy reg file names into text file
| Python | bsd-3-clause | nitikayad96/chandra_suli |
ba9a758161b6863704b2be7b28f6638e2191d8dd | test/test_nc.py | test/test_nc.py | #!/usr/bin/env python
"""
Unittests for csvnc module
"""
import os
import pytest
from csvnc import csvnc
def test_generated_file_should_have_extention_nc():
data_file = 'data.csv'
assert 'data.nc' == csvnc.new_name(data_file)
| #!/usr/bin/env python
"""
Unittests for csvnc module
"""
import os
import pytest
from csvnc import csvnc
class TestCsvnc(object):
def test_generated_file_should_have_extention_nc(self):
data_file = 'data.csv'
assert 'data.nc' == csvnc.new_name(data_file)
| Add test class for grouping tests | Add test class for grouping tests
| Python | mit | qba73/nc |
1b0253f09196d3824481451f8daee6b486825fa6 | prismriver/qt/gui.py | prismriver/qt/gui.py | import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from prismriver.qt.window import MainWindow
from prismriver import util
def run():
util.init_logging(False, True, None)
app = QApplication(sys.argv)
app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png'))
... | import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication
from prismriver.qt.window import MainWindow
from prismriver import util
def run():
util.init_logging(False, True, None)
app = QApplication(sys.argv)
app.setWindowIcon(QIcon('prismriver/pixmaps/prismriver-lunasa.png'))
... | Set application name to "Lunasa Prismriver" | [qt] Set application name to "Lunasa Prismriver"
That value will be used as WM_CLASS of application.
| Python | mit | anlar/prismriver-lyrics,anlar/prismriver-lyrics,anlar/prismriver,anlar/prismriver |
e852a210a84e91369752ef8fcfbbf52c27b3db59 | pycrest/visualize.py | pycrest/visualize.py | import matplotlib.pyplot as plt
from matplotlib.pyplot import triplot
from mpl_toolkits.mplot3d import Axes3D
from pycrest.mesh import Mesh2d
def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs):
figure = plt.figure() if standalone else None
triplot(tri.vertices[:, 0], tri.vertices[:, 1], tr... | import matplotlib.pyplot as plt
from matplotlib.pyplot import triplot
from mpl_toolkits.mplot3d import Axes3D
from pycrest.mesh import Mesh2d
def plot_triangulation(tri: Mesh2d, standalone=True, *args, **kwargs):
figure = plt.figure() if standalone else None
triplot(tri.vertices[:, 0], tri.vertices[:, 1], tr... | Make pycrest mesh viz more capable | Make pycrest mesh viz more capable
| Python | mit | Andlon/crest,Andlon/crest,Andlon/crest |
e1092caacec94bd016283b8452ad4399dba0f231 | cogs/gaming_tasks.py | cogs/gaming_tasks.py | from discord.ext import commands
from .utils import checks
import asyncio
import discord
import web.wsgi
from django.utils import timezone
from django.db import models
from django.utils import timezone
from gaming.models import DiscordUser, Game, GameUser, Server, Role, GameSearch, Channel
class GamingTasks:
def... | from discord.ext import commands
from .utils import checks
import asyncio
import discord
import web.wsgi
from django.utils import timezone
from django.db import models
from django.utils import timezone
from gaming.models import DiscordUser, Game, GameUser, Server, Role, GameSearch, Channel
class GamingTasks:
def... | Check if it is None before continuing | Check if it is None before continuing
| Python | mit | bsquidwrd/Squid-Bot,bsquidwrd/Squid-Bot |
99764a2d1f99cd6a2b61b35c4a262d730a26ba1f | pytest_hidecaptured.py | pytest_hidecaptured.py | # -*- coding: utf-8 -*-
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(rep... | # -*- coding: utf-8 -*-
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(rep... | Fix failing tests for captured output in teardown | Fix failing tests for captured output in teardown
| Python | mit | hamzasheikh/pytest-hidecaptured |
08aefdf3e5a991293ad9ce1cc7f1112a01e4506d | trade_server.py | trade_server.py | import threading
import socket
import SocketServer
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if data:
messages.append(data)
... | import json
import threading
import socket
import SocketServer
from orderbook import match_bid, offers, bids
messages = []
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
try:
while True:
data = self.request.recv(1024)
if d... | Add basic handling of incoming bids and offers. | Add basic handling of incoming bids and offers.
| Python | mit | Tribler/decentral-market |
c8828d563a3db96a52544c6bbe4ca219efd364c5 | falmer/events/filters.py | falmer/events/filters.py | from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from . import models
class EventFilterSet(FilterSet):
class Meta:
model = models.Event
fields = (
'title',
'venue',
'type',
'bundle',
'parent',
'brand',
... | from django_filters import FilterSet, CharFilter, IsoDateTimeFilter
from . import models
class EventFilterSet(FilterSet):
class Meta:
model = models.Event
fields = (
'title',
'venue',
'type',
'bundle',
'parent',
'brand',
... | Add filtering options to events | Add filtering options to events
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer |
45501645e06743bd6341cfd6d2573f6c5f36d094 | netmiko/ubiquiti/__init__.py | netmiko/ubiquiti/__init__.py | from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH
from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH
from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH
__all__ = [
"UbiquitiEdgeRouterSSH",
"UbiquitiEdgeSSH",
"UnifiSwitchSSH",
"UbiquitiUnifiSwitchSSH",
]
| from netmiko.ubiquiti.edge_ssh import UbiquitiEdgeSSH
from netmiko.ubiquiti.edgerouter_ssh import UbiquitiEdgeRouterSSH
from netmiko.ubiquiti.unifiswitch_ssh import UbiquitiUnifiSwitchSSH
__all__ = [
"UbiquitiEdgeRouterSSH",
"UbiquitiEdgeSSH",
"UbiquitiUnifiSwitchSSH",
]
| Fix __all__ import for ubiquiti | Fix __all__ import for ubiquiti
| Python | mit | ktbyers/netmiko,ktbyers/netmiko |
34c85636d11bc156a4ce4e5956ed1a19fe7f6f1f | buffer/models/profile.py | buffer/models/profile.py | import json
from buffer.response import ResponseObject
PATHS = {
'GET_PROFILES': 'profiles.json',
'GET_PROFILE': 'profiles/%s.json',
'GET_SCHEDULES': 'profiles/%s/schedules.json',
'UPDATE_SCHEDULES': 'profiles/%s/schedules/update.json'
}
class Profile(ResponseObject):
def __init__(self, api, raw_response)... | import json
from buffer.response import ResponseObject
PATHS = {
'GET_PROFILES': 'profiles.json',
'GET_PROFILE': 'profiles/%s.json',
'GET_SCHEDULES': 'profiles/%s/schedules.json',
'UPDATE_SCHEDULES': 'profiles/%s/schedules/update.json'
}
class Profile(ResponseObject):
def __init__(self, api, raw_response)... | Update the schedules times and days | Update the schedules times and days
| Python | mit | vtemian/buffpy,bufferapp/buffer-python |
c4406ffae02a4ea87a139b1d67d98d9c0c7a468b | train.py | train.py | import tensorflow as tf
import driving_data
import model
sess = tf.InteractiveSession()
loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y)))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
sess.run(tf.initialize_all_variables())
saver = tf.train.Saver()
#train over the dataset about 30 ti... | import os
import tensorflow as tf
import driving_data
import model
LOGDIR = './save'
sess = tf.InteractiveSession()
loss = tf.reduce_mean(tf.square(tf.sub(model.y_, model.y)))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
sess.run(tf.initialize_all_variables())
saver = tf.train.Saver()
#train... | Add check for folder to save checkpoints | Add check for folder to save checkpoints
| Python | apache-2.0 | tmaila/autopilot,tmaila/autopilot,SullyChen/Autopilot-TensorFlow,tmaila/autopilot |
06356979dd377137c77139c45a0b40deea3f5b27 | tests/test_api.py | tests/test_api.py | import scipy.interpolate
import numpy as np
import naturalneighbor
def test_output_size_matches_scipy():
points = np.random.rand(10, 3)
values = np.random.rand(10)
grid_ranges = [
[0, 4, 0.6], # step isn't a multiple
[-3, 3, 1.0], # step is a multiple
[0, 1, 3], # step is larg... | import scipy.interpolate
import numpy as np
import pytest
import naturalneighbor
@pytest.mark.parametrize("grid_ranges", [
[[0, 4, 0.6], [-3, 3, 1.0], [0, 1, 3]],
[[0, 2, 1], [0, 2, 1j], [0, 2, 2j]],
])
def test_output_size_matches_scipy(grid_ranges):
points = np.random.rand(10, 3)
values = np.random... | Add test for complex indexing | Add test for complex indexing
| Python | mit | innolitics/natural-neighbor-interpolation,innolitics/natural-neighbor-interpolation,innolitics/natural-neighbor-interpolation |
9a3b0e2fc81187a0ec91230552552805dc6593e4 | profile_collection/startup/50-scans.py | profile_collection/startup/50-scans.py | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | # vim: sw=4 ts=4 sts expandtab smarttab
# HXN step-scan configuration
import hxntools.scans
from bluesky.global_state import get_gs
gs = get_gs()
hxntools.scans.setup()
ct = hxntools.scans.count
ascan = hxntools.scans.absolute_scan
dscan = hxntools.scans.relative_scan
fermat = hxntools.scans.relative_fermat
spiral =... | Move smll and dcm to baseline devices | Move smll and dcm to baseline devices
| Python | bsd-2-clause | NSLS-II-HXN/ipython_ophyd,NSLS-II-HXN/ipython_ophyd |
2d7c286321683a9d3241d0e923f1f182adfd84be | sr/templatetags/sr.py | sr/templatetags/sr.py | from django import template
register = template.Library()
from .. import sr as sr_func
@register.simple_tag(name='sr')
def sr_tag(key, *args, **kwargs):
return sr_func(key, *args, **kwargs)
try:
from django_jinja.base import Library
jinja_register = Library()
jinja_register.global_function("sr", sr_... | from django import template
register = template.Library()
from .. import sr as sr_func
@register.simple_tag(name='sr')
def sr_tag(key, *args, **kwargs):
return sr_func(key, *args, **kwargs)
try:
from django_jinja import library as jinja_library
jinja_library.global_function("sr", sr_func)
except ImportE... | Update support for new django-jinja versions. (backward incompatible) | Update support for new django-jinja versions. (backward incompatible)
| Python | bsd-3-clause | jespino/django-sr |
60ef934e3bef7c00fc2d1823901babb665a4888f | get_study_attachments.py | get_study_attachments.py | import sys
import boto3
BUCKET_NAME = 'mitLookit'
def get_all_study_attachments(study_uuid):
s3 = boto3.resource('s3')
bucket = s3.Bucket(BUCKET_NAME)
study_files = []
for key in bucket.objects.filter(Prefix=f'videoStream_{study_uuid}'):
study_files.append(key)
return study_files
if __na... | import sys
import boto3
BUCKET_NAME = 'mitLookit'
def get_all_study_attachments(study_uuid):
s3 = boto3.resource('s3')
bucket = s3.Bucket(BUCKET_NAME)
return bucket.objects.filter(Prefix=f'videoStream_{study_uuid}')
if __name__ == '__main__':
study_uuid = sys.argv[1]
get_study_keys(study_uuid)
| Remove looping through items and appending them to list. | Remove looping through items and appending them to list.
| Python | apache-2.0 | CenterForOpenScience/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,pattisdr/lookit-api,CenterForOpenScience/lookit-api,CenterForOpenScience/lookit-api |
4bfa74aa2ea9ef936d5ec5efbf32f2d6a8a10634 | adr/recipes/config_durations.py | adr/recipes/config_durations.py | """
Get the average and total runtime for build platforms and types.
.. code-block:: bash
adr config_durations [--branch <branch>]
"""
from __future__ import absolute_import, print_function
from ..query import run_query
def run(config, args):
# process config data
data = run_query('config_durations', c... | """
Get the average and total runtime for build platforms and types.
.. code-block:: bash
adr config_durations [--branch <branch>]
"""
from __future__ import absolute_import, print_function
from ..query import run_query
BROKEN = True
def run(config, args):
# process config data
data = run_query('confi... | Disable failing recipe in CRON tests | Disable failing recipe in CRON tests
| Python | mpl-2.0 | ahal/active-data-recipes,ahal/active-data-recipes |
ba75572bd7de9a441cad72fe90d7ec233e9c1a15 | test/adapt.py | test/adapt.py | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="... | #!/usr/bin/env python
# vim:fileencoding=utf-8
# License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
from __init__ import TestCase
from html5_parser import parse
HTML = '''
<html lang="en" xml:lang="... | Fix test failing on python 3 | Fix test failing on python 3
| Python | apache-2.0 | kovidgoyal/html5-parser,kovidgoyal/html5-parser |
9ca0549ceff05f9f8a391c8ec2b685af48c0a5a8 | scripts/common.py | scripts/common.py | import sys
import psycopg2
import os
import yaml
if 'CATMAID_CONFIGURATION' in os.environ:
path = os.environ['CATMAID_CONFIGURATION']
else:
path = os.path.join(os.environ['HOME'], '.catmaid-db')
try:
conf = yaml.load(open(path))
except:
print >> sys.stderr, '''Your %s file should look like:
host: loc... | import sys
import psycopg2
import os
import yaml
if 'CATMAID_CONFIGURATION' in os.environ:
path = os.environ['CATMAID_CONFIGURATION']
else:
path = os.path.join(os.environ['HOME'], '.catmaid-db')
try:
conf = yaml.load(open(path))
except:
print >> sys.stderr, '''Your %s file should look like:
host: loc... | Define variables for the DB name, host, etc. so they can be imported | Define variables for the DB name, host, etc. so they can be imported
| Python | agpl-3.0 | fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID |
a26dc400c479572be59bfe90d8e809d2e9e65a63 | python_humble_utils/pytest_commands.py | python_humble_utils/pytest_commands.py | import os
def generate_tmp_file_path(tmpdir_factory,
file_name_with_extension: str,
tmp_dir_path: str = None) -> str:
"""
Generate file path rooted in a temporary dir.
:param tmpdir_factory: py.test's tmpdir_factory fixture.
:param file_name_with_... | import os
def generate_tmp_file_path(tmpdir_factory,
file_name_with_extension: str,
tmp_dir_path: str = None) -> str:
"""
Generate file path relative to a temporary directory.
:param tmpdir_factory: py.test's `tmpdir_factory` fixture.
:param file_... | Improve generate_tmp_file_path pytest command docs | Improve generate_tmp_file_path pytest command docs
| Python | mit | webyneter/python-humble-utils |
058e2e75384052dcc2b90690cef695e4533eb854 | scripts/insert_demo.py | scripts/insert_demo.py | """Insert the demo into the codemirror site."""
from __future__ import print_function
import os
import fileinput
import shutil
proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
code_mirror_path = os.path.join(
proselint_path,
"plugins",
"webeditor")
code_mirror_demo_path = os... | """Insert the demo into the codemirror site."""
from __future__ import print_function
import os
import fileinput
import shutil
proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
code_mirror_path = os.path.join(
proselint_path,
"plugins",
"webeditor")
code_mirror_demo_path = os... | Delete live writing demo before loading new one | Delete live writing demo before loading new one
| Python | bsd-3-clause | jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,jstewmon/proselint |
6620032e9f8574c3e1dad37c111040eca570a751 | features/memberships/models.py | features/memberships/models.py | from django.contrib.contenttypes import fields as contenttypes
from django.db import models
class Membership(models.Model):
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
date_joined = models.DateField(auto_now_add=True)
group = models.ForeignKey('grou... | from django.contrib.contenttypes import fields as contenttypes
from django.db import models
from . import querysets
class Membership(models.Model):
class Meta:
unique_together = ('group', 'member')
created_by = models.ForeignKey(
'gestalten.Gestalt', related_name='memberships_created')
... | Add queryset for ordering memberships by activity | Add queryset for ordering memberships by activity
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten |
13301dfe93bcdd44218166bdab1c7aeacd4e4a7c | winthrop/annotation/models.py | winthrop/annotation/models.py | from urllib.parse import urlparse
from django.db import models
from django.urls import resolve, Resolver404
from annotator_store.models import BaseAnnotation
from djiffy.models import Canvas
from winthrop.people.models import Person
class Annotation(BaseAnnotation):
# NOTE: do we want to associate explicitly with... | from urllib.parse import urlparse
from django.db import models
from django.urls import resolve, Resolver404
from annotator_store.models import BaseAnnotation
from djiffy.models import Canvas
from winthrop.people.models import Person
class Annotation(BaseAnnotation):
# NOTE: do we want to associate explicitly with... | Add author field & autocomplete to annotation model+interface | Add author field & autocomplete to annotation model+interface
| Python | apache-2.0 | Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django |
045ead44ef69d6ebf2cb0dddf084762efcc62995 | handlers/base_handler.py | handlers/base_handler.py | from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
return self.file[offset:offset + size]
| from collections import OrderedDict
class BaseHandler:
def __init__(self, file, file_name):
self.file = file
self.file_name = file_name
self.info = OrderedDict()
def read(self, offset, size):
if offset < 0:
raise IndexError("File offset must be greater than 0")
... | Add bounds checking to BaseHandler.read() | Add bounds checking to BaseHandler.read()
| Python | mit | drx/rom-info |
d153696d44220523d072653b9ff0f0d01eef325f | django_enum_js/__init__.py | django_enum_js/__init__.py | import json
class EnumWrapper:
def __init__(self):
self.registered_enums = {}
def register_enum(self, enum_class):
self.registered_enums[enum_class.__name__] = enum_class
def _enum_to_dict(self, enum_class):
return dict([(k,v) for k,v in enum_class.__dict__.items() if not k[:2] ==... | import json
class EnumWrapper:
def __init__(self):
self.registered_enums = {}
def register_enum(self, enum_class):
self.registered_enums[enum_class.__name__] = enum_class
return enum_class
def _enum_to_dict(self, enum_class):
return dict([(k,v) for k,v in enum_class.__dict... | Allow using register_enum as a decorator | Allow using register_enum as a decorator
By returning the original class instance, it'd be possible to use `enum_wrapper.register_enum` as a decorator, making the usage cleaner while staying backwards compatible:
```python
@enum_wrapper.register_enum
class MyAwesomeClass:
pass
``` | Python | mit | leifdenby/django_enum_js |
6dcb33004c3775d707f362a6f2c8217c1d558f56 | kobin/server_adapters.py | kobin/server_adapters.py | from typing import Dict, Any
class ServerAdapter:
quiet = False
def __init__(self, host: str='127.0.0.1', port: int=8080, **options) -> None:
self.options = options
self.host = host
self.port = int(port)
def run(self, handler):
pass
def __repr__(self):
args =... | from typing import Dict, Any
class ServerAdapter:
quiet = False
def __init__(self, host: str='127.0.0.1', port: int=8080, **options) -> None:
self.options = options
self.host = host
self.port = int(port)
def run(self, handler):
pass
def __repr__(self):
args =... | Add a gunicorn server adpter | Add a gunicorn server adpter
| Python | mit | kobinpy/kobin,kobinpy/kobin,c-bata/kobin,c-bata/kobin |
b7486b64cabc0ad4c022a520bb630fb88cb35e53 | feincms/content/raw/models.py | feincms/content/raw/models.py | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django import forms
class RawContent(models.Model):
text = models.TextField(_('content'), blank=True)
class Meta:
abstract = True
verbose_name = _('raw conte... | from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from django import forms
class RawContent(models.Model):
text = models.TextField(_('content'), blank=True)
class Meta:
abstract = True
verbose_name = _('raw conte... | Remove test content type media from RawContent | Remove test content type media from RawContent
| Python | bsd-3-clause | feincms/feincms,joshuajonah/feincms,pjdelport/feincms,feincms/feincms,matthiask/django-content-editor,joshuajonah/feincms,nickburlett/feincms,nickburlett/feincms,michaelkuty/feincms,mjl/feincms,joshuajonah/feincms,matthiask/django-content-editor,nickburlett/feincms,michaelkuty/feincms,matthiask/feincms2-content,nickbur... |
64636185744a9a64b1b04fcd81ee32930bb145af | scores.py | scores.py | from nameko.rpc import rpc, RpcProxy
class ScoreService(object):
name = 'score_service'
player_service = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_service.get_players()
return sorted(players, key=lambda player: player.score, reverse=True)
| from nameko.rpc import rpc, RpcProxy
class ScoreService(object):
name = 'score_service'
player_rpc = RpcProxy('players_service')
@rpc
def leaderboard(self):
players = self.player_rpc.get_players()
sorted_players = sorted(players, key=lambda player: player.score, reverse=True)
... | Add method to update a player's score | Add method to update a player's score
| Python | mit | radekj/poke-battle,skooda/poke-battle |
39ba5da2f6e80bc78ca061edb34c8a2dd7e9c199 | shortwave/urls.py | shortwave/urls.py | from django.conf.urls.defaults import *
from shortwave.views import wave_list, wave_detail
urlpatterns = patterns('',
url(r'^$', wave_list, name='shortwave-wave-list'),
url(r'^(?P<username>[-\w]+)/$', wave_detail, name='shortwave-wave-detail'),
)
| from django.conf.urls.defaults import *
from shortwave.views import wave_list, wave_detail
urlpatterns = patterns('',
url(r'^$',
wave_list,
name='shortwave-wave-list',
),
url(r'^(?P<username>[-\w]+)/$',
wave_detail,
name='shortwave-wave-detail',
),
)
| Format URL patterns into more readable form. | Format URL patterns into more readable form.
| Python | bsd-3-clause | benspaulding/django-shortwave |
071f42389aef9c57cb4f0a0434d8297ccba05ab2 | openquake/hazardlib/general.py | openquake/hazardlib/general.py | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, ... | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2014, GEM Foundation.
#
# OpenQuake is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, ... | Replace subprocess.Popen with check_output to avoid git zombies | Replace subprocess.Popen with check_output to avoid git zombies
| Python | agpl-3.0 | larsbutler/oq-hazardlib,larsbutler/oq-hazardlib,gem/oq-engine,gem/oq-hazardlib,mmpagani/oq-hazardlib,gem/oq-engine,gem/oq-engine,mmpagani/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-engine,larsbutler/oq-hazardlib,silviacanessa/oq-hazardlib,silviacanessa/oq-hazardlib,gem/oq-hazardlib,gem/oq-engine,vup1120/oq-hazardli... |
da51cd8b14231a3fa9850d0d1b939168ae7b0534 | sites/shared_conf.py | sites/shared_conf.py | from datetime import datetime
import os
import sys
import alabaster
# Alabaster theme
html_theme_path = [alabaster.get_path()]
# Paths relative to invoking conf.py - not this shared file
html_static_path = ['../_shared_static']
html_theme = 'alabaster'
html_theme_options = {
'description': "A Python implementati... | from datetime import datetime
import os
import sys
import alabaster
# Alabaster theme
html_theme_path = [alabaster.get_path()]
# Paths relative to invoking conf.py - not this shared file
html_static_path = ['../_shared_static']
html_theme = 'alabaster'
html_theme_options = {
'description': "A Python implementati... | Update to new alabaster-driven nav sidebar | Update to new alabaster-driven nav sidebar
| Python | lgpl-2.1 | jorik041/paramiko,anadigi/paramiko,toby82/paramiko,zarr12steven/paramiko,mirrorcoder/paramiko,paramiko/paramiko,varunarya10/paramiko,redixin/paramiko,zpzgone/paramiko,davidbistolas/paramiko,mhdaimi/paramiko,torkil/paramiko,digitalquacks/paramiko,fvicente/paramiko,dlitz/paramiko,thisch/paramiko,jaraco/paramiko,dorianpul... |
6c645b69b91b6a29d4e8786c07e6438d16667415 | emds/formats/exceptions.py | emds/formats/exceptions.py | """
Various parser-related exceptions.
"""
class ParseError(Exception):
"""
Raise this when some unrecoverable error happens while parsing serialized
market data.
"""
pass
| """
Various parser-related exceptions.
"""
from emds.exceptions import EMDSError
class ParseError(EMDSError):
"""
Raise this when some unrecoverable error happens while parsing serialized
market data.
"""
pass
| Make ParseError a child of EMDSError. | Make ParseError a child of EMDSError.
| Python | mit | gtaylor/EVE-Market-Data-Structures |
955fd5b8525e7edd6477d5f74d7cbe7b743a127c | wind_model.py | wind_model.py | #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 08:44:50 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import I... | #!/usr/bin/env python
"""
Reduced Gravity Shallow Water Model
based Matlab code by: Francois Primeau UC Irvine 2011
Kelsey Jordahl
kjordahl@enthought.com
Time-stamp: <Tue Apr 10 10:42:40 EDT 2012>
"""
from scipy.io.netcdf import netcdf_file
from ocean_model import ShallowWaterModel, OceanPlot
from traits.api import I... | Set depth for Lake Superior | Set depth for Lake Superior
| Python | bsd-3-clause | kjordahl/swm |
181da4be123dd63135592580f8fb567d5586d24b | apps/accounts/models.py | apps/accounts/models.py | from apps.teilar.models import Departments
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_le... | from apps.teilar.models import Departments
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.ForeignKey(User, unique = True)
dionysos_username = models.CharField(max_length = 15, unique = True)
dionysos_password = models.CharField(max_le... | Add deprecated field in students | Add deprecated field in students
| Python | agpl-3.0 | LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr |
c94f7e5f2c838c3fdd007229175da680de256b04 | tests/configurations/nginx/tests_file_size_limit.py | tests/configurations/nginx/tests_file_size_limit.py | #! coding: utf-8
import subprocess
import nose.tools as nt
from tests import TestPortalAndino
class TestFileSizeLimit(TestPortalAndino.TestPortalAndino):
@classmethod
def setUpClass(cls):
super(TestFileSizeLimit, cls).setUpClass()
def test_nginx_configuration_uses_1024_MB_as_file_size_limit(sel... | #! coding: utf-8
import subprocess
import nose.tools as nt
from tests import TestPortalAndino
class TestFileSizeLimit(TestPortalAndino.TestPortalAndino):
@classmethod
def setUpClass(cls):
super(TestFileSizeLimit, cls).setUpClass()
def test_nginx_configuration_uses_1024_MB_as_file_size_limit(sel... | Revert "Hago un strip del output de subprocess" | Revert "Hago un strip del output de subprocess"
This reverts commit f5f21d78d87be641617a7cb920d0869975175e58.
| Python | mit | datosgobar/portal-andino,datosgobar/portal-andino |
1a271575d92a6d7df1bc7dedf346b29a778f2261 | update.py | update.py | """DJRivals database updater."""
from random import shuffle
from time import localtime, sleep, strftime, time
import pop
import dj
import image
import html
def continuous():
"""continuous() -> None
Continuous incremental updates of the DJRivals database.
"""
while(True):
print("Beginning ne... | """DJRivals database updater."""
from collections import OrderedDict
from time import localtime, sleep, strftime, time
import json
from common import _link
import pop
import dj
import image
import html
def continuous():
"""continuous() -> None
Continuous incremental updates of the DJRivals database.
""... | Sort the disc list by timestamp. | Sort the disc list by timestamp.
| Python | bsd-2-clause | chingc/DJRivals,chingc/DJRivals |
b2b1c2b8543cae37990262b2a811a9b0f26327da | arm/utils/locker.py | arm/utils/locker.py | # -*- coding: utf-8 -*-
from kvs import CacheKvs
class Locker(object):
"""
locker for move the locker
"""
LOCKER_KEY = 'locker'
EXPIRES = 5 # 5 sec
def __init__(self, key=None):
self.key = self.LOCKER_KEY
if key:
self.key += '.{}'.format(key)
self.locker ... | # -*- coding: utf-8 -*-
from kvs import CacheKvs
class Locker(object):
"""
locker for move the locker
"""
LOCKER_KEY = 'locker'
EXPIRES = 5 # 5 sec
def __init__(self, key=None):
self.key = self.LOCKER_KEY
if key:
self.key += '.{}'.format(key)
self.locker ... | Fix redis lock, use SETNX | Fix redis lock, use SETNX
| Python | mit | mapler/tuesday,mapler/tuesday,mapler/tuesday |
34ea2629aa8a97580567535a5a6885b06cce3419 | examples/test_client.py | examples/test_client.py | import asyncio
import platform
import time
from zeep import AsyncClient
from zeep.cache import InMemoryCache
from zeep.transports import AsyncTransport
# Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client
# Allow CTRL+C on windows console w/ asyncio
if platform.system() == "Wi... | import asyncio
import platform
import time
from zeep import AsyncClient
from zeep.cache import InMemoryCache
from zeep.transports import AsyncTransport
# Spyne SOAP client using Zeep and async transport. Run with python -m examples.test_client
# Allow CTRL+C on windows console w/ asyncio
if platform.system() == "Wi... | Use asyncio.run() to run the test client. | Use asyncio.run() to run the test client.
This makes for cleaner code.
| Python | lgpl-2.1 | katajakasa/aiohttp-spyne |
07488d90549db4a47898bdea4ebd8687de638590 | forum/models.py | forum/models.py | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length... | from django.db import models
import django.contrib.auth.models as auth
class User(auth.User):
"""Model for representing users.
It has few fields that aren't in the standard authentication user
table, and are needed for the forum to work, like footers.
"""
display_name = models.CharField(max_length... | Add footers the comment discusses. | Add footers the comment discusses.
| Python | mit | xfix/NextBoard |
22b92437c1ae672297bed8567b335ef7da100103 | dotfiles/utils.py | dotfiles/utils.py | """
Misc utility functions.
"""
import os.path
from dotfiles.compat import islink, realpath
def compare_path(path1, path2):
return (realpath_expanduser(path1) == realpath_expanduser(path2))
def realpath_expanduser(path):
return realpath(os.path.expanduser(path))
def is_link_to(path, target):
def nor... | """
Misc utility functions.
"""
import os.path
from dotfiles.compat import islink, realpath
def compare_path(path1, path2):
return (realpath_expanduser(path1) == realpath_expanduser(path2))
def realpath_expanduser(path):
return realpath(os.path.expanduser(path))
def is_link_to(path, target):
def nor... | Fix link detection when target is itself a symlink | Fix link detection when target is itself a symlink
This shows up on OSX where /tmp is actually a symlink to /private/tmp.
| Python | isc | aparente/Dotfiles,nilehmann/dotfiles-1,aparente/Dotfiles,aparente/Dotfiles,aparente/Dotfiles,Bklyn/dotfiles |
1fa7237f47096bc9574ffdf649e6231bf2a670e9 | features/stadt/views.py | features/stadt/views.py | import django
import utils
from features import gestalten, groups
class Entity(django.views.generic.View):
def get(self, request, *args, **kwargs):
try:
entity = groups.models.Group.objects.get(slug=kwargs.get('entity_slug'))
view = groups.views.Group()
except groups.model... | import django
import core
import utils
from features import gestalten, groups
class Entity(core.views.PermissionMixin, django.views.generic.View):
def get(self, request, *args, **kwargs):
return self.view.get(request, *args, **kwargs)
def get_view(self):
entity_slug = self.kwargs.get('entity... | Fix permission checking for entity proxy view | Fix permission checking for entity proxy view
| Python | agpl-3.0 | stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten,stadtgestalten/stadtgestalten |
7ffdd38b500b38d6bd48ca7f1bf88fb92c88e1d5 | prime-factors/prime_factors.py | prime-factors/prime_factors.py | def prime_factors(n):
factors = []
factor = 2
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 1
return factors
| def prime_factors(n):
factors = []
while n % 2 == 0:
factors += [2]
n //= 2
factor = 3
while n != 1:
while n % factor == 0:
factors += [factor]
n //= factor
factor += 2
return factors
| Make solution more efficient by only testing odd numbers | Make solution more efficient by only testing odd numbers
| Python | agpl-3.0 | CubicComet/exercism-python-solutions |
6b7fe344827ddf49c40d165d6e0ff09013ee5716 | edxval/migrations/0002_data__default_profiles.py | edxval/migrations/0002_data__default_profiles.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
DEFAULT_PROFILES = [
"desktop_mp4",
"desktop_webm",
"mobile_high",
"mobile_low",
"youtube",
]
def create_default_profiles(apps, schema_editor):
""" Add default profiles """
Profile =... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
DEFAULT_PROFILES = [
"desktop_mp4",
"desktop_webm",
"mobile_high",
"mobile_low",
"youtube",
]
def create_default_profiles(apps, schema_editor):
""" Add default profiles """
Profile =... | Remove uses of using() from migrations | Remove uses of using() from migrations
This hardcoded the db_alias fetched from schema_editor and forces django
to try and migrate any second database you use, rather than routing to
the default database. In testing a build from scratch, these do not
appear needed.
Using using() prevents us from using multiple datab... | Python | agpl-3.0 | edx/edx-val |
78031ca1077a224d37c4f549cd8dac55edd4ed5f | fragdenstaat_de/urls.py | fragdenstaat_de/urls.py | from django.conf.urls.defaults import patterns
urlpatterns = patterns('fragdenstaat_de.views',
(r'^presse/(?P<slug>[-\w]+)/$', 'show_press', {}, 'fds-show_press'),
)
| from django.conf.urls import patterns, url
from django.http import HttpResponseRedirect
urlpatterns = patterns('fragdenstaat_de.views',
(r'^presse/(?P<slug>[-\w]+)/$', 'show_press', {}, 'fds-show_press'),
url(r'^nordrhein-westfalen/', lambda request: HttpResponseRedirect('/nrw/'),
name="jurisdiction-n... | Add custom NRW redirect url | Add custom NRW redirect url | Python | mit | okfse/fragastaten_se,catcosmo/fragdenstaat_de,okfse/fragdenstaat_de,okfse/fragastaten_se,catcosmo/fragdenstaat_de,okfse/fragdenstaat_de |
185571932f518760bb3045347578caa98ef820f5 | froide/foiidea/views.py | froide/foiidea/views.py | from django.shortcuts import render
from foiidea.models import Article
def index(request):
return render(request, 'foiidea/index.html', {
'object_list': Article.objects.all().select_related('public_bodies', 'foirequests')
})
| from django.shortcuts import render
from foiidea.models import Article
def index(request):
return render(request, 'foiidea/index.html', {
'object_list': Article.objects.get_ordered()
})
| Use manager method for view articles | Use manager method for view articles | Python | mit | fin/froide,LilithWittmann/froide,stefanw/froide,CodeforHawaii/froide,CodeforHawaii/froide,ryankanno/froide,LilithWittmann/froide,stefanw/froide,okfse/froide,okfse/froide,ryankanno/froide,ryankanno/froide,ryankanno/froide,LilithWittmann/froide,stefanw/froide,fin/froide,CodeforHawaii/froide,catcosmo/froide,CodeforHawaii/... |
52e15ab96718a491f805eee6f7130d4f02530940 | alfred/helpers.py | alfred/helpers.py | from alfred_db.models import User
from flask import current_app
from github import Github
from requests_oauth2 import OAuth2
from .database import db
def get_shell():
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
except ImportError:
import code
return lambda *... | from alfred_db.models import User
from flask import current_app
from github import Github
from requests_oauth2 import OAuth2
from .database import db
def get_shell():
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
except ImportError:
import code
return lambda *... | Add user to db.session only when it has been created | Add user to db.session only when it has been created
| Python | isc | alfredhq/alfred,alfredhq/alfred |
81e8fb8dd4f9f3d3648e13e8509208710619c615 | IMU_program/PythonServer.py | IMU_program/PythonServer.py | import socket
import serial.tools.list_ports
import serial
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
# print("Connecting on " + arduino_port[0])
PORT = 4242
HOST = 'localhost'
... | #!/usr/bin/env python3
import socket
import serial.tools.list_ports
import serial
ports = list(serial.tools.list_ports.comports())
arduino_port = next((port for port in ports if "Arduino" in port.description), None)
arduino = serial.Serial(arduino_port[0], 9600)
# print("Connecting on " + arduino_port[0])
PORT = 4... | Add shebang to python server | Add shebang to python server
| Python | apache-2.0 | dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo |
3fa9a7c62aeae10a191b3782e32df107618c19b3 | boris/reporting/forms.py | boris/reporting/forms.py | '''
Created on 3.12.2011
@author: xaralis
'''
from django import forms
from django.utils.translation import ugettext_lazy as _
from boris.utils.widgets import SelectYearWidget
class MonthlyStatsForm(forms.Form):
year = forms.IntegerField(widget=SelectYearWidget(history=10), label=_(u'Rok'))
class ServiceForm(fo... | '''
Created on 3.12.2011
@author: xaralis
'''
from django import forms
from django.utils.translation import ugettext_lazy as _
from boris.utils.widgets import SelectYearWidget
class MonthlyStatsForm(forms.Form):
year = forms.IntegerField(widget=SelectYearWidget(history=10), label=_(u'Rok'))
class ServiceForm(fo... | Make dates in the ServiceForm optional. | Make dates in the ServiceForm optional.
| Python | mit | fragaria/BorIS,fragaria/BorIS,fragaria/BorIS |
70a004f1455448aca08754084502d4d13b9cc9cd | indra/tests/test_rlimsp.py | indra/tests/test_rlimsp.py | from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_pmc('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations, "Missing a... | from indra.sources import rlimsp
def test_simple_usage():
rp = rlimsp.process_from_webservice('PMC3717945')
stmts = rp.statements
assert len(stmts) == 6, len(stmts)
for s in stmts:
assert len(s.evidence) == 1, "Wrong amount of evidence."
ev = s.evidence[0]
assert ev.annotations... | Add a test for pmids and update to new api. | Add a test for pmids and update to new api.
| Python | bsd-2-clause | johnbachman/indra,bgyori/indra,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,johnbachman/indra,johnbachman/indra,pvtodorov/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,bgyori/indra,sorgerlab/indra |
4a6fe04a93e0d500b9e2fa7ed9951bcb497045df | sphinxcontrib/dd/__init__.py | sphinxcontrib/dd/__init__.py | from docutils.nodes import SkipNode
from . import data_dictionary
from . import database_diagram
def skip(self, node):
_ = self
_ = node
raise SkipNode
def setup(app):
app.setup_extension('sphinx.ext.graphviz')
app.add_directive('data-dictionary', data_dictionary.Directive)
app.add_config... | from docutils.nodes import SkipNode
from . import data_dictionary
from . import database_diagram
def skip(self, node):
_ = self
_ = node
raise SkipNode
def setup(app):
app.setup_extension('sphinx.ext.graphviz')
app.add_directive('data-dictionary', data_dictionary.Directive)
for option in ... | Replace dash to underscore for config | Replace dash to underscore for config
| Python | mit | julot/sphinxcontrib-dd |
9201e9c433930da8fd0bfb13eadbc249469e4d84 | fireplace/cards/tourney/mage.py | fireplace/cards/tourney/mage.py | from ..utils import *
##
# Secrets
# Effigy
class AT_002:
events = Death(FRIENDLY + MINION).on(
lambda self, minion: Summon(self.controller, RandomMinion(cost=minion.cost))
)
| from ..utils import *
##
# Minions
# Dalaran Aspirant
class AT_006:
inspire = Buff(SELF, "AT_006e")
# Spellslinger
class AT_007:
play = Give(ALL_PLAYERS, RandomSpell())
# Rhonin
class AT_009:
deathrattle = Give(CONTROLLER, "EX1_277") * 3
##
# Spells
# Flame Lance
class AT_001:
play = Hit(TARGET, 8)
# Ar... | Implement Mage cards for The Grand Tournament | Implement Mage cards for The Grand Tournament
| Python | agpl-3.0 | Meerkov/fireplace,amw2104/fireplace,liujimj/fireplace,Ragowit/fireplace,smallnamespace/fireplace,jleclanche/fireplace,Ragowit/fireplace,oftc-ftw/fireplace,beheh/fireplace,smallnamespace/fireplace,NightKev/fireplace,liujimj/fireplace,Meerkov/fireplace,amw2104/fireplace,oftc-ftw/fireplace |
2145ee5961cc35d36013e2333c636c7390b6c039 | gooey/gui/util/taskkill.py | gooey/gui/util/taskkill.py | import sys
import os
import signal
if sys.platform.startswith("win"):
def taskkill(pid):
os.system('taskkill /F /PID {:d} /T >NUL 2>NUL'.format(pid))
else: # POSIX
def taskkill(pid):
os.kill(pid, signal.SIGTERM)
| import sys
import os
import signal
if sys.platform.startswith("win"):
def taskkill(pid):
os.system('taskkill /F /PID {:d} /T >NUL 2>NUL'.format(pid))
else: # POSIX
import psutil
def taskkill(pid):
parent = psutil.Process(pid)
for child in parent.children(recursive=True):
child.kill()
pare... | Kill child processes as well as shell process | Kill child processes as well as shell process
| Python | mit | jschultz/Gooey,partrita/Gooey,chriskiehl/Gooey,codingsnippets/Gooey |
229ea6b0f373aa2d37c40f794c4c17bfff231e01 | mox3/fixture.py | mox3/fixture.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://... | # Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | Remove vim header from source files | Remove vim header from source files
Change-Id: I67a1ee4e894841bee620b1012257ad72f5e31765
| Python | apache-2.0 | openstack/mox3 |
788ac45c702109036a4ebd0868919d5b42c040ef | this_app/forms.py | this_app/forms.py | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="... | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.validators import DataRequired, Length, Email
class SignupForm(FlaskForm):
"""Render and validate the signup form"""
email = StringField("Email", validators=[DataRequired(), Email(message="... | Rename form BucketlistItem to Activity | Rename form BucketlistItem to Activity
| Python | mit | borenho/flask-bucketlist,borenho/flask-bucketlist |
dddef6b793bc7c45d1f70f133a608d017ad4b341 | tests/manage_tests.py | tests/manage_tests.py | import os
import unittest
from application.default_settings import _basedir
from application import app, db
class ManagerTestCase(unittest.TestCase):
""" setup and teardown for the testing database """
def setUp(self):
create_db_dir = _basedir + '/db'
if not os.path.exists(create_db_dir):
... | import os
import unittest
from application.default_settings import _basedir
from application import app, db
class ManagerTestCase(unittest.TestCase):
""" setup and teardown for the testing database """
def setUp(self):
create_db_dir = _basedir + '/db'
if not os.path.exists(create_db_dir):
... | Fix tests for new index. | Fix tests for new index.
| Python | bsd-3-clause | san-bil/astan,san-bil/astan,fert89/prueba-3-heroku-flask,albertogg/flask-bootstrap-skel,Agreste/MobUrbRoteiro,fert89/prueba-3-heroku-flask,san-bil/astan,scwu/stress-relief,san-bil/astan,scwu/stress-relief,Agreste/MobUrbRoteiro,Agreste/MobUrbRoteiro,akhilaryan/clickcounter |
c32eb5f0a09f0a43172ed257ce21ab9545b6e03e | lazy_helpers.py | lazy_helpers.py | # Lazy objects, for the serializer to find them we put them here
class LazyDriver(object):
_driver = None
@classmethod
def get(cls):
import os
if cls._driver is None:
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
disp... | # Lazy objects, for the serializer to find them we put them here
class LazyDriver(object):
_driver = None
@classmethod
def get(cls):
import os
if cls._driver is None:
from pyvirtualdisplay import Display
cls._display = display
display = Display(visible=0... | Update lazy helper to support the idea of a reset on bad state. | Update lazy helper to support the idea of a reset on bad state.
| Python | apache-2.0 | holdenk/diversity-analytics,holdenk/diversity-analytics |
2f4ed65bcddf9494134f279046fde75b0772b07d | utils/database.py | utils/database.py | import ConfigParser
import os
import yaml
class Database(object):
""" Generic class for handling database-related tasks. """
def select_config_for_environment(self):
""" Read the value of env variable and load the property
database configuration based on the value of DB_ENV.
Takes no ... | import ConfigParser
import os
import yaml
class Database(object):
""" Generic class for handling database-related tasks. """
def select_config_for_environment(self):
""" Read the value of env variable and load the property
database configuration based on the value of DB_ENV.
Takes no ... | Fix mistake in path in warning when config file is missing | Fix mistake in path in warning when config file is missing
| Python | apache-2.0 | ProjectFlorida/outrider |
5dacd62d8d27f6d0d94313ec1bd39857ee314d2f | scrubadub/filth/named_entity.py | scrubadub/filth/named_entity.py | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | Change replacement string of named entity filth | Change replacement string of named entity filth
| Python | mit | deanmalmgren/scrubadub,datascopeanalytics/scrubadub,deanmalmgren/scrubadub,datascopeanalytics/scrubadub |
0e34fce69b01ab9b8f3ec00be633bc2581df26d5 | bibliopixel/animation/mixer.py | bibliopixel/animation/mixer.py | import copy
from . import parallel
from .. util import color_list
class Mixer(parallel.Parallel):
def __init__(self, *args, levels=None, master=1, **kwds):
self.master = master
super().__init__(*args, **kwds)
self.mixer = color_list.Mixer(
self.color_list,
[a.color... | import copy
from . import parallel
from .. util import color_list
class Mixer(parallel.Parallel):
def __init__(self, *args, levels=None, master=1, **kwds):
self.master = master
super().__init__(*args, **kwds)
self.mixer = color_list.Mixer(
self.color_list,
[a.color... | Handle getting and setting the Mixer levels correctly | Handle getting and setting the Mixer levels correctly
| Python | mit | rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel |
a41e07ff20d9dc44288a57f76a83e86b4944049a | nlppln/commands/frog_to_saf.py | nlppln/commands/frog_to_saf.py | #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Path())
def frog2saf(input_files, output_dir):
if n... | #!/usr/bin/env python
import click
import os
import codecs
import json
from xtas.tasks._frog import parse_frog, frog_to_saf
from nlppln.utils import create_dirs, out_file_name
@click.command()
@click.argument('input_files', nargs=-1, type=click.Path(exists=True))
@click.argument('output_dir', nargs=1, type=click.Pa... | Update command to use nlppln utils | Update command to use nlppln utils
- fixes the double extension of output files
| Python | apache-2.0 | WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln,WhatWorksWhenForWhom/nlppln |
5b66a57257807adf527fcb1de4c750013e532f25 | newsletter/utils.py | newsletter/utils.py | import logging
logger = logging.getLogger(__name__)
import random
from django.utils.hashcompat import sha_constructor
from django.contrib.sites.models import Site
from datetime import datetime
# Conditional import of 'now'
# Django 1.4 should use timezone.now, Django 1.3 datetime.now
try:
from django.utils.time... | import logging
logger = logging.getLogger(__name__)
import random
try:
from hashlib import sha1
except ImportError:
from django.utils.hashcompat import sha_constructor as sha1
from django.contrib.sites.models import Site
from datetime import datetime
# Conditional import of 'now'
# Django 1.4 should us... | Fix deprecation warnings with Django 1.5 | Fix deprecation warnings with Django 1.5
django/utils/hashcompat.py:9:
DeprecationWarning: django.utils.hashcompat is deprecated; use hashlib instead | Python | agpl-3.0 | dsanders11/django-newsletter,dsanders11/django-newsletter,ctxis/django-newsletter,ctxis/django-newsletter,viaregio/django-newsletter,dsanders11/django-newsletter,ctxis/django-newsletter,viaregio/django-newsletter |
45f30b4b1da110e79787b85c054796a671718910 | tests/__main__.py | tests/__main__.py |
import unittest
import os.path
if __name__ == '__main__':
HERE = os.path.dirname(__file__)
loader = unittest.loader.TestLoader()
suite = loader.discover(HERE)
result = unittest.result.TestResult()
suite.run(result)
print('Ran {} tests.'.format(result.testsRun))
print('{} errors, {} fail... |
import unittest
import os.path
if __name__ == '__main__':
HERE = os.path.dirname(__file__)
loader = unittest.loader.TestLoader()
suite = loader.discover(HERE)
result = unittest.result.TestResult()
suite.run(result)
print('Ran {} tests.'.format(result.testsRun))
print('{} errors, {} fail... | Print failures and errors in test run | Print failures and errors in test run
| Python | mit | funkybob/antfarm |
f2af046da299686515e4eaf2d9ae58a62108cc21 | games/urls/installers.py | games/urls/installers.py | # pylint: disable=C0103
from __future__ import absolute_import
from django.conf.urls import url
from games.views import installers as views
urlpatterns = [
url(r'revisions/(?P<pk>[\d]+)$',
views.InstallerRevisionDetailView.as_view(),
name="api_installer_revision_detail"),
url(r'(?P<pk>[\d]+)/r... | # pylint: disable=C0103
from __future__ import absolute_import
from django.conf.urls import url
from games.views import installers as views
urlpatterns = [
url(r'game/(?P<slug>[\w\-]+)$',
views.GameInstallerList.as_view(),
name='api_game_installer_list'),
url(r'game/(?P<slug>[\w\-]+)/revisions... | Fix order for installer API routes | Fix order for installer API routes
| Python | agpl-3.0 | lutris/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website |
3f1aeba98cd4bc2f326f9c18c34e66c396be99cf | scikits/statsmodels/tools/tests/test_data.py | scikits/statsmodels/tools/tests/test_data.py | import pandas
import numpy as np
from scikits.statsmodels.tools import data
def test_missing_data_pandas():
"""
Fixes GH: #144
"""
X = np.random.random((10,5))
X[1,2] = np.nan
df = pandas.DataFrame(X)
vals, cnames, rnames = data.interpret_data(df)
np.testing.assert_equal(rnames, [0,2,3... | import pandas
import numpy as np
from scikits.statsmodels.tools import data
def test_missing_data_pandas():
"""
Fixes GH: #144
"""
X = np.random.random((10,5))
X[1,2] = np.nan
df = pandas.DataFrame(X)
vals, cnames, rnames = data.interpret_data(df)
np.testing.assert_equal(rnames, [0,2,3... | Add some tests for unused function | TST: Add some tests for unused function
| Python | bsd-3-clause | Averroes/statsmodels,saketkc/statsmodels,wwf5067/statsmodels,phobson/statsmodels,musically-ut/statsmodels,hlin117/statsmodels,cbmoore/statsmodels,ChadFulton/statsmodels,pprett/statsmodels,statsmodels/statsmodels,gef756/statsmodels,rgommers/statsmodels,alekz112/statsmodels,jstoxrocky/statsmodels,kiyoto/statsmodels,music... |
98dd2759a184ba1066e8fd49cd09ff4194d2da0f | docweb/tests/__init__.py | docweb/tests/__init__.py | import os, sys
from django.conf import settings
# -- Setup Django configuration appropriately
TESTDIR = os.path.abspath(os.path.dirname(__file__))
settings.MODULE_DIR = TESTDIR
settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh')
# The CSRF middleware prevents the Django test client from working, so
# disabl... | import os, sys
from django.conf import settings
# -- Setup Django configuration appropriately
TESTDIR = os.path.abspath(os.path.dirname(__file__))
settings.MODULE_DIR = TESTDIR
settings.PULL_SCRIPT = os.path.join(TESTDIR, 'pull-test.sh')
settings.SITE_ID = 1
# The CSRF middleware prevents the Django test client from... | Set SITE_ID=1 in tests (corresponds to that in the test fixtures) | Set SITE_ID=1 in tests (corresponds to that in the test fixtures) | Python | bsd-3-clause | pv/pydocweb,pv/pydocweb |
85748e4b18dffca6436c5439a3e40ac773611c37 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon Surrell
# Copyright (c) 2013 Jon Surrell
#
# License: MIT
#
"""This module exports the Ghc plugin class."""
from SublimeLinter.lint import Linter, util
class Ghc(Linter):
"""Provides an interface to ghc."... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon Surrell
# Copyright (c) 2013 Jon Surrell
#
# License: MIT
#
"""This module exports the Ghc plugin class."""
from SublimeLinter.lint import Linter, util
class Ghc(Linter):
"""Provides an interface to ghc."... | Remove todo comment, no settings support | Remove todo comment, no settings support
| Python | mit | alexbiehl/SublimeLinter-stack-ghc,SublimeLinter/SublimeLinter-ghc |
23d8664a80a51c489615db6dbcde8a7e76265f15 | warehouse/defaults.py | warehouse/defaults.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///warehouse"
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.... | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
# The base domain name for this installation. Used to control linking to
# sub-domains.
SERVER_NAME = "warehouse.local"
# The URI for our PostgreSQL database.
SQLALCHEMY_DATABASE_URI = "postgres:///ware... | Move the SERVER_NAME to the start of the default config | Move the SERVER_NAME to the start of the default config
Minor nit but the SERVER_NAME is one of the more important settings
on a per app basis.
| Python | bsd-2-clause | davidfischer/warehouse |
71ec798d6a85a2aa0e4b80e6095d4da67612db70 | apps/article/serializers.py | apps/article/serializers.py | from rest_framework import serializers
from apps.article.models import Article, Tag
from apps.authentication.serializers import UserSerializer
class ArticleSerializer(serializers.ModelSerializer):
author = UserSerializer(source='created_by') # serializers.StringRelatedField(source='created_by')
absolute_url... | from rest_framework import serializers
from apps.article.models import Article, Tag
from apps.authentication.serializers import UserSerializer
class ArticleSerializer(serializers.ModelSerializer):
author = UserSerializer(source='created_by')
absolute_url = serializers.CharField(source='get_absolute_url', rea... | Clean up article serializer a bit | Clean up article serializer a bit
| Python | mit | dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4,dotKom/onlineweb4 |
3fca658f3db21a0b3b8de626e6a7faf07da6ddab | restalchemy/dm/models.py | restalchemy/dm/models.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2014 Eugene Frolov <eugene@frolov.net.ru>
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# ... | Add equal method to model with uuid | Add equal method to model with uuid
Change-Id: Iefa05d50f2f591399d5423debd699f88074a574e
| Python | apache-2.0 | phantomii/restalchemy |
2f34954716c3164b6fd65e997a6d0b02a4be6a03 | pyblox/api/http.py | pyblox/api/http.py | #
# http.py
# pyblox
#
# By Sanjay-B(Sanjay Bhadra)
# Copyright © 2017 Sanjay-B(Sanjay Bhadra). All rights reserved.
#
import json
import requests
class Http:
def sendRequest(url):
payload = requests.get(str(url))
statusCode = payload.status_code
header = payload.headers
content = paylo... | #
# http.py
# pyblox
#
# By Sanjay-B(Sanjay Bhadra)
# Copyright © 2017 Sanjay-B(Sanjay Bhadra). All rights reserved.
#
import json
import requests
class Http:
def sendRequest(url):
payload = requests.get(str(url))
statusCode = payload.status_code
header = payload.headers
content = paylo... | Check this commits description for more information | [Http] Check this commits description for more information
- sendRequest() and postRequest now have better error handling and display the error via console
- No longer toggles error on 403, instead it toggles everything but 200 | Python | mit | Sanjay-B/Pyblox |
2958e793ea30d879afe265bb511183e4512fc049 | webstr/core/config.py | webstr/core/config.py | """
Central configuration module of webstr selenium tests.
This module provides configuration options along with default values and
function to redefine values.
"""
# Copyright 2016 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | """
Central configuration module of webstr selenium tests.
This module provides configuration options along with default values and
function to redefine values.
"""
# Copyright 2016 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... | Change the default value for SELENIUM_SERVER | Change the default value for SELENIUM_SERVER
with this change it is possible to use webstr on localhost without any action
Change-Id: Ife533552d7a746401df01c03af0b2d1caf0702b5
Signed-off-by: ltrilety <b0b91364d2d251c1396ffbe2df56e3ab774d4d4b@redhat.com>
| Python | apache-2.0 | Webstr-framework/webstr |
d6d15743f6bac48a051798df0638190e1241ffb1 | parliament/politicians/twit.py | parliament/politicians/twit.py | import email
import datetime
import re
from django.conf import settings
import twitter
from parliament.core.models import Politician, PoliticianInfo
from parliament.activity import utils as activity
def save_tweets():
twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(s... | import email
import datetime
import re
from django.conf import settings
import twitter
from parliament.core.models import Politician, PoliticianInfo
from parliament.activity import utils as activity
def save_tweets():
twitter_to_pol = dict([(i.value.lower(), i.politician) for i in PoliticianInfo.objects.filter(s... | Change the base URL for the Twitter API | Change the base URL for the Twitter API
| Python | agpl-3.0 | rhymeswithcycle/openparliament,litui/openparliament,rhymeswithcycle/openparliament,litui/openparliament,twhyte/openparliament,rhymeswithcycle/openparliament,twhyte/openparliament,litui/openparliament,twhyte/openparliament |
add6013c8484e56545ed2f11c8c6e042c1384429 | swf/exceptions.py | swf/exceptions.py | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class PollTimeout(Exception):
pass
class InvalidCredentialsError(Exception):
pass
class ResponseError(Exception):
pass
class DoesNotExistError(Exception):
... | # -*- coding: utf-8 -*-
# Copyright (c) 2013, Theo Crevon
# Copyright (c) 2013, Greg Leclercq
#
# See the file LICENSE for copying permission.
class SWFError(Exception):
def __init__(self, message, raw_error, *args):
Exception.__init__(self, message, *args)
self.kind, self.details = raw_error.spli... | Enhance swf errors wrapping via an exception helper | Enhance swf errors wrapping via an exception helper
| Python | mit | botify-labs/python-simple-workflow,botify-labs/python-simple-workflow |
5f6fb9dc79982331a36debdeb33212357def2b11 | bayohwoolph.py | bayohwoolph.py | #!/usr/bin/python3
import asyncio
import configparser
import discord
import os
import logging
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','b... | #!/usr/bin/python3
import asyncio
import configparser
import discord
import os
import logging
from discord.ext import commands
logging.basicConfig(level=logging.INFO)
# Parse the config and stick in global "config" var
config = configparser.ConfigParser()
for inifile in [os.path.expanduser('~')+'/.bayohwoolph.ini','b... | Make bot respond to mentions. | Make bot respond to mentions.
| Python | agpl-3.0 | dark-echo/Bay-Oh-Woolph,freiheit/Bay-Oh-Woolph |
01ca6c2c71b8558e119ae4448e02c2c84a5ef6f9 | mailviews/tests/urls.py | mailviews/tests/urls.py | from mailviews.utils import is_django_version_greater
from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
| from django.conf.urls import include, url
from mailviews.previews import autodiscover, site
autodiscover()
urlpatterns = [
url(regex=r'', view=site.urls)
]
| Remove unused import on test url's | Remove unused import on test url's
| Python | apache-2.0 | disqus/django-mailviews,disqus/django-mailviews |
6d48f5fb6be6045d89948729c6e28ed1f1a305ab | pywal/reload.py | pywal/reload.py | """
Reload programs.
"""
import shutil
import subprocess
from pywal.settings import CACHE_DIR
from pywal import util
def reload_i3():
"""Reload i3 colors."""
if shutil.which("i3-msg"):
util.disown("i3-msg", "reload")
def reload_xrdb():
"""Merge the colors into the X db so new terminals use them... | """
Reload programs.
"""
import shutil
import subprocess
from pywal.settings import CACHE_DIR
from pywal import util
def reload_xrdb():
"""Merge the colors into the X db so new terminals use them."""
if shutil.which("xrdb"):
subprocess.call(["xrdb", "-merge", CACHE_DIR / "colors.Xresources"])
def r... | Fix bug with i3 titlebars not being the right color. | colors: Fix bug with i3 titlebars not being the right color.
| Python | mit | dylanaraps/pywal,dylanaraps/pywal,dylanaraps/pywal |
a99150d5c98074bde9218d6feb68f4cb200a0e4c | q_and_a/urls.py | q_and_a/urls.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import a... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.views.generic import TemplateView
# Uncomment the next two lines to enable the admin:
from django.contrib import a... | Use URLs from the prototype app | Use URLs from the prototype app
| Python | bsd-3-clause | DemocracyClub/candidate_questions,DemocracyClub/candidate_questions,DemocracyClub/candidate_questions |
580868c63f61bb7f6576dc7b0029aa137e274a51 | qnd/__init__.py | qnd/__init__.py | """Quick and Distributed TensorFlow command framework"""
from .flag import *
from .run import def_run
| """Quick and Distributed TensorFlow command framework"""
from .flag import *
from .run import def_run
__all__ = ["add_flag", "add_required_flag", "FlagAdder", "def_run"]
| Add __all__ variable to top level package | Add __all__ variable to top level package
| Python | unlicense | raviqqe/tensorflow-qnd,raviqqe/tensorflow-qnd |
697120d4e693bf7fbc192164b5df3dfb30f71a3f | tests/__init__.py | tests/__init__.py | import logging
import unittest
import os
from sqlalchemy import create_engine
from rtrss import config, database
logging.disable(logging.ERROR)
engine = create_engine(config.SQLALCHEMY_DATABASE_URI,
echo=False,
client_encoding='utf8')
# Reconfigure session factory to u... | import logging
import unittest
import os
import shutil
from sqlalchemy import create_engine
from rtrss import config, database
logging.disable(logging.ERROR)
engine = create_engine(config.SQLALCHEMY_DATABASE_URI,
echo=False,
client_encoding='utf8')
# Reconfigure sessio... | Remove test data folder with contents | Remove test data folder with contents
| Python | apache-2.0 | notapresent/rtrss,notapresent/rtrss,notapresent/rtrss,notapresent/rtrss |
2673f1bac21e43a4cad9edb7352f89750d6d0144 | tests/settings.py | tests/settings.py | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | # Case Conductor is a Test Case Management system.
# Copyright (C) 2011-2012 Mozilla
#
# This file is part of Case Conductor.
#
# Case Conductor is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3... | Enforce that tests run with anonymous access off. | Enforce that tests run with anonymous access off.
| Python | bsd-2-clause | mozilla/moztrap,mccarrmb/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,mozilla/moztrap,shinglyu/moztrap,mccarrmb/moztrap,shinglyu/moztrap,shinglyu/moztrap,mccarrmb/moztrap,mozilla/moztrap,bobsilverberg/moztrap,mozilla/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,bobs... |
15c8215415d36da4fac9c7333e62239f7b81c12d | test/support/mock_definitions.py | test/support/mock_definitions.py | # Generates validation/input definitions as if they were created by splunk for tests
class MockDefinitions(object):
def __init__(self, session_key=None):
self.session_key = session_key if session_key is not None else '123456789'
@property
def metadata(self):
host = os.getenv('SPLUNK_API_HOS... | import os
# Generates validation/input definitions as if they were created by splunk for tests
class MockDefinitions(object):
def __init__(self, session_key=None):
self.session_key = session_key if session_key is not None else '123456789'
@property
def metadata(self):
host = os.getenv('SPLU... | Change mock to be env dependant | Change mock to be env dependant
| Python | bsd-2-clause | Cisco-AMP/amp4e_splunk_events_input,Cisco-AMP/amp4e_splunk_events_input,Cisco-AMP/amp4e_splunk_events_input,Cisco-AMP/amp4e_splunk_events_input |
4f2dabc45f22a9ad6350ab33267e4bdf4a00b4ea | tests/testapp/tests/modelview.py | tests/testapp/tests/modelview.py | from django.test import TestCase
from towel import deletion
from testapp.models import Person, EmailAddress
class ModelViewTest(TestCase):
def test_list_view(self):
for i in range(7):
p = Person.objects.create(family_name='Family %r' % i)
# paginate_by=5
self.assertContains(... | from django.test import TestCase
from towel import deletion
from testapp.models import Person, EmailAddress
class ModelViewTest(TestCase):
def test_list_view(self):
for i in range(7):
p = Person.objects.create(family_name='Family %r' % i)
# paginate_by=5
self.assertContains(... | Add tests for adding stuff through the ModelView | Add tests for adding stuff through the ModelView
| Python | bsd-3-clause | matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel |
fa55f976f4a41bfcbf2009e543fd2a0057451c31 | metakernel/magics/plot_magic.py | metakernel/magics/plot_magic.py | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic, option
class PlotMagic(Magic):
@option(
'-s', '--size', action='store',
help='Pixel size of plots, "width,height"'
)
@option(
'-f', '--format', ac... | # Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.
from metakernel import Magic, option
class PlotMagic(Magic):
@option(
'-s', '--size', action='store',
help='Pixel size of plots, "width,height"'
)
@option(
'-f', '--format', ac... | Fix the option and update the note | Fix the option and update the note
| Python | bsd-3-clause | Calysto/metakernel |
630a8683ba748f130bbb70c285d30142e50cd8ba | playlist_kreator/gmusic.py | playlist_kreator/gmusic.py | from gmusicapi import Mobileclient
def create_playlist(playlist_name, artists, email, password, max_top_tracks=2):
api = Mobileclient()
logged_in = api.login(email, password, Mobileclient.FROM_MAC_ADDRESS)
if not logged_in:
raise Exception('Could not connect')
song_ids = []
for artist_n... | from gmusicapi import Mobileclient
def create_playlist(playlist_name, artists, email, password, max_top_tracks=2):
api = Mobileclient()
logged_in = api.login(email, password, Mobileclient.FROM_MAC_ADDRESS)
if not logged_in:
raise Exception('Could not connect')
song_ids = []
for artist_n... | Change logs for google music | Change logs for google music
| Python | mit | epayet/playlist_kreator,epayet/playlist_kreator |
3bcd36a063b112edb657a739287c6a2db3141746 | appolo/models.py | appolo/models.py | from django.db import models
class Locatie(models.Model):
def __unicode__(self):
return self.naam
naam = models.CharField(max_length=200)
lat = models.FloatField()
long = models.FloatField()
class Dag(models.Model):
def __unicode__(self):
return unicode(self.datum)
datum = mode... | from django.db import models
class Locatie(models.Model):
def __unicode__(self):
return self.naam
naam = models.CharField(max_length=200)
lat = models.FloatField()
long = models.FloatField()
class Meta:
verbose_name_plural = 'locaties'
class Dag(models.Model):
def __unicode__(... | Correct meervoud modellen van appolo | Correct meervoud modellen van appolo
| Python | mit | jonge-democraten/zues,jonge-democraten/zues,jonge-democraten/zues |
fe4a72a49b8291f680c31037baa1c8b33e2ed227 | tests/test_carddb.py | tests/test_carddb.py | from hearthstone.enums import CardType, GameTag, Rarity
import utils
CARDS = utils.fireplace.cards.db
def test_all_tags_known():
"""
Iterate through the card database and check that all specified GameTags
are known in hearthstone.enums.GameTag
"""
unknown_tags = set()
known_tags = list(GameTag)
known_rariti... | from hearthstone.enums import CardType, GameTag, Rarity
import utils
CARDS = utils.fireplace.cards.db
def test_all_tags_known():
"""
Iterate through the card database and check that all specified GameTags
are known in hearthstone.enums.GameTag
"""
unknown_tags = set()
known_tags = list(GameTag)
known_rariti... | Add a test for using card docstrings as names | Add a test for using card docstrings as names
| Python | agpl-3.0 | NightKev/fireplace,jleclanche/fireplace,beheh/fireplace |
a8571b066634b7e7cbeb35844e1ee0b0d678112c | tests/test_itunes.py | tests/test_itunes.py | """
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript
from itunes.exceptions import AppleScriptError
class ITunesTests... | """
test_itunes.py
Copyright © 2015 Alex Danoff. All Rights Reserved.
2015-08-02
This file tests the functionality provided by the itunes module.
"""
import unittest
from datetime import datetime
from itunes.itunes import parse_value, run_applescript, play_track
from itunes.exceptions import AppleScriptError, Track... | Add test for `play_track` function | Add test for `play_track` function
New tests make sure that `play_track` raises a TrackError when an
invalid track is requested.
| Python | mit | adanoff/iTunesTUI |
2ab1f7687e2cd3b2814ae4c68f48d76fcea4e42b | tests/test_parser.py | tests/test_parser.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
line = " 0:00 InitGame: \g_matchmode\1\g_gametype\7\g_allowvote\536871039\g_gear\KQ\mapname\ut4_dust2_v2\gamename\q3urt43\g_survivor\0\auth\0\g_modversion\4.3.4"
def test_initgame():
tmp = line.split()
assert tmp[1] == "InitGame:"
def test_mod43():
ret_val... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
line = " 0:00 InitGame: \g_matchmode\1\g_gametype\7\g_allowvote\536871039\g_gear\KQ\mapname\ut4_dust2_v2\gamename\q3urt43\g_survivor\0\auth\0\g_modversion\4.3.4"
def test_initgame():
tmp = line.split()
assert tmp[1] == "InitGame:"
def test_mod43():
ret_val... | Add test to check gear value | Add test to check gear value
| Python | mit | SpunkyBot/spunkybot,SpunkyBot/spunkybot |
9837d14d4c9a1fa85d6dd122ebbdda6a6b559087 | tests/test_travis.py | tests/test_travis.py | import unittest
import permstruct
import permstruct.dag
class TestTravis(unittest.TestCase):
def test_travis(self):
perm_prop = lambda p: p.avoids([2,3,1])
perm_bound = 6
inp_dag = permstruct.dag.incr_decr(perm_prop, perm_bound)
sol_iter = permstruct.construct_rule(perm_prop, perm_b... | import unittest
import permstruct
import permstruct.dag
import sys
class TestTravis(unittest.TestCase):
def test_travis(self):
perm_prop = lambda p: p.avoids([2,3,1])
perm_bound = 6
inp_dag = permstruct.dag.incr_decr(perm_prop, perm_bound)
sol_iter = permstruct.construct_rule(perm_p... | Make tests working with python 2 and 3 | Make tests working with python 2 and 3
| Python | bsd-3-clause | PermutaTriangle/PermStruct |
267076bba8b28f82da4d714d5ee3babc4d24b8da | voteswap/forms.py | voteswap/forms.py | from django import forms
from polling.models import CANDIDATES
from polling.models import CANDIDATES_THIRD_PARTY
from polling.models import STATES
class LandingPageForm(forms.Form):
state = forms.ChoiceField(choices=STATES)
preferred_candidate = forms.ChoiceField(choices=CANDIDATES)
second_candidate = fo... | from django import forms
from polling.models import CANDIDATES
from polling.models import CANDIDATES_THIRD_PARTY
from polling.models import STATES
class LandingPageForm(forms.Form):
state = forms.ChoiceField(choices=STATES)
preferred_candidate = forms.ChoiceField(choices=CANDIDATES)
second_candidate = fo... | Make second_candidate not required in sign up form | Make second_candidate not required in sign up form
| Python | mit | sbuss/voteswap,sbuss/voteswap,sbuss/voteswap,sbuss/voteswap |
373f0f4637103d526c75cae304740e621ad3c39c | resize.py | resize.py | # -*- coding: utf-8 -*-
import cv2
import sys
import numpy as np
def resize(src, w_ratio, h_ratio):
height = src.shape[0]
width = src.shape[1]
dst = cv2.resize(src,(width/100*w_ratio,height/100*h_ratio))
return dst
if __name__ == '__main__':
param = sys.argv
if (len(param) != 4):
print... | # -*- coding: utf-8 -*-
import cv2
import sys
def resize(src, w_ratio, h_ratio):
height = src.shape[0]
width = src.shape[1]
dst = cv2.resize(src,((int)(width/100*w_ratio),(int)(height/100*h_ratio)))
return dst
if __name__ == '__main__':
param = sys.argv
if (len(param) != 4):
print ("Us... | Fix bug and delete unused library | Fix bug and delete unused library
| Python | mit | karaage0703/python-image-processing,karaage0703/python-image-processing |
1c231a8ef54af82d8ec03b828856ddac619fd345 | knights/compat/django.py | knights/compat/django.py | import ast
from knights.library import Library
register = Library()
@register.tag
def static(parser, token):
src = parser.parse_expression(token)
return ast.Yield(value=ast.BinOp(
left=ast.Str(s='/static/%s'),
op=ast.Mod(),
right=src,
))
@register.tag(name='include')
def do_inc... | import ast
from knights.library import Library
register = Library()
@register.tag
def static(parser, token):
src = parser.parse_expression(token)
return ast.Yield(value=ast.BinOp(
left=ast.Str(s='/static/%s'),
op=ast.Mod(),
right=src,
))
@register.tag(name='include')
def do_inc... | Add a dummy safe filter for Django compat | Add a dummy safe filter for Django compat
| Python | mit | funkybob/knights-templater,funkybob/knights-templater |
5d8555ffc9a4b0549d32161a79aada3857b9d639 | webapp/graphite/events/models.py | webapp/graphite/events/models.py | import time
import os
from django.db import models
from django.contrib import admin
if os.environ.get('READTHEDOCS'):
TagField = lambda *args, **kwargs: None
else:
from tagging.fields import TagField
class Event(models.Model):
class Admin: pass
when = models.DateTimeField()
what = models.CharFie... | import time
import os
from django.db import models
from django.contrib import admin
from tagging.managers import ModelTaggedItemManager
if os.environ.get('READTHEDOCS'):
TagField = lambda *args, **kwargs: None
else:
from tagging.fields import TagField
class Event(models.Model):
class Admin: pass
whe... | Fix events to work on mysql | Fix events to work on mysql
Closes https://bugs.launchpad.net/graphite/+bug/993625
| Python | apache-2.0 | jssjr/graphite-web,mleinart/graphite-web,DanCech/graphite-web,bruce-lyft/graphite-web,dhtech/graphite-web,cgvarela/graphite-web,ceph/graphite-web,AICIDNN/graphite-web,kkdk5535/graphite-web,axibase/graphite-web,graphite-project/graphite-web,g76r/graphite-web,redice/graphite-web,section-io/graphite-web,cloudant/graphite-... |
767cf250a23c164cfcf7d6eba5a48116e3b111e5 | app/admin/forms.py | app/admin/forms.py | from flask_pagedown.fields import PageDownField
from wtforms.fields import StringField
from wtforms.validators import DataRequired
from app.models import Post, Tag
from app.utils.helpers import get_or_create
from app.utils.forms import RedirectForm
from app.utils.fields import TagListField
class PostForm(RedirectFor... | from flask_pagedown.fields import PageDownField
from wtforms.fields import StringField
from wtforms.validators import DataRequired
from app.models import Post, Tag
from app.utils.helpers import get_or_create
from app.utils.forms import RedirectForm
from app.utils.fields import TagListField
class PostForm(RedirectFor... | Return Post object in PostForm save method | Return Post object in PostForm save method
| Python | mit | Encrylize/flask-blogger,Encrylize/flask-blogger,Encrylize/flask-blogger |
6d9ad75ca3ac9a5ed9aac33e56a4809fc7e37f54 | gignore/__init__.py | gignore/__init__.py | __version__ = (2014, 10, 0)
def get_version():
"""
:rtype: str
"""
return '.'.join(str(i) for i in __version__)
class Gignore(object):
BASE_URL = 'https://raw.githubusercontent.com/github/gitignore/master/'
name = None
file_content = None
valid = True
def get_base_url(self):
... | __version__ = (2014, 10, 0)
def get_version():
"""
:rtype: str
"""
return '.'.join(str(i) for i in __version__)
class Gignore(object):
BASE_URL = 'https://raw.githubusercontent.com/github/gitignore/master/'
name = None
file_content = None
valid = True
errors = []
def get_bas... | Add errors attribute with setter/getter | Add errors attribute with setter/getter
| Python | bsd-3-clause | Alir3z4/python-gignore |
7141cedd5667b373e3dd5a723052de42ea5dfa10 | ome/terminal.py | ome/terminal.py | import sys
import os
ansi_colour_list = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
ansi_colour_code = dict((name, str(code)) for code, name in enumerate(ansi_colour_list, 30))
def is_ansi_terminal(file):
return ((sys.platform != 'win32' or 'ANSICON' in os.environ)
and hasattr(... | import sys
import os
ansi_colour_list = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white']
ansi_colour_code = dict((name, '{}m'.format(code)) for code, name in enumerate(ansi_colour_list, 30))
def is_ansi_terminal(file):
return ((sys.platform != 'win32' or 'ANSICON' in os.environ)
and... | Include m in colour code string instead of appending it later. | Include m in colour code string instead of appending it later.
| Python | mit | shaurz/ome,shaurz/ome |
01b1b649539beb41073e7df427d6f4622d687a5d | tests/django_settings.py | tests/django_settings.py | # Minimum settings that are needed to run django test suite
import os
import secrets
import tempfile
SECRET_KEY = secrets.token_hex()
if "postgresql" in os.getenv("TOX_ENV_NAME", "") or os.getenv("TEST_DATABASE") == "postgres":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresq... | # Minimum settings that are needed to run django test suite
import os
import secrets
import tempfile
USE_TZ = True
SECRET_KEY = secrets.token_hex()
if "postgresql" in os.getenv("TOX_ENV_NAME", "") or os.getenv("TEST_DATABASE") == "postgres":
DATABASES = {
'default': {
'ENGINE': 'django.db.back... | Set USE_TZ=True, django 4 raises a warning if this is not set to a value | Set USE_TZ=True, django 4 raises a warning if this is not set to a value
| Python | bsd-3-clause | romgar/django-dirtyfields |
54dc5c3a6ddf7fdc630547836058d017c778008f | python/recursive-digit-sum.py | python/recursive-digit-sum.py | #!/bin/python3
def superDigit(n, k):
p = create_p(n, k)
return get_super_digit(p)
def get_super_digit(p):
if len(p) == 1:
return int(p)
else:
digits = map(int, list(p))
return get_super_digit(str(sum(digits)))
def create_p(n, k):
return n * k
if __name__ == '__main__':
... | #!/bin/python3
def super_digit(n, k):
digits = map(int, list(n))
return get_super_digit(str(sum(digits) * k))
def get_super_digit(p):
if len(p) == 1:
return int(p)
else:
digits = map(int, list(p))
return get_super_digit(str(sum(digits)))
if __name__ == '__main__':
nk = inp... | Implement shortcut to compute initial p super digit | Implement shortcut to compute initial p super digit
| Python | mit | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank |
5d09fef9ee1f6b8627e372695a93be3236820f46 | app/main/errors.py | app/main/errors.py | from flask import jsonify
from . import main
from ..models import ValidationError
@main.app_errorhandler(ValidationError)
def validatation_error(e):
return jsonify(error=e.message), 400
def generic_error_handler(e):
# TODO: log the error
headers = []
error = e.description
if e.code == 401:
... | from flask import jsonify
from . import main
from ..models import ValidationError
@main.app_errorhandler(ValidationError)
def validatation_error(e):
return jsonify(error=e.message), 400
def generic_error_handler(e):
headers = []
code = getattr(e, 'code', 500)
error = getattr(e, 'description', 'Inte... | Fix app error handler raising an attribute error | Fix app error handler raising an attribute error
We're using a single error handler to return a JSON response for
any error code.
The handler expects a flask HTTP error exception with `.code` and
`.description` attributes (like the ones raised by `abort`).
However, if the app raises an exception that's not handled b... | Python | mit | alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api,alphagov/digitalmarketplace-api |
c313d6fb6803edabb956e1e90f040f8518c334bf | app/main/errors.py | app/main/errors.py | from flask import render_template
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
return render_template("404.html"), 404
| from flask import render_template
from . import main
@main.app_errorhandler(404)
def page_not_found(e):
return render_template("404.html",
**main.config['BASE_TEMPLATE_DATA']), 404
| Fix 404 page template static resources | Fix 404 page template static resources
| Python | mit | mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.