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
d3489d51621fc001d0700f5a8562e53d82b52cac
tests/test_cyclus.py
tests/test_cyclus.py
#! /usr/bin/env python import os from testcases import sim_files from cyclus_tools import run_cyclus, db_comparator """Tests""" def test_cyclus(): """Test for all inputs in sim_files. Checks if reference and current cyclus output is the same. WARNING: the tests require cyclus executable to be included ...
#! /usr/bin/env python import os from testcases import sim_files from cyclus_tools import run_cyclus, db_comparator """Tests""" def test_cyclus(): """Test for all inputs in sim_files. Checks if reference and current cyclus output is the same. WARNING: the tests require cyclus executable to be included ...
Remove output_temp.h5 only if it exists
Remove output_temp.h5 only if it exists
Python
bsd-3-clause
Baaaaam/cyCLASS,gonuke/cycamore,Baaaaam/cyBaM,cyclus/cycaless,rwcarlsen/cycamore,jlittell/cycamore,jlittell/cycamore,rwcarlsen/cycamore,gonuke/cycamore,cyclus/cycaless,Baaaaam/cycamore,Baaaaam/cyCLASS,Baaaaam/cyBaM,rwcarlsen/cycamore,gonuke/cycamore,jlittell/cycamore,Baaaaam/cycamore,Baaaaam/cycamore,Baaaaam/cyBaM,Baaa...
21e2db0e2c3873e6390eee1865c67ee4c73ba498
tests/test_cyprep.py
tests/test_cyprep.py
import numpy as np import pytest import yatsm._cyprep as cyprep def test_get_valid_mask(): n_bands, n_images, n_mask = 8, 500, 50 data = np.random.randint(0, 10000, size=(n_bands, n_images)).astype(np.int32) # Add in bad data _idx = np.arange(0, n_images) for b in rang...
import numpy as np import pytest import yatsm._cyprep as cyprep def test_get_valid_mask(): n_bands, n_images, n_mask = 8, 500, 50 data = np.random.randint(0, 10000, size=(n_bands, n_images)).astype(np.int32) # Add in bad data _idx = np.arange(0, n_images) for b in rang...
Fix bool logic in mask test & add test criteria
Fix bool logic in mask test & add test criteria
Python
mit
c11/yatsm,ceholden/yatsm,valpasq/yatsm,valpasq/yatsm,c11/yatsm,ceholden/yatsm
40edd2d679bcaebcbdb55b08fdd38b4c1af68672
tests/test_models.py
tests/test_models.py
#! /usr/bin/env python import os import pytest from pymt import models @pytest.mark.parametrize("cls", models.__all__) def test_model_setup(cls): model = models.__dict__[cls]() args = model.setup() assert os.path.isfile(os.path.join(args[1], args[0])) @pytest.mark.parametrize("cls", models.__all__) de...
#! /usr/bin/env python import os import pytest from pymt import models @pytest.mark.parametrize("cls", models.__all__) def test_model_setup(cls): model = models.__dict__[cls]() args = model.setup() assert os.path.isfile(os.path.join(args[1], args[0])) @pytest.mark.parametrize("cls", models.__all__) de...
Add test for finalize method.
Add test for finalize method.
Python
mit
csdms/coupling,csdms/pymt,csdms/coupling
d0d7c1f29ca17d3273033821a8ed1326b0ec7b4c
wmata.py
wmata.py
import datetime import urllib import json class WmataError(Exception): pass class Wmata(object): api_url = 'http://api.wmata.com/%(svc)s.svc/json/%(endpoint)s' # By default, we'll use the WMATA demonstration key def __init__(self, api_key='kfgpmgvfgacx98de9q3xazww'): if api_key is not None: ...
import datetime import urllib import json class WmataError(Exception): pass class Wmata(object): api_url = 'http://api.wmata.com/%(svc)s.svc/json/%(endpoint)s' # By default, we'll use the WMATA demonstration key def __init__(self, api_key='kfgpmgvfgacx98de9q3xazww'): self.api_key = api_key
Remove old default api_key logic in __init__.
Remove old default api_key logic in __init__.
Python
mit
ExperimentMonty/py3-wmata
b9f302f38e07b32590fc4008f413a5baa756dbee
zou/app/resources/source/csv/assets.py
zou/app/resources/source/csv/assets.py
from zou.app.resources.source.csv.base import BaseCsvImportResource from zou.app.project import project_info, asset_info from zou.app.models.entity import Entity from sqlalchemy.exc import IntegrityError class AssetsCsvImportResource(BaseCsvImportResource): def prepare_import(self): self.projects = {} ...
from zou.app.resources.source.csv.base import BaseCsvImportResource from zou.app.project import project_info, asset_info from zou.app.models.entity import Entity from sqlalchemy.exc import IntegrityError class AssetsCsvImportResource(BaseCsvImportResource): def prepare_import(self): self.projects = {} ...
Fix duplicates in asset import
Fix duplicates in asset import It relied on the unique constraint from the database, but it doesn't apply if parent_id is null. So it checks the existence of the asset before inserting it.
Python
agpl-3.0
cgwire/zou
9ebc81565171866462dae5eb068bb7c1d98948a7
ovp_users/serializers/__init__.py
ovp_users/serializers/__init__.py
from ovp_users.serializers.user import UserCreateSerializer from ovp_users.serializers.user import UserUpdateSerializer from ovp_users.serializers.user import CurrentUserSerializer from ovp_users.serializers.user import UserPublicRetrieveSerializer from ovp_users.serializers.user import UserProjectRetrieveSerializer fr...
from ovp_users.serializers.user import UserCreateSerializer from ovp_users.serializers.user import UserUpdateSerializer from ovp_users.serializers.user import CurrentUserSerializer from ovp_users.serializers.user import ShortUserPublicRetrieveSerializer from ovp_users.serializers.user import LongUserPublicRetrieveSeria...
Add ShortUserRetrieve and LongUserRetrieve serializers
Add ShortUserRetrieve and LongUserRetrieve serializers
Python
agpl-3.0
OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users
2a7eecbf55f5cc00bed76a70990946309baa2baa
boardinghouse/tests/test_sql.py
boardinghouse/tests/test_sql.py
""" Tests for the RAW sql functions. """ from django.conf import settings from django.test import TestCase from django.db.models import connection from boardinghouse.models import Schema class TestRejectSchemaColumnChange(TestCase): def test_exception_is_raised(self): Schema.objects.mass_create('a') ...
""" Tests for the RAW sql functions. """ from django.conf import settings from django.test import TestCase from django.db import connection from boardinghouse.models import Schema class TestRejectSchemaColumnChange(TestCase): def test_exception_is_raised(self): Schema.objects.mass_create('a') cur...
Make test work with 1.7
Make test work with 1.7
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
32efe6c239a62c2f011179c4431adf6e028442f0
alg_selection_sort.py
alg_selection_sort.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(a_list): """Selection Sort algortihm. Procedure: - Find out the max item's original slot first, - then swap it and the item at the max slot. - Iterate the proced...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def selection_sort(a_list): """Selection Sort algortihm. Time complexity: O(n^2). """ for max_slot in reversed(range(len(a_list))): select_slot = 0 for slot in range(1, max_slo...
Add to doc string: time complexity
Add to doc string: time complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
f828523180e8996e17ecb36e4a39c67656a372a3
launch_instance.py
launch_instance.py
# License under the MIT License - see LICENSE import boto.ec2 import os import time def launch(key_name=None, region='us-west-2', image_id='ami-5189a661', instance_type='t2.micro', security_groups='launch-wizard-1', user_data=None, initial_check=True): ''' ''' if not isinstance(sec...
# License under the MIT License - see LICENSE import boto.ec2 import os import time def launch(key_name=None, region='us-west-2', image_id='ami-5189a661', instance_type='t2.micro', security_groups='launch-wizard-1', user_data=None, initial_check=True): ''' ''' if not isinstance(sec...
Move status into initial check; fails when instance is stopped already
Move status into initial check; fails when instance is stopped already
Python
mit
Astroua/aws_controller,Astroua/aws_controller
5bf2f25cb309f38bc7a48d76c2018768117a456a
alg_tower_of_hanoi.py
alg_tower_of_hanoi.py
"""The tower of Hanoi.""" from __future__ import print_function def move_towers(height, from_pole, to_pole, with_pole): if height == 1: print('Moving disk from {0} to {1}'.format(from_pole, to_pole)) else: move_towers(height - 1, from_pole, with_pole, to_pole) move_towers(1, from_pole,...
"""The tower of Hanoi.""" from __future__ import absolute_import from __future__ import print_function from __future__ import division def tower_of_hanoi(height, from_pole, to_pole, with_pole, counter): if height == 1: counter[0] += 1 print('{0} -> {1}'.format(from_pole, to_pole)) else: ...
Revise tower of hanoi alg from Yuanlin
Revise tower of hanoi alg from Yuanlin
Python
bsd-2-clause
bowen0701/algorithms_data_structures
5987cfc1485b6dc4cccef2b1e538078b90a9acd1
pythonx/completers/javascript/__init__.py
pythonx/completers/javascript/__init__.py
# -*- coding: utf-8 -*- import json import os.path from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True trigger = r'\w+$|[\w\)\]\}\'\"]+\.\w*$' def format_cmd(self): binary =...
# -*- coding: utf-8 -*- import json import os.path import re from completor import Completor from completor.compat import to_unicode dirname = os.path.dirname(__file__) class Tern(Completor): filetype = 'javascript' daemon = True ident = re.compile(r"""(\w+)|(('|").+)""", re.U) trigger = r"""\w+$|[...
Add support for tern complete_strings plugin
Add support for tern complete_strings plugin
Python
mit
maralla/completor.vim,maralla/completor.vim
88752efa9ac2c0f251733e335763cb880da34741
thinglang/parser/definitions/member_definition.py
thinglang/parser/definitions/member_definition.py
from thinglang.lexer.definitions.tags import LexicalPrivateTag from thinglang.lexer.definitions.thing_definition import LexicalDeclarationMember from thinglang.lexer.values.identifier import Identifier from thinglang.parser.nodes import BaseNode from thinglang.parser.rule import ParserRule from thinglang.symbols.symbol...
from thinglang.lexer.definitions.tags import LexicalPrivateTag from thinglang.lexer.definitions.thing_definition import LexicalDeclarationMember from thinglang.lexer.values.identifier import Identifier from thinglang.parser.nodes import BaseNode from thinglang.parser.rule import ParserRule from thinglang.symbols.symbol...
Add visibility tagging to MethoDefinition
Add visibility tagging to MethoDefinition
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
f4a067acd58aa083680a556bb7d79e9d05403eba
cc/deploy/vendor_wsgi.py
cc/deploy/vendor_wsgi.py
""" Alternative WSGI entry-point that uses requirements/vendor for dependencies. """ import os, sys base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, base_dir) from cc.deploy.paths import add_vendor_lib add_vendor_lib() # Set default settings and instantiate application os....
""" Alternative WSGI entry-point that uses requirements/vendor for dependencies. """ import os, sys base_dir = os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) sys.path.insert(0, base_dir) from cc.deploy.paths import add_vendor_lib add_vendor_lib() # Set default settings and instan...
Fix path addition in vendor-wsgi.py.
Fix path addition in vendor-wsgi.py.
Python
bsd-2-clause
mozilla/moztrap,mozilla/moztrap,mozilla/moztrap,mccarrmb/moztrap,mccarrmb/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mccarrmb/moztrap,shinglyu/moztrap,mccarrmb/moztrap,mozilla/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,mozilla/moztrap,shinglyu/moztrap,bobsilverberg/moztrap,shinglyu/moztrap,bobsilverberg/moztrap...
6d16a7d137b723fe93260eb2729aca1d8f98e37f
actions/cloudbolt_plugins/multi_user_approval/two_user_approval.py
actions/cloudbolt_plugins/multi_user_approval/two_user_approval.py
""" Two User Approval Overrides CloudBolt's standard Order Approval workflow. This Orchestration Action requires two users to approve an order before it becomes Active. Requires CloudBolt 8.8 """ def run(order, *args, **kwargs): # Return the order's status to "PENDING" if fewer than two users have # approve...
""" Two User Approval ~~~~~~~~~~~~~~~~~ Overrides CloudBolt's standard Order Approval workflow. This Orchestration Action requires two users to approve an Order before it becomes Active. Version Req. ~~~~~~~~~~~~ CloudBolt 8.8 """ def run(order, *args, **kwargs): # Return the order's status to "PENDING" if fewe...
Standardize approval Orch Actions docstrings
Standardize approval Orch Actions docstrings [DEV-12140]
Python
apache-2.0
CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge
318c98ab5a9710dfdeedc0ee893e87993ac49727
robosync/test/test_robosync.py
robosync/test/test_robosync.py
import unittest import os import shutil class testMirror(unittest.TestCase): def setUp(self): os.mkdir('test_source') os.mkdir('test_dest') source_dirs = ['dir1', 'dir2', 'dir3'] filenames = ['file1.txt', 'file2.txt', 'file3.txt'] contents = ['foobar1', 'foobar2', 'foobar3'...
import unittest import os import shutil class testMirror(unittest.TestCase): def setUp(self): os.mkdir('test_source') os.mkdir('test_dest') source_dirs = ['dir1', 'dir2', 'dir3'] dest_dirs = ['dir1_c', 'dir2_c', 'dir3_c'] filenames = ['file1.txt', 'file2.txt', 'file3.txt'] ...
Add source and destination list to setup and teardown
Add source and destination list to setup and teardown
Python
mit
rbn920/robosync
7fc0c026508472726d2a47b5ab027b3bcc43f101
calibre_books/core/management/commands/synchronize.py
calibre_books/core/management/commands/synchronize.py
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import NoArgsCommand from django.conf import settings from django_dropbox.storage import DropboxStorage from dropbox.rest import ErrorResponse from calibre_books.calibre.models import Book, Data class Command(NoArgsCommand): ...
from django.core.exceptions import ObjectDoesNotExist from django.core.management.base import NoArgsCommand from django.conf import settings from django_dropbox.storage import DropboxStorage from dropbox.rest import ErrorResponse from calibre_books.calibre.models import Book, Data class Command(NoArgsCommand): ...
Add ability to get calibre db
Add ability to get calibre db
Python
bsd-2-clause
bogdal/calibre-books,bogdal/calibre-books
7183edee23f715d225b7dc506746e3b7a96d7d6b
gmql/dataset/loaders/__init__.py
gmql/dataset/loaders/__init__.py
""" Loader settings: we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the same id_sample based on the hash of the file name """ inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat' keyFormatClas...
import os """ Loader settings: we use the GMQL scala class CombineTextFileWithPathInputFormat in order to load the region and metadata files with the same id_sample based on the hash of the file name """ inputFormatClass = 'it.polimi.genomics.spark.implementation.loaders.Loaders$CombineTextFileWithPathInputFormat' ke...
Use only the base file name for key
Use only the base file name for key Former-commit-id: 3acbf9e93d3d501013e2a1b6aa9631bdcc663c66 [formerly eea949727d3693aa032033d84dcca3790d9072dd] [formerly ca065bc9f78b1416903179418d64b3273d437987] Former-commit-id: 58c1d18e8960ad3236a34b8080b18ccff5684eaa Former-commit-id: 6501068cea164df37ec055c3fb8baf8c89fc7823
Python
apache-2.0
DEIB-GECO/PyGMQL,DEIB-GECO/PyGMQL
a117b191c402ce051b6e8aec2fced315c119b9eb
test/test_large_source_tree.py
test/test_large_source_tree.py
import unittest from yeast_harness import * class TestLargeSourceTree(unittest.TestCase): def test_large_source_tree(self): make_filename = lambda ext='': ''.join( random.choice(string.ascii_lowercase) for _ in range(8)) + ext make_sources = lambda path: [ CSourc...
import unittest from yeast_harness import * class TestLargeSourceTree(unittest.TestCase): def test_large_source_tree(self): make_filename = lambda ext='': ''.join( random.choice(string.ascii_lowercase) for _ in range(8)) + ext make_sources = lambda path: [ CSourc...
Increase size of large source tree 10x
Increase size of large source tree 10x - up to 1000 source files - use parallel make - preserve source tree
Python
mit
sjanhunen/moss,sjanhunen/yeast,sjanhunen/moss,sjanhunen/gnumake-molds
68c7db19c0ac8c159bc12ff9714dea068a7835e4
importlib_resources/__init__.py
importlib_resources/__init__.py
"""Read resources contained within a package.""" import sys __all__ = [ 'Package', 'Resource', 'ResourceReader', 'contents', 'is_resource', 'open_binary', 'open_text', 'path', 'read_binary', 'read_text', ] if sys.version_info >= (3,): from importlib_resources._py3 im...
"""Read resources contained within a package.""" import sys __all__ = [ 'Package', 'Resource', 'ResourceReader', 'contents', 'files', 'is_resource', 'open_binary', 'open_text', 'path', 'read_binary', 'read_text', ] if sys.version_info >= (3,): from importlib_reso...
Add files to the exported names.
Add files to the exported names.
Python
apache-2.0
python/importlib_resources
3ef02d93f9c7e60341ea2d8e407a62d2cadd95f6
mangopaysdk/types/payinexecutiondetailsdirect.py
mangopaysdk/types/payinexecutiondetailsdirect.py
from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails class PayInExecutionDetailsDirect(PayInExecutionDetails): def __init__(self): # direct card self.CardId = None self.SecureModeReturnURL = None self.SecureModeRedirectURL = None # Mode3DSType ...
from mangopaysdk.types.payinexecutiondetails import PayInExecutionDetails class PayInExecutionDetailsDirect(PayInExecutionDetails): def __init__(self): # direct card self.CardId = None self.SecureModeReturnURL = None self.SecureModeRedirectURL = None self.SecureMod...
Add SecureModeNeeded property to PayInExecutionDetailsDirect
Add SecureModeNeeded property to PayInExecutionDetailsDirect
Python
mit
chocopoche/mangopay2-python-sdk,Mangopay/mangopay2-python-sdk
491ce4e51d666fc068e4bed14ab410b90e5b1ea8
extraction/utils.py
extraction/utils.py
import subprocess32 as subprocess import threading import signal def external_process(process_args, input_data='', timeout=None): ''' Pipes input_data via stdin to the process specified by process_args and returns the results Arguments: process_args -- passed directly to subprocess.Popen(), see there f...
import subprocess32 as subprocess import threading import signal import tempfile import os def external_process(process_args, input_data='', timeout=None): ''' Pipes input_data via stdin to the process specified by process_args and returns the results Arguments: process_args -- passed directly to subpr...
Add method to create tempfile with content easily
Add method to create tempfile with content easily
Python
apache-2.0
SeerLabs/extractor-framework,Tiger66639/extractor-framework
59db2a96034955fe678242e63d826610a009a103
indra/tests/test_dart_client.py
indra/tests/test_dart_client.py
import json from indra.literature.dart_client import _jsonify_query_data def test_timestamp(): # Should ignore "after" assert _jsonify_query_data(timestamp={'on': '2020-01-01', 'after': '2020-01-02'}) == \ json.dumps({"timestamp": {"on": "2020-01-01"}}) as...
import json import requests from indra.config import get_config from indra.literature.dart_client import _jsonify_query_data, dart_base_url def test_timestamp(): # Should ignore "after" assert _jsonify_query_data(timestamp={'on': '2020-01-01', 'after': '2020-01-02'}) ...
Add test for reaching API health endpoint
Add test for reaching API health endpoint
Python
bsd-2-clause
sorgerlab/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/belpy,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/indra,sorgerlab/belpy
0e6f62ec8230f85cfb891917be5d7ed144b44979
src/pretty_print.py
src/pretty_print.py
#!/usr/bin/python import argparse import re format = list(''' -- -- ----------- ----------- ---------- -------- ------- -- -- ----------- '''[1:-1]) def setFormatString(index, value): position = -1 for i in range(len(format)): if not format[i].isspace(): position += 1 if position == index: format[i...
#!/usr/bin/python import argparse import ast format = list(''' -- -- ----------- ----------- ---------- -------- ------- -- -- ----------- '''[1:-1]) # Print the given labels using the whitespace of format. def printFormatted(labels): i = 0 for c in format: if c.isspace(): print(c, end='') else: pr...
Clean up python script and make it run in linear time.
Clean up python script and make it run in linear time.
Python
mit
altayhunter/Pentomino-Puzzle-Solver,altayhunter/Pentomino-Puzzle-Solver
941392d41317943f4c0603d7d28a31858a2648bc
neutron/plugins/ml2/drivers/datacom/db/models.py
neutron/plugins/ml2/drivers/datacom/db/models.py
from sqlalchemy import Column, String, ForeignKey from sqlalchemy.orm import relationship, backref from neutron.db.model_base import BASEV2 from neutron.db.models_v2 import HasId class DatacomTenant(BASEV2, HasId): """Datacom Tenant table""" tenant = Column(String(50)) class DatacomNetwork(BASEV2, HasId): ...
from sqlalchemy import Column, String, ForeignKey, Integer from sqlalchemy.orm import relationship, backref from neutron.db.model_base import BASEV2 from neutron.db.models_v2 import HasId class DatacomNetwork(BASEV2, HasId): """Each VLAN represent a Network a network may have multiple ports """ vid = ...
Fix DB to fit new requirements
Fix DB to fit new requirements
Python
apache-2.0
asgard-lab/neutron,asgard-lab/neutron
e6611885dcb1200dec13603b68c5ad03fcae97e4
frasco/redis/ext.py
frasco/redis/ext.py
from frasco.ext import * from redis import StrictRedis from werkzeug.local import LocalProxy from .templating import CacheFragmentExtension class FrascoRedis(Extension): name = "frasco_redis" defaults = {"url": "redis://localhost:6379/0", "fragment_cache_timeout": 3600, "decode...
from frasco.ext import * from redis import Redis from werkzeug.local import LocalProxy from .templating import CacheFragmentExtension class FrascoRedis(Extension): name = "frasco_redis" defaults = {"url": "redis://localhost:6379/0", "fragment_cache_timeout": 3600, "decode_respo...
Set the encoding parameter in Redis constructor
[redis] Set the encoding parameter in Redis constructor
Python
mit
frascoweb/frasco,frascoweb/frasco
903274d3bf87e642430e5b603c924601baa3955a
emission/net/usercache/formatters/android/motion_activity.py
emission/net/usercache/formatters/android/motion_activity.py
import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata ...
import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata ...
Change the motionactivity formatter to match the new version of the google play library
Change the motionactivity formatter to match the new version of the google play library We bumped up the play version number in https://github.com/e-mission/e-mission-data-collection/commit/a93bc993ddcc1e78ab7fc15e6c9a588ce28a5e45 which will change the fields that show up in the android messages. We really need to re...
Python
bsd-3-clause
shankari/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server
92420d319865f2f0dcf0e53a4b4a3fecc30b6aad
components/lie_md/lie_md/gromacs_gromit.py
components/lie_md/lie_md/gromacs_gromit.py
# -*- coding: utf-8 -*- """ file: gromacs_gromit.py Prepaire gromit command line input """ GROMIT_ARG_DICT = { 'forcefield': '-ff', 'charge': '-charge', 'gromacs_lie': '-lie', 'periodic_distance': '-d', 'temperature': '-t', 'prfc': '-prfc', 'ttau': '-ttau', 'salinity': '-conc', 's...
# -*- coding: utf-8 -*- """ file: gromacs_gromit.py Prepaire gromit command line input """ GROMIT_ARG_DICT = { 'forcefield': '-ff', 'charge': '-charge', 'gromacs_lie': '-lie', 'periodic_distance': '-d', 'temperature': '-t', 'prfc': '-prfc', 'ttau': '-ttau', 'salinity': '-conc', 's...
Fix command line argument construction
Fix command line argument construction Boolean values not parsed correctly
Python
apache-2.0
MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio
3245d884845748ef641ae1b39a14a040cf9a97a9
debexpo/tests/functional/test_register.py
debexpo/tests/functional/test_register.py
from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): def test_maintainer_signup(self): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() self.assertEquals(count...
from debexpo.tests import TestController, url from debexpo.model import meta from debexpo.model.users import User class TestRegisterController(TestController): def test_maintainer_signup(self, actually_delete_it=True): count = meta.session.query(User).filter(User.email=='mr_me@example.com').count() ...
Add a test that reproduces the crash if you sign up a second time with the same name
Add a test that reproduces the crash if you sign up a second time with the same name
Python
mit
jonnylamb/debexpo,swvist/Debexpo,jonnylamb/debexpo,swvist/Debexpo,jonnylamb/debexpo,swvist/Debexpo,jadonk/debexpo,jadonk/debexpo,jadonk/debexpo
772cff48318cd745fd2fcadd4c6bdc52629b176d
dp/dirichlet.py
dp/dirichlet.py
# -*- coding: utf-8 -*- from random import betavariate, uniform def weighted_choice(weights): choices = range(len(weights)) total = sum(weights) r = uniform(0, total) upto = 0 for c, w in zip(choices, weights): if upto + w > r: return c upto += w raise Exception("E...
# -*- coding: utf-8 -*- from random import betavariate, uniform def weighted_choice(weights): choices = range(len(weights)) total = sum(weights) r = uniform(0, total) upto = 0 for c, w in zip(choices, weights): if upto + w > r: return c upto += w raise Exception("E...
Raise error on bad alpha value
Raise error on bad alpha value
Python
mit
fivejjs/dirichletprocess,tdhopper/dirichletprocess,fivejjs/dirichletprocess,tdhopper/dirichletprocess
f80b080f62b450531007f58849019fd18c75c25f
stacker/blueprints/rds/postgres.py
stacker/blueprints/rds/postgres.py
from stacker.blueprints.rds import base class PostgresMixin(object): def engine(self): return "postgres" def get_engine_versions(self): return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.4.1'] def get_db_families(self): return ["postgres9.3", "postgres9.4"] class MasterIns...
from stacker.blueprints.rds import base class PostgresMixin(object): def engine(self): return "postgres" def get_engine_versions(self): return ['9.3.1', '9.3.2', '9.3.3', '9.3.5', '9.3.6', '9.3.9', '9.3.10', '9.4.1', '9.4.4', '9.4.5'] def get_db_families(self): re...
Add new versions of Postgres
Add new versions of Postgres
Python
bsd-2-clause
mhahn/stacker,remind101/stacker,mhahn/stacker,remind101/stacker
6860d8a1fabdf7a8b18ad7cd6c687128443f85b5
HARK/tests/test_validators.py
HARK/tests/test_validators.py
import unittest from HARK.validators import non_empty class ValidatorsTests(unittest.TestCase): ''' Tests for validator decorators which validate function arguments ''' def test_non_empty(self): @non_empty('list_a') def foo(list_a, list_b): pass try: f...
import unittest from HARK.validators import non_empty class ValidatorsTests(unittest.TestCase): ''' Tests for validator decorators which validate function arguments ''' def test_non_empty(self): @non_empty('list_a') def foo(list_a, list_b): pass try: f...
Use different assert for Python 2 v 3
Use different assert for Python 2 v 3
Python
apache-2.0
econ-ark/HARK,econ-ark/HARK
35fe55e41a6b1d22cb0ca93651771152cba831ad
wafer/users/migrations/0001_initial.py
wafer/users/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.Create...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.core.validators from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations...
Add validator to initial user migration
Add validator to initial user migration
Python
isc
CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer
e139cb8fc8887f98724eb8670de930230280976f
mclearn/tests/test_experiment.py
mclearn/tests/test_experiment.py
import os import shutil from .datasets import Dataset from mclearn.experiment import ActiveExperiment class TestExperiment: @classmethod def setup_class(cls): cls.data = Dataset('wine') cls.policies = ['passive', 'margin', 'weighted-margin', 'confidence', 'weighted-confi...
import os import shutil from .datasets import Dataset from mclearn.experiment import ActiveExperiment class TestExperiment: @classmethod def setup_class(cls): cls.data = Dataset('wine') cls.policies = ['passive', 'margin', 'w-margin', 'confidence', 'w-confidence', 'entro...
Update policy names in test
Update policy names in test
Python
bsd-3-clause
chengsoonong/mclass-sky,chengsoonong/mclass-sky,alasdairtran/mclearn,alasdairtran/mclearn,chengsoonong/mclass-sky,chengsoonong/mclass-sky,alasdairtran/mclearn,alasdairtran/mclearn
59057c28746220cd0c9d9c78d4fe18b6480e8dda
vertica_python/vertica/messages/backend_messages/empty_query_response.py
vertica_python/vertica/messages/backend_messages/empty_query_response.py
from vertica_python.vertica.messages.message import BackendMessage class EmptyQueryResponse(BackendMessage): pass EmptyQueryResponse._message_id(b'I')
from vertica_python.vertica.messages.message import BackendMessage class EmptyQueryResponse(BackendMessage): def __init__(self, data=None): self.data = data EmptyQueryResponse._message_id(b'I')
Add init for empty query response
Add init for empty query response
Python
apache-2.0
uber/vertica-python
0ca662090e4b10b5fbc10b3d00fb87b861943272
calaccess_website/management/commands/updatedownloadswebsite.py
calaccess_website/management/commands/updatedownloadswebsite.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ import logging from django.core.management import call_command from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand logger = logging.getLogger(__name__) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Update to the latest CAL-ACCESS snapshot and bake static website pages. """ import logging from django.core.management import call_command from calaccess_raw.management.commands.updatecalaccessrawdata import Command as updatecommand logger = logging.getLogger(__name__) ...
Add processcalaccessdata to update routine
Add processcalaccessdata to update routine
Python
mit
california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website
666b011ef95ef6e82e59cc134b52fb29443ff9d8
iroha_cli/crypto.py
iroha_cli/crypto.py
import base64 import sha3 import os from collections import namedtuple class KeyPair: def __init__(self, pub, pri): self.private_key = pri self.public_key = pub from iroha_cli.crypto_ed25519 import generate_keypair_ed25519, sign_ed25519, verify_ed25519, ed25519_sha3_512, \ ed25519_sha3_256...
import base64 import sha3 import os from collections import namedtuple class KeyPair: def __init__(self, pub, pri): self.private_key = pri self.public_key = pub def raw_public_key(self): return base64.b64decode(self.public_key) from iroha_cli.crypto_ed25519 import generate_keypair_...
Add get raw key from KeyPair
Add get raw key from KeyPair
Python
apache-2.0
MizukiSonoko/iroha-cli,MizukiSonoko/iroha-cli
43783e4ff07c9a2ff9f9a11b92515d49e66abcb2
lms/djangoapps/open_ended_grading/controller_query_service.py
lms/djangoapps/open_ended_grading/controller_query_service.py
import json import logging import requests from requests.exceptions import RequestException, ConnectionError, HTTPError import sys from grading_service import GradingService from grading_service import GradingServiceError from django.conf import settings from django.http import HttpResponse, Http404 log = logging.get...
import json import logging import requests from requests.exceptions import RequestException, ConnectionError, HTTPError import sys from grading_service import GradingService from grading_service import GradingServiceError from django.conf import settings from django.http import HttpResponse, Http404 log = logging.get...
Add in an item to check for combined notifications
Add in an item to check for combined notifications
Python
agpl-3.0
apigee/edx-platform,motion2015/edx-platform,fly19890211/edx-platform,angelapper/edx-platform,yokose-ks/edx-platform,itsjeyd/edx-platform,chudaol/edx-platform,dkarakats/edx-platform,dsajkl/123,DNFcode/edx-platform,ferabra/edx-platform,iivic/BoiseStateX,marcore/edx-platform,UXE/local-edx,cyanna/edx-platform,praveen-pal/e...
b11399713d004a95da035ffceed9a1db8b837d11
diffs/__init__.py
diffs/__init__.py
from __future__ import absolute_import, unicode_literals __version__ = '0.1.6' default_app_config = 'diffs.apps.DiffLogConfig' klasses_to_connect = [] def register(cls): """ Decorator function that registers a class to record diffs. @diffs.register class ExampleModel(models.Model): ... ...
from __future__ import absolute_import, unicode_literals __version__ = '0.1.7' default_app_config = 'diffs.apps.DiffLogConfig' klasses_to_connect = [] def register(cls): """ Decorator function that registers a class to record diffs. @diffs.register class ExampleModel(models.Model): ... ...
Update decorator to optionally include DirtyFieldsMixin
Update decorator to optionally include DirtyFieldsMixin Update logic so the class is skipped if it hasattr get_dirty_fields * Release 0.1.7
Python
mit
linuxlewis/django-diffs
260beeaae9daeadb3319b895edc5328504e779b2
cansen.py
cansen.py
#! /usr/bin/python3 print('Test')
#! /usr/bin/python3 import cantera as ct gas = ct.Solution('mech.cti') gas.TPX = 1000,101325,'H2:2,O2:1,N2:3.76' reac = ct.Reactor(gas) netw = ct.ReactorNet([reac]) tend = 10 time = 0 while time < tend: time = netw.step(tend) print(time,reac.T,reac.thermo.P) if reac.T > 1400: break
Create working constant volume reactor test
Create working constant volume reactor test
Python
mit
kyleniemeyer/CanSen,bryanwweber/CanSen
105111b0ed02a7c698ba79f88a54636ec3d5b2a8
madrona/common/management/commands/install_cleangeometry.py
madrona/common/management/commands/install_cleangeometry.py
from django.core.management.base import BaseCommand, AppCommand from django.db import connection, transaction import os class Command(BaseCommand): help = "Installs a cleangeometry function in postgres required for processing incoming geometries." def handle(self, **options): path = os.path.abspath(os...
from django.core.management.base import BaseCommand, AppCommand from django.db import connection, transaction import os class Command(BaseCommand): help = "Installs a cleangeometry function in postgres required for processing incoming geometries." def handle(self, **options): path = os.path.abspath(os...
Use transactions to make sure cleangeometry function sticks
Use transactions to make sure cleangeometry function sticks
Python
bsd-3-clause
Ecotrust/madrona_addons,Ecotrust/madrona_addons
17345dd298860ddfe61f58234d2a38e0a7187d2c
rbm2m/worker.py
rbm2m/worker.py
# -*- coding: utf-8 -*- """ Task entry points """ from sqlalchemy.exc import SQLAlchemyError from action import scanner from helpers import make_config, make_session, make_redis config = make_config() sess = make_session(None, config) redis = make_redis(config) scanner = scanner.Scanner(config, sess, redis) def...
# -*- coding: utf-8 -*- """ Task entry points """ from sqlalchemy.exc import SQLAlchemyError from action import scanner from helpers import make_config, make_session, make_redis config = make_config() sess = make_session(None, config) redis = make_redis(config) scanner = scanner.Scanner(config, sess, redis) def...
Print SQLAlchemy exceptions to stdout and reraise
Print SQLAlchemy exceptions to stdout and reraise
Python
apache-2.0
notapresent/rbm2m,notapresent/rbm2m
f943aa57d6ee462146ff0ab2a091c406d009acce
polyaxon/scheduler/spawners/templates/services/default_env_vars.py
polyaxon/scheduler/spawners/templates/services/default_env_vars.py
from django.conf import settings from scheduler.spawners.templates.env_vars import get_from_app_secret def get_service_env_vars(): return [ get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'), get_from_app_secret('POLYAXON_INTERNAL_SECRET_TOKEN', 'polyaxon-internal-secret-token'), ...
from django.conf import settings from libs.api import API_KEY_NAME, get_settings_api_url from scheduler.spawners.templates.env_vars import get_env_var, get_from_app_secret def get_service_env_vars(): return [ get_from_app_secret('POLYAXON_SECRET_KEY', 'polyaxon-secret'), get_from_app_secret('POLY...
Add api url to default env vars
Add api url to default env vars
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
3ac9c317e266d79e96c20121996a4af4d82776dd
setup.py
setup.py
from distutils.core import setup import winsys if __name__ == '__main__': setup ( name='WinSys', version=winsys.__version__, url='http://svn.timgolden.me.uk/winsys', download_url='http://timgolden.me.uk/python/downloads', license='MIT', author='Tim Golden', auth...
from distutils.core import setup import winsys if __name__ == '__main__': setup ( name='WinSys', version=winsys.__version__, url='http://code.google.com/p/winsys', download_url='http://timgolden.me.uk/python/downloads/winsys', license='MIT', author='Tim Golden', ...
Correct the packaging of packages on winsys
Correct the packaging of packages on winsys modified setup.py
Python
mit
one2pret/winsys,one2pret/winsys
a3770920919f02f9609fe0a48789b70ec548cd3d
setup.py
setup.py
import sys from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [ Extension("nerven.epoc._parse", ["src/nerven/epoc/_parse.pyx"]) ] setup(name='nerven', version='0.1', author='Sharif Olorin', author_email='sio@tesser.org'...
import sys import numpy from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext ext_modules = [ Extension("nerven.epoc._parse", sources=["src/nerven/epoc/_parse.pyx"], include_dirs=[".", numpy.get_include()]), ] setup(name='nerven', ...
Fix the numpy include path used by the Cython extension
Fix the numpy include path used by the Cython extension Apparently this only worked because I had numpy installed system-wide (broke on virtualenv-only installs).
Python
mit
olorin/nerven,fractalcat/nerven,fractalcat/nerven,olorin/nerven
6131430ff7d1e9e8cd95f8d2793e82cc72679d81
auditlog/admin.py
auditlog/admin.py
from django.contrib import admin from .filters import ResourceTypeFilter from .mixins import LogEntryAdminMixin from .models import LogEntry class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin): list_display = ["created", "resource_url", "action", "msg_short", "user_url"] search_fields = [ "time...
from django.contrib import admin from auditlog.filters import ResourceTypeFilter from auditlog.mixins import LogEntryAdminMixin from auditlog.models import LogEntry class LogEntryAdmin(admin.ModelAdmin, LogEntryAdminMixin): list_display = ["created", "resource_url", "action", "msg_short", "user_url"] search_...
Change relative imports to absolute.
Change relative imports to absolute.
Python
mit
jjkester/django-auditlog
649dc183ecce5586483155a9bc3699e73b6c4601
plugins/configuration/preferences/preferences.py
plugins/configuration/preferences/preferences.py
#!/usr/bin/env python #-*- coding: utf-8 -*- #This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software. #The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif...
#!/usr/bin/env python #-*- coding: utf-8 -*- #This software is distributed under the Creative Commons license (CC0) version 1.0. A copy of this license should have been distributed with this software. #The license can also be read online: <https://creativecommons.org/publicdomain/zero/1.0/>. If this online license dif...
Prepare once plug-ins are loaded
Prepare once plug-ins are loaded With the new version of the listen hook.
Python
cc0-1.0
Ghostkeeper/Luna
0c2305db6c6792f624cf09a9134aaa090c82d5c1
tasks.py
tasks.py
from invoke import task import jschema @task def pip(ctx): ctx.run("rm -rf dist jschema.egg-info") ctx.run("./setup.py sdist") ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__)) @task def doc(ctx): ctx.run("./setup.py build_sphinx") ctx.run("./setup.py upload_sphinx")
from invoke import task from invoke.util import cd import jschema @task def pip(ctx): ctx.run("rm -rf dist jschema.egg-info") ctx.run("./setup.py sdist") ctx.run("twine upload dist/jschema-{}.tar.gz".format(jschema.__version__)) @task def doc(ctx): ctx.run("./setup.py build_sphinx") ctx.run("./se...
Add mezzo task, for copy project to mezzo
Add mezzo task, for copy project to mezzo
Python
mit
stepan-perlov/jschema,stepan-perlov/jschema
fa862fdd6be62eb4e79d0dfcef60471aecd46981
rest_framework_push_notifications/tests/test_serializers.py
rest_framework_push_notifications/tests/test_serializers.py
from django.test import TestCase from .. import serializers class TestAPNSDeviceSerializer(TestCase): def test_fields(self): expected = {'url', 'name', 'device_id', 'registration_id', 'active'} fields = serializers.APNSDevice().fields.keys() self.assertEqual(expected, set(fields)) de...
from django.test import TestCase from .. import serializers class TestAPNSDeviceSerializer(TestCase): def test_fields(self): expected = {'url', 'name', 'device_id', 'registration_id', 'active'} fields = serializers.APNSDevice().fields.keys() self.assertEqual(expected, set(fields)) de...
Check for registration_id in serializer errors
Check for registration_id in serializer errors
Python
bsd-2-clause
incuna/rest-framework-push-notifications
4f1c4f75a3576c4bfb3517e6e9168fc8433a5c4b
engine/gobject.py
engine/gobject.py
from .meta import GObjectMeta from . import signals from . import meta @meta.apply class GObject(metaclass=GObjectMeta): # Attributes of the object __attributes__ = () def __init__(self, **kwargs): for key in self.__attributes__: setattr(self, key, kwargs.pop(key)) if kwargs: ...
from .meta import GObjectMeta from . import signals from . import meta @meta.apply class GObject(metaclass=GObjectMeta): # Attributes of the object __attributes__ = () def __init__(self, **kwargs): for key in self.__attributes__: setattr(self, key, kwargs.pop(key)) if kwargs: ...
Add method set to GObject to set attributes
Add method set to GObject to set attributes
Python
bsd-3-clause
entwanne/NAGM
70931f5d0d1b90ce2f7853ffcab94838cab0dab5
api/base/views.py
api/base/views.py
from rest_framework.decorators import api_view from rest_framework.response import Response from .utils import absolute_reverse from api.users.serializers import UserSerializer @api_view(('GET',)) def root(request, format=None): if request.user and not request.user.is_anonymous(): user = request.user ...
from rest_framework.decorators import api_view from rest_framework.response import Response from .utils import absolute_reverse from api.users.serializers import UserSerializer @api_view(('GET',)) def root(request, format=None): if request.user and not request.user.is_anonymous(): user = request.user ...
Add context when calling UserSerializer
Add context when calling UserSerializer
Python
apache-2.0
brianjgeiger/osf.io,rdhyee/osf.io,billyhunt/osf.io,alexschiller/osf.io,samchrisinger/osf.io,acshi/osf.io,sbt9uc/osf.io,brandonPurvis/osf.io,amyshi188/osf.io,chrisseto/osf.io,baylee-d/osf.io,cosenal/osf.io,samchrisinger/osf.io,jnayak1/osf.io,petermalcolm/osf.io,monikagrabowska/osf.io,mfraezz/osf.io,mluo613/osf.io,Merlin...
cdee18e9a937f3dd7e788b92927f35652320e743
api/streams/views.py
api/streams/views.py
from api.streams.models import StreamConfiguration from django.http import JsonResponse from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): stream = StreamConfiguration.objects.get(slug=stream_slug) r = requests.get('http://{stream.host}:{...
from api.streams.models import StreamConfiguration from django.http import JsonResponse, Http404 from django.http.request import HttpRequest import requests def get_stream_status(request: HttpRequest, stream_slug: str): try: stream = StreamConfiguration.objects.get(slug=stream_slug) except StreamConfig...
Improve error handling in stream status view
Improve error handling in stream status view - Check if stream exists and raise a 404 otherwise - Check if upstream returned a success status code and raise a 500 otherwise
Python
mit
urfonline/api,urfonline/api,urfonline/api
583a32cd1e9e77d7648978d20a5b7631a4fe2334
tests/sentry/interfaces/tests.py
tests/sentry/interfaces/tests.py
# -*- coding: utf-8 -*- from __future__ import absolute_import import pickle from sentry.interfaces import Interface from sentry.testutils import TestCase class InterfaceTests(TestCase): def test_init_sets_attrs(self): obj = Interface(foo=1) self.assertEqual(obj.attrs, ['foo']) def test_...
# -*- coding: utf-8 -*- from __future__ import absolute_import import pickle from sentry.interfaces import Interface, Message, Stacktrace from sentry.models import Event from sentry.testutils import TestCase, fixture class InterfaceBase(TestCase): @fixture def event(self): return Event( ...
Improve test coverage on base Interface and Message classes
Improve test coverage on base Interface and Message classes
Python
bsd-3-clause
songyi199111/sentry,JTCunning/sentry,JackDanger/sentry,fotinakis/sentry,JamesMura/sentry,kevinlondon/sentry,mitsuhiko/sentry,felixbuenemann/sentry,fotinakis/sentry,jean/sentry,drcapulet/sentry,ifduyue/sentry,alexm92/sentry,pauloschilling/sentry,fuziontech/sentry,jokey2k/sentry,fotinakis/sentry,argonemyth/sentry,zenefit...
ed2580c14c9e1a0c00fc2df17abb85ab26f86f9f
tools/examples/check-modified.py
tools/examples/check-modified.py
#!/usr/bin/python # # USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ... # # prints out the URL associated with each item # import sys import os import os.path import svn.util import svn.client import svn.wc def usage(): print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n" sys.exit(0) def run(files...
#!/usr/bin/python # # USAGE: check-modified.py FILE_OR_DIR1 FILE_OR_DIR2 ... # # prints out the URL associated with each item # import sys import os import os.path import svn.util import svn.client import svn.wc FORCE_COMPARISON = 0 def usage(): print "Usage: " + sys.argv[0] + " FILE_OR_DIR1 FILE_OR_DIR2\n" sys....
Fix a broken example script.
Fix a broken example script. * check-modified.py (FORCE_COMPARISON): New variable. (run): Add FORCE_COMPARISON arg to call to svn_wc_text_modified_p.
Python
apache-2.0
jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion,jmckaskill/subversion
3ad9029b6bfddb5cef1afed7e0093e8e26fe2884
shcol/config.py
shcol/config.py
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read durin...
# -*- coding: utf-8 -*- # Copyright (c) 2013-2015, Sebastian Linke # Released under the Simplified BSD license # (see LICENSE file for details). """ Constants that are used by `shcol` in many places. This is meant to modified (if needed) only *before* running `shcol`, since most of these constants are only read durin...
Use "utf-8"-encoding if `TERMINAL_STREAM` lacks `encoding`-attribute.
Use "utf-8"-encoding if `TERMINAL_STREAM` lacks `encoding`-attribute.
Python
bsd-2-clause
seblin/shcol
6af05b8af7bb284388af4960bbf240122f7f3dae
plugins/PerObjectSettingsTool/__init__.py
plugins/PerObjectSettingsTool/__init__.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import PerObjectSettingsTool from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": i18n_catalog.i18nc("@label", "Per Object...
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import PerObjectSettingsTool from UM.i18n import i18nCatalog i18n_catalog = i18nCatalog("uranium") def getMetaData(): return { "plugin": { "name": i18n_catalog.i18nc("@label", "Per Object...
Add order to PerObjectSettings tool
Add order to PerObjectSettings tool
Python
agpl-3.0
ynotstartups/Wanhao,hmflash/Cura,fieldOfView/Cura,senttech/Cura,hmflash/Cura,fieldOfView/Cura,Curahelper/Cura,senttech/Cura,Curahelper/Cura,totalretribution/Cura,totalretribution/Cura,ynotstartups/Wanhao
0aa1fb5d7f4eca6423a7d4b5cdd166bf29f48423
ordering/__init__.py
ordering/__init__.py
from fractions import Fraction class Ordering: _start = object() _end = object() def __init__(self): self._labels = { self._start: Fraction(0), self._end: Fraction(1) } self._successors = { self._start: self._end } self._predeces...
from fractions import Fraction from functools import total_ordering class Ordering: _start = object() _end = object() def __init__(self): self._labels = { self._start: Fraction(0), self._end: Fraction(1) } self._successors = { self._start: self....
Add class representing an element in the ordering
Add class representing an element in the ordering
Python
mit
madman-bob/python-order-maintenance
3b61b9dfeda38e0a7afd5ec90b32f8abab18ef4f
unzip.py
unzip.py
#!/usr/bin/env python3 # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: import argparse import os import zipfile parser = argparse.ArgumentParser(description = "Extract zip file includes cp932 encoding file name") parser.add_argument("file") args = parser.parse_args() with zipfile.ZipFile(args.file, 'r...
#!/usr/bin/env python3 # vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: import argparse import os import zipfile parser = argparse.ArgumentParser(description = "Extract zip file includes cp932 encoding file name") parser.add_argument("file") parser.add_argument("-d", "--directory", nargs="?", type=str, ...
Add -d / --directory option
Add -d / --directory option
Python
mit
fujimakishouten/unzip-cp932
4d29aa24b39285c491182edd69ecb7c22a9d643d
ceph_medic/tests/test_main.py
ceph_medic/tests/test_main.py
import pytest import ceph_medic.main class TestMain(object): def test_main(self): assert ceph_medic.main def test_invalid_ssh_config(self, capsys): argv = ["ceph-medic", "--ssh-config", "/does/not/exist"] with pytest.raises(SystemExit): ceph_medic.main.Medic(argv) ...
import pytest import ceph_medic.main from mock import patch class TestMain(object): def test_main(self): assert ceph_medic.main def test_invalid_ssh_config(self, capsys): argv = ["ceph-medic", "--ssh-config", "/does/not/exist"] with pytest.raises(SystemExit): ceph_medic.m...
Fix test breakage when ssh_config missing
tests: Fix test breakage when ssh_config missing I assumed /etc/ssh/ssh_config would be present, but it turns out in a mock chroot environment it isn't. Signed-off-by: Zack Cerza <d7cdf09fc0f0426e98c9978ee42da5d61fa54986@redhat.com>
Python
mit
alfredodeza/ceph-doctor
93acb34d999f89d23d2b613f12c1c767304c2ad6
gor/middleware.py
gor/middleware.py
# coding: utf-8 import os, sys from .base import Gor from tornado import gen, ioloop, queues class TornadoGor(Gor): def __init__(self, *args, **kwargs): super(TornadoGor, self).__init__(*args, **kwargs) self.q = queues.Queue() self.concurrency = kwargs.get('concurrency', 2) @gen.c...
# coding: utf-8 import sys import errno import logging from .base import Gor from tornado import gen, ioloop, queues import contextlib from tornado.stack_context import StackContext @contextlib.contextmanager def die_on_error(): try: yield except Exception: logging.error("exception in asyn...
Exit as soon as KeyboardInterrupt catched
Exit as soon as KeyboardInterrupt catched
Python
mit
amyangfei/GorMW
aaaab0d93723e880119afb52840718634b184054
falcom/logtree.py
falcom/logtree.py
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class MutableTree: value = None def full_length (self): return 0 def walk (self): return iter(()) def __l...
# Copyright (c) 2017 The Regents of the University of Michigan. # All Rights Reserved. Licensed according to the terms of the Revised # BSD License. See LICENSE.txt for details. class MutableTree: def __init__ (self): self.value = None def full_length (self): return 0 def walk (self): ...
Set MutableTree.value on the object only
Set MutableTree.value on the object only
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
918e1c59aa2d0e790eb993e091fd7a327fd12cc4
utils.py
utils.py
import re import textwrap import html2text text_maker = html2text.HTML2Text() text_maker.body_width = 0 def strip_html_tags(text): text = re.sub(r'<a.*?</a>', '', text) return re.sub('<[^<]+?>', '', text) def html_to_md(string, strip_html=True, markdown=False): if not string: return 'No Descri...
import re import textwrap import html2text text_maker = html2text.HTML2Text() text_maker.body_width = 0 def strip_html_tags(text): text = re.sub(r'<a.*?</a>', '', text) return re.sub('<[^<]+?>', '', text) def html_to_md(string, strip_html=True, markdown=False): if not string: return 'No Descri...
Update `get_formatted_book_data` to include page number and year
Update `get_formatted_book_data` to include page number and year
Python
mit
avinassh/Laozi,avinassh/Laozi
7b0bd58c359f5ea21af907cb90234171a6cfca5c
photobox/photobox.py
photobox/photobox.py
from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' cheesepicfolder = '/home/pi/cheesepics/' windowwidth = 1024 windowheight = 768 camera = Gphoto() s...
from cheesefolder import Cheesefolder from photofolder import Photofolder from folder import RealFolder from gphotocamera import Gphoto from main import Photobox from rcswitch import RCSwitch ########## # config # ########## photodirectory = '/var/www/html/' cheesepicpath = '/home/pi/cheesepics/' windowwidth = 1024 wi...
Use the correct chesefolder objects
Use the correct chesefolder objects
Python
mit
MarkusAmshove/Photobox
c3ab90da466e2c4479c9c1865f4302c9c8bdb8e9
tests/extmod/ujson_loads.py
tests/extmod/ujson_loads.py
try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true')) my_print(json.loads('1')) my_print(json.loads('1.2')) my...
try: import ujson as json except: import json def my_print(o): if isinstance(o, dict): print('sorted dict', sorted(o.items())) elif isinstance(o, float): print('%.3f' % o) else: print(o) my_print(json.loads('null')) my_print(json.loads('false')) my_print(json.loads('true'))...
Make printing of floats hopefully more portable.
tests: Make printing of floats hopefully more portable.
Python
mit
dinau/micropython,selste/micropython,danicampora/micropython,turbinenreiter/micropython,tobbad/micropython,SungEun-Steve-Kim/test-mp,SungEun-Steve-Kim/test-mp,turbinenreiter/micropython,matthewelse/micropython,dxxb/micropython,ahotam/micropython,torwag/micropython,swegener/micropython,jmarcelino/pycom-micropython,marti...
6cb6b3d0f9bc3bf8f1662129cd4bd55eec42e6ff
pyqode/python/folding.py
pyqode/python/folding.py
""" Contains the python code folding mode """ from pyqode.core.api import IndentFoldDetector, TextBlockHelper, TextHelper class PythonFoldDetector(IndentFoldDetector): def detect_fold_level(self, prev_block, block): # Python is an indent based language so use indentation for folding # makes sense ...
""" Contains the python code folding mode """ from pyqode.core.api import IndentFoldDetector, TextBlockHelper, TextHelper class PythonFoldDetector(IndentFoldDetector): def detect_fold_level(self, prev_block, block): # Python is an indent based language so use indentation for folding # makes sense ...
Fix bug with end of line comments which prevent detection of new fold level
Fix bug with end of line comments which prevent detection of new fold level
Python
mit
zwadar/pyqode.python,pyQode/pyqode.python,pyQode/pyqode.python,mmolero/pyqode.python
6ffa10ad56acefe3d3178ff140ebe048bb1a1df9
Code/Python/Kamaelia/Kamaelia/Apps/SocialBookmarks/Print.py
Code/Python/Kamaelia/Kamaelia/Apps/SocialBookmarks/Print.py
import sys import os import inspect def __LINE__ (): caller = inspect.stack()[1] return int (caller[2]) def __FUNC__ (): caller = inspect.stack()[1] return caller[3] def __BOTH__(): caller = inspect.stack()[1] return int (caller[2]), caller[3], caller[1] def Print(*args): caller = ...
import sys import os import inspect import time def __LINE__ (): caller = inspect.stack()[1] return int (caller[2]) def __FUNC__ (): caller = inspect.stack()[1] return caller[3] def __BOTH__(): caller = inspect.stack()[1] return int (caller[2]), caller[3], caller[1] def Print(*args): ...
Add in the timestamp for each message, to enable tracking of how long problems take to resolve
Add in the timestamp for each message, to enable tracking of how long problems take to resolve
Python
apache-2.0
sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia
0a7b88df526016672e18608339524cdb527e5928
aspen/__main__.py
aspen/__main__.py
""" python -m aspen =============== Aspen ships with a server (wsgiref.simple_server) that is suitable for development and testing. It can be invoked via: python -m aspen though even for development you'll likely want to specify a project root, so a more likely incantation is: ASPEN_PROJECT_ROOT=/path/to/w...
""" python -m aspen =============== Aspen ships with a server (wsgiref.simple_server) that is suitable for development and testing. It can be invoked via: python -m aspen though even for development you'll likely want to specify a project root, so a more likely incantation is: ASPEN_PROJECT_ROOT=/path/to/w...
Fix ImportError in `python -m aspen`
Fix ImportError in `python -m aspen`
Python
mit
gratipay/aspen.py,gratipay/aspen.py
b7dffc28ebef45293a70561348512d513eaf857c
migrations/versions/19b8969073ab_add_latest_green_build_table.py
migrations/versions/19b8969073ab_add_latest_green_build_table.py
"""add latest green build table Revision ID: 19b8969073ab Revises: 2b7153fe25af Create Date: 2014-07-10 10:53:34.415990 """ # revision identifiers, used by Alembic. revision = '19b8969073ab' down_revision = '2b7153fe25af' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( '...
"""add latest green build table Revision ID: 19b8969073ab Revises: 4d235d421320 Create Date: 2014-07-10 10:53:34.415990 """ # revision identifiers, used by Alembic. revision = '19b8969073ab' down_revision = '4d235d421320' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( '...
Update latest green build migration
Update latest green build migration
Python
apache-2.0
wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,dropbox/changes,dropbox/changes,dropbox/changes
cee76d5c2216f6f42a54b28a753fe288accc40d7
corehq/apps/accounting/migrations/0026_auto_20180508_1956.py
corehq/apps/accounting/migrations/0026_auto_20180508_1956.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-05-08 19:56 from __future__ import unicode_literals from __future__ import absolute_import from django.db import migrations from corehq.sql_db.operations import HqRunPython def noop(*args, **kwargs): pass def _convert_emailed_to_array_field(apps, sc...
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-05-08 19:56 from __future__ import unicode_literals from __future__ import absolute_import from django.db import migrations from corehq.sql_db.operations import HqRunPython def noop(*args, **kwargs): pass def _convert_emailed_to_array_field(apps, sc...
Save record in migrations file
Save record in migrations file
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
f646fb88e793897cf827fd7d9484386a4bb08594
pages/tests/test_serializers.py
pages/tests/test_serializers.py
from mock import patch from django.test import TestCase from rest_framework.reverse import reverse from .. import serializers from . import factories from pages.utils import build_url class PageSerializerTest(TestCase): def expected_data(self, page): expected = { 'id': page.pk, '...
from rest_framework.reverse import reverse from user_management.models.tests.utils import APIRequestTestCase from .. import serializers from . import factories from pages.utils import build_url class PageSerializerTest(APIRequestTestCase): def setUp(self): self.request = self.create_request() sel...
Fix DeprecationWarnings for serializer context
Fix DeprecationWarnings for serializer context * Pass a context containing a request to every serializer Conflicts: pages/tests/test_serializers.py
Python
bsd-2-clause
incuna/feincms-pages-api
419131bba11cab27c36ef2b21199cdc3540cde16
byceps/services/shop/order/actions/revoke_ticket_bundles.py
byceps/services/shop/order/actions/revoke_ticket_bundles.py
""" byceps.services.shop.order.actions.revoke_ticket_bundles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2014-2022 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from .....typing import UserID from ..transfer.action import ActionParameters from ..transfer.ord...
""" byceps.services.shop.order.actions.revoke_ticket_bundles ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :Copyright: 2014-2022 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from .....typing import UserID from ..transfer.action import ActionParameters from ..transfer.ord...
Fix ticket bundle revocation order action
Fix ticket bundle revocation order action
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
83d45c0fa64da347eec6b96f46c5eb1fbfe516d4
plugins/call_bad_permissions.py
plugins/call_bad_permissions.py
# -*- coding:utf-8 -*- # # Copyright 2014 Hewlett-Packard Development Company, L.P. # #    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...
# -*- coding:utf-8 -*- # # Copyright 2014 Hewlett-Packard Development Company, L.P. # #    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...
Fix bug with permissions matching
Fix bug with permissions matching
Python
apache-2.0
chair6/bandit,stackforge/bandit,austin987/bandit,pombredanne/bandit,stackforge/bandit,pombredanne/bandit
99cbd692ae6b7dab65aae9d77fd2d8333fe075e4
Lib/scipy_version.py
Lib/scipy_version.py
major = 0 minor = 3 micro = 3 #release_level = 'alpha' release_level='' from __cvs_version__ import cvs_version cvs_minor = cvs_version[-3] cvs_serial = cvs_version[-1] if release_level: scipy_version = '%(major)d.%(minor)d.%(micro)d_%(release_level)s'\ '_%(cvs_minor)d.%(cvs_serial)d' % (local...
major = 0 minor = 3 micro = 2 #release_level = 'alpha' release_level='' try: from __cvs_version__ import cvs_version cvs_minor = cvs_version[-3] cvs_serial = cvs_version[-1] except ImportError,msg: print msg cvs_minor = 0 cvs_serial = 0 if cvs_minor or cvs_serial: if release_level: ...
Handle missing __cvs_version__.py in a branch.
Handle missing __cvs_version__.py in a branch.
Python
bsd-3-clause
gef756/scipy,aman-iitj/scipy,jakevdp/scipy,efiring/scipy,Eric89GXL/scipy,WarrenWeckesser/scipy,zerothi/scipy,argriffing/scipy,futurulus/scipy,juliantaylor/scipy,tylerjereddy/scipy,fernand/scipy,ndchorley/scipy,fredrikw/scipy,niknow/scipy,nmayorov/scipy,nmayorov/scipy,Gillu13/scipy,WarrenWeckesser/scipy,mdhaber/scipy,wi...
a895661f7ce1a814f308dbe8b5836a4cdb472c8c
cla_public/apps/base/filters.py
cla_public/apps/base/filters.py
import re from cla_public.apps.base import base @base.app_template_filter() def matches(value, pattern): return bool(re.search(pattern, value))
from cla_public.apps.base import base @base.app_template_filter() def test(value): return value
Revert "BE: Update custom template filter"
Revert "BE: Update custom template filter" This reverts commit ea0c0beb1d2aa0d5970b629ac06e6f9b9708bfdd.
Python
mit
ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public
8e4e12b3c9d64a8c6771b9deb7613c3653f47656
rpihelper/transmission/tasks.py
rpihelper/transmission/tasks.py
# -*- coding: utf-8 -*- from rpihelper.celery import current_app, celery from rpihelper.dropboxclient.logic import Client as DropBoxClient from rpihelper.transmission.logic import ( transmissionrpc_client, transmissionrpc_add_torrent, ) __all__ = ( 'check_torrent_files', ) @celery.task def check_torrent_fil...
# -*- coding: utf-8 -*- from tempfile import NamedTemporaryFile from rpihelper.celery import current_app, celery from rpihelper.dropboxclient.logic import Client as DropBoxClient from rpihelper.transmission.logic import ( transmissionrpc_client, transmissionrpc_add_torrent, ) __all__ = ( 'check_torrent_files...
Fix transmission task for torrent files
Fix transmission task for torrent files
Python
mit
Gr1N/rpihelper,Gr1N/rpihelper
f672d140987614c5e4e80114cf28f2f6350be233
pyBattleship.py
pyBattleship.py
import boards def main(): playerDead = False enemyDead = False enemyBoard = boards.makeEnemyBoard() enemyLocations = boards.setupEnemyBoard() playerBoard = boards.makePlayerBoard() print("----BATTLESHIP----") boards.printBoards(enemyBoard, playerBoard) while not playerDea...
import boards def main(): MAX_HITS = 17 enemyDead = False playerDead = False hitsOnEnemy = 0 hitsOnPlayer = 0 turn = 1 enemyBoard = boards.makeEnemyBoard() enemyLocations = boards.setupEnemyBoard() playerBoard = boards.makePlayerBoard() print("----BATTLESHIP----") ...
Add player input evaluation, determines hit/miss
Add player input evaluation, determines hit/miss
Python
apache-2.0
awhittle3/pyBattleship
a365d9a9021b9500475d4f54b7c29cede0064017
pynmea2/types/proprietary/grm.py
pynmea2/types/proprietary/grm.py
# Garmin from ... import nmea class GRM(nmea.ProprietarySentence): sentence_types = {} def __new__(_cls, manufacturer, data): name = manufacturer + data[0] cls = _cls.sentence_types.get(name, _cls) return super(GRM, cls).__new__(cls) class GRME(GRM): """ GARMIN Estim...
# Garmin from ... import nmea class GRM(nmea.ProprietarySentence): sentence_types = {} def __new__(_cls, manufacturer, data): name = manufacturer + data[0] cls = _cls.sentence_types.get(name, _cls) return super(GRM, cls).__new__(cls) def __init__(self, manufacturer, dat...
Add __init__ method to fix parsing
Add __init__ method to fix parsing Ported this init method from ubx.py. This has the effect of removing the sentence sub-type from the data list. Addresses issue #44
Python
mit
silentquasar/pynmea2,Knio/pynmea2
76ca06c26d74aaad1f0773321fdd382b12addcdc
src/django_easyfilters/utils.py
src/django_easyfilters/utils.py
try: from django.db.models.constants import LOOKUP_SEP except ImportError: # Django < 1.5 fallback from django.db.models.sql.constants import LOOKUP_SEP from django.db.models.related import RelatedObject import six def python_2_unicode_compatible(klass): # Copied from Django 1.5 """ A decorator that de...
try: from django.db.models.constants import LOOKUP_SEP except ImportError: # Django < 1.5 fallback from django.db.models.sql.constants import LOOKUP_SEP from django.db.models.related import RelatedObject from six import PY3 def python_2_unicode_compatible(klass): # Copied from Django 1.5 """ A decorat...
Fix error handling in get_model_field (passthrough).
Fix error handling in get_model_field (passthrough).
Python
mit
ionelmc/django-easyfilters,ionelmc/django-easyfilters
b04fcc4a11eec2df0e9b2f8057aff2d073684122
config/experiment_config_lib.py
config/experiment_config_lib.py
import itertools import string class ControllerConfig(object): _port_gen = itertools.count(8888) def __init__(self, cmdline="", address="127.0.0.1", port=None, nom_port=None): ''' Store metadata for the controller. - cmdline is an array of command line tokens. Note: if you need to pass in t...
import itertools import string class ControllerConfig(object): _port_gen = itertools.count(8888) def __init__(self, cmdline="", address="127.0.0.1", port=None): ''' Store metadata for the controller. - cmdline is an array of command line tokens. Note: if you need to pass in the address and ...
Remove nom_port from options. This should be infered by the controller name. Add a name member for that. For now, infer the controller from the commandline string'
Remove nom_port from options. This should be infered by the controller name. Add a name member for that. For now, infer the controller from the commandline string'
Python
apache-2.0
ucb-sts/sts,jmiserez/sts,ucb-sts/sts,jmiserez/sts
6c86f7ef2ba5acdb387d154a618dd0f6bb65af6c
stacker/hooks/route53.py
stacker/hooks/route53.py
import logging logger = logging.getLogger(__name__) from aws_helper.connection import ConnectionManager from stacker.util import create_route53_zone def create_domain(region, namespace, mappings, parameters, **kwargs): conn = ConnectionManager(region) try: domain = parameters['BaseDomain'] exc...
import logging logger = logging.getLogger(__name__) from aws_helper.connection import ConnectionManager from stacker.util import create_route53_zone def create_domain(region, namespace, mappings, parameters, **kwargs): conn = ConnectionManager(region) domain = kwargs.get('domain', parameters.get('BaseDoma...
Allow creation of domains without BaseDomain
Allow creation of domains without BaseDomain Gives the hook the ability to parse args.
Python
bsd-2-clause
mhahn/stacker,mhahn/stacker,federicobaldo/stacker,EnTeQuAk/stacker,remind101/stacker,remind101/stacker
1f1699bb7b8cf537b8d2e206ac0ff03b74d5b3a7
container_files/init/mldb_finish.py
container_files/init/mldb_finish.py
#!/usr/bin/env python # Copyright Datacratic 2016 # Author: Jean Raby <jean@datacratic.com> # This script is called by runsv when the mldb service exits. # See http://smarden.org/runit/runsv.8.html for more details. # Two arguments are given to ./finish: # The first one is ./run's exit code, or -1 if ./run didn't exit...
#!/usr/bin/env python # Copyright Datacratic 2016 # Author: Jean Raby <jean@datacratic.com> # This script is called by runsv when the mldb service exits. # See http://smarden.org/runit/runsv.8.html for more details. # Two arguments are given to ./finish: # The first one is ./run's exit code, or -1 if ./run didn't exit...
Add signal map and human readable description
Add signal map and human readable description
Python
apache-2.0
mldbai/mldb,mldbai/mldb,mldbai/mldb,mldbai/mldb,mldbai/mldb,mldbai/mldb,mldbai/mldb
cec8a1d5afa936ce7df5bae8b7cead9564ac7b97
youmap/views.py
youmap/views.py
from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.order_by('-modified_at')[:100] return { ...
from django.views.generic import TemplateView from chickpea.models import Map class Home(TemplateView): template_name = "youmap/home.html" list_template_name = "chickpea/map_list.html" def get_context_data(self, **kwargs): maps = Map.objects.order_by('-pk')[:100] return { "ma...
Order by modified_at create problem with endless_navigation and browser cache
Order by modified_at create problem with endless_navigation and browser cache Need to handle cache properly before
Python
agpl-3.0
diraol/umap
b6052b35235a09f508aa75012badc830df8bcfa0
sethji/views/sync.py
sethji/views/sync.py
# -*- coding: utf-8 -*- # from sethji.model.sync import SyncAws from sethji.views.account import requires_login from flask import Blueprint, redirect, url_for, flash, request mod = Blueprint('sync', __name__, url_prefix='/sync') @mod.route("/", methods=["POST"]) @requires_login def sync(): sync_aws = SyncAws()...
# -*- coding: utf-8 -*- # from sethji.model.sync import SyncAws from sethji.views.account import requires_login from flask import Blueprint, redirect, url_for, flash mod = Blueprint('sync', __name__, url_prefix='/sync') @mod.route("/", methods=["POST"]) @requires_login def sync(): sync_aws = SyncAws() sync...
Revert "Redirect to same page"
Revert "Redirect to same page" This reverts commit 1f49ee31c21e1bebefb3be9ecc9e4df7c115a5ef.
Python
mit
rohit01/sethji,rohit01/sethji,rohit01/sethji
fa8e30c2b41e8078ca87a73cc90c2652c46b1ee0
corvus/console.py
corvus/console.py
import sys from corvus.client import Corvus def main(): corvus = Corvus() corvus.init_drive() total_sectors = corvus.get_drive_capacity(1) with open("image.bin", "wb") as f: for i in range(total_sectors): orig_data = corvus.read_sector_512(1, i) corvus.write_sector_512(1...
import sys from corvus.client import Corvus def backup(corvus, filename): total_sectors = corvus.get_drive_capacity(1) with open(filename, "wb") as f: for i in range(total_sectors): data = corvus.read_sector_512(1, i) f.write(''.join([ chr(d) for d in data ])) sys.st...
Add backup and restore functions
Add backup and restore functions
Python
bsd-3-clause
mnaberez/corvus
cdcecaad78b8acf1c067c5eb631e6c3ae7167c2c
elasticsearch_dsl/__init__.py
elasticsearch_dsl/__init__.py
from .query import Q from .filter import F from .aggs import A from .function import SF from .search import Search from .field import * from .document import DocType from .mapping import Mapping from .index import Index from .analysis import analyzer, token_filter, char_filter, tokenizer VERSION = (0, 0, 4, 'dev') __v...
from .query import Q from .filter import F from .aggs import A from .function import SF from .search import Search from .field import * from .document import DocType, MetaField from .mapping import Mapping from .index import Index from .analysis import analyzer, token_filter, char_filter, tokenizer VERSION = (0, 0, 4,...
Include MetaField in things importable from root
Include MetaField in things importable from root
Python
apache-2.0
sangheestyle/elasticsearch-dsl-py,3lnc/elasticsearch-dsl-py,elastic/elasticsearch-dsl-py,harshmaur/elasticsearch-dsl-py,solarissmoke/elasticsearch-dsl-py,Quiri/elasticsearch-dsl-py,harshit298/elasticsearch-dsl-py,f-santos/elasticsearch-dsl-py,reflection/elasticsearch-dsl-py,REVLWorld/elasticsearch-dsl-py,ziky90/elastic...
eac383015161f661de33a94dae958a21761071dc
zeus/run.py
zeus/run.py
#!/usr/bin/env python """ run.py makes it easy to start Flask's built-in development webserver. To start a development server, ensure all the necessary packages are installed: (I suggest setting up a Virtualenv for this) $ pip install -r requirements.txt < ... > $ python run.py * Running on http://127.0.0.1:5000/ ...
#!/usr/bin/env python """ run.py makes it easy to start Flask's built-in development webserver. To start a development server, ensure all the necessary packages are installed: (I suggest setting up a Virtualenv for this) $ pip install -r requirements.txt < ... > $ python run.py * Running on http://127.0.0.1:5000/ ...
Move all api routes into /api/
Move all api routes into /api/
Python
bsd-2-clause
nbroeking/OPLabs,jrahm/OPLabs,jrahm/OPLabs,ZachAnders/OPLabs,nbroeking/OPLabs,ZachAnders/OPLabs,ZachAnders/OPLabs,nbroeking/OPLabs,ZachAnders/OPLabs,nbroeking/OPLabs,nbroeking/OPLabs,jrahm/OPLabs,jrahm/OPLabs,ZachAnders/OPLabs,nbroeking/OPLabs,jrahm/OPLabs,jrahm/OPLabs,ZachAnders/OPLabs
b0231d8d8832559a2e5382c3e0ad47e6d6232761
src/oscar/apps/offer/signals.py
src/oscar/apps/offer/signals.py
from django.db.models.signals import post_delete from django.dispatch import receiver from oscar.core.loading import get_model ConditionalOffer = get_model('offer', 'ConditionalOffer') Condition = get_model('offer', 'Condition') Benefit = get_model('offer', 'Benefit') @receiver(post_delete, sender=ConditionalOffer)...
from django.db.models.signals import post_delete from django.dispatch import receiver from oscar.core.loading import get_model ConditionalOffer = get_model('offer', 'ConditionalOffer') Condition = get_model('offer', 'Condition') Benefit = get_model('offer', 'Benefit') @receiver(post_delete, sender=ConditionalOffer)...
Rename offer signal to remove unused conditions/benefits
Rename offer signal to remove unused conditions/benefits
Python
bsd-3-clause
sasha0/django-oscar,sasha0/django-oscar,sasha0/django-oscar,solarissmoke/django-oscar,solarissmoke/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,solarissmoke/django-oscar,sasha0/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,django-oscar/django-oscar,sonofatailor/django-oscar,solari...
dda35a476f81be0deb67c1a45320d17dc927788b
smile_base/models/ir_config_parameter.py
smile_base/models/ir_config_parameter.py
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under th...
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013 Smile (<http://www.smile.fr>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under th...
Allow to override any config parameter via config file
[IMP] Allow to override any config parameter via config file
Python
agpl-3.0
chadyred/odoo_addons,chadyred/odoo_addons,ovnicraft/odoo_addons,bmya/odoo_addons,chadyred/odoo_addons,odoocn/odoo_addons,tiexinliu/odoo_addons,bmya/odoo_addons,odoocn/odoo_addons,ovnicraft/odoo_addons,tiexinliu/odoo_addons,ovnicraft/odoo_addons,odoocn/odoo_addons,tiexinliu/odoo_addons,bmya/odoo_addons
9f3f9229718694570d7b56fe6cd63478f59f0de5
us_ignite/common/tests/utils.py
us_ignite/common/tests/utils.py
from django.core.urlresolvers import reverse from django.contrib.messages.storage.base import BaseStorage, Message def get_login_url(url): """Returns an expected login URL.""" return ('%s?next=%s' % (reverse('auth_login'), url)) class TestMessagesBackend(BaseStorage): """ When unit testing a django ...
from django.contrib.auth.models import User, AnonymousUser from django.core.urlresolvers import reverse from django.contrib.messages.storage.base import BaseStorage, Message from django.test import client from mock import Mock def get_login_url(url): """Returns an expected login URL.""" return ('%s?next=%s'...
Add utilities to generate request doubles.
Add utilities to generate request doubles. The new ``get_request`` function is a helper used to generate request doubles the first argument is the ``method``, an optional user can be attached to the request.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
38221a3d8df945981f9595842871b5dae6a68c0f
user_management/models/tests/factories.py
user_management/models/tests/factories.py
import factory from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): FACTORY_FOR = get_user_model() name = factory.Sequence(lambda i: 'Test User {}'.format(i)) email = factory.Sequence(lambda i: 'email{}@example.com'.format(i)) password = factory.PostGeneration...
import factory from django.contrib.auth import get_user_model class UserFactory(factory.DjangoModelFactory): FACTORY_FOR = get_user_model() name = factory.Sequence(lambda i: 'Test User {}'.format(i)) email = factory.Sequence(lambda i: 'email{}@example.com'.format(i)) is_active = True @factory.po...
Add raw_password to Users in tests
Add raw_password to Users in tests
Python
bsd-2-clause
incuna/django-user-management,incuna/django-user-management
cbaab510c92566ffdcc7eb65af0ec9cf1320f173
recipes/webrtc.py
recipes/webrtc.py
# Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import recipe_util # pylint: disable=F0401 # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=W0232...
# Copyright (c) 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import recipe_util # pylint: disable=F0401 # This class doesn't need an __init__ method, so we disable the warning # pylint: disable=W0232...
Switch WebRTC recipe to Git.
Switch WebRTC recipe to Git. BUG=412012 Review URL: https://codereview.chromium.org/765373002 git-svn-id: bd64dd6fa6f3f0ed0c0666d1018379882b742947@294546 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Python
bsd-3-clause
svn2github/chromium-depot-tools,svn2github/chromium-depot-tools,svn2github/chromium-depot-tools
54ab41cb8c30ddd46154f23e89947286222616e1
raven/__init__.py
raven/__init__.py
""" raven ~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ __all__ = ('VERSION', 'Client', 'load') try: VERSION = __import__('pkg_resources') \ .get_distribution('raven').version except Exception as e: VERSION = 'unknow...
""" raven ~~~~~ :copyright: (c) 2010-2012 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import os import os.path from raven.base import * # NOQA from raven.conf import * # NOQA __all__ = ('VERSION', 'Client', 'load', 'get_version') try: VERSION = __import...
Add git sha to version if available
Add git sha to version if available
Python
bsd-3-clause
getsentry/raven-python,icereval/raven-python,inspirehep/raven-python,inspirehep/raven-python,dbravender/raven-python,hzy/raven-python,getsentry/raven-python,jmagnusson/raven-python,Goldmund-Wyldebeast-Wunderliebe/raven-python,icereval/raven-python,ewdurbin/raven-python,smarkets/raven-python,johansteffner/raven-python,j...
b58caeae59a5ab363b4b6b40cbd19004b40dd206
calvin/actorstore/systemactors/sensor/Distance.py
calvin/actorstore/systemactors/sensor/Distance.py
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 ...
# -*- coding: utf-8 -*- # Copyright (c) 2015 Ericsson AB # # 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 ...
Fix a bug where periodic timers weren't removed when application was stopped. FIXME: Check up on the semantics of will/did_start, will_migrate, did_migrate, will_stop.
Fix a bug where periodic timers weren't removed when application was stopped. FIXME: Check up on the semantics of will/did_start, will_migrate, did_migrate, will_stop.
Python
apache-2.0
EricssonResearch/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base,EricssonResearch/calvin-base
3f88f20a8855dd38ef53b270621d15bf0df4d62c
scavenger/main.py
scavenger/main.py
import logging from time import time, sleep from .net_utils import * logger = logging.getLogger(__name__) def target_scaner(interface, min_interval=30): old_peers = {} while True: begin_time = time() peers = {} for ip, mac in arp_scaner(): peers[ip] = mac if ip...
import logging from time import time, sleep from .net_utils import * logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def target_scaner(interface, min_interval=30): old_peers = {} while True: begin_time = time() peers = {} for ip, mac in arp_scaner(): ...
Set logging level to INFO
Set logging level to INFO
Python
mit
ThomasLee969/scavenger
f48cb4fd946c8fa4b6157b8e1ea9ad8b385bc67a
src/hades/bin/generate_config.py
src/hades/bin/generate_config.py
import os import sys from hades import constants from hades.common.cli import ArgumentParser, parser as common_parser from hades.config.generate import ConfigGenerator from hades.config.loader import load_config def main(): parser = ArgumentParser(parents=[common_parser]) parser.add_argument(dest='source', m...
import logging import os import sys from hades import constants from hades.common.cli import ArgumentParser, parser as common_parser from hades.config.generate import ConfigGenerator from hades.config.loader import load_config logger = logging.getLogger() def main(): parser = ArgumentParser(parents=[common_pars...
Use logger for hades-generate-config error messages
Use logger for hades-generate-config error messages
Python
mit
agdsn/hades,agdsn/hades,agdsn/hades,agdsn/hades,agdsn/hades
295200dba8569a7a667de46a13c6e36ca757f5d5
quickstart/python/understand/example-2/create_joke_intent.6.x.py
quickstart/python/understand/example-2/create_joke_intent.6.x.py
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new intent named ...
# Download the helper library from https://www.twilio.com/docs/python/install from twilio.rest import Client # Your Account Sid and Auth Token from twilio.com/console account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' client = Client(account_sid, auth_token) # Create a new task named 't...
Update console link, intent-->task in comments
Update console link, intent-->task in comments
Python
mit
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
e7962ec34a86fe464862ab81ec8cc8da14a732f6
models/weather.py
models/weather.py
from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'o...
from configparser import ConfigParser from googletrans import Translator import pyowm import logging import re logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO) logger = logging.getLogger(__name__) cfg = ConfigParser() cfg.read('config') api_key = cfg.get('auth', 'o...
Add Info to Weather Check
Add Info to Weather Check Add current weather status to weather check features.
Python
mit
iGene/igene_bot
6cdb6ada40f28ecc7629ecdb5dd67c06f6013e88
router_monitor.py
router_monitor.py
import schedule, time, os, sys, urllib2, base64 from datetime import datetime def check_connection(): sys.stdout.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " Connection") hostname = "google.com" response = os.system("ping -c 1 " + hostname + " > /dev/null") if response == 0: print " is up" else: prin...
# python -u router_monitor.py >> router_log.txt 2>&1 & import schedule, time, os, sys, urllib2, base64 from datetime import datetime def check_connection(): sys.stdout.write(datetime.now().strftime("%Y-%m-%d %H:%M:%S") + " Connection") hostname = "google.com" response = os.system("ping -c 1 " + hostname + " > /dev/n...
Add usage comment and remove python version
Add usage comment and remove python version
Python
mit
danic85/router_monitor
779639680e02fb4de920a95558eceecc2a55ab46
indra/bel/ndex_client.py
indra/bel/ndex_client.py
import requests import json import time #ndex_base_url = 'http://services.bigmech.ndexbio.org' ndex_base_url = 'http://52.37.175.128' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_result(re...
import requests import json import time ndex_base_url = 'http://general.bigmech.ndexbio.org:8082' #ndex_base_url = 'http://52.37.175.128' def send_request(url_suffix, params): res = requests.post(ndex_base_url + url_suffix, data=json.dumps(params)) res_json = get_result(res) return res_json def get_resul...
Add new URL for NDEx service
Add new URL for NDEx service
Python
bsd-2-clause
jmuhlich/indra,johnbachman/belpy,sorgerlab/indra,jmuhlich/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,pvtodorov/indra,jmuhlich/ind...
a2005d98cd81424a2a43277cae0595806751e9dc
swh/web/ui/controller/service.py
swh/web/ui/controller/service.py
# Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from swh.web.ui.back import http, api_query from swh.core.json import SW...
# Copyright (C) 2015 The Software Heritage developers # See the AUTHORS file at the top-level directory of this distribution # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information from swh.web.ui.back import http, api_query from swh.core.json import SW...
Refactor - Simplify the call to api
Refactor - Simplify the call to api
Python
agpl-3.0
SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui
c20fd19d10a77cda0c16fd5a4fa329a43933751f
src/commoner/profiles/models.py
src/commoner/profiles/models.py
from django.db import models from django.db.models import permalink from django.contrib.auth.models import User class Content(models.Model): commoner = models.ForeignKey(User) title = models.CharField(max_length=255, blank=True) url = models.URLField(max_length=255, blank=False) def __unicode__(self...
import urlparse from django.db import models from django.db.models import permalink from django.core.urlresolvers import reverse from django.contrib.auth.models import User from commoner.util import getBaseURL class Content(models.Model): commoner = models.ForeignKey(User) title = models.CharField(max_leng...
Support generating a completely absolute URL for the profile; added a display_name method to the Profile model.
Support generating a completely absolute URL for the profile; added a display_name method to the Profile model.
Python
agpl-3.0
cc-archive/commoner,cc-archive/commoner