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
f9e1c8a536c0212414047b941f502bfbee92be92
l10n_br_fiscal/wizards/document_cancel_wizard.py
l10n_br_fiscal/wizards/document_cancel_wizard.py
# Copyright 2019 KMEE # Copyright (C) 2020 Renato Lima - Akretion <renato.lima@akretion.com.br> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, models class DocumentCancelWizard(models.TransientModel): _name = 'l10n_br_fiscal.document.cancel.wizard' _description = 'F...
# Copyright 2019 KMEE # Copyright (C) 2020 Renato Lima - Akretion <renato.lima@akretion.com.br> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import api, models class DocumentCancelWizard(models.TransientModel): _name = 'l10n_br_fiscal.document.cancel.wizard' _description = 'Fisc...
Update Fiscal document cancel wizard
[FIX] Update Fiscal document cancel wizard
Python
agpl-3.0
OCA/l10n-brazil,akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil
cc8624cfa3788dc66e7afb144fc24ef5f1a79ff9
scripts/json-concat-lists.py
scripts/json-concat-lists.py
import json import argparse parser = argparse.ArgumentParser() parser.add_argument('json_file', nargs='+') parser.add_argument('output_file') if __name__ == "__main__": args = parser.parse_args() list_all = [] for jf in args.json_file: with open(jf) as in_f: list_all += json.load(in_f...
import json import argparse parser = argparse.ArgumentParser() parser.add_argument('json_file', nargs='+') parser.add_argument('output_file') if __name__ == "__main__": args = parser.parse_args() list_all = [] for jf in args.json_file: with open(jf) as in_f: file_jsons = json.load(in_...
Remove duplicate JSON gaferences when concatenating
Remove duplicate JSON gaferences when concatenating
Python
bsd-3-clause
geneontology/go-site,geneontology/go-site,geneontology/go-site,geneontology/go-site,geneontology/go-site
44d8692b6739856170ba5d5b9712a2afe170f4df
presentation/tests.py
presentation/tests.py
from django.contrib.auth.models import AnonymousUser from django.core.urlresolvers import reverse from django.test import TestCase from django.test import RequestFactory from presentation.models import Presentation from presentation.views import PresentationList from warp.users.models import User class PresentationL...
from django.core.urlresolvers import reverse from django.test import Client from django.test import TestCase from presentation.models import Presentation from warp.users.models import User class PresentationListTest(TestCase): def setUp(self): self.client = Client() self.test_user = self.create_t...
Fix test case with client
Fix test case with client
Python
mit
SaturDJang/warp,SaturDJang/warp,SaturDJang/warp,SaturDJang/warp
b307bb4e59598670cf2ee09c4107d9f42d8b7d3c
warehouse/database/mixins.py
warehouse/database/mixins.py
from sqlalchemy.dialects import postgresql as pg from sqlalchemy.sql.expression import text from warehouse import db class UUIDPrimaryKeyMixin(object): id = db.Column(pg.UUID(as_uuid=True), primary_key=True, server_default=text("uuid_generate_v4()"))
from sqlalchemy.dialects import postgresql as pg from sqlalchemy.sql import func from sqlalchemy.sql.expression import text from warehouse import db from warehouse.database.schema import TableDDL class UUIDPrimaryKeyMixin(object): id = db.Column(pg.UUID(as_uuid=True), primary_key=True, server_defaul...
Add a database mixin for Timestamping models
Add a database mixin for Timestamping models
Python
bsd-2-clause
davidfischer/warehouse
22823ca55e4c342149b83d84d18ad879d55023d7
oslib/__init__.py
oslib/__init__.py
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2017 Caian Benedicto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2017 Caian Benedicto # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights #...
Add find import to oslib init
Add find import to oslib init
Python
mit
Caian/ostools
6e89594c231698d4f20590e723a876699876fb52
utils/__init__.py
utils/__init__.py
from . import util from . import irc sysver = "".join(__import__("sys").version.split("\n")) gitver = __import__("subprocess").check_output(['git', 'rev-parse', '--short', 'HEA...
# pylint: disable=unused-import from . import util from . import irc # pylint: enable=unused-import sysver = "".join(__import__("sys").version.split("\n")) gitver = __import__("subprocess").check_output(['git', 'rev-parse', ...
Make Pylint ignore some unused imports
Make Pylint ignore some unused imports Ignore them because they are required for the bot to work
Python
mit
wolfy1339/Python-IRC-Bot
5c9a121d9ab8b66c49d7a58d24805c1eecfc8a71
ce/common.py
ce/common.py
#!/usr/bin/env python # vim: set fileencoding=UTF-8 : import inspect class DynamicMethods(object): def list_methods(self, predicate): """Find all transform methods within the class that satisfies the predicate. Returns: A list of tuples containing method names and correspon...
#!/usr/bin/env python # vim: set fileencoding=UTF-8 : import inspect class DynamicMethods(object): def list_methods(self, predicate): """Find all transform methods within the class that satisfies the predicate. Returns: A list of tuples containing method names and correspon...
Fix infinite recursion of comparing Comparable
Fix infinite recursion of comparing Comparable
Python
mit
admk/soap
a49e697e45a0c7a678a852f0c9215bd7a3fa24bf
tests/backends/test_macOS.py
tests/backends/test_macOS.py
import pytest import keyring from keyring.testing.backend import BackendBasicTests from keyring.backends import macOS @pytest.mark.skipif( not keyring.backends.macOS.Keyring.viable, reason="macOS backend not viable", ) class Test_macOSKeychain(BackendBasicTests): def init_keyring(self): return ma...
import pytest import keyring from keyring.testing.backend import BackendBasicTests from keyring.backends import macOS @pytest.mark.skipif( not keyring.backends.macOS.Keyring.viable, reason="macOS backend not viable", ) class Test_macOSKeychain(BackendBasicTests): def init_keyring(self): return ma...
Add test capturing need for an alternate keyring with an alternate keychain.
Add test capturing need for an alternate keyring with an alternate keychain.
Python
mit
jaraco/keyring
9d35218506368702ac33d78be197ee3151d24ed9
ledger_type.py
ledger_type.py
from openerp.osv import fields, osv from openerp.tools.translate import _ _enum_ledger_type = [ ('ledger_a', _('Ledger A')), ('ledger_b', _('Ledger B')), ('ledger_c', _('Ledger C')), ('ledger_d', _('Ledger D')), ('ledger_e', _('Ledger E')), ] class ledger_type(osv.Model): _name = 'alternate_le...
from openerp.osv import fields, osv from openerp.tools.translate import _ _enum_ledger_type = [ ('ledger_a', _('Ledger A')), ('ledger_b', _('Ledger B')), ('ledger_c', _('Ledger C')), ('ledger_d', _('Ledger D')), ('ledger_e', _('Ledger E')), ] class ledger_type(osv.Model): _name = 'alternate_le...
Order by ledger types by name
Order by ledger types by name
Python
agpl-3.0
xcgd/alternate_ledger,xcgd/alternate_ledger
e5eaf68490098cb89cf9d6ad8b4eaa96bafd0450
compose/cli/docker_client.py
compose/cli/docker_client.py
import logging import os import ssl from docker import Client from docker import tls from ..const import HTTP_TIMEOUT log = logging.getLogger(__name__) def docker_client(): """ Returns a docker-py client configured using environment variables according to the same logic as the official Docker client. ...
import logging import os from docker import Client from docker.utils import kwargs_from_env from ..const import HTTP_TIMEOUT log = logging.getLogger(__name__) def docker_client(): """ Returns a docker-py client configured using environment variables according to the same logic as the official Docker cl...
Remove custom docker client initialization logic
Remove custom docker client initialization logic Signed-off-by: Aanand Prasad <94fc4f3e3d0be608b3ed7b8529ff28d2a445cce1@gmail.com>
Python
apache-2.0
phiroict/docker,denverdino/docker.github.io,phiroict/docker,denverdino/docker.github.io,jzwlqx/denverdino.github.io,docker/docker.github.io,shin-/docker.github.io,swoopla/compose,rillig/docker.github.io,jiekechoo/compose,bdwill/docker.github.io,joeuo/docker.github.io,sanscontext/docker.github.io,amitsaha/compose,GM-Ale...
03b4575a60cab53629c62eca5df5acdd9688fbbb
project/views/twilioviews.py
project/views/twilioviews.py
from flask import request import requests from ..utils.status import get_status from ..utils.reminders import create_reminder import twilio.twiml import json from datetime import datetime def call(): resp = twilio.twiml.Response() resp.record(timeout=10, transcribe=True, transcribeCallback='http://...
from flask import request import requests from ..utils.status import get_status from ..utils.reminders import create_reminder import twilio.twiml import json from datetime import datetime def call(): resp = twilio.twiml.Response() resp.record(timeout=10, transcribe=True, transcribeCallback='http://...
Add print debug to text function
Add print debug to text function
Python
apache-2.0
tjcsl/mhacksiv
ee17ff42931e718d77ac2180b23e750bedcd31d4
test/test_searchentities.py
test/test_searchentities.py
import unittest from . import models from sir.schema.searchentities import SearchEntity as E, SearchField as F class QueryResultToDictTest(unittest.TestCase): def setUp(self): self.entity = E(models.B, [ F("id", "id"), F("c_bar", "c.bar"), F("c_bar_trans", "c.bar", tra...
import mock import unittest from . import models from xml.etree.ElementTree import Element, tostring from sir.schema.searchentities import SearchEntity as E, SearchField as F class QueryResultToDictTest(unittest.TestCase): def setUp(self): self.entity = E(models.B, [ F("id", "id"), ...
Add a test for wscompat conversion
Add a test for wscompat conversion
Python
mit
jeffweeksio/sir
6637d13202e647058296e0a8a5606bf64598b63e
Lib/misc/setup.py
Lib/misc/setup.py
import os from numpy.distutils.misc_util import Configuration def configuration(parent_package='',top_path=None): config = Configuration('misc',parent_package, top_path) config.add_data_files('lena.dat') print "########", config return config if __name__ == '__main__': from numpy.distutils.core i...
import os from numpy.distutils.misc_util import Configuration def configuration(parent_package='',top_path=None): config = Configuration('misc',parent_package, top_path) config.add_data_files('lena.dat') return config if __name__ == '__main__': from numpy.distutils.core import setup setup(**confi...
Remove extra noise on install.
Remove extra noise on install. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@1549 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
scipy/scipy-svn,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,lesserwhirls/scipy-cwt,scipy/scipy-svn
ccf3bcfc962a37d088507b542bd8e3af2ce515b6
tests/test_with_testcase.py
tests/test_with_testcase.py
import time import unittest import pytest class TerribleTerribleWayToWriteTests(unittest.TestCase): @pytest.fixture(autouse=True) def setupBenchmark(self, benchmark): self.benchmark = benchmark def test_foo(self): self.benchmark(time.sleep, 0.000001) class TerribleTerribleWayToWritePat...
import time import unittest import pytest class TerribleTerribleWayToWriteTests(unittest.TestCase): @pytest.fixture(autouse=True) def setupBenchmark(self, benchmark): self.benchmark = benchmark def test_foo(self): self.benchmark(time.sleep, 0.000001) class TerribleTerribleWayToWritePat...
Remove use of context manager.
Remove use of context manager.
Python
bsd-2-clause
thedrow/pytest-benchmark,aldanor/pytest-benchmark,SectorLabs/pytest-benchmark,ionelmc/pytest-benchmark
8a9a0f1dc277d26767ffc3f34c00c18d00bd5e2e
conanfile.py
conanfile.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, CMake class PEGTLConan(ConanFile): name = "pegtl" description = "C++ header-only parser combinator library for creating PEG parsers" homepage = "https://github.com/taocpp/PEGTL" url = homepage license = "MIT" author = "...
#!/usr/bin/env python # -*- coding: utf-8 -*- from conans import ConanFile, CMake class PEGTLConan(ConanFile): name = "pegtl" description = "C++ header-only parser combinator library for creating PEG parsers" homepage = "https://github.com/taocpp/PEGTL" topics = ("conan", "taocpp", "pegtl", "peg", "gra...
Fix missing generator on Windows
Fix missing generator on Windows - Since compiler is not listed on settings, CMake is not able to detect a valid generator, using MingGW by default - Add topics to be used as tags for searching Signed-off-by: Uilian Ries <d4bad57018205bdda203549c36d3feb0bfe416a7@gmail.com>
Python
mit
ColinH/PEGTL,ColinH/PEGTL
153688b63103a024b126a7c92eb9d0816500d2dc
ircstat/ent.py
ircstat/ent.py
# Copyright 2013 John Reese # Licensed under the MIT license class Struct(object): """A basic object type that, given a dictionary or keyword arguments, converts the key/value pairs into object attributes.""" def __init__(self, data=None, **kwargs): if data is not None: self.__dict__.up...
# Copyright 2013 John Reese # Licensed under the MIT license class Struct(object): """A basic object type that, given a dictionary or keyword arguments, converts the key/value pairs into object attributes.""" def __init__(self, data=None, **kwargs): if data is not None: self.__dict__.up...
Update Struct.__repr__ to show subclass names
Update Struct.__repr__ to show subclass names
Python
mit
jreese/ircstat,jreese/ircstat
497313620772c1cb0d520be1a0024c12ca02742e
tests/python_tests/fontset_test.py
tests/python_tests/fontset_test.py
#!/usr/bin/env python from nose.tools import * from utilities import execution_path import os, mapnik def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os.chdir(execution_path('.')) def test_loading_fontset_from_map(): m = mapnik.Map(2...
#!/usr/bin/env python from nose.tools import * from utilities import execution_path import os, mapnik def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() os.chdir(execution_path('.')) def test_loading_fontset_from_map(): m = mapnik.Map(2...
Add a test (currently failing) ensuring that named fontsets created in python are propertly serialized
Add a test (currently failing) ensuring that named fontsets created in python are propertly serialized
Python
lgpl-2.1
Mappy/mapnik,qianwenming/mapnik,tomhughes/mapnik,jwomeara/mapnik,pnorman/mapnik,davenquinn/python-mapnik,yiqingj/work,pnorman/mapnik,Mappy/mapnik,yohanboniface/python-mapnik,mapycz/python-mapnik,jwomeara/mapnik,Mappy/mapnik,yiqingj/work,strk/mapnik,kapouer/mapnik,Mappy/mapnik,qianwenming/mapnik,lightmare/mapnik,garnert...
0141340d2abddc954ea4388fe31629d98189632c
tests/test_exceptions.py
tests/test_exceptions.py
# -*- coding: utf-8 -*- from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError('foo') assert err.messages == ['foo'] def test_can_pass_list_of_messages(self): err = ValidationError(['foo', 'bar']) ...
# -*- coding: utf-8 -*- from marshmallow.exceptions import ValidationError class TestValidationError: def test_stores_message_in_list(self): err = ValidationError('foo') assert err.messages == ['foo'] def test_can_pass_list_of_messages(self): err = ValidationError(['foo', 'bar']) ...
Add test for storing dictionaries on ValidationError
Add test for storing dictionaries on ValidationError
Python
mit
0xDCA/marshmallow,Bachmann1234/marshmallow,xLegoz/marshmallow,bartaelterman/marshmallow,VladimirPal/marshmallow,daniloakamine/marshmallow,mwstobo/marshmallow,dwieeb/marshmallow,etataurov/marshmallow,maximkulkin/marshmallow,marshmallow-code/marshmallow,0xDCA/marshmallow,quxiaolong1504/marshmallow,Tim-Erwin/marshmallow
358b40875647734bb25d2b9e25506d13ca60a740
neuroimaging/utils/tests/data/__init__.py
neuroimaging/utils/tests/data/__init__.py
"""Information used for locating nipy test data. Nipy uses a set of test data that is installed separately. The test data should be located in the directory ``~/.nipy/tests/data``. Install the data in your home directory from the data repository:: $ mkdir -p .nipy/tests/data $ svn co http://neuroimaging.scipy.or...
""" Nipy uses a set of test data that is installed separately. The test data should be located in the directory ``~/.nipy/tests/data``. Install the data in your home directory from the data repository:: $ mkdir -p .nipy/tests/data $ svn co http://neuroimaging.scipy.org/svn/ni/data/trunk/fmri .nipy/tests/data """...
Extend error message regarding missing test data.
Extend error message regarding missing test data.
Python
bsd-3-clause
yarikoptic/NiPy-OLD,yarikoptic/NiPy-OLD
2430d4ae362ca22ebff83b405355d60343b3a0c1
non_iterable_example/_5_context.py
non_iterable_example/_5_context.py
def print_numbers(numbers): for n in numbers: print(n) if random: numbers = 1 print_numbers(numbers) else: numbers = 1, 2, 3 print_numbers(numbers)
def print_numbers(flag, numbers): if flag: for n in numbers: print(n) if random: numbers = 1 print_numbers(False, numbers) else: numbers = 1, 2, 3 print_numbers(True, numbers)
Modify example to emphasise importance of context.
Modify example to emphasise importance of context.
Python
unlicense
markshannon/buggy_code
13c6a1527bb5d241989c7b7beb11a48eacc4d69c
tests/unit/http_tests.py
tests/unit/http_tests.py
import unittest, os, sys current_dir = os.path.dirname(__file__) base_dir = os.path.join(current_dir, os.pardir, os.pardir) sys.path.append(base_dir) from requests.exceptions import ConnectionError from pycrawler.http import HttpRequest class HttpRequestTests(unittest.TestCase): def test_response_not_empty(sel...
import unittest, os, sys current_dir = os.path.dirname(__file__) base_dir = os.path.join(current_dir, os.pardir, os.pardir) sys.path.append(base_dir) from pycrawler.http import HttpRequest, UrlNotValidException class HttpRequestTests(unittest.TestCase): def test_response_not_empty(self): url = 'http://...
Change raises class to UrlNotValidException
Change raises class to UrlNotValidException
Python
mit
slaveofcode/pycrawler,slaveofcode/pycrawler
53cb3adb97bb434a896938c2c7f78109e5b5566f
tests/test_identify_repo.py
tests/test_identify_repo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_identify_repo ------------------ """ import pytest from cookiecutter import exceptions, vcs def test_identify_git_github(): repo_url = "https://github.com/audreyr/cookiecutter-pypackage.git" assert vcs.identify_repo(repo_url) == "git" def test_identi...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_identify_repo ------------------ """ import pytest from cookiecutter import exceptions, vcs def test_identify_git_github(): repo_url = 'https://github.com/audreyr/cookiecutter-pypackage.git' assert vcs.identify_repo(repo_url) == 'git' def test_identi...
Use single quotes instead of double quotes
Use single quotes instead of double quotes
Python
bsd-3-clause
audreyr/cookiecutter,audreyr/cookiecutter,sp1rs/cookiecutter,lucius-feng/cookiecutter,luzfcb/cookiecutter,christabor/cookiecutter,jhermann/cookiecutter,terryjbates/cookiecutter,cichm/cookiecutter,terryjbates/cookiecutter,Springerle/cookiecutter,venumech/cookiecutter,moi65/cookiecutter,0k/cookiecutter,ramiroluz/cookiecu...
6722f037783580f30e94317e1eb8e5c34b0e7719
runtests.py
runtests.py
import os from django.conf import settings os.environ['REUSE_DB'] = '1' if not settings.configured: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django_nose', 'markitup', '...
import os from django.conf import settings os.environ['REUSE_DB'] = '1' if not settings.configured: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django_nose', 'markitup', '...
Read database user and password from environment.
Read database user and password from environment.
Python
mit
zsiciarz/django-pgallery,zsiciarz/django-pgallery
29041cdaf3beca926f1dff1d3f147b7dc07ad8dd
pylp/cli/run.py
pylp/cli/run.py
""" Run a pylpfile. Copyright (C) 2017 The Pylp Authors. This file is under the MIT License. """ import runpy, os, sys import traceback import asyncio import pylp, pylp.cli.logger as logger # Run a pylpfile def run(path, tasks): # Test if the pylpfile exists if not os.path.isfile(path): logger.log(logger.red(...
""" Run a pylpfile. Copyright (C) 2017 The Pylp Authors. This file is under the MIT License. """ import runpy, os, sys import traceback import asyncio import pylp import pylp.cli.logger as logger from pylp.utils.paths import make_readable_path # Run a pylpfile def run(path, tasks): # Test if the pylpfile exists ...
Make pylpfile path more readable
Make pylpfile path more readable
Python
mit
pylp/pylp
4dcb0a9860b654a08839a61f5e67af69771de39c
tests/test_slow_requests.py
tests/test_slow_requests.py
import datetime import dnstwister.tools def test2(): """Looooong domain names highlighted that the idna decoding is slooooow. This is a basic benchmark for performance. """ domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzzzzzzzzzzzzzzzppieo.com' start = date...
import datetime import dnstwister.tools def test2(): """Looooong domain names highlighted that the idna decoding is slooooow. This is a basic benchmark for performance, based on a bot's behaviour recently. """ domain = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.zzzzzzzzzzzz...
Test threshold increased because the Travis server is a bit slower :)
Test threshold increased because the Travis server is a bit slower :)
Python
unlicense
thisismyrobot/dnstwister,thisismyrobot/dnstwister,thisismyrobot/dnstwister
7aab7b17858fb307e8e4f136038e4448be449f9e
runtests.py
runtests.py
# Unit test driver. import os import sys from unittest import TestLoader, TestSuite, TextTestRunner topdir = os.path.split(os.path.abspath(__file__))[0] os.chdir(topdir) loader = TestLoader() if sys.version_info[:2] < (3, 0): tests = loader.discover('.', 'test_*.py') elif sys.version_info[:2] > (3, 2): test...
# Unit test driver. import os import sys from unittest import TestLoader, TestSuite, TextTestRunner topdir = os.path.split(os.path.abspath(__file__))[0] os.chdir(topdir) loader = TestLoader() if sys.version_info < (3, 0): tests = loader.discover('.', 'test_*.py') elif sys.version_info > (3, 2): tests = Test...
Exit non-zero if tests fail
Exit non-zero if tests fail runtests.py was exiting 0 if test either failed or passed (which confused tox, travis, etc). Determine the status code based on the success of the test suite run.
Python
mit
cocagne/txdbus
6ac70bb24b7fab272adb9805fa0509aa2282add4
pysswords/db.py
pysswords/db.py
from glob import glob import os from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = create_gpg(gpg_b...
from glob import glob import os from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = create_gpg(gpg_b...
Fix get gpg key from database
Fix get gpg key from database
Python
mit
scorphus/passpie,marcwebbie/pysswords,marcwebbie/passpie,scorphus/passpie,eiginn/passpie,eiginn/passpie,marcwebbie/passpie
850464de61237a7fae64219a39e9c937f7d40c01
randcat.py
randcat.py
#! /usr/bin/python3 import random random.seed() # this initializes with the Date, which I think is a novel enough seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much just go until it's killed print(chr(random.getrandbits(8)), end='')
#! /usr/bin/python3 import calendar import time seed = calendar.timegm(time.gmtime()) # We'll use the epoch time as a seed. def random (seed): seed2 = (seed*297642 + 83782)/70000 return int(seed2) % 70000; p = seed while True: # if we're going with a mimicing of cat /dev/random, it'll pretty much j...
Make it so we're using our own seed.
Make it so we're using our own seed.
Python
apache-2.0
Tombert/RandCat
74983020db5cfcd3e81e258837979522f2d1b639
flac_errors.py
flac_errors.py
import re errorFile = open('samples/foobar2000-errors.txt', 'r') errors = errorFile.readlines() index = -1 for i in range(len(errors)): line = errors[i] if re.search(r'List of undecodable items:', line): index = i nbErrorsFoobar = 0 for i in range(index, len(errors)): line = errors[i] match = re.search(r'"(.*....
import re errorFile = open('samples/foobar2000-errors.txt', 'r') errors = errorFile.readlines() errorsSet = set() index = -1 for i in range(len(errors)): line = errors[i] if re.search(r'List of undecodable items:', line): index = i nbErrorsFoobar = 0 for i in range(index, len(errors)): line = errors[i] match =...
Use a Set to avoid duplicates
Use a Set to avoid duplicates
Python
mit
derekhendrickx/find-my-flac-errors
42c6d252084fa9336cf5c5d1766de29bc31bf082
dbaas/workflow/steps/util/resize/start_database.py
dbaas/workflow/steps/util/resize/start_database.py
# -*- coding: utf-8 -*- import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0022 from workflow.steps.util.restore_snapshot import use_database_initialization_script LOG = logging.getLogger(__name__) class StartDatabase(BaseStep): ...
# -*- coding: utf-8 -*- import logging from util import full_stack from workflow.steps.util.base import BaseStep from workflow.exceptions.error_codes import DBAAS_0022 from workflow.steps.util.restore_snapshot import use_database_initialization_script from time import sleep LOG = logging.getLogger(__name__) class St...
Add sleep on start database
Add sleep on start database
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
6e31eb9e1049d75ad4e7e1031c0dfa4d6617c48f
csaps/__init__.py
csaps/__init__.py
# -*- coding: utf-8 -*- """ Cubic spline approximation (smoothing) """ from csaps._version import __version__ # noqa from csaps._base import ( SplinePPForm, UnivariateCubicSmoothingSpline, MultivariateCubicSmoothingSpline, NdGridCubicSmoothingSpline, ) from csaps._types import ( UnivariateDataT...
# -*- coding: utf-8 -*- """ Cubic spline approximation (smoothing) """ from csaps._version import __version__ # noqa from csaps._base import ( SplinePPForm, NdGridSplinePPForm, UnivariateCubicSmoothingSpline, MultivariateCubicSmoothingSpline, NdGridCubicSmoothingSpline, ) from csaps._types impo...
Add NdGridSplinePPForm to csaps imports
Add NdGridSplinePPForm to csaps imports
Python
mit
espdev/csaps
6aa8f148b3b3975363d5d4a763f5abb45ea6cbd8
databin/parsers/__init__.py
databin/parsers/__init__.py
from databin.parsers.util import ParseException from databin.parsers.simple import parse_csv, parse_tsv from databin.parsers.psql import parse_psql PARSERS = [ ('Comma-Separated Values', 'csv', parse_csv), ('Tab-Separated Values', 'tsv', parse_tsv), ('Excel copy & paste', 'excel', parse_tsv), ('psql Sh...
from databin.parsers.util import ParseException from databin.parsers.simple import parse_csv, parse_tsv from databin.parsers.psql import parse_psql PARSERS = [ ('Excel copy & paste', 'excel', parse_tsv), ('Comma-Separated Values', 'csv', parse_csv), ('Tab-Separated Values', 'tsv', parse_tsv), ('psql Sh...
Make excel format the default
Make excel format the default
Python
mit
LeTristanB/Pastable,pudo/databin,LeTristanB/Pastable
301f62a80140c319735d37fdab80b66712722de0
h2o-bindings/bin/custom/R/gen_isolationforest.py
h2o-bindings/bin/custom/R/gen_isolationforest.py
def update_param(name, param): if name == 'stopping_metric': param['values'] = ['AUTO', 'anomaly_score'] return param return None # param untouched extensions = dict( required_params=['training_frame', 'x'], validate_required_params="", set_required_params=""" parms$training_frame...
def update_param(name, param): if name == 'validation_response_column': param['name'] = None return param if name == 'stopping_metric': param['values'] = ['AUTO', 'anomaly_score'] return param return None # param untouched extensions = dict( required_params=['training_f...
Disable validation_response_column in R (only Python supported at first)
Disable validation_response_column in R (only Python supported at first)
Python
apache-2.0
michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,michalkurka/h2o-3,michalkurka/h2o-3
5ae12aa12cef04704ff90071acf098fdfdc7a91a
utils/tests/test_pipeline.py
utils/tests/test_pipeline.py
from io import StringIO from django.core.management import call_command from django.test import TestCase class PipelineTestCase(TestCase): def test_success(self): call_command('collectstatic', '--noinput', stdout=StringIO()) call_command('clean_staticfilesjson', stdout=StringIO())
import os from io import StringIO from django.conf import settings from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase class PipelineTestCase(TestCase): def setUp(self): file_path = os.path.join(settings.STATIC_ROOT, 'stati...
Add test for missing staticfiles.json
Add test for missing staticfiles.json
Python
mit
bulv1ne/django-utils,bulv1ne/django-utils
d0046ae1dfc6c3cd86477180c3175562834c8f41
test/test_datapath.py
test/test_datapath.py
# coding=UTF8 import pytest from core import hybra class TestUM: def setup(self): hybra.set_data_path('./data2/') self.g = hybra.data( 'news', folder = '', terms = ['yle.json'] ) def test_is_changed( self ): assert( hybra.data_path() == './data2/' )
# coding=UTF8 import pytest from core import hybra class TestUM: def setup(self): hybra.set_data_path('./data_empty/') def test_is_changed( self ): assert( hybra.data_path() == './data_empty/' )
Remove data load from test
Remove data load from test
Python
mit
HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core,HIIT/hybra-core
fd19236999eccd9cbf049bc5b8917cd603974f97
centerline/__init__.py
centerline/__init__.py
from .centerline import Centerline __all__ = ['Centerline']
# -*- coding: utf-8 -*- from __future__ import unicode_literals from . import utils from .centerline import Centerline __all__ = ['utils', 'Centerline']
Add the utils module to the package index
Add the utils module to the package index
Python
mit
fitodic/polygon-centerline,fitodic/centerline,fitodic/centerline
7488988934a5370b372eed0f5245518ab612fa89
utils/mail_utils.py
utils/mail_utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Utils for sending emails via SMTP on localhost. """ from email.utils import formatdate from email.mime.text import MIMEText import smtplib import textwrap from config import MAILSERVER_HOST def wrap_message(message, chars_in_line=80): """Wraps an unformatted bl...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Utils for sending emails via SMTP on localhost. """ from email.utils import formatdate from email.mime.text import MIMEText import smtplib import textwrap from config import MAILSERVER_HOST, MAILSERVER_PORT def wrap_message(message, chars_in_line=80): """Wraps ...
Add possibility to locally forward the mail server
Add possibility to locally forward the mail server
Python
mit
MarauderXtreme/sipa,lukasjuhrich/sipa,lukasjuhrich/sipa,MarauderXtreme/sipa,agdsn/sipa,agdsn/sipa,agdsn/sipa,agdsn/sipa,lukasjuhrich/sipa,fgrsnau/sipa,lukasjuhrich/sipa,MarauderXtreme/sipa,fgrsnau/sipa,fgrsnau/sipa
4fd5fd238d4c8353e131e5399a184edbd6de159d
ibmcnx/test/loadFunction.py
ibmcnx/test/loadFunction.py
import sys from java.lang import String from java.util import HashSet from java.util import HashMap import java import lotusConnectionsCommonAdmin globdict = globals() locdict = locals() def loadFilesService(): global globdict global locdict execfile("filesAdmin.py",globdict,locdict)
import sys from java.lang import String from java.util import HashSet from java.util import HashMap import java import lotusConnectionsCommonAdmin globdict = globals() locdict = locals() def loadFilesService(): global globdict global locdict ldict(globals(),locals()) execfile("filesAdmin.py",globdict...
Customize scripts to work with menu
Customize scripts to work with menu
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
76252224293f3b54dafa1cf2356dcc9a2991cf39
externaldata/adsbedata/RetrieveHistoricalADSBEdata.py
externaldata/adsbedata/RetrieveHistoricalADSBEdata.py
""" Utilities for downloading historical data in a given AOI. Python 3.5 """ import requests import io import zipfile import os from time import strftime import logging import yaml from model import aircraft_report from model import report_receiver from utils import postgres as pg_utils logger = logging.getLogger(__...
""" Utilities for downloading historical data in a given AOI. Python 3.5 """ import requests import io import zipfile import os from time import strftime import logging import yaml from model import aircraft_report from model import report_receiver from utils import postgres as pg_utils logger = logging.getLogger(__...
Refactor output for zip archive and download
Refactor output for zip archive and download
Python
apache-2.0
GISDev01/adsbpostgis
53ee8d6a3fd773b08003ca6e7a371ac787eab622
polling_stations/apps/data_collection/management/commands/import_watford.py
polling_stations/apps/data_collection/management/commands/import_watford.py
""" Import Watford """ from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from Watford """ council_id = 'E07000103' districts_name = 'Watford_Polling_Districts' stations_name = 'Watford_Polling_Stations...
""" Import Watford """ from data_collection.management.commands import BaseShpShpImporter class Command(BaseShpShpImporter): """ Imports the Polling Station data from Watford """ council_id = 'E07000103' districts_name = 'Watford_Polling_Districts' stations_name = 'Watford_Polling_Stations...
Add polling_district_id in Watford import script
Add polling_district_id in Watford import script
Python
bsd-3-clause
chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,chris48s/UK-Polling-Stations,andylolz/UK-Polling-Stations,andylolz/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,andylolz/UK-Polling-Stations
761b0a959882499b629d9bc3fbd1b971beaf66a5
mymodule/blueprints/api_v1/__init__.py
mymodule/blueprints/api_v1/__init__.py
import flask from flask import current_app as app from werkzeug import exceptions from mymodule.blueprints.api_v1 import upload blueprint = flask.Blueprint('v1', __name__, url_prefix='/api/v1') blueprint.add_url_rule('/upload', view_func=upload.post, methods=['POST']) @blueprint.route('/test') def index(): app...
import flask from flask import current_app as app from werkzeug import exceptions from . import upload blueprint = flask.Blueprint('v1', __name__, url_prefix='/api/v1') blueprint.add_url_rule('/upload', view_func=upload.post, methods=['POST']) @blueprint.route('/test') def index(): app.logger.info('TEST %d', 1...
Simplify import of api_v1 subpackage.
Simplify import of api_v1 subpackage.
Python
mit
eduardobmc/flask-test
48c20cdd866299a8b7495038ecb7ec9ea831657e
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create documentation of DataSource Settings
: Create documentation of DataSource Settings Task-Url:
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
cc2e96a6030840c5221a2cce5042bedb69f8fc55
templates/openwisp2/urls.py
templates/openwisp2/urls.py
from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('django_netjsonconfig.controller.urls', namespace='controller')), ] ...
from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles.urls import staticfiles_urlpatterns admin.autodiscover() admin.site.site_url = None urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('django_netjsonconfig.controller.urls', n...
Hide "view site" link in admin
Hide "view site" link in admin
Python
bsd-3-clause
nemesisdesign/ansible-openwisp2,openwisp/ansible-openwisp2,ritwickdsouza/ansible-openwisp2
d0dfd2c9055092f64e396177275dbe285ad41efb
blo/DBControl.py
blo/DBControl.py
import sqlite3 class DBControl: def __init__(self, db_name=":memory:"): self.db_conn = sqlite3.connect(db_name)
import sqlite3 class DBControl: def __init__(self, db_name=":memory:"): self.db_conn = sqlite3.connect(db_name) def create_tables(self): self.db_conn.execute("""CREATE TABLE IF NOT EXISTS Articles (" id INTEGER PRIMARY KEY AUTOINCREMENT, ...
Add Create tables method and close db connection method.
Add Create tables method and close db connection method. create_table method create article table (if not exists in db) and virtual table for full text search.
Python
mit
10nin/blo,10nin/blo
b2ed8de7302cbea0a80b87f3dfe370ca0a60d75a
kawasemi/backends/github.py
kawasemi/backends/github.py
# -*- coding: utf-8 -*- import json import requests from .base import BaseChannel from ..exceptions import HttpError class GitHubChannel(BaseChannel): def __init__(self, token, owner, repository, base_url="https://api.github.com", *args, **kwargs): self.token = token self.url = ...
# -*- coding: utf-8 -*- import json import requests from .base import BaseChannel from ..exceptions import HttpError class GitHubChannel(BaseChannel): def __init__(self, token, owner, repository, base_url="https://api.github.com", *args, **kwargs): self.token = token self.url = ...
Set Accept header explicitly in GitHubChannel
Set Accept header explicitly in GitHubChannel
Python
mit
ymyzk/kawasemi,ymyzk/django-channels
c04c9dcfdc2be2368ac2c705ce4852039573767b
datac/main.py
datac/main.py
# -*- coding: utf-8 -*- import copy def init_abscissa(params, abscissae, abscissa_name): """ List of dicts to initialize object w/ calc method This method generates a list of dicts; each dict is sufficient to initialize an object featuring a calculator method of interest. This list can be thought of as th...
# -*- coding: utf-8 -*- import copy def init_abscissa(abscissae, abscissa_name, params = {}): """ List of dicts to initialize object w/ calc method This method generates a list of dicts; each dict is sufficient to initialize an object featuring a calculator method of interest. This list can be thought of ...
Reorder arg list, set default for static params
Reorder arg list, set default for static params
Python
mit
jrsmith3/datac,jrsmith3/datac
746510dc0b939fe11a2b025805678a0829cf814a
handler/minion_server.py
handler/minion_server.py
#!/usr/bin/env python import server import supervisor class MinionServer(server.Server): def __init__(self, ip, port): super(MinionServer, self).__init__(ip, port) def handle(self, data): supervisor.start( 'worker.conf', target='worker_{}'.format(data['image']), ...
#!/usr/bin/env python import server import supervisor class MinionServer(server.Server): def __init__(self, ip, port): super(MinionServer, self).__init__(ip, port) def handle(self, data): """Start a worker. Message format: { 'image': 'image name' ...
Document message format for minion server
Document message format for minion server
Python
mit
waltermoreira/adama-minion
75eed75ee9c70368100d7ce8f3fdcc8169912062
lfc/context_processors.py
lfc/context_processors.py
# lfc imports import lfc.utils from django.conf import settings from django.utils import translation def main(request): """context processor for LFC. """ current_language = translation.get_language() default_language = settings.LANGUAGE_CODE return { "PORTAL" : lfc.utils.get_portal(), ...
# lfc imports import lfc.utils from django.conf import settings from django.utils import translation def main(request): """context processor for LFC. """ current_language = translation.get_language() default_language = settings.LANGUAGE_CODE is_default_language = default_language == current_la...
Return correct language for using within links
Improvement: Return correct language for using within links
Python
bsd-3-clause
natea/django-lfc,natea/django-lfc
fb34c787c1d0050436698929d200202329a27bf3
app/settings.py
app/settings.py
import os SECURE_MESSAGING_DATABASE_URL = os.getenv('SECURE_MESSAGING_DATABASE_URL', 'sqlite:////tmp/messages.db') # postgres://rasmessage:rasmessage@localhost:5432/messages
import os ''' This file is the main configuration for the Secure Messaging Service. It contains a full default configuration All configuration may be overridden by setting the appropriate environment variable name. ''' SECURE_MESSAGING_DATABASE_URL = os.getenv('SECURE_MESSAGING_DATABASE_URL', 'sqlite:////tmp/...
Add docstring to main configuration.
Add docstring to main configuration.
Python
mit
qateam123/secure-messaging-api
8570efd42f35b89d9a97d9aa5a5aa47765cd21f6
diary/logthread.py
diary/logthread.py
from threading import Thread try: from queue import Queue except ImportError: # python 2 from Queue import Queue class ElemThread(Thread): """A thread for logging as to not disrupt the logged application""" def __init__(self, elem, name="Elementary Logger"): """Construct a thread for logging...
from threading import Thread try: from queue import Queue except ImportError: # python 2 from Queue import Queue class DiaryThread(Thread): """A thread for logging as to not disrupt the logged application""" def __init__(self, diary, name="Diary Logger"): """Construct a thread for logging ...
Make last changes over to diary name
Make last changes over to diary name
Python
mit
GreenVars/diary
ac8ec95b5d9f3f0bca2f6c1e367a08a5fd0ee787
bdp/runtests.py
bdp/runtests.py
""" Module runtests.py - Runs all unittests configured in different buildout projects. """ import os import subprocess, shlex PYPROJECTS = 'platform/frontend' def run(): """ Main eintry point """ projects = PYPROJECTS.split(',') for project in projects: cmd = shlex.split('bin/django jenki...
""" Module runtests.py - Runs all unittests configured in different buildout projects. """ import os import subprocess, shlex PYPROJECTS = 'platform/frontend' def run(): """ Main eintry point """ projects = PYPROJECTS.split(',') projects_root = os.getcwd() for project in projects: os....
Change to correct directory when testing
Change to correct directory when testing
Python
apache-2.0
telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform
4f20f940102d353b6200f44ae5aaa51a85b89aba
pxe_manager/tests/test_pxemanager.py
pxe_manager/tests/test_pxemanager.py
from pxe_manager.pxemanager import PxeManager from resource_manager.client import ResourceManagerClient import httpretty @httpretty.activate def test_defaults(): client = ResourceManagerClient() cobbler_url = "http://cobbler.example.com/cobbler_api" cobbler_user = "user" cobbler_password = "password" ...
from pxe_manager.pxemanager import PxeManager from resource_manager.client import ResourceManagerClient import httpretty @httpretty.activate def test_defaults(): host_client = ResourceManagerClient() pub_ip_client = ResourceManagerClient(resource_type='public-addresses') priv_ip_client = ResourceManagerCl...
Update unit test with new pxemanager signature
Update unit test with new pxemanager signature
Python
apache-2.0
tbeckham/DeploymentManager,tbeckham/DeploymentManager,ccassler/DeploymentManager,tbeckham/DeploymentManager,ccassler/DeploymentManager,ccassler/DeploymentManager
e307d4e5586ac08559cf607e484e55d70bd4b0ae
tests/people/test_models.py
tests/people/test_models.py
import pytest from components.people.models import Group, Idol, Membership, Staff from components.people.factories import (GroupFactory, IdolFactory, MembershipFactory, StaffFactory) @pytest.mark.django_db def test_group_factory(): factory = GroupFactory() assert isinstance(factory, Group) assert 'gr...
import pytest from components.people.models import Group, Idol, Membership, Staff from components.people.factories import (GroupFactory, IdolFactory, MembershipFactory, StaffFactory) pytestmark = pytest.mark.django_db def test_group_factory(): factory = GroupFactory() assert isinstance(factory, Group) ...
Mark all of these tests too.
Mark all of these tests too.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
61c4c634807b4adfe9e08152543eba396e256ab9
conllu/tree_helpers.py
conllu/tree_helpers.py
from __future__ import print_function, unicode_literals from collections import namedtuple TreeNode = namedtuple('TreeNode', ['data', 'children']) def create_tree(node_children_mapping, start=0): subtree = [ TreeNode(child, create_tree(node_children_mapping, child["id"])) for child in node_childre...
from __future__ import print_function, unicode_literals from collections import namedtuple TreeNode = namedtuple('TreeNode', ['data', 'children']) def create_tree(node_children_mapping, start=0): subtree = [ TreeNode(child, create_tree(node_children_mapping, child["id"])) for child in node_childre...
Generalize print_tree to work with different number of columns.
Generalize print_tree to work with different number of columns.
Python
mit
EmilStenstrom/conllu
c7deb065bc51661501289b1f695aa0c21260266d
python/saliweb/backend/process_jobs.py
python/saliweb/backend/process_jobs.py
def main(webservice): web = webservice.get_web_service(webservice.config) web.do_all_processing()
from optparse import OptionParser import saliweb.backend import sys def get_options(): parser = OptionParser() parser.set_usage(""" %prog [-h] [-v] Do any necessary processing of incoming, completed, or old jobs. """) parser.add_option('-v', '--verbose', action="store_true", dest="verbose", ...
Add a verbose option; by default, swallow any statefile exception.
Add a verbose option; by default, swallow any statefile exception.
Python
lgpl-2.1
salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb
5c296cdb60f448c6dc15720d5ec7a5310a09f1ae
troposphere/eventschemas.py
troposphere/eventschemas.py
# 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: 10.0.0 from . import AWSObject from troposphere import Tags class Discoverer(AWSObject): resource_type = "AW...
# 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: 14.1.0 from . import AWSObject from troposphere import Tags class Discoverer(AWSObject): resource_type = "AW...
Update EventSchemas per 2020-04-30 changes
Update EventSchemas per 2020-04-30 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
c30534ae95dd5d8ffbe449a842538fafd808c773
python/tests/test_none.py
python/tests/test_none.py
import types def test_none_singleton(py2): if py2: assert isinstance(None, types.NoneType) else: # https://stackoverflow.com/questions/21706609 assert type(None)() is None class Negator(object): def __eq__(self, other): return not other # doesn't make sense def test_none_...
import types def test_singleton(py2): if py2: assert isinstance(None, types.NoneType) else: # https://stackoverflow.com/questions/21706609 assert type(None)() is None class Negator(object): def __eq__(self, other): return not other # doesn't make sense def __ne__(self...
Improve tests relevant to None comparison
[python] Improve tests relevant to None comparison
Python
mit
imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning,imsardine/learning
b6b627cb4c5d6b7dc1636794de870a2bf6da262b
cookiecutter/replay.py
cookiecutter/replay.py
# -*- coding: utf-8 -*- """ cookiecutter.replay ------------------- """ from __future__ import unicode_literals from .compat import is_string def dump(template_name, context): if not is_string(template_name): raise TypeError('Template name is required to be of type str')
# -*- coding: utf-8 -*- """ cookiecutter.replay ------------------- """ from __future__ import unicode_literals from .compat import is_string def dump(template_name, context): if not is_string(template_name): raise TypeError('Template name is required to be of type str') if not isinstance(context,...
Raise a TypeError if context is not a dict
Raise a TypeError if context is not a dict
Python
bsd-3-clause
pjbull/cookiecutter,hackebrot/cookiecutter,cguardia/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,agconti/cookiecutter,michaeljoseph/cookiecutter,venumech/cookiecutter,christabor/cookiecutter,michaeljoseph/cookiecutter,terryjbates/cookiecutter,takeflight/cookiecutter,dajose/cookiecutter,pjbull/cookiecutter,...
0c17311f7fd511f5dae8f8e4acc2dce1a2de3cf5
main.py
main.py
import numpy as np import matplotlib.pyplot as plt # generate sample data x_data = np.linspace(-5, 5, 20) y_data = np.random.normal(0.0, 1.0, x_data.size) plt.plot(x_data, y_data, 'o') plt.show()
import math import numpy as np import matplotlib.pyplot as plt # generate sample data x_data = np.linspace(-math.pi, math.pi, 30) y_data = np.sin(x_data) + np.random.normal(0.0, 0.1, x_data.size) plt.plot(x_data, y_data, 'o') plt.show()
Change to sin() function with noise
Change to sin() function with noise
Python
mit
MorganR/basic-gaussian-process
65074720eee3f86f819046607e986d293c7d400f
api/commands.py
api/commands.py
import json import requests from Suchary.local_settings import GCM_API_KEY from api.models import Device URL = 'https://android.googleapis.com/gcm/send' HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'} def get_reg_ids(): reg_ids = [device.registration_id for device in Device.o...
import json import requests from Suchary.local_settings import GCM_API_KEY from api.models import Device URL = 'https://android.googleapis.com/gcm/send' HEADER = {'Authorization': 'key=' + GCM_API_KEY, 'Content-Type': 'application/json'} def get_reg_ids(alias): devices = Device.objects.filter(active=True) ...
Send message only to one device if its alias was specified.
Send message only to one device if its alias was specified.
Python
mit
jchmura/suchary-django,jchmura/suchary-django,jchmura/suchary-django
08adcf2402f46dfc3332146cac1705e149b18e32
tree/108.py
tree/108.py
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None #recursive solution class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None #recursive solution class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: if not nums: return None ...
Convert Sorted Array to Binary Search Tree
Convert Sorted Array to Binary Search Tree
Python
apache-2.0
MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode,MingfeiPan/leetcode
221d672368f8989508aaf5b36f6a4f9f5bd5425a
winthrop/books/migrations/0008_add-digital-edition.py
winthrop/books/migrations/0008_add-digital-edition.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-17 18:01 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('djiffy', '0002_add-digital-edition'), ('books', '00...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-02-17 18:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('djiffy', '0001_initial'), ('books', '0007_title-len...
Fix migration so it works with actual existing djiffy migrations
Fix migration so it works with actual existing djiffy migrations
Python
apache-2.0
Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django,Princeton-CDH/winthrop-django
0f77c9a48e84a3185794f97c5f15c7b13ae1d505
tests/test_vector2_angle.py
tests/test_vector2_angle.py
from ppb_vector import Vector2 from math import isclose import pytest @pytest.mark.parametrize("left, right, expected", [ (Vector2(1, 1), Vector2(0, -1), 135), (Vector2(1, 1), Vector2(-1, 0), 135), (Vector2(0, 1), Vector2(0, -1), 180), (Vector2(-1, -1), Vector2(1, 0), 135), (Vector2(-1, -1), Vector...
from ppb_vector import Vector2 from math import isclose import pytest @pytest.mark.parametrize("left, right, expected", [ (Vector2(1, 1), Vector2(0, -1), 135), (Vector2(1, 1), Vector2(-1, 0), 135), (Vector2(0, 1), Vector2(0, -1), 180), (Vector2(-1, -1), Vector2(1, 0), 135), (Vector2(-1, -1), Vector...
Add some additional test cases
Add some additional test cases
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
11022b79ded961bdd2e9a6bff0c4f4a03097084c
scripts/install_new_database.py
scripts/install_new_database.py
#!/usr/bin/env python3 import os import sys _upper_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) if _upper_dir not in sys.path: sys.path.append(_upper_dir) import chdb if __name__ == '__main__': chdb.install_scratch_db()
#!/usr/bin/env python3 import os import sys _upper_dir = os.path.abspath( os.path.join(os.path.dirname(__file__), '..')) if _upper_dir not in sys.path: sys.path.append(_upper_dir) import chdb def sanity_check(): sdb = chdb.init_scratch_db() snippet_count = sdb.execute_with_retry_s( '''SELECT ...
Add a couple of sanity checks so we don't break the database.
Add a couple of sanity checks so we don't break the database. Part of #139.
Python
mit
guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,eggpi/citationhunt
4836cb93b03eae38c0e1eebeee831f9b4fc012eb
cozify/config.py
cozify/config.py
import configparser import os def ephemeralWrite(): with open(ephemeralFile, 'w') as configfile: ephemeral.write(configfile) # prime ephemeral storage ephemeralFile = "%s/.config/python-cozify.cfg" % os.path.expanduser('~') try: file = open(ephemeralFile, 'r') except IOError: file = open(ephemeral...
import configparser import os ephemeralFile = "%s/.config/python-cozify.cfg" % os.path.expanduser('~') ephemeral = None def ephemeralWrite(): with open(ephemeralFile, 'w') as configfile: ephemeral.write(configfile) # allow setting the ephemeral storage location. # Useful especially for testing without a...
Support for changing ephemeral state storage mid-run. Mostly useful for debugging and testing without hosing your main state
Support for changing ephemeral state storage mid-run. Mostly useful for debugging and testing without hosing your main state
Python
mit
Artanicus/python-cozify,Artanicus/python-cozify
4a3da350105314310cb0a44f11b50c9c6c6617ee
integration-test/1387-business-and-spur-routes.py
integration-test/1387-business-and-spur-routes.py
from . import FixtureTest class BusinessAndSpurRoutes(FixtureTest): def test_first_capitol_dr_i70_business(self): self.load_fixtures([ 'https://www.openstreetmap.org/relation/1933234', ]) # check that First Capitol Dr, part of the above relation, is given # a network ...
from . import FixtureTest class BusinessAndSpurRoutes(FixtureTest): def _check_route_relation( self, rel_id, way_id, tile, shield_text, network): z, x, y = map(int, tile.split('/')) self.load_fixtures([ 'https://www.openstreetmap.org/relation/%d' % (rel_id,), ], c...
Add more test cases for spur / business route modifiers.
Add more test cases for spur / business route modifiers.
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
f7d83caae3264d86420ce654f3669175c284a82d
ocradmin/core/decorators.py
ocradmin/core/decorators.py
# Miscellaneos functions relating the projects app import os from datetime import datetime from django.http import HttpResponseRedirect from django.utils.http import urlquote from django.conf import settings def project_required(func): """ Decorator function for other actions that require a project to be ...
# Miscellaneos functions relating the projects app import os from datetime import datetime from django.http import HttpResponseRedirect from django.utils.http import urlquote from django.conf import settings def project_required(func): """ Decorator function for other actions that require a project to be ...
Add project as request attribute to save a little boilerplate
Add project as request attribute to save a little boilerplate
Python
apache-2.0
vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium,vitorio/ocropodium
abfe1e291d0c9963cb91d0e95996c8fe72167107
src/Figures/FigureHelpers.py
src/Figures/FigureHelpers.py
""" Created on Jun 12, 2013 @author: agross """ import matplotlib.pyplot as plt def init_ax(ax, figsize=None): """ Helper to initialize an axis. If the axis is not specified (eg is None), this fill create a new figure. ax: matplotlib axis object, or None figsize: size of figure if we have ...
""" Created on Jun 12, 2013 @author: agross """ import matplotlib.pyplot as plt def init_ax(ax, figsize=None): """ Helper to initialize an axis. If the axis is not specified (eg is None), this fill create a new figure. ax: matplotlib axis object, or None figsize: size of figure if we have ...
Add non-default option to despline top of axis.
Add non-default option to despline top of axis.
Python
mit
theandygross/Figures
203642a879fb934b99e4d55025eede171390a4d4
mopidy_dleyna/__init__.py
mopidy_dleyna/__init__.py
import pathlib from mopidy import config, exceptions, ext __version__ = "1.2.2" class Extension(ext.Extension): dist_name = "Mopidy-dLeyna" ext_name = "dleyna" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_co...
import pathlib import pkg_resources from mopidy import config, exceptions, ext __version__ = pkg_resources.get_distribution("Mopidy-dLeyna").version class Extension(ext.Extension): dist_name = "Mopidy-dLeyna" ext_name = "dleyna" version = __version__ def get_default_config(self): return c...
Use pkg_resources to read version
Use pkg_resources to read version
Python
apache-2.0
tkem/mopidy-dleyna
a044d33c1e29a1d283baa6bd24b1c63676b061df
install-qt.py
install-qt.py
''' Simple script to install PyQt or PySide based on PYTEST_QT_FORCE_PYQT and python version. Meant to be used in travis-ci. ''' import os import sys def run(cmd): print(cmd) r = os.system(cmd) if r != 0: sys.exit('command %s failed with status %s' % (cmd, r)) py3k = sys.version_info[0] == 3 if os...
''' Simple script to install PyQt or PySide based on PYTEST_QT_FORCE_PYQT and python version. Meant to be used in travis-ci. ''' import os import sys def run(cmd): print(cmd) r = os.system(cmd) if r != 0: sys.exit('command %s failed with status %s' % (cmd, r)) py3k = sys.version_info[0] == 3 if os...
Install debugging symbols on Travis
Install debugging symbols on Travis
Python
mit
pytest-dev/pytest-qt,The-Compiler/pytest-qt
b744498b2308748dacf9947b78386f10f2072061
beetle/utils.py
beetle/utils.py
import os def read_folder(folder, mode): for folder, __, files in os.walk(folder): for file_name in files: path = os.path.join(folder, file_name) with open(path, mode) as fo: yield path, fo.read() def remove_leading_folder(path): __, partial_path = path.split(...
import os def read_folder(folder, mode): if 'b' in mode: encoding = None else: encoding = 'utf-8' for folder, __, files in os.walk(folder): for file_name in files: path = os.path.join(folder, file_name) with open(path, mode, encoding=encoding) as fo: ...
Define encoding when reading files if they aren't opened in binary mode
Define encoding when reading files if they aren't opened in binary mode
Python
mit
cknv/beetle
65b1f849cbf02320992e3ef9db86c71e564cc826
src/mountebank/exceptions.py
src/mountebank/exceptions.py
class ImposterException(StandardError): def __init__(self, response): self._response = response
import sys if sys.version_info.major == 2: error_base_class = StandardError elif sys.version_info.major == 3: error_base_class = Exception else: raise RuntimeError('Unsupported Python version: {}'.format(sys.version)) class ImposterException(error_base_class): def __init__(self, response): s...
Make Python 2 and 3 compatible
Make Python 2 and 3 compatible
Python
bsd-2-clause
kevinjqiu/py-mountebank
e9d62c12448822246ad0ed79a90b36dd27429615
echidna/demo/server.py
echidna/demo/server.py
""" Echidna demo server. """ import os from cyclone.web import RequestHandler from echidna.server import EchidnaServer class DemoServer(EchidnaServer): """ A server to demo Echidna. """ def __init__(self, **settings): defaults = { "template_path": ( os.path.join...
""" Echidna demo server. """ import os from cyclone.web import RequestHandler from echidna.server import EchidnaServer class DemoServer(EchidnaServer): """ A server to demo Echidna. """ def __init__(self, **settings): defaults = { "template_path": ( os.path.join...
Add list of channels to demo.html template context.
Add list of channels to demo.html template context.
Python
bsd-3-clause
praekelt/echidna,praekelt/echidna,praekelt/echidna,praekelt/echidna
396df5eac473fccc16e103d3d3316aefd653789a
changeling/models.py
changeling/models.py
import uuid import jsonschema import changeling.exception class Change(object): schema = { 'name': 'change', 'properties': { 'id': {'type': 'string'}, 'name': {'type': 'string'}, 'description': {'type': 'string'}, }, 'additionalProperties': Fa...
import uuid import jsonschema import changeling.exception class Change(object): schema = { 'name': 'change', 'properties': { 'id': {'type': 'string'}, 'name': {'type': 'string'}, 'description': {'type': 'string'}, 'tags': {'type': 'array'}, ...
Add tags - that was too easy
Add tags - that was too easy
Python
apache-2.0
bcwaldon/changeling,bcwaldon/changeling
4a24e19c160535c7a65c7f3f11748e6048386038
examples/gst/wavenc.py
examples/gst/wavenc.py
#!/usr/bin/env python import sys import gst def decode(filename): output = filename + '.wav' pipeline = ('filesrc location="%s" ! spider ! audio/x-raw-int,rate=44100,stereo=2 ! wavenc ! ' 'filesink location="%s"') % (filename, output) bin = gst.parse_launch(pipeline) bin.set_state(...
#!/usr/bin/env python import sys import gst def decode(filename): output = filename + '.wav' pipeline = ('{ filesrc location="%s" ! spider ! audio/x-raw-int,rate=44100,stereo=2 ! wavenc ! ' 'filesink location="%s" }') % (filename, output) bin = gst.parse_launch(pipeline) bin.set_st...
Put it in a thread and run it in a mainloop
Put it in a thread and run it in a mainloop Original commit message from CVS: Put it in a thread and run it in a mainloop
Python
lgpl-2.1
lubosz/gst-python,freedesktop-unofficial-mirror/gstreamer__gst-python,lubosz/gst-python,alessandrod/gst-python,freedesktop-unofficial-mirror/gstreamer__gst-python,GStreamer/gst-python,pexip/gst-python,freedesktop-unofficial-mirror/gstreamer-sdk__gst-python,GStreamer/gst-python,pexip/gst-python,freedesktop-unofficial-mi...
fc523d543392b9ef7d5b8b6c8ec962b151552e42
tests/test_fields/test_uuid_field.py
tests/test_fields/test_uuid_field.py
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.test import TestCase from model_utils.fields import UUIDField class UUIDFieldTests(TestCase): def test_uuid_version_default(self): instance = UUIDField() self.assertEqual(instance...
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.test import TestCase from model_utils.fields import UUIDField class UUIDFieldTests(TestCase): def test_uuid_version_default(self): instance = UUIDField() self.assertEqual(instance...
Add tdd to increase coverage
Add tdd to increase coverage
Python
bsd-3-clause
carljm/django-model-utils,carljm/django-model-utils
61018e88f6ef7e24665fca8b336493ff254fa61b
examples/irrev_rxns.py
examples/irrev_rxns.py
"""Example of irreversible reaction.""" import os from chemkinlib.utils import Parser from chemkinlib.reactions import ReactionSystems from chemkinlib.config import DATA_DIRECTORY import numpy # USER INPUT: reaction (xml) file xml_filename = os.path.join(DATA_DIRECTORY, "rxnset_long.xml") parser = Parser.ReactionP...
"""Example of irreversible reaction.""" import os from chemkinlib.utils import Parser from chemkinlib.reactions import ReactionSystems from chemkinlib.config import DATA_DIRECTORY import numpy # USER INPUT: reaction (xml) file xml_filename = os.path.join(DATA_DIRECTORY, "rxnset_long.xml") parser = Parser.ReactionP...
Add documentation of the new functions
Add documentation of the new functions
Python
mit
cs207-group11/cs207-FinalProject,krmotwani/cs207-FinalProject,hsim13372/cs207-FinalProject
6d43879608a3f218120b88da911c8bacf8177d82
owebunit/tests/simple.py
owebunit/tests/simple.py
import BaseHTTPServer import threading import time import owebunit import bottle app = bottle.Bottle() @app.route('/ok') def ok(): return 'ok' @app.route('/internal_server_error') def internal_error(): bottle.abort(500, 'internal server error') def run_server(): app.run(host='localhost', port=8041) cla...
import BaseHTTPServer import threading import time import owebunit import bottle app = bottle.Bottle() @app.route('/ok') def ok(): return 'ok' @app.route('/internal_server_error') def internal_error(): bottle.abort(500, 'internal server error') def run_server(): app.run(host='localhost', port=8041) cla...
Test using multiple concurrent sessions
Test using multiple concurrent sessions
Python
bsd-2-clause
p/webracer
5b8482aa7851f11df81e8a457c85b53dbcbeeddf
f8a_jobs/graph_sync.py
f8a_jobs/graph_sync.py
"""Functions to retrieve pending list and invoke Graph Sync.""" import f8a_jobs.defaults as configuration import requests import traceback import logging logger = logging.getLogger(__name__) def _api_call(url, params={}): try: logger.info("API Call for url: %s, params: %s" % (url, params)) r = ...
"""Functions to retrieve pending list and invoke Graph Sync.""" import f8a_jobs.defaults as configuration import requests import traceback import logging from urllib.parse import urljoin logger = logging.getLogger(__name__) def _api_call(url, params=None): params = params or {} try: logger.info("AP...
Fix code for review comments
Fix code for review comments
Python
apache-2.0
fabric8-analytics/fabric8-analytics-jobs,fabric8-analytics/fabric8-analytics-jobs
079e7cbbd59266e1dc8b161989c90202caa4c5a8
flaskbb/utils/views.py
flaskbb/utils/views.py
from flask import render_template from flask.views import View class RenderableView(View): def __init__(self, template, view): self.template = template self.view = view def dispatch_request(self, *args, **kwargs): view_model = self.view(*args, **kwargs) return render_template(...
from flaskbb.utils.helpers import render_template from flask.views import View class RenderableView(View): def __init__(self, template, view): self.template = template self.view = view def dispatch_request(self, *args, **kwargs): view_model = self.view(*args, **kwargs) return ...
Use local render_template than Flask's native
Use local render_template than Flask's native TODO: Provide a renderer argument at instantation?
Python
bsd-3-clause
realityone/flaskbb,realityone/flaskbb,dromanow/flaskbb,dromanow/flaskbb,realityone/flaskbb,dromanow/flaskbb
3dcf879c7188f61d43d3a3b11dc74b8de431037a
pyethapp/tests/test_jsonrpc.py
pyethapp/tests/test_jsonrpc.py
solidity_code = "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }" def test_compileSolidity(): from pyethapp.jsonrpc import Compilers, data_encoder import ethereum._solidity s = ethereum._solidity.get_solidity() c = Compilers() assert 'solidity' in c.getCompilers() ...
import pytest solidity_code = "contract test { function multiply(uint a) returns(uint d) { return a * 7; } }" def test_compileSolidity(): from pyethapp.jsonrpc import Compilers, data_encoder import ethereum._solidity s = ethereum._solidity.get_solidity() if s == None: pytest.xfail("solidity...
Fix test to xfail when Solidity is not present
Fix test to xfail when Solidity is not present
Python
mit
ethereum/pyethapp,changwu-tw/pyethapp,gsalgado/pyethapp,RomanZacharia/pyethapp,changwu-tw/pyethapp,ethereum/pyethapp,d-das/pyethapp,vaporry/pyethapp,RomanZacharia/pyethapp,gsalgado/pyethapp
e77ed1e555f363c23734ec80a0daf6fa740b78ee
scripts/cache/dm/combine.py
scripts/cache/dm/combine.py
# Combine DM layers into one shapefile! # Daryl Herzmann 4 Nov 2005 import mapscript, dbflib, sys ts = sys.argv[1] outshp = mapscript.shapefileObj('dm_%s.shp'%ts, mapscript.MS_SHAPEFILE_POLYGON ) dbf = dbflib.create("dm_%s"%ts) dbf.add_field("DCAT", dbflib.FTInteger, 1, 0) counter = 0 for d in range(5): shp = map...
# Combine DM layers into one shapefile! # Daryl Herzmann 4 Nov 2005 import mapscript, dbflib, sys, os ts = sys.argv[1] outshp = mapscript.shapefileObj('dm_%s.shp'%ts, mapscript.MS_SHAPEFILE_POLYGON ) dbf = dbflib.create("dm_%s"%ts) dbf.add_field("DCAT", dbflib.FTInteger, 1, 0) counter = 0 for d in range(5): if no...
Check for shapefile existance before attempting to open
Check for shapefile existance before attempting to open
Python
mit
akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem
713e720bd3e4029273d72ab58aa79fbd79f0bafa
unit_tests/test_analyse_idynomics.py
unit_tests/test_analyse_idynomics.py
from nose.tools import * from analyse_idynomics import * from os.path import join, dirname, realpath class TestAnalyseiDynomics: expected_solutes = ['MyAtmos', 'pressure'] expected_species = ['MyBact'] expected_timesteps = 2 expected_dimensions = (20.0, 20.0, 2.0) def setUp(self): self...
from nose.tools import * from analyse_idynomics import * from os.path import join, dirname, realpath class TestAnalyseiDynomics: expected_solutes = ['MyAtmos', 'pressure'] expected_species = ['MyBact'] expected_reaction_rates = ['MyGrowth-rate'] expected_timesteps = 2 expected_dimensions = (20.0, 2...
Add unit test for getting reaction rate names
Add unit test for getting reaction rate names
Python
mit
fophillips/pyDynoMiCS
284d750d7da25b1d3db17ca4d5931e1b6d1d7319
tests/browser/test_editor.py
tests/browser/test_editor.py
from fancypages.test.testcases import SplinterTestCase class TestEditingFancyPage(SplinterTestCase): is_staff = True is_logged_in = True def test_moving_a_block(self): pass
from django.core.urlresolvers import reverse from fancypages.test.testcases import SplinterTestCase class TestTheEditorPanel(SplinterTestCase): is_staff = True is_logged_in = True def _get_cookie_names(self): return [c.get('name') for c in self.browser.cookies.all()] def test_can_be_opened_...
Add tests for editor panel JS
Add tests for editor panel JS
Python
bsd-3-clause
tangentlabs/django-fancypages,socradev/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages
53cf4a078a072c9510e389295c19a0391b1eeef8
grab/tools/encoding.py
grab/tools/encoding.py
import re RE_SPECIAL_ENTITY = re.compile('&#(1[2-6][0-9]);') def smart_str(value, encoding='utf-8'): """ Normalize unicode/byte string to byte string. """ if isinstance(value, unicode): value = value.encode(encoding) return value def smart_unicode(value, encoding='utf-8'): """ N...
import re RE_SPECIAL_ENTITY = re.compile('&#(1[2-6][0-9]);') def smart_str(value, encoding='utf-8'): """ Normalize unicode/byte string to byte string. """ if isinstance(value, unicode): value = value.encode(encoding) return value def smart_unicode(value, encoding='utf-8'): """ N...
Fix issue in special_entity_handler function
Fix issue in special_entity_handler function
Python
mit
alihalabyah/grab,pombredanne/grab-1,SpaceAppsXploration/grab,alihalabyah/grab,codevlabs/grab,DDShadoww/grab,lorien/grab,kevinlondon/grab,raybuhr/grab,maurobaraldi/grab,huiyi1990/grab,istinspring/grab,giserh/grab,DDShadoww/grab,maurobaraldi/grab,pombredanne/grab-1,shaunstanislaus/grab,subeax/grab,huiyi1990/grab,liorvh/g...
a0a90c7a4be2b419af0d745753b83f11f63916d2
registration/__init__.py
registration/__init__.py
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
VERSION = (1, 0, 0, 'final', 0) def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases...
Fix version number reporting so we can be installed before Django.
Fix version number reporting so we can be installed before Django.
Python
bsd-3-clause
lubosz/django-registration,lubosz/django-registration
66dc90fd88f3d70b166c5bb69a4b4e2bed743848
synapse/tests/test_config.py
synapse/tests/test_config.py
from synapse.tests.common import * import synapse.lib.config as s_config class ConfTest(SynTest): def test_conf_base(self): defs = ( ('fooval',{'type':'int','doc':'what is foo val?','defval':99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}), ) ...
from synapse.tests.common import * import synapse.lib.config as s_config class ConfTest(SynTest): def test_conf_base(self): defs = ( ('fooval',{'type':'int','doc':'what is foo val?','defval':99}), ('enabled',{'type':'bool','doc':'is thing enabled?','defval':0}), ) ...
Update test to ensure that default configuration values are available via getConfOpt
Update test to ensure that default configuration values are available via getConfOpt
Python
apache-2.0
vivisect/synapse,vertexproject/synapse,vertexproject/synapse,vertexproject/synapse
658e0a3dbd260f2d27756ed5605794b2320ba728
backend/src/pox/ext/gini/samples/packet_loss.py
backend/src/pox/ext/gini/samples/packet_loss.py
#!/usr/bin/python2 """ packet_loss.py: Simulates packet loss by dropping all packets with a probability of 25%. """ import random from pox.core import core import pox.openflow.libopenflow_01 as of def packet_in(event):. if random.random() >= 0.25: msg = of.ofp_packet_out(data = event.ofp) msg.ac...
#!/usr/bin/python2 """ packet_loss.py: Simulates packet loss by dropping all packets with a probability of 25%. """ import random from pox.core import core import pox.openflow.libopenflow_01 as of def packet_in(event): if random.random() >= 0.25: msg = of.ofp_packet_out(data = event.ofp) msg.act...
Fix bug in packet loss
Fix bug in packet loss
Python
mit
anrl/gini3,michaelkourlas/gini,michaelkourlas/gini,anrl/gini3,michaelkourlas/gini,anrl/gini3,michaelkourlas/gini,anrl/gini3,anrl/gini3,michaelkourlas/gini
9b859b4dfc0f215b61e05662f0d0af435227e932
src/adhocracy_sample/adhocracy_sample/__init__.py
src/adhocracy_sample/adhocracy_sample/__init__.py
"""Simple sample app using the Adhocracy core.""" from adhocracy import root_factory from pyramid.config import Configurator def includeme(config): """Setup sample app.""" config.include('adhocracy') # include default resource types config.include('adhocracy.resources.tag') config.include('adhocra...
"""Simple sample app using the Adhocracy core.""" from adhocracy import root_factory from pyramid.config import Configurator def includeme(config): """Setup sample app.""" config.include('adhocracy') # include additional default resource types config.include('adhocracy.resources.tag') config.inclu...
Include additional resources + sheets for login test.
Include additional resources + sheets for login test.
Python
agpl-3.0
fhartwig/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,liqd/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,liqd/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,xs2maverick/adhocracy3.mercator,fhartwig/adhocracy3.mercator,liqd/adhocra...
b7eff5f52801fb066b975ce1726a76bcfa64987a
injectors/tty.py
injectors/tty.py
# vim: set fileencoding=utf-8 # Pavel Odvody <podvody@redhat.com> # # HICA - Host integrated container applications # # MIT License (C) 2015 from base.hica_base import * class TtyInjector(HicaInjector): def get_description(self): return 'Allocates a TTY for the process' def get_config_key(self): return '...
# vim: set fileencoding=utf-8 # Pavel Odvody <podvody@redhat.com> # # HICA - Host integrated container applications # # MIT License (C) 2015 from base.hica_base import * class TtyInjector(HicaInjector): def get_description(self): return 'Allocates a TTY for the process' def get_config_key(self): return '...
Use the proper none value
Use the proper none value
Python
mit
shaded-enmity/docker-hica
c30d9685239607883aeaee73618651f694f7d1b2
server/lib/slack/add_player.py
server/lib/slack/add_player.py
#!/usr/bin/python2.7 import re import lib.webutil as webutil from lib.data import players as player_data def handle(command_text): player_components = command_text.split(' ') new_player_id = re.sub('[<@]', '', player_components[2].split('|')[0]) player = player_data.get_player(new_player_id) if player...
#!/usr/bin/python2.7 import re import lib.webutil as webutil import slack.util as slackutil from lib.data import players as player_data def handle(command_text): player_components = command_text.split(' ') new_player_id = re.sub('[<@]', '', player_components[2].split('|')[0]) player = player_data.get_play...
Update response for adding a player
Update response for adding a player
Python
mit
groppe/mario
d34fb5a386eae07f57c78125d13664aa7965c487
demo/__init__.py
demo/__init__.py
#!/usr/bin/env python """Package for PythonTemplateDemo.""" __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = __project__ + '-' + __version__
"""Package for PythonTemplateDemo.""" __project__ = 'PythonTemplateDemo' __version__ = '0.0.0' VERSION = __project__ + '-' + __version__
Deploy Travis CI build 352 to GitHub
Deploy Travis CI build 352 to GitHub
Python
mit
jacebrowning/template-python-demo
a5b57601da6e9b85eca18d61e3784addd1863fa4
i3pystatus/__init__.py
i3pystatus/__init__.py
#!/usr/bin/env python from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp
from pkgutil import extend_path from i3pystatus.core import Status from i3pystatus.core.modules import Module, IntervalModule from i3pystatus.core.settings import SettingsBase from i3pystatus.core.util import formatp __path__ = extend_path(__path__, __name__)
Make i3pystatus a namespace package
Make i3pystatus a namespace package
Python
mit
Arvedui/i3pystatus,schroeji/i3pystatus,opatut/i3pystatus,MaicoTimmerman/i3pystatus,eBrnd/i3pystatus,m45t3r/i3pystatus,teto/i3pystatus,drwahl/i3pystatus,Arvedui/i3pystatus,teto/i3pystatus,fmarchenko/i3pystatus,plumps/i3pystatus,paulollivier/i3pystatus,juliushaertl/i3pystatus,ismaelpuerto/i3pystatus,schroeji/i3pystatus,n...
aad810071f5b0a93f312a93d3bfa12271ae477ee
ext/avalon-gunicorn.py
ext/avalon-gunicorn.py
# Configuration for running the Avalon Music Server under Gunicorn # http://docs.gunicorn.org # Note that this configuration omits a bunch of features that Gunicorn # has (such as running as a daemon, changing users, error and access # logging) because it is designed to be used when running Gunicorn # with supervisord...
# Configuration for running the Avalon Music Server under Gunicorn # http://docs.gunicorn.org # Note that this configuration omits a bunch of features that Gunicorn # has (such as running as a daemon, changing users, error and access # logging) because it is designed to be used when running Gunicorn # with supervisord...
Fix comment about why we use preload
Fix comment about why we use preload
Python
mit
tshlabs/avalonms
29a1a39cf4f0fed6999bd787cce7e8e65c49ef4e
display_image.py
display_image.py
import matplotlib.pyplot as plt class ImageWindow: def __init__(self): self.imsh = None plt.ion() plt.show() def display(self, image): if self.imsh is None or not plt.fignum_exists(self.imsh.figure.number): self.imsh = plt.imshow(image, interpolation='nearest') ...
import matplotlib.pyplot as plt class ImageWindow: def __init__(self): self.imsh = None plt.ion() plt.show() def display(self, image): if self.imsh is None or not plt.fignum_exists(self.imsh.figure.number): self.imsh = plt.imshow(image, interpolation='nearest') ...
Set image to fill the entire matplotlib window
Set image to fill the entire matplotlib window
Python
mit
crowsonkb/style_transfer,crowsonkb/style_transfer,crowsonkb/style_transfer,crowsonkb/style_transfer
402056a272c94d3d28da62b08cac14ace18c835a
test/python_api/default-constructor/sb_address.py
test/python_api/default-constructor/sb_address.py
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.GetFileAddress() obj.GetLoadAddress(lldb.SBTarget()) obj.OffsetAddress(sys.maxint) obj.GetDescription(lldb.SBStream()) obj.Clear()
""" Fuzz tests an object after the default construction to make sure it does not crash lldb. """ import sys import lldb def fuzz_obj(obj): obj.GetFileAddress() obj.GetLoadAddress(lldb.SBTarget()) obj.SetLoadAddress(0xffff, lldb.SBTarget()) obj.OffsetAddress(sys.maxint) obj.GetDescription(lldb.SBSt...
Add new API for SBAddress to the fuzz test:
Add new API for SBAddress to the fuzz test: SetLoadAddress (lldb::addr_t load_addr, lldb::SBTarget &target); git-svn-id: b33bab8abb5b18c12ee100cd7761ab452d00b2b0@135793 91177308-0d34-0410-b5e6-96231b3b80d8
Python
apache-2.0
llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb
eb06650567fe94b65e6ccf55446982af746761af
cumulusci/tasks/salesforce/communities_preflights.py
cumulusci/tasks/salesforce/communities_preflights.py
import requests from cumulusci.tasks.salesforce import BaseSalesforceApiTask class IsCommunitiesEnabled(BaseSalesforceApiTask): api_version = "48.0" def _run_task(self): s = requests.Session() s.get(self.org_config.start_url).raise_for_status() r = s.get( "{}/sites/servlet...
import requests from cumulusci.tasks.salesforce import BaseSalesforceApiTask class IsCommunitiesEnabled(BaseSalesforceApiTask): api_version = "48.0" def _run_task(self): s = requests.Session() s.get(self.org_config.start_url).raise_for_status() r = s.get( "{}/sites/servlet...
Clean logic in Communities preflight
Clean logic in Communities preflight
Python
bsd-3-clause
SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI
d5fb6c5320dbb6827e24dc22be08454f05aac83e
emails/tests.py
emails/tests.py
from django.test import TestCase from django.core.urlresolvers import reverse from common.util import create_admin, create_user class TestEmailRendering(TestCase): def setUp(self): self.user = create_user(username='user', password='password') self.admin = create_admin(username='admin', password='p...
from django.test import TestCase from django.core.urlresolvers import reverse from common.util import create_admin, create_user class TestEmailRendering(TestCase): def setUp(self): self.user = create_user(username='user', password='password') self.admin = create_admin(username='admin', password='p...
Test that regular users can send test emails
Test that regular users can send test emails
Python
agpl-3.0
Turupawn/website,lutris/website,Turupawn/website,Turupawn/website,lutris/website,Turupawn/website,lutris/website,lutris/website
a5e7423b01ffb4fed1987dfadbe9283480f04929
grazer/core/parsing.py
grazer/core/parsing.py
import re import logging logger = logging.getLogger("Parsing") def create_node(data): tag_part = r"(?P<tag>\w+)" attr_part = r"(?P<q>\[(?P<attr>\w+)=(\"|\')(?P<val>.+?)(\"|\')\])?" selector_part = r"(\{(?P<selector>\d+)\})?" p = tag_part + attr_part + selector_part patt = re.compile(p) m = p...
import re import logging logger = logging.getLogger("Parsing") def create_node(data): tag_part = r"(?P<tag>\w+)" attr_part = r"(?P<q>\[(?P<attr>\w+)=(\"|\')(?P<val>.+?)(\"|\')\])?" selector_part = r"(\{(?P<selector>\d+)\})?" p = tag_part + attr_part + selector_part patt = re.compile(p) m = p...
Fix for zero depth path
Fix for zero depth path
Python
mit
CodersOfTheNight/verata
5bbed41d8150f6d0657f1a7670b449619f3ba0f7
promgen/util.py
promgen/util.py
# Copyright (c) 2017 LINE Corporation # These sources are released under the terms of the MIT license: see LICENSE import requests from promgen.version import __version__ def post(url, *args, **kwargs): '''Wraps requests.post with our user-agent''' if 'headers' not in kwargs: kwargs['headers'] = {} ...
# Copyright (c) 2017 LINE Corporation # These sources are released under the terms of the MIT license: see LICENSE import requests.sessions from promgen.version import __version__ def post(url, **kwargs): with requests.sessions.Session() as session: session.headers['User-Agent'] = 'promgen/{}'.format(__...
Copy the pattern from requests.api to use a slightly more stable API
Copy the pattern from requests.api to use a slightly more stable API
Python
mit
kfdm/promgen,kfdm/promgen,kfdm/promgen,kfdm/promgen