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 |
|---|---|---|---|---|---|---|---|---|---|---|
4c9e18f39908e9b1a36989b3e4097ca458d94af4 | docs/conf.py | docs/conf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath('.')))
import youtube_dl_server as ydl_server
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension modu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath('.')))
import youtube_dl_server as ydl_server
# -- General configuration -----------------------------------------------------
# Add any Sphin... | Use the current year in the copyright | docs: Use the current year in the copyright
| Python | unlicense | jaimeMF/youtube-dl-api-server,apllicationCOM/youtube-dl-api-server,apllicationCOM/youtube-dl-api-server,jaimeMF/youtube-dl-api-server,apllicationCOM/youtube-dl-api-server,jaimeMF/youtube-dl-api-server | ---
+++
@@ -2,8 +2,9 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
+import datetime
+import os
import sys
-import os
sys.path.insert(0, os.path.dirname(os.path.abspath('.')))
import youtube_dl_server as ydl_server
@@ -21,7 +22,7 @@
# General information about the project.
project = '... |
eaf74f092e73dcb832d624d9f19e9eaee5fbc244 | pyfakefs/pytest_plugin.py | pyfakefs/pytest_plugin.py | """A pytest plugin for using pyfakefs as a fixture
When pyfakefs is installed, the "fs" fixture becomes available.
:Usage:
def my_fakefs_test(fs):
fs.create_file('/var/data/xx1.txt')
assert os.path.exists('/var/data/xx1.txt')
"""
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
... | """A pytest plugin for using pyfakefs as a fixture
When pyfakefs is installed, the "fs" fixture becomes available.
:Usage:
def my_fakefs_test(fs):
fs.create_file('/var/data/xx1.txt')
assert os.path.exists('/var/data/xx1.txt')
"""
import linecache
import py
import pytest
from pyfakefs.fake_filesystem_unittes... | Add linecache module to skipped modules for pytest plugin | Add linecache module to skipped modules for pytest plugin
- see #381
- fixes the problem under Python 3, but not under Python 2
| Python | apache-2.0 | mrbean-bremen/pyfakefs,pytest-dev/pyfakefs,mrbean-bremen/pyfakefs,jmcgeheeiv/pyfakefs | ---
+++
@@ -8,11 +8,14 @@
fs.create_file('/var/data/xx1.txt')
assert os.path.exists('/var/data/xx1.txt')
"""
+import linecache
+
import py
import pytest
from pyfakefs.fake_filesystem_unittest import Patcher
Patcher.SKIPMODULES.add(py) # Ignore pytest components when faking filesystem
+Patcher.SKIPMO... |
0770a8e77463ee70851404a37138da050aead5bb | pymatgen/core/__init__.py | pymatgen/core/__init__.py | """
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .l... | """
This package contains core modules and classes for representing structures and
operations on them.
"""
__author__ = "Shyue Ping Ong"
__date__ = "Dec 15, 2010 7:21:29 PM"
from .periodic_table import *
from .composition import *
from .structure import *
from .structure_modifier import *
from .bonds import *
from .l... | Add units to Core import. | Add units to Core import.
Former-commit-id: 0f1c678c7da36ebc85827601645f6729a11e5f41 [formerly 80676409b706f3927b463afef6aa844d00aeb107]
Former-commit-id: f99f3956f55a26845ce5ce583545a0413e4f36ce | Python | mit | tallakahath/pymatgen,matk86/pymatgen,aykol/pymatgen,matk86/pymatgen,gpetretto/pymatgen,setten/pymatgen,tschaume/pymatgen,ndardenne/pymatgen,gVallverdu/pymatgen,dongsenfo/pymatgen,johnson1228/pymatgen,montoyjh/pymatgen,johnson1228/pymatgen,nisse3000/pymatgen,ndardenne/pymatgen,tschaume/pymatgen,davidwaroquiers/pymatgen,... | ---
+++
@@ -14,3 +14,4 @@
from .lattice import *
from .sites import *
from .operations import *
+from .units import * |
7255033298cad9a4a7c51bdceafe84c0536e78ba | pytopkapi/infiltration.py | pytopkapi/infiltration.py | """Infiltration module.
"""
import numpy as np
from scipy.optimize import fsolve
def green_ampt_cum_infiltration(F, psi, dtheta, K, t):
"""The Green-Ampt cumulative infiltration equation.
"""
tmp = psi*dtheta
# np.log(x) computes ln(x)
return F - tmp*np.log(1 + F/tmp) - K*t
if __name__ == '... | """Infiltration module.
"""
import numpy as np
from scipy.optimize import fsolve
def _green_ampt_cum_eq(F, psi, dtheta, K, t):
"""The Green-Ampt cumulative infiltration equation
"""
tmp = psi*dtheta
# np.log(x) computes ln(x)
return F - tmp*np.log(1 + F/tmp) - K*t
def green_ampt_cum_infiltratio... | Change the API and add a test and documentation | ENH: Change the API and add a test and documentation
| Python | bsd-3-clause | scottza/PyTOPKAPI,sahg/PyTOPKAPI | ---
+++
@@ -4,22 +4,62 @@
import numpy as np
from scipy.optimize import fsolve
-def green_ampt_cum_infiltration(F, psi, dtheta, K, t):
- """The Green-Ampt cumulative infiltration equation.
+def _green_ampt_cum_eq(F, psi, dtheta, K, t):
+ """The Green-Ampt cumulative infiltration equation
"""
tmp... |
1223c77fb3ada03d32e6c9da0a08dd43bfc5ad7b | docs/test.py | docs/test.py | import sys, os
if sys.version_info >= (2, 4):
import doctest
else:
raise ImportError("Python 2.4 doctest required")
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def test():
for doc in ['SQLObject.txt']:
doctest.testfile(doc, optionflags=doctest.ELLIPSIS)
if __name... | import sys, os
if sys.version_info >= (2, 4):
import doctest
else:
raise ImportError("Python 2.4 doctest required")
sys.path.insert(
0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def test():
for doc in ['SQLObject.txt']:
doctest.testfile(doc, optionflags=doctest.ELLIPSIS)
i... | Make sure checkout is first on sys.path | Make sure checkout is first on sys.path
git-svn-id: fe2f45b2405132b4a9af5caedfc153c2e6f542f4@894 95a46c32-92d2-0310-94a5-8d71aeb3d4b3
| Python | lgpl-2.1 | sqlobject/sqlobject,drnlm/sqlobject,sqlobject/sqlobject,drnlm/sqlobject | ---
+++
@@ -5,7 +5,8 @@
else:
raise ImportError("Python 2.4 doctest required")
-sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+sys.path.insert(
+ 0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def test():
for doc in ['SQLObject.txt']: |
49897f091c159220a7aa1fac2d5e03f42236053f | tests/dotnetexample/conf.py | tests/dotnetexample/conf.py | # -*- coding: utf-8 -*-
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'dotnetexample'
copyright = u'2015, rtfd'
author = u'rtfd'
version = '0.1'
release = '0.1'
language = None
exclude_patterns = ['_build']
pygments_style = 'sphinx'
todo_include_todos = False
html_theme = 'sphi... | # -*- coding: utf-8 -*-
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'dotnetexample'
copyright = u'2015, rtfd'
author = u'rtfd'
version = '0.1'
release = '0.1'
language = None
exclude_patterns = ['_build']
pygments_style = 'sphinx'
todo_include_todos = False
html_theme = 'sphi... | Make sure example repo exists | Make sure example repo exists
| Python | mit | rtfd/sphinx-autoapi,rtfd/sphinx-autoapi,rtfd/sphinx-autoapi,rtfd/sphinx-autoapi | ---
+++
@@ -19,3 +19,10 @@
autoapi_type = 'dotnet'
autoapi_dir = 'example/Identity/src/'
autoapi_keep_files = True
+
+import os
+
+SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
+DIR = os.path.join(SITE_ROOT, autoapi_dir)
+if not os.path.exists(DIR):
+ os.system('git clone https://github.com/aspnet/Ide... |
bb3ec131261f0619a86f21f549d6b1cb47f2c9ad | graph/serializers.py | graph/serializers.py | from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm
class GraphSeriesSerializer(serializers.ModelSerializer):
x = serializers.SerializerMethodField('get_time')
y = seriali... | from rest_framework import serializers
from measurement.models import Measurement
from threshold_value.models import ThresholdValue
from calendar import timegm
from alarm.models import Alarm
class GraphSeriesSerializer(serializers.ModelSerializer):
x = serializers.SerializerMethodField('get_time')
y = seriali... | Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint | Simplify SimpleAlarmSerializer to improve the performance of the graph_data endpoint
| Python | mit | sigurdsa/angelika-api | ---
+++
@@ -48,4 +48,4 @@
class SimpleAlarmSerializer(serializers.ModelSerializer):
class Meta:
model = Alarm
- fields = ('id', 'time_created', 'is_treated', 'treated_text')
+ fields = ['is_treated'] |
34667b59161f0079715e9bffa11237a1a8c5500f | fedimg/uploader.py | fedimg/uploader.py | #!/bin/env python
# -*- coding: utf8 -*-
import koji
def upload(builds):
""" Takes a list of one or more Koji build IDs (passed to it from
consumer.py) and sends the appropriate image files off to cloud
services. """
if isinstance(builds, list):
for build in builds:
pass
else:... | #!/bin/env python
# -*- coding: utf8 -*-
import koji
from pprint import pprint
def upload(builds):
""" Takes a list of one or more Koji build IDs (passed to it from
consumer.py) and sends the appropriate image files off to cloud
services. """
if isinstance(builds, list):
# Create a Koji conn... | Add some koji API code for testing getting build results/output. | Add some koji API code for testing getting build results/output.
| Python | agpl-3.0 | fedora-infra/fedimg,fedora-infra/fedimg | ---
+++
@@ -2,6 +2,8 @@
# -*- coding: utf8 -*-
import koji
+
+from pprint import pprint
def upload(builds):
@@ -9,8 +11,20 @@
consumer.py) and sends the appropriate image files off to cloud
services. """
if isinstance(builds, list):
- for build in builds:
- pass
+ # Cr... |
0f9168caa5085cb225ea04b725a2379eef8c3b8d | app/Voltage/voltage.py | app/Voltage/voltage.py | import smbus
import time
ADDRESS = 4
CMD_READ_ANALOG = 1
VOLT12 = 650
VOLT18 = 978
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
class Voltage:
def __init__(self):
self.bus = s... | import smbus
import time
ADDRESS = 4
CMD_READ_ANALOG = 1
VOLT12 = 650
VOLT18 = 978
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
class Voltage:
def __init__(self):
self.bus =... | Fix some minor formatting issues | Fix some minor formatting issues
| Python | mit | gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x,thelonious/g2x | ---
+++
@@ -6,18 +6,20 @@
VOLT12 = 650
VOLT18 = 978
+
def map_range(x, in_min, in_max, out_min, out_max):
out_delta = out_max - out_min
in_delta = in_max - in_min
return (x - in_min) * out_delta / in_delta + out_min
+
class Voltage:
def __init__(self):
self.bus = smbus.SMBus(1)
... |
dc82d59b739934d093ed0d704583e7edf1278fc3 | core/management/commands/delete_old_sessions.py | core/management/commands/delete_old_sessions.py | from datetime import datetime
from django.core.management.base import BaseCommand
from django.contrib.sessions.models import Session
class Command(BaseCommand):
args = '<count count ...>'
help = "Delete old sessions"
def handle(self, *args, **options):
old_sessions = Session.objects.filter(expi... | from datetime import datetime
from django.core.management.base import NoArgsCommand
from django.contrib.sessions.models import Session
class Command(NoArgsCommand):
help = "Delete old sessions"
def handle_noargs(self, **options):
old_sessions = Session.objects.filter(expire_date__lt=datetime.now())... | Add delete old sessions command | Add delete old sessions command
| Python | mit | QLGu/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,QLGu/djangopackages,pydanny/djangopackages,pydanny/djangopackages,nanuxbe/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages | ---
+++
@@ -1,15 +1,14 @@
from datetime import datetime
-from django.core.management.base import BaseCommand
+from django.core.management.base import NoArgsCommand
from django.contrib.sessions.models import Session
-class Command(BaseCommand):
+class Command(NoArgsCommand):
- args = '<count count ...>'
... |
591a40b6e1f4ac8b1d21050ccfa10779dc9dbf7c | analytic_code.py | analytic_code.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 XCG Consulting (www.xcg-consulting.fr)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# pub... | Add string to display the name of the field Dimension during the import | Add string to display the name of the field Dimension during the import
| Python | agpl-3.0 | xcgd/analytic_structure | ---
+++
@@ -27,7 +27,7 @@
_columns = dict(
name=fields.char("Name", size=128, translate=True, required=True),
nd_id=fields.many2one(
- "analytic.dimension", ondelete="restrict"),
+ "analytic.dimension", "Dimensions", ondelete="restrict"),
active=fields.boolean('Ac... |
50146d9e3e43ca4d9c50d044c52714cf4234cee1 | tests/window/window_util.py | tests/window/window_util.py | #!/usr/bin/python
# $Id:$
from pyglet.gl import *
def draw_client_border(window):
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, window.width, 0, window.height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()... | #!/usr/bin/python
# $Id:$
from pyglet.gl import *
def draw_client_border(window):
glClearColor(0, 0, 0, 1)
glClear(GL_COLOR_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(0, window.width, 0, window.height, -1, 1)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()... | Fix window test border _again_ (more fixed). | Fix window test border _again_ (more fixed).
| Python | bsd-3-clause | adamlwgriffiths/Pyglet,adamlwgriffiths/Pyglet,seeminglee/pyglet64,adamlwgriffiths/Pyglet,adamlwgriffiths/Pyglet,seeminglee/pyglet64,niklaskorz/pyglet,niklaskorz/pyglet,seeminglee/pyglet64,niklaskorz/pyglet,niklaskorz/pyglet | ---
+++
@@ -22,7 +22,7 @@
glEnd()
glColor3f(1, 0, 0)
- rect(-1, -1, window.width + 1, window.height - 1)
+ rect(-1, -1, window.width, window.height)
glColor3f(0, 1, 0)
rect(0, 0, window.width - 1, window.height - 1) |
6782ad40a405f79f07fa1527131634f96944ffd6 | apps/innovate/views.py | apps/innovate/views.py | import random
import jingo
from users.models import Profile
from projects.models import Project
from events.models import Event
from feeds.models import Entry
def splash(request):
"""Display splash page. With featured project, event, person, blog post."""
def get_random(cls, **kwargs):
choices = cls... | import random
import jingo
from users.models import Profile
from projects.models import Project
from events.models import Event
from feeds.models import Entry
def splash(request):
"""Display splash page. With featured project, event, person, blog post."""
def get_random(cls, **kwargs):
choices = cls... | Add status codes to the 404/500 error handlers. | Add status codes to the 404/500 error handlers.
| Python | bsd-3-clause | mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite | ---
+++
@@ -30,9 +30,9 @@
def handle404(request):
"""Handle 404 responses."""
- return jingo.render(request, 'handlers/404.html')
+ return jingo.render(request, 'handlers/404.html', status=404)
def handle500(request):
"""Handle server errors."""
- return jingo.render(request, 'handlers/500.... |
e84ca65440bb6b38bf0630373766789d6915a20d | dataset/dataset/spiders/dataset_spider.py | dataset/dataset/spiders/dataset_spider.py | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from dataset import DatasetItem
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.... | from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from dataset import DatasetItem
class DatasetSpider(CrawlSpider):
name = 'dataset'
allowed_domains = ['data.gc.ca/data/en']
start_urls = ['http://data.... | Add text selection inside 'li' element | Add text selection inside 'li' element
| Python | mit | MaxLikelihood/CODE | ---
+++
@@ -16,6 +16,6 @@
dataset = DatasetItem()
dataset['url'] = response.url
dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1").extract()
- dataset['frequency'] = sel.xpath("//div[@class='span-2... |
8d651ed493d2787da478f0c7c120917d3335b4d5 | email_from_template/utils.py | email_from_template/utils.py | from . import app_settings
_render_method = None
def get_render_method():
global _render_method
if _render_method is None:
_render_method = from_dotted_path(app_settings.EMAIL_RENDER_METHOD)
return _render_method
_context_processors = None
def get_context_processors():
global _context_proces... | from django.utils.functional import memoize
from . import app_settings
def get_render_method():
return from_dotted_path(app_settings.EMAIL_RENDER_METHOD)
get_render_method = memoize(get_render_method, {}, 0)
def get_context_processors():
return [from_dotted_path(x) for x in app_settings.EMAIL_CONTEXT_PROCESS... | Use Django's memoize over a custom one. | Use Django's memoize over a custom one.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@playfire.com>
| Python | bsd-3-clause | playfire/django-email-from-template,lamby/django-email-from-template | ---
+++
@@ -1,24 +1,14 @@
+from django.utils.functional import memoize
+
from . import app_settings
-_render_method = None
def get_render_method():
- global _render_method
+ return from_dotted_path(app_settings.EMAIL_RENDER_METHOD)
+get_render_method = memoize(get_render_method, {}, 0)
- if _render_met... |
07d7eddac89d5ac54af62e185801cdbe71720b7c | hybridJaccardTest.py | hybridJaccardTest.py | import argparse
import sys
import hybridJaccard as hj
def main():
"Command line testinterface."
parser = argparse.ArgumentParser()
parser.add_argument('-c','--configFile', help="Configuration file (JSON).", required=False)
parser.add_argument('-i','--input', help="Input file of phrases to test.", requ... | import argparse
import sys
import hybridJaccard as hj
def main():
"Command line testinterface."
parser = argparse.ArgumentParser()
parser.add_argument('-c','--configFile', help="Configuration file (JSON).", required=False)
parser.add_argument('-i','--input', help="Input file of phrases to test.", requ... | Read the intput file specified on the command line. | Read the intput file specified on the command line.
| Python | apache-2.0 | usc-isi-i2/hybrid-jaccard | ---
+++
@@ -12,7 +12,7 @@
args = parser.parse_args()
sm = hj.HybridJaccard(ref_path=args.referenceFile, config_path=args.configFile)
- with open("input.txt") as input:
+ with open(args.input) as input:
for line in input:
line = line.strip()
match = sm.findBestMatch... |
fcbb2ec6ebceebea0012971a831f2941d1943708 | src/knesset/links/managers.py | src/knesset/links/managers.py | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_unicode
class LinksManager(models.Manager):
def for_model(self, model):
"""
QuerySet for all links for a particular model (either an instance or
a class).
... | from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_unicode
class LinksManager(models.Manager):
def for_model(self, model):
"""
QuerySet for all links for a particular model (either an instance or
a class).
... | Use select related for link_type | Use select related for link_type
| Python | bsd-3-clause | habeanf/Open-Knesset,jspan/Open-Knesset,noamelf/Open-Knesset,navotsil/Open-Knesset,OriHoch/Open-Knesset,noamelf/Open-Knesset,habeanf/Open-Knesset,noamelf/Open-Knesset,daonb/Open-Knesset,Shrulik/Open-Knesset,ofri/Open-Knesset,OriHoch/Open-Knesset,ofri/Open-Knesset,noamelf/Open-Knesset,MeirKriheli/Open-Knesset,DanaOshri/... | ---
+++
@@ -1,6 +1,7 @@
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.utils.encoding import force_unicode
+
class LinksManager(models.Manager):
@@ -10,7 +11,8 @@
a class).
"""
ct = ContentType.objects.get_for_model(model)
- ... |
79dd629be9b858fd7bc73e7d16aecbb25de0d5db | fireplace/cards/wog/rogue.py | fireplace/cards/wog/rogue.py | from ..utils import *
##
# Minions
##
# Spells
class OG_073:
"Thistle Tea"
play = Draw(CONTROLLER).then(Give(CONTROLLER, Copy(Draw.CARD)) * 2)
| from ..utils import *
##
# Minions
class OG_070:
"Bladed Cultist"
combo = Buff(SELF, "OG_070e")
OG_070e = buff(+1, +1)
class OG_267:
"Southsea Squidface"
deathrattle = Buff(FRIENDLY_WEAPON, "OG_267e")
OG_267e = buff(atk=2)
##
# Spells
class OG_073:
"Thistle Tea"
play = Draw(CONTROLLER).then(Give(CONTROL... | Implement Bladed Cultist, Southsea Squidface, and Shadow Strike | Implement Bladed Cultist, Southsea Squidface, and Shadow Strike
| Python | agpl-3.0 | NightKev/fireplace,jleclanche/fireplace,beheh/fireplace | ---
+++
@@ -3,6 +3,19 @@
##
# Minions
+
+class OG_070:
+ "Bladed Cultist"
+ combo = Buff(SELF, "OG_070e")
+
+OG_070e = buff(+1, +1)
+
+
+class OG_267:
+ "Southsea Squidface"
+ deathrattle = Buff(FRIENDLY_WEAPON, "OG_267e")
+
+OG_267e = buff(atk=2)
##
@@ -11,3 +24,8 @@
class OG_073:
"Thistle Tea"
play = ... |
b8ad378a796ee867acfa3198e04d47a500dd90d3 | mla/neuralnet/activations.py | mla/neuralnet/activations.py | import autograd.numpy as np
"""
References:
https://en.wikipedia.org/wiki/Activation_function
"""
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def softmax(z):
# Avoid numerical overflow by removing max
e = np.exp(z - np.amax(z, axis=1, keepdims=True))
return e / np.sum(e, axis=1, keepdims=True)
... | import autograd.numpy as np
"""
References:
https://en.wikipedia.org/wiki/Activation_function
"""
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def softmax(z):
# Avoid numerical overflow by removing max
e = np.exp(z - np.amax(z, axis=1, keepdims=True))
return e / np.sum(e, axis=1, keepdims=True)
... | Add Leaky ReLU activation. Differentiation with autograd package confirmed to work correctly. | Add Leaky ReLU activation.
Differentiation with autograd package confirmed to work correctly.
| Python | mit | rushter/MLAlgorithms | ---
+++
@@ -39,6 +39,10 @@
return np.maximum(0, z)
+def leakyrelu(z, a=0.01):
+ return np.maximum(z * a, z)
+
+
def get_activation(name):
"""Return activation function by name"""
try: |
f6cad3a2bfeb4238da359c882fe7cbbaedb5d8b7 | setuptools/extension.py | setuptools/extension.py | from distutils.core import Extension as _Extension
from dist import _get_unpatched
_Extension = _get_unpatched(_Extension)
try:
from Pyrex.Distutils.build_ext import build_ext
except ImportError:
have_pyrex = False
else:
have_pyrex = True
class Extension(_Extension):
"""Extension that uses '.c' files... | from distutils.core import Extension as _Extension
from setuptools.dist import _get_unpatched
_Extension = _get_unpatched(_Extension)
try:
from Pyrex.Distutils.build_ext import build_ext
except ImportError:
have_pyrex = False
else:
have_pyrex = True
class Extension(_Extension):
"""Extension that uses... | Fix import that was breaking py3k | Fix import that was breaking py3k
--HG--
branch : distribute
extra : rebase_source : 76bf8f9213536189bce76a41e798c44c5f468cbd
| Python | mit | pypa/setuptools,pypa/setuptools,pypa/setuptools | ---
+++
@@ -1,5 +1,5 @@
from distutils.core import Extension as _Extension
-from dist import _get_unpatched
+from setuptools.dist import _get_unpatched
_Extension = _get_unpatched(_Extension)
try: |
bd78b8c1bab94b5f048f8bc4895657f1fd36ddfc | project_generator/commands/clean.py | project_generator/commands/clean.py | # Copyright 2014-2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | # Copyright 2014-2015 0xc0170
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | Clean - tool is not required, as tool_supported are there | Clean - tool is not required, as tool_supported are there
| Python | apache-2.0 | 0xc0170/project_generator,sarahmarshy/project_generator,hwfwgrp/project_generator,molejar/project_generator,project-generator/project_generator,ohagendorf/project_generator | ---
+++
@@ -34,4 +34,4 @@
subparser.add_argument("-f", "--file", help="YAML projects file", default='projects.yaml')
subparser.add_argument("-p", "--project", required = True, help="Specify which project to be removed")
subparser.add_argument(
- "-t", "--tool", required = True, help="Clean proje... |
2bf883741ce763bde729f2930af913c44a807cb5 | jiraconfig-sample.py | jiraconfig-sample.py | JIRA = {
"server": "https://example.com/jira/",
"user": "user",
"password": "password"
}
| import keyring
JIRA = {
"server": "https://example.com/jira/",
"user": "user",
"password": keyring.get_password("system", "user")
}
| Add keyring to example config | Add keyring to example config
| Python | mit | mrts/ask-jira | ---
+++
@@ -1,5 +1,7 @@
+import keyring
+
JIRA = {
"server": "https://example.com/jira/",
"user": "user",
- "password": "password"
+ "password": keyring.get_password("system", "user")
} |
235f8061caa667f7c9bc1f424e14326c22932547 | Examples/Infovis/Python/cone_layout.py | Examples/Infovis/Python/cone_layout.py | from vtk import *
reader = vtkXMLTreeReader()
reader.SetFileName("vtkclasses.xml")
reader.Update()
print reader.GetOutput()
view = vtkGraphLayoutView()
view.AddRepresentationFromInputConnection(reader.GetOutputPort())
view.SetVertexLabelArrayName("id")
view.SetVertexLabelVisibility(True)
view.SetVertexColorArrayName... | from vtk import *
reader = vtkXMLTreeReader()
reader.SetFileName("vtkclasses.xml")
view = vtkGraphLayoutView()
view.AddRepresentationFromInputConnection(reader.GetOutputPort())
view.SetVertexLabelArrayName("id")
view.SetVertexLabelVisibility(True)
view.SetVertexColorArrayName("vertex id")
view.SetColorVertices(True)... | Remove errant printout in python cone layout example. | ENH: Remove errant printout in python cone layout example.
| Python | bsd-3-clause | daviddoria/PointGraphsPhase1,jmerkow/VTK,mspark93/VTK,hendradarwin/VTK,aashish24/VTK-old,Wuteyan/VTK,jmerkow/VTK,berendkleinhaneveld/VTK,msmolens/VTK,ashray/VTK-EVM,msmolens/VTK,hendradarwin/VTK,sumedhasingla/VTK,ashray/VTK-EVM,johnkit/vtk-dev,sumedhasingla/VTK,SimVascular/VTK,sankhesh/VTK,candy7393/VTK,jmerkow/VTK,spt... | ---
+++
@@ -3,8 +3,6 @@
reader = vtkXMLTreeReader()
reader.SetFileName("vtkclasses.xml")
-reader.Update()
-print reader.GetOutput()
view = vtkGraphLayoutView()
view.AddRepresentationFromInputConnection(reader.GetOutputPort()) |
72d0ca4e2f4be7969498b226af4243315f2dff0c | tests/test_colors.py | tests/test_colors.py | """Test imagemagick functions."""
import unittest
from pywal import colors
class TestGenColors(unittest.TestCase):
"""Test the gen_colors functions."""
def test_gen_colors(self):
"""> Generate a colorscheme."""
result = colors.get("tests/test_files/test.jpg")
self.assertEqual(result[... | """Test imagemagick functions."""
import unittest
from pywal import colors
class TestGenColors(unittest.TestCase):
"""Test the gen_colors functions."""
def test_gen_colors(self):
"""> Generate a colorscheme."""
result = colors.get("tests/test_files/test.jpg")
self.assertEqual(len(res... | Check color length instead of value since the tests will fail on other versions of imageamgick | tests: Check color length instead of value since the tests will fail on other versions of imageamgick
| Python | mit | dylanaraps/pywal,dylanaraps/pywal,dylanaraps/pywal | ---
+++
@@ -10,7 +10,7 @@
def test_gen_colors(self):
"""> Generate a colorscheme."""
result = colors.get("tests/test_files/test.jpg")
- self.assertEqual(result["colors"]["color0"], "#0D191B")
+ self.assertEqual(len(result["colors"]["color0"]), 7)
if __name__ == "__main__": |
323cc3f50fa0bbd072bfe243443adf12e1b25220 | bluebottle/projects/migrations/0019_auto_20170118_1537.py | bluebottle/projects/migrations/0019_auto_20170118_1537.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-18 14:37
from __future__ import unicode_literals
import binascii
import os
from django.db import migrations
def generate_key():
return binascii.hexlify(os.urandom(20)).decode()
def create_auth_token(apps, schema_editor):
Member = apps.get_mode... | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-18 14:37
from __future__ import unicode_literals
import binascii
import os
from django.db import migrations
def generate_key():
return binascii.hexlify(os.urandom(20)).decode()
def create_auth_token(apps, schema_editor):
Member = apps.get_mode... | Add dependency on different migrations | Add dependency on different migrations
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle | ---
+++
@@ -31,6 +31,8 @@
dependencies = [
('projects', '0018_merge_20170118_1533'),
('authtoken', '0001_initial'),
+ ('quotes', '0005_auto_20180717_1017'),
+ ('slides', '0006_auto_20180717_1017'),
]
operations = [ |
23e1766731dbd08d3d6c55d9d1fe2bbf1be42614 | sncosmo/tests/test_builtins.py | sncosmo/tests/test_builtins.py | import pytest
import sncosmo
@pytest.mark.might_download
def test_hst_bands():
""" check that the HST and JWST bands are accessible """
for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m',
'f115w']: # jwst nircam
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
de... | import pytest
import sncosmo
@pytest.mark.might_download
def test_hst_bands():
""" check that the HST and JWST bands are accessible """
for bandname in ['f606w', 'uvf606w', 'f125w', 'f127m',
'f115w']: # jwst nircam
sncosmo.get_bandpass(bandname)
@pytest.mark.might_download
de... | Update tests to cover every Roman WFI filter | Update tests to cover every Roman WFI filter
| Python | bsd-3-clause | sncosmo/sncosmo,sncosmo/sncosmo,sncosmo/sncosmo | ---
+++
@@ -24,4 +24,11 @@
@pytest.mark.might_download
def test_roman_bandpass():
- bp = sncosmo.get_bandpass('f087')
+ sncosmo.get_bandpass('f062')
+ sncosmo.get_bandpass('f087')
+ sncosmo.get_bandpass('f106')
+ sncosmo.get_bandpass('f129')
+ sncosmo.get_bandpass('f158')
+ sncosmo.get_bandpa... |
d4033694f7686fe1ad48a185ae740c4d966d40d8 | classes/dnsresolver.py | classes/dnsresolver.py | import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call t... | import dns
import dns.resolver
import dns.rdatatype
from typing import Union, List
class DNSResolver(dns.resolver.Resolver):
def __init__(self, filename='/etc/resolv.conf', configure=False,
nameservers: Union[str, List[str]] = None):
# Run the dns.resolver.Resolver superclass init call t... | Implement rdatatype-aware and NoAnswer-aware DNS handling | Implement rdatatype-aware and NoAnswer-aware DNS handling
This will work for CNAME entries because CNAMEs hit by A or AAAA lookups behave like `dig` does - they will trigger a second resultset for the CNAME entry in order to return the IP address.
This also is amended to handle a "NoAnswer" response - i.e. if there a... | Python | apache-2.0 | Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector | ---
+++
@@ -26,12 +26,20 @@
def dns_resolve(domain: str, resolver: DNSResolver = DNSResolver(configure=True)) -> list:
addrs = []
- for answer in resolver.query(domain, 'A').response.answer:
- for item in answer:
- addrs.append(item.address)
+ try:
+ for answer in resolver.query... |
c81fff4ff4cccc51faf47c7ca9a63cd9eb6a2699 | projects/tests/factories.py | projects/tests/factories.py | import factory
from django.contrib.auth.models import User
from accounts.tests.factories import UserFactory
from .. import models
class OrganizationFactory(factory.DjangoModelFactory):
"""Organization factory"""
FACTORY_FOR = models.Organization
name = factory.Sequence(lambda n: 'organization {}'.format(... | import factory
from django.contrib.auth.models import User
from accounts.tests.factories import UserFactory
from .. import models
class OrganizationFactory(factory.DjangoModelFactory):
"""Organization factory"""
FACTORY_FOR = models.Organization
name = factory.Sequence(lambda n: 'organization {}'.format(... | Change project factory default values | Change project factory default values
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web | ---
+++
@@ -29,6 +29,7 @@
name = factory.Sequence(lambda n: 'project{}'.format(n))
url = factory.Sequence(lambda n: 'http://test{}.com'.format(n))
organization = factory.SubFactory(OrganizationFactory)
+ run_here = False
@factory.sequence
def owner(n): |
1c6fcd2e1ab02fef60e3507ba57cb9224b19d616 | elephantblog/context_processors.py | elephantblog/context_processors.py | from django.utils import translation
from feincms.module.page.models import Page
def blog_page(request):
""" Used to get the feincms page navigation within the blog app. """
from feincms.module.page.models import Page
try:
return {'blog_page' : Page.objects.get(slug='blog', language=translation.get... | from feincms.module.page.models import Page
from feincms.translations import short_language_code
def blog_page(request):
""" Used to get the feincms page navigation within the blog app. """
from feincms.module.page.models import Page
return {'blog_page': Page.objects.get(slug='blog', language=short_la... | Handle page module without translations extension too | blog_page: Handle page module without translations extension too
| Python | bsd-3-clause | matthiask/feincms-elephantblog,feincms/feincms-elephantblog,joshuajonah/feincms-elephantblog,matthiask/feincms-elephantblog,feincms/feincms-elephantblog,michaelkuty/feincms-elephantblog,matthiask/feincms-elephantblog,sbaechler/feincms-elephantblog,joshuajonah/feincms-elephantblog,sbaechler/feincms-elephantblog,sbaechle... | ---
+++
@@ -1,10 +1,13 @@
-from django.utils import translation
from feincms.module.page.models import Page
+from feincms.translations import short_language_code
+
def blog_page(request):
""" Used to get the feincms page navigation within the blog app. """
from feincms.module.page.models import Page
- ... |
c9aa7b60e3e985883854e7aba38838c7a45aa6fa | matches/models.py | matches/models.py | from django.db import models
from wrestlers.models import WrestlingEntity
class Card(models.Model):
date = models.DateField()
def __unicode__(self):
return unicode(self.date)
class Match(models.Model):
card = models.ForeignKey(Card)
participants = models.ManyToManyField(WrestlingEntity)
... | from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
class Review(models.Model):
reviewed_by = models.ForeignKey(User)
reviewed_at = models.DateTimeField()
class Meta:
abstract = True
class Card(models.Model):
date = models... | Add basic Review model and use it for matches. | Add basic Review model and use it for matches.
| Python | agpl-3.0 | OddBloke/moore | ---
+++
@@ -1,6 +1,16 @@
+from django.contrib.auth.models import User
from django.db import models
from wrestlers.models import WrestlingEntity
+
+
+class Review(models.Model):
+
+ reviewed_by = models.ForeignKey(User)
+ reviewed_at = models.DateTimeField()
+
+ class Meta:
+ abstract = True
c... |
74b1d24cde1e58a4829ce6ae0b7e3b52b8ced40f | nipy/modalities/fmri/__init__.py | nipy/modalities/fmri/__init__.py | """
TODO
"""
__docformat__ = 'restructuredtext'
import fmri, hrf, utils
import fmristat
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| """
TODO
"""
__docformat__ = 'restructuredtext'
import fmri, hrf, utils, formula
import fmristat
from nipy.testing import Tester
test = Tester().test
bench = Tester().bench
| Fix missing import of formula in fmri. | Fix missing import of formula in fmri. | Python | bsd-3-clause | yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD | ---
+++
@@ -4,7 +4,7 @@
__docformat__ = 'restructuredtext'
-import fmri, hrf, utils
+import fmri, hrf, utils, formula
import fmristat
from nipy.testing import Tester |
11238c63240fa19b87fc478916bac3a4bdd86df5 | django_project/realtime/tasks/test/test_celery_tasks.py | django_project/realtime/tasks/test/test_celery_tasks.py | # coding=utf-8
import logging
import unittest
from django import test
from timeout_decorator import timeout_decorator
from realtime.app_settings import LOGGER_NAME
from realtime.tasks import check_realtime_broker
from realtime.tasks.realtime.celery_app import app as realtime_app
from realtime.utils import celery_work... | # coding=utf-8
import logging
import unittest
from django import test
from timeout_decorator import timeout_decorator
from realtime.app_settings import LOGGER_NAME
from realtime.tasks import check_realtime_broker, \
retrieve_felt_earthquake_list
from realtime.tasks.realtime.celery_app import app as realtime_app
f... | Add unittests for BMKG EQ List Scrapper | Add unittests for BMKG EQ List Scrapper
| Python | bsd-2-clause | AIFDR/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django,AIFDR/inasafe-django | ---
+++
@@ -6,7 +6,8 @@
from timeout_decorator import timeout_decorator
from realtime.app_settings import LOGGER_NAME
-from realtime.tasks import check_realtime_broker
+from realtime.tasks import check_realtime_broker, \
+ retrieve_felt_earthquake_list
from realtime.tasks.realtime.celery_app import app as rea... |
38ce0d6b0433a68787c18691407c815d4eb1fdb2 | txscrypt/__init__.py | txscrypt/__init__.py | """
A Twisted-friendly wrapper for scrypt.
"""
from txscrypt.wrapper import computeKey, verifyPassword
from txscrypt._version import __version__
__all__ = ["computeKey", "verifyPassword"]
| """
A Twisted-friendly wrapper for scrypt.
"""
from txscrypt.wrapper import checkPassword, computeKey
from txscrypt._version import __version__
__all__ = ["verifyPassword", "computeKey"]
| Make checkPassword the only public API, remove verifyPassword | Make checkPassword the only public API, remove verifyPassword
| Python | isc | lvh/txscrypt | ---
+++
@@ -1,7 +1,7 @@
"""
A Twisted-friendly wrapper for scrypt.
"""
-from txscrypt.wrapper import computeKey, verifyPassword
+from txscrypt.wrapper import checkPassword, computeKey
from txscrypt._version import __version__
-__all__ = ["computeKey", "verifyPassword"]
+__all__ = ["verifyPassword", "computeKey"... |
f360c61cbe0a895ca3d8efe5be97f08ea7ff5682 | packages/vic/git/__init__.py | packages/vic/git/__init__.py | from mykde import Action
class Action(Action):
name = 'git'
description = "Git with helper programs and custom settings"
packages = ['git', 'gitk', 'giggle']
def proceed(self):
# useful aliases
self.call('git config --global alias.ci "commit -a"')
self.call('git config --glo... | from mykde import Action
class Action(Action):
name = 'git'
description = "Git with helper programs and custom settings"
packages = ['git', 'gitk', 'giggle']
def proceed(self):
# useful aliases
self.call('git config --global alias.ci "commit -a"')
self.call('git config --glo... | Add one more default option for git. | Add one more default option for git.
| Python | bsd-3-clause | warvariuc/mykde,warvariuc/mykde | ---
+++
@@ -18,3 +18,5 @@
self.call('git config --global push.default current')
# colorize UI
self.call('git config --global color.ui true')
+ # do not call pager for content less than one page
+ self.call('git config --global --add core.pager "less -F -X"') |
b2f1f97000c8d3479e1df6778f0cc85ec0680571 | garden-watering01/mybuddy.py | garden-watering01/mybuddy.py | import machine
def setntptime(maxretries=10):
# ntptime is a helper module which gets packaged into the firmware
# Check https://raw.githubusercontent.com/micropython/micropython/master/esp8266/scripts/ntptime.py
import ntptime
for i in range (maxretries):
try:
ntptime.settime()
break
excep... | import machine
def have_internet():
import urequests
try:
resp = urequests.request("HEAD", "http://jsonip.com/")
return True
except:
return False
def setntptime(maxretries=10):
# ntptime is a helper module which gets packaged into the firmware
# Check https://raw.githubusercontent.com/micropytho... | Add a function to check status of internet connectivity | Add a function to check status of internet connectivity
| Python | mit | fuzzyhandle/esp8266hangout,fuzzyhandle/esp8266hangout,fuzzyhandle/esp8266hangout | ---
+++
@@ -1,4 +1,12 @@
import machine
+
+def have_internet():
+ import urequests
+ try:
+ resp = urequests.request("HEAD", "http://jsonip.com/")
+ return True
+ except:
+ return False
def setntptime(maxretries=10):
# ntptime is a helper module which gets packaged into the firmware |
66d159fb1800b5e55c057316ac53fb62f1eb6b6e | metakernel/utils/kernel.py | metakernel/utils/kernel.py | import pkgutil
import os
def install_kernel_resources(destination):
"""
Copy the resource files to the kernelspec folder.
"""
for filename in ["logo-64x64.png", "logo-32x32.png"]:
data = pkgutil.get_data("metakernel", filename)
with open(os.path.join(destination, filename), "w") as fp:
... | import pkgutil
import os
def install_kernel_resources(destination):
"""
Copy the resource files to the kernelspec folder.
"""
for filename in ["logo-64x64.png", "logo-32x32.png"]:
data = pkgutil.get_data("metakernel", filename)
with open(os.path.join(destination, filename), "wb") as fp:... | Write bytes; make Travis happy | Write bytes; make Travis happy
| Python | bsd-3-clause | Calysto/metakernel | ---
+++
@@ -7,5 +7,5 @@
"""
for filename in ["logo-64x64.png", "logo-32x32.png"]:
data = pkgutil.get_data("metakernel", filename)
- with open(os.path.join(destination, filename), "w") as fp:
+ with open(os.path.join(destination, filename), "wb") as fp:
fp.write(data) |
8db3ee0d6b73b864a91cd3617342138f05175d9d | accounts/models.py | accounts/models.py | # coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver
class UserAccount(models.Model):
"""
A user account. Used to store any information related... | # coding: utf-8
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from registration.signals import user_activated
from django.dispatch import receiver
class UserAccount(models.Model):
"""
A user account. Used to store any information related... | Add __unicode__ method to UserAccount model | Add __unicode__ method to UserAccount model
| Python | agpl-3.0 | coders4help/volunteer_planner,alper/volunteer_planner,klinger/volunteer_planner,pitpalme/volunteer_planner,volunteer-planner/volunteer_planner,pitpalme/volunteer_planner,christophmeissner/volunteer_planner,pitpalme/volunteer_planner,christophmeissner/volunteer_planner,alper/volunteer_planner,flindenberg/volunteer_plann... | ---
+++
@@ -19,6 +19,9 @@
verbose_name_plural = _('user accounts')
+ def __unicode__(self):
+ return u'{}'.format(self.user.username)
+
@receiver(user_activated)
def registration_completed(sender, user, request, **kwargs):
account, created = UserAccount.objects.get_or_create(user=user) |
ec1a25c541770a82953c743f13d525a447f3bd2d | syntacticframes_project/syntacticframes/management/commands/update_members_and_translations.py | syntacticframes_project/syntacticframes/management/commands/update_members_and_translations.py | """
Updates members and translations for all classes
When LVF and LADL mappings change, everything under this change could change.
When a frameset is hidden or shown, everything in that class could change.
When the algorithm changes, everything in VerbeNet could change.
This command ensures that after an algorithmic ... | """
Updates members and translations for all classes
When LVF and LADL mappings change, everything under this change could change.
When a frameset is hidden or shown, everything in that class could change.
When the algorithm changes, everything in VerbeNet could change.
This command ensures that after an algorithmic ... | Include time of update start/end | Include time of update start/end
| Python | mit | aymara/verbenet-editor,aymara/verbenet-editor,aymara/verbenet-editor | ---
+++
@@ -9,6 +9,7 @@
consistent.
"""
+from time import gmtime, strftime
from django.core.management.base import BaseCommand
@@ -16,7 +17,13 @@
class Command(BaseCommand):
def handle(self, *args, **options):
+
+ when = strftime("%d/%m/%Y %H:%M:%S", gmtime())
+ verb_logger.info("{}: St... |
743f4affcd89aa3d9fd37774e2e5f8e05525cb04 | api/sync_wallet.py | api/sync_wallet.py | import urlparse
import os, sys
import json
tools_dir = os.environ.get('TOOLSDIR')
lib_path = os.path.abspath(tools_dir)
sys.path.append(lib_path)
from msc_apps import *
data_dir_root = os.environ.get('DATADIR')
def sync_wallet_response(request_dict):
if not request_dict.has_key('type'):
return (None, 'No field ... | import urlparse
import os, sys
import json
tools_dir = os.environ.get('TOOLSDIR')
lib_path = os.path.abspath(tools_dir)
sys.path.append(lib_path)
from msc_apps import *
data_dir_root = os.environ.get('DATADIR')
def sync_wallet_response(request_dict):
if not request_dict.has_key('type'):
return (None, 'No field ... | Clean up return value for API | Clean up return value for API
| Python | agpl-3.0 | ripper234/omniwallet,maran/omniwallet,maran/omniwallet,Nevtep/omniwallet,FuzzyBearBTC/omniwallet,FuzzyBearBTC/omniwallet,achamely/omniwallet,curtislacy/omniwallet,habibmasuro/omniwallet,OmniLayer/omniwallet,ripper234/omniwallet,habibmasuro/omniwallet,ripper234/omniwallet,Nevtep/omniwallet,habibmasuro/omniwallet,curtisl... | ---
+++
@@ -14,11 +14,11 @@
req_type = request_dict['type'][0].upper()
if req_type == "SYNCWALLET":
- response_data = syncWallets(request_dict['masterWallets'][0])
+ syncWallets(request_dict['masterWallets'][0])
else:
return (None, req_type + ' is not supported')
- response = { 'status': 'OK... |
d81fe16eda36d3a5fa23d163de27bd46f84c4815 | app.py | app.py | from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/')
def webprint():
return(render_template('index.html'))
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| from flask import Flask, render_template
import os
app = Flask(__name__)
@app.route('/')
def webprint():
return 'Hello world!'
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000))
app.run(host='0.0.0.0', port=port)
| Return text message on / | Return text message on /
| Python | mit | fablabjoinville/groselha,fablabjoinville/groselha,fablabjoinville/groselha,fablabjoinville/groselha | ---
+++
@@ -6,7 +6,7 @@
@app.route('/')
def webprint():
- return(render_template('index.html'))
+ return 'Hello world!'
if __name__ == "__main__":
port = int(os.environ.get('PORT', 5000)) |
cfcee83354f4917e719c3ef4236a2644dc98e153 | ophyd/__init__.py | ophyd/__init__.py | import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
from . import *
# Signals
from .signal import (Signal, EpicsSignal, EpicsSignalRO)
# Positioners
from .positioner import Positioner
from .epics_motor import EpicsMotor
from .pv_positioner import (PVPositioner, PVPositioner... | import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
from . import *
# Signals
from .signal import (Signal, EpicsSignal, EpicsSignalRO)
# Positioners
from .positioner import Positioner
from .epics_motor import EpicsMotor
from .pv_positioner import (PVPositioner, PVPositioner... | Add StatusBase to top-level API. | MNT: Add StatusBase to top-level API.
| Python | bsd-3-clause | dchabot/ophyd,dchabot/ophyd | ---
+++
@@ -18,6 +18,7 @@
# Devices
from .scaler import EpicsScaler
from .device import (Device, Component, DynamicDeviceComponent)
+from .ophydobj import StatusBase
from .mca import EpicsMCA, EpicsDXP
# Areadetector-related |
17c90fd954441c2623495e50a2f89790e1ff5489 | projects/tests/test_tools.py | projects/tests/test_tools.py | from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Project access mix... | import sure
from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from accounts.tests.factories import UserFactory
from ..utils import ProjectAccessMixin
from ..models import Project
from . import factories
class ProjectAccessMixinCase(TestCase):
"""Projec... | Use sure in project tools cases | Use sure in project tools cases
| Python | mit | nvbn/coviolations_web,nvbn/coviolations_web | ---
+++
@@ -1,3 +1,4 @@
+import sure
from mock import MagicMock
from django.core.exceptions import PermissionDenied
from django.test import TestCase
@@ -27,15 +28,16 @@
def test_can_access(self):
"""Test can access"""
Project.can_access.return_value = True
- self.assertIsNone(self.mix... |
db08c5ae962c2e66c8ad2e668f530d08934200af | geometry.py | geometry.py | from geom2d import *
l1 = []
for i in range(-5, 6):
l1.append(Point(i, i*i))
l2 = []
for el in l1:
l2.append(Point(el.x, -el.y))
print(l1)
print(l2)
# List comprehension
l1c = [Point(i, i*i) for i in range(-5, 6)]
l2c = [Point(el.x, -el.y) for el in l1c]
print("List comprehension")
print(l1c)
print(l2c)
| from geom2d import *
l1 = list(map(lambda i: Point(i, i*i), range(-5, 6)))
# l2 = list(map(lambda p: Point(p.x, -p.y), l1))
# l2 = list(filter(lambda p: p.x > 0, l1))
l2 = list(filter(lambda p: p.x % 2 == 0, l1))
print(l1)
print(l2)
| Work with lists in functional way (map, filter) | Work with lists in functional way (map, filter)
| Python | apache-2.0 | maciekp85/python-for-testers | ---
+++
@@ -1,22 +1,11 @@
from geom2d import *
-l1 = []
+l1 = list(map(lambda i: Point(i, i*i), range(-5, 6)))
-for i in range(-5, 6):
- l1.append(Point(i, i*i))
+# l2 = list(map(lambda p: Point(p.x, -p.y), l1))
-l2 = []
-
-for el in l1:
- l2.append(Point(el.x, -el.y))
+# l2 = list(filter(lambda p: p.x >... |
98870a8dc7fe51936fcdcdceef3484fa28947eaf | get_data.py | get_data.py | #!/usr/bin/env python
from rajab_roza import RajabRoza
lat = 51.0 + 32.0/60.0
lng = -22.0/60.0
start_year = 1400
end_year = 1500
filename = "london-durations.yml"
if __name__ == '__main__':
rajab_roza = RajabRoza(lat, lng, start_year, end_year)
rajab_roza.get_roza_durations()
rajab_roza.save_to_yaml(file... | #!/usr/bin/env python
from rajab_roza import RajabRoza
lat = 51.0 + 32.0/60.0
lng = -22.0/60.0
start_year = 1400
end_year = 1500
filename = "data/london-durations.yml"
if __name__ == '__main__':
rajab_roza = RajabRoza(lat, lng, start_year, end_year)
rajab_roza.get_roza_durations()
rajab_roza.save_to_yaml... | Correct output filename for data. | Correct output filename for data.
| Python | mit | mygulamali/rajab_roza | ---
+++
@@ -6,7 +6,7 @@
lng = -22.0/60.0
start_year = 1400
end_year = 1500
-filename = "london-durations.yml"
+filename = "data/london-durations.yml"
if __name__ == '__main__':
rajab_roza = RajabRoza(lat, lng, start_year, end_year) |
0636d474764c1dd6f795ebf5c4f73e2a101ae023 | correlations/server.py | correlations/server.py | #!/usr/bin/python3
from flask import Flask, jsonify, request
from funds_correlations import correlations, parse_performances_from_dict
import traceback
app = Flask(__name__)
@app.route("/correlations", methods=['POST'])
def correlation_api():
req_json = request.get_json()
perf_list = parse_performances_from_d... | #!/usr/bin/python3
from flask import Flask, jsonify, request
from funds_correlations import correlations, parse_performances_from_dict
import traceback
app = Flask(__name__)
@app.route("/correlations", methods=['POST'])
def correlation_api():
try:
req_json = request.get_json()
valid_input = True
... | Improve API robustness Case where no JSON is sent | Improve API robustness
Case where no JSON is sent
| Python | apache-2.0 | egenerat/portfolio,egenerat/portfolio,egenerat/portfolio | ---
+++
@@ -7,26 +7,32 @@
@app.route("/correlations", methods=['POST'])
def correlation_api():
- req_json = request.get_json()
- perf_list = parse_performances_from_dict(req_json)
- if len(perf_list) < 2:
- return jsonify({
- 'error': 'not enough valid data'
- }), 400
try:
+... |
2812f11bdc86495dd9ef62b4b45d90335bcbda7d | runtests.py | runtests.py | #!/usr/bin/env python
import os
import sys
from django.conf import settings
try:
from django import setup
except ImportError:
def setup():
pass
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
... | #!/usr/bin/env python
import os
import sys
from django.conf import settings
try:
from django import setup
except ImportError:
def setup():
pass
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
... | Set middleware classes to suppress warning on 1.7+ | Set middleware classes to suppress warning on 1.7+
| Python | bsd-2-clause | mlavin/django-selectable,affan2/django-selectable,affan2/django-selectable,mlavin/django-selectable,mlavin/django-selectable,affan2/django-selectable | ---
+++
@@ -18,6 +18,7 @@
'NAME': ':memory:',
}
},
+ MIDDLEWARE_CLASSES=(),
INSTALLED_APPS=(
'selectable',
), |
aa89bed3502e4a94ab41005dd9265bfee58fd784 | runtests.py | runtests.py | #!/usr/bin/env python
import os
from django.core.management import call_command
if __name__ == '__main__':
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
import django
if hasattr(django, 'setup'):
django.setup()
call_command('test', nomigrations=True)
| #!/usr/bin/env python
import os
from django.core.management import execute_from_command_line
if __name__ == '__main__':
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
execute_from_command_line(['manage.py', 'test', '--nomigrations'])
| Use a higher level command line api | Use a higher level command line api | Python | mit | henriquebastos/django-test-without-migrations,henriquebastos/django-test-without-migrations | ---
+++
@@ -1,14 +1,10 @@
#!/usr/bin/env python
import os
-from django.core.management import call_command
+from django.core.management import execute_from_command_line
if __name__ == '__main__':
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings'
- import django
- if hasattr(django, 'setup'... |
e98201ae47f3af4fe8756c69464986dc524206e5 | corehq/apps/hqwebapp/management/commands/list_waf_allow_patterns.py | corehq/apps/hqwebapp/management/commands/list_waf_allow_patterns.py | import re
from django.core.management import BaseCommand
from django.urls import get_resolver
from corehq.apps.hqwebapp.decorators import waf_allow
class Command(BaseCommand):
def handle(self, *args, **options):
resolver = get_resolver()
for kind, views in waf_allow.views.items():
p... | import re
from django.core.management import BaseCommand
from django.urls import get_resolver
from corehq.apps.hqwebapp.decorators import waf_allow
class Command(BaseCommand):
def handle(self, *args, **options):
resolver = get_resolver()
for kind, views in waf_allow.views.items():
p... | Fix issue: 'URLResolver' object has no attribute 'regex' | Fix issue: 'URLResolver' object has no attribute 'regex'
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | ---
+++
@@ -21,7 +21,7 @@
else:
# @waf_allow(kind)
for urlmatch in resolver.reverse_dict.getlist(view):
- patterns.append(resolver.regex.pattern + urlmatch[1])
+ patterns.append(str(resolver.pattern) + urlmatch[1]... |
04d85784eeeb619e0e273aa0ffb41f12ffeada43 | ureport/polls/migrations/0051_auto_20180316_0912.py | ureport/polls/migrations/0051_auto_20180316_0912.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-16 09:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0050_auto_20170615_1455'),
]
def populate_default_backend(apps, schema_ed... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-16 09:12
from __future__ import unicode_literals
from django.db import migrations, models
from ureport.utils import chunk_list
class Migration(migrations.Migration):
dependencies = [
('polls', '0050_auto_20170615_1455'),
]
def pop... | Update pull results default value in batches | Update pull results default value in batches
| Python | agpl-3.0 | rapidpro/ureport,Ilhasoft/ureport,Ilhasoft/ureport,rapidpro/ureport,Ilhasoft/ureport,rapidpro/ureport,Ilhasoft/ureport,rapidpro/ureport | ---
+++
@@ -3,6 +3,7 @@
from __future__ import unicode_literals
from django.db import migrations, models
+from ureport.utils import chunk_list
class Migration(migrations.Migration):
@@ -13,7 +14,17 @@
def populate_default_backend(apps, schema_editor):
PollResult = apps.get_model("polls", "Pol... |
606feda80b4631f9079021214c7b6078beb9a3f4 | api/v2/views/maintenance_record.py | api/v2/views/maintenance_record.py | import django_filters
from rest_framework import filters
from rest_framework.serializers import ValidationError
from core.models import AtmosphereUser, MaintenanceRecord
from core.query import only_current
from api.permissions import CanEditOrReadOnly
from api.v2.serializers.details import MaintenanceRecordSerialize... | import django_filters
from rest_framework import filters
from rest_framework.serializers import ValidationError
from core.models import AtmosphereUser, MaintenanceRecord
from core.query import only_current
from api.permissions import CanEditOrReadOnly
from api.v2.serializers.details import MaintenanceRecordSerialize... | Add 'DELETE' operation to Maintenance Record | [ATMO-1201] Add 'DELETE' operation to Maintenance Record
| Python | apache-2.0 | CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend | ---
+++
@@ -28,7 +28,7 @@
"""
API endpoint that allows records to be viewed or edited.
"""
- http_method_names = ['get', 'post', 'put', 'patch', 'head', 'options', 'trace']
+ http_method_names = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace']
queryset = MaintenanceRecor... |
65abd52d1bfd54097ca6bd01b1924e6ffcad8840 | pytablewriter/_csv_writer.py | pytablewriter/_csv_writer.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import dataproperty
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
Concrete class of a table writer for CSV format.
:Examples:
:ref:`... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com>
"""
from __future__ import absolute_import
import dataproperty
from ._text_writer import TextTableWriter
class CsvTableWriter(TextTableWriter):
"""
Concrete class of a table writer for CSV format.
:Examples:
:ref:`... | Delete redundant lines of code | Delete redundant lines of code
| Python | mit | thombashi/pytablewriter | ---
+++
@@ -32,9 +32,6 @@
self.is_padding = False
self.is_write_header_separator_row = False
- def _verify_header(self):
- pass
-
def _write_header(self):
if dataproperty.is_empty_list_or_tuple(self.header_list):
return |
a990362d80980b90b04907c0e7717a55c421bf9d | quran_tafseer/serializers.py | quran_tafseer/serializers.py | from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = ... | from django.urls import reverse
from rest_framework import serializers
from .models import Tafseer, TafseerText
class TafseerSerializer(serializers.ModelSerializer):
class Meta:
model = Tafseer
fields = ['id', 'name']
class TafseerTextSerializer(serializers.ModelSerializer):
tafseer_id = ... | Return Ayah's pk instead of number | [FIX] Return Ayah's pk instead of number
| Python | mit | EmadMokhtar/tafseer_api | ---
+++
@@ -16,7 +16,7 @@
tafseer_id = serializers.IntegerField(source='tafseer.id')
tafseer_name = serializers.CharField(source='tafseer.name')
ayah_url = serializers.SerializerMethodField()
- ayah_number = serializers.IntegerField(source='ayah.pk')
+ ayah_number = serializers.IntegerField(sourc... |
cdb55b385074d50a98f87027fd46021d663f9df8 | bin/commands/utils/messages.py | bin/commands/utils/messages.py | from __future__ import print_function
import sys
def error(message, exit=True):
"""Print an error message and optionally exit."""
assert isinstance(message, str), "message must be a str"
assert isinstance(exit, bool), "exit must be a bool"
print("error:", message, file=sys.stderr)
if exit:
... | from __future__ import print_function
import sys
def error(message, exit=True):
"""Print an error message and optionally exit."""
assert isinstance(message, str), "message must be a str"
assert isinstance(exit, bool), "exit must be a bool"
print("error:", message, file=sys.stderr)
if exit:
... | Add warn and usage message options | Add warn and usage message options
| Python | mit | Brickstertwo/git-commands | ---
+++
@@ -14,6 +14,16 @@
sys.exit(1)
+def warn(message):
+ """Print a simple warning message."""
+ info('warn: {}'.format(message), False)
+
+
+def usage(message):
+ """Print a simple usage message."""
+ info('usage: {}'.format(message), False)
+
+
def info(message, quiet=False):
"""P... |
3cc1cb9894fdb1b88a84ad8315669ad2f0858fdb | cloud_logging.py | cloud_logging.py | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Change some errors to go to stderr. | Change some errors to go to stderr.
These non-fatal errors violated GTP protocol.
| Python | apache-2.0 | tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo,tensorflow/minigo | ---
+++
@@ -23,9 +23,9 @@
def configure(project=LOGGING_PROJECT):
if not project:
- print('!! Error: The $LOGGING_PROJECT enviroment '
+ sys.stderr.write('!! Error: The $LOGGING_PROJECT enviroment '
'variable is required in order to set up cloud logging. '
- 'Cloud lo... |
6d13b3b041e3e6cd6089814ad3276a905aa10bc3 | troposphere/fms.py | troposphere/fms.py | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSProperty, AWSObject, Tags
from .validators import json_checker, boolean
class IEMap(AWSProperty):
props = {
'ACCOUNT': ([basestring], False),
}
class Policy(AWSObject... | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSProperty, AWSObject, Tags
from .validators import json_checker, boolean
class IEMap(AWSProperty):
props = {
'ACCOUNT': ([basestring], False),
'ORGUNIT': ([basestrin... | Update AWS::FMS::Policy per 2020-06-18 changes | Update AWS::FMS::Policy per 2020-06-18 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -11,6 +11,7 @@
class IEMap(AWSProperty):
props = {
'ACCOUNT': ([basestring], False),
+ 'ORGUNIT': ([basestring], False),
}
|
fe4cc596e65f6dc5ec7f99d40f7346143b695633 | slackbot.py | slackbot.py | #! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
url = "https://{}.slack.... | #! /usr/bin/env python2.7
import requests
class Slackbot(object):
def __init__(self, slack_name, token):
self.slack_name = slack_name
self.token = token
assert self.token, "Token should not be blank"
self.url = self.sb_url()
def sb_url(self):
url = "https://{}.slack.... | Fix unicode encoding of Slack message posts | Fix unicode encoding of Slack message posts
| Python | apache-2.0 | TheConnMan/destalinator,royrapoport/destalinator,randsleadershipslack/destalinator,royrapoport/destalinator,TheConnMan/destalinator,randsleadershipslack/destalinator,underarmour/destalinator | ---
+++
@@ -24,5 +24,5 @@
if channel[0] == '#':
channel = channel[1:]
nurl = self.url + "?token={}&channel=%23{}".format(self.token, channel)
- p = requests.post(nurl, statement)
+ p = requests.post(nurl, data=statement.encode('utf-8'))
return p.status_code |
29c977a7f7293f1ce45f393a4c8464bbb9691f9e | linkedevents/urls.py | linkedevents/urls.py | from django.conf.urls import url, include
from django.views.generic import RedirectView
from .api import LinkedEventsAPIRouter
from django.contrib import admin
admin.autodiscover()
api_router = LinkedEventsAPIRouter()
urlpatterns = [
url(r'^(?P<version>(v0.1|v1))/', include(api_router.urls)),
url(r'^admin... | from django.core.urlresolvers import reverse
from django.conf.urls import url, include
from django.views.generic import RedirectView
from .api import LinkedEventsAPIRouter
from django.contrib import admin
admin.autodiscover()
api_router = LinkedEventsAPIRouter()
class RedirectToAPIRootView(RedirectView):
perma... | Make redirect-to-API work even with URL prefix | Make redirect-to-API work even with URL prefix
| Python | mit | aapris/linkedevents,aapris/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,tuomas777/linkedevents,tuomas777/linkedevents,aapris/linkedevents,City-of-Helsinki/linkedevents | ---
+++
@@ -1,3 +1,4 @@
+from django.core.urlresolvers import reverse
from django.conf.urls import url, include
from django.views.generic import RedirectView
@@ -9,10 +10,15 @@
api_router = LinkedEventsAPIRouter()
+class RedirectToAPIRootView(RedirectView):
+ permanent = False
+
+ def get_redirect_url(... |
63ee144892ed0e740b87cb87895cf07d78b87d1f | lib/slack.py | lib/slack.py | from lib.config import Config
from slackclient import SlackClient
class Tubey():
def __init__(self, **kwargs):
### Cache the client in memory ###
self._client = None
def get_client(self):
### Fetch a cached slack client or create one and return it ###
if self._client is not No... | from lib.config import Config
from slackclient import SlackClient
class Tubey():
def __init__(self, **kwargs):
# cache the client in memory
self._client = None
def send_message(self, message):
raise NotImplemented
def get_client(self):
### Fetch a cached slack client or c... | Revert "Implement send message functionality" | Revert "Implement send message functionality"
| Python | mit | ImShady/Tubey | ---
+++
@@ -4,8 +4,11 @@
class Tubey():
def __init__(self, **kwargs):
- ### Cache the client in memory ###
+ # cache the client in memory
self._client = None
+
+ def send_message(self, message):
+ raise NotImplemented
def get_client(self):
### Fetch a cached sl... |
6e1a1c2ac4eaa32e0af4fb9349844fe3ce7df7c0 | matching/__init__.py | matching/__init__.py | import os
import logging
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
a... | import os
import logging
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from .health import Health
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
from werkzeug.contrib.fixers import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app)
logging.basicConfig(level=logging.INFO... | Add proxy fix as in lr this will run with reverse proxy | Add proxy fix as in lr this will run with reverse proxy
| Python | mit | LandRegistry-Attic/matching-alpha,LandRegistry-Attic/matching-alpha,LandRegistry-Attic/matching-alpha | ---
+++
@@ -9,6 +9,9 @@
app = Flask(__name__)
app.config.from_object(os.environ.get('SETTINGS'))
+
+from werkzeug.contrib.fixers import ProxyFix
+app.wsgi_app = ProxyFix(app.wsgi_app)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__) |
4eab1fb42f58d6203a0862aa9caf304193d3442b | libcloud/common/maxihost.py | libcloud/common/maxihost.py | from libcloud.utils.py3 import httplib
from libcloud.common.types import InvalidCredsError
from libcloud.common.base import JsonResponse
from libcloud.common.base import ConnectionKey
class MaxihostResponse(JsonResponse):
valid_response_codes = [httplib.OK, httplib.ACCEPTED, httplib.CREATED,
... | from libcloud.utils.py3 import httplib
from libcloud.common.types import InvalidCredsError
from libcloud.common.base import JsonResponse
from libcloud.common.base import ConnectionKey
class MaxihostResponse(JsonResponse):
valid_response_codes = [httplib.OK, httplib.ACCEPTED, httplib.CREATED,
... | Add Accept header to use version 1.1 | Add Accept header to use version 1.1
| Python | apache-2.0 | ByteInternet/libcloud,andrewsomething/libcloud,ByteInternet/libcloud,Kami/libcloud,apache/libcloud,andrewsomething/libcloud,mistio/libcloud,Kami/libcloud,mistio/libcloud,andrewsomething/libcloud,apache/libcloud,apache/libcloud,ByteInternet/libcloud,Kami/libcloud,mistio/libcloud | ---
+++
@@ -40,4 +40,5 @@
"""
headers['Authorization'] = 'Bearer %s' % (self.key)
headers['Content-Type'] = 'application/json'
+ headers['Accept']: 'application/vnd.maxihost.v1.1+json'
return headers |
6c4081f6c1fde79e9f14da98f0d670a8bdef8e13 | pipeline/settings/production.py | pipeline/settings/production.py | from .base import *
DEBUG = False
try:
from .local import *
except ImportError:
pass
| from .base import *
DEBUG = False
WAGTAIL_ENABLE_UPDATE_CHECK = False
try:
from .local import *
except ImportError:
pass
| Disable Wagtail update check in prod | Disable Wagtail update check in prod
| Python | mit | thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline | ---
+++
@@ -1,6 +1,8 @@
from .base import *
DEBUG = False
+
+WAGTAIL_ENABLE_UPDATE_CHECK = False
try:
from .local import * |
f576004e7d1352c7e8c1e203ae0a8b6769ce1b08 | cla_backend/apps/core/views.py | cla_backend/apps/core/views.py | from django.views import defaults
from sentry_sdk import capture_message
def page_not_found(*args, **kwargs):
capture_message("Page not found", level="error")
return defaults.page_not_found(*args, **kwargs)
| from django.views import defaults
from sentry_sdk import capture_message, push_scope
def page_not_found(request, *args, **kwargs):
with push_scope() as scope:
scope.set_tag("type", "404")
scope.set_extra("path", request.path)
capture_message("Page not found", level="error")
return de... | Set some event data on 404 logging | Set some event data on 404 logging
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend | ---
+++
@@ -1,8 +1,12 @@
from django.views import defaults
-from sentry_sdk import capture_message
+from sentry_sdk import capture_message, push_scope
-def page_not_found(*args, **kwargs):
- capture_message("Page not found", level="error")
+def page_not_found(request, *args, **kwargs):
+ with push_scope() ... |
55c7681304d66ad076372be7aa8f319baef153eb | polyaxon/runner/management/commands/clean_project_jobs.py | polyaxon/runner/management/commands/clean_project_jobs.py | from django.core.management import BaseCommand
from django.db import ProgrammingError
from django.db.models import Q
from projects.models import Project
from runner.schedulers import notebook_scheduler, tensorboard_scheduler
class Command(BaseCommand):
@staticmethod
def _clean():
for project in Proje... | from django.core.management import BaseCommand
from django.db import ProgrammingError
from django.db.models import Q
from projects.models import Project
from runner.schedulers import notebook_scheduler, tensorboard_scheduler
class Command(BaseCommand):
@staticmethod
def _clean():
filters = Q(tensorbo... | Update clean project jobs command | Update clean project jobs command
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | ---
+++
@@ -9,7 +9,8 @@
class Command(BaseCommand):
@staticmethod
def _clean():
- for project in Project.objects.exclude(Q(tensorboard=None) | Q(notebook=None)):
+ filters = Q(tensorboard_jobs=None) | Q(notebook_jobs=None)
+ for project in Project.objects.exclude(filters):
... |
1aa121daa3c99849173d5cd4c6a80d6bf94f5186 | saleor/attribute/__init__.py | saleor/attribute/__init__.py | class AttributeInputType:
"""The type that we expect to render the attribute's values as."""
DROPDOWN = "dropdown"
MULTISELECT = "multiselect"
FILE = "file"
REFERENCE = "reference"
CHOICES = [
(DROPDOWN, "Dropdown"),
(MULTISELECT, "Multi Select"),
(FILE, "File"),
... | class AttributeInputType:
"""The type that we expect to render the attribute's values as."""
DROPDOWN = "dropdown"
MULTISELECT = "multiselect"
FILE = "file"
REFERENCE = "reference"
CHOICES = [
(DROPDOWN, "Dropdown"),
(MULTISELECT, "Multi Select"),
(FILE, "File"),
... | Add info about required updates in AttributeEntityType | Add info about required updates in AttributeEntityType
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | ---
+++
@@ -24,7 +24,12 @@
class AttributeEntityType:
- """Type of a reference entity type. Must match the name of the graphql type."""
+ """Type of a reference entity type. Must match the name of the graphql type.
+
+ After adding new value, `REFERENCE_VALUE_NAME_MAPPING`
+ and `ENTITY_TYPE_TO_MODEL... |
ceb848021d5323b5bad8518ac7ed850a51fc89ca | raco/myrial/myrial_test.py | raco/myrial/myrial_test.py |
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parser = parser.Parser()
self.processor ... |
import collections
import math
import unittest
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
from raco.myrialang import compile_to_json
class MyrialTestCase(unittest.TestCase):
def setUp(self):
self.db = raco.fakedb.FakeDatabase()
self.parse... | Add compile_to_json invocation in Myrial test fixture | Add compile_to_json invocation in Myrial test fixture
| Python | bsd-3-clause | uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco,uwescience/raco | ---
+++
@@ -6,6 +6,7 @@
import raco.fakedb
import raco.myrial.interpreter as interpreter
import raco.myrial.parser as parser
+from raco.myrialang import compile_to_json
class MyrialTestCase(unittest.TestCase):
@@ -23,7 +24,10 @@
plan = self.processor.get_logical_plan()
else:
... |
8dba7c06d1f6fd6365c7150d0934eb055e1b2fd3 | inthe_am/taskmanager/middleware.py | inthe_am/taskmanager/middleware.py | from inthe_am.taskmanager.models import TaskStore
class AuthenticationTokenMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if hasattr(request, 'user') and request.user.is_authent... | from inthe_am.taskmanager.models import TaskStore
class AuthenticationTokenMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if hasattr(request, 'user') and request.user.is_authent... | Delete cookie instead of setting to empty string. | Delete cookie instead of setting to empty string.
| Python | agpl-3.0 | coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am,coddingtonbear/inthe.am | ---
+++
@@ -12,6 +12,6 @@
store = TaskStore.get_for_user(request.user)
response.set_cookie('authentication_token', store.api_key.key)
else:
- response.set_cookie('authentication_token', '')
+ response.delete_cookie('authentication_token')
return resp... |
3f5a6dcd622d7b1c890ced67468ecebd02b1806f | mastertickets/db_default.py | mastertickets/db_default.py | # Created by Noah Kantrowitz on 2007-07-04.
# Copyright (c) 2007 Noah Kantrowitz. All rights reserved.
from trac.db import Table, Column
name = 'mastertickets'
version = 2
tables = [
Table('mastertickets', key=('source','dest'))[
Column('source', type='integer'),
Column('dest', type='integer'),
... | # Created by Noah Kantrowitz on 2007-07-04.
# Copyright (c) 2007 Noah Kantrowitz. All rights reserved.
from trac.db import Table, Column
name = 'mastertickets'
version = 2
tables = [
Table('mastertickets', key=('source','dest'))[
Column('source', type='integer'),
Column('dest', type='integer'),
... | Fix the migration to actual work. | Fix the migration to actual work. | Python | bsd-3-clause | SpamExperts/trac-masterticketsplugin,SpamExperts/trac-masterticketsplugin,SpamExperts/trac-masterticketsplugin | ---
+++
@@ -14,9 +14,9 @@
def convert_to_int(data):
"""Convert both source and dest in the mastertickets table to ints."""
- for row in data['mastertickets'][1]:
- for i, (n1, n2) in enumerate(row):
- row[i] = [int(n1), int(n2)]
+ rows = data['mastertickets'][1]
+ for i, (n1, n2) in... |
9d9825d7f08c7cc3c078f9b43b3a67019335f75d | nodeconductor/core/models.py | nodeconductor/core/models.py | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from uuidfield import UUIDField
class UuidM... | from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from uuidfield import UUIDField
class UuidM... | Increase size of the alternative field | Increase size of the alternative field
- NC-87
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | ---
+++
@@ -21,12 +21,13 @@
class User(UuidMixin, AbstractUser):
- alternative_name = models.CharField(_('alternative name'), max_length=40, blank=True)
+ alternative_name = models.CharField(_('alternative name'), max_length=60, blank=True)
civil_number = models.CharField(_('civil number'), max_length... |
a662eded2841b87ccbccdd6dfb21315725d0a0c5 | python/pyspark_llap/__init__.py | python/pyspark_llap/__init__.py | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | Add aliases for HIVE_WAREHOUSE_CONNECTOR, DATAFRAME_TO_STREAM and STREAM_TO_STREAM | Add aliases for HIVE_WAREHOUSE_CONNECTOR, DATAFRAME_TO_STREAM and STREAM_TO_STREAM
| Python | apache-2.0 | hortonworks-spark/spark-llap,hortonworks-spark/spark-llap,hortonworks-spark/spark-llap | ---
+++
@@ -17,4 +17,15 @@
from pyspark_llap.sql.session import HiveWarehouseSession
-__all__ = ['HiveWarehouseSession']
+# These are aliases so that importing this module exposes those attributes below directly.
+DATAFRAME_TO_STREAM = HiveWarehouseSession.DATAFRAME_TO_STREAM
+HIVE_WAREHOUSE_CONNECTOR = HiveWare... |
5a7291b9c305445aebe77ef020017ac9cffd35e2 | pythonparser/test/test_utils.py | pythonparser/test/test_utils.py | # coding:utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
unicode = type("")
class BytesOnly(bytes):
def __new__(cls, s):
if isinstance(s, unicode):
s = s.encode()
return bytes.__new__(BytesOnly, s)
def __eq__(self, o):
r... | # coding:utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
unicode = type("")
class BytesOnly(bytes):
def __new__(cls, s):
if isinstance(s, unicode):
s = s.encode()
return bytes.__new__(BytesOnly, s)
def __eq__(self, o):
return isin... | Fix indentation error in LongOnly.__ne__() | Fix indentation error in LongOnly.__ne__()
Also follow Python porting best practice [__use feature detection instead of version detection__](https://docs.python.org/3/howto/pyporting.html#use-feature-detection-instead-of-version-detection). | Python | mit | m-labs/pythonparser | ---
+++
@@ -1,7 +1,7 @@
# coding:utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
-import sys
+
unicode = type("")
@@ -24,12 +24,12 @@
def __ne__(self, o):
return not self == o
-if sys.version_info >= (3,):
- LongOnly = int
-else:
- class LongOnly... |
d6b801a6f327d2a87266cca9ada780ba2c9c9309 | skylines/lib/helpers/__init__.py | skylines/lib/helpers/__init__.py | # -*- coding: utf-8 -*-
"""WebHelpers used in SkyLines."""
from __future__ import absolute_import
import datetime
import simplejson as json
from urllib import urlencode
from tg import flash
from webhelpers import date, feedgenerator, html, number, misc, text
from .string import *
from .country import *
from skylin... | # -*- coding: utf-8 -*-
"""WebHelpers used in SkyLines."""
from __future__ import absolute_import
import datetime
import simplejson as json
from urllib import urlencode
from flask import flash
from webhelpers import date, feedgenerator, html, number, misc, text
from .string import *
from .country import *
from sky... | Use flask.flash instead of tg.flash | lib/helpers: Use flask.flash instead of tg.flash
| Python | agpl-3.0 | TobiasLohner/SkyLines,snip/skylines,Turbo87/skylines,skylines-project/skylines,Turbo87/skylines,Harry-R/skylines,skylines-project/skylines,RBE-Avionik/skylines,kerel-fs/skylines,RBE-Avionik/skylines,Harry-R/skylines,Harry-R/skylines,Harry-R/skylines,RBE-Avionik/skylines,skylines-project/skylines,Turbo87/skylines,snip/s... | ---
+++
@@ -8,7 +8,7 @@
import simplejson as json
from urllib import urlencode
-from tg import flash
+from flask import flash
from webhelpers import date, feedgenerator, html, number, misc, text
from .string import * |
c0549cc670af0735753e08c2c375d32989f04c9c | shopify_python/__init__.py | shopify_python/__init__.py | # Copyright (c) 2017 "Shopify inc." All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found in the LICENSE file.
from __future__ import unicode_literals
from pylint import lint
from shopify_python import google_styleguide
from shopify_python import shopify_styleguide
__ver... | # Copyright (c) 2017 "Shopify inc." All rights reserved.
# Use of this source code is governed by a MIT-style license that can be found in the LICENSE file.
from __future__ import unicode_literals
from pylint import lint
from shopify_python import google_styleguide
from shopify_python import shopify_styleguide
__ver... | Increase version number to 0.2.0 | Increase version number to 0.2.0
| Python | mit | Shopify/shopify_python | ---
+++
@@ -7,7 +7,7 @@
from shopify_python import shopify_styleguide
-__version__ = '0.1.2'
+__version__ = '0.2.0'
def register(linter): # type: (lint.PyLinter) -> None |
57c34cae582764b69bb32faa712110a46df69dde | chaser/__init__.py | chaser/__init__.py | __version__ = "0.1"
| __version__ = "0.1"
import requests
import io
import tarfile
import ccr
def get_source_files(pkgname, workingdir):
"""Download the source tarball and extract it"""
r = requests.get(ccr.getpkgurl(pkgname))
tar = tarfile.open(mode='r', fileobj=io.BytesIO(r.content))
tar.extractall(workingdir)
| Add initial function for get_source_files | Add initial function for get_source_files
| Python | bsd-3-clause | rshipp/chaser,rshipp/chaser | ---
+++
@@ -1 +1,13 @@
__version__ = "0.1"
+
+import requests
+import io
+import tarfile
+
+import ccr
+
+def get_source_files(pkgname, workingdir):
+ """Download the source tarball and extract it"""
+ r = requests.get(ccr.getpkgurl(pkgname))
+ tar = tarfile.open(mode='r', fileobj=io.BytesIO(r.content))
+ ... |
b16b701f6ad80d0df27ab6ea1d9f115a6e2b9106 | pymatgen/__init__.py | pymatgen/__init__.py | __author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, " + \
"Geoffroy Hautier, William Davidson Richard, Dan Gunter, " + \
"Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jul 27, 2012"
__version__ = "2.1.2"
"""
Useful aliases for commonly used objects and modules.
"""... | __author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, " + \
"Geoffroy Hautier, William Davidson Richard, Dan Gunter, " + \
"Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jul 27, 2012"
__version__ = "2.1.3dev"
"""
Useful aliases for commonly used objects and modules.
... | Increase minor version number + dev. | Increase minor version number + dev.
Former-commit-id: 44023123016583dcb692ce23c19978e6f5d90abd [formerly 01b7fa7fe0778c195d9f75d35d43618691778ef8]
Former-commit-id: a96aa4b8265bf7b15143879b0a3b98e30a9e5953 | Python | mit | blondegeek/pymatgen,tallakahath/pymatgen,dongsenfo/pymatgen,mbkumar/pymatgen,vorwerkc/pymatgen,mbkumar/pymatgen,johnson1228/pymatgen,setten/pymatgen,johnson1228/pymatgen,tschaume/pymatgen,davidwaroquiers/pymatgen,fraricci/pymatgen,dongsenfo/pymatgen,blondegeek/pymatgen,aykol/pymatgen,richardtran415/pymatgen,dongsenfo/p... | ---
+++
@@ -2,7 +2,7 @@
"Geoffroy Hautier, William Davidson Richard, Dan Gunter, " + \
"Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jul 27, 2012"
-__version__ = "2.1.2"
+__version__ = "2.1.3dev"
"""
Useful aliases for commonly used objects and modules. |
19e84f0c528fd1c19dba709972f31343284c0a40 | pymatgen/__init__.py | pymatgen/__init__.py | __author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, Geoffroy Hautier, Will Richards, Dan Gunter, Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jun 28, 2012"
__version__ = "2.0.0"
"""
Useful aliases for commonly used objects and modules.
"""
from pymatgen.core.periodic_table import Element, ... | __author__ = "Shyue Ping Ong, Anubhav Jain, Michael Kocher, Geoffroy Hautier, Will Richards, Dan Gunter, Shreyas Cholia, Vincent L Chevrier, Rickard Armiento"
__date__ = "Jun 28, 2012"
__version__ = "2.0.0"
"""
Useful aliases for commonly used objects and modules.
"""
from pymatgen.core.periodic_table import Element, ... | Add an alias to file_open_zip_aware as openz. | Add an alias to file_open_zip_aware as openz.
Former-commit-id: 97796b7a5593858b2fc15c8009658926afa3eda0 [formerly 1ce26a0b0cbddb49047da0f8bac8214fb298c646]
Former-commit-id: 7bdb412108a247f3ebc9d3d9906f03c222178449 | Python | mit | gVallverdu/pymatgen,richardtran415/pymatgen,Bismarrck/pymatgen,fraricci/pymatgen,aykol/pymatgen,gpetretto/pymatgen,johnson1228/pymatgen,mbkumar/pymatgen,dongsenfo/pymatgen,gVallverdu/pymatgen,blondegeek/pymatgen,aykol/pymatgen,vorwerkc/pymatgen,dongsenfo/pymatgen,nisse3000/pymatgen,czhengsci/pymatgen,setten/pymatgen,gV... | ---
+++
@@ -10,3 +10,4 @@
from pymatgen.core.lattice import Lattice
from pymatgen.serializers.json_coders import PMGJSONEncoder, PMGJSONDecoder
from pymatgen.electronic_structure.core import Spin, Orbital
+from pymatgen.util.io_utils import file_open_zip_aware as openz |
5753ecdcb71ea3b64e0fb902cf873dfff124160d | skcode/utility/__init__.py | skcode/utility/__init__.py | """
SkCode utilities library.
"""
# Auto paragraphs utility
from .paragraphs import (PARAGRAPH_NODE_NAME,
ParagraphTagOptions,
make_paragraphs)
# TODO replace cosmetic utility (maybe mixin for postrender callback instead?)
# TODO replace smiley utility (maybe mixin fo... | """
SkCode utilities library.
"""
# Auto paragraphs utilities
from .paragraphs import (PARAGRAPH_NODE_NAME,
ParagraphTagOptions,
make_paragraphs)
# TODO replace cosmetic utility (maybe mixin for postrender callback instead?)
# TODO replace smiley utility (maybe mixin ... | Update utility module friendly imports. | Update utility module friendly imports.
| Python | agpl-3.0 | TamiaLab/PySkCode | ---
+++
@@ -2,7 +2,7 @@
SkCode utilities library.
"""
-# Auto paragraphs utility
+# Auto paragraphs utilities
from .paragraphs import (PARAGRAPH_NODE_NAME,
ParagraphTagOptions,
make_paragraphs)
@@ -11,7 +11,17 @@
# TODO replace smiley utility (maybe mixin for ... |
b8f67c96febd1f7bc2ce1e87f1df0a468faddb87 | src/taskmaster/util.py | src/taskmaster/util.py | """
taskmaster.util
~~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
def import_target(target, default=None):
"""
>>> import_target('foo.bar:blah', 'get_jobs')
<function foo.bar.blah>
>>> import_target('foo.bar', 'get_jobs')
<function f... | """
taskmaster.util
~~~~~~~~~~~~~~~
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
import imp
import sys
from os.path import exists
def import_target(target, default=None):
"""
>>> import_target('foo.bar:blah', 'get_jobs')
<function foo.bar.blah>
>>> imp... | Allow targets to be specified as files | Allow targets to be specified as files
| Python | apache-2.0 | alex/taskmaster,dcramer/taskmaster | ---
+++
@@ -5,6 +5,9 @@
:copyright: (c) 2010 DISQUS.
:license: Apache License 2.0, see LICENSE for more details.
"""
+import imp
+import sys
+from os.path import exists
def import_target(target, default=None):
@@ -17,15 +20,30 @@
>>> import_target('foo.bar:get_jobs')
<function foo.bar.get_jobs>
+
... |
b5cb4fe7abaa9fe1a4c387148af6ee494f69bd07 | astropy/nddata/convolution/tests/test_make_kernel.py | astropy/nddata/convolution/tests/test_make_kernel.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from numpy.testing import assert_allclose
from ....tests.helper import pytest
from ..make_kernel import make_kernel
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
@pytest.mark.skipif('not HAS_SCI... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
from ....tests.compat import assert_allclose
from ....tests.helper import pytest
from ..make_kernel import make_kernel
try:
import scipy
HAS_SCIPY = True
except ImportError:
HAS_SCIPY = False
@pytest.mark.skipif('not HAS_... | Fix compatibility with Numpy 1.4.1 | Fix compatibility with Numpy 1.4.1 | Python | bsd-3-clause | AustereCuriosity/astropy,MSeifert04/astropy,pllim/astropy,DougBurke/astropy,mhvk/astropy,larrybradley/astropy,kelle/astropy,pllim/astropy,funbaker/astropy,stargaser/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,saimn/astropy,lpsinger/astropy,aleksandr-bakanov/astropy,joergdietrich/astropy,AustereCuriosity/... | ---
+++
@@ -1,7 +1,7 @@
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import numpy as np
-from numpy.testing import assert_allclose
+from ....tests.compat import assert_allclose
from ....tests.helper import pytest
from ..make_kernel import make_kernel |
38b236c9fb0f944b41b6300963fbf5e67d0f3fe7 | mwstools/requesters/utils.py | mwstools/requesters/utils.py | import os
from mws.mws import DictWrapper
requesters_dir = os.path.dirname(os.path.abspath(__file__))
responses_dir = os.path.join(requesters_dir, 'responses')
def write_response(response, fname):
with open(os.path.join(responses_dir, fname), 'wb') as f:
if isinstance(response, DictWrapper):
... | import os
from mws.mws import DictWrapper
requesters_dir = os.path.dirname(os.path.abspath(__file__))
responses_dir = os.path.join(requesters_dir, 'responses')
def write_response(response, fname):
return
with open(os.path.join(responses_dir, fname), 'wb') as f:
if isinstance(response, DictWrapper):
... | Write response now returns None since after packaging, the code becomes unusable | Write response now returns None since after packaging, the code becomes unusable
| Python | unlicense | ziplokk1/python-amazon-mws-tools | ---
+++
@@ -7,6 +7,7 @@
def write_response(response, fname):
+ return
with open(os.path.join(responses_dir, fname), 'wb') as f:
if isinstance(response, DictWrapper):
f.write(response.original) |
13ad993a0ca542d5b7e0901afe4c889c18deff5f | source/services/tmdb_service.py | source/services/tmdb_service.py | import os
import requests
class TmdbService:
__TMDB_API = 'https://api.themoviedb.org/3/movie/'
__IMAGE_URL = 'https://image.tmdb.org/t/p/w396/'
def __init__(self, movie_id):
self.id = movie_id
def get_artwork(self):
api_key = os.environ.get('TMDB_API_KEY')
payload = {'api_k... | import os
import requests
class TmdbService:
__TMDB_API = 'https://api.themoviedb.org/3/movie/'
__IMAGE_URL = 'https://image.tmdb.org/t/p/w396'
def __init__(self, movie_id):
self.id = movie_id
def get_artwork(self):
api_key = os.environ.get('TMDB_API_KEY')
payload = {'api_ke... | Remove extra slash from url (poster url returned from api is preceded by one) | Remove extra slash from url (poster url returned from api is preceded by one)
| Python | mit | jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu | ---
+++
@@ -5,7 +5,7 @@
class TmdbService:
__TMDB_API = 'https://api.themoviedb.org/3/movie/'
- __IMAGE_URL = 'https://image.tmdb.org/t/p/w396/'
+ __IMAGE_URL = 'https://image.tmdb.org/t/p/w396'
def __init__(self, movie_id):
self.id = movie_id |
0a3eb4b966dff69cbe582c60bf4444facb4b683d | tcconfig/_tc_command_helper.py | tcconfig/_tc_command_helper.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import subprocrunner as spr
from ._common import find_bin_path
from ._const import TcSubCommand
from ._error import NetworkInterfaceNotFoundError
def get_tc_base_comma... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
import subprocrunner as spr
from ._common import find_bin_path
from ._const import TcSubCommand
from ._error import NetworkInterfaceNotFoundError
def get_tc_base_comma... | Change to avoid a DeprecationWarning | Change to avoid a DeprecationWarning
| Python | mit | thombashi/tcconfig,thombashi/tcconfig | ---
+++
@@ -14,7 +14,7 @@
def get_tc_base_command(tc_subcommand):
- if tc_subcommand not in TcSubCommand:
+ if not isinstance(tc_subcommand, TcSubCommand):
raise ValueError("the argument must be a TcSubCommand value")
return "{:s} {:s}".format(find_bin_path("tc"), tc_subcommand.value) |
42cb96833b71365745aa2a5a741bfe5eeb506098 | statdyn/figures/colour.py | statdyn/figures/colour.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com>
#
# Distributed under terms of the MIT license.
"""Create functions to colourize figures."""
import logging
import numpy as np
from hsluv import hpluv_to_hex
logger = logging.getLogger(__name_... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Malcolm Ramsay <malramsay64@gmail.com>
#
# Distributed under terms of the MIT license.
"""Create functions to colourize figures."""
import logging
import numpy as np
from hsluv import hpluv_to_hex
from ..analysis.order import get_z... | Revert deletion of clean_orientation function | Revert deletion of clean_orientation function
The clean_orientation function is needed for the active configuration
plot. I am yet to change that to using the plot function.
| Python | mit | malramsay64/MD-Molecules-Hoomd,malramsay64/MD-Molecules-Hoomd | ---
+++
@@ -13,11 +13,25 @@
import numpy as np
from hsluv import hpluv_to_hex
+from ..analysis.order import get_z_orientation
+
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
HEX_VALUES_DARK = np.array([hpluv_to_hex((value, 85, 65)) for value in range(360)])
HEX_VALUES_LIGHT = np.array(... |
5a3a91fe075aa6d0c29cccb3b9bdfc5b40e3dba9 | leapp/libraries/stdlib/__init__.py | leapp/libraries/stdlib/__init__.py | """
:py:mod:`leapp.libraries.stdlib`
represents a location for functions that otherwise would be defined multiple times across leapp actors
and at the same time, they are really useful for other actors.
"""
import six
import subprocess
import os
def call(args, split=True):
"""
Call an external program, captur... | """
:py:mod:`leapp.libraries.stdlib`
represents a location for functions that otherwise would be defined multiple times across leapp actors
and at the same time, they are really useful for other actors.
"""
import six
import subprocess
import os
from leapp.libraries.stdlib import api
def call(args, split=True):
... | Make api directly available in stdlib | stdlib: Make api directly available in stdlib
| Python | lgpl-2.1 | leapp-to/prototype,leapp-to/prototype,leapp-to/prototype,leapp-to/prototype | ---
+++
@@ -6,6 +6,8 @@
import six
import subprocess
import os
+
+from leapp.libraries.stdlib import api
def call(args, split=True): |
931d6e4f4ce2cf0d3ea53a3e18ac050e2004741e | splunk_handler/__init__.py | splunk_handler/__init__.py | import datetime
import json
import logging
import socket
import traceback
from threading import Thread
from splunklib import client
_client = None
class SplunkFilter(logging.Filter):
"""
A logging filter for Splunk's debug logs on the root logger to avoid recursion
"""
def filter(self, record):
... | import logging
import socket
import traceback
from threading import Thread
from splunklib import client
_client = None
class SplunkFilter(logging.Filter):
"""
A logging filter for Splunk's debug logs on the root logger to avoid recursion
"""
def filter(self, record):
return not (record.modu... | Remove a couple useless imports | Remove a couple useless imports
| Python | mit | zach-taylor/splunk_handler,sullivanmatt/splunk_handler | ---
+++
@@ -1,5 +1,3 @@
-import datetime
-import json
import logging
import socket
import traceback |
10b0d6102b391f489e98fd1c2e08b766e77c87e9 | osbrain/logging.py | osbrain/logging.py | import os
from .core import Agent
from .core import Proxy
def pyro_log():
os.environ["PYRO_LOGFILE"] = "pyro_osbrain.log"
os.environ["PYRO_LOGLEVEL"] = "DEBUG"
def log_handler(agent, message, topic):
# TODO: handle INFO, ERROR... differently?
agent.log_history.append(message)
def run_logger(name, ... | import os
from .core import Agent
from .core import Proxy
from .core import BaseAgent
from .core import run_agent
def pyro_log():
os.environ["PYRO_LOGFILE"] = "pyro_osbrain.log"
os.environ["PYRO_LOGLEVEL"] = "DEBUG"
class Logger(BaseAgent):
def on_init(self):
self.log_history = []
handle... | Allow Logger to be subclassed and modified more easily | Allow Logger to be subclassed and modified more easily
| Python | apache-2.0 | opensistemas-hub/osbrain | ---
+++
@@ -1,6 +1,8 @@
import os
from .core import Agent
from .core import Proxy
+from .core import BaseAgent
+from .core import run_agent
def pyro_log():
@@ -8,12 +10,21 @@
os.environ["PYRO_LOGLEVEL"] = "DEBUG"
-def log_handler(agent, message, topic):
- # TODO: handle INFO, ERROR... differently?... |
e582ef07d4b9f537e31d31c1546df870a2bd361c | tests/plugins/async_plugin/asyncplugin.py | tests/plugins/async_plugin/asyncplugin.py | from senpy.plugins import AnalysisPlugin
import multiprocessing
class AsyncPlugin(AnalysisPlugin):
def _train(self, process_number):
return process_number
def _do_async(self, num_processes):
with multiprocessing.Pool(processes=num_processes) as pool:
values = pool.map(self._train... | from senpy.plugins import AnalysisPlugin
import multiprocessing
def _train(process_number):
return process_number
class AsyncPlugin(AnalysisPlugin):
def _do_async(self, num_processes):
pool = multiprocessing.Pool(processes=num_processes)
values = pool.map(_train, range(num_processes))
... | Fix multiprocessing tests in python2.7 | Fix multiprocessing tests in python2.7
Closes #28 for python 2.
Apparently, process pools are not contexts in python 2.7.
On the other hand, in py2 you cannot pickle instance methods, so
you have to implement Pool tasks as independent functions.
| Python | apache-2.0 | gsi-upm/senpy,gsi-upm/senpy,gsi-upm/senpy | ---
+++
@@ -3,13 +3,15 @@
import multiprocessing
+def _train(process_number):
+ return process_number
+
+
class AsyncPlugin(AnalysisPlugin):
- def _train(self, process_number):
- return process_number
+ def _do_async(self, num_processes):
+ pool = multiprocessing.Pool(processes=num_proces... |
1a534a3ac6ab1617e9d48e84ce34c0b482730e4d | pritunl_node/call_buffer.py | pritunl_node/call_buffer.py | from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiter = None
self.queue = collections.deque(maxlen=CALL_QUEUE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback):
self.stop_waiter()
calls = []
while... | from constants import *
import collections
import uuid
class CallBuffer():
def __init__(self):
self.waiter = None
self.queue = collections.deque(maxlen=CALL_QUEUE_MAX)
self.call_waiters = {}
def wait_for_calls(self, callback):
self.stop_waiter()
calls = []
while... | Add cancel call to call buffer | Add cancel call to call buffer
| Python | agpl-3.0 | pritunl/pritunl-node,pritunl/pritunl-node | ---
+++
@@ -29,8 +29,8 @@
self.waiter(None)
self.waiter = None
- def return_call(self, id, response):
- callback = self.call_waiters.pop(id, None)
+ def return_call(self, call_id, response):
+ callback = self.call_waiters.pop(call_id, None)
if callback:
... |
716f953069b4fceebe4fec1a1ea2402e77cbb629 | docs/src/conf.py | docs/src/conf.py | # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'... | # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'... | Replace execfile with py3 equivalent | Replace execfile with py3 equivalent
| Python | mit | Erebot/Plop | ---
+++
@@ -29,6 +29,6 @@
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
- execfile(conf, globs, locs)
+ exec(compile(open(conf).read(), conf, 'exec'), globs, locs)
prepare(globals(), locals... |
a02739cc7b1384e51f44d86a05af5a9845469fca | pygame/__init__.py | pygame/__init__.py | """ XXX: fish """
from pygame.color import Color
from pygame.rect import Rect
from pygame.surface import Surface
from pygame.constants import *
from pygame import (
display, color, surface, time, event, constants, sprite,
mouse, locals, image, transform, pkgdata, font, mixer,
cursors, key, draw
)
from pyga... | """ XXX: fish """
from pygame.color import Color
from pygame.rect import Rect
from pygame.surface import Surface
from pygame.constants import *
from pygame import (
display, color, surface, time, event, constants, sprite,
mouse, locals, image, transform, pkgdata, font, mixer,
cursors, key, draw
)
from pyga... | Add Mask to toplevel pygame namespace | Add Mask to toplevel pygame namespace
| Python | lgpl-2.1 | CTPUG/pygame_cffi,caseyc37/pygame_cffi,CTPUG/pygame_cffi,caseyc37/pygame_cffi,caseyc37/pygame_cffi,CTPUG/pygame_cffi | ---
+++
@@ -14,6 +14,7 @@
register_quit
)
from pygame._error import get_error, set_error, SDLError
+from pygame.mask import Mask
# map our exceptions on pygame's default
error = SDLError |
bd11f978535e4a64537eccd000b7eb50e6dab95f | pocket2pinboard/bookmarks.py | pocket2pinboard/bookmarks.py | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | Add date to info reported for new links | Add date to info reported for new links
| Python | apache-2.0 | dhellmann/pocket2pinboard | ---
+++
@@ -21,7 +21,7 @@
if not i.tags:
# Skip anything that isn't tagged.
continue
- LOG.info('%s: %s' % (i.title, i.tags))
+ LOG.info('%s - %s: %s' % (i.time_updated.date(), i.title, i.tags))
LOG.debug('%r', i)
pinboard_client.posts.add(
... |
409182019048a5cb84499258f6f8daaffb62aeae | tests/test_simulation_forward.py | tests/test_simulation_forward.py | import os
import pytest
import pandas as pd
from glob import glob
import numpy as np
from gypsy import DATA_DIR
from gypsy.forward_simulation import simulate_forwards_df
TEST_FILES = glob(os.path.join(DATA_DIR, 'forward_simulation_files', '*.csv'))
TEST_FILES = [(item) for item in TEST_FILES]
CHART_FILES = glob(os.p... | import os
import pytest
import pandas as pd
from glob import glob
import numpy as np
from gypsy import DATA_DIR
from gypsy.forward_simulation import simulate_forwards_df
TEST_FILES = glob(os.path.join(DATA_DIR, 'forward_simulation_files', '*.csv'))
TEST_FILES = [(item) for item in TEST_FILES]
CHART_FILES = glob(os.p... | Revise tests to use np.testing.assert_allclose | Revise tests to use np.testing.assert_allclose
this is better - if na values mismatch (e,g, na in result where expected
has a value) this errors and gives a message to that effect. the
previous one just errored and it was very hard to tell why
| Python | mit | tesera/pygypsy,tesera/pygypsy | ---
+++
@@ -28,8 +28,9 @@
expected = pd.read_csv(expected_data_path, index_col=0)
assert isinstance(result, pd.DataFrame)
- assert np.allclose(
- expected.values.astype(np.float64), result.values.astype(np.float64),
+ assert np.testing.assert_allclose(
+ expected.values, result.values,... |
0f9cb6eb32ce014cb6ae8d24aefed2347efe68d9 | src/python/cargo/condor/host.py | src/python/cargo/condor/host.py | """
cargo/condor/host.py
Host individual condor jobs.
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
import os
import sys
import cPickle as pickle
def main():
"""
Application entry point.
"""
# make the job identifier obvious
process_number = int(os.environ["CONDOR_PROCESS"])
cluster_... | """
cargo/condor/host.py
Host individual condor jobs.
@author: Bryan Silverthorn <bcs@cargo-cult.org>
"""
import os
import sys
import cPickle as pickle
def main():
"""
Application entry point.
"""
# make the job identifier obvious
process_number = int(os.environ["CONDOR_PROCESS"])
cluster_... | Load job from a job file instead of stdin. | Load job from a job file instead of stdin.
| Python | mit | borg-project/cargo,borg-project/cargo | ---
+++
@@ -23,7 +23,8 @@
open(identifier_path, "w").close()
# load and run the job
- job = pickle.load(sys.stdin)
+ with open("job.pickle") as job_file:
+ job = pickle.load(job_file)
job.run()
|
354fb43cc95d68b06b85e8d1fa2426ca663ef8b9 | common/__init__.py | common/__init__.py | VERSION = (0, 0, 0)
__version__ = '.'.join(map(str, VERSION))
from django import template
template.add_to_builtins('common.templatetags.common')
template.add_to_builtins('common.templatetags.development') | VERSION = (0, 1, 0)
__version__ = '.'.join(map(str, VERSION))
from django import template
template.add_to_builtins('common.templatetags.common')
template.add_to_builtins('common.templatetags.development')
# Add db_name to options for use in model.Meta class
import django.db.models.options as options
options.DEFAULT_N... | Add db_name to options for use in model.Meta class | Add db_name to options for use in model.Meta class
| Python | bsd-3-clause | baskoopmans/djcommon,baskoopmans/djcommon,baskoopmans/djcommon | ---
+++
@@ -1,7 +1,10 @@
-VERSION = (0, 0, 0)
+VERSION = (0, 1, 0)
__version__ = '.'.join(map(str, VERSION))
-
from django import template
template.add_to_builtins('common.templatetags.common')
template.add_to_builtins('common.templatetags.development')
+
+# Add db_name to options for use in model.Meta class
+i... |
02d184f94e2e5a0521e2ec06e2c10ca644ba2cef | python/balcaza/t2wrapper.py | python/balcaza/t2wrapper.py | from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
setattr(self.task, flow.name, NestedWorkflow(flow))
nested = ge... | from t2activity import NestedWorkflow
from t2types import ListType, String
from t2flow import Workflow
class WrapperWorkflow(Workflow):
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
self.task[flow.name] = NestedWorkflow(flow)
nested = self.task[... | Use [] notation in wrapper module for task management | Use [] notation in wrapper module for task management
| Python | lgpl-2.1 | jongiddy/balcazapy,jongiddy/balcazapy,jongiddy/balcazapy | ---
+++
@@ -7,8 +7,8 @@
def __init__(self, flow):
self.flow = flow
Workflow.__init__(self, flow.title, flow.author, flow.description)
- setattr(self.task, flow.name, NestedWorkflow(flow))
- nested = getattr(self.task, flow.name)
+ self.task[flow.name] = NestedWorkflow(flow)
+ nested = self.task[flow.name]... |
3048bf667ec24c93d1c60f08124d68b6d1fc458d | src/python/borg/defaults.py | src/python/borg/defaults.py | """@author: Bryan Silverthorn <bcs@cargo-cult.org>"""
import os
machine_speed = 1.0
minimum_fake_run_budget = 1800.0 # XXX
proc_poll_period = 1.0
root_log_level = os.environ.get("BORG_LOG_ROOT_LEVEL", "NOTSET")
try:
from borg_site_defaults import *
except ImportError:
pass
| """@author: Bryan Silverthorn <bcs@cargo-cult.org>"""
import os
machine_speed = 1.0
proc_poll_period = 1.0
root_log_level = os.environ.get("BORG_LOG_ROOT_LEVEL", "NOTSET")
try:
from borg_site_defaults import *
except ImportError:
pass
| Remove an ancient configuration setting. | Remove an ancient configuration setting.
| Python | mit | borg-project/borg | ---
+++
@@ -3,7 +3,6 @@
import os
machine_speed = 1.0
-minimum_fake_run_budget = 1800.0 # XXX
proc_poll_period = 1.0
root_log_level = os.environ.get("BORG_LOG_ROOT_LEVEL", "NOTSET")
|
640b5c45727b0c84ab77a759f8b910212762c4c6 | rest-api/config.py | rest-api/config.py | """Configuration parameters.
Contains things such as the database to connect to.
"""
CLOUDSQL_INSTANCE = 'pmi-drc-api-test:us-central1:pmi-rdr'
CLOUDSQL_SOCKET = '/cloudsql/' + CLOUDSQL_INSTANCE
CLOUDSQL_USER = 'api'
PYTHON_TEST_CLIENT_ID = '116540421226121250670'
ALLOWED_CLIENT_IDS = [PYTHON_TEST_CLIENT_ID]
# TOD... | """Configuration parameters.
Contains things such as the database to connect to.
"""
CLOUDSQL_INSTANCE = 'pmi-drc-api-test:us-central1:pmi-rdr'
CLOUDSQL_SOCKET = '/cloudsql/' + CLOUDSQL_INSTANCE
CLOUDSQL_USER = 'api'
PYTHON_TEST_CLIENT_ID = '116540421226121250670'
ALLOWED_CLIENT_IDS = [PYTHON_TEST_CLIENT_ID]
# TOD... | Add the staging service account to the account whitelist. | Add the staging service account to the account whitelist.
| Python | bsd-3-clause | all-of-us/raw-data-repository,all-of-us/raw-data-repository,all-of-us/raw-data-repository | ---
+++
@@ -14,4 +14,5 @@
# TODO: Move all authentication into the datastore.
ALLOWED_USERS = [
'test-client@pmi-rdr-api-test.iam.gserviceaccount.com',
+ 'pmi-hpo-staging@appspot.gserviceaccount.com',
] |
525f7fff89e02e54ad2a731533e6b817424594f1 | tomviz/python/RotationAlign.py | tomviz/python/RotationAlign.py | # Perform alignment to the estimated rotation axis
#
# Developed as part of the tomviz project (www.tomviz.com).
def transform_scalars(dataset, SHIFT=None, rotation_angle=90.0):
from tomviz import utils
from scipy import ndimage
import numpy as np
data_py = utils.get_array(dataset) # Get data as nump... | # Perform alignment to the estimated rotation axis
#
# Developed as part of the tomviz project (www.tomviz.com).
def transform_scalars(dataset, SHIFT=None, rotation_angle=90.0):
from tomviz import utils
from scipy import ndimage
import numpy as np
data_py = utils.get_array(dataset) # Get data as nump... | Fix ndimage complaining about shift being of NoneType | Fix ndimage complaining about shift being of NoneType
| Python | bsd-3-clause | OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz,mathturtle/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz | ---
+++
@@ -12,7 +12,8 @@
if data_py is None: #Check if data exists
raise RuntimeError("No data array found!")
-
+ if SHIFT is None:
+ SHIFT = np.zeros(len(data_py.shape), dtype=np.int)
data_py_return = np.empty_like(data_py)
ndimage.interpolation.shift(data_py, SHIFT, order=0, out... |
669b95d2092f67bcc220b5fa106064d6c3df6a63 | rolca_core/urls.py | rolca_core/urls.py | from __future__ import absolute_import, unicode_literals
from django.conf.urls import patterns, url
from django.views.generic import TemplateView
urlpatterns = patterns( # pylint: disable=invalid-name
'',
url(r'^$', 'uploader.views.upload_app', name="upload_app"),
url(r'^potrditev$',
TemplateVie... | from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views as core_views
urlpatterns = [ # pylint: disable=invalid-name
url(r'^$', core_views.upload_app, name="upload_app"),
url(r'^potrditev$',
TemplateV... | Rewrite urlpatterns to new format | Rewrite urlpatterns to new format
| Python | apache-2.0 | dblenkus/rolca,dblenkus/rolca,dblenkus/rolca | ---
+++
@@ -1,30 +1,28 @@
from __future__ import absolute_import, unicode_literals
-from django.conf.urls import patterns, url
+from django.conf.urls import url
from django.views.generic import TemplateView
-urlpatterns = patterns( # pylint: disable=invalid-name
- '',
+from . import views as core_views
- ... |
54046bfb8834f5fc2a93841ae56e2790ae82eecf | shared/api.py | shared/api.py | from __future__ import print_function
import boto3
import json
import os
import btr3baseball
jobTable = os.environ['JOB_TABLE']
jobQueue = os.environ['JOB_QUEUE']
queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue)
jobRepo = btr3baseball.JobRepository(jobTable)
dsRepo = btr3baseball.DatasourceReposito... | from __future__ import print_function
import boto3
import json
import os
import btr3baseball
jobTable = os.environ['JOB_TABLE']
jobQueue = os.environ['JOB_QUEUE']
queue = boto3.resource('sqs').get_queue_by_name(QueueName=jobQueue)
jobRepo = btr3baseball.JobRepository(jobTable)
dsRepo = btr3baseball.DatasourceReposito... | Add debug print of data | Add debug print of data
| Python | apache-2.0 | bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball,bryantrobbins/baseball | ---
+++
@@ -17,6 +17,8 @@
data = event['data']
else:
data = None
+
+ print(data)
if method == 'submitJob':
return submitJob(data, context) |
94ca5bc46570175a5b9577d64163cf691c787a8a | virtool/handlers/files.py | virtool/handlers/files.py | import os
import virtool.file
import virtool.utils
from virtool.handlers.utils import json_response, not_found
async def find(req):
db = req.app["db"]
query = {
"ready": True
}
file_type = req.query.get("type", None)
if file_type:
query["type"] = file_type
cursor = db.file... | import os
import virtool.file
import virtool.utils
from virtool.handlers.utils import json_response, not_found
async def find(req):
db = req.app["db"]
query = {
"ready": True
}
file_type = req.query.get("type", None)
if file_type:
query["type"] = file_type
cursor = db.file... | Replace call to deprecated virtool.file.processor | Replace call to deprecated virtool.file.processor
| Python | mit | virtool/virtool,igboyes/virtool,igboyes/virtool,virtool/virtool | ---
+++
@@ -21,7 +21,7 @@
found_count = await cursor.count()
- documents = [virtool.file.processor(d) for d in await cursor.to_list(15)]
+ documents = [virtool.utils.base_processor(d) for d in await cursor.to_list(15)]
return json_response({
"documents": documents, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.