commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
3082fb50c028979643d479c0e65cb92ef12de586
hunter/udacity.py
hunter/udacity.py
import requests import os class UnauthorizedToken(Exception): pass class UdacityConnection: def __init__(self): self.certifications_url = 'https://review-api.udacity.com/api/v1/me/certifications.json' token = os.environ.get('UDACITY_AUTH_TOKEN') self.headers = {'Authorization': toke...
import requests import os class UnauthorizedToken(Exception): pass class UdacityConnection: def __init__(self): self.certifications_url = 'https://review-api.udacity.com/api/v1/me/certifications.json' token = os.environ.get('UDACITY_AUTH_TOKEN') self.headers = {'Authorization': toke...
Add request to inside of try
Add request to inside of try
Python
mit
anapaulagomes/reviews-assigner
--- +++ @@ -14,8 +14,8 @@ self.headers = {'Authorization': token, 'Content-Length': '0'} def certifications(self): - raw_response = requests.get(self.certifications_url, headers=self.headers) try: + raw_response = requests.get(self.certifications_url, headers=self.headers) ...
047f061514740d7935cce8e2aa25ef138b93f91f
deployer/__init__.py
deployer/__init__.py
from __future__ import absolute_import import deployer.logger from celery.signals import setup_logging __version__ = '0.3.11' __author__ = 'sukrit' deployer.logger.init_logging() setup_logging.connect(deployer.logger.init_celery_logging)
from __future__ import absolute_import import deployer.logger from celery.signals import setup_logging __version__ = '0.4.0' __author__ = 'sukrit' deployer.logger.init_logging() setup_logging.connect(deployer.logger.init_celery_logging)
Prepare for next development version
Prepare for next development version
Python
mit
totem/cluster-deployer,totem/cluster-deployer,totem/cluster-deployer
--- +++ @@ -3,7 +3,7 @@ from celery.signals import setup_logging -__version__ = '0.3.11' +__version__ = '0.4.0' __author__ = 'sukrit' deployer.logger.init_logging()
3e37885f7241b985740bf753ca237c31497ac57e
courriers/management/commands/mailjet_sync_unsubscribed.py
courriers/management/commands/mailjet_sync_unsubscribed.py
from django.core.management.base import BaseCommand from django.db import DEFAULT_DB_ALIAS from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--connection', action='store', dest='connection', ...
from django.core.management.base import BaseCommand from django.db import DEFAULT_DB_ALIAS from optparse import make_option class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option('--connection', action='store', dest='connection', ...
Use list comprehension for mailjet_users list
Use list comprehension for mailjet_users list
Python
mit
ulule/django-courriers,ulule/django-courriers
--- +++ @@ -31,9 +31,7 @@ mailjet_contacts = backend.mailjet_api.contact.list() - mailjet_users = [] - for contact in mailjet_contacts['result']: - mailjet_users.append(contact['email']) + mailjet_users = [contact['email'] for contact in mailjet_contacts['result']] ...
fa089cabcc3b3aa71bcc86e028066e3dbcf25d5d
commands/cmd_help.py
commands/cmd_help.py
from lib.command import Command class HelpCommand(Command): name = 'help' aliases = ['start'] description = 'Lists all bot commands and their descriptions.' def run(self, message, args): reply = 'Hi! I\'m {0} and these are my commands: \n\n'.format(self.bot.telegram.get_me().username) ...
from lib.command import Command class HelpCommand(Command): name = 'help' aliases = ['start'] description = 'Lists all bot commands and their descriptions.' def run(self, message, args): reply = 'Hi! I\'m {0} and these are my commands: \n\n'.format(self.bot.telegram.get_me().username) ...
Add slash to all command aliases
Add slash to all command aliases
Python
agpl-3.0
TheReverend403/Pyper,TheReverend403/Pyper
--- +++ @@ -11,7 +11,7 @@ for command in self.bot.commands.values(): reply += '/{0} - {1}'.format(command.name, command.description) if hasattr(command, 'aliases'): - reply += ' (Aliases: /{0})'.format(', '.join(command.aliases)) + reply += ' (Aliases: ...
ce3028f29e40ce72693394798ca0a8daa98c1a4a
data/make_hash_dict.py
data/make_hash_dict.py
import data, json, os, sys def make_hash_dict(top): """ Returns a dictionary with file paths and corresponding hashes. Parameters ---------- data : str The path to the directory containing files needing hashes. Returns ------- hash_dict : dict Dictionary with file ...
import data, json, os, sys def make_hash_dict(top): """ Returns a dictionary with file paths and corresponding hashes. Parameters ---------- data : str The path to the directory containing files needing hashes. Returns ------- hash_dict : dict Dictionary with file ...
Make JSON containing paths and hashs
WIP: Make JSON containing paths and hashs
Python
bsd-3-clause
berkeley-stat159/project-delta
--- +++ @@ -18,3 +18,8 @@ # generate_file_md5() takes as input a file path and outputs its hash hash_dict = [data.generate_file_md5(path) for path in paths] return hash_dict + +if __name__ == "__main__": + hash_dict = make_hash_dict("ds005") + with open("ds005_hashes.json", "x", newline = "\n") a...
8660d5570144894cf4e6e07b3a30526b35575dce
test/Analysis/analyzer_test.py
test/Analysis/analyzer_test.py
import lit.formats import lit.TestRunner # Custom format class for static analyzer tests class AnalyzerTest(lit.formats.ShTest): def execute(self, test, litConfig): result = self.executeWithAnalyzeSubstitution( test, litConfig, '-analyzer-constraints=range') if result.code == lit.Test...
import lit.formats import lit.TestRunner # Custom format class for static analyzer tests class AnalyzerTest(lit.formats.ShTest): def execute(self, test, litConfig): results = [] # Parse any test requirements ('REQUIRES: ') saved_test = test lit.TestRunner.parseIntegratedTestScript...
Improve test handling with multiple constraint managers
[analyzer]: Improve test handling with multiple constraint managers Summary: Modify the test infrastructure to properly handle tests that require z3, and merge together the output of all tests on success. This is required for D28954. Reviewers: dcoughlin, zaks.anna, NoQ, xazax.hun Subscribers: cfe-commits Different...
Python
apache-2.0
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-cl...
--- +++ @@ -5,24 +5,39 @@ class AnalyzerTest(lit.formats.ShTest): def execute(self, test, litConfig): - result = self.executeWithAnalyzeSubstitution( - test, litConfig, '-analyzer-constraints=range') + results = [] - if result.code == lit.Test.FAIL: - return result...
ab1ea39c020e39bdc7b739e2ab49b1cacbecd081
detectem/ws.py
detectem/ws.py
import sys import json from detectem.exceptions import SplashError, NoPluginsError try: from bottle import run, post, request except ImportError: print("Install bottle to use the web service ..") sys.exit(0) from detectem.cli import get_detection_results @post('/detect') def do_detection(): url = ...
import sys import json try: import bottle from bottle import run, post, request except ImportError: print('[+] Install bottle to use the web service') sys.exit(0) from detectem.exceptions import SplashError, NoPluginsError from detectem.cli import get_detection_results from detectem.settings import DE...
Add debug mode to webservice
Add debug mode to webservice Add main function to avoid executing the webserver in tests Reorder imports
Python
mit
spectresearch/detectem
--- +++ @@ -1,16 +1,16 @@ import sys import json -from detectem.exceptions import SplashError, NoPluginsError - try: + import bottle from bottle import run, post, request except ImportError: - print("Install bottle to use the web service ..") + print('[+] Install bottle to use the web service') ...
7266d78fa491acc5d2000bdf14cb8bc8dbc8c7f4
test/testfunctions/__init__.py
test/testfunctions/__init__.py
# -*- coding: utf-8 -*- # __all__ = [ 'annotate', 'basic_sin', 'circle_patch', 'dual_axis', 'errorband', 'errorbar', 'fancybox', 'heat', 'image_plot', 'legends2', 'legends', 'loglogplot', 'logplot', 'noise', 'noise2', 'patches', 'scatter', 'subplots', 'subplot4x4', 'text_overlay'...
# -*- coding: utf-8 -*- # __all__ = [ 'annotate', 'basic_sin', 'circle_patch', 'dual_axis', 'errorband', 'errorbar', 'fancybox', 'heat', 'image_plot', 'legends2', 'legends', 'loglogplot', 'logplot', 'marker', 'noise', 'noise2', 'patches', 'scatter', 'subplots', 'subplot4x4', 't...
Add 'marker' to the list of tests to be run
Add 'marker' to the list of tests to be run
Python
mit
nschloe/matplotlib2tikz,danielhkl/matplotlib2tikz,m-rossi/matplotlib2tikz,dougnd/matplotlib2tikz
--- +++ @@ -14,6 +14,7 @@ 'legends', 'loglogplot', 'logplot', + 'marker', 'noise', 'noise2', 'patches',
53025df032e1b9296713f3d8f7866e9936ed1af7
qsimcirq/_version.py
qsimcirq/_version.py
"""The version number defined here is read automatically in setup.py.""" __version__ = "0.12.1"
"""The version number defined here is read automatically in setup.py.""" __version__ = "0.12.2.dev20220422"
Update to dev version 2022-04-22
Update to dev version 2022-04-22
Python
apache-2.0
quantumlib/qsim,quantumlib/qsim,quantumlib/qsim,quantumlib/qsim
--- +++ @@ -1,3 +1,3 @@ """The version number defined here is read automatically in setup.py.""" -__version__ = "0.12.1" +__version__ = "0.12.2.dev20220422"
3f65b43bce12739af8bb3dfc451a7f58a6af12b1
dbaas/api/environment.py
dbaas/api/environment.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers from physical import models class EnvironmentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Environment fields = ('url', 'id', 'name',)...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers from physical.models import Environment class EnvironmentSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Environment fields = ('url', 'id', 'na...
Add povisioner and stage on env API
Add povisioner and stage on env API
Python
bsd-3-clause
globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service
--- +++ @@ -1,14 +1,14 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from rest_framework import viewsets, serializers -from physical import models +from physical.models import Environment class EnvironmentSerializer(serializers.HyperlinkedModelSerializer): class Me...
c897942c8b1c3d9283ea6453bcc6616ca3d5108e
builds/python3.6_ci/src/lint_turtle_files.py
builds/python3.6_ci/src/lint_turtle_files.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ This script takes the path to a directory, and looks for any Turtle files (https://www.w3.org/TeamSubmission/turtle/), then uses RDFLib to check if they're valid TTL. It exits with code 0 if all files are valid, 1 if not. """ print("Hello, I am turtle linter")
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ This script takes the path to a directory, and looks for any Turtle files (https://www.w3.org/TeamSubmission/turtle/), then uses RDFLib to check if they're valid TTL. It exits with code 0 if all files are valid, 1 if not. """ import logging import os import daiquir...
Write a proper Turtle linter
Write a proper Turtle linter
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
--- +++ @@ -8,4 +8,52 @@ It exits with code 0 if all files are valid, 1 if not. """ -print("Hello, I am turtle linter") +import logging +import os + +import daiquiri +import rdflib + +daiquiri.setup(level=logging.INFO) + +logger = daiquiri.getLogger(__name__) + +# This is a slightly cheaty way of tracking which p...
62f028d61b9d5669bc05c2bbe5ce5f4e0d4401cc
src/vimapt/library/vimapt/RemoteRepo.py
src/vimapt/library/vimapt/RemoteRepo.py
#!/usr/bin/env python import os from .data_format import dumps class RemoteRepo(object): def __init__(self, repo_dir): self.repo_dir = repo_dir # initial setup pool_relative_dir = "pool" package_relative_path = "index/package" self.pool_absolute_dir = os.path.join(self.r...
#!/usr/bin/env python import os from .data_format import dumps class RemoteRepo(object): def __init__(self, repo_dir): self.repo_dir = repo_dir # initial setup pool_relative_dir = "pool" package_relative_path = "index/package" self.pool_absolute_dir = os.path.join(self.r...
Fix bug when parse version info
Fix bug when parse version info
Python
mit
howl-anderson/vimapt,howl-anderson/vimapt
--- +++ @@ -27,7 +27,10 @@ if os.path.isfile(os.path.join(self.pool_absolute_dir, f))] package_data = {} for file_name in files: - package_name, version_and_ext = file_name.split('_', 1) + pkg_name_segments = file_name.split("_") + package_name = '_...
726c4f14fd5ddd49024163182917aeb9f4af504d
src/wirecloud/core/catalogue_manager.py
src/wirecloud/core/catalogue_manager.py
# -*- coding: utf-8 -*- # Copyright 2012 Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #...
# -*- coding: utf-8 -*- # Copyright 2012 Universidad Politécnica de Madrid # This file is part of Wirecloud. # Wirecloud is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or #...
Make published mashups visibles to all users
Make published mashups visibles to all users
Python
agpl-3.0
jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud
--- +++ @@ -32,4 +32,5 @@ template = TemplateParser(build_template_from_workspace(publish_options, published_workspace.workspace, user)) resource = add_resource_from_template(published_workspace.get_template_url(request), template, user) - resource.users.add(user) + resource.publish ...
32cd8227260f5c2fedc50b9b817ee27df2398a82
Server/Code/database/model.py
Server/Code/database/model.py
from config import PASSWORD_LENGTH from sqlalchemy import BigInteger, Column, ForeignKey, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(BigInteger, primary_key=True, autoincrement=True) password = Column(Stri...
from config import PASSWORD_LENGTH from sqlalchemy import BigInteger, Column, ForeignKey, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): __tablename__ = 'user' id = Column(BigInteger, primary_key=True, autoincrement=True) password = Column(Stri...
Update user, fight foreign key dependency
Update user, fight foreign key dependency
Python
mit
HueyPark/Unreal-Knights,HueyPark/Unreal-Knights,HueyPark/Unreal-Knights,HueyPark/Unreal-Knights
--- +++ @@ -10,7 +10,6 @@ id = Column(BigInteger, primary_key=True, autoincrement=True) password = Column(String(PASSWORD_LENGTH)) - fight_id = Column(BigInteger, ForeignKey('fight.id')) def __init__(self, password: str): self.password = password @@ -20,7 +19,7 @@ __tablename__ = '...
6854f889e38f565acb80c52a74df09730e0f7e45
uitools/notifications/linux.py
uitools/notifications/linux.py
from gi.repository import GLib, Notify as LibNotify class Notification(object): def __init__(self, title, message, subtitle=None, sticky=False): self.title = title self.subtitle = subtitle self.message = message self.sticky = sticky self._sent = False def send(self):...
from gi.repository import GLib, Notify as LibNotify DEV = False class Notification(object): def __init__(self, title, message, subtitle=None, sticky=False): self.title = title self.subtitle = subtitle self.message = message self.sticky = sticky self._sent = False de...
Clean up for production Linux use
Clean up for production Linux use
Python
bsd-3-clause
westernx/uitools
--- +++ @@ -1,6 +1,8 @@ from gi.repository import GLib, Notify as LibNotify + +DEV = False class Notification(object): @@ -16,20 +18,22 @@ # see: https://developer.gnome.org/libnotify/0.7/libnotify-notify.html # see: https://developer.gnome.org/libnotify/0.7/NotifyNotification.html - ...
3f9d79d50890f8605c7dfbaf5147b6f099b063b4
Machine/admin.py
Machine/admin.py
from django.contrib import admin from django.db import models from Machine import models as mmod class ContactInLine(admin.TabularInline): model = mmod.Contact max_num = 2 class StatusAdmin(admin.ModelAdmin): list_display = ('name', 'description') fieldsets = ( (None, {'fields': ('name', ...
from django.contrib import admin from django.db import models from Machine import models as mmod class ContactInLine(admin.TabularInline): model = mmod.Contact max_num = 2 class StatusAdmin(admin.ModelAdmin): list_display = ('name', 'description') fieldsets = ( (None, {'fields': ('name', ...
Change the third item of the search_field from 'mac' to 'mac1'
Change the third item of the search_field from 'mac' to 'mac1'
Python
apache-2.0
abztrakt/labtracker,abztrakt/labtracker,abztrakt/labtracker
--- +++ @@ -16,7 +16,7 @@ class ItemAdmin(admin.ModelAdmin): list_display = ('name', 'type','location','ip','mac1','mac2', 'wall_port','date_added','manu_tag','uw_tag') - search_fields = ['name','ip','mac','wall_port'] + search_fields = ['name','ip','mac1','wall_port'] list_filter = ['ty...
513aa1bd78d4f2d592ad5f34835331e315a5af77
dyngraph/__init__.py
dyngraph/__init__.py
__all__ = ['algorithms', 'dialogs', 'exporter', 'legend', 'mainui', 'puplot', 'tsplot', 'utils']
__all__ = ['algorithms', 'dialogs', 'exporter', 'legend', 'mainui', 'puplot', 'tsplot', 'utils', 'ui']
Add ui module to path
Add ui module to path
Python
isc
jaj42/dyngraph,jaj42/GraPhysio,jaj42/GraPhysio
--- +++ @@ -1 +1 @@ -__all__ = ['algorithms', 'dialogs', 'exporter', 'legend', 'mainui', 'puplot', 'tsplot', 'utils'] +__all__ = ['algorithms', 'dialogs', 'exporter', 'legend', 'mainui', 'puplot', 'tsplot', 'utils', 'ui']
76df79075d0fdfb310a99f0805ccae253d439ee2
game/player.py
game/player.py
#!/usr/bin/env python from abc import ABCMeta, abstractmethod from game.gameboard import GameBoard class Player(object): __metaclass__ = ABCMeta def __init__(self, color): self._color = color.lower() def color(self): return self._color def is_winner(self, board): if board.gam...
#!/usr/bin/env python from abc import ABCMeta, abstractmethod from game.gameboard import GameBoard class Player(object): __metaclass__ = ABCMeta def __init__(self, color): self._color = color.lower() def color(self): return self._color def is_winner(self, board): return board...
Replace the particular boolean returns with a boolean expression on is_winner
Replace the particular boolean returns with a boolean expression on is_winner
Python
apache-2.0
apojomovsky/cuatro_en_linea,apojomovsky/cuatro_en_linea
--- +++ @@ -12,9 +12,7 @@ return self._color def is_winner(self, board): - if board.game_over() and board.winner_color() == self._color: - return True - return False + return board.game_over() and board.winner_color() == self._color @abstractmethod def play(...
425152f3c65b6c58065cde9ccbcebd360289ec8c
files_and_folders.py
files_and_folders.py
import os def files_and_folders(dir_path='.'): files = [] folders = [] for filename in sorted(os.listdir(dir_path)): if os.path.isdir(os.path.join(dir_path, filename)): folders.append(filename) else: files.append(filename) return tuple(files), tuple(folders)
import os # improvement liberally borrowed from: # https://forum.omz-software.com/topic/2784/feature-request-pythonista-built-in-file-picker def files_and_folders(dir_path='.'): '''Return a dict containing a sorted tuple of files and a sorted tuple of folders''' f_and_f = os.listdir(dir_path) folders...
Cut number of lines in half
Cut number of lines in half @The-Penultimate-Defenestrator use of sets is a nice optimization! # improvement liberally borrowed from: # https://forum.omz-software.com/topic/2784/feature-request-pythonista-built-in-file-picker
Python
apache-2.0
cclauss/Ten-lines-or-less
--- +++ @@ -1,5 +1,19 @@ import os + +# improvement liberally borrowed from: +# https://forum.omz-software.com/topic/2784/feature-request-pythonista-built-in-file-picker + + def files_and_folders(dir_path='.'): + '''Return a dict containing a sorted tuple of files and a sorted + tuple of folders''' + f_and...
a1fdc8e14377d4fe619550e12ea359e5e9c60f0e
dear_astrid/test/helpers.py
dear_astrid/test/helpers.py
import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*...
import datetime import os import sys import time from dear_astrid.constants import * from dear_astrid.constants import __all__ as _constants_all from dear_astrid.tzinfo import * from dear_astrid.tzinfo import __all__ as _tzinfo_all __all__ = [ 'dtu', 'u', 'timezone', ] + _constants_all + _tzinfo_all def dtu(*...
Simplify py 2/3 unicode string helper
Simplify py 2/3 unicode string helper
Python
mit
rwstauner/dear_astrid,rwstauner/dear_astrid
--- +++ @@ -41,14 +41,9 @@ def __exit__(self, *args): self.set_env(self.orig) -PY3 = False -try: - PY3 = (sys.version_info.major == 3) -except: - pass +PY3 = sys.version_info >= (3,) -if PY3: - def u(string): - return string -else: - exec("def u(string):\n return string + u''\n") +def u(string): +...
9c0f06228254a41bd68062feafaf8c8dbaddd06b
marshmallow/base.py
marshmallow/base.py
# -*- coding: utf-8 -*- '''Abstract base classes. These are necessary to avoid circular imports between core.py and fields.py. ''' class FieldABC(object): '''Abstract base class from which all Field classes inherit. ''' parent = None name = None def format(self, value): raise NotImplemen...
# -*- coding: utf-8 -*- '''Abstract base classes. These are necessary to avoid circular imports between core.py and fields.py. ''' import copy class FieldABC(object): '''Abstract base class from which all Field classes inherit. ''' parent = None name = None def format(self, value): raise...
Speed up deep copy of fields
Speed up deep copy of fields
Python
mit
dwieeb/marshmallow,VladimirPal/marshmallow,bartaelterman/marshmallow,mwstobo/marshmallow,maximkulkin/marshmallow,Tim-Erwin/marshmallow,jmcarp/marshmallow,0xDCA/marshmallow,daniloakamine/marshmallow,marshmallow-code/marshmallow,xLegoz/marshmallow,Bachmann1234/marshmallow,jmcarp/marshmallow,0xDCA/marshmallow,etataurov/ma...
--- +++ @@ -3,6 +3,7 @@ These are necessary to avoid circular imports between core.py and fields.py. ''' +import copy class FieldABC(object): @@ -16,6 +17,10 @@ def output(self, key, obj): raise NotImplementedError + + def __deepcopy__(self, memo): + ret = copy.copy(self) + r...
50c734268a1380379d8d326a0860b2a9f2fade23
restpose/__init__.py
restpose/__init__.py
# -*- coding: utf-8 - # # This file is part of the restpose python module, released under the MIT # license. See the COPYING file for more information. """Python client for the RestPose search server. """ from .client import Server from .version import dev_release, version_info, __version__ from restkit import Reso...
# -*- coding: utf-8 - # # This file is part of the restpose python module, released under the MIT # license. See the COPYING file for more information. """Python client for the RestPose search server. """ from .client import Server from .errors import RestPoseError, CheckPointExpiredError from .version import dev_re...
Add RestPoseError and CheckPointExpiredError to top-level module symbols
Add RestPoseError and CheckPointExpiredError to top-level module symbols
Python
mit
restpose/restpose-py,restpose/restpose-py
--- +++ @@ -7,6 +7,7 @@ """ from .client import Server +from .errors import RestPoseError, CheckPointExpiredError from .version import dev_release, version_info, __version__ from restkit import ResourceNotFound, Unauthorized, RequestFailed, \
f41ff2e0a2eee56dd090e729b4470923958444b9
conditional/util/flask.py
conditional/util/flask.py
from flask import render_template as flask_render_template from db.models import EvalSettings from util.ldap import ldap_is_active from util.ldap import ldap_is_alumni from util.ldap import ldap_is_eboard from util.ldap import ldap_is_financial_director from util.ldap import ldap_is_eval_director from util.ldap import...
from flask import render_template as flask_render_template from db.models import EvalSettings from util.ldap import ldap_is_active from util.ldap import ldap_is_alumni from util.ldap import ldap_is_eboard from util.ldap import ldap_is_financial_director from util.ldap import ldap_is_eval_director from util.ldap import...
Fix template var exports for directors
Fix template var exports for directors
Python
mit
ComputerScienceHouse/conditional,RamZallan/conditional,ComputerScienceHouse/conditional,RamZallan/conditional,RamZallan/conditional,ComputerScienceHouse/conditional
--- +++ @@ -33,7 +33,7 @@ is_active=is_active, is_alumni=is_alumni, is_eboard=is_eboard, - is_eval=is_eval, - is_financial=is_financial, + is_eval_director=is_eval, + is_financial_director=is_financial, is_intromember=is_intromember, **kwargs)
746be2e5557f6626e984a679f1699c6a76fa932e
miner/block_test.py
miner/block_test.py
import unittest from block import Block class TestBlock(unittest.TestCase): class MerkleTreeMock: pass def test_init(self): prev = 0x123123 tree = TestBlock.MerkleTreeMock() time = 0x432432 bits = 0x1a44b9f2 b = Block(prev, tree, time, bits) self.ass...
import unittest from block import Block class TestBlock(unittest.TestCase): class MerkleTreeMock: pass def test_init(self): prev = bytes([123] * 32) tree = TestBlock.MerkleTreeMock() time = 432432 bits = 0x1a44b9f2 b = Block(prev, tree, time, bits) s...
Change block init test to pass bytes for hash
Change block init test to pass bytes for hash
Python
mit
DrPandemic/pickaxe,DrPandemic/pickaxe,DrPandemic/pickaxe,DrPandemic/pickaxe
--- +++ @@ -8,9 +8,9 @@ pass def test_init(self): - prev = 0x123123 + prev = bytes([123] * 32) tree = TestBlock.MerkleTreeMock() - time = 0x432432 + time = 432432 bits = 0x1a44b9f2 b = Block(prev, tree, time, bits)
65695bd7c4c7fcf3449358c0946e4584bb30a8ec
climate_data/migrations/0024_auto_20170623_0308.py
climate_data/migrations/0024_auto_20170623_0308.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-23 03:08 from __future__ import unicode_literals from django.db import migrations # noinspection PyUnusedLocal def add_station_sensor_link_to_reading(apps, schema_editor): # noinspection PyPep8Naming Reading = apps.get_model('climate_data', 'Rea...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-06-23 03:08 from __future__ import unicode_literals from django.db import migrations import sys # noinspection PyUnusedLocal def add_station_sensor_link_to_reading(apps, schema_editor): # noinspection PyPep8Naming Reading = apps.get_model('climate...
Increase page size again in station-sensor link / reading migration, and add a percent indicator. Exclude any readings that have previously been fixed up by the migration.
Increase page size again in station-sensor link / reading migration, and add a percent indicator. Exclude any readings that have previously been fixed up by the migration.
Python
apache-2.0
qubs/data-centre,qubs/climate-data-api,qubs/data-centre,qubs/climate-data-api
--- +++ @@ -3,6 +3,8 @@ from __future__ import unicode_literals from django.db import migrations + +import sys # noinspection PyUnusedLocal @@ -13,18 +15,28 @@ StationSensorLink = apps.get_model('climate_data', 'StationSensorLink') offset = 0 - pagesize = 5000 - count = Reading.objects.all(...
5c353a23dfc2378c97fb4888db09e4a505bf8f8f
editorconfig/__init__.py
editorconfig/__init__.py
"""EditorConfig Python Core""" from versiontools import join_version VERSION = (0, 11, 0, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" handler = Ed...
"""EditorConfig Python Core""" from editorconfig.versiontools import join_version VERSION = (0, 11, 0, "final") __all__ = ['get_properties', 'EditorConfigError', 'exceptions'] __version__ = join_version(VERSION) def get_properties(filename): """Locate and parse EditorConfig files for the given filename""" ...
Fix import style for Python3
Fix import style for Python3
Python
bsd-2-clause
johnfraney/editorconfig-vim,johnfraney/editorconfig-vim,johnfraney/editorconfig-vim,benjifisher/editorconfig-vim,VictorBjelkholm/editorconfig-vim,benjifisher/editorconfig-vim,benjifisher/editorconfig-vim,pocke/editorconfig-vim,VictorBjelkholm/editorconfig-vim,pocke/editorconfig-vim,VictorBjelkholm/editorconfig-vim,pock...
--- +++ @@ -1,6 +1,6 @@ """EditorConfig Python Core""" -from versiontools import join_version +from editorconfig.versiontools import join_version VERSION = (0, 11, 0, "final") @@ -15,5 +15,5 @@ return handler.get_configurations() -from handler import EditorConfigHandler -from exceptions import * +fro...
afd67433190427f0234bc27ef67cde8b2f6ae746
gravatar/gravatar.py
gravatar/gravatar.py
""" Gravatar plugin for Pelican =========================== This plugin assigns the ``author_gravatar`` variable to the Gravatar URL and makes the variable available within the article's context. """ import hashlib import six from pelican import signals def add_gravatar(generator, metadata): #first check emai...
""" Gravatar plugin for Pelican =========================== This plugin assigns the ``author_gravatar`` variable to the Gravatar URL and makes the variable available within the article's context. """ import hashlib import six from pelican import signals def add_gravatar(generator, metadata): #first check emai...
Use https instead http to get secure resources content in blog over https
Use https instead http to get secure resources content in blog over https
Python
agpl-3.0
farseerfc/pelican-plugins,MarkusH/pelican-plugins,farseerfc/pelican-plugins,danmackinlay/pelican-plugins,florianjacob/pelican-plugins,cctags/pelican-plugins,farseerfc/pelican-plugins,rlaboiss/pelican-plugins,jakevdp/pelican-plugins,rlaboiss/pelican-plugins,if1live/pelican-plugins,kdheepak89/pelican-plugins,florianjacob...
--- +++ @@ -22,7 +22,7 @@ #then add gravatar url if 'email' in metadata.keys(): email_bytes = six.b(metadata['email']).lower() - gravatar_url = "http://www.gravatar.com/avatar/" + \ + gravatar_url = "https://www.gravatar.com/avatar/" + \ hashlib.md5(email_byte...
a89983d2e218c6438587be9e6ea89e76f4c5a8c6
14B-088/Combined_HI/HI_single_channel_clean.py
14B-088/Combined_HI/HI_single_channel_clean.py
import sys from casa_tools import myclean ''' Cleans an MS with a single channel given a mask and a model ''' vis_1 = sys.argv[-5] vis_2 = sys.argv[-4] model = sys.argv[-3] mask = sys.argv[-2] out_root = sys.argv[-1] if model == "None": model = None else: model = [model] * 2 if mask == "None": mask = ...
import sys from casa_tools import myclean ''' Cleans an MS with a single channel given a mask and a model ''' vis_1 = sys.argv[-5] vis_2 = sys.argv[-4] model = sys.argv[-3] mask = sys.argv[-2] out_root = sys.argv[-1] if model == "None": model = None else: model = [model] * 2 if mask == "None": mask = ...
Add larger scale to match C config only map
Add larger scale to match C config only map
Python
mit
e-koch/VLA_Lband,e-koch/VLA_Lband
--- +++ @@ -26,7 +26,7 @@ myclean(vis=[vis_1, vis_2], imagename=out_root+'.clean', field='M33*', restfreq='1420.40575177MHz', mode='channel', width=1, nchan=1, start=1, - cell='1.5arcsec', multiscale=[0, 4, 8, 20, 40, 80], + cell='1.5arcsec', multiscale=[0, 4, 8, 20, 40, 80, 160], ...
f6b7a4ec8aa72acfd93e7f85199b251e91ca4465
cherrypy/test/test_refleaks.py
cherrypy/test/test_refleaks.py
"""Tests for refleaks.""" from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob import threading import cherrypy data = object() from cherrypy.test import helper class ReferenceTests(helper.CPWebCase): @staticmethod def setup_server(): class Root: @cherrypy.expose ...
"""Tests for refleaks.""" import itertools from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob import threading import cherrypy data = object() from cherrypy.test import helper class ReferenceTests(helper.CPWebCase): @staticmethod def setup_server(): class Root: ...
Use a simple counter rather than appending booleans to a list and counting them.
Use a simple counter rather than appending booleans to a list and counting them.
Python
bsd-3-clause
cherrypy/cheroot,Safihre/cherrypy,cherrypy/cherrypy,cherrypy/cherrypy,Safihre/cherrypy
--- +++ @@ -1,4 +1,6 @@ """Tests for refleaks.""" + +import itertools from cherrypy._cpcompat import HTTPConnection, HTTPSConnection, ntob import threading @@ -27,7 +29,7 @@ cherrypy.tree.mount(Root()) def test_threadlocal_garbage(self): - success = [] + success = itertools.count() ...
0141527409771ff9396252eedd02c6729aa3f3d9
eegtools/data/schalk_physiobank_test.py
eegtools/data/schalk_physiobank_test.py
import schalk_physiobank def test_s1(): r = schalk_physiobank.load(1) assert str(r) == 'Recording "schalk-physiobank-s1" (64 channels x 259520 '\ 'samples) at 160.00 Hz in 14 continuous blocks, with 362 events in 11 '\ 'classes.' def test_s14(): '''Test subject 14 which contains runs *without* any event...
import schalk_physiobank def test_s1(): r = schalk_physiobank.load(1) assert str(r) == 'Recording "schalk-physiobank-s1" (64 channels x 259520 '\ 'samples) at 160.00 Hz in 14 continuous blocks, with 362 events in 11 '\ 'classes.' def test_s14(): '''Test subject 14 which contains runs *without* any event...
Fix regression test after EDF+ annotation fix in 60753f.
Fix regression test after EDF+ annotation fix in 60753f.
Python
bsd-3-clause
breuderink/eegtools
--- +++ @@ -10,5 +10,5 @@ '''Test subject 14 which contains runs *without* any event.''' r = schalk_physiobank.load(14) assert str(r) == 'Recording "schalk-physiobank-s14" (64 channels x 255520 '\ - 'samples) at 160.00 Hz in 14 continuous blocks, with 361 events in 11 '\ + 'samples) at 160.00 Hz in 14 ...
0c8e3f6d962a573618d5224b20b68e57790f4beb
feder/institutions/forms.py
feder/institutions/forms.py
# -*- coding: utf-8 -*- from atom.forms import SingleButtonMixin from braces.forms import UserKwargModelFormMixin from django import forms from .models import Institution class InstitutionForm(SingleButtonMixin, UserKwargModelFormMixin, forms.ModelForm): def __init__(self, *args, **kwargs): super(Instit...
# -*- coding: utf-8 -*- from atom.forms import SingleButtonMixin from braces.forms import UserKwargModelFormMixin from django import forms from .models import Institution class InstitutionForm(SingleButtonMixin, UserKwargModelFormMixin, forms.ModelForm): def __init__(self, *args, **kwargs): super(Instit...
Fix InstitutionForm to include jst field
Fix InstitutionForm to include jst field
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
--- +++ @@ -13,4 +13,4 @@ class Meta: model = Institution - fields = ['name', 'address'] + fields = ['name', 'address', 'jst']
4ea698622a7a581b84ce61de8f5f65ce12f0c129
morenines/output.py
morenines/output.py
import click def print_message(message): print message def print_filelist(header, filelist, colour=None): click.echo(header) for line in filelist: if colour: line = click.style(line, fg=colour) click.echo(" {}".format(line)) def print_filelists(new_files, changed_files, m...
import click def print_message(message): print message def print_filelist(header, filelist, colour=None): click.echo(header) for line in sorted(filelist): if colour: line = click.style(line, fg=colour) click.echo(" {}".format(line)) def print_filelists(new_files, changed_...
Make print_filelist sort the list before printing
Make print_filelist sort the list before printing
Python
mit
mcgid/morenines,mcgid/morenines
--- +++ @@ -7,7 +7,7 @@ def print_filelist(header, filelist, colour=None): click.echo(header) - for line in filelist: + for line in sorted(filelist): if colour: line = click.style(line, fg=colour)
a5b3dd62e58dc23c03b7876ee99b757022413e94
billjobs/urls.py
billjobs/urls.py
from django.conf.urls import url, include from rest_framework.authtoken.views import obtain_auth_token from . import views urlpatterns = [ url(r'^generate_pdf/(?P<bill_id>\d+)$', views.generate_pdf, name='generate-pdf'), url(r'^user/$', views.UserAdmin.as_view(), name='user'), url(r'^user/(?P<pk>[0...
from django.conf.urls import url, include from rest_framework.authtoken.views import obtain_auth_token from . import views api_patterns = [ url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^token-auth/', obtain_auth_token, name='api-token-auth'), url...
Move api auth url to api_patterns
Move api auth url to api_patterns
Python
mit
ioO/billjobs
--- +++ @@ -2,12 +2,17 @@ from rest_framework.authtoken.views import obtain_auth_token from . import views +api_patterns = [ + url(r'^auth/', + include('rest_framework.urls', namespace='rest_framework')), + url(r'^token-auth/', obtain_auth_token, name='api-token-auth'), + url(r'^us...
71798ca99fe7245a578ea1d6ba367e485d9ad5f8
mvp/renderlayers.py
mvp/renderlayers.py
# -*- coding: utf-8 -*- from contextlib import contextmanager import maya.app.renderSetup.model.renderSetup as renderSetup from maya import cmds @contextmanager def enabled_render_layers(): old_layer = cmds.editRenderLayerGlobals(query=True, currentRenderLayer=True) try: rs = renderSetup.instance() ...
# -*- coding: utf-8 -*- from contextlib import contextmanager import maya.app.renderSetup.model.renderSetup as renderSetup from maya import cmds @contextmanager def enabled_render_layers(): old_layer = cmds.editRenderLayerGlobals( query=True, currentRenderLayer=True, ) try: rs = r...
Fix defaultRenderLayer was not included when blasting all layers.
Fix defaultRenderLayer was not included when blasting all layers.
Python
mit
danbradham/mvp
--- +++ @@ -7,7 +7,10 @@ @contextmanager def enabled_render_layers(): - old_layer = cmds.editRenderLayerGlobals(query=True, currentRenderLayer=True) + old_layer = cmds.editRenderLayerGlobals( + query=True, + currentRenderLayer=True, + ) try: rs = renderSetup.instance() @@ -1...
56528264cdc76dc1b00804b7f67908d3bb1b1b0e
flask_appconfig/docker.py
flask_appconfig/docker.py
#!/usr/bin/env python import os from six.moves.urllib_parse import urlparse def from_docker_envvars(config): # linked postgres database (link name 'pg' or 'postgres') if 'PG_PORT' in os.environ: pg_url = urlparse(os.environ['PG_PORT']) if not pg_url.scheme == 'tcp': raise ValueEr...
#!/usr/bin/env python import os from six.moves.urllib_parse import urlparse def from_docker_envvars(config): # linked postgres database (link name 'pg' or 'postgres') if 'PG_PORT' in os.environ: pg_url = urlparse(os.environ['PG_PORT']) if not pg_url.scheme == 'tcp': raise ValueEr...
Use correct database name instead of None when not supplied.
Use correct database name instead of None when not supplied.
Python
mit
mbr/flask-appconfig
--- +++ @@ -19,7 +19,7 @@ password=os.environ.get('PG_ENV_POSTGRES_PASSWORD', ''), host=host, port=port, - database=os.environ.get('PG_ENV_POSTGRES_DB')) + database=os.environ.get('PG_ENV_POSTGRES_DB', 'postgres')) config['SQLALCHEMY_DATABASE_URI...
809f2f781fb2186e3bad27cdd19115b6f425cd0b
tint/tests/test_grid_utils.py
tint/tests/test_grid_utils.py
""" Unit tests for grid_utils module. """ from datetime import datetime import numpy as np from tint import grid_utils from tint.testing.sample_objects import grid, field from tint.testing.sample_objects import params, grid_size def test_parse_grid_datetime(): dt = grid_utils.parse_grid_datetime(grid) asser...
""" Unit tests for grid_utils module. """ from datetime import datetime import numpy as np from tint import grid_utils from tint.testing.sample_objects import grid, field from tint.testing.sample_objects import params, grid_size def test_parse_grid_datetime(): dt = grid_utils.parse_grid_datetime(grid) asser...
Update for unit tests for PR 37
TST: Update for unit tests for PR 37
Python
bsd-2-clause
openradar/TINT,openradar/TINT
--- +++ @@ -10,7 +10,7 @@ def test_parse_grid_datetime(): dt = grid_utils.parse_grid_datetime(grid) - assert(dt == datetime(2015, 7, 10, 18, 34, 6)) + assert(dt == datetime(2015, 7, 10, 18, 34, 102000)) def test_get_grid_size():
c8a08042cc7eb0ddb0b617f1fb935691a5803a29
gitcommitautosave.py
gitcommitautosave.py
"""Git Commit Auto Save. Sublime Text 3 package to auto save commit messages when the window is closed. This allows the user to close the window without having to save before, or having to deal with the "Save File" popup. """ import sublime_plugin class GitCommitAutoSave(sublime_plugin.EventListener): def on_load(s...
"""Git Commit Auto Save. Sublime Text 3 package to auto save commit messages when the window is closed. This allows the user to close the window without having to save before, or having to deal with the "Save File" popup. """ import sublime_plugin class GitCommitAutoSave(sublime_plugin.EventListener): def on_load(s...
Add PULLREQ_EDITMSG for hub pull requests
Add PULLREQ_EDITMSG for hub pull requests
Python
mit
aristidesfl/sublime-git-commit-message-auto-save
--- +++ @@ -18,6 +18,6 @@ def is_git_file(path): - git_files = ('COMMIT_EDITMSG', 'git-rebase-todo', 'MERGE_MSG') + git_files = ('COMMIT_EDITMSG', 'git-rebase-todo', 'MERGE_MSG', 'PULLREQ_EDITMSG') if path and any(path.endswith(name) for name in git_files): return True
07e7f5023958538933802f78c7bdd5d61f04a825
flocker/restapi/__init__.py
flocker/restapi/__init__.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Infrastructure for publishing a REST HTTP API. """ from ._infrastructure import structured __all__ = ["structured"]
# Copyright Hybrid Logic Ltd. See LICENSE file for details. """ Infrastructure for publishing a REST HTTP API. """ from ._infrastructure import ( structured, EndpointResponse, userDocumentation, ) __all__ = ["structured", "EndpointResponse", "userDocumentation"]
Address review comment: Make more APIs public.
Address review comment: Make more APIs public.
Python
apache-2.0
moypray/flocker,adamtheturtle/flocker,Azulinho/flocker,agonzalezro/flocker,1d4Nf6/flocker,1d4Nf6/flocker,runcom/flocker,1d4Nf6/flocker,moypray/flocker,lukemarsden/flocker,LaynePeng/flocker,jml/flocker,moypray/flocker,adamtheturtle/flocker,lukemarsden/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,jml/flocker,And...
--- +++ @@ -4,7 +4,9 @@ Infrastructure for publishing a REST HTTP API. """ -from ._infrastructure import structured +from ._infrastructure import ( + structured, EndpointResponse, userDocumentation, + ) -__all__ = ["structured"] +__all__ = ["structured", "EndpointResponse", "userDocumentation"]
b016fad5d55993b064a1c4d15fd281f439045491
gateway/camera/device.py
gateway/camera/device.py
from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address def send(self, opcode, body=None): packet = net.encode_packet(opcode, body) yie...
from tornado import gen from gateway import net class CameraDevice(object): def __init__(self, stream, address): self.resolution = None self.framerate = None self.__stream = stream self.__address = address @gen.coroutine def send(self, opcode, body=None): packet =...
Fix CameraDevice's send method is not called
Fix CameraDevice's send method is not called Add send method @gen.coroutine decorator
Python
mit
walkover/auto-tracking-cctv-gateway
--- +++ @@ -1,3 +1,5 @@ +from tornado import gen + from gateway import net @@ -8,6 +10,7 @@ self.__stream = stream self.__address = address + @gen.coroutine def send(self, opcode, body=None): packet = net.encode_packet(opcode, body) yield self.__stream.write(packet)
9f0c05eb9926dc5a9be6eb65bd71f7f1218e24e1
grano/logic/validation.py
grano/logic/validation.py
import re import colander from colander import Invalid from grano.logic.references import ProjectRef from grano.core import db from grano.model import Schema, Attribute FORBIDDEN = ['project', 'source', 'target', 'id', 'created_at', 'updated_at', 'author', 'author_id'] database_forbidden = colander.Function(lambda v...
import colander from colander import Invalid class All(object): """ Composite validator which succeeds if none of its subvalidators raises an :class:`colander.Invalid` exception""" def __init__(self, *validators): self.validators = validators def __call__(self, node, value): for valid...
Fix handling of All() exceptions.
Fix handling of All() exceptions.
Python
mit
4bic/grano,CodeForAfrica/grano,4bic-attic/grano,granoproject/grano
--- +++ @@ -1,16 +1,22 @@ -import re import colander from colander import Invalid -from grano.logic.references import ProjectRef -from grano.core import db -from grano.model import Schema, Attribute +class All(object): + """ Composite validator which succeeds if none of its + subvalidators raises an :clas...
5ed5855efe09c92efbf93dab5eb0b37325072381
opps/api/__init__.py
opps/api/__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.http import HttpResponse from django.contrib.auth import authenticate from piston.handler import BaseHandler as Handler from opps.api.models import ApiKey class BaseHandler(Handler): def read(self, request): base = self.model.objects if ...
Fix method get on ApiKeyAuthentication
Fix method get on ApiKeyAuthentication
Python
mit
jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,jeanmask/opps,williamroot/opps,opps/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,jeanmask/opps
--- +++ @@ -26,7 +26,11 @@ if request.method == 'GET' and 'GET' in self.method: return True - method = getattr(request, request.method) + try: + method = getattr(request, request.method) + except: + method = request.GET + try: Ap...
66c0b220188499a5871ee1fbe5b79f0a57db4ec9
feder/tasks/filters.py
feder/tasks/filters.py
# -*- coding: utf-8 -*- from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter from django.utils.translation import ugettext_lazy as _ import django_filters from .models import Task class TaskFilter(CrispyFilterMixin, django_filters.FilterSet): case = AutocompleteChoiceFilter('CaseAutocomplete') ...
# -*- coding: utf-8 -*- from atom.filters import CrispyFilterMixin, AutocompleteChoiceFilter from django.utils.translation import ugettext_lazy as _ import django_filters from .models import Task class TaskFilter(CrispyFilterMixin, django_filters.FilterSet): case = AutocompleteChoiceFilter('CaseAutocomplete') ...
Add is_done filter for task
Add is_done filter for task
Python
mit
watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder
--- +++ @@ -11,6 +11,8 @@ case__institution = AutocompleteChoiceFilter('InstitutionAutocomplete') case__monitoring = AutocompleteChoiceFilter('MonitoringAutocomplete') created = django_filters.DateRangeFilter(label=_("Creation date")) + done = django_filters.BooleanFilter(label=_("Is done?"), + ...
98392a42381470153fe2c13cda8e24cdccc5fe4b
hr_holidays_legal_leave/models/res_config.py
hr_holidays_legal_leave/models/res_config.py
# -*- coding: utf-8 -*- # © 2015 iDT LABS (http://www.@idtlabs.sl) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import fields, models, api class HumanResourcesConfiguration(models.TransientModel): _inherit = 'hr.config.settings' legal_holidays_status_id = fields.Many2on...
# -*- coding: utf-8 -*- # © 2015 iDT LABS (http://www.@idtlabs.sl) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from openerp import fields, models, api class HumanResourcesConfiguration(models.TransientModel): _inherit = 'hr.config.settings' legal_holidays_status_id = fields.Many2on...
Remove fields from method definition.
Remove fields from method definition.
Python
agpl-3.0
VitalPet/hr,feketemihai/hr,Eficent/hr,open-synergy/hr,VitalPet/hr,thinkopensolutions/hr,Eficent/hr,acsone/hr,open-synergy/hr,thinkopensolutions/hr,acsone/hr,feketemihai/hr
--- +++ @@ -14,7 +14,7 @@ ) @api.model - def get_legal_holidays_status_id(self, fields): + def get_legal_holidays_status_id(self): company = self.env.user.company_id return { 'legal_holidays_status_id': company.legal_holidays_status_id.id,
c55a42737a99104734a79e946304849258bfa44b
aplib/__init__.py
aplib/__init__.py
# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
# Copyright (c) 2002-2011 IronPort Systems and Cisco Systems # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, mo...
Allow aplib to be imported when coro is not installed.
Allow aplib to be imported when coro is not installed.
Python
mit
ironport/aplib,ironport/aplib
--- +++ @@ -18,4 +18,9 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -from make_socket_for_ip import make_socket_for_ip +# Wrap this in case coro has not been installed +try: + from make_socket_for_ip import make_socket_for_ip +except ImportError: + def make_...
f4701ac73f884ef28e62bb35adc81330ce512171
goto_last_edit.py
goto_last_edit.py
import sublime_plugin # the last edited Region, keyed to View.id _last_edits = {} class RecordLastEdit(sublime_plugin.EventListener): def on_modified(self, view): _last_edits[view.id()] = view.sel()[0] class GotoLastEdit(sublime_plugin.TextCommand): def run(self, edit): last_edit = _last...
import sublime, sublime_plugin LAST_EDITS_SETTING = 'last_edits' class RecordLastEdit(sublime_plugin.EventListener): def on_modified(self, view): last_edits = view.settings().get(LAST_EDITS_SETTING, {}) edit_position = view.sel()[0] last_edits[str(view.id())] = {'a': edit_position.a, '...
Return to original if cursor is already at least edit
Return to original if cursor is already at least edit
Python
mit
abrookins/GotoLastEdit
--- +++ @@ -1,20 +1,54 @@ -import sublime_plugin +import sublime, sublime_plugin -# the last edited Region, keyed to View.id -_last_edits = {} +LAST_EDITS_SETTING = 'last_edits' class RecordLastEdit(sublime_plugin.EventListener): def on_modified(self, view): - _last_edits[view.id()] = view.sel()[...
3a80b55c8a46f46ecd5b458d0aee26b34e8ad1f5
backend/core/app.py
backend/core/app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask from flask_restful import Api from .db import configure_database class Application: def __init__(self): self.flask_app = Flask(__name__) self.api = Api(self.flask_app) self.import_configuration() self.configur...
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask from flask_restful import Api from .db import configure_database class Application: def __init__(self): self.flask_app = Flask(__name__) self.api = Api(self.flask_app) self.import_configuration() self.configur...
Add another user in fixture code
Add another user in fixture code
Python
unlicense
azlyth/tokens,azlyth/tokens,azlyth/tokens
--- +++ @@ -29,7 +29,8 @@ def bootstrap(self): from .models import User, Question, Category if not Question.find_all(): - User.create('peter', 'asdf') + User.create('peter', 'valdez') + User.create('sundar', 'raman') Question.create(text='Is this ...
c892077dd55405d71cbe6d6191c53260b74447d2
hubblestack/extmods/grains/hostuuid.py
hubblestack/extmods/grains/hostuuid.py
# -*- coding: utf-8 -*- ''' Generate a unique uuid for this host, storing it on disk so it persists across restarts ''' import logging import os import uuid log = logging.getLogger(__name__) def host_uuid(): ''' Generate a unique uuid for this host, storing it on disk so it persists across restarts '...
# -*- coding: utf-8 -*- ''' Generate a unique uuid for this host, storing it on disk so it persists across restarts ''' import logging import os import uuid log = logging.getLogger(__name__) def host_uuid(): ''' Generate a unique uuid for this host, storing it on disk so it persists across restarts '...
Write the correct variable to disk
Write the correct variable to disk Maybe I should get more sleep
Python
apache-2.0
basepi/hubble,basepi/hubble
--- +++ @@ -24,5 +24,5 @@ log.exception('Problem retrieving cached host uuid') generated = uuid.uuid4() with open(cached_uuid, 'w') as f: - f.write(cached_uuid) + f.write(generated) return {'host_uuid': generated}
ebb0236d7c68883de7a4202df23e74becd943f29
hooks/pre_gen_project.py
hooks/pre_gen_project.py
project_slug = '{{ cookiecutter.project_slug }}' print('pre gen') if hasattr(project_slug, 'isidentifier'): assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
project_slug = '{{ cookiecutter.project_slug }}' if hasattr(project_slug, 'isidentifier'): assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
Fix a typo in the pre-generation hooks
Fix a typo in the pre-generation hooks
Python
bsd-3-clause
valerymelou/cookiecutter-django-gulp,valerymelou/cookiecutter-django-gulp,valerymelou/cookiecutter-django-gulp
--- +++ @@ -1,6 +1,5 @@ project_slug = '{{ cookiecutter.project_slug }}' -print('pre gen') if hasattr(project_slug, 'isidentifier'): assert project_slug.isidentifier(), 'Project slug should be valid Python identifier!'
b7b38e67ae95a5d5bed68661c2e106149117fa80
mendel/views.py
mendel/views.py
from django.conf import settings from django.shortcuts import render from rest_framework import permissions from rest_framework.views import APIView from rest_framework.response import Response from models import Context, Review, Keyword, Category def index(request): context = {'DEBUG': settings.DEBUG} return...
from django.conf import settings from django.shortcuts import render from rest_framework import permissions from rest_framework.views import APIView from rest_framework.response import Response from models import Context, Review, Keyword, Category def index(request): context = {'DEBUG': settings.DEBUG} return...
Handle review deletion when updating categories for a context
Handle review deletion when updating categories for a context
Python
agpl-3.0
Architizer/mendel,Architizer/mendel,Architizer/mendel,Architizer/mendel
--- +++ @@ -24,7 +24,15 @@ name=request.data.get('keyword_proposed')['name'] ) - existing_review_count = Review.objects.filter(context=context).count() + existing_review_count = Review.objects.filter(user=request.user, context=context).count() + + # If there are ex...
5748265d5102ee69e928d65ff3d40779af120dac
count-inversions/count_inversions.py
count-inversions/count_inversions.py
from random import randint import sys def sort_and_count(arr): n = len(arr) if n == 1: return 0 else: first_half = arr[:n/2] second_half = arr[n/2:] return merge_and_count_split(sort_and_count(first_half), sort_and_count(second_half)) def merge_and_count_split(arr1, arr2): return 0 def main(arr_len): ...
from random import randint import sys def sort_and_count(arr): n = len(arr) if n == 1: return arr else: first_half = arr[:n/2] second_half = arr[n/2:] return merge_and_count_split(sort_and_count(first_half), sort_and_count(second_half)) def merge_and_count_split(arr1, arr2): i, j = 0, 0 result = [] ...
Implement merge component of merge_and_count_split
Implement merge component of merge_and_count_split The merging part of merge_and_count_split was is taken right out of merge-sort. A test revealed a mistake in merge_and_sort where 0 was returned instead of the array when the array has one element, so that was fixed.
Python
mit
timpel/stanford-algs,timpel/stanford-algs
--- +++ @@ -5,7 +5,7 @@ n = len(arr) if n == 1: - return 0 + return arr else: first_half = arr[:n/2] @@ -14,7 +14,25 @@ def merge_and_count_split(arr1, arr2): - return 0 + i, j = 0, 0 + result = [] + + while 1: + if i == len(arr1): + result.extend(arr2[j:]) + break + if j == len(arr2): + r...
2f26197d10a1c7cfc010074576c7e1a2c2a31e78
data_structures/bitorrent/torrent.py
data_structures/bitorrent/torrent.py
import hashlib import urllib import bencode class Torrent(object): def __init__(self, path): self.encoded = self._get_meta(path) self.decoded = bencode.bdecode(self.encoded) def _get_meta(self, path): with open(path) as f: return f.read() @property def hash(self): info_hash = hashlib...
import hashlib import urllib import bencode class Torrent(object): def __init__(self, path): self.encoded = self._get_meta(path) self.decoded = bencode.bdecode(self.encoded) def _get_meta(self, path): with open(path) as f: return f.read() def __getitem__(self, item): return self.decode...
Use __getitem__ to improve readbility
Use __getitem__ to improve readbility
Python
apache-2.0
vtemian/university_projects,vtemian/university_projects,vtemian/university_projects
--- +++ @@ -14,6 +14,9 @@ with open(path) as f: return f.read() + def __getitem__(self, item): + return self.decoded[item] + @property def hash(self): info_hash = hashlib.sha1(bencode.bencode(self.decoded['info'])).digest()
9caa0aa6c8fddc8a21997cf4df88d407b1598412
keras_cv/__init__.py
keras_cv/__init__.py
# Copyright 2022 The KerasCV Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
# Copyright 2022 The KerasCV Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
Add export for models module
Add export for models module
Python
apache-2.0
keras-team/keras-cv,keras-team/keras-cv,keras-team/keras-cv
--- +++ @@ -14,6 +14,7 @@ from keras_cv import layers from keras_cv import metrics +from keras_cv import models from keras_cv import utils from keras_cv import version_check from keras_cv.core import ConstantFactorSampler
4e18d3d3c35e92d6b800f347b65765ca36d6148b
playserver/track.py
playserver/track.py
import configmanager import osascript APP_CONFIG_PATH = "../applications/" applicationConfigs = configmanager.ConfigManager(APP_CONFIG_PATH) #TODO: Make this user choosable currentApplication = "radiant" def getCurrentConfig(): return applicationConfigs[currentApplication] def _executeCommand(command): config = g...
import configmanager import osascript APP_CONFIG_PATH = "../applications/" applicationConfigs = configmanager.ConfigManager(APP_CONFIG_PATH) #TODO: Make this user choosable currentApplication = "radiant" def getCurrentConfig(): return applicationConfigs[currentApplication] def _executeCommand(command): config = g...
Return full osascript output from getCurrentConfig
Return full osascript output from getCurrentConfig
Python
mit
ollien/playserver,ollien/playserver,ollien/playserver
--- +++ @@ -14,6 +14,4 @@ config = getCurrentConfig() fullCommand = "tell application \"{}\" to {}".format(config["name"], config["commands"][command]) - result = osascript.osascript(fullCommand) - #Return the return code of the command - 0 if succuessful. - return result[0] + return osascript.osascript(fullCo...
e7a8c76c1f8f07866a4b7ea55870dacb5c76ef90
face/tests/model_tests.py
face/tests/model_tests.py
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'...
from django.test import TestCase from functional_tests.factory import FaceFactory class Facetest(TestCase): def setUp(self): self.face = FaceFactory(title='Lokesh') def test_title_to_share_returns_meet_Lokesh__farmer_from_sivaganga_tamil_nadu(self): self.assertEqual(self.face.title_to_share,'...
Fix unit test for seo faces url
Fix unit test for seo faces url
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
--- +++ @@ -16,4 +16,4 @@ self.assertEqual(str(self.face),'Lokesh Sivaganga') def test_get_absolute_url_return_path_with_faces_s_face_page(self): - self.assertEqual(self.face.get_absolute_url(),'/categories/faces/s/lokesh/') + self.assertRegexpMatches(self.face.get_absolute_url(),'/categ...
8df691acaebffc343dac4535a64f8a809607558a
Demo/sgi/cd/cdaiff.py
Demo/sgi/cd/cdaiff.py
import sys import readcd import aiff import AL import CD Error = 'cdaiff.Error' def writeaudio(a, type, data): a.writesampsraw(data) def main(): if len(sys.argv) > 1: a = aiff.Aiff().init(sys.argv[1], 'w') else: a = aiff.Aiff().init('@', 'w') a.sampwidth = AL.SAMPLE_16 a.nchannels = AL.STEREO a.samprate = ...
import sys import readcd import aifc import AL import CD Error = 'cdaiff.Error' def writeaudio(a, type, data): a.writeframesraw(data) def main(): if len(sys.argv) > 1: a = aifc.open(sys.argv[1], 'w') else: a = aifc.open('@', 'w') a.setsampwidth(AL.SAMPLE_16) a.setnchannels(AL.STEREO) a.setframerate(AL.RATE...
Use module aifc instead of module aiff.
Use module aifc instead of module aiff.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -1,22 +1,22 @@ import sys import readcd -import aiff +import aifc import AL import CD Error = 'cdaiff.Error' def writeaudio(a, type, data): - a.writesampsraw(data) + a.writeframesraw(data) def main(): if len(sys.argv) > 1: - a = aiff.Aiff().init(sys.argv[1], 'w') + a = aifc.open(sys.argv[1...
b097675e5906f7b0e9c050110fea58e40491814b
music/api.py
music/api.py
from django.conf.urls.defaults import url from tastypie.resources import ModelResource from jmbo.api import ModelBaseResource from music.models import Track class TrackResource(ModelBaseResource): class Meta: queryset = Track.permitted.all() resource_name = 'track' ordering = ['last_pla...
from django.conf.urls.defaults import url from tastypie.resources import ModelResource from tastypie.constants import ALL from jmbo.api import ModelBaseResource from music.models import Track class TrackResource(ModelBaseResource): class Meta: queryset = Track.permitted.all() resource_name = 't...
Allow filtering and ordering on API
Allow filtering and ordering on API
Python
bsd-3-clause
praekelt/jmbo-music,praekelt/jmbo-music
--- +++ @@ -1,6 +1,7 @@ from django.conf.urls.defaults import url from tastypie.resources import ModelResource +from tastypie.constants import ALL from jmbo.api import ModelBaseResource from music.models import Track @@ -11,6 +12,9 @@ class Meta: queryset = Track.permitted.all() resourc...
61bfc62937176b580b8b6ae12a90c5b76b00d50d
libcloud/__init__.py
libcloud/__init__.py
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # libcloud.org licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # libcloud.org licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not...
Add version string to libcloud
Add version string to libcloud git-svn-id: 353d90d4d8d13dcb4e0402680a9155a727f61a5a@895867 13f79535-47bb-0310-9956-ffa450edef68
Python
apache-2.0
Kami/libcloud,jimbobhickville/libcloud,ClusterHQ/libcloud,apache/libcloud,DimensionDataCBUSydney/libcloud,curoverse/libcloud,smaffulli/libcloud,schaubl/libcloud,techhat/libcloud,DimensionDataCBUSydney/libcloud,cryptickp/libcloud,cloudControl/libcloud,supertom/libcloud,ZuluPro/libcloud,Verizon/libcloud,t-tran/libcloud,S...
--- +++ @@ -16,3 +16,5 @@ """ libcloud provides a unified interface to the cloud computing resources. """ + +__version__ = "0.1.1-dev"
372ff487c068da2b31cd25e550e8dcd7bd12d17d
openprocurement/tender/esco/adapters.py
openprocurement/tender/esco/adapters.py
# -*- coding: utf-8 -*- from openprocurement.tender.openeu.adapters import TenderAboveThresholdEUConfigurator from openprocurement.tender.esco.models import Tender class TenderESCOConfigurator(TenderAboveThresholdEUConfigurator): """ ESCO Tender configuration adapter """ name = "esco Tender configurator" ...
# -*- coding: utf-8 -*- from openprocurement.tender.openeu.adapters import TenderAboveThresholdEUConfigurator from openprocurement.tender.esco.models import Tender class TenderESCOConfigurator(TenderAboveThresholdEUConfigurator): """ ESCO Tender configuration adapter """ name = "esco Tender configurator" ...
Add awarding criteria field to configurator
Add awarding criteria field to configurator
Python
apache-2.0
openprocurement/openprocurement.tender.esco
--- +++ @@ -11,3 +11,6 @@ # Param to configure award criteria - awards are generated from higher to lower by value.amount reverse_awarding_criteria = True + + # Param to set awarding criteria field + awarding_criteria_key = 'amountPerfomance'
b94e4971e3bcde718c40dc963a995e8afa5cf99f
examples/rate_limiting_test.py
examples/rate_limiting_test.py
from seleniumbase import BaseCase from seleniumbase.common import decorators class MyTestClass(BaseCase): @decorators.rate_limited(4) # The arg is max calls per second def print_item(self, item): print item def test_rate_limited_printing(self): print "\nRunning rate-limited print test:"...
from seleniumbase import BaseCase from seleniumbase.common import decorators class MyTestClass(BaseCase): @decorators.rate_limited(3.5) # The arg is max calls per second def print_item(self, item): print item def test_rate_limited_printing(self): print "\nRunning rate-limited print test...
Make the rate-limiting test more fancy
Make the rate-limiting test more fancy
Python
mit
mdmintz/SeleniumBase,mdmintz/seleniumspot,possoumous/Watchers,ktp420/SeleniumBase,ktp420/SeleniumBase,mdmintz/SeleniumBase,possoumous/Watchers,possoumous/Watchers,ktp420/SeleniumBase,mdmintz/SeleniumBase,mdmintz/seleniumspot,mdmintz/SeleniumBase,possoumous/Watchers,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,se...
--- +++ @@ -4,11 +4,11 @@ class MyTestClass(BaseCase): - @decorators.rate_limited(4) # The arg is max calls per second + @decorators.rate_limited(3.5) # The arg is max calls per second def print_item(self, item): print item def test_rate_limited_printing(self): print "\nRunn...
50f577e63fe58531447dc0bc2eed80859d3aa1ad
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create script to save documentation to a file
4: Create script to save documentation to a file Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/4
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
--- +++ @@ -14,11 +14,5 @@ import ibmcnx.functions -ds = AdminConfig.list('DataSource') - -dsArray = ds.splitlines() -test = AdminControl.getPropertiesForDataSource(dsArray[0]) - -print dsArray -print '\n' -print test +t1 = ibmcnx.functions.getDSId( db ) +AdminConfig.list( t1 )
6d25dcdb5eaca6d0d0404b4104017a18076174f8
mass/utils.py
mass/utils.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Helper functions. """ # built-in modules import json # local modules from mass.input_handler import InputHandler from mass.scheduler.swf import config def submit(job, protocol=None, priority=1): """Submit mass job to SWF with specific priority. """ impo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Helper functions. """ # built-in modules import json # local modules from mass.exception import UnsupportedScheduler from mass.input_handler import InputHandler from mass.scheduler.swf import config def submit(job, protocol=None, priority=1, scheduler='swf'): "...
Raise UnsupportedScheduler if specific scheduler for submit is not supported (Now just swf is supported).
Raise UnsupportedScheduler if specific scheduler for submit is not supported (Now just swf is supported).
Python
apache-2.0
KKBOX/mass,badboy99tw/mass,KKBOX/mass,badboy99tw/mass,badboy99tw/mass,KKBOX/mass
--- +++ @@ -8,13 +8,16 @@ import json # local modules +from mass.exception import UnsupportedScheduler from mass.input_handler import InputHandler from mass.scheduler.swf import config -def submit(job, protocol=None, priority=1): +def submit(job, protocol=None, priority=1, scheduler='swf'): """Submit m...
adb265a57baed6a94f83ba13f88342313ad78566
tests/adapter.py
tests/adapter.py
"""adapter Mock storage adapter class for unit tests """ class MockStorageAdapter: """Mock storage adapter class. Will be patched for testing purposes """ def store_entry(self, entry): """Mock store_entry""" pass def store_response(self, response): """Mock store_response"...
"""adapter Mock storage adapter class for unit tests """ class MockStorageAdapter: """Mock storage adapter class. Will be patched for testing purposes """ def store_entry(self, entry: dict): """Mock store_entry""" pass def store_response(self, response: dict): """Mock sto...
Add type annotations to MockStorageAdapter methods
Add type annotations to MockStorageAdapter methods
Python
mit
tjmcginnis/tmj
--- +++ @@ -8,11 +8,11 @@ Will be patched for testing purposes """ - def store_entry(self, entry): + def store_entry(self, entry: dict): """Mock store_entry""" pass - def store_response(self, response): + def store_response(self, response: dict): """Mock store_resp...
915001e0e46fef2cf1e6b1c78614d0254b9db21e
backoff/_wait_gen.py
backoff/_wait_gen.py
# coding:utf-8 import itertools def expo(base=2, factor=1, max_value=None): """Generator for exponential decay. Args: base: The mathematical base of the exponentiation operation factor: Factor to multiply the exponentation by. max_value: The maximum value to yield. Once the value in ...
# coding:utf-8 import itertools def expo(base=2, factor=1, max_value=None): """Generator for exponential decay. Args: base: The mathematical base of the exponentiation operation factor: Factor to multiply the exponentiation by. max_value: The maximum value to yield. Once the value in...
Fix spelling of exponential in pydoc
Fix spelling of exponential in pydoc
Python
mit
litl/backoff
--- +++ @@ -8,7 +8,7 @@ Args: base: The mathematical base of the exponentiation operation - factor: Factor to multiply the exponentation by. + factor: Factor to multiply the exponentiation by. max_value: The maximum value to yield. Once the value in the true expone...
32126085f361489bb5c9c18972479b0c313c7d10
bash_runner/tasks.py
bash_runner/tasks.py
""" Cloudify plugin for running a simple bash script. Operations: start: Run a script """ from celery import task from cosmo.events import send_event as send_riemann_event from cloudify.utils import get_local_ip get_ip = get_local_ip send_event = send_riemann_event @task def start(__cloudify_id, port=8080, **...
""" Cloudify plugin for running a simple bash script. Operations: start: Run a script """ from celery import task from cosmo.events import send_event as send_riemann_event from cloudify.utils import get_local_ip get_ip = get_local_ip send_event = send_riemann_event @task def start(__cloudify_id, port=8080, **...
Send the output to a tmp file
Send the output to a tmp file
Python
apache-2.0
rantav/cosmo-plugin-bash-runner
--- +++ @@ -16,5 +16,6 @@ @task def start(__cloudify_id, port=8080, **kwargs): - print 'HELLO BASH! %s' % port + with open('/tmp/HELLO', 'w') as f: + print >> f, 'HELLO BASH! %s' % port send_event(__cloudify_id, get_ip(), "hello_bash status", "state", "running")
7c460a174b1c461c76d08161698ead77e1236f15
redshirt/analyze.py
redshirt/analyze.py
import numpy as np from scipy import ndimage as ndi from skimage.filters import threshold_otsu def _extract_roi(image, axis=-1): max_frame = np.max(image, axis=axis) initial_mask = max_frame > threshold_otsu(max_frame) regions = ndi.label(initial_mask)[0] region_sizes = np.bincount(np.ravel(regions)) ...
import numpy as np from scipy import ndimage as ndi from skimage.filters import threshold_li def _extract_roi(image, axis=-1): max_frame = np.max(image, axis=axis) initial_mask = max_frame > threshold_li(max_frame) regions = ndi.label(initial_mask)[0] region_sizes = np.bincount(np.ravel(regions)) ...
Use Li method for thresholding instead of Otsu
Use Li method for thresholding instead of Otsu
Python
mit
jni/python-redshirt
--- +++ @@ -1,11 +1,11 @@ import numpy as np from scipy import ndimage as ndi -from skimage.filters import threshold_otsu +from skimage.filters import threshold_li def _extract_roi(image, axis=-1): max_frame = np.max(image, axis=axis) - initial_mask = max_frame > threshold_otsu(max_frame) + initial_...
637651e572d9bcd4049ad5351f7fde1869c6823a
onadata/libs/authentication.py
onadata/libs/authentication.py
from django.utils.translation import ugettext as _ from django_digest import HttpDigestAuthenticator from rest_framework.authentication import ( BaseAuthentication, get_authorization_header, BasicAuthentication) from rest_framework.exceptions import AuthenticationFailed class DigestAuthentication(BaseAuthenti...
from django.conf import settings from django.utils.translation import ugettext as _ from django_digest import HttpDigestAuthenticator from rest_framework.authentication import ( BaseAuthentication, get_authorization_header, BasicAuthentication) from rest_framework.exceptions import AuthenticationFailed class ...
Allow HTTP auth during tests
Allow HTTP auth during tests
Python
bsd-2-clause
kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat,kobotoolbox/kobocat
--- +++ @@ -1,3 +1,4 @@ +from django.conf import settings from django.utils.translation import ugettext as _ from django_digest import HttpDigestAuthenticator from rest_framework.authentication import ( @@ -35,7 +36,8 @@ # authenticators user_auth = super(HttpsOnlyBasicAuthentication, self).authe...
c5096a3370ad9b4fff428580e1b3c0c7de1399ce
scripts/set_ports.py
scripts/set_ports.py
#!/usr/bin/env python -B from optparse import OptionParser import inspect import json import os def get_port_mappings(container): script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) container_id = os.popen('cat %s/../containers/%s/host.id' % (script_dir, container)).read().strip...
#!/usr/bin/env python -B from optparse import OptionParser import inspect import json import os container_id=None def get_port_mappings(container): global container_id script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) container_id = os.popen('cat %s/../containers/%s/host.id'...
Set container_id and ext_ip container serf tags.
Set container_id and ext_ip container serf tags.
Python
apache-2.0
johanatan/datt-metadatt,johanatan/datt-metadatt,dattlabs/datt-metadatt,johanatan/datt-metadatt,johanatan/datt-metadatt,dattlabs/datt-metadatt,dattlabs/datt-metadatt,dattlabs/datt-metadatt
--- +++ @@ -5,7 +5,9 @@ import json import os +container_id=None def get_port_mappings(container): + global container_id script_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) container_id = os.popen('cat %s/../containers/%s/host.id' % (script_dir, container)).read().strip(...
aa11d654d59dc604fa71b2e73a56338aff7a23e7
pymake/setup.py
pymake/setup.py
"""cppmake auto-generates a big CMake file from C++ headers """ import setuptools description = "Python Super CMake" setuptools.setup( name='generate_cmake', version='1.8.0', license='MIT', long_description=__doc__, url='https://github.com/jpanikulam/experiments/tree/master/pymake', author='Ja...
"""cppmake auto-generates a big CMake file from C++ headers """ import setuptools description = "Python Super CMake" setuptools.setup( name='generate_cmake', version='1.8.1', license='MIT', long_description=__doc__, url='https://github.com/jpanikulam/experiments/tree/master/pymake', author='Ja...
Update pymake version and post twine
Update pymake version and post twine
Python
mit
jpanikulam/experiments,jpanikulam/experiments,jpanikulam/experiments,jpanikulam/experiments
--- +++ @@ -6,7 +6,7 @@ setuptools.setup( name='generate_cmake', - version='1.8.0', + version='1.8.1', license='MIT', long_description=__doc__, url='https://github.com/jpanikulam/experiments/tree/master/pymake',
2ab41930077dec805388bef4c5c8f67912240709
templation/models.py
templation/models.py
# -*- coding: utf-8 -*- import os.path from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from .settings import DAV_ROOT, PROVIDER_NAME, RESOURCE_MODEL, RESOURCE_ACCESS_MODEL_INITIALIZER class AbstractRes...
# -*- coding: utf-8 -*- import os.path from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from .settings import DAV_ROOT, PROVIDER_NAME, RESOURCE_MODEL, RESOURCE_ACCESS_MODEL_INITIALIZER class AbstractRes...
Initialize folder only at creation
Initialize folder only at creation
Python
bsd-3-clause
qdqmedia/django-templation,qdqmedia/django-templation,qdqmedia/django-templation
--- +++ @@ -37,9 +37,9 @@ # Initialize folders (TODO: copy template) try: os.makedirs(os.path.join(DAV_ROOT, str(instance.resource.id))) + RESOURCE_ACCESS_MODEL_INITIALIZER(instance) except OSError as e: if e.errno != 17: raise - ...
aedabe987e6ce93d61ed7707f0ebdc874b60fa1b
libtmux/__about__.py
libtmux/__about__.py
__title__ = 'libtmux' __package_name__ = 'libtmux' __version__ = '0.8.1' __description__ = 'scripting library / orm for tmux' __email__ = 'tony@git-pull.com' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tmux-python/libtmux' __pypi__ = 'https://pypi.org/project/libtmux/' __license__ = 'MIT' __copyright__...
__title__ = 'libtmux' __package_name__ = 'libtmux' __version__ = '0.8.1' __description__ = 'scripting library / orm for tmux' __email__ = 'tony@git-pull.com' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tmux-python/libtmux' __docs__ = 'https://libtmux.git-pull.com' __tracker__ = 'https://github.com/tmux...
Add docs and issue tracker to metadata
Add docs and issue tracker to metadata
Python
bsd-3-clause
tony/libtmux
--- +++ @@ -5,6 +5,8 @@ __email__ = 'tony@git-pull.com' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tmux-python/libtmux' +__docs__ = 'https://libtmux.git-pull.com' +__tracker__ = 'https://github.com/tmux-python/libtmux/issues' __pypi__ = 'https://pypi.org/project/libtmux/' __license__ = 'MIT' _...
2de494810b73dd69c6b4bb87e87007291309d573
lightstep/util.py
lightstep/util.py
""" Utility functions """ import random import time from . import constants def _service_url_from_hostport(secure, host, port): """ Create an appropriate service URL given the parameters. `secure` should be a bool. """ if secure: protocol = 'https://' else: protocol = 'http://'...
""" Utility functions """ import random import time from . import constants def _service_url_from_hostport(secure, host, port): """ Create an appropriate service URL given the parameters. `secure` should be a bool. """ if secure: protocol = 'https://' else: protocol = 'http://'...
Fix _time_to_micros bug. It was calling time.time() when it should use its own argument.
Fix _time_to_micros bug. It was calling time.time() when it should use its own argument.
Python
mit
lightstephq/lightstep-tracer-python
--- +++ @@ -32,7 +32,7 @@ """ Convert a time.time()-style timestamp to microseconds. """ - return long(round(time.time() * constants.SECONDS_TO_MICRO)) + return long(round(t * constants.SECONDS_TO_MICRO)) def _merge_dicts(*dict_args): """Destructively merges dictionaries, returns None ins...
7278f68b18f8cee3f9a78e1265df0994a23254bc
mamba/__init__.py
mamba/__init__.py
from mamba.loader import describe, context from mamba.hooks import before, after from mamba.decorators import skip __all__ = [describe, context, before, after, skip]
from mamba.loader import describe, context from mamba.hooks import before, after from mamba.decorators import skip __all__ = ['describe', 'context', 'before', 'after', 'skip']
Fix the import all mamba error
Fix the import all mamba error
Python
mit
nestorsalceda/mamba,markng/mamba,alejandrodob/mamba,dex4er/mamba,angelsanz/mamba,jaimegildesagredo/mamba,eferro/mamba
--- +++ @@ -2,4 +2,4 @@ from mamba.hooks import before, after from mamba.decorators import skip -__all__ = [describe, context, before, after, skip] +__all__ = ['describe', 'context', 'before', 'after', 'skip']
ec8d7181be646498717b8efa97dd6770d61f067a
test/viz/test_pca.py
test/viz/test_pca.py
def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', "B1": 'b', "B2": 'b', 'B3': 'b'}) ...
import pytest @pytest.mark.timeout(10) def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data import pandas as pd data = sequana_data("test_pca.csv") df = pd.read_csv(data) df = df.set_index("Id") p = PCA(df, colors={ "A1": 'r', "A2": 'r', 'A3': 'r', ...
Set timeout on pca test
Set timeout on pca test
Python
bsd-3-clause
sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana
--- +++ @@ -1,5 +1,7 @@ +import pytest +@pytest.mark.timeout(10) def test_pca(): from sequana.viz.pca import PCA from sequana import sequana_data
a7ece0bd59b63455d26efbc927df7dc5607ce55b
tests/test_player.py
tests/test_player.py
import unittest from pypoker import Player from pypoker import Table class PlayerTestCase(unittest.TestCase): ''' Tests for the Player class ''' def setUp(self): self.player = Player('usman', 1000, None) def test_player_initialization(self): self.assertEqual([self.player.player_name,...
import unittest from pypoker import Player from pypoker import Table class PlayerTestCase(unittest.TestCase): ''' Tests for the Player class ''' def setUp(self): self.player = Player('usman', 1000, None) self.table = Table(50,100,2,10,100,1000) self.table.add_player('bob',1000)...
Add unit tests for functions call and check and fold for module player
Add unit tests for functions call and check and fold for module player
Python
mit
ueg1990/pypoker
--- +++ @@ -8,18 +8,37 @@ ''' def setUp(self): self.player = Player('usman', 1000, None) + self.table = Table(50,100,2,10,100,1000) + self.table.add_player('bob',1000) + self.table.add_player('jane',1000) + self.table.add_player('dylan',1000) + self.table.add_play...
7bed531fcbc63de25572a6b02fb8b19bd066fa50
test_pearhash.py
test_pearhash.py
import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256)))
import unittest from pearhash import PearsonHasher class TestPearsonHasher(unittest.TestCase): def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256))) def test_two_bytes(self): hasher = PearsonHasher(2) self.assertEqual(hasher.ha...
Add a few trivial tests
Add a few trivial tests
Python
mit
ze-phyr-us/pearhash
--- +++ @@ -8,3 +8,18 @@ def test_table_is_a_permutation_of_range_256(self): hasher = PearsonHasher(2) self.assertEqual(set(hasher.table), set(range(256))) + + + def test_two_bytes(self): + hasher = PearsonHasher(2) + self.assertEqual(hasher.hash(b'ni hao').hexdigest(), '1297') + + + def test_two_bytes_cust...
44de3c76421a2ed4917ac7f2c6798dec631650a8
spacy/tests/regression/test_issue834.py
spacy/tests/regression/test_issue834.py
# coding: utf-8 from __future__ import unicode_literals from io import StringIO import pytest word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510   -1.499184 -0.184280 -0.598371""" @pytest.mark.xfail def test_issue834(en_vocab): f = StringIO(word2vec_...
# coding: utf-8 from __future__ import unicode_literals word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510 \u00A0 -1.499184 -0.184280 -0.598371""" def test_issue834(en_vocab, text_file): """Test that no-break space (U+00A0) is detected as space by th...
Reformat test and use text_file fixture
Reformat test and use text_file fixture
Python
mit
spacy-io/spaCy,raphael0202/spaCy,explosion/spaCy,explosion/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,banglakit/spaCy,spacy-io/spaCy,explosion/spaCy,aikramer2/spaCy,banglakit/spaCy,oroszgy/spaCy.hu,honnibal/spaCy,raphael0202/spaCy,Gregory-Howard/spaCy,banglakit/spaCy,aikramer2/spaCy,recognai/spaCy,spacy-io/spaCy,Gregory-How...
--- +++ @@ -1,17 +1,16 @@ # coding: utf-8 +from __future__ import unicode_literals -from __future__ import unicode_literals -from io import StringIO - -import pytest word2vec_str = """, -0.046107 -0.035951 -0.560418 de -0.648927 -0.400976 -0.527124 . 0.113685 0.439990 -0.634510 -  -1.499184 -0.184280 -0.59837...
042791f62619a4a8694df91dc8d03f0ba4460bc2
mineserver.py
mineserver.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # This is the new base initialization layer for Mineserver. # Always call this instead of server_core.py. from __future__ import print_function from server_core.server import * import sys main(sys.argv[1:])
#!/usr/bin/env python # -*- coding: utf-8 -*- # This is the new base initialization layer for Mineserver. # Always call this instead of server_core/server.py from __future__ import print_function from server_core.server import * import sys main(sys.argv[1:])
Fix a misleading and confusing outdated typo in base layer.
Fix a misleading and confusing outdated typo in base layer.
Python
mit
TiberiumPY/puremine,Armored-Dragon/pymineserver
--- +++ @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # This is the new base initialization layer for Mineserver. -# Always call this instead of server_core.py. +# Always call this instead of server_core/server.py from __future__ import print_function from server_core.server import * import sys
cdbb9e8bcffc4c5ba47791b81782df4a07273b6b
Lib/test/test_file.py
Lib/test/test_file.py
from test_support import TESTFN from UserList import UserList # verify writelines with instance sequence l = UserList(['1', '2']) f = open(TESTFN, 'wb') f.writelines(l) f.close() f = open(TESTFN, 'rb') buf = f.read() f.close() assert buf == '12' # verify writelines with integers f = open(TESTFN, 'wb') try: f.writ...
import os from test_support import TESTFN from UserList import UserList # verify writelines with instance sequence l = UserList(['1', '2']) f = open(TESTFN, 'wb') f.writelines(l) f.close() f = open(TESTFN, 'rb') buf = f.read() f.close() assert buf == '12' # verify writelines with integers f = open(TESTFN, 'wb') try:...
Clean up the temporary file when done with it.
Clean up the temporary file when done with it.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -1,3 +1,5 @@ +import os + from test_support import TESTFN from UserList import UserList @@ -43,3 +45,5 @@ else: print "writelines accepted sequence of non-string objects" f.close() + +os.unlink(TESTFN)
be1904cdbea85fa53b1a324449bd42aab320e185
config/interface.py
config/interface.py
import importlib def get_specifications(name): """Return a datasource specification file according to the following pattern:\n\ datasource_<name>.py where <name> is the datasource identifier (e.g. "fmi", "mch", "bom", etc.) """ datasoruce_name = ".datasource_%s" % name return...
import importlib def get_specifications(name): """Return a datasource specification file according to the following pattern:\n\ datasource_<name>.py where <name> is the datasource identifier (e.g. "fmi", "mch", "bom", etc.) """ datasource_name = ".datasource_%s" % name return...
Correct a typo in variable name
Correct a typo in variable name
Python
bsd-3-clause
pySTEPS/pysteps
--- +++ @@ -8,5 +8,5 @@ where <name> is the datasource identifier (e.g. "fmi", "mch", "bom", etc.) """ - datasoruce_name = ".datasource_%s" % name - return importlib.import_module(datasoruce_name, "config") + datasource_name = ".datasource_%s" % name + return importlib.import_module(datasource...
f89f24c22d2dd3c1bab59083397501238e2d0ba9
sputnik/core.py
sputnik/core.py
import requests import simplejson as json def getbaseurl(service='search', version='1', method='track', format='json'): """Returns the base URL for a Spotify Web API query""" baseurl = "http://ws.spotify.com/{0}/{1}/{2}.{3}" return baseurl.format(service, version, method, format) def sea...
import requests try: import simplejson as json except ImportError: import json def getbaseurl(service='search', version='1', method='track', format='json'): """Returns the base URL for a Spotify Web API query""" baseurl = "http://ws.spotify.com/{0}/{1}/{2}.{3}" return baseurl.forma...
Add json module as fallback for simplejson
Add json module as fallback for simplejson
Python
mit
iconpin/sputnik-python
--- +++ @@ -1,5 +1,8 @@ import requests -import simplejson as json +try: + import simplejson as json +except ImportError: + import json def getbaseurl(service='search', version='1', method='track',
2ba8beb54b6de9fbe68501fa71a878da1426e6cd
tests/conftest.py
tests/conftest.py
import os import pytest from mothership import create_app, settings from mothership import db as _db @pytest.fixture(scope='session') def app(request): app = create_app('mothership.settings.TestConfig') # Establish an application context before running the tests. ctx = app.app_context() ctx.push() ...
import os, sys import pytest """ So PYTHONPATH enviroment variable doesn't have to be set for pytest to find mothership module. """ curdir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(curdir,'..')) from mothership import create_app, settings from mothership import db as _db...
Allow tests to find mothership module
Allow tests to find mothership module
Python
mit
afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership,afl-mothership/afl-mothership
--- +++ @@ -1,5 +1,10 @@ -import os +import os, sys import pytest + +""" So PYTHONPATH enviroment variable doesn't have to + be set for pytest to find mothership module. """ +curdir = os.path.dirname(os.path.realpath(__file__)) +sys.path.insert(0, os.path.join(curdir,'..')) from mothership import create_app, set...
40ae333ab81ae1f4d93f3937306ddd12718b59a8
virtool/processes.py
virtool/processes.py
import virtool.db.processes FIRST_STEPS = { "delete_reference": "delete_indexes", "clone_reference": "copy_otus", "import_reference": "load_file", "remote_reference": "download", "update_remote_reference": "download", "update_software": "", "install_hmms": "" } class ProgressTracker: ...
import virtool.db.processes FIRST_STEPS = { "delete_reference": "delete_indexes", "clone_reference": "copy_otus", "import_reference": "load_file", "remote_reference": "download", "update_remote_reference": "download", "update_software": "download", "install_hmms": "download" } class Progr...
Make download first step for install_software process type
Make download first step for install_software process type
Python
mit
virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool
--- +++ @@ -6,8 +6,8 @@ "import_reference": "load_file", "remote_reference": "download", "update_remote_reference": "download", - "update_software": "", - "install_hmms": "" + "update_software": "download", + "install_hmms": "download" }
6ae84a6e098275cdaac8598695c97403dcb2092e
volttron/__init__.py
volttron/__init__.py
''' Copyright (c) 2013, Battelle Memorial Institute All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions ...
# This is a namespace package; do not add anything else to this file. from pkgutil import extend_path __path__ = extend_path(__path__, __name__)
Make volttron a namespace package.
Make volttron a namespace package.
Python
bsd-2-clause
schandrika/volttron,schandrika/volttron,schandrika/volttron,schandrika/volttron
--- +++ @@ -1,52 +1,3 @@ -''' -Copyright (c) 2013, Battelle Memorial Institute -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright ...
7c12d7f8e5fcd4cc328e109e0bdde9e62b4706f7
parse_tweets.py
parse_tweets.py
# Requires pandas and matplotlib to be installed, e.g. # # `sudo apt-get install pandas-python` import json import re import pandas as pd import matplotlib.pyplot as plt tweets_data_path = './twitter_data.txt' tweets_data = [] tweets_file = open(tweets_data_path, "r") for line in tweets_file: try: t...
# Requires pandas and matplotlib to be installed, e.g. # # `sudo apt-get install pandas-python` import json import re import pandas as pd import matplotlib.pyplot as plt import sys tweets_data_path = './twitter_data.txt' tweets_data = [] tweets_file = open(tweets_data_path, "r") for line in tweets_file: try...
Add next part of parser, and fix errors in earlier part arising from incomplete data items
Add next part of parser, and fix errors in earlier part arising from incomplete data items
Python
mit
0x7df/twitter2pocket
--- +++ @@ -6,6 +6,7 @@ import re import pandas as pd import matplotlib.pyplot as plt +import sys tweets_data_path = './twitter_data.txt' @@ -21,3 +22,52 @@ print len(tweets_data) +tweets = pd.DataFrame() + + +def getData(tweet, key): + try: + txt = tweet[key] + except: + return '' + ...
9cfdb35fb1f645eda99d28085b093ee36dd14625
processors/closure_compiler.py
processors/closure_compiler.py
from collections import OrderedDict import os import StringIO from django.conf import settings from django.utils.encoding import smart_str from ..base import Processor from django.core.exceptions import ImproperlyConfigured class ClosureCompiler(Processor): def modify_expected_output_filenames(self, filenames): ...
from collections import OrderedDict import os import StringIO from django.conf import settings from django.utils.encoding import smart_str from ..base import Processor from django.core.exceptions import ImproperlyConfigured class ClosureCompiler(Processor): def modify_expected_output_filenames(self, filenames): ...
Use the ECMASCRIPT5_STRICT flag otherwise AngularJS dies
Use the ECMASCRIPT5_STRICT flag otherwise AngularJS dies
Python
bsd-2-clause
potatolondon/assetpipe
--- +++ @@ -24,7 +24,7 @@ try: for filename, contents in inputs.items(): cmd = Popen([ - 'java', '-jar', compressor], + 'java', '-jar', compressor, "--language_in", "ECMASCRIPT5_STRICT"], stdin=PIPE, stdout=PIPE, stderr=...
9452c8d4bebcb8466cda82d272c04bd9abe7f91d
tests/test_app.py
tests/test_app.py
import flask_testing import logging import unittest import urllib import server logging.disable(logging.CRITICAL) class TestIndex(unittest.TestCase): def test_index_returns_greeting(self): self.assertEquals(server.index(), 'Hello World') class TestLiveIndex(flask_testing.LiveServerTestCase): def c...
import flask_testing import logging import unittest import urllib import server logging.disable(logging.CRITICAL) class TestIndex(unittest.TestCase): def test_index_returns_greeting(self): self.assertEqual(server.index(), 'Hello World') class TestLiveIndex(flask_testing.LiveServerTestCase): def cr...
Change assertEquals to assertEqual due to deprecation warnings
Change assertEquals to assertEqual due to deprecation warnings
Python
mit
Laspimon/transact,Laspimon/transact
--- +++ @@ -10,7 +10,7 @@ class TestIndex(unittest.TestCase): def test_index_returns_greeting(self): - self.assertEquals(server.index(), 'Hello World') + self.assertEqual(server.index(), 'Hello World') class TestLiveIndex(flask_testing.LiveServerTestCase): @@ -23,7 +23,7 @@ def test_...
84342312ab663b1d7c9a9ac5e09811c2ed636fb4
site_scons/utils.py
site_scons/utils.py
import os import os.path from os.path import join as pjoin def download_file(source, target): return 'wget %s -O %s' % (source, target) def get_file_list(base_path, include_list = None, exclude_list = None): if not isinstance(include_list, (list, tuple)): include_list = [ include_list ] if not exclude_list...
import os import os.path import hashlib from os.path import join as pjoin def download_file(source, target): return 'wget %s -O %s' % (source, target) def get_file_list(base_path, include_list = None, exclude_list = None): if not isinstance(include_list, (list, tuple)): include_list = [ include_list ] if n...
Add some more utility functions.
Add some more utility functions.
Python
apache-2.0
cloudkick/cast,cloudkick/cast,cloudkick/cast,cloudkick/cast
--- +++ @@ -1,5 +1,6 @@ import os import os.path +import hashlib from os.path import join as pjoin def download_file(source, target): @@ -33,3 +34,26 @@ files.append(file_path) return files + +def file_sum(file_path, hash_type='md5'): + if hash not in [ 'sha1', 'md5' ]: + raise ValueError('Inv...
38d2aceecf485e59af4e66be711d7d0f12086c06
twinsies/clock.py
twinsies/clock.py
from apscheduler.schedulers.blocking import BlockingScheduler from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins, update_status) from memory_profiler import profile sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=16) @profile def twinsy_finder(fetch_size=10000): ...
from apscheduler.schedulers.blocking import BlockingScheduler from twinsies.twitter import (random_trend_query, fetch_tweets, dig_for_twins, update_status) from memory_profiler import profile sched = BlockingScheduler() @sched.scheduled_job('interval', minutes=16) @profile def twinsy_finder(fetch_size=10000): ...
Remove del fetched_tweets (now a generator)
Remove del fetched_tweets (now a generator)
Python
mit
kkwteh/twinyewest
--- +++ @@ -13,7 +13,6 @@ print("Running twinsy finder...") fetched_tweets = fetch_tweets('Kanye', fetch_size=fetch_size) tweets = dig_for_twins(fetched_tweets) - del fetched_tweets if tweets: print("Twins found, updating status.") update_status(tweets)
caa96562fb65dfdedc37f6efc463701e8b22d410
zipview/views.py
zipview/views.py
import zipfile from django.views.generic import View from django.http import HttpResponse from django.core.files.base import ContentFile from django.utils.six import b class BaseZipView(View): """A base view to zip and stream several files.""" http_method_names = ['get'] zipfile_name = 'download.zip' ...
import zipfile from django.views.generic import View from django.http import HttpResponse from django.core.files.base import ContentFile class BaseZipView(View): """A base view to zip and stream several files.""" http_method_names = ['get'] zipfile_name = 'download.zip' def get_files(self): ...
Remove obsolete python2 unicode helpers
Remove obsolete python2 unicode helpers
Python
mit
thibault/django-zipview
--- +++ @@ -3,7 +3,6 @@ from django.views.generic import View from django.http import HttpResponse from django.core.files.base import ContentFile -from django.utils.six import b class BaseZipView(View): @@ -20,7 +19,7 @@ return self.zipfile_name def get(self, request, *args, **kwargs): - ...
1e006b5df70303b743cb2fd7d6c2a5ef4234f70b
zazo/__init__.py
zazo/__init__.py
"""An Extensible Dependency Resolver written in Python """ __version__ = "0.1.0.dev0"
"""An Extensible Dependency Resolver written in Python """ __version__ = "0.0.0a2"
Switch to an alpha version
Switch to an alpha version
Python
mit
pradyunsg/zazo,pradyunsg/zazo
--- +++ @@ -1,4 +1,4 @@ """An Extensible Dependency Resolver written in Python """ -__version__ = "0.1.0.dev0" +__version__ = "0.0.0a2"
fd819ff0ff1a7d73dd58f152d2c4be8aea18e2d3
rebulk/processors.py
rebulk/processors.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Processor functions """ def conflict_prefer_longer(matches): """ Remove shorter matches if they conflicts with longer ones :param matches: :type matches: rebulk.match.Matches :param context: :type context: :return: :rtype: list[rebulk....
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Processor functions """ def conflict_prefer_longer(matches): """ Remove shorter matches if they conflicts with longer ones :param matches: :type matches: rebulk.match.Matches :param context: :type context: :return: :rtype: list[rebulk....
Fix issue when a private match is found multiple times
Fix issue when a private match is found multiple times
Python
mit
Toilal/rebulk
--- +++ @@ -45,12 +45,8 @@ :return: :rtype: """ - to_remove_matches = set() - for match in matches: + for match in list(matches): if match.private: - to_remove_matches.add(match) - - for match in list(to_remove_matches): - matches.remove(match) + matche...
7366e84afdc93b68278b64bc9ddfac08901cb032
python/peacock/tests/postprocessor_tab/gold/TestPostprocessorPluginManager_test_script.py
python/peacock/tests/postprocessor_tab/gold/TestPostprocessorPluginManager_test_script.py
#* This file is part of the MOOSE framework #* https://www.mooseframework.org #* #* All rights reserved, see COPYRIGHT for full restrictions #* https://github.com/idaholab/moose/blob/master/COPYRIGHT #* #* Licensed under LGPL 2.1, please see LICENSE for details #* https://www.gnu.org/licenses/lgpl-2.1.html """ python ...
""" python TestPostprocessorPluginManager_test_script.py """ import matplotlib.pyplot as plt import mooseutils # Create Figure and Axes figure = plt.figure(facecolor='white') axes0 = figure.add_subplot(111) axes1 = axes0.twinx() # Read Postprocessor Data data = mooseutils.PostprocessorReader('../input/white_elephant_...
Remove header from gold script file
Remove header from gold script file
Python
lgpl-2.1
milljm/moose,YaqiWang/moose,nuclear-wizard/moose,bwspenc/moose,sapitts/moose,idaholab/moose,idaholab/moose,jessecarterMOOSE/moose,permcody/moose,nuclear-wizard/moose,milljm/moose,lindsayad/moose,laagesen/moose,idaholab/moose,andrsd/moose,milljm/moose,SudiptaBiswas/moose,dschwen/moose,permcody/moose,lindsayad/moose,sapi...
--- +++ @@ -1,12 +1,3 @@ -#* This file is part of the MOOSE framework -#* https://www.mooseframework.org -#* -#* All rights reserved, see COPYRIGHT for full restrictions -#* https://github.com/idaholab/moose/blob/master/COPYRIGHT -#* -#* Licensed under LGPL 2.1, please see LICENSE for details -#* https://www.gnu.org/...
ae5b93c4e12f732a8c56de80b39f227c90ef4809
polls/models.py
polls/models.py
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=140) published_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'published_at' def __str__(self): return self.question_text class Choice(models.Model): ...
from django.db import models class Question(models.Model): question_text = models.CharField(max_length=140) published_at = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'published_at' ordering = ('-published_at',) def __str__(self): return self.question_...
Order questions by published date
Order questions by published date Closes #23
Python
mit
apiaryio/polls-api
--- +++ @@ -7,6 +7,7 @@ class Meta: get_latest_by = 'published_at' + ordering = ('-published_at',) def __str__(self): return self.question_text
10e3c7b8dbc4befa2533de1a07f1f7827b961f81
rejected/__init__.py
rejected/__init__.py
""" Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon """ import logging # Add NullHandler to prevent logging warnings logging.getLogger(__name__).addHandler(logging.NullHandler()) from rejected.consumer import ( Consumer, ConsumerException, MessageException, ProcessingException,...
""" Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon """ import logging # Add NullHandler to prevent logging warnings logging.getLogger(__name__).addHandler(logging.NullHandler()) from rejected.consumer import ( # noqa: E402 Consumer, ConsumerException, MessageException, Proces...
Fix noqa location, bump version
Fix noqa location, bump version
Python
bsd-3-clause
gmr/rejected,gmr/rejected
--- +++ @@ -7,18 +7,18 @@ # Add NullHandler to prevent logging warnings logging.getLogger(__name__).addHandler(logging.NullHandler()) -from rejected.consumer import ( +from rejected.consumer import ( # noqa: E402 Consumer, ConsumerException, MessageException, ProcessingException, Publish...
c3d20f0f394063abe7e149d9de41aa3ac0ab91f1
knowit/rules/alternative.py
knowit/rules/alternative.py
from knowit.rule import Rule class AlternativeRule(Rule): """Alternative rule.""" def __init__(self, name, prop_name: str, **kwargs): super().__init__(name, **kwargs) self.prop_name = prop_name def execute(self, props, pv_props, context): """Execute the rule against properties....
from knowit.rule import Rule class AlternativeRule(Rule): """Alternative rule.""" def __init__(self, name, prop_name: str, **kwargs): super().__init__(name, **kwargs) self.prop_name = prop_name def execute(self, props, pv_props, context): """Execute the rule against properties."...
Fix multiple spaces after ','
Fix multiple spaces after ','
Python
mit
ratoaq2/knowit
--- +++ @@ -5,7 +5,7 @@ class AlternativeRule(Rule): """Alternative rule.""" - def __init__(self, name, prop_name: str, **kwargs): + def __init__(self, name, prop_name: str, **kwargs): super().__init__(name, **kwargs) self.prop_name = prop_name
c9491f47e1fc98e0a6aadf9bf379f21112768332
platformio/builder/scripts/windows_x86.py
platformio/builder/scripts/windows_x86.py
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. """ Builder for Windows x86 """ from SCons.Script import AlwaysBuild, Default, DefaultEnvironment from platformio.util import get_systype env = DefaultEnvironment() env.Replace( SIZEPRINTCMD="size $SOURCES", PROGSUFFIX=".exe" ) ...
# Copyright (C) Ivan Kravets <me@ikravets.com> # See LICENSE for details. """ Builder for Windows x86 """ from SCons.Script import AlwaysBuild, Default, DefaultEnvironment from platformio.util import get_systype env = DefaultEnvironment() env.Replace( AR="$_MINGWPREFIX-ar", AS="$_MINGWPREFIX-as", ...
Add support for mingw-linux toolchains
Add support for mingw-linux toolchains
Python
apache-2.0
ZachMassia/platformio,platformio/platformio-core,mseroczynski/platformio,eiginn/platformio,valeros/platformio,mcanthony/platformio,platformio/platformio,dkuku/platformio,platformio/platformio-core,atyenoria/platformio,mplewis/platformio
--- +++ @@ -13,20 +13,25 @@ env = DefaultEnvironment() env.Replace( - SIZEPRINTCMD="size $SOURCES", + AR="$_MINGWPREFIX-ar", + AS="$_MINGWPREFIX-as", + CC="$_MINGWPREFIX-gcc", + CXX="$_MINGWPREFIX-g++", + OBJCOPY="$_MINGWPREFIX-objcopy", + RANLIB="$_MINGWPREFIX-ranlib", + SIZETOOL="$_MINGW...
e4ae1bae94eb2afd5ea851d4ce6528f81c46c32d
pebble/PblCommand.py
pebble/PblCommand.py
import os class PblCommand: name = '' help = '' def run(args): pass def configure_subparser(self, parser): parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)') def sdk_path(self, args): """ Tries to guess the location of the Pe...
import os class PblCommand: name = '' help = '' def run(args): pass def configure_subparser(self, parser): parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)') parser.add_argument('--debug', action='store_true', help = 'Ena...
Allow user to enter pebble <cmd> --debug as well as pebble --debug <cmd>
Allow user to enter pebble <cmd> --debug as well as pebble --debug <cmd>
Python
mit
pebble/libpebble,pebble/libpebble,pebble/libpebble,pebble/libpebble
--- +++ @@ -9,6 +9,8 @@ def configure_subparser(self, parser): parser.add_argument('--sdk', help='Path to Pebble SDK (ie: ~/pebble-dev/PebbleSDK-2.X/)') + parser.add_argument('--debug', action='store_true', + help = 'Enable debugging output') def sdk_path(self, args): ...
a17933c7806634391137244e2c17327898187146
djstripe/__init__.py
djstripe/__init__.py
""" .. module:: djstripe. :synopsis: dj-stripe - Django + Stripe Made Easy """ from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources from . import checks # noqa: Register the checks __version__ = pkg_resources.require("dj-stripe")[0].version
""" .. module:: djstripe. :synopsis: dj-stripe - Django + Stripe Made Easy """ from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources import stripe from . import checks # noqa: Register the checks __version__ = pkg_resources.require("dj-stripe")[0].version # Se...
Set dj-stripe as stripe app info
Set dj-stripe as stripe app info https://stripe.com/docs/building-plugins#setappinfo
Python
mit
pydanny/dj-stripe,pydanny/dj-stripe,jleclanche/dj-stripe,dj-stripe/dj-stripe,kavdev/dj-stripe,jleclanche/dj-stripe,dj-stripe/dj-stripe,kavdev/dj-stripe
--- +++ @@ -5,7 +5,19 @@ """ from __future__ import absolute_import, division, print_function, unicode_literals import pkg_resources + +import stripe + from . import checks # noqa: Register the checks __version__ = pkg_resources.require("dj-stripe")[0].version + + +# Set app info +# https://stripe.com/docs/...
26d2e13945f4780ff74dfe99695be7045fb9ed39
piper/prop.py
piper/prop.py
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dicti...
import facter from collections import MutableMapping from piper.abc import DynamicItem class PropBase(DynamicItem): def __init__(self): super(PropBase, self).__init__(None) self._props = None @property def properties(self): """ Collect system properties and return a dicti...
Add PropBase.flatten() support for flattening lists
Add PropBase.flatten() support for flattening lists
Python
mit
thiderman/piper
--- +++ @@ -31,6 +31,11 @@ if isinstance(v, MutableMapping): items.extend(self.flatten(v, new_key).items()) + elif isinstance(v, list): + # Make lists have keys like 'foo.bar.x' + for x, item in enumerate(v): + key = '{2}{0}{1...
6c7ca64fbd93ab52dfc1ba792fd314395483d651
piazza_api/piazza.py
piazza_api/piazza.py
class Piazza(object): """Unofficial Client for Piazza's Internal API""" def __init__(self): pass
from .rpc import PiazzaRPC class Piazza(object): """Unofficial Client for Piazza's Internal API""" def __init__(self): self._rpc_api = None def user_login(self, email=None, password=None): """Login with email, password and get back a session cookie :type email: str :para...
Add login methods to Piazza
feat(user): Add login methods to Piazza
Python
mit
hfaran/piazza-api,kwangkim/piazza-api
--- +++ @@ -1,4 +1,41 @@ +from .rpc import PiazzaRPC + + class Piazza(object): """Unofficial Client for Piazza's Internal API""" def __init__(self): + self._rpc_api = None + + def user_login(self, email=None, password=None): + """Login with email, password and get back a session cookie + +...