commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
00e9f7d239287896946511b81e2029a5db1f435c
scipy/fftpack/__init__.py
scipy/fftpack/__init__.py
# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft'...
# # fftpack - Discrete Fourier Transform algorithms. # # Created: Pearu Peterson, August,September 2002 from info import __all__,__doc__ from fftpack_version import fftpack_version as __version__ from basic import * from pseudo_diffs import * from helper import * from numpy.dual import register_func for k in ['fft'...
Add dct and idct in scipy.fftpack namespace.
Add dct and idct in scipy.fftpack namespace. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5519 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,scipy/scipy-svn,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor
5a9fe4f8100a36fff3e4c4af21a76d18ac27766f
headers/cpp/headers.py
headers/cpp/headers.py
#!/usr/bin/env python """Find and print the headers #include'd in a source file.""" import os import sys from cpp import ast from cpp import utils _TRANSITIVE = False _INCLUDE_DIRS = ['.'] def ReadSource(relative_filename): source = None for path in _INCLUDE_DIRS: filename = os.path.join(path, re...
#!/usr/bin/env python """Find and print the headers #include'd in a source file.""" import os import sys from cpp import ast from cpp import utils # Allow a site to override the defaults if they choose. # Just put a siteheaders.py somewhere in the PYTHONPATH. try: import siteheaders except ImportError: site...
Allow a site to override the default search (include) directories.
Allow a site to override the default search (include) directories. git-svn-id: b0ea89ea3bf41df64b6a046736e217d0ae4a0fba@19 806ff5bb-693f-0410-b502-81bc3482ff28
Python
apache-2.0
myint/cppclean,myint/cppclean,myint/cppclean,myint/cppclean
85f8d0662901047115f2d852489a3a5be1a01226
datafilters/views.py
datafilters/views.py
try: from django.views.generic.base import ContextMixin as mixin_base except ImportError: mixin_base = object __all__ = ('FilterFormMixin',) class FilterFormMixin(mixin_base): """ Mixin that adds filtering behaviour for Class Based Views. Changed in a way that can play nicely with other CBV simpl...
from django.views.generic.list import MultipleObjectMixin __all__ = ('FilterFormMixin',) class FilterFormMixin(MultipleObjectMixin): """ Mixin that adds filtering behaviour for Class Based Views. Changed in a way that can play nicely with other CBV simply by overriding the get_queryset(self) and get_...
Set base class for view mixin to MultipleObjectMixin
Set base class for view mixin to MultipleObjectMixin
Python
mit
freevoid/django-datafilters,zorainc/django-datafilters,zorainc/django-datafilters
9a43f573f2072051c64fc6da432aaad5d31e0023
PyMarkdownGen/test/block_code_test.py
PyMarkdownGen/test/block_code_test.py
import unittest import PyMarkdownGen.PyMarkdownGen as md class BlockquoteTests(unittest.TestCase): def test_block_quote(self): expected = \ """> this is a > block quote > on multiple > lines. """ self.assertEqual(expected, md.gen_block_quote( ...
"""This module contains the unit tests for the formatting of block quotes. """ import unittest import PyMarkdownGen.PyMarkdownGen as md class BlockquoteTests(unittest.TestCase): """The test case (fixture) for testing block quotes.""" def test_block_quote(self): """Tests block quotes that cont...
Add docstrings for tests of block qotes
Add docstrings for tests of block qotes
Python
epl-1.0
LukasWoodtli/PyMarkdownGen
4548cf2a5ec69f75c19169769fffe88ea3d061e1
djlint/analyzers/context.py
djlint/analyzers/context.py
"""Inspired by django.template.Context""" class ContextPopException(Exception): """pop() has been called more times than push()""" class Context(object): """A stack container for imports and assignments.""" def __init__(self): self.dicts = [{}] def push(self): d = {} self.d...
"""Inspired by django.template.Context""" class ContextPopException(Exception): """pop() has been called more times than push()""" class Context(object): """A stack container for imports and assignments.""" def __init__(self): self.dicts = [{}] def push(self): d = {} self.d...
Add has_value method to Context class
Add has_value method to Context class
Python
isc
alfredhq/djlint
2001f6460e31f3657c3ed2dc7e118452362ab847
month/widgets.py
month/widgets.py
""" Select widget for MonthField. Copied and modified from https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#base-widget-classes """ from datetime import date from django.forms import widgets class MonthSelectorWidget(widgets.MultiWidget): def __init__(self, attrs=None): # create choices for days, m...
""" Select widget for MonthField. Copied and modified from https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#base-widget-classes """ from datetime import date from django.forms import widgets class MonthSelectorWidget(widgets.MultiWidget): def __init__(self, attrs=None): # create choices for days, m...
Handle case where deconstruct receives string
Handle case where deconstruct receives string
Python
bsd-3-clause
mpachas/django-monthfield,clearspark/django-monthfield
9b774ae7e5725ffbf3f8f0780b67d1f7e5bff98d
ircelsos/sos.py
ircelsos/sos.py
# -*- coding: utf-8 -*- """ Created on Sun Jul 12 23:16:17 2015 @author: Joris Van den Bossche """ from __future__ import print_function from owslib.sos import SensorObservationService BASE_URL = 'http://sos.irceline.be/sos' def get_sos(): """Return a SensorObservationService instance""" return SensorObs...
# -*- coding: utf-8 -*- """ Created on Sun Jul 12 23:16:17 2015 @author: Joris Van den Bossche """ from __future__ import print_function import sys import os import datetime from xml.etree import ElementTree import requests from owslib.sos import SensorObservationService BASE_URL = 'http://sos.irceline.be/sos' d...
Enable offline import + save capabilities xml for reuse
Enable offline import + save capabilities xml for reuse
Python
bsd-2-clause
jorisvandenbossche/ircelsos
1d66cbb31ba6da6c72290352c234680caba89594
rpy2_helpers.py
rpy2_helpers.py
#! /usr/bin/env python2.7 """Avoid some boilerplate rpy2 usage code with helpers. Mostly I wrote this so that I can use xyplot without having to remember a lot of details. """ import click from rpy2.robjects import DataFrame, Formula, globalenv from rpy2.robjects.packages import importr grdevices = importr('grDevi...
#! /usr/bin/env python2.7 """Avoid some boilerplate rpy2 usage code with helpers. Mostly I wrote this so that I can use xyplot without having to remember a lot of details. """ import click from rpy2.robjects import DataFrame, Formula, globalenv from rpy2.robjects.packages import importr grdevices = importr('grDevi...
Document the xyplot function and support data dict
Document the xyplot function and support data dict
Python
mit
ecashin/rpy2_helpers
cac5d03fc56bf0d4fd6f2daba7942d5d379e344b
content/util/webassets_integration.py
content/util/webassets_integration.py
class Integration: def __init__(self, env): """ :type env: webassets.Environment """ self.env = env def asset_url(self, bundle_name): """ :type bundle_name: str """ return self.env[bundle_name].urls()[0] def register(self, app): app.j...
class Integration: def __init__(self, env): """ :type env: webassets.Environment """ self.env = env def asset_url(self, bundle_name): """ :type bundle_name: str """ urls = self.env[bundle_name].urls() return "/{}".format(urls[0]) # /{} to...
Prepend '/' to urls gotten from asset_url() to make them absolute. This fixes /projects/* documentation not displaying correctly.
Prepend '/' to urls gotten from asset_url() to make them absolute. This fixes /projects/* documentation not displaying correctly.
Python
apache-2.0
daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru
6ad8c9fc7846f51e2f784d38f9a92017552da996
lanes/models.py
lanes/models.py
from django.db import models from django.contrib.auth.models import User from kitabu.models.subjects import VariableSizeSubject, BaseSubject from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation from kitabu.models import validators from pools.models import Pool class La...
from django.db import models from django.contrib.auth.models import User from kitabu.models.subjects import VariableSizeSubject, BaseSubject from kitabu.models.reservations import ReservationMaybeExclusive, ReservationGroup, BaseReservation from kitabu.models import validators from pools.models import Pool class La...
Add new validators to SPA
Add new validators to SPA
Python
mit
mbad/kitabu,mbad/kitabu,mbad/kitabu
d6c4a38e172894a2240a658fe73ea9816e89cd03
deduplicated/web/__init__.py
deduplicated/web/__init__.py
# -*- coding: utf-8 -*- # # Copyright (c) 2015 Eduardo Klosowski # License: MIT (see LICENSE for details) # from flask import Flask, render_template import jinja2 from .. import Directory, directory_list, str_size # Init app jinja2.filters.FILTERS['str_size'] = str_size app = Flask(__name__) # Pages @app.route...
# -*- coding: utf-8 -*- # # Copyright (c) 2015 Eduardo Klosowski # License: MIT (see LICENSE for details) # from flask import Flask, redirect, render_template, request import jinja2 from .. import Directory, directory_list, str_size # Init app jinja2.filters.FILTERS['str_size'] = str_size app = Flask(__name__) ...
Add web function for add new directory
Add web function for add new directory
Python
mit
eduardoklosowski/deduplicated,eduardoklosowski/deduplicated
00adc1c77d2bcc231a7f8995558ed86bb8071ae7
zun/websocket/websocketclient.py
zun/websocket/websocketclient.py
# Copyright 2017 Linaro Limited # # 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 ...
# Copyright 2017 Linaro Limited # # 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 ...
Remove unused LOG in websocket
Remove unused LOG in websocket Change-Id: Ic45e5e4353dd816fd5416b880aa47df8542b2e02
Python
apache-2.0
kevin-zhaoshuai/zun,kevin-zhaoshuai/zun,kevin-zhaoshuai/zun
e2d51e23f530202b82ba13ae11c686deb1388435
prototype/BioID.py
prototype/BioID.py
#!/usr/bin/env python # # A class for auto identifying bioinformatics file formats. # By Lee & Matt import re import json import mmap class BioID: defs = None def __init__(self, defpath): with open(defpath, "r") as deffile: conts = deffile.read() self.defs = json.loads(conts)["fo...
#!/usr/bin/env python # # A class for auto identifying bioinformatics file formats. # By Lee & Matt import re import json import mmap class BioID: defs = None def __init__(self, defpath): with open(defpath, "r") as deffile: conts = deffile.read() self.defs = json.loads(conts)["formats"] @classmethod def...
Indent return in identify class.
Indent return in identify class.
Python
mit
LeeBergstrand/BioMagick,LeeBergstrand/BioMagick
afac07ce173af3e7db4a6ba6dab4786903e217b7
ocradmin/ocr/tools/plugins/cuneiform_wrapper.py
ocradmin/ocr/tools/plugins/cuneiform_wrapper.py
""" Wrapper for Cuneiform. """ from generic_wrapper import * def main_class(): return CuneiformWrapper class CuneiformWrapper(GenericWrapper): """ Override certain methods of the OcropusWrapper to use Cuneiform for recognition of individual lines. """ name = "cuneiform" capabilities = (...
""" Wrapper for Cuneiform. """ import tempfile import subprocess as sp from ocradmin.ocr.tools import check_aborted, set_progress from ocradmin.ocr.utils import HocrParser from generic_wrapper import * def main_class(): return CuneiformWrapper class CuneiformWrapper(GenericWrapper): """ Override certai...
Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output
Allow Cuneiform to do full page conversions. Downsides: 1) it crashes on quite a lot of pages 2) there's no progress output
Python
apache-2.0
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
c69e4e6f3aab80ad3ac28e7a6b13f309a1b2d205
alembic/versions/151b2f642877_text_to_json.py
alembic/versions/151b2f642877_text_to_json.py
"""text to JSON Revision ID: 151b2f642877 Revises: aee7291c81 Create Date: 2015-06-12 14:40:56.956657 """ # revision identifiers, used by Alembic. revision = '151b2f642877' down_revision = 'aee7291c81' from alembic import op import sqlalchemy as sa def upgrade(): query = 'ALTER TABLE project ALTER COLUMN info...
"""text to JSON Revision ID: 151b2f642877 Revises: ac115763654 Create Date: 2015-06-12 14:40:56.956657 """ # revision identifiers, used by Alembic. revision = '151b2f642877' down_revision = 'ac115763654' from alembic import op import sqlalchemy as sa def upgrade(): query = 'ALTER TABLE project ALTER COLUMN in...
Fix alembic revision after merge master
Fix alembic revision after merge master
Python
agpl-3.0
PyBossa/pybossa,Scifabric/pybossa,Scifabric/pybossa,PyBossa/pybossa,jean/pybossa,OpenNewsLabs/pybossa,geotagx/pybossa,geotagx/pybossa,OpenNewsLabs/pybossa,jean/pybossa
8c780f99dd82887a43c8ce661925f993fbc41003
readux/__init__.py
readux/__init__.py
from django.conf import settings __version_info__ = (1, 2, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to a...
__version_info__ = (1, 3, 0, 'dev') # Dot-connect all but the last. Last is dash-connected if not None. __version__ = '.'.join([str(i) for i in __version_info__[:-1]]) if __version_info__[-1] is not None: __version__ += ('-%s' % (__version_info__[-1],)) # context processor to add version to the template environ...
Bump version to 1.3.0-dev after releasing 1.2
Bump version to 1.3.0-dev after releasing 1.2
Python
apache-2.0
emory-libraries/readux,emory-libraries/readux,emory-libraries/readux
e06cc3da015505bc58eb705b5ee77fbbaae61a09
har/model/log.py
har/model/log.py
from datetime import datetime from har import db class Log(db.Model): id = db.Column(db.Integer, primary_key=True) subject_id = db.Column(db.Integer, db.ForeignKey('subject.device')) log_type = db.Column(db.String(40)) activity = db.Column(db.String(40)) sensor_placement = db.Column(db.String(40))...
from datetime import datetime from har import db class Log(db.Model): STATUS_PENDING = "pending" STATUS_PENDING = "trained" id = db.Column(db.Integer, primary_key=True) subject_id = db.Column(db.Integer, db.ForeignKey('subject.device')) log_type = db.Column(db.String(40)) activity = db.Colum...
Add status column to Log model
Add status column to Log model
Python
mit
ilhamadun/har,ilhamadun/har
9da9ec6618de8c9a1276e44e81c32639d42efada
setup.py
setup.py
from distutils.core import setup setup( name='hy-py', version='0.0.2', packages=['hy'], license='MIT', author='Joakim Ekberg', author_email='jocke.ekberg@gmail.com', url='https://github.com/kalasjocke/hy', long_description=open('README.md').read(), install_requires=open('requirement...
from distutils.core import setup setup( name='hy-py', version='0.0.3', packages=['hy', 'hy.adapters'], license='MIT', author='Joakim Ekberg', author_email='jocke.ekberg@gmail.com', url='https://github.com/kalasjocke/hy', long_description=open('README.md').read(), install_requires=op...
Include the serializer adapters in the PyPI package
Include the serializer adapters in the PyPI package
Python
mit
kalasjocke/hyp
c1b97bbc6fc0603c0f2a809175edf88cd1e4a207
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup packages = [ 'upho', 'upho.phonon', 'upho.harmonic', 'upho.analysis', 'upho.structure', 'upho.irreps', 'upho.qpoints', 'group', ] scripts = [ 'scripts/upho_weights', 'scripts/upho_sf', 'scripts/qpoints', ] setup(name='up...
#!/usr/bin/env python from distutils.core import setup packages = [ 'upho', 'upho.phonon', 'upho.harmonic', 'upho.analysis', 'upho.structure', 'upho.irreps', 'upho.qpoints', 'group', ] scripts = [ 'scripts/upho_weights', 'scripts/upho_sf', 'scripts/qpoints', ] setup(name='up...
Add requirement of h5py and phonopy
Add requirement of h5py and phonopy
Python
mit
yuzie007/ph_unfolder,yuzie007/upho
f890663daa329e3f22d0f619ed6acf9365308c7c
apps/ignite/views.py
apps/ignite/views.py
from django.shortcuts import get_object_or_404 import jingo from challenges.models import Submission, Category from projects.models import Project def splash(request, project, slug, template_name='challenges/show.html'): """Show an individual project challenge.""" project = get_object_or_404(Project, slug=pr...
from django.shortcuts import get_object_or_404 import jingo from challenges.models import Submission, Category from projects.models import Project def splash(request, project, slug, template_name='challenges/show.html'): """Show an individual project challenge.""" project = get_object_or_404(Project, slug=pr...
Update splash view to use visible() method.
Update splash view to use visible() method.
Python
bsd-3-clause
mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite
d4b487ed1b276be230440e60ab3cdc81e73cff47
tests/unit/utils/test_utils.py
tests/unit/utils/test_utils.py
# coding=utf-8 ''' Test case for utils/__init__.py ''' from __future__ import unicode_literals, print_function, absolute_import from tests.support.unit import TestCase, skipIf from tests.support.mock import ( NO_MOCK, NO_MOCK_REASON, MagicMock, patch ) try: import pytest except ImportError: pyt...
# coding=utf-8 ''' Test case for utils/__init__.py ''' from __future__ import unicode_literals, print_function, absolute_import from tests.support.unit import TestCase, skipIf from tests.support.mock import ( NO_MOCK, NO_MOCK_REASON, MagicMock, patch ) try: import pytest except ImportError: pyt...
Add unit test to get opts from the environment
Add unit test to get opts from the environment
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
974112e0ebd9397e3b3d3e49034465713b8df996
tools/lxlcrawler/lxlcrawler.py
tools/lxlcrawler/lxlcrawler.py
#!/usr/bin/env python3 from urllib.parse import urljoin from urllib.request import urlopen, Request import json import codecs reader = codecs.getreader("utf-8") def crawl(collection_url): while True: req = Request(collection_url, headers={'accept': 'application/json'}) data = json.load(reader(urlo...
#!/usr/bin/env python3 from urllib.parse import urljoin from urllib.request import urlopen, Request import json import codecs reader = codecs.getreader("utf-8") def crawl(collection_url): while True: req = Request(collection_url, headers={'accept': 'application/json'}) data = json.load(reader(urlo...
Handle both forms of next links
Handle both forms of next links
Python
cc0-1.0
Kungbib/datalab,Kungbib/datalab
e249e1c03fab60c2f09a171924f3a1f701a0c7aa
astropy/tests/image_tests.py
astropy/tests/image_tests.py
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') def i...
import matplotlib from matplotlib import pyplot as plt from ..utils.decorators import wraps MPL_VERSION = matplotlib.__version__ ROOT = "http://{server}/testing/astropy/2018-02-01T23:31:45.013149/{mpl_version}/" IMAGE_REFERENCE_DIR = (ROOT.format(server='data.astropy.org', mpl_version=MPL_VERSION[:3] + '.x') + ',' ...
Add back mirror for image tests
Add back mirror for image tests
Python
bsd-3-clause
pllim/astropy,stargaser/astropy,MSeifert04/astropy,funbaker/astropy,larrybradley/astropy,astropy/astropy,pllim/astropy,lpsinger/astropy,saimn/astropy,MSeifert04/astropy,mhvk/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,StuartLittlefair/astropy,bsipocz/astropy,astropy/astropy,lpsinger/astropy,bsipocz/astropy,DougB...
652fceb8f7d22c6cb22a81e4ce048ff8edd34e8b
migrations/versions/148_add_last_modified_column_for_events.py
migrations/versions/148_add_last_modified_column_for_events.py
"""add last_modified column for events Revision ID: 54dcea22a268 Revises: 41f957b595fc Create Date: 2015-03-16 23:15:55.908307 """ # revision identifiers, used by Alembic. revision = '54dcea22a268' down_revision = '41f957b595fc' from alembic import op from sqlalchemy.sql import text import sqlalchemy as sa def up...
"""add last_modified column for events Revision ID: 54dcea22a268 Revises: 486c7fa5b533 Create Date: 2015-03-16 23:15:55.908307 """ # revision identifiers, used by Alembic. revision = '54dcea22a268' down_revision = '486c7fa5b533' from alembic import op from sqlalchemy.sql import text import sqlalchemy as sa def up...
Undo revision changes to previous migration
Undo revision changes to previous migration
Python
agpl-3.0
Eagles2F/sync-engine,gale320/sync-engine,closeio/nylas,ErinCall/sync-engine,gale320/sync-engine,jobscore/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,ErinCall/sync-engine,wakermahmud/sync-engine,wakermahmud/sync-engine,gale320/sync-engine,nylas/sync-engine,nylas/sync-engine,wakermahmud/sync-engine,closeio/nyla...
926ee23ef946dc2eba0cae5321601c5fadad9e5e
examples/faceted_lineplot.py
examples/faceted_lineplot.py
""" Line plots on multiple facets ============================= _thumb: .45, .42 """ import seaborn as sns sns.set(style="ticks") dots = sns.load_dataset("dots") # Define a palette to ensure that colors will be # shared across the facets palette = dict(zip(dots.coherence.unique(), sns.color_palet...
""" Line plots on multiple facets ============================= _thumb: .45, .42 """ import seaborn as sns sns.set(style="ticks") dots = sns.load_dataset("dots") # Define a palette to ensure that colors will be # shared across the facets palette = dict(zip(dots.coherence.unique(), sns.color_palet...
Update dots lineplot example to use relplot
Update dots lineplot example to use relplot
Python
bsd-3-clause
sauliusl/seaborn,lukauskas/seaborn,petebachant/seaborn,phobson/seaborn,anntzer/seaborn,lukauskas/seaborn,mwaskom/seaborn,phobson/seaborn,arokem/seaborn,anntzer/seaborn,arokem/seaborn,mwaskom/seaborn
29fef644079a03fe0cfeb792dd47af7749382dba
unnaturalcode/http/__main__.py
unnaturalcode/http/__main__.py
#!/usr/bin/env python # Copyright (C) 2014 Eddie Antonio Santos # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
#!/usr/bin/env python # Copyright (C) 2014 Eddie Antonio Santos # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later versio...
Fix to allow invocation by `python unnaturalcode/http`
Fix to allow invocation by `python unnaturalcode/http`
Python
agpl-3.0
orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,naturalness/unnaturalcode,orezpraw/estimate-charm,na...
36e37a5409ef7fce9286f5fa9c24a185592df59a
health_check/contrib/celery/backends.py
health_check/contrib/celery/backends.py
from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_status(self): timeout = getattr(sett...
from django.conf import settings from health_check.backends import BaseHealthCheckBackend from health_check.exceptions import ( ServiceReturnedUnexpectedResult, ServiceUnavailable ) from .tasks import add class CeleryHealthCheck(BaseHealthCheckBackend): def check_status(self): timeout = getattr(sett...
Revert "Clean results task Health Check"
Revert "Clean results task Health Check" This reverts commit 4d4148ea831d425327a3047ebb9be8c3129eaff6. Close #269
Python
mit
KristianOellegaard/django-health-check,KristianOellegaard/django-health-check
7229e9f43a94ab9336ef1dc2fe27a14fc6662a8b
knights/base.py
knights/base.py
import ast from . import parse class Template: def __init__(self, raw): self.raw = raw self.parser = parse.Parser(raw) self.nodelist = self.parser() code = ast.Expression( body=ast.GeneratorExp( elt=ast.Call( func=ast.Name(id='str'...
import ast from . import parse class Template: def __init__(self, raw): self.raw = raw self.parser = parse.Parser(raw) self.nodelist = self.parser() code = ast.Expression( body=ast.GeneratorExp( elt=ast.Call( func=ast.Name(id='str'...
Add tags and filters into the context
Add tags and filters into the context
Python
mit
funkybob/knights-templater,funkybob/knights-templater
812d3cdace821a77fdcb2e0441ba5fa2650bf5fd
pybo/bayesopt/utils.py
pybo/bayesopt/utils.py
""" Simple utilities for creating Bayesian optimization components. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # exported symbols __all__ = ['params'] def params(*args): """ Decorator for annotating a BO component with th...
""" Simple utilities for creating Bayesian optimization components. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports import inspect # exported symbols __all__ = ['params'] def params(*args): """ Decorator for ...
Update params decorator with basic error checking.
Update params decorator with basic error checking.
Python
bsd-2-clause
mwhoffman/pybo,jhartford/pybo
03201b992adfada04e4104611ee27b125c157eeb
apps/local_apps/account/context_processors.py
apps/local_apps/account/context_processors.py
from account.models import Account, AnonymousAccount def openid(request): return {'openid': request.openid} def account(request): if request.user.is_authenticated(): try: account = Account._default_manager.get(user=request.user) except (Account.DoesNotExist, Account.MultipleObject...
from account.models import Account, AnonymousAccount def openid(request): return {'openid': request.openid} def account(request): if request.user.is_authenticated(): try: account = Account._default_manager.get(user=request.user) except Account.DoesNotExist: account = A...
Throw 500 error on multiple accounts in account context processor
Throw 500 error on multiple accounts in account context processor git-svn-id: 51ba99f60490c2ee9ba726ccda75a38950f5105d@1121 45601e1e-1555-4799-bd40-45c8c71eef50
Python
mit
amarandon/pinax,alex/pinax,amarandon/pinax,amarandon/pinax,amarandon/pinax,alex/pinax,alex/pinax
1c1d915596f5700a08efb6e5906a4ccfa0ddb932
tests/registryd/test_registry_startup.py
tests/registryd/test_registry_startup.py
# Pytest will pick up this module automatically when running just "pytest". # # Each test_*() function gets passed test fixtures, which are defined # in conftest.py. So, a function "def test_foo(bar)" will get a bar() # fixture created for it. PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'o...
# Pytest will pick up this module automatically when running just "pytest". # # Each test_*() function gets passed test fixtures, which are defined # in conftest.py. So, a function "def test_foo(bar)" will get a bar() # fixture created for it. PROPERTIES_IFACE = 'org.freedesktop.DBus.Properties' ACCESSIBLE_IFACE = 'o...
Test that the registry's root has a null parent
Test that the registry's root has a null parent
Python
lgpl-2.1
GNOME/at-spi2-core,GNOME/at-spi2-core,GNOME/at-spi2-core
ea2d16c78eff88ba4a32a89793a7cd644e20cdb3
tools/perf/benchmarks/draw_properties.py
tools/perf/benchmarks/draw_properties.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on trac...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from core import perf_benchmark from measurements import draw_properties from telemetry import benchmark import page_sets # This benchmark depends on trac...
Disable the "draw properties" benchmark
Disable the "draw properties" benchmark We'd still like to be able to run this benchmark manually, but we don't need it to be run automatically. BUG=None CQ_EXTRA_TRYBOTS=tryserver.chromium.perf:linux_perf_bisect;tryserver.chromium.perf:mac_perf_bisect;tryserver.chromium.perf:win_perf_bisect;tryserver.chromium.perf:a...
Python
bsd-3-clause
Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-cross...
e8d7a81f74566775aa243a2441939f778b5c266d
frigg/builds/serializers.py
frigg/builds/serializers.py
from rest_framework import serializers from .models import Build, BuildResult, Project class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ( 'id', 'owner', 'name', 'private', 'approved', ...
from rest_framework import serializers from .models import Build, BuildResult, Project class BuildResultSerializer(serializers.ModelSerializer): class Meta: model = BuildResult fields = ( 'id', 'coverage', 'succeeded', 'tasks', ) class Bu...
Add builds to project api
Add builds to project api
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
8200beb4aa68a3e88a95394d2b8146ce264e1055
flask_authorization_panda/tests/test_basic_auth.py
flask_authorization_panda/tests/test_basic_auth.py
import json from base64 import b64encode import pytest from flask import Flask from flask_authorization_panda import basic_auth @pytest.fixture def flask_app(): app = Flask(__name__) app.config['TESTING'] = True @app.route('/') @basic_auth def hello_world(): return 'Hello World!' r...
from base64 import b64encode import pytest from flask import Flask, jsonify from flask_authorization_panda import basic_auth @pytest.fixture def flask_app(): app = Flask(__name__) app.config['TESTING'] = True @app.route('/') @basic_auth def hello_world(): return jsonify({"statusCode": 2...
Add unit test for successful completion.
Add unit test for successful completion.
Python
mit
eikonomega/flask-authorization-panda
f360b8ada2783636c1c77f47fa9b982581a3c944
lib/arguments.py
lib/arguments.py
from os import path from actions import VersionAction from argparse import ArgumentParser from functions import parse_extra_vars parser = ArgumentParser( prog='cikit', add_help=False, ) parser.add_argument( 'playbook', nargs='?', default='', help='The name of a playbook to run.', ) parser.add...
from os import path from actions import VersionAction from argparse import ArgumentParser from functions import parse_extra_vars parser = ArgumentParser( prog='cikit', add_help=False, ) parser.add_argument( 'playbook', nargs='?', default='', help='The name of a playbook to run.', ) options = ...
Add "-h" and "-v" to mutually exclusive group
[CIKit] Add "-h" and "-v" to mutually exclusive group
Python
apache-2.0
BR0kEN-/cikit,BR0kEN-/cikit,BR0kEN-/cikit,BR0kEN-/cikit,BR0kEN-/cikit
e8942651a43c7af1375b42ddd6521b4e65169b95
conanfile.py
conanfile.py
from conans import ConanFile, CMake class Core8(ConanFile): name = "core8" version = "0.1" url = "https://github.com/benvenutti/core8.git" settings = "os", "compiler", "build_type", "arch" license = "MIT" exports_sources = "*" def build(self): cmake = CMake(self.settings) s...
from conans import ConanFile, CMake class Core8(ConanFile): name = "core8" version = "0.1" url = "https://github.com/benvenutti/core8.git" description = """A Chip-8 VM implemented in C++""" settings = "os", "compiler", "build_type", "arch" license = "MIT" exports_sources = "*" def buil...
Add description and test build stage
Add description and test build stage
Python
mit
benvenutti/core8,benvenutti/core8
2f91ba989260c0723c9b02bd8d48805db637e350
dockci/migrations/0002.py
dockci/migrations/0002.py
""" Migrate config to docker hosts list """ import os import yaml filename = os.path.join('data', 'configs.yaml') with open(filename) as handle: data = yaml.load(handle) host = data.pop('docker_host') data['docker_hosts'] = [host] with open(filename, 'w') as handle: yaml.dump(data, handle, default_flow_styl...
""" Migrate config to docker hosts list """ import os import sys import yaml filename = os.path.join('data', 'configs.yaml') try: with open(filename) as handle: data = yaml.load(handle) except FileNotFoundError: # This is fine; will fail for new installs sys.exit(0) host = data.pop('docker_host')...
Handle no config.yaml in migrations
Handle no config.yaml in migrations
Python
isc
RickyCook/paas-in-a-day-dockci,RickyCook/paas-in-a-day-dockci
df9fdb39f78cd001b6f420d7c54c64886b378483
project/wsgi.py
project/wsgi.py
""" WSGI config for project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTI...
""" WSGI config for project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTI...
Configure WhiteNoise to serve static files
Configure WhiteNoise to serve static files
Python
apache-2.0
SethGreylyn/gwells,rstens/gwells,SethGreylyn/gwells,SethGreylyn/gwells,SethGreylyn/gwells,rstens/gwells,rstens/gwells,bcgov/gwells,rstens/gwells,bcgov/gwells,bcgov/gwells,bcgov/gwells
b67b677d4092e5bec445649321b142d31cfc0fb6
linkatos/activities.py
linkatos/activities.py
from . import parser from . import printer from . import firebase as fb from . import reaction as react def is_empty(events): return ((events is None) or (len(events) == 0)) def is_url(url_cache): return url_cache is not None def is_reaction(index): return index is not None def event_consumer(expect...
from . import parser from . import printer from . import firebase as fb from . import reaction as react def is_empty(events): return ((events is None) or (len(events) == 0)) def is_url(url_cache): return url_cache is not None def is_reaction(index): return index is not None def remove_url_from(url_c...
Add function to remove reacted to urls
feat: Add function to remove reacted to urls
Python
mit
iwi/linkatos,iwi/linkatos
0c803c41fc7a54ddf0b8d1c580c39e7e2c325b8b
container/getPureElkIndex.py
container/getPureElkIndex.py
__author__ = 'terry' import sys from elasticsearch import Elasticsearch import time if __name__ == '__main__': time.sleep(5) # create a connection to the Elasticsearch database client = Elasticsearch(['pureelk-elasticsearch:9200'], retry_on_timeout=True) if client.indices.exists(index='pureelk-globa...
__author__ = 'terry' import sys from elasticsearch import Elasticsearch import time if __name__ == '__main__': time.sleep(5) # create a connection to the Elasticsearch database client = Elasticsearch(['pureelk-elasticsearch:9200'], retry_on_timeout=True) if client.exists(index='.kibana', doc_type='i...
Change the test for pureelk in elasticsearch
Change the test for pureelk in elasticsearch It makes more sense to test for a specific index pattern rather than pureelk-global-arrays index. The reason is if someone never adds an array startup code will try to re-add .kibana data
Python
apache-2.0
pureelk/pureelk,pureelk/pureelk,pureelk/pureelk,pureelk/pureelk
5ae97ea5eb7e07c9e967741bac5871379b643b39
nova/db/base.py
nova/db/base.py
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
Add super call to db Base class
Add super call to db Base class Without this call, multiple inheritance involving the db Base class does not work correctly. Change-Id: Iac6b99d34f00babb8b66fede4977bf75f0ed61d4
Python
apache-2.0
joker946/nova,alexandrucoman/vbox-nova-driver,felixma/nova,watonyweng/nova,devendermishrajio/nova,joker946/nova,Juniper/nova,NeCTAR-RC/nova,BeyondTheClouds/nova,redhat-openstack/nova,Yusuke1987/openstack_template,bgxavier/nova,ted-gould/nova,redhat-openstack/nova,phenoxim/nova,tudorvio/nova,jeffrey4l/nova,scripnichenko...
ae855bd4ba0da5667e6ba43b59d457e62e4c0d99
tests/util.py
tests/util.py
from robber import BadExpectation from robber.matchers.base import Base expectation_count = 0 fail_count = 0 old_match = Base.match def new_match(self): global expectation_count expectation_count += 1 try: old_match(self) except BadExpectation: global fail_count fail_count +...
from robber import BadExpectation from robber.matchers.base import Base expectation_count = 0 fail_count = 0 old_match = Base.match def new_match(self): global expectation_count expectation_count += 1 try: old_match(self) except BadExpectation: global fail_count fail_count +...
Make must_fail fully compatible with nose
[r] Make must_fail fully compatible with nose Originally, whenever you run a must_fail test alone and directly with nose, you would get this error message: 'ValueError: no such test method in <test reference>: test_decorated'
Python
mit
vesln/robber.py
f1aabcad9e6f6daae23c158c2fba7b28f0e57416
message_view.py
message_view.py
import sublime import sublime_plugin PANEL_NAME = "SublimeLinter Messages" OUTPUT_PANEL = "output." + PANEL_NAME def plugin_unloaded(): for window in sublime.windows(): window.destroy_output_panel(PANEL_NAME) class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand): def run(self, msg=""...
import sublime import sublime_plugin PANEL_NAME = "SublimeLinter Messages" OUTPUT_PANEL = "output." + PANEL_NAME def plugin_unloaded(): for window in sublime.windows(): window.destroy_output_panel(PANEL_NAME) class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand): def run(self, msg=""...
Fix mypy error by asserting
Fix mypy error by asserting Since we just asked `is_panel_active`, the following `find_output_panel` *must* succeed. So we `assert panel` to tell it mypy.
Python
mit
SublimeLinter/SublimeLinter3,SublimeLinter/SublimeLinter3
c8a7b9acc6c66a44eeb9ceac91587bb8ad08ad89
pagedown/utils.py
pagedown/utils.py
from django.conf import settings def compatible_staticpath(path): ''' Try to return a path compatible all the way back to Django 1.2. If anyone has a cleaner or better way to do this let me know! ''' try: # >= 1.4 from django.contrib.staticfiles.storage import staticfiles_storage ...
from django.conf import settings def compatible_staticpath(path): ''' Try to return a path compatible all the way back to Django 1.2. If anyone has a cleaner or better way to do this let me know! ''' try: # >= 1.4 from django.templatetags.static import static return static(...
Use `django.templatetags.static`to load the file
Use `django.templatetags.static`to load the file Debugging this issue: https://github.com/timmyomahony/django-pagedown/issues/25
Python
bsd-3-clause
timmyomahony/django-pagedown,timmyomahony/django-pagedown,timmyomahony/django-pagedown
6dfc0d6cec2d0bd9d873f4e0854cee46414c37ec
marked_tests.py
marked_tests.py
import unittest class MarkedTests(unittest.TestCase): pass if __name__ == '__main__': unittest.main()
import unittest import marked class MarkedTests(unittest.TestCase): pass if __name__ == '__main__': unittest.main()
Add import for marked to tests
Add import for marked to tests
Python
bsd-3-clause
1stvamp/marked
3d06be213f7dc2c98cf77ddd497a603af2671e53
nbt/__init__.py
nbt/__init__.py
__all__ = ["chunk", "region", "world", "nbt"] from . import * VERSION = (1, 3) def _get_version(): return ".".join(VERSION)
__all__ = ["nbt", "world", "region", "chunk"] from . import * VERSION = (1, 3) def _get_version(): """Return the NBT version as string.""" return ".".join([str(v) for v in VERSION])
Fix nbt._get_version() Function did not work (it tried to join integers as a string) Also re-order __all__ for documentation purposes
Fix nbt._get_version() Function did not work (it tried to join integers as a string) Also re-order __all__ for documentation purposes
Python
mit
twoolie/NBT,cburschka/NBT,macfreek/NBT,devmario/NBT,fwaggle/NBT
2f2ae3308256d2233e0363cb46ee88067da54b4b
modules/roles.py
modules/roles.py
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg =...
import discord import shlex rolesTriggerString = '!role' # String to listen for as trigger async def parse_roles_command(message, client): server_roles = message.server.roles # Grab a list of all roles as Role objects server_roles_str = [x.name for x in server_roles] # String-ify it into their names msg =...
Add role removal and logic cleanup
Add role removal and logic cleanup
Python
mit
suclearnub/scubot
0602aad845f0a04cdc535b97b4860469f600d9b0
django_tablib/datasets.py
django_tablib/datasets.py
from __future__ import absolute_import from .base import BaseDataset class SimpleDataset(BaseDataset): def __init__(self, queryset, headers=None): self.queryset = queryset if headers is None: fields = queryset.model._meta.fields self.header_list = [field.name for field in f...
from __future__ import absolute_import from .base import BaseDataset class SimpleDataset(BaseDataset): def __init__(self, queryset, headers=None): self.queryset = queryset if headers is None: fields = queryset.model._meta.fields self.header_list = [field.name for field in f...
Use isinstance to check type
Use isinstance to check type This should also allow to use subtypes like a SortedDict to pass in headers.
Python
mit
joshourisman/django-tablib,joshourisman/django-tablib,ebrelsford/django-tablib,ebrelsford/django-tablib
bd7cf1f28d20fff3434325f0281d5a5a528983f8
mangopaysdk/entities/card.py
mangopaysdk/entities/card.py
from mangopaysdk.entities.entitybase import EntityBase class Card(EntityBase): """Card entity""" def __init__(self, id = None): # MMYY self.ExpirationDate = None # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414 self.Alias = None # The card ...
from mangopaysdk.entities.entitybase import EntityBase class Card(EntityBase): """Card entity""" def __init__(self, id = None): self.UserId = None # MMYY self.ExpirationDate = None # first 6 and last 4 are real card numbers for example: 497010XXXXXX4414 self.Alias...
Add extra missing items to the entity
Add extra missing items to the entity
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
a8c7067c3e3eb8931c9bdeb7a4a3e445ee6e338d
djasana/tests/test_connect.py
djasana/tests/test_connect.py
import unittest from django.core.exceptions import ImproperlyConfigured from django.test import override_settings from asana.error import NoAuthorizationError from djasana.connect import client_connect class ClientConnectTestCase(unittest.TestCase): @override_settings(ASANA_ACCESS_TOKEN=None, ASANA_CLIENT_ID=No...
import requests import unittest from django.core.exceptions import ImproperlyConfigured from django.test import override_settings from asana.error import NoAuthorizationError from djasana.connect import client_connect class ClientConnectTestCase(unittest.TestCase): @override_settings(ASANA_ACCESS_TOKEN=None, AS...
Fix test for no connection - In the case of no connectivity, test will skip rather than fail
Fix test for no connection - In the case of no connectivity, test will skip rather than fail
Python
mit
sbywater/django-asana
06a052c7f60fd413f39b8e313e44bfeea970896a
work/admin.py
work/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from django import forms from django.utils.translation import ugettext_lazy as _ from parler.admin import TranslatableTabularInline from adminsortable.admin import SortableTabularInline from cms.admin.placeholderadmin import PlaceholderAdminMixin from allink_cor...
# -*- coding: utf-8 -*- from django.contrib import admin from django import forms from parler.admin import TranslatableTabularInline from adminsortable.admin import SortableTabularInline from cms.admin.placeholderadmin import PlaceholderAdminMixin from allink_core.allink_base.admin import AllinkBaseAdminSortable from...
TEST allink_apps subtree - pulling
TEST allink_apps subtree - pulling
Python
bsd-3-clause
allink/allink-apps,allink/allink-apps
c811e0e02d06f8d5fd6a0b738546b0e200c706cd
fairseq/criterions/fairseq_criterion.py
fairseq/criterions/fairseq_criterion.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from torch.nn.modules.loss import ...
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from torch.nn.modules.loss import ...
Store task in the criterion base class
Store task in the criterion base class Summary: Pull Request resolved: https://github.com/fairinternal/fairseq-py/pull/737 Differential Revision: D16377805 Pulled By: myleott fbshipit-source-id: 1e090a02ff4fbba8695173f57d3cc5b88ae98bbf
Python
mit
pytorch/fairseq,pytorch/fairseq,pytorch/fairseq
0d6706383b6414459cf158b213f4102fa3452b5a
pmxbot/slack.py
pmxbot/slack.py
import time import importlib import pmxbot class Bot(pmxbot.core.Bot): def __init__(self, server, port, nickname, channels, password=None): token = pmxbot.config['slack token'] sc = importlib.import_module('slackclient') self.client = sc.SlackClient(token) def start(self): res = self.client.rtm_connect() ...
import time import importlib from tempora import schedule import pmxbot class Bot(pmxbot.core.Bot): def __init__(self, server, port, nickname, channels, password=None): token = pmxbot.config['slack token'] sc = importlib.import_module('slackclient') self.client = sc.SlackClient(token) self.scheduler = sche...
Implement scheduled task handling in Slack
Implement scheduled task handling in Slack
Python
mit
yougov/pmxbot,yougov/pmxbot,yougov/pmxbot
938725a3693ee885a761e5ba07e75d2b94d78661
pytask/profile/urls.py
pytask/profile/urls.py
from django.conf.urls.defaults import patterns from django.conf.urls.defaults import url urlpatterns = patterns('pytask.profile.views', url(r'^view/$', 'view_profile', name='view_profile'), url(r'^edit/$', 'edit_profile', name='edit_profile'), url(r'^notf/browse/$', 'browse_notifications', name='edit_prof...
from django.conf.urls.defaults import patterns from django.conf.urls.defaults import url urlpatterns = patterns('pytask.profile.views', url(r'^view/$', 'view_profile', name='view_profile'), url(r'^edit/$', 'edit_profile', name='edit_profile'), url(r'^notification/browse/$', 'browse_notifications', name='b...
Fix styling issue in URLConf.
Fix styling issue in URLConf.
Python
agpl-3.0
madhusudancs/pytask,madhusudancs/pytask,madhusudancs/pytask
f415a411f748ce5a8eb142d862970e00d0267004
tests/test_environment.py
tests/test_environment.py
# -*- coding: utf-8 -*- import pytest from cookiecutter.environment import StrictEnvironment from cookiecutter.exceptions import UnknownExtension def test_env_should_raise_for_unknown_extension(): context = { 'cookiecutter': { '_extensions': ['foobar'] } } with pytest.raises...
# -*- coding: utf-8 -*- import pytest from cookiecutter.environment import StrictEnvironment from cookiecutter.exceptions import UnknownExtension def test_env_should_raise_for_unknown_extension(): context = { 'cookiecutter': { '_extensions': ['foobar'] } } with pytest.raises...
Add a simple test to make sure cookiecutter comes with jinja2_time
Add a simple test to make sure cookiecutter comes with jinja2_time
Python
bsd-3-clause
Springerle/cookiecutter,dajose/cookiecutter,luzfcb/cookiecutter,michaeljoseph/cookiecutter,willingc/cookiecutter,luzfcb/cookiecutter,michaeljoseph/cookiecutter,Springerle/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,audreyr/cookiecutter,audreyr/cookiecutter,willingc/cookiecutter,pjbull/cookiecutter,hackebrot/co...
54674b79fecf7eec4f09e885e7d68c9b6181efcf
mollie/api/objects/base.py
mollie/api/objects/base.py
class Base(dict): def _get_property(self, name): """Return the named property from dictionary values.""" if not self[name]: return None return self[name]
class Base(dict): def _get_property(self, name): """Return the named property from dictionary values.""" if name not in self: return None return self[name]
Make _get_property to return none when name does not exist
Make _get_property to return none when name does not exist
Python
bsd-2-clause
mollie/mollie-api-python
13c3379717d1ad10a179f26838950090a2b6e4f4
pyxb/__init__.py
pyxb/__init__.py
"""PyWXSB -- Python W3C XML Schema Bindings. binding - Module used to generate the bindings and at runtime to support the generated bindings utils - Common utilities used in parsing, generating, and running xmlschema - Class that convert XMLSchema from a DOM model to a Python class model based on the XMLSchema compo...
"""PyWXSB -- Python W3C XML Schema Bindings. binding - Module used to generate the bindings and at runtime to support the generated bindings utils - Common utilities used in parsing, generating, and running xmlschema - Class that convert XMLSchema from a DOM model to a Python class model based on the XMLSchema compo...
Handle unicode and string creation correctly
Handle unicode and string creation correctly
Python
apache-2.0
jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,CantemoInternal/pyxb,jonfoster/pyxb-upstream-mirror,pabigot/pyxb,CantemoInternal/pyxb,jonfoster/pyxb2,balanced/PyXB,jonfoster/pyxb2,pabigot/pyxb,jonfoster/pyxb2,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,balanced/PyXB,CantemoInternal/pyxb,balanced/PyXB
f2d02748202571bdb3b993788ea218a1a522488d
python/setup.py
python/setup.py
from distutils.core import setup from distutils.core import Extension from distutils.command.build_ext import build_ext as _build_ext import sys modules = [ Extension('wiringX.gpio', sources=['wiringX/wiringx.c', '../wiringX.c', '../hummingboard.c', '../bananapi.c', '../radxa.c', '../raspberrypi.c'], include_dirs=['...
from distutils.core import setup from distutils.core import Extension from distutils.command.build_ext import build_ext as _build_ext import sys modules = [ Extension('wiringX.gpio', sources=['wiringX/wiringx.c', '../wiringX.c', '../hummingboard.c', '../bananapi.c', '../radxa.c', '../raspberrypi.c', '../ci20.c'], in...
Fix issue with Python bindings caused by introduction of CI20 platform
Fix issue with Python bindings caused by introduction of CI20 platform this adds ci20.c to the compile path for Python bindings, otherwise you get the following: ImportError: /usr/lib/python3.4/site-packages/wiringX/gpio.cpython-34m.so: undefined symbol: ci20Init
Python
mpl-2.0
mwischer/wiringX,mwischer/wiringX,bkrepo/wiringX,wiringX/wiringX,mxOBS/wiringX,mxOBS/wiringX,mwischer/wiringX,mxOBS/wiringX,bkrepo/wiringX,wiringX/wiringX,bkrepo/wiringX,wiringX/wiringX
2537cdf45650eb2d7d57d5e108a11658b4d64898
saleor/product/urls.py
saleor/product/urls.py
from django.conf.urls import patterns, url from . import views urlpatterns = [ url(r'^(?P<slug>[a-z0-9-]+?)-(?P<product_id>[0-9]+)/$', views.product_details, name='details'), url(r'^category/(?P<slug>[a-z0-9-]+?)/$', views.category_index, name='category') ]
from django.conf.urls import url from . import views urlpatterns = [ url(r'^(?P<slug>[a-z0-9-]+?)-(?P<product_id>[0-9]+)/$', views.product_details, name='details'), url(r'^category/(?P<slug>[\w-]+?)/$', views.category_index, name='category') ]
Fix url pattern for category's slug
Fix url pattern for category's slug
Python
bsd-3-clause
arth-co/saleor,HyperManTT/ECommerceSaleor,HyperManTT/ECommerceSaleor,rchav/vinerack,paweltin/saleor,avorio/saleor,arth-co/saleor,tfroehlich82/saleor,dashmug/saleor,maferelo/saleor,avorio/saleor,laosunhust/saleor,itbabu/saleor,KenMutemi/saleor,car3oon/saleor,Drekscott/Motlaesaleor,maferelo/saleor,taedori81/saleor,Dreksc...
28f6be52b429eb999a70ff900f526142fc5f162c
tests/test_exec_mixin.py
tests/test_exec_mixin.py
from gears.asset_handler import AssetHandlerError, ExecMixin from mock import patch, Mock from unittest2 import TestCase class Exec(ExecMixin): executable = 'program' class ExecMixinTests(TestCase): @patch('gears.asset_handler.Popen') def test_returns_stdout_on_success(self, Popen): result = Mo...
from __future__ import with_statement from gears.asset_handler import AssetHandlerError, ExecMixin from mock import patch, Mock from unittest2 import TestCase class Exec(ExecMixin): executable = 'program' class ExecMixinTests(TestCase): @patch('gears.asset_handler.Popen') def test_returns_stdout_on_suc...
Fix Python 2.5 support in tests
Fix Python 2.5 support in tests
Python
isc
gears/gears,gears/gears,gears/gears
d83d2bb2ea9bc690a5b279a88fdc22fa23e6299a
tests/test_pagination.py
tests/test_pagination.py
import unittest import sys import os try: from instagram_private_api_extensions import pagination except ImportError: sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from instagram_private_api_extensions import pagination class TestPagination(unittest.TestCase): def test_page(self): ...
import unittest import sys import os try: from instagram_private_api_extensions import pagination except ImportError: sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from instagram_private_api_extensions import pagination class TestPagination(unittest.TestCase): def test_page(self): ...
Add wait for pagination test
Add wait for pagination test
Python
mit
ping/instagram_private_api_extensions
aacfb96c55c5179e768745f06b1586b3c0f70969
pygp/utils/abc.py
pygp/utils/abc.py
""" Modifications to ABC to allow for additional metaclass actions. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports from abc import ABCMeta as ABCMeta_ from abc import abstractmethod # exported symbols __all__ = ['ABCM...
""" Modifications to ABC to allow for additional metaclass actions. """ # future imports from __future__ import division from __future__ import absolute_import from __future__ import print_function # global imports from abc import ABCMeta as ABCMeta_ from abc import abstractmethod # exported symbols __all__ = ['ABCM...
Update the modified ABCMeta to copy docstrings to abstractmethods.
Update the modified ABCMeta to copy docstrings to abstractmethods.
Python
bsd-2-clause
mwhoffman/pygp
738e4ddd0043c204095767f1f7458db9e6948262
tensorflow/tools/docker/jupyter_notebook_config.py
tensorflow/tools/docker/jupyter_notebook_config.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
Allow disabling password and token auth on jupyter notebooks
Allow disabling password and token auth on jupyter notebooks
Python
apache-2.0
Intel-tensorflow/tensorflow,renyi533/tensorflow,hsaputra/tensorflow,zasdfgbnm/tensorflow,dendisuhubdy/tensorflow,ageron/tensorflow,pavelchristof/gomoku-ai,av8ramit/tensorflow,hfp/tensorflow-xsmm,alivecor/tensorflow,Xeralux/tensorflow,seanli9jan/tensorflow,DavidNorman/tensorflow,ghchinoy/tensorflow,seanli9jan/tensorflow...
ee85d2fffc0e42022be66bf667005eb44391cb9e
django/similarities/utils.py
django/similarities/utils.py
import echonest from artists.models import Artist from echonest.models import SimilarResponse from users.models import User from .models import (GeneralArtist, UserSimilarity, Similarity, update_similarities) def add_new_similarities(artist, force_update=False): similarities = [] response...
from django.db.models import Q import echonest from artists.models import Artist from echonest.models import SimilarResponse from users.models import User from .models import (GeneralArtist, UserSimilarity, Similarity, update_similarities) def add_new_similarities(artist, force_update=False): ...
Order similar artist results properly
Order similar artist results properly
Python
bsd-3-clause
FreeMusicNinja/freemusic.ninja,FreeMusicNinja/freemusic.ninja
9f967406e634fcb340fb8af0b8f5981661936038
profile_bs_xf03id/startup/01-bluesky.py
profile_bs_xf03id/startup/01-bluesky.py
from ophyd.commands import setup_ophyd setup_ophyd() from ophyd.commands import * from bluesky.callbacks import * from bluesky.plans import * # from bluesky.spec_api import * from bluesky.utils import install_qt_kicker from bluesky.global_state import (get_gs, abort, stop, resume) from databroker import (DataBroker a...
from ophyd.commands import setup_ophyd setup_ophyd() from ophyd.commands import * from bluesky.callbacks import * from bluesky.plans import * # from bluesky.spec_api import * from bluesky.utils import (install_qt_kicker, register_transform) from bluesky.global_state import (get_gs, abort, stop, resume) from databroke...
Add magic for RE(...) calls
Add magic for RE(...) calls
Python
bsd-2-clause
NSLS-II-HXN/ipython_ophyd,NSLS-II-HXN/ipython_ophyd
64feb2ed638e43f15b7008507907f7d607ebccf3
nbgrader/apps/assignapp.py
nbgrader/apps/assignapp.py
from IPython.config.loader import Config from IPython.config.application import catch_config_error from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp class AssignApp(CustomNbConvertApp): name = Unicode(u'nbgrader-assign') description = Unicode(u'Pre...
from IPython.config.loader import Config from IPython.utils.traitlets import Unicode from nbgrader.apps.customnbconvertapp import CustomNbConvertApp from nbgrader.apps.customnbconvertapp import aliases as base_aliases from nbgrader.apps.customnbconvertapp import flags as base_flags aliases = {} aliases.update(base_al...
Add some flags to nbgrader assign
Add some flags to nbgrader assign
Python
bsd-3-clause
ellisonbg/nbgrader,modulexcite/nbgrader,jupyter/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,jdfreder/nbgrader,EdwardJKim/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,dementrock/nbgrader,EdwardJKim/nbgrader,ellisonbg/nbgrader,dementrock/nbgrader,alope107/nbgrader,MatKallada/nbgrader,jhamrick/nbgrader,ellisonbg/nbgrader...
ea902f4002344c1cbf56dbd989c27aa1ad41a363
task_run_system.py
task_run_system.py
import sys import bson.objectid import config.global_configuration as global_conf import database.client import batch_analysis.trial_runner as trial_runner def main(*args): """ Run a given system with a given image source. This represents a basic task. Scripts to run this will be autogenerated by the ...
import sys import bson.objectid import config.global_configuration as global_conf import database.client import core.image_collection import core.image_entity import systems.deep_learning.keras_frcnn import batch_analysis.trial_runner as trial_runner def main(*args): """ Run a given system with a given image ...
Make the run system task more error friendly
Make the run system task more error friendly
Python
bsd-2-clause
jskinn/robot-vision-experiment-framework,jskinn/robot-vision-experiment-framework
2a494efd72d34ac638763d162559d43fe3705698
test/test_datac.py
test/test_datac.py
# -*- coding: utf-8 -*- import datac import numpy as np import os params = {"temp_sun": 6000.} bandgaps = np.linspace(0, 3.25, 100) abscissae = datac.generate_abscissae(bandgaps, "bandgap", params) pwd = os.getcwd() testdir = "test" filename = "data.dat" fqpn = os.path.join(pwd, testdir, filename) datac.write_json(f...
# -*- coding: utf-8 -*- import datac import numpy as np import os import unittest class dummyclass(object): """ Simple class for testing `generate_ordinates` """ def __init__(self, params): pass def fun(self): """ Return value of `True` """ return True par...
Add dummy class to test generate_ordinates
Add dummy class to test generate_ordinates
Python
mit
jrsmith3/datac,jrsmith3/datac
f07a114ed23109c9b834b2cbc37ba54c728d73cb
fmn/lib/__init__.py
fmn/lib/__init__.py
""" fedmsg-notifications internal API """ import fmn.lib.models import logging log = logging.getLogger(__name__) def recipients(session, config, message): """ The main API function. Accepts a fedmsg message as an argument. Returns a dict mapping context names to lists of recipients. """ res =...
""" fedmsg-notifications internal API """ import fmn.lib.models import logging log = logging.getLogger(__name__) def recipients(session, config, message): """ The main API function. Accepts a fedmsg message as an argument. Returns a dict mapping context names to lists of recipients. """ res =...
Restructure the valid_paths list into a dict.
Restructure the valid_paths list into a dict.
Python
lgpl-2.1
jeremycline/fmn,jeremycline/fmn,jeremycline/fmn
f264a06db669df1017df60d932b301dac7208233
sqk/datasets/models.py
sqk/datasets/models.py
from django.db import models from django.utils import timezone class Dataset(models.Model): name = models.CharField(max_length=100, default='') description = models.CharField(max_length=500, default='') source = models.FileField(upload_to='data_sources') created_at = models.DateTimeField('created at', ...
from django.db import models from django.utils import timezone class Dataset(models.Model): name = models.CharField(max_length=100, default='') description = models.CharField(max_length=500, default='') source = models.FileField(upload_to='data_sources') created_at = models.DateTimeField('created at', ...
Add is_label_name field to Feature model
Add is_label_name field to Feature model
Python
bsd-3-clause
sloria/sepal,sloria/sepal,sloria/sepal,sloria/sepal,sloria/sepal
26833c5d41bb3611aa61655c28da4d40b173712e
Orange/tests/test_preprocess.py
Orange/tests/test_preprocess.py
import unittest from mock import Mock, MagicMock, patch import Orange class TestPreprocess(unittest.TestCase): def test_read_data_calls_reader(self): class MockPreprocessor(Orange.preprocess.preprocess.Preprocess): __init__ = Mock() __call__ = Mock() @classmethod ...
import unittest from mock import Mock, MagicMock, patch import Orange class TestPreprocess(unittest.TestCase): def test_read_data_calls_reader(self): class MockPreprocessor(Orange.preprocess.preprocess.Preprocess): __init__ = Mock(return_value=None) __call__ = Mock() @...
Fix tests for Preprocess constructors
Fix tests for Preprocess constructors
Python
bsd-2-clause
qusp/orange3,qusp/orange3,qPCR4vir/orange3,qusp/orange3,qPCR4vir/orange3,kwikadi/orange3,qPCR4vir/orange3,qPCR4vir/orange3,marinkaz/orange3,marinkaz/orange3,cheral/orange3,qPCR4vir/orange3,qPCR4vir/orange3,kwikadi/orange3,cheral/orange3,kwikadi/orange3,marinkaz/orange3,qusp/orange3,kwikadi/orange3,cheral/orange3,marink...
23a8943d2e3688753371b08c490aaae2052eb356
ckanext/mapactionevent/logic/action/create.py
ckanext/mapactionevent/logic/action/create.py
import ckan.logic as logic import ckan.plugins.toolkit as toolkit def event_create(context, data_dict): """ Creates a 'event' type group with a custom unique identifier for the event """ if data_dict.get('name'): name = data_dict.get('name') else: # Generate a new operation ID ...
import ckan.logic as logic import ckan.plugins.toolkit as toolkit def event_create(context, data_dict): """ Creates a 'event' type group with a custom unique identifier for the event """ if data_dict.get('name'): name = data_dict.get('name') else: # Generate a new operation ID ...
Make auto-incrementing event names work with a mixture of numeric and non-numeric event names
Make auto-incrementing event names work with a mixture of numeric and non-numeric event names
Python
agpl-3.0
aptivate/ckanext-mapactionevent,aptivate/ckanext-mapactionevent,aptivate/ckanext-mapactionevent
f306f78304d657a163b2a03284c83afc09271e2b
populous/cli.py
populous/cli.py
import click @click.group() @click.version_option() def cli(): pass
import click from .loader import load_yaml from .blueprint import Blueprint @click.group() @click.version_option() def cli(): pass @cli.command() @click.argument('files', nargs=-1) def predict(files): """ Predict how many objects will be created if the given files are used. """ blueprint = Blue...
Add a naive implementation of the predict command
Add a naive implementation of the predict command
Python
mit
novafloss/populous
0ac8062ea2c16edcc5d81c14976413a3ddde43b6
clowder_test/clowder_test/clowder_test_app.py
clowder_test/clowder_test/clowder_test_app.py
# -*- coding: utf-8 -*- """Clowder test command line app .. codeauthor:: Joe Decapo <joe@polka.cat> """ from __future__ import print_function import os import colorama from cement.core.foundation import CementApp from clowder_test import ROOT_DIR from clowder_test.cli.base_controller import BaseController from cl...
# -*- coding: utf-8 -*- """Clowder test command line app .. codeauthor:: Joe Decapo <joe@polka.cat> """ from __future__ import print_function import os import colorama from cement.core.foundation import CementApp from clowder_test import ROOT_DIR from clowder_test.cli.base_controller import BaseController from cl...
Move clowder_test directory setup to post arg parse hook
Move clowder_test directory setup to post arg parse hook
Python
mit
JrGoodle/clowder,JrGoodle/clowder,JrGoodle/clowder
bc97d63893858ba8cbcd44f83f4123fdd826ac71
addons/bestja_api_user/models.py
addons/bestja_api_user/models.py
# -*- coding: utf-8 -*- from openerp import models, fields, api class User(models.Model): _inherit = 'res.users' def __init__(self, pool, cr): super(User, self).__init__(pool, cr) self._add_permitted_fields(level='privileged', fields={'email'}) self._add_permitted_fields(level='owner'...
# -*- coding: utf-8 -*- from openerp import models, fields, api class User(models.Model): _inherit = 'res.users' def __init__(self, pool, cr): super(User, self).__init__(pool, cr) self._add_permitted_fields(level='privileged', fields={'email'}) self._add_permitted_fields(level='owner'...
Fix for Partner's email not being accessible to administrator
Fix for Partner's email not being accessible to administrator
Python
agpl-3.0
EE/bestja,EE/bestja,ludwiktrammer/bestja,ludwiktrammer/bestja,ludwiktrammer/bestja,EE/bestja
2f168fa2886a4e3c00f15b5407bb860f0f9b38f4
main.py
main.py
""" Classify images using random decision forests """ import sys from mlearner import train_model from utils import get_feature_vector def classify_image(image_path, clf): """ Classify given image """ fvecs = [get_feature_vector(image_path)] print(clf.predict(fvecs)) def main(): if len(sys.argv...
""" Classify images using random decision forests """ import sys, os from mlearner import train_model from utils import get_feature_vector def classify_image(image_path, clf): """ Classify given image """ fvecs = [get_feature_vector(image_path)] print(clf.predict(fvecs), clf.predict_proba(fvecs)) d...
Add ability to test model on all images in some directory
Add ability to test model on all images in some directory
Python
mit
kpj/PyClass
06a71d22df5b6f1196cbdff737ab071ba92fad0b
spacy/tests/regression/test_issue834.py
spacy/tests/regression/test_issue834.py
# coding: utf-8 from io import StringIO word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" def test_issue834(en_vocab): f = StringIO(word2vec_str) vector_length = en_vocab.load_vectors(f) assert vector_lengt...
# coding: utf-8 from __future__ import unicode_literals from io import StringIO word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" def test_issue834(en_vocab): f = StringIO(word2vec_str) vector_length = en_vocab...
Fix test failure by using unicode literals
Fix test failure by using unicode literals
Python
mit
explosion/spaCy,banglakit/spaCy,aikramer2/spaCy,spacy-io/spaCy,raphael0202/spaCy,recognai/spaCy,Gregory-Howard/spaCy,honnibal/spaCy,spacy-io/spaCy,aikramer2/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,raphael0202/spaCy,raphael0202/spaCy,recognai/spaCy,honnibal/spaCy,raphael0202/spaCy,explosion/s...
b674f76c93b5208ad302fcba2d43b8c30bbaf14c
main.py
main.py
from altitude import run run.run("27279", "C://Program Files (x86)/Altitude/servers/command.txt", "C://Program Files (x86)/Altitude/servers/log.txt", "C://Program Files (x86)/Altitude/servers/log_old.txt", "C://Program Files (x86)/Altitude/servers/logs_archive.txt")
from altitude import run run.run("27279", "/home/user/altitude-files/servers/command.txt", "/home/user/altitude-files/servers/log.txt", "/home/user/altitude-files/servers/log_old.txt", "/home/user/altitude-files/servers/logs_archive.txt")
Put the directories back as they were for the server
Put the directories back as they were for the server
Python
mit
StamKaly/altitude-mod,StamKaly/altitude-mod
cfaeb584ed74b10de76247a6984c0c6950a1eb25
Ispyra/checks.py
Ispyra/checks.py
from discord.ext import commands from bot_globals import bot_masters, blacklist #Check if a user is allowed to use a command #Perm 0 is simply blacklist checking #Perm 1 also checks if the user is a botmaster def allowed(perm, pref): def permission(ctx): uid = ctx.message.author.id if perm == 0: ...
from discord.ext import commands from bot_globals import bot_masters, blacklist #Check if a user is allowed to use a command #Perm 0 is simply blacklist checking #Perm 1 also checks if the user is a botmaster def allowed(perm, pref): def permission(ctx): uid = ctx.message.author.id if perm == 0: ...
Fix prefix checking only working for botmaster commands
Fix prefix checking only working for botmaster commands
Python
mit
Ispira/Ispyra
791f64250d5e7c2ac2c5e01aa1e890dbefbc0417
falcon_hateoas/middleware.py
falcon_hateoas/middleware.py
import json import decimal import datetime import sqlalchemy class AlchemyJSONEncoder(json.JSONEncoder): def _is_alchemy_object(self, obj): try: sqlalchemy.orm.base.object_mapper(obj) return True except sqlalchemy.orm.exc.UnmappedInstanceError: return False ...
import json import decimal import datetime class AlchemyJSONEncoder(json.JSONEncoder): def default(self, o): d = {} for col in o.__table__.columns.keys(): value = getattr(o, col) if hasattr(value, 'isoformat'): d[col] = value.isoformat() elif isi...
Remove dead code from AlchemyJSONEncoder
Remove dead code from AlchemyJSONEncoder Signed-off-by: Michal Juranyi <29976087921aeab920eafb9b583221faa738f3f4@vnet.eu>
Python
mit
Vnet-as/falcon-hateoas
6259df76129327a42c08fdd4b999ea7c617c6c9d
project/ndaparser/models.py
project/ndaparser/models.py
# -*- coding: utf-8 -*- import datetime import slugify as unicodeslugify from django.db import models, transaction from django.conf import settings from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from asylum.models import AsylumModel def get_sentinel_user(): ...
# -*- coding: utf-8 -*- import datetime import slugify as unicodeslugify from django.db import models, transaction from django.conf import settings from django.contrib.auth import get_user_model from django.utils.translation import ugettext_lazy as _ from asylum.models import AsylumModel def get_sentinel_user(): ...
Fix the filename normalizing to keep extension
Fix the filename normalizing to keep extension
Python
mit
rambo/asylum,jautero/asylum,HelsinkiHacklab/asylum,rambo/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,rambo/asylum,jautero/asylum,hacklab-fi/asylum,HelsinkiHacklab/asylum,rambo/asylum,HelsinkiHacklab/asylum,hacklab-fi/asylum,jautero/asylum,hacklab-fi/asylum,jautero/asylum
a6a88fac6300b92c82e797f72477df1df6b87dbe
faq/views.py
faq/views.py
from django.http import Http404 from django.views.generic import ListView, DetailView from faq.models import Question, Category class FAQQuestionListView(ListView): context_object_name = "question_list" template_name = "faq/question_list.html" def get_queryset(self): return Question.objects.all() class FAQQ...
from django.http import Http404 from django.views.generic import ListView, DetailView from faq.models import Question, Category class FAQQuestionListView(ListView): context_object_name = "question_list" template_name = "faq/question_list.html" def get_queryset(self): return Question.objects.filter(categories...
Index should be ones without a category.
Index should be ones without a category.
Python
bsd-3-clause
myles-archive/django-faq,asgardproject/django-faq
0ecea9e68755bb7f03702b68d3f8565dde4fd16b
src/squibs/memsquib.py
src/squibs/memsquib.py
#!/usr/bin/python2 # vim:set ts=4 sw=4 et nowrap syntax=python ff=unix: ############################################################################## import sys, time def memory (): f = open('/proc/meminfo', 'r') lines = f.readlines() f.close() mem = [] for x in range(4): mem.append(int(...
#!/usr/bin/python2 # vim:set ts=4 sw=4 et nowrap syntax=python ff=unix: ############################################################################## import sys, time def memory (): f = open('/proc/meminfo', 'r') lines = f.readlines() f.close() mem = [] for x in range(4): mem.append(int(...
Add a memory used metric
Add a memory used metric
Python
apache-2.0
mcrewson/squib
f4d87b49f100121896ab147e08f634ebcf68ae40
generator.py
generator.py
import graph def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print("<!DOCTYPE html>\n<html>\n<head>\n" + ...
import graph import datetime def generate(): count = graph.getTotalCount() zahajeni = graph.getSkupinaZahajeni(count) probihajici = graph.getSkupinaProbihajici(count) printHeader() printBody(count, zahajeni, probihajici) printFooter() def printHeader(): print("<!DOCTYPE html>\n<html>\n<...
Print generated date & time
Print generated date & time
Python
mit
eghuro/pirgroups
199b3b2d95c7ada67a0b3c49abe9b6347266c0eb
codefett/users/serializers.py
codefett/users/serializers.py
from rest_framework import serializers from .models import CFUser class CFUserSerializer(serializers.ModelSerializer): """ Serializes a CFUser Model """ user__password = serializers.CharField(write_only=True, required=False) class Meta: model = CFUser fields = ('id', 'user__email'...
from django.contrib.auth import update_session_auth_hash from rest_framework import serializers from .models import CFUser class CFUserSerializer(serializers.ModelSerializer): """ Serializes a CFUser Model """ password = serializers.CharField(write_only=True, required=False) confirm_password = ser...
Complete update method of User Serializer
Complete update method of User Serializer
Python
agpl-3.0
Rulox/codefett,Rulox/codefett,Rulox/codefett
4e5674d938e40d86a140ec591d6a7429b9c29902
test/conftest.py
test/conftest.py
def pytest_addoption(parser): parser.addoption("--webdriver", action="store", default="None", help=("Selenium WebDriver interface to use for running the test. " "Choices: None, PhantomJS, Chrome, Firefox, ChromeHeadless, " "FirefoxHeadless....
import os def pytest_addoption(parser): parser.addoption("--webdriver", action="store", default="None", help=("Selenium WebDriver interface to use for running the test. " "Choices: None, PhantomJS, Chrome, Firefox, ChromeHeadless, " "Firef...
Add --offline flag for testing without downloads
Add --offline flag for testing without downloads
Python
bsd-3-clause
spacetelescope/asv,qwhelan/asv,spacetelescope/asv,airspeed-velocity/asv,spacetelescope/asv,spacetelescope/asv,airspeed-velocity/asv,airspeed-velocity/asv,pv/asv,pv/asv,qwhelan/asv,pv/asv,qwhelan/asv,qwhelan/asv,airspeed-velocity/asv,pv/asv
d47e3b7216effab8aa067d0a214b071ca77393fd
stories/serializers.py
stories/serializers.py
from rest_framework import serializers from users.serializers import AuthorSerializer from .models import Story, StoryLine class StoryLineSerializer(serializers.ModelSerializer): class Meta: model = StoryLine fields = ('id', 'content', 'posted_on') class StorySerializer(serializers.ModelSeriali...
from rest_framework import serializers from users.serializers import AuthorSerializer from .models import Story, StoryLine class StoryLineSerializer(serializers.ModelSerializer): class Meta: model = StoryLine fields = ('id', 'content', 'posted_on') class StorySerializer(serializers.ModelSeriali...
Set stories_set to read only field
Set stories_set to read only field
Python
mit
pu6ki/tarina,pu6ki/tarina,pu6ki/tarina
ca8fa466638c0ef405a82dfc3cfecfdb400faaa7
sublime_jedi/helper.py
sublime_jedi/helper.py
# -*- coding: utf-8 -*- import sublime import sublime_plugin from .utils import ask_daemon class HelpMessageCommand(sublime_plugin.TextCommand): def run(self, edit, docstring): self.view.close() self.view.insert(edit, self.view.size(), docstring) class SublimeJediDocstring(sublime_plugin.TextC...
# -*- coding: utf-8 -*- import sublime import sublime_plugin from .utils import ask_daemon, PythonCommandMixin class HelpMessageCommand(sublime_plugin.TextCommand): def run(self, edit, docstring): self.view.close() self.view.insert(edit, self.view.size(), docstring) class SublimeJediDocstring(...
Hide documentation commands in non-python scope
Hide documentation commands in non-python scope
Python
mit
srusskih/SublimeJEDI,edelvalle/SublimeJEDI
ea43efc9d820833090670305a73543b43cf4286b
test/test_pyc.py
test/test_pyc.py
""" Test completions from *.pyc files: - generated a dummy python module - compile the dummy module to generate a *.pyc - delete the pure python dummy module - try jedi on the generated *.pyc """ import os import compileall import jedi SRC = """class Foo: pass class Bar: pass """ def generate_pyc(): ...
""" Test completions from *.pyc files: - generate a dummy python module - compile the dummy module to generate a *.pyc - delete the pure python dummy module - try jedi on the generated *.pyc """ import compileall import os import shutil import sys import jedi SRC = """class Foo: pass class Bar: pass ""...
Fix pyc test for python3
Fix pyc test for python3 To import pyc modules, we must move them out of the __pycache__ directory and rename them to remove ".cpython-%s%d". This should still faild with python3 (UnicodeDecodeError)
Python
mit
flurischt/jedi,flurischt/jedi,dwillmer/jedi,jonashaag/jedi,WoLpH/jedi,jonashaag/jedi,mfussenegger/jedi,tjwei/jedi,dwillmer/jedi,tjwei/jedi,mfussenegger/jedi,WoLpH/jedi
997b8fc0658a5c581d65211285bf11df771889a4
app/single_resource/forms.py
app/single_resource/forms.py
from flask.ext.wtf import Form from wtforms.fields import FloatField, StringField, SubmitField from wtforms.validators import InputRequired, Length class SingleResourceForm(Form): name = StringField('Name', validators=[ InputRequired(), Length(1, 500) ]) address = StringField('Address', va...
from flask.ext.wtf import Form from wtforms.fields import FloatField, StringField, SubmitField from wtforms.validators import InputRequired, Length, Optional class SingleResourceForm(Form): name = StringField('Name', validators=[ InputRequired(), Length(1, 500) ]) address = StringField('Ad...
Add validator if latitude/longitude is empty
Add validator if latitude/longitude is empty
Python
mit
hack4impact/maps4all,hack4impact/maps4all,hack4impact/maps4all,hack4impact/maps4all
906505d85914287af3a031bf77f74dd79a4aaa32
pygraphc/preprocess/CreateGraphModel.py
pygraphc/preprocess/CreateGraphModel.py
from pygraphc.preprocess.ParallelPreprocess import ParallelPreprocess from pygraphc.similarity.JaroWinkler import JaroWinkler from pygraphc.pruning.TrianglePruning import TrianglePruning import networkx as nx class CreateGraphModel(object): def __init__(self, log_file): self.log_file = log_file se...
from pygraphc.preprocess.ParallelPreprocess import ParallelPreprocess from pygraphc.similarity.CosineSimilarity import ParallelCosineSimilarity from pygraphc.pruning.TrianglePruning import TrianglePruning import networkx as nx class CreateGraphModel(object): def __init__(self, log_file): self.log_file = l...
Change jaro-winkler to cosine similarity
Change jaro-winkler to cosine similarity
Python
mit
studiawan/pygraphc
19a58255f247199d0e60408cab8220a8c2a1ff3b
qxlc/minifier.py
qxlc/minifier.py
import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(text): return Markup(htmlmin.minify(text.unescape(), remove_comments=True, remove_empty_space=True))
import htmlmin from markupsafe import Markup from qxlc import app @app.template_filter("minify") def minify_filter(s): return Markup(htmlmin.minify(str(s), remove_comments=True, remove_empty_space=True))
Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)
Use str(s) instead of s.unescape() to add support for escaping things inside. (took me a while to find that str() worked)
Python
apache-2.0
daboross/qxlc,daboross/qxlc
fbae436ae2d9ee29b64f81331ee3b316b153f750
locksmith/common.py
locksmith/common.py
import hashlib import hmac import urllib, urllib2 KEY_STATUSES = ( ('U', 'Unactivated'), ('A', 'Active'), ('S', 'Suspended') ) UNPUBLISHED, PUBLISHED, NEEDS_UPDATE = range(3) PUB_STATUSES = ( (UNPUBLISHED, 'Unpublished'), (PUBLISHED, 'Published'), (NEEDS_UPDATE, 'Needs Update'), ) def get_si...
import hashlib import hmac import urllib, urllib2 KEY_STATUSES = ( ('U', 'Unactivated'), ('A', 'Active'), ('S', 'Suspended') ) UNPUBLISHED, PUBLISHED, NEEDS_UPDATE = range(3) PUB_STATUSES = ( (UNPUBLISHED, 'Unpublished'), (PUBLISHED, 'Published'), (NEEDS_UPDATE, 'Needs Update'), ) def get_sig...
Make get_signature support unicode characters by encoding to utf-8 instead of ascii.
Make get_signature support unicode characters by encoding to utf-8 instead of ascii.
Python
bsd-3-clause
sunlightlabs/django-locksmith,sunlightlabs/django-locksmith,sunlightlabs/django-locksmith
f180f75d97439b10e2325c1e85b88c0ecfb03e73
bmi_tester/tests/__init__.py
bmi_tester/tests/__init__.py
# Both of these variables should be overriden to test a particular # BMI class Bmi = None INPUT_FILE = None
# Both of these variables should be overriden to test a particular # BMI class Bmi = None INPUT_FILE = None BMI_VERSION_STRING = '1.1'
Set default for BMI_VERSION_STRING to 1.1.
Set default for BMI_VERSION_STRING to 1.1.
Python
mit
csdms/bmi-tester
f81e409ab1666a8a3bb1ff1806d256644712382f
structures/__init__.py
structures/__init__.py
#!/usr/bin/python # -*- coding: utf-8 -*- from .base import DBStructure, _Generated from .files.main import * from .files.custom import * from ..locales import L class StructureError(Exception): pass class StructureLoader(): wowfiles = None @classmethod def setup(cls): if cls.wowfiles is None: cls.wowfile...
#!/usr/bin/python # -*- coding: utf-8 -*- from .base import DBStructure, _Generated from .files.main import * from .files.custom import * from ..locales import L class UnknownStructure(Exception): pass class StructureLoader(): wowfiles = None @classmethod def setup(cls): if cls.wowfiles is None: cls.wowfi...
Raise more appropriate UnknownStructure exception rather than StructureError if a structure is not found.
structures: Raise more appropriate UnknownStructure exception rather than StructureError if a structure is not found.
Python
cc0-1.0
jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow
f8d551627781ea9568b97a426135bce74adf3adf
utils/helpers.py
utils/helpers.py
import boto3 class Helpers(object): """A container class for convenience functions.""" _aws_account_id = None @classmethod def aws_account_id(cls): """Query for the current account ID by inspecting the default security group.""" if cls._aws_account_id is None: cls._aws_ac...
import boto3 class Helpers(object): """A container class for convenience functions.""" _aws_account_id = None @classmethod def aws_account_id(cls): """Query for the current account ID by inspecting the caller identity.""" if cls._aws_account_id is None: caller_data = boto...
Use get_caller_identity instead of default SG to determine account id
Use get_caller_identity instead of default SG to determine account id
Python
mit
dliggat/local-lambda-toolkit
55e316a45256d054d19425015ef13868a84c5ff1
src/pip/_internal/resolution/resolvelib/reporter.py
src/pip/_internal/resolution/resolvelib/reporter.py
from collections import defaultdict from logging import getLogger from pip._vendor.resolvelib.reporters import BaseReporter from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import DefaultDict from .base import Candidate logger = getLogger(__name__) class PipRe...
from collections import defaultdict from logging import getLogger from pip._vendor.resolvelib.reporters import BaseReporter from pip._internal.utils.typing import MYPY_CHECK_RUNNING if MYPY_CHECK_RUNNING: from typing import DefaultDict from .base import Candidate logger = getLogger(__name__) class PipRe...
Add the last line to the info message
Add the last line to the info message
Python
mit
sbidoul/pip,pradyunsg/pip,pypa/pip,pypa/pip,sbidoul/pip,pfmoore/pip,pfmoore/pip,pradyunsg/pip
fb65fedbf60481d37e097ea9db290f53b84cae26
giveaminute/migrations/versions/001_Initial_models.py
giveaminute/migrations/versions/001_Initial_models.py
from sqlalchemy import * from migrate import * def upgrade(migrate_engine): # Upgrade operations go here. Don't create your own engine; bind migrate_engine # to your metadata import os with open(os.path.join(os.path.dirname(__file__), '000_Initial_models.sql')) as initial_file: sql = initi...
from sqlalchemy import * from migrate import * def upgrade(migrate_engine): # Upgrade operations go here. Don't create your own engine; bind migrate_engine # to your metadata import os # Uncomment the following lines if you do not yet have a database to set up. # If you run this migration, it will...
Comment out the initial migration step by default (so that we're not inadvertently blowing peoples databases away
Comment out the initial migration step by default (so that we're not inadvertently blowing peoples databases away
Python
agpl-3.0
codeforamerica/Change-By-Us,localprojects/Change-By-Us,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,localprojects/Change-By-Us,codeforeurope/Change-By-Us,codeforeurope/Change-By-Us,codeforamerica/Change-By-Us,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,localprojects/Change-By-Us,localprojects/Change-By-Us,watchcat/c...
a0c9e2d6d5115aba04a650281b10d47e31873671
tensorflow/contrib/distributions/python/__init__.py
tensorflow/contrib/distributions/python/__init__.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
Fix futures test Change: 115766190
Fix futures test Change: 115766190
Python
apache-2.0
mortada/tensorflow,maciekcc/tensorflow,yaroslavvb/tensorflow,AnishShah/tensorflow,pcm17/tensorflow,eaplatanios/tensorflow,arborh/tensorflow,tornadozou/tensorflow,horance-liu/tensorflow,Intel-Corporation/tensorflow,tntnatbry/tensorflow,gojira/tensorflow,brchiu/tensorflow,nburn42/tensorflow,tillahoffmann/tensorflow,horan...
9846559d9164216924e5f8bb1544148b3e6965b6
tensorflow_time_two/python/ops/time_two_ops_test.py
tensorflow_time_two/python/ops/time_two_ops_test.py
# Copyright 2018 The Sonnet Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
# Copyright 2018 The Sonnet Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
Make test works with make and bazel
Make test works with make and bazel
Python
apache-2.0
tensorflow/custom-op,tensorflow/custom-op,tensorflow/custom-op