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
d7df867b2a5e7c8f5255d9e7627999c3e2132e9c
example/tests/test_utils.py
example/tests/test_utils.py
""" Test rest_framework_json_api's utils functions. """ from rest_framework_json_api import utils from ..serializers import EntrySerializer from ..tests import TestBase class GetRelatedResourceTests(TestBase): """ Ensure the `get_related_resource_type` function returns correct types. """ def test_re...
""" Test rest_framework_json_api's utils functions. """ from rest_framework_json_api import utils from ..serializers import EntrySerializer from ..tests import TestBase class GetRelatedResourceTests(TestBase): """ Ensure the `get_related_resource_type` function returns correct types. """ def test_re...
Add failing test for m2m too.
Add failing test for m2m too.
Python
bsd-2-clause
abdulhaq-e/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,Instawork/django-rest-framework-json-api,django-json-api/rest_framework_ember,django-json-api/django-rest-framework-json-api
e790e47e6b87bc2e49e8b74d491eb023c4468254
src/sentry/web/frontend/csrf_failure.py
src/sentry/web/frontend/csrf_failure.py
from __future__ import absolute_import from django.middleware.csrf import REASON_NO_REFERER from sentry.web.frontend.base import BaseView class CsrfFailureView(BaseView): auth_required = False sudo_required = False def handle(self, request, reason=""): context = { 'no_referer': reas...
from __future__ import absolute_import from django.middleware.csrf import REASON_NO_REFERER from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from django.utils.decorators import method_decorator from sentry.web.helpers import render_to_response class CsrfFailureView(View): ...
Kill possible recursion on csrf decorator
Kill possible recursion on csrf decorator
Python
bsd-3-clause
boneyao/sentry,jean/sentry,boneyao/sentry,mvaled/sentry,felixbuenemann/sentry,kevinlondon/sentry,TedaLIEz/sentry,JamesMura/sentry,kevinastone/sentry,korealerts1/sentry,JackDanger/sentry,songyi199111/sentry,songyi199111/sentry,fuziontech/sentry,JamesMura/sentry,BuildingLink/sentry,camilonova/sentry,wujuguang/sentry,argo...
156d62f15963bc95f52db7eb1493fad6890e2fc7
dadi/__init__.py
dadi/__init__.py
import numpy # This gives a nicer printout for masked arrays. numpy.ma.default_real_fill_value = numpy.nan import IO import Integration import PhiManip import SFS import ms try: import os __DIRECTORY__ = os.path.dirname(IO.__file__) __svn_file__ = os.path.join(__DIRECTORY__, 'svnversion') __SVNVERSION...
import numpy # This gives a nicer printout for masked arrays. numpy.ma.default_real_fill_value = numpy.nan import IO import Integration import PhiManip import SFS import ms import Plotting try: import os __DIRECTORY__ = os.path.dirname(IO.__file__) __svn_file__ = os.path.join(__DIRECTORY__, 'svnversion') ...
Add Plotting to default imports.
Add Plotting to default imports. git-svn-id: 4c7b13231a96299fde701bb5dec4bd2aaf383fc6@43 979d6bd5-6d4d-0410-bece-f567c23bd345
Python
bsd-3-clause
beni55/dadi,beni55/dadi,ChenHsiang/dadi,RyanGutenkunst/dadi,paulirish/dadi,yangjl/dadi,ChenHsiang/dadi,cheese1213/dadi,yangjl/dadi,cheese1213/dadi,paulirish/dadi,niuhuifei/dadi,niuhuifei/dadi,RyanGutenkunst/dadi
cb72e1107096df9b80915fad4ee0fd1d930c7b59
examples/redis/src/bolts.py
examples/redis/src/bolts.py
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += i...
from collections import Counter from redis import StrictRedis from streamparse import Bolt class WordCountBolt(Bolt): outputs = ['word', 'count'] def initialize(self, conf, ctx): self.counter = Counter() self.total = 0 def _increment(self, word, inc_by): self.counter[word] += i...
Add missing outputs to wordcount_mem topology
Add missing outputs to wordcount_mem topology
Python
apache-2.0
Parsely/streamparse,Parsely/streamparse
933fcfff7a9c63b03e13b0bb7756f0530603c556
series.py
series.py
"""Read and print an integer series.""" import sys def read_series(filename): f = open(filename, mode='rt', encoding='utf-8') series = [] for line in f: a = int(line.strip()) series.append(a) f.close() return series def main(filename): print(read_series(filename)) if __nam...
"""Read and print an integer series.""" import sys def read_series(filename): try: f = open(filename, mode='rt', encoding='utf-8') return [int(line.strip()) for line in f] finally: f.close() def main(filename): print(read_series(filename)) if __name__ == '__main__': main(s...
Refactor to ensure closing and also use list comprehension
Refactor to ensure closing and also use list comprehension
Python
mit
kentoj/python-fundamentals
35c44f0f585d11dea632e509b9eec20d4697dc9d
functions/eitu/timeedit_to_csv.py
functions/eitu/timeedit_to_csv.py
import requests import csv import ics_parser URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics' URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics' def fetch_and_parse(url): return ics_parser.parse(...
import requests import csv from datetime import datetime import ics_parser URL_STUDY_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6Q7Z6QQw0Z5gQ9f50on7Xx5YY00ZQ1ZYQycZw.ics' URL_ACTIVITIES = 'https://dk.timeedit.net/web/itu/db1/public/ri6g7058yYQZXxQ5oQgZZ0vZ56Y1Q0f5c0nZQwYQ.ics' def fetch_and_parse(url)...
Sort events by start and iso format datetimes
Sort events by start and iso format datetimes
Python
mit
christianknu/eitu,christianknu/eitu,eitu/eitu,christianknu/eitu,eitu/eitu
194e01f54c710c7eebc0105942c10337dedb90d9
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup import os from deflect import __version__ as version def read_file(filename): """ Utility function to read a provided filename. """ return open(os.path.join(os.path.dirname(__file__), filename)).read() packages = [ 'deflect', ] package_da...
#!/usr/bin/env python from distutils.core import setup import os from deflect import __version__ as version def read_file(filename): """ Utility function to read a provided filename. """ return open(os.path.join(os.path.dirname(__file__), filename)).read() packages = [ 'deflect', 'deflect....
Add tests module to packaging list
Add tests module to packaging list
Python
bsd-3-clause
jbittel/django-deflect
cfb4d6fb92f7eaed5bfea18ae0b3b772ce868097
tasks.py
tasks.py
from invoke import task, run @task def clean_docs(): run("rm -rf docs/_build") @task('clean_docs') def docs(): run("sphinx-build docs docs/_build") run("open docs/_build/index.html") @task def flake8(): run("flake8 binaryornot tests") @task def autopep8(): run("autopep8 --in-place --aggressive -...
from invoke import task, run @task def clean_docs(): run("rm -rf docs/_build") run("rm -rf docs/binaryornot.rst") run("rm -rf docs/modules.rst") @task('clean_docs') def docs(): run("sphinx-apidoc -o docs/ binaryornot/") run("sphinx-build docs docs/_build") run("open docs/_build/index.html") @...
Use sphinx-apidoc to generate API docs from docstrings.
Use sphinx-apidoc to generate API docs from docstrings.
Python
bsd-3-clause
hackebrot/binaryornot,hackebrot/binaryornot,audreyr/binaryornot,0k/binaryornot,audreyr/binaryornot,pombredanne/binaryornot,0k/binaryornot,pombredanne/binaryornot,hackebrot/binaryornot,audreyr/binaryornot,pombredanne/binaryornot
00ab7f48fff7f824e7db41bd8fedf1623f904a42
awsume/awsumepy/lib/saml.py
awsume/awsumepy/lib/saml.py
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) attributes = response.get('saml2p:Response', {}).g...
import base64 import xmltodict import json import colorama from . safe_print import safe_print from . exceptions import SAMLAssertionParseError def parse_assertion(assertion: str) -> list: roles = [] response = xmltodict.parse(base64.b64decode(assertion)) if response.get('saml2p:Response') is not None: ...
Handle SAML 1 in addition to SAML 2.
Handle SAML 1 in addition to SAML 2.
Python
mit
trek10inc/awsume,trek10inc/awsume
e5939631835ce04d808246fdc391c95354f3b044
slug/posix.py
slug/posix.py
""" Versions of the base functionality optimized for by-the-spec POSIX. Linux/Mac/BSD-specific code should live elsewhere. """ import signal from . import base __all__ = ('Process',) class Process(base.Process): def pause(self): """ Pause the process, able to be continued later """ ...
""" Versions of the base functionality optimized for by-the-spec POSIX. Linux/Mac/BSD-specific code should live elsewhere. """ import signal import selectors from . import base __all__ = ('Process', 'Valve') class Process(base.Process): def pause(self): """ Pause the process, able to be continue...
Correct Valve behavior on Posix
Correct Valve behavior on Posix
Python
bsd-3-clause
xonsh/slug
99947acb784d975319bd99240abed066a4f0a51f
pytablewriter/_converter.py
pytablewriter/_converter.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import re def lower_bool_converter(bool_value): return str(bool_value).lower() def strip_quote(text, value): re_replace = re.compile( '["\']%s["\']' % (value), re.MULTILINE) ...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <gogogo.vm@gmail.com> """ from __future__ import absolute_import import re def lower_bool_converter(bool_value): return str(bool_value).lower() def str_datetime_converter(value): return value.strftime("%Y-%m-%dT%H:%M:%S%z") def strip_quote(text, va...
Add a converter which convert datetime to string
Add a converter which convert datetime to string
Python
mit
thombashi/pytablewriter
24ff6aa99c7ee78d58200aad03c50722563cb1a0
purchase_product_usage/models/account_move.py
purchase_product_usage/models/account_move.py
# Copyright 2019 Aleph Objects, Inc. # Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0). from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.onchange( "amount_currency", "currency_id", ...
# Copyright 2019 Aleph Objects, Inc. # Copyright 2019 ForgeFlow S.L. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl-3.0). from odoo import api, models class AccountMoveLine(models.Model): _inherit = "account.move.line" @api.onchange( "amount_currency", "currency_id", ...
Change only account if usage is defined in POL
[13.0][FIX] purchase_product_usage: Change only account if usage is defined in POL
Python
agpl-3.0
OCA/purchase-workflow,OCA/purchase-workflow
cc6c40b64f8dfde533977883124e22e0fbc80e5c
soco/__init__.py
soco/__init__.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ SoCo (Sonos Controller) is a simple library to control Sonos speakers """ # Will be parsed by setup.py to determine package metadata __author__ = 'Rahim Sonawalla <rsonawalla@gmail.com>' __version__ = '0.7' __website__ = 'https://github.com/SoCo/SoCo...
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ SoCo (Sonos Controller) is a simple library to control Sonos speakers """ # Will be parsed by setup.py to determine package metadata __author__ = 'The SoCo-Team <python-soco@googlegroups.com>' __version__ = '0.7' __website__ = 'https://github.com/SoC...
Update author info to "The SoCo-Team"
Update author info to "The SoCo-Team"
Python
mit
TrondKjeldas/SoCo,flavio/SoCo,dundeemt/SoCo,xxdede/SoCo,KennethNielsen/SoCo,petteraas/SoCo,bwhaley/SoCo,xxdede/SoCo,oyvindmal/SocoWebService,TrondKjeldas/SoCo,TrondKjeldas/SoCo,petteraas/SoCo,dajobe/SoCo,intfrr/SoCo,intfrr/SoCo,xxdede/SoCo,fgend31/SoCo,jlmcgehee21/SoCo,DPH/SoCo,dsully/SoCo,meska/SoCo,bwhaley/SoCo,dajob...
910fd1b323f05b695cccf6d3250b340c46cc2db5
venvctrl/cli/relocate.py
venvctrl/cli/relocate.py
"""Relocate a virtual environment.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import argparse from .. import api def relocate(source, destination, move=False): """Adjust the virtual environment settings...
"""Relocate a virtual environment.""" from __future__ import division from __future__ import absolute_import from __future__ import print_function from __future__ import unicode_literals import argparse from .. import api def relocate(source, destination, move=False): """Adjust the virtual environment settings...
Fix cli module for new lint detection
Fix cli module for new lint detection Since the last commit (2015), some of the test dependencies have updated. This commit specifically addresses updates in PyLint which result in more lint being detected in the project that previous test runs.
Python
mit
kevinconway/venvctrl
742569a4781132d11de6d41811ee11ad55560294
django_slack/exceptions.py
django_slack/exceptions.py
import six class SlackException(ValueError): def __init__(self, message, message_data): super(SlackException, self).__init__(message) self.message_data = message_data @six.python_2_unicode_compatible class ChannelNotFound(SlackException): def __str__(self): # Override base __str__ to...
import six class SlackException(ValueError): def __init__(self, message, message_data): super(SlackException, self).__init__(message) self.message_data = message_data @six.python_2_unicode_compatible class ChannelNotFound(SlackException): def __str__(self): # Override base __str__ to...
Add another specific error class
Add another specific error class
Python
bsd-3-clause
lamby/django-slack
220e0008924878f774f570cc0122c563f2c17465
recipes/migrations/0010_auto_20150919_1228.py
recipes/migrations/0010_auto_20150919_1228.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage"...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def change_to_usage(apps, schema_editor): Recipe = apps.get_model("recipes", "Recipe") Ingredient = apps.get_model("recipes", "Ingredient") IngredientUsage = apps.get_model("recipes", "IngredientUsage"...
Make the data migration actually work
Make the data migration actually work
Python
agpl-3.0
XeryusTC/rotd,XeryusTC/rotd,XeryusTC/rotd
afddecff42b7d8b78048f122488e70eb48660327
test-mm.py
test-mm.py
from psautohint import autohint from psautohint import psautohint d = "tests/data/source-code-pro" mm = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold") gg = [] ii = None for m in mm: f = autohint.openOpenTypeFile("%s/%s/font.otf" % (d, m), "font.otf", None) g = f.convertToBez("A", Fa...
from psautohint import autohint from psautohint import psautohint baseDir = "tests/data/source-code-pro" masters = ("Black", "Bold", "ExtraLight", "Light", "Medium", "Regular", "Semibold") glyphList = None fonts = [] for master in masters: print("Hinting %s" % master) path = "%s/%s/font.otf" % (baseDir, mas...
Rewrite the test script to hint all glyphs
Rewrite the test script to hint all glyphs Which reveals that no MM-compatible hinting is really done :(
Python
apache-2.0
khaledhosny/psautohint,khaledhosny/psautohint
93623d3bc8336073b65f586e2d1573831c492084
iatidataquality/__init__.py
iatidataquality/__init__.py
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3...
# IATI Data Quality, tools for Data QA on IATI-formatted publications # by Mark Brough, Martin Keegan, Ben Webb and Jennifer Smith # # Copyright (C) 2013 Publish What You Fund # # This programme is free software; you may redistribute and/or modify # it under the terms of the GNU Affero General Public License v3...
Add survey controller to routes
Add survey controller to routes
Python
agpl-3.0
pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality,pwyf/IATI-Data-Quality
b90f01bb8e10751ccfa51872dc32054b5be31d1b
vishwin_http/__init__.py
vishwin_http/__init__.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from flask import Flask from werkzeug.contrib.cache import FileSystemCache import pkg_resources app=Flask(__name__) #ap...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from flask import Flask from werkzeug.contrib.cache import MemcachedCache import pkg_resources app=Flask(__name__) app....
Switch to memcached cache backend
Switch to memcached cache backend - Reinstate config file - Read server locations and key prefix from config
Python
mpl-2.0
vishwin/vishwin.info-http,vishwin/vishwin.info-http,vishwin/vishwin.info-http
3eb37589ab7a2e58922a69f42bbc1ec443df44ed
addons/purchase/models/stock_config_settings.py
addons/purchase/models/stock_config_settings.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class StockConfigSettings(models.TransientModel): _inherit = 'stock.config.settings' po_lead = fields.Float(related='company_id.po_lead', default=lambda self: self.env.user...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class StockConfigSettings(models.TransientModel): _inherit = 'stock.config.settings' po_lead = fields.Float(related='company_id.po_lead') use_po_lead = fields.Boolean( ...
Remove useless default value for po_lead
[IMP] purchase: Remove useless default value for po_lead
Python
agpl-3.0
ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo,ygol/odoo
a2ffa3d02ef4b7cd345602b475f86ac172bd7c6c
support/jenkins/buildAllModuleCombination.py
support/jenkins/buildAllModuleCombination.py
import os from subprocess import call from itertools import product, repeat # To be called from the main OpenSpace modules = os.listdir("modules") modules.remove("base") # Get 2**len(modules) combinatorical combinations of ON/OFF settings = [] for args in product(*repeat(("ON", "OFF"), len(modules))): settings.ap...
import os from subprocess import call from itertools import product, repeat import shutil # To be called from the main OpenSpace modules = os.listdir("modules") modules.remove("base") # Get 2**len(modules) combinatorical combinations of ON/OFF settings = [] for args in product(*repeat(("ON", "OFF"), len(modules))): ...
Use python internal functions for generating, removing and changing directories
Use python internal functions for generating, removing and changing directories
Python
mit
OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace,OpenSpace/OpenSpace
d8d6647c1710cd0d66119da4e5a604578efb4bc7
scikits/talkbox/__init__.py
scikits/talkbox/__init__.py
__all__ = [] from tools import * import tools __all__ += tools.__all__ import linpred from linpred import * __all__ += linpred.__all__ from numpy.testing import Tester test = Tester().test bench = Tester().bench
__all__ = [] from tools import * import tools __all__ += tools.__all__ import linpred from linpred import * __all__ += linpred.__all__ import version from numpy.testing import Tester test = Tester().test bench = Tester().bench
Make version module available in main namespace.
Make version module available in main namespace.
Python
mit
cournape/talkbox,cournape/talkbox
31ee84042a12fc65be539de896daf755b342d9a0
junction/proposals/permissions.py
junction/proposals/permissions.py
# -*- coding: utf-8 -*- from django.core.exceptions import PermissionDenied from junction.conferences.models import ConferenceProposalReviewer from .models import ProposalSectionReviewer def is_proposal_author(user, proposal): return user.is_authenticated() and proposal.author == user def is_proposal_reviewer...
# -*- coding: utf-8 -*- from django.core.exceptions import PermissionDenied from junction.conferences.models import ConferenceProposalReviewer from .models import ProposalSectionReviewer def is_proposal_author(user, proposal): return user.is_authenticated() and proposal.author == user def is_proposal_reviewer...
Move check for authentication to top
Move check for authentication to top
Python
mit
ChillarAnand/junction,pythonindia/junction,ChillarAnand/junction,ChillarAnand/junction,pythonindia/junction,ChillarAnand/junction,pythonindia/junction,pythonindia/junction
c67a468d9b02e396c184305dc7b1bbb97982cf7b
python/testData/debug/test_multithread.py
python/testData/debug/test_multithread.py
try: import thread except : import _thread as thread import threading def bar(y): z = 100 + y print("Z=%d"%z) t = None def foo(x): global t y = x + 1 print("Y=%d"%y) t = threading.Thread(target=bar, args=(y,)) t.start() id = thread.start_new_thread(foo, (1,)) while True: p...
try: import thread except : import _thread as thread import threading from time import sleep def bar(y): z = 100 + y print("Z=%d"%z) t = None def foo(x): global t y = x + 1 print("Y=%d"%y) t = threading.Thread(target=bar, args=(y,)) t.start() id = thread.start_new_thread(foo, (...
Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.
Fix tests: add sleep to the main thread in order to stop in the child threads on the slow IronPython.
Python
apache-2.0
FHannes/intellij-community,signed/intellij-community,xfournet/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,hurricup/intell...
7bbd2effa7d1b07e3c924b23ed082bf3dcd2920e
hungarian-nltk/src/snowball_stemmer_sentence.py
hungarian-nltk/src/snowball_stemmer_sentence.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals from nltk.stem.snowball import HungarianStemmer class SnowballStemmerSentence: def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()): self.sentence = tokenize_sentence self.stemmer = stemmer def p...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals from nltk.stem.snowball import HungarianStemmer class SnowballStemmerSentence: def __init__(self, tokenize_sentence, stemmer = HungarianStemmer()): self.sentence = tokenize_sentence self.stemmer = stemmer def p...
Delete testcases from src file
Delete testcases from src file
Python
apache-2.0
davidpgero/hungarian-nltk
763073bc71e59953b7010840fc7923fc15881265
tests/scoring_engine/models/test_settings.py
tests/scoring_engine/models/test_settings.py
from scoring_engine.models.setting import Setting from tests.scoring_engine.unit_test import UnitTest class TestSetting(UnitTest): def test_init_setting(self): setting = Setting(name='test_setting', value='test value example') assert setting.id is None assert setting.name == 'test_settin...
from scoring_engine.models.setting import Setting from tests.scoring_engine.unit_test import UnitTest class TestSetting(UnitTest): def test_init_setting(self): setting = Setting(name='test_setting', value='test value example') assert setting.id is None assert setting.name == 'test_settin...
Remove leftover parameter in settings tests
Remove leftover parameter in settings tests
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
b025558ecf354894132fcfc9bda33bd8a627a27e
lib/python/mod_python/__init__.py
lib/python/mod_python/__init__.py
# # Copyright 2004 Apache Software Foundation # # 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 applicabl...
# # Copyright 2004 Apache Software Foundation # # 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 applicabl...
Fix for MODPYTHON-55 : added a version attribute to the mod_python package.
Fix for MODPYTHON-55 : added a version attribute to the mod_python package.
Python
apache-2.0
grisha/mod_python,carlmcdade/mod_python,dacaiguoguo/mod_python,dacaiguoguo/mod_python,dacaiguoguo/mod_python,grisha/mod_python,runt18/mod_python,runt18/mod_python,carlmcdade/mod_python,grisha/mod_python,runt18/mod_python,carlmcdade/mod_python
087a58c80d0c0764881fdf45d4bdf997a99de29f
srv/budget.py
srv/budget.py
""" Main budget web app (backend) Written by Fela Maslen, 2016 """ from flask import Flask, request, render_template from srv.config import PIE_TOLERANCE from srv.misc import get_serial from srv.rest_api import WebAPI APP = Flask('budget') @APP.route('/api', methods=['GET', 'POST']) def api(): """ api entry poi...
""" Main budget web app (backend) Written by Fela Maslen, 2016 """ from flask import Flask, request, render_template from srv.config import PIE_TOLERANCE from srv.misc import get_serial from srv.rest_api import WebAPI APP = Flask('budget') @APP.route('/api', methods=['GET', 'POST']) def api(): """ api entry poi...
Add index.html alias on api
Add index.html alias on api
Python
mit
felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget,felamaslen/budget
c02bf0729872450110de981cfb016ea0e864f93b
ato_children/api/filters.py
ato_children/api/filters.py
import django_filters from ..models import Gift class GiftFilter(django_filters.FilterSet): """docstring for GiftFilter""" class Meta: model = Gift fields = ['region']
import django_filters from ..models import Gift class GiftFilter(django_filters.FilterSet): """docstring for GiftFilter""" class Meta: model = Gift fields = ['region', 'status']
Enable status filter in API
Enable status filter in API
Python
mit
webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children,webknjaz/webchallenge-ato-children
64c937439911760c7fdc0c70af323381ad13b86d
fellowms/forms.py
fellowms/forms.py
from django.forms import ModelForm, widgets from .models import Fellow, Event, Expense, Blog class FellowForm(ModelForm): class Meta: model = Fellow exclude = [ "home_lon", "home_lat", "inauguration_year", "mentor", ] ...
from django.forms import ModelForm, widgets from .models import Fellow, Event, Expense, Blog class FellowForm(ModelForm): class Meta: model = Fellow exclude = [ "home_lon", "home_lat", "inauguration_year", "funding_notes", ...
Update form to handle notes about funding
Update form to handle notes about funding
Python
bsd-3-clause
softwaresaved/fat,softwaresaved/fat,softwaresaved/fat,softwaresaved/fat
7ea233b7f955f7dbb291d0662fe321cddfceba80
mopidy/frontends/lastfm/__init__.py
mopidy/frontends/lastfm/__init__.py
from __future__ import unicode_literals import mopidy from mopidy import ext from mopidy.exceptions import ExtensionError __doc__ = """ Frontend which scrobbles the music you play to your `Last.fm <http://www.last.fm>`_ profile. .. note:: This frontend requires a free user account at Last.fm. **Dependencies:*...
from __future__ import unicode_literals import mopidy from mopidy import exceptions, ext from mopidy.utils import config, formatting default_config = """ [ext.lastfm] # If the Last.fm extension should be enabled or not enabled = true # Your Last.fm username username = # Your Last.fm password password = """ __doc...
Add default config and config schema
lastfm: Add default config and config schema
Python
apache-2.0
diandiankan/mopidy,jmarsik/mopidy,ZenithDK/mopidy,diandiankan/mopidy,bacontext/mopidy,ali/mopidy,jcass77/mopidy,quartz55/mopidy,rawdlite/mopidy,priestd09/mopidy,kingosticks/mopidy,mopidy/mopidy,bencevans/mopidy,swak/mopidy,mokieyue/mopidy,hkariti/mopidy,quartz55/mopidy,kingosticks/mopidy,vrs01/mopidy,glogiotatidis/mopi...
79cb3d5b8fdca5eba436f0c879633d1994f857a5
detect_tone.py
detect_tone.py
from gz_dsp import * from cfg import * # By FFT, I mean Goertzel transform def detect_tone(signal): ideal_samples_per_fft = SAMPLE_FREQ/float(FFT_FREQ) samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ aspf = actual_samples_per_fft = int(samples_per_cycle*max(round(ideal_samples_per_fft/samples_per_cycle), 1)) coeff...
from gz_dsp import * from cfg import * def detect_tone(signal): ideal_samples_per_transform = SAMPLE_FREQ/float(transform_FREQ) samples_per_cycle = SAMPLE_FREQ/MORSE_FREQ aspt = actual_samples_per_transform = int(samples_per_cycle*max(round(ideal_samples_per_transform/samples_per_cycle), 1)) coeffs = [] for ...
Change variable names to reflect that it doesn't use FFT's anymore
Change variable names to reflect that it doesn't use FFT's anymore
Python
mit
nickodell/morse-code
135e579f8d087bff88e0d67addc455210a0866da
django/applications/catmaid/control/__init__.py
django/applications/catmaid/control/__init__.py
from common import * from connector import * from label import * from link import * from neurohdf import * from neuron import * from node import * from object import * from project import * from search import * from skeletongroup import * from skeletonexport import * from skeleton import * from stack import * from stat...
from common import * from connector import * from label import * from link import * from neurohdf import * from neuron import * from node import * from object import * from project import * from search import * from skeletongroup import * from skeletonexport import * from skeleton import * from stack import * from stat...
Remove superfluous importer namespace import in catmaid.control
Remove superfluous importer namespace import in catmaid.control I double checked that no importer methods are used directly through the catmaid.control module. This relates to issue #570.
Python
agpl-3.0
fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID
c5a1eab4cc08e26d852cc9e1f73478c65174af3c
students/psbriant/final_project/test_clean_data.py
students/psbriant/final_project/test_clean_data.py
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Tests for Final Project """ import clean_data as cd import matplotlib.pyplot as plt import pandas import pytest def get_data(): """ Retrieve data from csv file to test. """ data = pandas.read_cs...
""" Name: Paul Briant Date: 12/11/16 Class: Introduction to Python Assignment: Final Project Description: Tests for Final Project """ import clean_data as cd import matplotlib.pyplot as plt import pandas import pytest def get_data(): """ Retrieve data from csv file to test. """ data = pandas.read_cs...
Add empty test function for user interface.
Add empty test function for user interface.
Python
unlicense
UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016,weidnem/IntroPython2016,UWPCE-PythonCert/IntroPython2016
cd1b68aaaefffc15ce10789445d7749c99deb3d4
shingen/generators/hosts.py
shingen/generators/hosts.py
from ..shinkenconfig import ConfigObject def generate_host_config(config, project_name, instance): co = ConfigObject('host') co.properties['use'] = 'generic-host' co.properties['host_name'] = instance['name'] co.properties['address'] = instance['ip'][0] projects = [project_name, config.get('default...
from ..shinkenconfig import ConfigObject def generate_host_config(config, project_name, instance): co = ConfigObject('host') co.properties['use'] = 'generic-host' co.properties['host_name'] = instance['name'] co.properties['address'] = instance['ip'][0] projects = [project_name, config.get('default...
Put project name in 'notes' field of host
Put project name in 'notes' field of host Labs' graphite metrics architecture means we need both the project name and the hostname to find a full path to our host. Abusing this field for that purpose. Change-Id: If097526f413f36407acdff852cc81216f9c84556
Python
apache-2.0
wikimedia/operations-software-shinkengen
dfaf3d1461a25ca26ed7562831373603010d2f29
xml_json_import/__init__.py
xml_json_import/__init__.py
from django.conf import settings class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
from django.conf import settings from os import path class XmlJsonImportModuleException(Exception): pass if not hasattr(settings, 'XSLT_FILES_DIR'): raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter') if not path.exists(settings.XSLT_FILES_DIR): raise XmlJsonImp...
Throw exception for not existing XSLT_FILES_DIR path
Throw exception for not existing XSLT_FILES_DIR path
Python
mit
lev-veshnyakov/django-import-data,lev-veshnyakov/django-import-data
4063752757a97c444b8913947a0890f2c2387bca
numpy/array_api/_set_functions.py
numpy/array_api/_set_functions.py
from __future__ import annotations from ._array_object import Array from typing import Tuple, Union import numpy as np def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]: """ Array API compatible wrapper for :p...
from __future__ import annotations from ._array_object import Array from typing import Tuple, Union import numpy as np def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]: """ Array API compatible wrapper for :p...
Fix the array API unique() function
Fix the array API unique() function
Python
bsd-3-clause
simongibbons/numpy,rgommers/numpy,numpy/numpy,numpy/numpy,charris/numpy,numpy/numpy,endolith/numpy,mattip/numpy,simongibbons/numpy,endolith/numpy,jakirkham/numpy,anntzer/numpy,seberg/numpy,anntzer/numpy,rgommers/numpy,mattip/numpy,pdebuyl/numpy,pdebuyl/numpy,mhvk/numpy,seberg/numpy,charris/numpy,seberg/numpy,endolith/n...
5c2ffba0f4200a4ba501de08adfbb88504f6252a
alg_selection_sort.py
alg_selection_sort.py
def selection_sort(a_list): """Selection Sort algortihm. Concept: - Find out the max item's original slot first, - then swap it and the item at the max slot. - Iterate the procedure for the next max, etc. """ for max_slot in reversed(range(len(a_list))): select_slot = 0 ...
def selection_sort(a_list): """Selection Sort algortihm. Concept: - Find out the max item's original slot first, - then swap it and the item at the max slot. - Iterate the procedure for the next max, etc. Selection sort is more efficient than bubble sort since the former does not s...
Add comment about more efficient than bubble sort
Add comment about more efficient than bubble sort
Python
bsd-2-clause
bowen0701/algorithms_data_structures
b4932c9e95b34a875c8d5234a1aa025aa5d5dad0
migrations/versions/07ebe99161d5_add_banner_image_url_to_sessio.py
migrations/versions/07ebe99161d5_add_banner_image_url_to_sessio.py
"""add banner_image_url field to session Revision ID: 07ebe99161d5 Revises: d6b1904bea0e Create Date: 2018-11-21 19:06:35.140390 """ # revision identifiers, used by Alembic. revision = '07ebe99161d5' down_revision = 'd6b1904bea0e' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('s...
"""add banner_image_url field to session Revision ID: 07ebe99161d5 Revises: 60a132ae73f1 Create Date: 2018-11-21 19:06:35.140390 """ # revision identifiers, used by Alembic. revision = '07ebe99161d5' down_revision = '60a132ae73f1' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('s...
Update down_revision in migration file.
Update down_revision in migration file.
Python
agpl-3.0
hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel,hasgeek/funnel
906803349e6a4c37311b73a25c1787716b69c17a
glaciertests/__init__.py
glaciertests/__init__.py
from glaciertests.util import GlacierTestsConfig def purge_prefix_vaults(): conn = GlacierTestsConfig().connection() all_vaults = conn.list_vaults() for vault in all_vaults['VaultList']: if vault['VaultName'].startswith(GlacierTestsConfig().prefix()): conn.delete_vault(vault['VaultName'...
from glaciertests.util import GlacierTestsConfig def purge_prefix_vaults(): conn = GlacierTestsConfig().connection() all_vaults = conn.list_vaults() jobs = {} for vault in all_vaults['VaultList']: if vault['VaultName'].startswith(GlacierTestsConfig().prefix()): # Try to delete and ...
Remove vaults with data before and after tests.
Remove vaults with data before and after tests.
Python
mit
bouncestorage/glacier-tests,timuralp/glacier-tests,bouncestorage/glacier-tests,timuralp/glacier-tests
140dc4f38e3302a8478a721cbeb9176029689b38
Functions/template-python/lambda_function.py
Functions/template-python/lambda_function.py
"""Created By: Andrew Ryan DeFilippis""" print('Lambda cold-start...') from json import dumps, loads def lambda_handler(event, context): print('LOG RequestId: {}\tResponse:\n\n{}'.format( context.aws_request_id, None )) return None # Comment or remove everything below before deploying...
"""Created By: Andrew Ryan DeFilippis""" print('Lambda cold-start...') from json import dumps, loads # Disable 'testing_locally' when deploying to AWS Lambda testing_locally = True verbose = True class CWLogs(object): def __init__(self, context): self.context = context def event(self, message, ev...
Rewrite custom log format to a class, add verbosity, and vars for options.
Rewrite custom log format to a class, add verbosity, and vars for options.
Python
apache-2.0
andrewdefilippis/aws-lambda
1f5f821ac464e9986025988f6c306c742dd842fa
Instanssi/ext_blog/templatetags/blog_tags.py
Instanssi/ext_blog/templatetags/blog_tags.py
# -*- coding: utf-8 -*- from django import template from Instanssi.ext_blog.models import BlogEntry register = template.Library() @register.inclusion_tag('ext_blog/blog_messages.html') def render_blog(event_id): entries = BlogEntry.objects.filter(event_id=int(event_id), public=True) return {'entries': entrie...
# -*- coding: utf-8 -*- from django import template from Instanssi.ext_blog.models import BlogEntry register = template.Library() @register.inclusion_tag('ext_blog/blog_messages.html') def render_blog(event_id): entries = BlogEntry.objects.filter(event_id=int(event_id), public=True) return {'entries': entrie...
Tag for getting a valid RSS feed url for event.
ext_blog: Tag for getting a valid RSS feed url for event.
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
5cfcf2615e46fc3ef550159e38dc51c7362543af
readux/books/management/commands/web_export.py
readux/books/management/commands/web_export.py
from eulfedora.server import Repository from django.core.management.base import BaseCommand import shutil from readux.books import annotate, export from readux.books.models import Volume class Command(BaseCommand): help = 'Construct web export of an annotated volume' def add_arguments(self, parser): ...
from eulfedora.server import Repository from eulxml.xmlmap import load_xmlobject_from_file from django.core.management.base import BaseCommand import shutil from readux.books import annotate, export from readux.books.models import Volume from readux.books.tei import Facsimile class Command(BaseCommand): help = '...
Add an option to pass in generated TEI, for speed & troubleshooting
Add an option to pass in generated TEI, for speed & troubleshooting
Python
apache-2.0
emory-libraries/readux,emory-libraries/readux,emory-libraries/readux
b009c40b8cdefaa39c39851b873caa49873527bd
learning_journal/models.py
learning_journal/models.py
import datetime import psycopg2 from sqlalchemy import ( Column, DateTime, Integer, Unicode, UnicodeText, ForeignKey, ) from pyramid.security import Allow, Everyone from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, ...
import datetime import psycopg2 from sqlalchemy import ( Column, DateTime, Integer, Unicode, UnicodeText, ForeignKey, ) from pyramid.security import Allow, Everyone from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, ...
Remove references to User class
Remove references to User class
Python
mit
DZwell/learning_journal,DZwell/learning_journal,DZwell/learning_journal
48426b63bd4123ed6f63a38f3e4e2b401cd5c188
planetstack/core/models/__init__.py
planetstack/core/models/__init__.py
from .plcorebase import PlCoreBase from .planetstack import PlanetStack from .project import Project from .singletonmodel import SingletonModel from .service import Service from .service import ServiceAttribute from .tag import Tag from .role import Role from .site import Site,Deployment, DeploymentRole, DeploymentPriv...
from .plcorebase import PlCoreBase from .planetstack import PlanetStack from .project import Project from .singletonmodel import SingletonModel from .service import Service from .service import ServiceAttribute from .tag import Tag from .role import Role from .site import Site,Deployment, DeploymentRole, DeploymentPriv...
Add credentials module to core list
Add credentials module to core list
Python
apache-2.0
xmaruto/mcord,jermowery/xos,cboling/xos,jermowery/xos,xmaruto/mcord,cboling/xos,cboling/xos,cboling/xos,jermowery/xos,xmaruto/mcord,cboling/xos,jermowery/xos,xmaruto/mcord
24d3f19984e4bfa1ad38faf700ae53f5f4ac10bd
jay/urls.py
jay/urls.py
"""jay URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based v...
"""jay URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based v...
Add votes URL scheme to main URL scheme
Add votes URL scheme to main URL scheme
Python
mit
OpenJUB/jay,kuboschek/jay,OpenJUB/jay,OpenJUB/jay,kuboschek/jay,kuboschek/jay
707ded0f673f44b31d0762d8210a6b94074200e8
troposphere/certificatemanager.py
troposphere/certificatemanager.py
from . import AWSObject, AWSProperty, Tags class DomainValidationOption(AWSProperty): props = { 'DomainName': (basestring, True), 'ValidationDomain': (basestring, True), } class Certificate(AWSObject): resource_type = "AWS::CertificateManager::Certificate" props = { 'DomainN...
# Copyright (c) 2012-2019, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 15.1.0 from . import AWSObject from . import AWSProperty from troposphere import Tags class DomainValidationOpti...
Update AWS::CertificateManager::Certificate per 2020-06-11 changes
Update AWS::CertificateManager::Certificate per 2020-06-11 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
bf19eb9083888d33dabec2228ffaa200ce282ef8
superlists/functional_tests/test_list_item_validation.py
superlists/functional_tests/test_list_item_validation.py
from unittest import skip from .base import FunctionalTest class ItemValidationTest(FunctionalTest): def test_cannot_add_empty_list_items(self): self.fail("write me!")
from unittest import skip from .base import FunctionalTest class ItemValidationTest(FunctionalTest): def test_cannot_add_empty_list_items(self): # Edith goes to the home page and accidentally tries to submit and empty # list item. She hits Enter on the empty input box self.browser.get(self...
Create test to detect submission of empty list items
Create test to detect submission of empty list items
Python
apache-2.0
rocity/the-testing-goat,rocity/the-testing-goat
2af6a3fcafc7447f15352a32507f5034b42984a6
contrail_api_cli/context.py
contrail_api_cli/context.py
class SchemaNotInitialized(Exception): pass class Context(object): _instance = None _schema = None def __new__(class_, *args, **kwargs): if not isinstance(class_._instance, class_): class_._instance = object.__new__(class_, *args, **kwargs) return class_._instance @p...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from six import add_metaclass from .utils import Singleton class SchemaNotInitialized(Exception): pass @add_metaclass(Singleton) class Context(object): _schema = None @property def schema(self): if self._schema is None: ...
Use Singleton metaclass on Context
Use Singleton metaclass on Context
Python
mit
eonpatapon/contrail-api-cli
ec2a18c8da029aadb7bc853c73dc6e1484ddac3b
into/backends/tests/test_spark.py
into/backends/tests/test_spark.py
import pytest from into import into from pyspark import RDD data = [['Alice', 100.0, 1], ['Bob', 200.0, 2], ['Alice', 50.0, 3]] @pytest.fixture def rdd(sc): return sc.parallelize(data) def test_spark_into(rdd): seq = [1, 2, 3] assert isinstance(into(rdd, seq), RDD) assert into([], ...
import pytest from into import into, discover from pyspark import RDD data = [['Alice', 100.0, 1], ['Bob', 200.0, 2], ['Alice', 50.0, 3]] @pytest.fixture def rdd(sc): return sc.parallelize(data) def test_spark_into(rdd): seq = [1, 2, 3] assert isinstance(into(rdd, seq), RDD) assert...
Test discover on a vanilla RDD
Test discover on a vanilla RDD
Python
bsd-3-clause
ContinuumIO/odo,ywang007/odo,cpcloud/odo,ywang007/odo,alexmojaki/odo,cpcloud/odo,Dannnno/odo,ContinuumIO/odo,cowlicks/odo,Dannnno/odo,quantopian/odo,blaze/odo,quantopian/odo,blaze/odo,alexmojaki/odo,cowlicks/odo
8feb733383a90ea6f16cd9cc696446343b4678e9
errorreporter.py
errorreporter.py
from errormarker import ErrorMarker from util import delayed class ErrorReporter(object): def __init__(self, window, error_report, settings, expand_filename): self._marker = ErrorMarker(window, error_report, settings) self._error_report = error_report self._expand_filename = expand_filen...
from errormarker import ErrorMarker from util import delayed class ErrorReporter(object): def __init__(self, window, error_report, settings, expand_filename): self._marker = ErrorMarker(window, error_report, settings) self._error_report = error_report self._expand_filename = expand_filen...
Fix a race condition in error reporting causing highlighted lines to get out of sync
Fix a race condition in error reporting causing highlighted lines to get out of sync
Python
mit
jarhart/SublimeSBT
9f5e61bf821823c14f6a0640bd334c8732d41296
ipkg/files/backends/filesystem.py
ipkg/files/backends/filesystem.py
try: from urlparse import urlparse except ImportError: # Python 3 from urllib.parse import urlparse from . import BaseFile, BackendException class LocalFileException(BackendException): """An error occurred while accessing a local file.""" class LocalFile(BaseFile): """A file on the local filesystem...
import os try: from urlparse import urlparse except ImportError: # Python 3 from urllib.parse import urlparse from . import BaseFile, BackendException class LocalFileException(BackendException): """An error occurred while accessing a local file.""" class LocalFile(BaseFile): """A file on the local...
Check if its a file
Check if its a file
Python
mit
pmuller/ipkg
2261b3c6cb579ae65c1119db45f291e246f536c2
examples/main.py
examples/main.py
import asyncio import sys from contextlib import suppress sys.path.append("..") from asynccmd import Cmd class Commander(Cmd): def __init__(self, intro, prompt): if sys.platform == 'win32': super().__init__(mode="Run", run_loop=False) else: super().__init__(mode="Reader", ru...
import asyncio import sys from contextlib import suppress sys.path.append("..") from asynccmd import Cmd class Commander(Cmd): def __init__(self, intro, prompt): if sys.platform == 'win32': super().__init__(mode="Run", run_loop=False) else: super().__init__(mode="Reader", ru...
FIX example for both Win and NIX
FIX example for both Win and NIX TODO: tasks wont work
Python
apache-2.0
valentinmk/asynccmd
df40edea93b530752cc21c3de04825bc791d4910
parser2.py
parser2.py
from pprint import pprint input = open('example_ignition.txt').read() hands = input.split('\n\n\n') for i, h in enumerate(hands): segments = "seats preflop flop turn river".split() s = h.split('\n*** ') hands[i] = {} while len(s) > 1: # We don't always have flop, turn, riv, but last element is ...
from pprint import pprint input = open('example_ignition.txt').read() hands = input.split('\n\n\n') class Hand: def __init__(self, se=None, p=None, f=None, t=None, r=None, su=None): self.seats = se self.preflop = p self.flop = f self.turn = t self.river = r self.summ...
Use class instead of dict, preparing for methods.
Use class instead of dict, preparing for methods.
Python
mit
zimolzak/Ignition-poker-parser
f94eefc0fe1d869753ec7bbe5e315c5df6cc8303
src/pubmed.py
src/pubmed.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubm...
#!/usr/bin/env python # -*- coding: utf-8 -*- import httplib #import xml.dom.minidom as minidom #import urllib import time, sys import xml.etree.ElementTree as ET def get_pubmed_abs(pmid): conn = httplib.HTTPConnection("eutils.ncbi.nlm.nih.gov") conn.request("GET", '/entrez/eutils/efetch.fcgi?db=pubm...
Return Pubmed title and abstract
Return Pubmed title and abstract
Python
mit
AndreLamurias/IBEnt,AndreLamurias/IBEnt,AndreLamurias/IBRel,AndreLamurias/IBRel
17b6b91cd898f48f18b941dfb2250e7a00bc0506
kyokai/context.py
kyokai/context.py
""" Stores HTTPRequestContext """ from asphalt.core import Context from typeguard import check_argument_types class HTTPRequestContext(Context): """ Sub-class of context used for HTTP requests. """ cfg = {} def __init__(self, request, parent: Context): assert check_argument_types() ...
""" Stores HTTPRequestContext """ from asphalt.core import Context from typeguard import check_argument_types import kyokai class HTTPRequestContext(Context): """ Sub-class of context used for HTTP requests. """ cfg = {} def __init__(self, request, parent: Context): assert check_argumen...
Make request a property on HTTPRequestContext.
Make request a property on HTTPRequestContext.
Python
mit
SunDwarf/Kyoukai
5640a85b2095083da3617380fe315b5c4f26560f
rsfmri/examples/rsfmri_wrapper.py
rsfmri/examples/rsfmri_wrapper.py
from rsfmri import utils from rsfmri import register """ This is done in native space, add warped after (Renaud others)?? despike? split raw func realign (no slicetime (ANTS)) realign w/slicetime (spm) generate movement regressors make meanfunc files -> 4dfunc (bias correct anat and meanfunc?) register anat to meanf...
from rsfmri import utils from rsfmri import register """ This is done in native space, add warped after (Renaud others)?? despike? split raw func realign (no slicetime (ANTS)) realign w/slicetime (spm) generate movement regressors make meanfunc remove values < 100 (outside brain) files -> 4dfunc (bias correct an...
Update wrapper to show latest changes to code
Update wrapper to show latest changes to code
Python
mit
klarnemann/jagust_rsfmri,klarnemann/jagust_rsfmri,klarnemann/jagust_rsfmri
8df03bdd466270127b4185afa792d26e71e323f7
avalonstar/apps/api/views.py
avalonstar/apps/api/views.py
# -*- coding: utf-8 -*- from django.shortcuts import get_object_or_404 from rest_framework import viewsets from rest_framework.response import Response from apps.broadcasts.models import Broadcast, Host, Raid, Series from apps.games.models import Game from apps.subscribers.models import Ticket from .serializers impo...
# -*- coding: utf-8 -*- from django.shortcuts import get_object_or_404 from rest_framework import viewsets from rest_framework.response import Response from apps.broadcasts.models import Broadcast, Host, Raid, Series from apps.games.models import Game from apps.subscribers.models import Ticket from .serializers impo...
Order the tickets correctly in the API.
Order the tickets correctly in the API.
Python
apache-2.0
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
1477d3e94f088399f15bb13fd399d3c33af9c55a
backend/breach/tests/base.py
backend/breach/tests/base.py
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round class RuptureTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='https://di.uoa.gr/?breach=%s', prefix='test', alphabet='0123456789' ) ...
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round class RuptureTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='https://di.uoa.gr/?breach=%s', prefix='test', alphabet='0123456789' ) ...
Add balance checking test round
Add balance checking test round
Python
mit
dimriou/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimkarakostas/rupture,dimkarakostas/rupture,esarafianou/rupture,dionyziz/rupture,dionyziz/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dionyziz/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,dimriou/ruptu...
0aa3af24533a0aa605d05bd034a0bfdcc55c2993
backend/conferences/types.py
backend/conferences/types.py
import graphene from .models import Conference from graphene_django import DjangoObjectType from tickets.types import TicketType class ConferenceType(DjangoObjectType): tickets = graphene.List(graphene.NonNull(TicketType)) def resolve_tickets(self, info): return self.tickets.all() class Meta:...
import graphene from .models import Conference from graphene_django import DjangoObjectType from tickets.types import TicketType class ConferenceType(DjangoObjectType): tickets = graphene.List(graphene.NonNull(TicketType)) def resolve_tickets(self, info): return self.tickets.all() class Meta:...
Add dates to Conference GraphQL type
Add dates to Conference GraphQL type
Python
mit
patrick91/pycon,patrick91/pycon
457f2daeb087ab06d7cb738cb69268bad29d11f4
examples/mhs_atmosphere/mhs_atmosphere_plot.py
examples/mhs_atmosphere/mhs_atmosphere_plot.py
# -*- coding: utf-8 -*- """ Created on Fri Jan 9 12:52:31 2015 @author: stuart """ import os import glob import yt model = 'spruit' datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/') files = glob.glob(datadir+'/*') files.sort() print(files) ds = yt.load(files[0]) slc = yt.SlicePlot(ds, normal='y', fie...
# -*- coding: utf-8 -*- """ Created on Fri Jan 9 12:52:31 2015 @author: stuart """ import os import glob import yt model = 'spruit' datadir = os.path.expanduser('~/mhs_atmosphere/'+model+'/') files = glob.glob(datadir+'/*') files.sort() print(files) ds = yt.load(files[0]) # uncomment for axis swapping for norm...
Add in axes swapping for normal='y'
Add in axes swapping for normal='y'
Python
bsd-2-clause
SWAT-Sheffield/pysac,Cadair/pysac
a3c2f22819271adb7f08d18a54af863e5ca75c51
test/test_api.py
test/test_api.py
# -*- coding: utf-8 -*- import pytest import warthog.api import warthog.exceptions @pytest.fixture def exports(): return set([item for item in dir(warthog.api) if not item.startswith('_')]) def test_public_exports(exports): declared = set(warthog.api.__all__) assert exports == declared, 'Exports and __...
# -*- coding: utf-8 -*- import pytest import warthog.api import warthog.exceptions @pytest.fixture def exports(): return set([item for item in dir(warthog.api) if not item.startswith('_')]) def test_public_exports(exports): declared = set(warthog.api.__all__) assert exports == declared, 'Exports and __...
Add potential to include warnings in warthog.exceptions
Add potential to include warnings in warthog.exceptions
Python
mit
smarter-travel-media/warthog
3c1a9a2db94a094446e9037a65acc7da9bb5586a
myname.py
myname.py
"""Little module to find the path of a Cosmo box simulation""" import os.path as path base=path.expanduser("~/data/Cosmo/") def get_name(sim, ff=True): """Get the directory for a simulation""" halo = "Cosmo"+str(sim)+"_V6" if ff: halo=path.join(halo,"L25n512/output") else: halo=path.j...
"""Little module to find the path of a Cosmo box simulation""" import os.path as path base=path.expanduser("~/data/Cosmo/") def get_name(sim, ff=True, box=25): """Get the directory for a simulation""" halo = "Cosmo"+str(sim)+"_V6" if ff: halo=path.join(halo,"L"+str(box)+"n512/output") else: ...
Allow loading of different box sizes
Allow loading of different box sizes
Python
mit
sbird/vw_spectra
9fb1e795cd2489e2889041018ff5a357afba0221
test_collectr.py
test_collectr.py
# -*- coding: utf-8 -*- """ test_collectr ------------- Some functions to test the collectr library. :copyright: (c) 2013 Cory Benfield :license: MIT License, for details see LICENSE. """ import unittest import collectr class CollectrTest(unittest.TestCase): """ Tests for the collectr library. """ d...
# -*- coding: utf-8 -*- """ test_collectr ------------- Some functions to test the collectr library. :copyright: (c) 2013 Cory Benfield :license: MIT License, for details see LICENSE. """ import unittest import collectr class CollectrTest(unittest.TestCase): """ Tests for the collectr library. """ d...
Delete any files that get moved.
Delete any files that get moved.
Python
mit
Lukasa/collectr,Lukasa/collectr
c3f94790e8d4d7bca68eb86d1172c9f69f1c070c
tests/support.py
tests/support.py
import os def open_file(filename): ''' Load a file from the fixtures directory. ''' path = 'fixtures/' + filename if ('tests' in os.listdir('.')): path = 'tests/' + path return open(path, mode='rb')
import os def open_file(filename, mode='rb'): ''' Load a file from the fixtures directory. ''' path = 'fixtures/' + filename if ('tests' in os.listdir('.')): path = 'tests/' + path return open(path, mode=mode)
Support opening files as text streams on tests
Support opening files as text streams on tests
Python
mit
jaraco/ofxparse,rdsteed/ofxparse,udibr/ofxparse,jseutter/ofxparse
8932d0717bf57c86b81b6744353d6387821b8b15
wsgi/setup.py
wsgi/setup.py
import subprocess import sys import setup_util import os def start(args): subprocess.Popen("gunicorn hello:app -b 0.0.0.0:8080 -w " + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi") return 0 def stop(): p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE) out, err = p.com...
import subprocess import sys import setup_util import os def start(args): subprocess.Popen('gunicorn hello:app --worker-class="egg:meinheld#gunicorn_worker" -b 0.0.0.0:8080 -w ' + str((args.max_threads * 2)) + " --log-level=critical", shell=True, cwd="wsgi") return 0 def stop(): p = subproces...
Use meinheld worker (same as other Python Frameworks)
wsgi: Use meinheld worker (same as other Python Frameworks)
Python
bsd-3-clause
jamming/FrameworkBenchmarks,s-ludwig/FrameworkBenchmarks,Ocramius/FrameworkBenchmarks,diablonhn/FrameworkBenchmarks,ashawnbandy-te-tfb/FrameworkBenchmarks,zloster/FrameworkBenchmarks,donovanmuller/FrameworkBenchmarks,zdanek/FrameworkBenchmarks,markkolich/FrameworkBenchmarks,circlespainter/FrameworkBenchmarks,saturday06...
0e68b94d4d5f204dfe9596ddbd3444e906011183
sumy/document/_paragraph.py
sumy/document/_paragraph.py
# -*- coding: utf8 -*- from __future__ import absolute_import from __future__ import division, print_function, unicode_literals from itertools import chain from .._compat import unicode_compatible from ..utils import cached_property from ._sentence import Sentence @unicode_compatible class Paragraph(object): de...
# -*- coding: utf8 -*- from __future__ import absolute_import from __future__ import division, print_function, unicode_literals from itertools import chain from .._compat import unicode_compatible from ..utils import cached_property from ._sentence import Sentence @unicode_compatible class Paragraph(object): de...
Allow using iterable of sentences in 'Paragraph'
Allow using iterable of sentences in 'Paragraph'
Python
apache-2.0
miso-belica/sumy,miso-belica/sumy
01198751bcdf7ded4e5a3144d08cccd9db7856fc
helusers/urls.py
helusers/urls.py
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if not settings.LOGOUT_REDIRECT_URL: raise ImproperlyConfigured( "You must configure LOGOUT_REDIRECT_URL to u...
"""URLs module""" from django.urls import path from django.conf import settings from django.core.exceptions import ImproperlyConfigured from . import views app_name = "helusers" urlpatterns = [] if ( "social_django" in settings.INSTALLED_APPS and "helusers.tunnistamo_oidc.TunnistamoOIDCAuth" in settings...
Include social_auth specific URLs only if social_auth is in use
Include social_auth specific URLs only if social_auth is in use
Python
bsd-2-clause
City-of-Helsinki/django-helusers,City-of-Helsinki/django-helusers
256409e253939e70652891a94ffd3d30b365ba13
docs/extensions/settings.py
docs/extensions/settings.py
"""Settings for Zinnia documentation""" from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS DATABASES = {'default': {'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3'}} SITE_ID = 1 STATIC_URL = '/static/' SECRET_KEY = 'secret-key' AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY' TYPEPAD_SECR...
"""Settings for Zinnia documentation""" from zinnia.xmlrpc import ZINNIA_XMLRPC_METHODS DATABASES = {'default': {'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3'}} SITE_ID = 1 STATIC_URL = '/static/' SECRET_KEY = 'secret-key' AKISMET_SECRET_API_KEY = 'AKISMET_API_KEY' TYPEPAD_SECR...
Configure the extension to use django_comments
Configure the extension to use django_comments
Python
bsd-3-clause
Fantomas42/django-blog-zinnia,ghachey/django-blog-zinnia,dapeng0802/django-blog-zinnia,Fantomas42/django-blog-zinnia,1844144/django-blog-zinnia,marctc/django-blog-zinnia,1844144/django-blog-zinnia,ghachey/django-blog-zinnia,marctc/django-blog-zinnia,marctc/django-blog-zinnia,ZuluPro/django-blog-zinnia,extertioner/djang...
3701ab7e372d73c2076988954dabff82f0f16557
build/adama-app/adama-package/adama/store.py
build/adama-app/adama-package/adama/store.py
import collections import pickle import redis from .serf import node class Store(collections.MutableMapping): def __init__(self, db=0): host, port = node(role='redis', port=6379) self._db = redis.StrictRedis(host=host, port=port, db=db) def __getitem__(self, key): obj = self._db.ge...
import collections import pickle import redis from .tools import location class Store(collections.MutableMapping): def __init__(self, db=0): host, port = location('redis', 6379) self._db = redis.StrictRedis(host=host, port=port, db=db) def __getitem__(self, key): obj = self._db.get...
Store is using serfnode service discovery
Store is using serfnode service discovery
Python
mit
waltermoreira/adama-app,waltermoreira/adama-app,waltermoreira/adama-app
79770a0e0f31f1292f8b5ab103509e7835570f20
src/collectors/SmartCollector/SmartCollector.py
src/collectors/SmartCollector/SmartCollector.py
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { ...
import diamond.collector import subprocess import re import os class SmartCollector(diamond.collector.Collector): """ Collect data from S.M.A.R.T.'s attribute reporting. """ def get_default_config(self): """ Returns default configuration options. """ return { ...
Use ID instead of attribute if attribute name is 'Unknown_Attribute'.
Use ID instead of attribute if attribute name is 'Unknown_Attribute'.
Python
mit
zoidbergwill/Diamond,CYBERBUGJR/Diamond,TinLe/Diamond,tellapart/Diamond,Netuitive/Diamond,socialwareinc/Diamond,hvnsweeting/Diamond,joel-airspring/Diamond,joel-airspring/Diamond,hamelg/Diamond,signalfx/Diamond,stuartbfox/Diamond,disqus/Diamond,python-diamond/Diamond,rtoma/Diamond,mfriedenhagen/Diamond,socialwareinc/Dia...
c642acd29a013c25fab420961109a0a1ebe3c195
open511/views.py
open511/views.py
from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view()
from open511.models import RoadEvent from open511.utils.views import JSONView class RoadEventListView(JSONView): allow_jsonp = True def get(self, request): return [ rdev.to_json_structure() for rdev in RoadEvent.objects.all() ] list_roadevents = RoadEventListView.as_view()
Allow JSONP requests to the roadevents API
Allow JSONP requests to the roadevents API
Python
mit
Open511/open511-server,Open511/open511-server,Open511/open511-server
09c1941ecf6ab6bc61dff67ed0e33badee5048d4
ipy_user_conf.py
ipy_user_conf.py
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3...
# Case Conductor is a Test Case Management system. # Copyright (C) 2011 uTest Inc. # # This file is part of Case Conductor. # # Case Conductor is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3...
Add model auto-imports to IPython profile.
Add model auto-imports to IPython profile.
Python
bsd-2-clause
shinglyu/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mozilla/moztrap,mozilla/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,mozilla/moztrap,shinglyu/moztrap,mozilla/moztrap,shinglyu/moztrap,mccarrmb/moztrap,mozilla/moztrap,bobsilverberg/moztrap,mccarrmb/moztrap,shinglyu/moztrap,bobs...
a15e3b80383ba6ca79a19a566beeb9290d1ad017
conference_scheduler/tests/test_scheduler.py
conference_scheduler/tests/test_scheduler.py
from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) #...
from collections import Counter from conference_scheduler import scheduler def test_is_valid_schedule(people): # Test empty schedule schedule = tuple() assert not scheduler.is_valid_schedule(schedule) def test_schedule(events, rooms, slots): schedule = scheduler.schedule(events, rooms, slots) #...
Add working test for only one event per room per slot
Add working test for only one event per room per slot
Python
mit
PyconUK/ConferenceScheduler
ebe7b76a441311afb2369b1e24640a790a5b4c77
setuptools_extversion/__init__.py
setuptools_extversion/__init__.py
""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ if attr == VERSION_PRO...
""" setuptools_extversion Allows getting distribution version from external sources (e.g.: shell command, Python function) """ import pkg_resources import subprocess VERSION_PROVIDER_KEY = 'extversion' def version_calc(dist, attr, value): """ Handler for parameter to setup(extversion=value) """ i...
Add support for using a function
Add support for using a function `extversion` can be a a dict with a `function` key -- e.g.: setup( ... setup_requires='setuptools_extversion', extversion={'function': 'my_package.version:get_package_version'}, )
Python
mit
msabramo/python_setuptools_extversion
2f0819fa6bea3e6f034516358563086d5ab9aa67
dasem/app/__init__.py
dasem/app/__init__.py
"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..semantic import Semantic app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_semantic = Semantic() from . impo...
"""Dasem app.""" from __future__ import absolute_import, division, print_function from flask import Flask from flask_bootstrap import Bootstrap from ..dannet import Dannet from ..wikipedia import ExplicitSemanticAnalysis app = Flask(__name__) Bootstrap(app) app.dasem_dannet = Dannet() app.dasem_wikipedia_esa = E...
Change to use ESA class in other module
Change to use ESA class in other module
Python
apache-2.0
fnielsen/dasem,fnielsen/dasem
6272798c06da66bb3c9b8d2c9ea45c3bceb9a550
diss/tests/test_fs.py
diss/tests/test_fs.py
import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == I...
import os import pytest from fuse import FUSE, FuseOSError from diss.fs import id_from_path, DissFilesystem from .testdata import ID @pytest.fixture def fs(): return DissFilesystem() def test_id_from_path(): assert id_from_path('/blobs/SOMEID') == 'SOMEID' assert id_from_path('/files/hello.txt') == I...
Add test getattr for FUSE
Add test getattr for FUSE
Python
agpl-3.0
hoh/Billabong,hoh/Billabong
471fc55cd7dc968a9891b571aad5bf745a52fd01
ckanext/stadtzhtheme/tests/test_validation.py
ckanext/stadtzhtheme/tests/test_validation.py
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): factories.Sysadmin(apikey="my-test-key") app = self._get_...
import nose from ckanapi import TestAppCKAN, ValidationError from ckan.tests import helpers, factories eq_ = nose.tools.eq_ assert_true = nose.tools.assert_true class TestValidation(helpers.FunctionalTestBase): def test_invalid_url(self): """Test that an invalid resource url is caught by our validator. ...
Add extra test for resource url validator
Add extra test for resource url validator
Python
agpl-3.0
opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme
bea8123561c24391a6db368773a56a04a1a98fb2
dataprep/dataframe.py
dataprep/dataframe.py
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") tokens = lines.map(lambda l: l.split("\t")) data = tokens.map(lambda t: Row(year=int(t[0]), month=int(t[1]), day=int(t[2]), hour=int(t[3]), page=t[4], hits=int(t[5]))) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDat...
from pyspark.sql import SQLContext, Row lines = sc.textFile("/user/admin/Wikipedia/*") def parse_line(line): tokens = line.split('\t') return Row(page=tokens[4], hits=int(tokens[5])) data = lines.map(parse_line) sqlContext = SQLContext(sc) wtDataFrame = sqlContext.createDataFrame(data) wtDataFrame.registerTem...
Use parse_line function like in later sections
Use parse_line function like in later sections
Python
apache-2.0
aba1476/ds-for-wall-street,thekovinc/ds-for-wall-street,cdalzell/ds-for-wall-street,nishantyp/ds-for-wall-street
bb8f1d915785fbcbbd8ccd99436a63a449d26e88
patterns.py
patterns.py
# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', ...
# -*- coding: utf-8 -*- import re pre_patterns = [ ( r'(\d{16}-[-\w]*\b)', r'REQUEST_ID_SUBSTITUTE', ), ( # r'([\dA-F]){8}-[\dA-F]{4}-4[\dA-F]{3}-[89AB][\dA-F]{3}-[\dA-F]{12}', r'([0-9A-F]){8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}', # r'[0-9A-F-]{36}', ...
Add js error position SUBSTITUTE
Add js error position SUBSTITUTE
Python
mit
abcdw/direlog,abcdw/direlog
f63c37597a51f738bbd478afaf2d21b10741dc91
kid_readout/utils/easync.py
kid_readout/utils/easync.py
""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filen...
""" easync.py - easier access to netCDF4 files """ import netCDF4 class EasyGroup(object): def __repr__(self): return "EasyNC: %s %s" % (self._filename,self.group.path) def __str__(self): return self.__repr__() def __init__(self,group,filename): self._filen...
Add easy access to close and sync methods of nc files
Add easy access to close and sync methods of nc files
Python
bsd-2-clause
ColumbiaCMB/kid_readout,ColumbiaCMB/kid_readout
5d519c31b17a60441d522ab2a5c17c944c376afd
py/brick-wall.py
py/brick-wall.py
import heapq class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ n_row = len(wall) heap = [(wall[i][0], i, 0) for i in xrange(n_row)] heapq.heapify(heap) max_noncross = 0 while True: ...
from collections import Counter class Solution(object): def leastBricks(self, wall): """ :type wall: List[List[int]] :rtype: int """ c = Counter() wall_width = sum(wall[0]) max_non_cut = 0 for row in wall: subsum = 0 for n in ro...
Add py solution for 554. Brick Wall
Add py solution for 554. Brick Wall 554. Brick Wall: https://leetcode.com/problems/brick-wall/ Approach2: O(n_brick): Count # of every length can formed by any row
Python
apache-2.0
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
a708645581542822985be2e8778b60f0008d75a6
Lib/whichdb.py
Lib/whichdb.py
"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" o...
"""Guess which db package to use to open a db file.""" import struct def whichdb(filename): """Guess which db package to use to open a db file. Return values: - None if the database file can't be read; - empty string if the file can be read but can't be recognized - the module name (e.g. "dbm" o...
Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.
Support byte-swapped dbhash (bsddb) files. Found by Ben Sayer.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
b8cc70280941653dd84982994ca145a6ff56eda9
reindex.py
reindex.py
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) a...
import sys import argparse from elasticsearch import Elasticsearch from annotator.reindexer import Reindexer description = """ Reindex an elasticsearch index. WARNING: Documents that are created while reindexing may be lost! """ def main(argv): argparser = argparse.ArgumentParser(description=description) a...
Use default host when not specified
Use default host when not specified
Python
mit
nobita-isc/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,nobita-isc/annotator-store,openannotation/annotator-store,happybelly/annotator-store,ningyifan/annotator-store
3ec325afca110e866a5b60e4e92a38738aee4906
graphene_django_extras/directives/__init__.py
graphene_django_extras/directives/__init__.py
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import * from .list import * from .numbers import * from .string import * all_directives = ( # date DateGraphQLDirective, # list ShuffleGraphQLDirective, SampleGraphQLDirective, # ...
# -*- coding: utf-8 -*- from graphql.type.directives import specified_directives as default_directives from .date import DateGraphQLDirective from .list import ShuffleGraphQLDirective, SampleGraphQLDirective from .numbers import FloorGraphQLDirective, CeilGraphQLDirective from .string import ( DefaultGraphQLDirect...
Make minor improvements for CI.
Make minor improvements for CI.
Python
mit
eamigo86/graphene-django-extras
097cccec41d4455c73d586ef4506075f8c7c1004
amon/apps/notifications/opsgenie/sender.py
amon/apps/notifications/opsgenie/sender.py
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v1/json/alert" # Message is limited to 130 chars data = { 'apiKey': auth.get('api_key')...
import requests import json from amon.apps.notifications.models import notifications_model def send_opsgenie_notification(message=None, auth=None): sent = False url = "https://api.opsgenie.com/v2/alerts" headers = { 'Authorization': 'GenieKey '+ auth.get('api_key'), 'Content-Type': 'applic...
Switch to OpsGenie API V2
Switch to OpsGenie API V2
Python
agpl-3.0
amonapp/amon,amonapp/amon,martinrusev/amonone,martinrusev/amonone,amonapp/amon,amonapp/amon,martinrusev/amonone,amonapp/amon,martinrusev/amonone
dfaa49b31e8abd10456761110d0cadc1b7c7640d
zaqar/transport/wsgi/app.py
zaqar/transport/wsgi/app.py
# Copyright (c) 2013 Red Hat, Inc. # # 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 writ...
# Copyright (c) 2013 Red Hat, Inc. # # 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 writ...
Make the log work when deploy Zaqar with uwsgi
Make the log work when deploy Zaqar with uwsgi The zaqar-wsgi runs under uwsgi by devstack can't print any WARNING, DEBUG, ERROR or INFO log now. This path add the log initialization for uwsgi boot. Change-Id: Ifcd6be908442275d2acbde2562e593b2ca87b277 Cloese-bug: #1645492
Python
apache-2.0
openstack/zaqar,openstack/zaqar,openstack/zaqar,openstack/zaqar
a25b03f83c7003ccea2eb554117e8fedc153e4fe
corgi/coerce.py
corgi/coerce.py
def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if isinstance(obj, dict): return obj return {key: obj}
def listify(obj): if not isinstance(obj, list): return [obj] return obj def dictify(obj, key): if not isinstance(obj, dict): return {key: obj} return obj
Make dictify similar in flow to listify
Make dictify similar in flow to listify
Python
mit
log0ymxm/corgi
25cd8afdfede8a522f8d0f08ee4678a2e9c46a4b
curious/commands/__init__.py
curious/commands/__init__.py
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. All arguments are pass...
""" Commands helpers. """ import functools from curious.commands.command import Command def command(*args, klass: type=Command, **kwargs): """ A decorator to mark a function as a command. This will put a `factory` attribute on the function, which can later be called to create the Command instance. A...
Allow changing what object is returned from Command instances.
Allow changing what object is returned from Command instances.
Python
mit
SunDwarf/curious
79c449473f5ee0c349df8f4de4577e61776bd337
lily/utils/models/factories.py
lily/utils/models/factories.py
from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES faker = Factory.cr...
import unicodedata from factory.declarations import LazyAttribute from factory.django import DjangoModelFactory from factory.fuzzy import FuzzyChoice from faker.factory import Factory from .models import EmailAddress, PhoneNumber, Address, PHONE_TYPE_CHOICES, ExternalAppLink from lily.utils.countries import COUNTRIES ...
Fix tests generating invalid email addresses
LILY-1809: Fix tests generating invalid email addresses
Python
agpl-3.0
HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily,HelloLily/hellolily
b8cacab927c5b98285f15ae4d400b9577dbacef6
openstack_dashboard/dashboards/admin/dashboard.py
openstack_dashboard/dashboards/admin/dashboard.py
# Copyright 2012 Nebula, Inc. # # 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 agree...
# Copyright 2012 Nebula, Inc. # # 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 agree...
Remove broken telemetry policy check
Remove broken telemetry policy check The reference to telemetry policy is no longer needed as well as broken causing the admin dashboard to show up inappropriately. Closes-Bug: #1643009 Change-Id: I07406f5d6c23b0fcc34df00a29b573ffc2c900e7
Python
apache-2.0
yeming233/horizon,ChameleonCloud/horizon,noironetworks/horizon,ChameleonCloud/horizon,noironetworks/horizon,NeCTAR-RC/horizon,noironetworks/horizon,BiznetGIO/horizon,BiznetGIO/horizon,yeming233/horizon,NeCTAR-RC/horizon,BiznetGIO/horizon,openstack/horizon,BiznetGIO/horizon,ChameleonCloud/horizon,openstack/horizon,Chame...
ce4923461b0f9202ec6ca9ccdbbc5b700018ba18
src/adhocracy/lib/helpers/adhocracy_service.py
src/adhocracy/lib/helpers/adhocracy_service.py
import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_servic...
import requests from pylons import config class RESTAPI(object): """Helper to work with the adhocarcy_service rest api (adhocracy_kotti.mediacenter, adhocracy_kotti.staticpages, plone). """ session = requests.Session() def __init__(self): self.api_token = config.get('adhocracy_servic...
Change API to get single external static page
Adhocracy-service: Change API to get single external static page
Python
agpl-3.0
liqd/adhocracy,alkadis/vcv,phihag/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,alkadis/vcv,DanielNeugebauer/adhocracy,alkadis/vcv,alkadis/vcv,liqd/adhocracy,phihag/adhocracy,DanielNeugebauer/adhocracy,liqd/adhocracy,liqd/adhocracy,alkadis/v...
d5007da66f8fb179d3cefd1668d767d4e9a3d9d5
TitanicData.py
TitanicData.py
# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_c...
# coding=utf-8 # Import necessary packages (Pandas, NumPy, etc.) import pandas as pd import numpy as np # Set file paths for Titanic data (Source: Kaggle) filepath_train = 'Data/train.csv' filepath_test = 'Data/test.csv' # Load train/test datasets as Pandas DataFrames df_train = pd.read_csv('Data/train.csv', index_c...
Add Combined DataFrame by Merging Train/Test Sets
Add Combined DataFrame by Merging Train/Test Sets Before merging, a new column was assigned to both sets with discrete values ['Train'/'Test'] that correspond to the set an observation is inclusive of.
Python
mit
vnaidu/kaggle-titanic
ad6d981cfbb9af0b02b40346548eb37631538016
poradnia/users/migrations/0007_migrate_avatars.py
poradnia/users/migrations/0007_migrate_avatars.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter(primary=True).all(): avatar.user.picture = avatar.avatar avatar.use...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations if 'avatar' in settings.INSTALLED_APPS: def migrate_avatar(apps, schema_editor): Avatar = apps.get_model("avatar", "Avatar") for avatar in Avatar.objects.filter...
Fix migrations after django-avatar drop
Fix migrations after django-avatar drop
Python
mit
watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia.siecobywatelska.pl,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia.siecobywatelska.pl,watchdogpolska/poradnia,watchdogpolska/poradnia,rwakulszowa/poradnia,rwakulszowa/poradnia,watchdogpolska/poradnia,watchdogpolska/poradnia
9c9a33869747223952b4a999a5a14354ffb3e540
contrib/examples/actions/pythonactions/forloop_parse_github_repos.py
contrib/examples/actions/pythonactions/forloop_parse_github_repos.py
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_i...
from st2actions.runners.pythonrunner import Action from bs4 import BeautifulSoup class ParseGithubRepos(Action): def run(self, content): try: soup = BeautifulSoup(content, 'html.parser') repo_list = soup.find_all("h3") output = {} for each_item in repo_list: repo_half_url = each_i...
Throw exception instead of returning false.
Throw exception instead of returning false.
Python
apache-2.0
StackStorm/st2,Plexxi/st2,Plexxi/st2,nzlosh/st2,Plexxi/st2,StackStorm/st2,Plexxi/st2,StackStorm/st2,nzlosh/st2,nzlosh/st2,nzlosh/st2,StackStorm/st2
99899f753ff9697f926389efe688c1ae2088c4c4
kpi/management/commands/wait_for_database.py
kpi/management/commands/wait_for_database.py
# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the con...
# coding: utf-8 import time from django.core.management.base import BaseCommand, CommandError from django.db import connection from django.db.utils import OperationalError class Command(BaseCommand): help = ( 'Repeatedly attempt to connect to the default database, exiting ' 'silently once the con...
Make database connection error more descriptive
Make database connection error more descriptive
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
0da53cf2fcdc37574bebfe538778fffdae58e516
examples/delete_old_files.py
examples/delete_old_files.py
#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' ...
#!/bin/python # installation: # pip install pytz pyuploadcare~=2.1.0 import pytz from datetime import timedelta, datetime import time from pyuploadcare import conf from pyuploadcare.api_resources import FileList, FilesStorage MAX_LIFETIME = 30 # days conf.pub_key = 'demopublickey' conf.secret = 'demoprivatekey' ...
Add file sorting in the example script
Add file sorting in the example script
Python
mit
uploadcare/pyuploadcare
a9de2f3c9a05236c7254a2b1b03049b034fd555e
elections/bf_elections_2015/lib.py
elections/bf_elections_2015/lib.py
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ...
from candidates.static_data import ( BaseMapItData, BasePartyData, BaseAreaPostData ) class MapItData(BaseMapItData): pass class PartyData(BasePartyData): def __init__(self): super(PartyData, self).__init__() self.ALL_PARTY_SETS = ( {'slug': 'national', 'name': 'National'}, ...
Fix missing post group defaults for Burkina Faso
Fix missing post group defaults for Burkina Faso
Python
agpl-3.0
neavouli/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextrepresentative,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,datamade/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournextmp-popit,mysociety/yournextmp-popit,datamade/yournext...
f34a6b4ec6b192607f4a3557f6da3f5c119aab04
tests/scoring_engine/unit_test.py
tests/scoring_engine/unit_test.py
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.create_all(engine) self.create_default_settings() def teardown(self...
from scoring_engine.db import session, engine from scoring_engine.models.base import Base from scoring_engine.models.setting import Setting class UnitTest(object): def setup(self): self.session = session Base.metadata.drop_all(engine) Base.metadata.create_all(engine) self.create_de...
Modify unit test framework to delete db during setup
Modify unit test framework to delete db during setup
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
2ef0571e5468ac72f712a69180fa5dc18652e8d7
app/applier.py
app/applier.py
import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): ...
import random from collections import namedtuple Rule = namedtuple('Rule', ['changes', 'environments']) sonorization = Rule({'p': 'b', 't': 'd', 'ʈ': 'ɖ', 'c':'ɟ', 'k': 'g', 'q': 'ɢ'}, ['^.', 'V.V']) rules = [sonorization] words = ['potato', 'tobado', 'tabasco'] def choose_rule(words, rules): ...
Implement rule filtering by phoneme.
Implement rule filtering by phoneme.
Python
mit
kdelwat/LangEvolve,kdelwat/LangEvolve,kdelwat/LangEvolve