commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
eb9e2c3217ff0f19a28fc49b2fa5f14d295f32e2
app/views.py
app/views.py
from flask import render_template, jsonify, request from app import app from app import evolver @app.route('/') @app.route('/index') def index(): return render_template('index.html') def format_transcriptions(transcriptions): '''Split the raw string of transcriptions into the correct tuple rules.''' ...
from flask import render_template, jsonify, request from app import app from app import evolver @app.route('/') @app.route('/index') def index(): return render_template('index.html') def format_transcriptions(transcriptions): '''Split the raw string of transcriptions into the correct tuple rules.''' ...
Fix bug when transcriptions are empty
Fix bug when transcriptions are empty
Python
mit
kdelwat/LangEvolve,kdelwat/LangEvolve,kdelwat/LangEvolve
87bdef439a3faf465bb8c23166beeb8a142400f7
fapistrano/plugins/curl.py
fapistrano/plugins/curl.py
# -*- coding: utf-8 -*- from fabric.api import cd, env, run from .. import signal, configuration def init(): configuration.setdefault('curl_url', '') configuration.setdefault('curl_options', '') signal.register('deploy.updating', download_artifact) def download_artifact(**kwargs): with cd(env.release...
# -*- coding: utf-8 -*- from fabric.api import cd, env, run from .. import signal, configuration def init(): configuration.setdefault('curl_url', '') configuration.setdefault('curl_options', '') configuration.setdefault('curl_extract_tar', '') configuration.setdefault('curl_postinstall_script', '') ...
Add extract_tar and post_install_script option.
Add extract_tar and post_install_script option.
Python
mit
liwushuo/fapistrano
83e147ca35cbdc70a5b3e3e374a14a3ad4efdd17
vumi_http_api/__init__.py
vumi_http_api/__init__.py
from .vumi_api import VumiApiWorker __all__ = ['VumiApiWorker']
from .vumi_api import VumiApiWorker __version__ = "0.0.1a" __all__ = ['VumiApiWorker']
Add __version__ to vumi_http_api package.
Add __version__ to vumi_http_api package.
Python
bsd-3-clause
praekelt/vumi-http-api,praekelt/vumi-http-api
bd3cb20453d044882fc476e55e2aade8c5c81ea7
2/ConfNEP.py
2/ConfNEP.py
"""A custom ILAMB confrontation for net ecosystem productivity (nep).""" import os import numpy as np from ILAMB.Confrontation import Confrontation from ILAMB.Variable import Variable from ILAMB.ilamblib import MakeComparable class ConfNEP(Confrontation): """Confront ``nep`` model outputs with ``nee`` observation...
"""A custom ILAMB confrontation for net ecosystem productivity (nep).""" import os import numpy as np from ILAMB.Confrontation import Confrontation from ILAMB.Variable import Variable from ILAMB.ilamblib import MakeComparable class ConfNEP(Confrontation): """Confront ``nep`` model outputs with ``nee`` observation...
Remove call to _checkRegions method
Remove call to _checkRegions method At one point it was a method of the super (I believe), but it's no longer there.
Python
mit
permamodel/ILAMB-experiments
528759e6ba579de185616190e3e514938989a54e
tests/console/asciimatics/widgets/testcheckbox.py
tests/console/asciimatics/widgets/testcheckbox.py
from scriptcore.testing.testcase import TestCase from scriptcore.console.asciimatics.widgets.checkbox import CheckBox from asciimatics.widgets import CheckBox as ACheckBox class TestCheckBox(TestCase): def test_checkbox(self): """ Test the checkbox :return: void """ c...
from scriptcore.testing.testcase import TestCase from scriptcore.console.asciimatics.widgets.checkbox import CheckBox from asciimatics.widgets import CheckBox as ACheckBox class TestCheckBox(TestCase): def test_checkbox(self): """ Test the checkbox :return: void """ c...
Check if checkbox value has updated.
Check if checkbox value has updated.
Python
apache-2.0
LowieHuyghe/script-core
d6b4024d502e189e67d9027a50e472b7c295a83f
misc/migrate_miro_vhs.py
misc/migrate_miro_vhs.py
#!/usr/bin/env python # -*- encoding: utf-8 import boto3 def get_existing_records(dynamodb_client): """ Generates existing Miro records from the SourceData table. """ paginator = dynamodb_client.get_paginator('scan') for page in paginator.paginate(TableName='SourceData'): for item in page...
#!/usr/bin/env python # -*- encoding: utf-8 import boto3 OLD_TABLE = 'SourceData' OLD_BUCKET = 'wellcomecollection-vhs-sourcedata' NEW_TABLE = 'wellcomecollection-vhs-sourcedata-miro' NEW_BUCKET = 'wellcomecollection-vhs-sourcedata-miro' def get_existing_records(dynamodb_client): """ Generates existing Mi...
Copy the S3 object into the new bucket
Copy the S3 object into the new bucket
Python
mit
wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api,wellcometrust/platform-api
df0d950747d80024f962216f17f2d3f967e4363b
source/hostel_huptainer/environment.py
source/hostel_huptainer/environment.py
"""Inspects dictionary for desired keys and stores for later usage.""" from hostel_huptainer.errors import InputError class Environment(object): """Searches ``environment`` for expected variables and stores them.""" def __init__(self, environment): self.hostname = environment.get('CERTBOT_HOSTNAME')...
"""Inspects dictionary for desired keys and stores for later usage.""" from hostel_huptainer.errors import InputError class Environment(object): """Searches ``environment`` for expected variables and stores them.""" def __init__(self, environment): self.hostname = environment.get('CERTBOT_HOSTNAME')...
Decrease line length for pycodestyle compliance
Decrease line length for pycodestyle compliance A line exceeded 75 characters in length.
Python
apache-2.0
Jitsusama/hostel-huptainer
7a7de7b7a44180f4ea3b6d5b3334ce406eb72b38
discussion/migrations/0002_discussionthread_updated.py
discussion/migrations/0002_discussionthread_updated.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('discussion', '0001_initial'), ] operations = [ migrations.AddField( ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.utils import timezone class Migration(migrations.Migration): dependencies = [ ('discussion', '0001_initial'), ] operations = [ migrations.AddField( model_name...
Fix because we're not timezone aware.
Fix because we're not timezone aware.
Python
mit
btomaszewski/webdoctor-server
bab10c6a1e9c8548fe778817595aa18baa5e3cdb
account_fiscal_position_no_source_tax/account.py
account_fiscal_position_no_source_tax/account.py
from openerp import models, api, fields class account_fiscal_position(models.Model): _inherit = 'account.fiscal.position' @api.v7 def map_tax(self, cr, uid, fposition_id, taxes, context=None): result = super(account_fiscal_position, self).map_tax( cr, uid, fposition_id, taxes, contex...
from openerp import models, api, fields class account_fiscal_position(models.Model): _inherit = 'account.fiscal.position' @api.v7 def map_tax(self, cr, uid, fposition_id, taxes, context=None): result = super(account_fiscal_position, self).map_tax( cr, uid, fposition_id, taxes, contex...
FIX fiscal position no source tax
FIX fiscal position no source tax
Python
agpl-3.0
csrocha/account_journal_payment_subtype,csrocha/account_voucher_payline
5dec1db567ef7c2b6ea1cca3ddd02612cb9f7d8a
Lib/encodings/bz2_codec.py
Lib/encodings/bz2_codec.py
""" Python 'bz2_codec' Codec - bz2 compression encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Adapted by Raymond Hettinger from zlib_codec.py which was written by Marc-Andre Lemburg (mal@lemburg.com). """ import ...
""" Python 'bz2_codec' Codec - bz2 compression encoding Unlike most of the other codecs which target Unicode, this codec will return Python string objects for both encode and decode. Adapted by Raymond Hettinger from zlib_codec.py which was written by Marc-Andre Lemburg (mal@lemburg.com). """ import ...
Revert previous change. MAL preferred the old version.
Revert previous change. MAL preferred the old version.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
cc29f43a351f1e0418edaceb830e5b189d31b3ad
script/lib/config.py
script/lib/config.py
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '5d5539f8232bb4d0253438216de11a99159b3c4d' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[...
#!/usr/bin/env python import platform import sys NODE_VERSION = 'v0.11.13' BASE_URL = 'https://gh-contractor-zcbenz.s3.amazonaws.com/libchromiumcontent' LIBCHROMIUMCONTENT_COMMIT = '99d263cbd842ba57331ddb975aad742470a4cff4' ARCH = { 'cygwin': '32bit', 'darwin': '64bit', 'linux2': platform.architecture()[...
Update libchromiumcontent to fix shared workers.
win: Update libchromiumcontent to fix shared workers.
Python
mit
tinydew4/electron,mattotodd/electron,fritx/electron,kcrt/electron,RobertJGabriel/electron,lzpfmh/electron,sshiting/electron,leethomas/electron,fomojola/electron,Gerhut/electron,subblue/electron,dahal/electron,posix4e/electron,jsutcodes/electron,thingsinjars/electron,subblue/electron,Jacobichou/electron,aichingm/electro...
e0a34d86837b6d1e1a9d740fbc5f0b8e2a2ee4b1
Lib/email/__init__.py
Lib/email/__init__.py
# Copyright (C) 2001 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """A package for parsing, handling, and generating email messages. """ __version__ = '1.0' __all__ = ['Encoders', 'Errors', 'Generator', 'Image', 'Iterators', 'MIMEBase', ...
# Copyright (C) 2001 Python Software Foundation # Author: barry@zope.com (Barry Warsaw) """A package for parsing, handling, and generating email messages. """ __version__ = '1.0' __all__ = ['Encoders', 'Errors', 'Generator', 'Iterators', 'MIMEAudio', 'MIMEBase',...
Fix __all__ to the current list of exported modules (must pass the tests in test_email.py).
Fix __all__ to the current list of exported modules (must pass the tests in test_email.py).
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
36ce36541bbd6512feaaf8e385bcfa7e11251281
infcommon/yaml_reader/factory.py
infcommon/yaml_reader/factory.py
# -*- coding: utf-8 -*- from infcommon.factory import Factory from infcommon.yaml_reader.yaml_reader import YamlReader def yaml_reader(path=None): return Factory.instance('yaml_reader', lambda: YamlReader(path))
# -*- coding: utf-8 -*- import os from infcommon.factory import Factory from infcommon.yaml_reader.yaml_reader import YamlReader DEFAULT_PATH_ENVIRONMENT_VARIABLE_NAME = 'CONF_FILE' def yaml_reader(path=None): path = path or os.environ[DEFAULT_PATH_ENVIRONMENT_VARIABLE_NAME] return Factory.instance('yaml_...
Use environment variable with deafult path when no path given
[FEATURE] Use environment variable with deafult path when no path given
Python
mit
aleasoluciones/infcommon,aleasoluciones/infcommon
ebc5831cf8cd3a87c6d663c28afb94a952f4e42f
mint/scripts/db2db/migrate.py
mint/scripts/db2db/migrate.py
#!/usr/bin/python # # Copyright (c) 2009 rPath, Inc. # # All rights reserved. # import logging from conary import dbstore from mint.scripts.db2db import db2db log = logging.getLogger(__name__) def switchToPostgres(cfg): if cfg.dbDriver in ('postgresql', 'pgpool'): return sourceTuple = (cfg.dbDrive...
#!/usr/bin/python # # Copyright (c) 2009 rPath, Inc. # # All rights reserved. # import logging from conary import dbstore from mint.scripts.db2db import db2db log = logging.getLogger(__name__) def switchToPostgres(cfg): if cfg.dbDriver in ('postgresql', 'pgpool'): return sourceTuple = (cfg.dbDrive...
Fix another use of the rbuilder postgres user
Fix another use of the rbuilder postgres user
Python
apache-2.0
sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint
9a3d8a96ed9cf0d1d1f002bf324d57b099ddde0f
gateway/utils/testfinder.py
gateway/utils/testfinder.py
import os import unittest from gateway.utils.resourcelocator import ResourceLocator from unittest import TestLoader TEST_PATH = "tests" verbosity = 1 test_loader = unittest.defaultTestLoader def find_test_modules(test_modules=None): test_locator = ResourceLocator.get_locator(TEST_PATH) test_suite = test_lo...
import os import unittest from gateway.utils.resourcelocator import ResourceLocator from unittest import TestLoader TEST_PATH = "tests" verbosity = 1 test_loader = unittest.defaultTestLoader def find_test_modules(test_modules=None): test_locator = ResourceLocator.get_locator(TEST_PATH) test_suite = test_load...
Add documentation Clean duplicate code remove unused code
Add documentation Clean duplicate code remove unused code
Python
mit
aceofwings/Evt-Gateway,aceofwings/Evt-Gateway
bf89baf003bace5b48bcf8421a0548c7e1fd73a0
viper/interpreter/value.py
viper/interpreter/value.py
from .environment import Environment from viper.parser.ast.nodes import Expr class Value: pass class TupleVal(Value): def __init__(self, *vals: Value): self.vals = list(vals) def __repr__(self) -> str: return f"TupleVal({', '.join(map(str, self.vals))})" class NumVal(Value): def ...
from .environment import Environment from viper.parser.ast.nodes import AST, Parameter from typing import List class Value: pass class TupleVal(Value): def __init__(self, *vals: Value): self.vals = list(vals) def __repr__(self) -> str: return f"TupleVal({', '.join(map(str, self.vals))...
Update CloVal to allow for specifying multiple parameters
Update CloVal to allow for specifying multiple parameters
Python
apache-2.0
pdarragh/Viper
312bb90415218398ddbe9250cfe7dbc4bb013e14
opal/core/lookuplists.py
opal/core/lookuplists.py
""" OPAL Lookuplists """ from django.contrib.contenttypes.fields import GenericRelation from django.db import models # class LookupList(models.Model): # class Meta: # abstract = True class LookupList(models.Model): name = models.CharField(max_length=255, unique=True) synonyms = GenericRelation('o...
""" OPAL Lookuplists """ from django.contrib.contenttypes.fields import GenericRelation from django.db import models class LookupList(models.Model): name = models.CharField(max_length=255, unique=True) synonyms = GenericRelation('opal.Synonym') class Meta: ordering = ['name'] abstract = Tr...
Delete commented out old code.
Delete commented out old code.
Python
agpl-3.0
khchine5/opal,khchine5/opal,khchine5/opal
35f286ac175d5480d3dbb7261205f12dd97144bb
checkmail.py
checkmail.py
#!/usr/bin/env python """ Simple Python module to parse a Thunderbird mail file and scan each email message with ClamAV in order to detect suspect messages. """ import pyclamav import os import re import email import argparse import sys import tempfile mail_split_re = re.compile(r'\s(?=From -)') def pr...
#!/usr/bin/env python """ Simple Python module to parse a Thunderbird mail file and scan each email message with ClamAV in order to detect suspect messages. """ import pyclamav import os import email import argparse import sys import tempfile import mailbox def print_message(parsed, signature=None): ...
Use the python MBox class rather than parsing the mailbox manually
Use the python MBox class rather than parsing the mailbox manually
Python
mit
DanSearle/CheckMail
842cfc631949831053f4310f586e7b2a83ff7cde
notifications_utils/timezones.py
notifications_utils/timezones.py
from datetime import datetime import pytz from dateutil import parser local_timezone = pytz.timezone("Europe/London") def utc_string_to_aware_gmt_datetime(date): """ Date can either be a string or a naive datetime """ if not isinstance(date, datetime): date = parser.parse(date) forced_u...
from datetime import datetime import pytz from dateutil import parser local_timezone = pytz.timezone("Europe/London") def utc_string_to_aware_gmt_datetime(date): """ Date can either be a string, naive UTC datetime or an aware UTC datetime Returns an aware London datetime, essentially the time you'd see ...
Add descriptions to timezone functions
Add descriptions to timezone functions These are quite complex things and benefit from having better descriptions. Note, we weren't quite happy with the names of the functions. `aware_gmt_datetime` should really be `aware_london_datetime` and the other two functions could have more verbose names (mentioning that the...
Python
mit
alphagov/notifications-utils
38bf0cba402d3c747584b8aae109c3735d23f6fa
config/settings/__init__.py
config/settings/__init__.py
import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INS...
import os # include settimgs from daiquiri from daiquiri.core.settings import * # include settings from base.py from .base import * # include settings from local.py from .local import * # include 3rd party apps after the daiquiri apps from base.py INSTALLED_APPS = DJANGO_APPS + DAIQUIRI_APPS + ADDITIONAL_APPS + INS...
Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL
Fix prepend BASE_URL for ACCOUNT_LOGOUT_REDIRECT_URL
Python
apache-2.0
aipescience/django-daiquiri-app,aipescience/django-daiquiri-app
41f254bd53ca6998725c959d9abe71975cffc92f
froide/accesstoken/admin.py
froide/accesstoken/admin.py
from django.contrib import admin from .models import AccessToken class AccessTokenAdmin(admin.ModelAdmin): raw_id_fields = ('user',) admin.site.register(AccessToken, AccessTokenAdmin)
from django.contrib import admin from .models import AccessToken class AccessTokenAdmin(admin.ModelAdmin): raw_id_fields = ('user',) list_filter = ('purpose',) search_fields = ('user__email',) admin.site.register(AccessToken, AccessTokenAdmin)
Add search, filter to access tokens
Add search, filter to access tokens
Python
mit
stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide
38c2f86e8784530efc0234851d3bb9ebbfef58f5
froide/account/api_views.py
froide/account/api_views.py
from rest_framework import serializers, views, permissions, response from oauth2_provider.contrib.rest_framework import TokenHasScope from .models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id',) def to_representation(self, ...
from rest_framework import serializers, views, permissions, response from .models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'private') def to_representation(self, obj): default = super(UserSerializer, self).to_r...
Make logged in user endpoint available w/o token
Make logged in user endpoint available w/o token
Python
mit
stefanw/froide,fin/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide
97db526a655f9723342df3c0c27e7325002c50aa
ovp_users/serializers.py
ovp_users/serializers.py
from django.core.exceptions import ValidationError from django.contrib.auth.password_validation import validate_password from ovp_users import models from rest_framework import serializers class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['id', 'name', 'email'...
from django.core.exceptions import ValidationError from django.contrib.auth.password_validation import validate_password from ovp_users import models from rest_framework import serializers class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = models.User fields = ['id', 'name', 'email'...
Add password as a write_only field on CreateUserSerializer
Add password as a write_only field on CreateUserSerializer
Python
agpl-3.0
OpenVolunteeringPlatform/django-ovp-users,OpenVolunteeringPlatform/django-ovp-users
a0baec4446efb96483d414a11bc71a483ded1d2b
tests/alerts/alert_test_case.py
tests/alerts/alert_test_case.py
import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): def __init__(self, description, events=[], events_type='event', expected_alert=None): self.description = description # As a r...
import os.path import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../../alerts")) from alert_test_suite import AlertTestSuite class AlertTestCase(object): def __init__(self, description, events=[], expected_alert=None): self.description = description # As a result of defining our...
Remove events_type from alert test case
Remove events_type from alert test case
Python
mpl-2.0
mpurzynski/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mozilla/MozDef,mpurzynski/MozDef,jeffbryner/MozDef,mpurzynski/MozDef,mozilla/MozDef,mozilla/MozDef,mozilla/MozDef,jeffbryner/MozDef,jeffbryner/MozDef
5a8348fa634748caf55f1c35e204fda500297157
pywkeeper.py
pywkeeper.py
#!/usr/bin/env python import json import os import optparse import random from crypto import * from file_io import * from settings import * options = None arguments = None def main(): if arguments[0] == 'generate': generate() elif arguments[0] == 'save': save() elif arguments[0] == 'edit'...
#!/usr/bin/env python import json import os import optparse import random from crypto import * from file_io import * from settings import * options = None arguments = None def main(): if arguments[0] == 'generate': generate() elif arguments[0] == 'save': save() elif arguments[0] == 'edit'...
Use optparser for generate length
Use optparser for generate length
Python
unlicense
kvikshaug/pwkeeper
a09491de1278db810c31280405c923c30337deb0
scanblog/scanning/management/commands/fixuploadperms.py
scanblog/scanning/management/commands/fixuploadperms.py
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLO...
import os from django.core.management.base import BaseCommand from django.conf import settings class Command(BaseCommand): args = '' help = "Set all permissions in the uploads directory for deploy." def handle(self, *args, **kwargs): for dirname in (os.path.join(settings.MEDIA_ROOT, settings.UPLO...
Change order of permission changes
Change order of permission changes
Python
agpl-3.0
yourcelf/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,flexpeace/btb,flexpeace/btb,yourcelf/btb,flexpeace/btb,yourcelf/btb
80bdeb25795776bd73b911909863bc54b0afeea4
tree/treeplayer/test/dataframe/dataframe_histograms.py
tree/treeplayer/test/dataframe/dataframe_histograms.py
import unittest import ROOT class HistogramsFromTDF(unittest.TestCase): @classmethod def setUp(cls): ROOT.gRandom.SetSeed(1) def test_histo1D(self): ROOT.gRandom.SetSeed(1) tdf = ROOT.ROOT.Experimental.TDataFrame(64) g = tdf.Define("r","gRandom->Gaus(0,1)") h1Proxy = g.Histo1D(...
import unittest import ROOT class HistogramsFromTDF(unittest.TestCase): @classmethod def setUp(cls): ROOT.gRandom.SetSeed(1) def test_histo1D(self): ROOT.gRandom.SetSeed(1) tdf = ROOT.ROOT.Experimental.TDataFrame(64) g = tdf.Define("r","gRandom->Gaus(0,1)") h1Proxy ...
Replace tabs with spaces in the unit tests.
[TDF] Replace tabs with spaces in the unit tests.
Python
lgpl-2.1
karies/root,root-mirror/root,karies/root,root-mirror/root,root-mirror/root,karies/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,olifre/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,olifre/root,zzxuanyuan/root,root-mirror/root,zzxuanyuan/root,olifre/root,karies/root,karies/root,zzxuanyuan/root,roo...
836551789ee6764f48a1328804c55222acc106b1
lc131_palindrome_partitioning.py
lc131_palindrome_partitioning.py
"""Leetcode 131. Palindrome Partitioning Medium URL: https://leetcode.com/problems/palindrome-partitioning/ Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example: Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] """ ...
"""Leetcode 131. Palindrome Partitioning Medium URL: https://leetcode.com/problems/palindrome-partitioning/ Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s. Example: Input: "aab" Output: [ ["aa","b"], ["a","a","b"] ] """ ...
Use partial for duplicated partial string
Use partial for duplicated partial string
Python
bsd-2-clause
bowen0701/algorithms_data_structures
703861029a2d3a36bbb18ed9e56c55064323478c
account_banking_payment_export/migrations/8.0.0.1.166/pre-migrate.py
account_banking_payment_export/migrations/8.0.0.1.166/pre-migrate.py
# -*- coding: utf-8 -*- ############################################################################## # # This module copyright (C) 2015 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # ...
# -*- coding: utf-8 -*- ############################################################################## # # This module copyright (C) 2015 Therp BV (<http://therp.nl>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # ...
Check if column exists before creating it
[FIX] account_banking_payment_export: Check if column exists before creating it
Python
agpl-3.0
incaser/bank-payment,damdam-s/bank-payment,sergiocorato/bank-payment,Antiun/bank-payment,acsone/bank-payment,damdam-s/bank-payment,CompassionCH/bank-payment,diagramsoftware/bank-payment,sergiocorato/bank-payment,open-synergy/bank-payment,hbrunn/bank-payment,Antiun/bank-payment,CompassionCH/bank-payment
2b8377d968dc336cd344dd4191e24b3c4f76857d
openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py
openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models, OperationalError, connection from openedx.core.djangoapps.content.course_overviews.models import CourseOverview class Migration(migrations.Migration): dependencies = [ ('course_overviews', '0008_rem...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models, connection def table_description(): """Handle Mysql/Pg vs Sqlite""" # django's mysql/pg introspection.get_table_description tries to select * # from table and fails during initial migrations from scra...
Migrate correctly from scratch also
Migrate correctly from scratch also Unfortunately, instrospection.get_table_description runs select * from course_overview_courseoverview, which of course does not exist while django is calculating initial migrations, causing this to fail. Additionally, sqlite does not support information_schema, but does not do a se...
Python
agpl-3.0
Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform
dd646b7573c1e2bb41f60723e02aa6ddf58d59f6
kobo/apps/help/permissions.py
kobo/apps/help/permissions.py
# coding: utf-8 from rest_framework import permissions class InAppMessagePermissions(permissions.BasePermission): def has_permission(self, request, view): if not request.user.is_authenticated: # Deny access to anonymous users return False if request.user.is_superuser: ...
# coding: utf-8 from rest_framework import exceptions, permissions class InAppMessagePermissions(permissions.BasePermission): def has_permission(self, request, view): if not request.user.is_authenticated: # Deny access to anonymous users return False if request.user.is_supe...
Fix Python 2-to-3 bug in in-app messages
Fix Python 2-to-3 bug in in-app messages …so that the permission check for `PATCH`ing `interactions` does not always fail. Fixes #2762
Python
agpl-3.0
kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi,kobotoolbox/kpi
61db23b71aa15d14b8c88e36205c17cc1b01882f
frontends/etiquette_flask/etiquette_flask_prod.py
frontends/etiquette_flask/etiquette_flask_prod.py
''' This file is the WSGI entrypoint for remote / production use. If you are using Gunicorn, for example: gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-" ''' import werkzeug.middleware.proxy_fix import backend backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.w...
''' This file is the WSGI entrypoint for remote / production use. If you are using Gunicorn, for example: gunicorn etiquette_flask_prod:site --bind "0.0.0.0:PORT" --access-logfile "-" ''' import werkzeug.middleware.proxy_fix import backend backend.site.wsgi_app = werkzeug.middleware.proxy_fix.ProxyFix(backend.site.w...
Remove arg create because it will use closest_photodb.
Remove arg create because it will use closest_photodb.
Python
bsd-3-clause
voussoir/etiquette,voussoir/etiquette,voussoir/etiquette
5b7469d573235405f735089e87d3b939b1a5e142
tests/test_quotes.py
tests/test_quotes.py
import wikiquote import unittest class QuotesTest(unittest.TestCase): """ Test wikiquote.quotes() """ def test_disambiguation(self): self.assertRaises(wikiquote.DisambiguationPageException, wikiquote.quotes, 'Matrix') def test_no_such_pa...
import wikiquote import unittest class QuotesTest(unittest.TestCase): """ Test wikiquote.quotes() """ def test_disambiguation(self): self.assertRaises(wikiquote.DisambiguationPageException, wikiquote.quotes, 'Matrix') def test_no_such_pa...
Add test for alternate version of cast credit
Add test for alternate version of cast credit
Python
mit
federicotdn/python-wikiquotes,jakerockland/python-wikiquotes
53c014a5ccff103a89c2b9ff9b5f1f30b5d4f7b0
tests/test_states.py
tests/test_states.py
# coding: utf-8 import pytest from mmvdApp.utils import objective_function from mmvdApp.utils import valid_solution @pytest.mark.utils @pytest.mark.linprog def test_objective_function(states1): """ Test if ``utils.linprog.objective_function`` correctly calculates expected objective function value. """...
# coding: utf-8 import pytest from mmvdApp.utils import objective_function from mmvdApp.utils import valid_solution from mmvdApp.utils import InvalidOrderException @pytest.mark.utils @pytest.mark.linprog def test_objective_function(states1): """ Test if ``utils.linprog.objective_function`` correctly calculate...
Test missing checking for InvalidOrderException raised
Fix: Test missing checking for InvalidOrderException raised
Python
mit
WojciechFocus/MMVD,WojciechFocus/MMVD
c1b600596e49409daf31d20f821f280d0aadf124
emission/net/usercache/formatters/android/motion_activity.py
emission/net/usercache/formatters/android/motion_activity.py
import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata ...
import logging import emission.core.wrapper.motionactivity as ecwa import emission.net.usercache.formatters.common as fc import attrdict as ad def format(entry): formatted_entry = ad.AttrDict() formatted_entry["_id"] = entry["_id"] formatted_entry.user_id = entry.user_id metadata = entry.metadata ...
Support the new google play motion activity format
Support the new google play motion activity format As part of the change to slim down the apk for android, https://github.com/e-mission/e-mission-phone/pull/46, https://github.com/e-mission/e-mission-data-collection/pull/116 we switched from google play version from 8.1.0 to 8.3.0, which is the version that has separa...
Python
bsd-3-clause
yw374cornell/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,e-mission/e-mission-server,shankari/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-...
61c256b11897fb7130faadbe2ffa3d02d0863db6
scripts/export-tutorial.py
scripts/export-tutorial.py
""" Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their support files in the ../docs/tutorial folder. """ import subprocess import os # Get the list of tutorial notebooks. tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in...
""" Exports tutorial materials written in Jupyter notebooks in the ../notebooks/tutorial folder to RST pages and their support files in the ../docs/tutorial folder. """ import subprocess import os # Get the list of tutorial notebooks. tutorial_notebooks = [f for f in os.listdir("../notebooks/tutorial") if (".ipynb" in...
Remove old criuft. FIx. Partially fix export issue.
Remove old criuft. FIx. Partially fix export issue.
Python
mit
ResidentMario/geoplot
e93151490ea9c96b3856ec2e269552d8b52e0355
lobster/cmssw/__init__.py
lobster/cmssw/__init__.py
from job import JobProvider from publish import publish from jobit import JobitStore from merge import MergeProvider
from job import JobProvider from jobit import JobitStore from merge import MergeProvider from plotting import plot from publish import publish
Add plotting to the default imports of cmssw.
Add plotting to the default imports of cmssw.
Python
mit
matz-e/lobster,matz-e/lobster,matz-e/lobster
efcafd02930d293f780c4d18910c5a732c552c43
scheduler.py
scheduler.py
from apscheduler.schedulers.blocking import BlockingScheduler import logging import warner import archiver import announcer import flagger import os logging.basicConfig() sched = BlockingScheduler() @sched.scheduled_job("cron", hour=4) #@sched.scheduled_job("cron", hour="*", minute="*/10") # for testing def destalina...
from apscheduler.schedulers.blocking import BlockingScheduler import logging import warner import archiver import announcer import flagger import os # When testing changes, set the "TEST_SCHEDULE" envvar to run more often if os.getenv("TEST_SCHEDULE"): schedule_kwargs = {"hour": "*", "minute": "*/10"} else: s...
Switch to a test schedule based on the environment
Switch to a test schedule based on the environment Switching an environment variable and kicking the `clock` process feels like a neater solution than commenting out one line, uncommenting another, and redeploying.
Python
apache-2.0
rossrader/destalinator
a8c8781373e1501ed8a628004904acc465b80dad
rep.py
rep.py
""" The top level of the APL Read-Evaluate-Print loop UNDER DEVELOPMENT This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop. """ import sys def read_evaluate_print (prompt): """ Read input, echo input """ try: while True: p...
""" The top level of the APL Read-Evaluate-Print loop UNDER DEVELOPMENT This version adds trivial apl_quit() and apl_exit() routines to the read-evaluate-print loop. """ import sys def read_evaluate_print (prompt): """ Read input, echo input """ try: while True: p...
Add recognition of )OFF to mean exit gracefully
Add recognition of )OFF to mean exit gracefully
Python
apache-2.0
NewForester/apl-py,NewForester/apl-py
eea9655d6b92c9bfd0276b1173010dad9fa54fa5
api_tests/licenses/views/test_license_detail.py
api_tests/licenses/views/test_license_detail.py
from nose.tools import * # flake8: noqa import functools from tests.base import ApiTestCase from osf.models.licenses import NodeLicense from api.base.settings.defaults import API_BASE class TestLicenseDetail(ApiTestCase): def setUp(self): super(TestLicenseDetail, self).setUp() self.license = Nod...
import pytest import functools from api.base.settings.defaults import API_BASE from osf.models.licenses import NodeLicense @pytest.mark.django_db class TestLicenseDetail: @pytest.fixture() def license(self): return NodeLicense.find()[0] @pytest.fixture() def url_license(self, license): ...
Convert license detail to pytest
Convert license detail to pytest
Python
apache-2.0
caneruguz/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,caneruguz/osf.io,caseyrollins/osf.io,cslzchen/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,Johnetordoff/osf.io,felliott/osf.io,chrisseto/osf.io,mattclark/osf.io,crcresearch/osf.io,felliott/osf.io,binoculars/osf.io,icereval/osf.io,adlius/osf.io...
bd4ee91c964ce7fb506b722d4d93a8af019d4e7c
test/test_future_and_futures.py
test/test_future_and_futures.py
import imp import os import sys from django.test import TestCase from kolibri import dist as kolibri_dist dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase): def test_import_concurrent_py3(self): import concurrent if sys.version_info[0]...
import imp import os import sys # Import from kolibri first to ensure Kolibri's monkey patches are applied. from kolibri import dist as kolibri_dist # noreorder from django.test import TestCase # noreorder dist_dir = os.path.realpath(os.path.dirname(kolibri_dist.__file__)) class FutureAndFuturesTestCase(TestCase...
Fix import order in tests.
Fix import order in tests.
Python
mit
learningequality/kolibri,learningequality/kolibri,learningequality/kolibri,learningequality/kolibri
26f8c6d4cf51c1f479edc512fa8097ad4b8e1059
puppet/modules/commonservices-apache/files/index.py
puppet/modules/commonservices-apache/files/index.py
#!/usr/bin/python import os from string import Template print "Content-Type: text/html" print tmpl = Template(file('index.html.tmpl').read()) target = os.environ['REQUEST_URI'] if target.startswith('/_'): target = '/' + target.lstrip('/').lstrip('_') target = target.replace('%7C', '#', 1) else: target =...
#!/usr/bin/python import os from urllib import unquote from string import Template print "Content-Type: text/html" print tmpl = Template(file('index.html.tmpl').read()) target = os.environ['REQUEST_URI'] if target.startswith('/_'): target = '/' + target.lstrip('/').lstrip('_') target = unquote(target) t...
Fix URL fragment management on Firefox
Fix URL fragment management on Firefox Close Bug: 13 Change-Id: If3e3182e670b4c498043a58f2b5a82cb87560722
Python
apache-2.0
enovance/software-factory,invenfantasy/software-factory,invenfantasy/software-factory,enovance/software-factory,enovance/software-factory,invenfantasy/software-factory,invenfantasy/software-factory,invenfantasy/software-factory,enovance/software-factory,enovance/software-factory
7a552161eab19d24b7b221635e51a915adff0166
templater.py
templater.py
#!/usr/bin/python import string if __name__ == "__main__": import sys template_file = sys.argv[1] with open(template_file) as f: data = f.read() template = string.Template(data) template_mapping = {} for item in sys.argv[2:]: # item is in the following form: KEY=VALUE ...
#!/usr/bin/python import string import os if __name__ == "__main__": from optparse import OptionParser parser = OptionParser() parser.add_option("-t", "--template", dest="template_file", help="Input template file") (options, args) = parser.parse_args() if not os.path.isfil...
Use OptionParser instead of simple sys.argv.
Use OptionParser instead of simple sys.argv.
Python
mit
elecro/strep
462397443770d55617356bf257b021406367b4c2
wluopensource/osl_flatpages/models.py
wluopensource/osl_flatpages/models.py
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(max_length=100) description = models.CharField(max_length=255) markdown_content = models.TextField('content') content = mod...
from django.db import models import markdown class Flatpage(models.Model): page_name = models.CharField(max_length=100, primary_key=True, unique=True) title = models.CharField(blank=True, max_length=100) description = models.CharField(blank=True, max_length=255) markdown_content = models.TextField('con...
Allow blank entries for title and description for flatpages
Allow blank entries for title and description for flatpages
Python
bsd-3-clause
jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website
ba84740e7ba0edd709c9cd076a7dce83a6c91a30
research/mlt_quality_research.py
research/mlt_quality_research.py
#!/usr/bin/env python import pprint from elasticsearch import Elasticsearch '''Inside ipython: [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNa...
#!/usr/bin/env python import pprint from elasticsearch import Elasticsearch '''Inside ipython: [(r['_score'], r['_source']['Header']['En'], r['_source']['UnitTypeDesc'])for r in es.mlt(index='bhp10', doc_type='places', id=71433, mlt_fields=related_fields, search_types=['places','personalities','photoUnits','familyNa...
Add ES search example, similar to Mongo related FTS
Add ES search example, similar to Mongo related FTS
Python
agpl-3.0
Beit-Hatfutsot/dbs-back,Beit-Hatfutsot/dbs-back,Beit-Hatfutsot/dbs-back,Beit-Hatfutsot/dbs-back
182b94f777b1743671b706c939ce14f89c31efca
lint/queue.py
lint/queue.py
from . import persist import time import threading # Map from view_id to threading.Timer objects timers = {} # For compatibility this is a class with unchanged API from SL3. class Daemon: def start(self, callback): self._callback = callback def hit(self, view): assert self._callback, "Queu...
from . import persist import time import threading # Map from view_id to threading.Timer objects timers = {} # For compatibility this is a class with unchanged API from SL3. class Daemon: def start(self, callback): self._callback = callback def hit(self, view): assert self._callback, "Queu...
Remove MIN_DELAY bc a default setting is guaranteed
Remove MIN_DELAY bc a default setting is guaranteed
Python
mit
SublimeLinter/SublimeLinter3,SublimeLinter/SublimeLinter3
e01f8f4a9c9c0329b4d33106ef5589580ce5337d
bluesky/epics_callbacks.py
bluesky/epics_callbacks.py
import epics import asyncio class PVSuspender: """ A class to manage the callback interface between asyincio and pyepics. This will probably be a base class eventually. """ def __init__(self, RE, pv_name, loop=None): if loop is None: loop = asyncio.get_event_loop() ...
import epics import asyncio class PVSuspender: """ A class to manage the callback interface between asyincio and pyepics. This will probably be a base class eventually. """ def __init__(self, RE, pv_name, loop=None): if loop is None: loop = asyncio.get_event_loop() ...
Use the correct Event loop.
FIX: Use the correct Event loop.
Python
bsd-3-clause
ericdill/bluesky,dchabot/bluesky,dchabot/bluesky,ericdill/bluesky,klauer/bluesky,sameera2004/bluesky,klauer/bluesky,sameera2004/bluesky
b0434a28080d59c27a755b70be195c9f3135bf94
mdx_linkify/mdx_linkify.py
mdx_linkify/mdx_linkify.py
import bleach from html5lib.sanitizer import HTMLSanitizer from markdown.postprocessors import Postprocessor from markdown import Extension class MyTokenizer(HTMLSanitizer): def sanitize_token(self, token): return token class LinkifyPostprocessor(Postprocessor): def __init__(self, md, linkify_call...
import bleach from markdown.postprocessors import Postprocessor from markdown import Extension class LinkifyPostprocessor(Postprocessor): def __init__(self, md, linkify_callbacks=[]): super(Postprocessor, self).__init__(md) self._callbacks = linkify_callbacks def run(self, text): tex...
Make compatible with Bleach v2.0 and html5lib v1.0
Make compatible with Bleach v2.0 and html5lib v1.0
Python
mit
daGrevis/mdx_linkify
929997d9d86f93033ef013c586095b59f151bce8
setup.py
setup.py
#!/usr/local/bin/python -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os print 'Checking node.js presence:' if 0 != os.system('node -...
#!/usr/local/bin/python3 -u __author__ = 'Oliver Ratzesberger <https://github.com/fxstein>' __copyright__ = 'Copyright (C) 2015 Oliver Ratzesberger' __license__ = 'Apache License, Version 2.0' # Make sure we have access to SentientHome commons import os print 'Checking node.js presence:' if 0 != os.system('node ...
Add Python 3 requests install
Add Python 3 requests install
Python
apache-2.0
fxstein/SentientHome
27d281ab2c733d80fdf7f3521e250e72341c85b7
setup.py
setup.py
from distutils.core import setup import os f = open("README.rst") try: try: readme_text = f.read() except: readme_text = "" finally: f.close() setup(name="ftptool", version="0.4", url="http://blogg.se", description="Higher-level interface to ftplib", author="Blogg Esse AB", ...
from distutils.core import setup import os readme_fname = os.path.join(os.path.dirname(__file__), "README.rst") readme_text = open(readme_fname).read() setup(name="ftptool", version="0.4", url="http://blogg.se", description="Higher-level interface to ftplib", author="Blogg Esse AB", author_email="open...
Make long description import path agnostic.
Make long description import path agnostic.
Python
bsd-3-clause
bloggse/ftptool
9de760794eac63dd053b9a2ac78072a3648b7752
tests/run.py
tests/run.py
from __future__ import print_function import datetime import os import sys from io import BytesIO from pprint import pprint import requests import voxjar if __name__ == "__main__": metadata = { "identifier": "test_call_identifier", "timestamp": datetime.datetime.now(), "type": { ...
from __future__ import print_function import datetime import os import sys from io import BytesIO from pprint import pprint from uuid import uuid4 import requests import voxjar if __name__ == "__main__": metadata = { "identifier": "test_{}".format(uuid4()), "timestamp": datetime.datetime.now(), ...
Add uuid to identifier in test script
Add uuid to identifier in test script
Python
apache-2.0
platoai/platoai-python,platoai/platoai
ccebabfc39fbb43c7f0f11dae7b5aa288e565788
test_echo.py
test_echo.py
#!/usr/bin/env python import pytest import echo_server import echo_client
#!/usr/bin/env python import pytest import echo_server from threading import Thread import socket def dummy_client(): message = "Christian Bale is a terrible actor." port = 50000 address = '127.0.0.1' client_socket = socket.socket( socket.AF_INET, socket.SOCK_STREAM, socket.IPP...
Add test_connection unit test. This single test seems to cover it.
Add test_connection unit test. This single test seems to cover it.
Python
mit
charlieRode/network_tools
ee6e887bc4be703c0d279baff1fac402c971883b
gitfs/views/index.py
gitfs/views/index.py
import os from errno import ENOENT from stat import S_IFDIR from gitfs import FuseMethodNotImplemented, FuseOSError from .view import View from log import log class IndexView(View): def statfs(self, path): return {} def getattr(self, path, fh=None): ''' Returns a dictionary with ke...
import os from errno import ENOENT from stat import S_IFDIR from gitfs import FuseMethodNotImplemented, FuseOSError from .view import View from log import log class IndexView(View): def statfs(self, path): return {} def getattr(self, path, fh=None): ''' Returns a dictionary with ke...
Remove unused code from IndexView.
Remove unused code from IndexView.
Python
apache-2.0
bussiere/gitfs,PressLabs/gitfs,PressLabs/gitfs,ksmaheshkumar/gitfs,rowhit/gitfs
43fa842244da9d75496ba3ba02517870daca8849
provision/08-create-keystone-stuff.py
provision/08-create-keystone-stuff.py
#!/usr/bin/env python import ConfigParser import requests cp = ConfigParser.SafeConfigParser() cp.read('/etc/keystone/keystone.conf') token = cp.get('DEFAULT', 'admin_token') baseurl = 'http://localhost:35357/v3/OS-FEDERATION' headers = { 'X-Auth-Token': token, 'Content-Type': 'application/json', } with open...
#!/usr/bin/env python import ConfigParser import requests cp = ConfigParser.SafeConfigParser() cp.read('/etc/keystone/keystone.conf') token = cp.get('DEFAULT', 'admin_token') baseurl = 'http://localhost:35357/v3/OS-FEDERATION' headers = { 'X-Auth-Token': token, 'Content-Type': 'application/json', } with open...
Fix paths to json files
Fix paths to json files
Python
apache-2.0
norcams/himlar-connect,norcams/himlar-connect
317eaa7dd37638f233d8968fb55ed596bc2b8502
pycroscopy/io/translators/__init__.py
pycroscopy/io/translators/__init__.py
from . import be_odf from . import be_odf_relaxation from . import beps_ndf from . import general_dynamic_mode from . import gmode_iv from . import gmode_line from . import image from . import ndata_translator from . import numpy_translator from . import oneview from . import ptychography from . import sporc from . imp...
from . import be_odf from . import be_odf_relaxation from . import beps_ndf from . import general_dynamic_mode from . import gmode_iv from . import gmode_line from . import image from . import ndata_translator from . import numpy_translator from . import igor_ibw from . import oneview from . import ptychography from . ...
Add missing import statement for igor translator
Add missing import statement for igor translator
Python
mit
anugrah-saxena/pycroscopy,pycroscopy/pycroscopy
43ea528a1832c94dd7879f995a1c4cc8dfb2a315
pyroonga/tests/functional/conftest.py
pyroonga/tests/functional/conftest.py
# -*- coding: utf-8 -*- import json import os import pytest from pyroonga.odm.table import tablebase, TableBase from pyroonga.tests import utils FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture') FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json') @pytest.fixture def Table(request): cl...
# -*- coding: utf-8 -*- import json import os import pytest from pyroonga.odm.table import tablebase, TableBase from pyroonga.tests import utils FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'fixture') FIXTURE_PATH = os.path.join(FIXTURE_DIR, 'dbfixture%s.json') @pytest.fixture def Table(request): cl...
Fix an issue that tables not be removed in end of each test
Fix an issue that tables not be removed in end of each test
Python
mit
naoina/pyroonga,naoina/pyroonga
c613df26375d205272ecc1ccc6295b292508cc13
PhotoLoader/loader/tests/test_model.py
PhotoLoader/loader/tests/test_model.py
from io import BytesIO from PIL import Image from django.core.files.base import ContentFile from django.db import transaction from django.db.utils import IntegrityError from django.test import TestCase from .factory import PhotoFactory class ModelTest(TestCase): def setUp(self): self.photo = PhotoFactory()...
from io import BytesIO import os from django.core.files.base import ContentFile from django.core.files.storage import default_storage from django.db import transaction from django.db.utils import IntegrityError from django.test import TestCase from PIL import Image from .factory import PhotoFactory class ModelTest(T...
Delete unnecessary file in 'media' folder
Delete unnecessary file in 'media' folder
Python
mit
SerSamgy/PhotoLoader,SerSamgy/PhotoLoader
47f19fec718f8407965487e2d3b993e8dbc7e23b
qregexeditor/api/match_highlighter.py
qregexeditor/api/match_highlighter.py
import re from pyqode.core.qt import QtGui class MatchHighlighter(QtGui.QSyntaxHighlighter): def __init__(self, document): super().__init__(document) self.prog = None self._format = QtGui.QTextCharFormat() self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb'))) def h...
import re from pyqode.core.qt import QtGui class MatchHighlighter(QtGui.QSyntaxHighlighter): def __init__(self, document): super().__init__(document) self.prog = None self._format = QtGui.QTextCharFormat() self._format.setBackground(QtGui.QBrush(QtGui.QColor('#bbfcbb'))) def h...
Fix highlighting when multiple matches
Fix highlighting when multiple matches
Python
mit
ColinDuquesnoy/QRegexEditor
d4e5af537be36bd50405e60fdb46f31b88537916
src/commoner_i/views.py
src/commoner_i/views.py
from django.core.files.storage import default_storage from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django.http import HttpResponse def badge(request, username, size=''): # serve the inactive badge by default filename = 'images/badge/%sinactive.png' % size ...
from django.core.files.storage import default_storage from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from django.http import HttpResponse, Http404 def badge(request, username, size=''): # serve the inactive badge by default filename = 'images/badge/%sinactive.png' %...
Raise a 404 when for FREE profile badge requests
Raise a 404 when for FREE profile badge requests
Python
agpl-3.0
cc-archive/commoner,cc-archive/commoner
ff3ec67192ec144c12cabc7b403f17650c460757
tests/sentry/metrics/test_datadog.py
tests/sentry/metrics/test_datadog.py
from __future__ import absolute_import import socket from mock import patch from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(prefix='sentrytest.') @patch('...
from __future__ import absolute_import from mock import patch from datadog.util.hostname import get_hostname from sentry.metrics.datadog import DatadogMetricsBackend from sentry.testutils import TestCase class DatadogMetricsBackendTest(TestCase): def setUp(self): self.backend = DatadogMetricsBackend(pr...
Test DatadogMetricsBackend against datadog's get_hostname
Test DatadogMetricsBackend against datadog's get_hostname This fixes tests in Travis since the hostname returned is different
Python
bsd-3-clause
ngonzalvez/sentry,korealerts1/sentry,fotinakis/sentry,beeftornado/sentry,ngonzalvez/sentry,gencer/sentry,nicholasserra/sentry,BuildingLink/sentry,JamesMura/sentry,kevinlondon/sentry,jean/sentry,beeftornado/sentry,mvaled/sentry,mvaled/sentry,Natim/sentry,looker/sentry,kevinlondon/sentry,korealerts1/sentry,daevaorn/sentr...
8d02522c276b87f45999281c3aa6a57e19df9c09
src/core/middlewares.py
src/core/middlewares.py
import re from django.conf import settings from django.http import HttpResponseRedirect # Matches things like # /en # /en/ # /en/foo/bar (can be anything after the first trailing slash) # But not # /en-gb # because the fallback language code is not followed immediately by a slash. FALLBACK_PREFIX_PATTERN = r...
import re from django.conf import settings from django.core.urlresolvers import get_script_prefix from django.http import HttpResponseRedirect # Matches things like # /en # /en/ # /en/foo/bar (can be anything after the first trailing slash) # But not # /en-gb # because the fallback language code is not follo...
Prepend script prefix when replacing lang code
Prepend script prefix when replacing lang code
Python
mit
pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016
4489a5ffcd7fee5f6c243e050de5e65ef45a3100
nested_comments/serializers.py
nested_comments/serializers.py
# Third party apps from rest_framework import serializers # Other AstroBin apps from common.api_fields import PKRelatedFieldAcceptNull # This app from .models import NestedComment class NestedCommentSerializer(serializers.ModelSerializer): class Meta: model = NestedComment fields = ( ...
# Third party apps from rest_framework import serializers # Other AstroBin apps from common.api_fields import PKRelatedFieldAcceptNull # This app from .models import NestedComment class NestedCommentSerializer(serializers.ModelSerializer): class Meta: model = NestedComment fields = ( ...
Remove unneded API serializer field that was breaking nested comments
Remove unneded API serializer field that was breaking nested comments
Python
agpl-3.0
astrobin/astrobin,astrobin/astrobin,astrobin/astrobin,astrobin/astrobin
80c192155256aa02f290130f792fc804fb59a4d7
pycat/talk.py
pycat/talk.py
"""Communication link driver.""" import sys import selectors CLIENT_TO_SERVER = object() SERVER_TO_CLIENT = object() def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer): """Run communication, in a loop. Input from `source` is sent on `socket`, and data received on `socket` is forwarded to `si...
"""Communication link driver.""" import sys import select def talk(socket, source=sys.stdin.buffer, sink=sys.stdout.buffer): """Run communication, in a loop. Input from `source` is sent on `socket`, and data received on `socket` is forwarded to `sink`. All file descriptors must be non-blocking. """ ...
Switch to just using `select` directly
Switch to just using `select` directly This is less efficient, but does let use get the "exceptional" cases and handle them more pleasantly.
Python
mit
prophile/pycat
133bddf28eed38273eeb384b152ec35ae861a480
sunpy/__init__.py
sunpy/__init__.py
""" SunPy ===== An open-source Python library for Solar Physics data analysis. Web Links --------- Homepage: http://sunpy.org Documentation: http://docs.sunpy.org/en/stable/ """ from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: ...
""" SunPy ===== An open-source Python library for Solar Physics data analysis. Web Links --------- Homepage: http://sunpy.org Documentation: http://docs.sunpy.org/en/stable/ """ from __future__ import absolute_import try: from .version import version as __version__ except ImportError: __version__ = '' try: ...
Make sure package does not import itself during setup
Make sure package does not import itself during setup
Python
bsd-2-clause
dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy
0dda4e65d4c15e3654cb77298e008d6f2d1f179b
numpy/_array_api/_dtypes.py
numpy/_array_api/_dtypes.py
import numpy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype('int8') int16 = np.dtype('int16') int32 = np.dtype('int32') int64 = np.dtype('int64') uint8 = np.dtype('uint8') uint16 = np.dtype('uint16') uint32 = np.dtype...
import numpy as np # Note: we use dtype objects instead of dtype classes. The spec does not # require any behavior on dtypes other than equality. int8 = np.dtype('int8') int16 = np.dtype('int16') int32 = np.dtype('int32') int64 = np.dtype('int64') uint8 = np.dtype('uint8') uint16 = np.dtype('uint16') uint32 = np.dtype...
Use tuples for internal type lists in the array API
Use tuples for internal type lists in the array API These are easier for type checkers to handle.
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
57280453c222dddff6433e234608e89684e79c93
test_board_pytest.py
test_board_pytest.py
from board import Board def test_constructor(): board = Board(0,0) assert board.boardMatrix.size == 0 assert board.columns == 0 assert board.rows == 0 board = Board(5,5) assert board.boardMatrix.size == 25 assert board.columns == 5 assert board.rows == 5 def test_addPiece(): board...
from board import Board def test_constructor(): board = Board(0,0) assert board.boardMatrix.size == 0 assert board.columns == 0 assert board.rows == 0 board = Board(5,5) assert board.boardMatrix.size == 25 assert board.columns == 5 assert board.rows == 5 def test_addPiece(): board...
Add more tests for addPiece method.
Add more tests for addPiece method.
Python
mit
isaacarvestad/four-in-a-row
0575b4345fc21ca537a95866ff2a24d25128c698
readthedocs/config/find.py
readthedocs/config/find.py
"""Helper functions to search files.""" from __future__ import division, print_function, unicode_literals import os import re def find_all(path, filename_regex): """Find all files in ``path`` that match ``filename_regex`` regex.""" path = os.path.abspath(path) for root, dirs, files in os.walk(path, topd...
"""Helper functions to search files.""" from __future__ import division, print_function, unicode_literals import os import re def find_one(path, filename_regex): """Find the first file in ``path`` that match ``filename_regex`` regex.""" _path = os.path.abspath(path) for filename in os.listdir(_path): ...
Remove logic for iterating directories to search for config file
Remove logic for iterating directories to search for config file
Python
mit
rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org,rtfd/readthedocs.org
09cfd33df218725aa88d2f64d87868056c2778ba
indra/tests/test_biogrid.py
indra/tests/test_biogrid.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from indra.databases import biogrid_client from indra.util import unicode_strs from nose.plugins.attrib import attr @attr('webservice', 'nonpublic') def test_biogrid_request(): results = biogrid_client._send_req...
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str from indra.databases import biogrid_client from indra.util import unicode_strs from nose.plugins.attrib import attr from indra.sources.biogrid import process_file from indra.statements import Complex @attr('webservi...
Add test for downloading and parsing biogrid tsv file
Add test for downloading and parsing biogrid tsv file
Python
bsd-2-clause
johnbachman/belpy,pvtodorov/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,johnbachman/indra,sorgerlab/indra,pvtodorov/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,johnbachman/belpy,bgyori/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra
5da62bbe9df92df58dea742120f4e78555509bd0
lib/log_processor.py
lib/log_processor.py
import re import snmpy class log_processor(snmpy.plugin): def create(self): for k, v in sorted(self.conf['objects'].items()): extra = { 'count': re.compile(v['count']), 'reset': re.compile(v['reset']) if 'reset' in v else None, 'start': int(v['...
import glob import re import snmpy class log_processor(snmpy.plugin): def create(self): for k, v in sorted(self.conf['objects'].items()): extra = { 'count': re.compile(v['count']), 'reset': re.compile(v['reset']) if 'reset' in v else None, 'star...
Support file globbing for log processor since names could be dynamic (based on hostname, etc.).
Support file globbing for log processor since names could be dynamic (based on hostname, etc.).
Python
mit
mk23/snmpy,mk23/snmpy
0d70cc8fb27240390e252881615f740103535c93
testsuite/python3.py
testsuite/python3.py
#!/usr/bin/env python3 from typing import ClassVar, List # Annotated function (Issue #29) def foo(x: int) -> int: return x + 1 # Annotated variables #575 CONST: int = 42 class Class: cls_var: ClassVar[str] def m(self): xs: List[int] = []
#!/usr/bin/env python3 from typing import ClassVar, List # Annotated function (Issue #29) def foo(x: int) -> int: return x + 1 # Annotated variables #575 CONST: int = 42 class Class: cls_var: ClassVar[str] for_var: ClassVar[str] while_var: ClassVar[str] def_var: ClassVar[str] if_var: Class...
Add test when variable with annotation start with a keyword
Add test when variable with annotation start with a keyword
Python
mit
PyCQA/pep8
72064e373e6b13f5847199aeb8116ab1708523b2
astroquery/cadc/tests/setup_package.py
astroquery/cadc/tests/setup_package.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.vot'), os.path.join('data', '*.xml'), o...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import import os # setup paths to the test data # can specify a single file or a list of files def get_package_data(): paths = [os.path.join('data', '*.vot'), os.path.join('data', '*.xml'), o...
Add fits file to package build
Add fits file to package build
Python
bsd-3-clause
imbasimba/astroquery,ceb8/astroquery,ceb8/astroquery,imbasimba/astroquery
1e71dbaa3d82ca757e1e38f114f2153a2d54500e
app/views.py
app/views.py
from flask import Flask, render_template, session, redirect, url_for, flash from app import app, forms, models @app.route('/', methods=['GET', 'POST']) def index(): login_form = forms.LoginForm() if login_form.validate_on_submit(): user = models.User.query.filter_by(username = login_form.username.data)...
from flask import Flask, render_template, session, redirect, url_for, flash from app import app, forms, models, db import datetime @app.route('/', methods=['GET', 'POST']) def index(): login_form = forms.LoginForm() if login_form.validate_on_submit(): user = models.User.query.filter_by(username = login...
Add patient data from the create form to the database.
Add patient data from the create form to the database.
Python
mit
jawrainey/atc,jawrainey/atc
5ab0e32f3a3b49747b6035cee6dcc1002b5075e1
path/program_drive_provider.py
path/program_drive_provider.py
import os from functools import lru_cache from .. import logger # use absolute path because of re-occuraing imports '.' could not work from .program_path_provider import get_cached_program_path @lru_cache(maxsize=None) def get_cached_program_drive(): """Get the value of the #PROGRAMDRIVE# variable""" rainme...
""" This module provides methods for determine the program drive. Rainmeter has an built-in variable called #PROGRAMDRIVE#. With this you can directly route to the drive in which Rainmeter is contained. If by some chance people use @Include on #PROGRAMDRIVE# it is still able to resolve the path and open the include fo...
Add docstring to program drive provider
Add docstring to program drive provider
Python
mit
thatsIch/sublime-rainmeter
d2a024dda2d9032680131b1e8fba38e6bcf0f671
billjobs/tests/tests_user_admin_api.py
billjobs/tests/tests_user_admin_api.py
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin class UserAdminAPI(TestCase): """ Test User Admin API REST endpoint """ ...
from django.test import TestCase from django.contrib.auth.models import User from rest_framework import status from rest_framework.test import APIClient, APIRequestFactory, \ force_authenticate from billjobs.views import UserAdmin, UserAdminDetail class UserAdminAPI(TestCase): """ Test User Admin API REST ...
Add test admin to retrieve a user detail
Add test admin to retrieve a user detail
Python
mit
ioO/billjobs
6ff6bdad9f7544be103e798838c12509411a2098
tests/__init__.py
tests/__init__.py
import logging from unittest import TestCase import datetime from redash import settings settings.DATABASE_CONFIG = { 'name': 'circle_test', 'threadlocals': True } settings.REDIS_URL = "redis://localhost:6379/5" from redash import models, redis_connection logging.getLogger('peewee').setLevel(logging.INFO) ...
import os os.environ['REDASH_REDIS_URL'] = "redis://localhost:6379/5" import logging from unittest import TestCase import datetime from redash import settings settings.DATABASE_CONFIG = { 'name': 'circle_test', 'threadlocals': True } from redash import models, redis_connection logging.getLogger('peewee').se...
Use the correct redis connection in tests
Use the correct redis connection in tests
Python
bsd-2-clause
guaguadev/redash,vishesh92/redash,easytaxibr/redash,guaguadev/redash,pubnative/redash,M32Media/redash,vishesh92/redash,rockwotj/redash,amino-data/redash,pubnative/redash,chriszs/redash,alexanderlz/redash,stefanseifert/redash,vishesh92/redash,hudl/redash,ninneko/redash,easytaxibr/redash,akariv/redash,denisov-vlad/redash...
75d6920503b166efd778a6becf0939fe1d2cbe1f
openprescribing/pipeline/management/commands/fetch_prescribing_data.py
openprescribing/pipeline/management/commands/fetch_prescribing_data.py
import os import requests from bs4 import BeautifulSoup from django.conf import settings from django.core.management import BaseCommand from openprescribing.utils import mkdir_p class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("year", type=int) parser.add_argumen...
import os import requests from django.conf import settings from django.core.management import BaseCommand from openprescribing.utils import mkdir_p class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument("year", type=int) parser.add_argument("month", type=int) def ...
Use BSA's API to get URL of latest prescribing data
Use BSA's API to get URL of latest prescribing data
Python
mit
ebmdatalab/openprescribing,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,annapowellsmith/openpresc,ebmdatalab/openprescribing,ebmdatalab/openprescribing,ebmdatalab/openprescribing
3bb560dc03809238f586f78385deb41bba512ba9
scripts/asgard-deploy.py
scripts/asgard-deploy.py
#!/usr/bin/env python import sys import logging import click import tubular.asgard as asgard logging.basicConfig(stream=sys.stdout, level=logging.INFO) @click.command() @click.option('--ami_id', envvar='AMI_ID', help='The ami-id to deploy', required=True) def deploy(ami_id): try: asgard.deploy(ami_id) ...
#!/usr/bin/env python import sys import logging import click from os import path # Add top-level module path to sys.path before importing tubular code. sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) ) from tubular import asgard logging.basicConfig(stream=sys.stdout, level=logging.INFO) @cl...
Add top-level module path before tubular import.
Add top-level module path before tubular import.
Python
agpl-3.0
eltoncarr/tubular,eltoncarr/tubular
b60b03c5f9ff8b203c309714c06922c2680a244e
tests/test_now.py
tests/test_now.py
# -*- coding: utf-8 -*- import pytest from jinja2 import Environment @pytest.fixture(scope='session') def environment(): return Environment(extensions=['jinja2_time.TimeExtension']) def test_foobar(environment): assert environment
# -*- coding: utf-8 -*- from freezegun import freeze_time from jinja2 import Environment, exceptions import pytest @pytest.fixture(scope='session') def environment(): return Environment(extensions=['jinja2_time.TimeExtension']) def test_tz_is_required(environment): with pytest.raises(exceptions.TemplateSyn...
Implement a test for the extensions default datetime format
Implement a test for the extensions default datetime format
Python
mit
hackebrot/jinja2-time
8237072384204e51bc281de3dcdfd83e9c85df2d
us_ignite/sections/templatetags/sections_tags.py
us_ignite/sections/templatetags/sections_tags.py
from django import template from django.template.loader import render_to_string from us_ignite.sections.models import Sponsor register = template.Library() class RenderingNode(template.Node): def __init__(self, template_name): self.template_name = template_name def render(self, context): ...
from django import template from django.template.loader import render_to_string from us_ignite.sections.models import Sponsor register = template.Library() class RenderingNode(template.Node): def __init__(self, template_name): self.template_name = template_name def render(self, context): ...
Make the request context available in the template.
Make the request context available in the template.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
d78ff232acee51f95af3e815e72d3db32cb90533
apps/privatemsg/management/commands/cleanupprivatemsg.py
apps/privatemsg/management/commands/cleanupprivatemsg.py
""" Management command to cleanup deleted private message database entries. """ from django.core.management.base import NoArgsCommand from apps.privatemsg.models import PrivateMessage class Command(NoArgsCommand): """ A management command which deletes deleted private messages from the database. Calls `...
""" Management command to cleanup deleted private message from database. """ from django.core.management.base import NoArgsCommand from ...models import PrivateMessage class Command(NoArgsCommand): """ A management command which deletes deleted private messages from the database. Calls ``PrivateMessage....
Use relative import and update docstring
Use relative import and update docstring
Python
agpl-3.0
TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker,TamiaLab/carnetdumaker
07b0b608a948e1058aeb40fdfbf5a0425933562d
mcavatar/__init__.py
mcavatar/__init__.py
from redis import Redis from flask import Flask, g app = Flask(__name__) app.config.from_pyfile('config.py') _redis = Redis( host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB'] ) from mcavatar.views.public import public from mcavatar.views.img import img app.register_...
from redis import Redis from flask import Flask, g app = Flask(__name__) app.config.from_pyfile('config.py') _redis = Redis( host=app.config['REDIS_HOST'], port=app.config['REDIS_PORT'], db=app.config['REDIS_DB'] ) from mcavatar.views.public import public from mcavatar.views.img import img app.register_...
Increment total_requests key in redis after each request
Increment total_requests key in redis after each request
Python
mit
joealcorn/MCAvatar
e1a9f02051038270cdf3377c38c650a27bd65507
apps/organizations/middleware.py
apps/organizations/middleware.py
from django.http import Http404 from django.shortcuts import get_object_or_404 from .models import Organization class OrganizationMiddleware(object): def process_request(self, request): subdomain = request.subdomain user = request.user if subdomain is None: request.organizat...
from django.http import Http404 from django.shortcuts import get_object_or_404 from .models import Organization class OrganizationMiddleware(object): def process_request(self, request): subdomain = request.subdomain user = request.user request.organization = None if subdomain is...
Set requestion organization to none
Set requestion organization to none
Python
mit
xobb1t/ddash2013,xobb1t/ddash2013
ee9df63aeaabb4111cea3698a4f0e30b4502e519
test/disable_captcha.py
test/disable_captcha.py
import owebunit import urlparse from wolis_test_case import WolisTestCase class AcpLoginTestCase(WolisTestCase): def test_disable_captcha(self): self.login('morpheus', 'morpheus') self.acp_login('morpheus', 'morpheus') start_url = '/adm/index.php' self.get_with_sid(start_ur...
import owebunit import urlparse from wolis_test_case import WolisTestCase class AcpLoginTestCase(WolisTestCase): def test_disable_captcha(self): self.login('morpheus', 'morpheus') self.acp_login('morpheus', 'morpheus') self.change_acp_knob( link_text='Spambot countermea...
Generalize to allow editing other configuration
Generalize to allow editing other configuration
Python
bsd-2-clause
p/wolis-phpbb,p/wolis-phpbb
d2d6e614bf618428ebd51019b82b6576f2e9c677
bluebottle/activities/effects.py
bluebottle/activities/effects.py
from django.utils.timezone import now from django.utils.translation import ugettext_lazy as _ from bluebottle.fsm.effects import Effect from bluebottle.activities.models import Organizer, OrganizerContribution class CreateOrganizer(Effect): "Create an organizer for the activity" def post_save(self, **kwarg...
from django.utils.timezone import now from django.utils.translation import ugettext_lazy as _ from bluebottle.fsm.effects import Effect from bluebottle.activities.models import Organizer, OrganizerContribution class CreateOrganizer(Effect): "Create an organizer for the activity" display = False def po...
Make sure we can add activities to initiatives in admin
Make sure we can add activities to initiatives in admin
Python
bsd-3-clause
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
d130a926c847f37f039dfff7c14140d933b7a6af
django/website/contacts/tests/test_group_permissions.py
django/website/contacts/tests/test_group_permissions.py
import pytest from django.contrib.auth.models import Permission, Group, ContentType from contacts.group_permissions import GroupPermissions @pytest.mark.django_db def test_add_perms(): g1, _ = Group.objects.get_or_create(name="Test Group 1") g2, _ = Group.objects.get_or_create(name="Test Group 2") any_m...
import pytest from django.contrib.auth.models import Permission, Group, ContentType from django.core.exceptions import ObjectDoesNotExist from contacts.group_permissions import GroupPermissions @pytest.mark.django_db def test_add_perms(): g1, _ = Group.objects.get_or_create(name="Test Group 1") g2, _ = Grou...
Test can't give group non-exsitent permission
Test can't give group non-exsitent permission
Python
agpl-3.0
aptivate/alfie,daniell/kashana,aptivate/alfie,aptivate/kashana,aptivate/alfie,aptivate/alfie,daniell/kashana,daniell/kashana,aptivate/kashana,daniell/kashana,aptivate/kashana,aptivate/kashana
dd444029abd63da594a36f52efbbc72851ac344f
bnw_handlers/command_register.py
bnw_handlers/command_register.py
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * import random import time import bnw_core.bnw_objects as objs def _(s,user): return s from uuid import uuid4 import re @check_arg(name=USER_RE) @defer.inlineCallbacks def cmd_register(request,name=""): """ Регистрация """...
# -*- coding: utf-8 -*- #from twisted.words.xish import domish from base import * import random import time import bnw_core.bnw_objects as objs def _(s,user): return s from uuid import uuid4 import re @check_arg(name=USER_RE) @defer.inlineCallbacks def cmd_register(request,name=""): """ Регистрация """...
Set servicejid setting on register
Set servicejid setting on register
Python
bsd-2-clause
un-def/bnw,stiletto/bnw,stiletto/bnw,stiletto/bnw,ojab/bnw,ojab/bnw,ojab/bnw,un-def/bnw,un-def/bnw,un-def/bnw,stiletto/bnw,ojab/bnw
eda0dc8bdc89e815ff21be91ade9d53f0c13721a
mockito/tests/numpy_test.py
mockito/tests/numpy_test.py
import mockito from mockito import when, patch import numpy as np from . import module def xcompare(a, b): if isinstance(a, mockito.matchers.Matcher): return a.matches(b) return np.array_equal(a, b) class TestEnsureNumpyWorks: def testEnsureNumpyArrayAllowedWhenStubbing(self): array = ...
import mockito from mockito import when, patch import pytest import numpy as np from . import module pytestmark = pytest.mark.usefixtures("unstub") def xcompare(a, b): if isinstance(a, mockito.matchers.Matcher): return a.matches(b) return np.array_equal(a, b) class TestEnsureNumpyWorks: def ...
Make numpy test clearer and ensure unstub
Make numpy test clearer and ensure unstub
Python
mit
kaste/mockito-python
6df1f99592588f68c3aeac4c5808bde3f108be84
owl2csv.py
owl2csv.py
import sys import click import json import csv from rdflib import Graph, Namespace, URIRef def observe_dataset(dataset, query, prefixes): g = Graph() if prefixes: prefixes = json.load(prefixes) for name, url in prefixes.items(): g.bind(name, Namespace(url.strip('<>'))) g.parse(...
import sys import click import json import csv from rdflib import Graph, Namespace, URIRef def observe_dataset(datasets, query, prefixes): g = Graph() if prefixes: prefixes = json.load(prefixes) for name, url in prefixes.items(): g.bind(name, Namespace(url.strip('<>'))) for dat...
Add support for multiple datasets
Add support for multiple datasets
Python
mit
Guhogu/owl2csv
17cad98d95eeb1c5ae2748fbad0621d0ca460e8b
PrettyJson.py
PrettyJson.py
import sublime import sublime_plugin import simplejson as json from simplejson import OrderedDict import decimal s = sublime.load_settings("Pretty JSON.sublime-settings") class PrettyjsonCommand(sublime_plugin.TextCommand): """ Pretty Print JSON """ def run(self, edit): for region in self.view.se...
import sublime import sublime_plugin import PrettyJSON.simplejson as json from PrettyJSON.simplejson import OrderedDict import decimal s = sublime.load_settings("Pretty JSON.sublime-settings") class PrettyjsonCommand(sublime_plugin.TextCommand): """ Pretty Print JSON """ def run(self, edit): for ...
Prepend simplejson import with 'module' name
Prepend simplejson import with 'module' name
Python
mit
dzhibas/SublimePrettyJson
43bae84b1359d56ad150b49b38c2f8d400b05af2
opps/core/cache/managers.py
opps/core/cache/managers.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.core.cache import cache from django.conf import settings class CacheManager(models.Manager): def __cache_key(self, id): return u'{}:{}:{}'.format(settings.CACHE_PREFIX, self.model._meta...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.core.cache import cache from django.conf import settings def _cache_key(model, id): return u'{}:{}:{}'.format(settings.CACHE_PREFIX, model._meta.db_table, id) class ...
Fix cache key set, on core cache
Fix cache key set, on core cache
Python
mit
jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,opps/opps,opps/opps,opps/opps
e3369232014adf29f78975ff102f8e3aec51b81a
corgi/pandas_utils.py
corgi/pandas_utils.py
import math import numpy as np def remove_single_value_columns(df): drop_ix = df.apply(pd.Series.value_counts, normalize=True, axis=0).max() == 1 drop_cols = df.columns[drop_ix] df = df.drop(drop_cols, axis=1) return df def sample(df, sample_percent=2e-...
import math import numpy as np def remove_single_value_columns(df): drop_ix = df.apply(pd.Series.value_counts, normalize=True, axis=0).max() == 1 drop_cols = df.columns[drop_ix] df = df.drop(drop_cols, axis=1) return df
Remove pandas sample utils, these are built into pandas
Remove pandas sample utils, these are built into pandas
Python
mit
log0ymxm/corgi
7f91d84cb7e57332ea843aac35ef9fae0a3023f0
cumulusci/__init__.py
cumulusci/__init__.py
__import__('pkg_resources').declare_namespace('cumulusci') __version__ = '2.0.0-beta56'
import os __import__('pkg_resources').declare_namespace('cumulusci') __version__ = '2.0.0-beta56' __location__ = os.path.dirname(os.path.realpath(__file__))
Add a never changing __location__ attribute to cumulusci to get the root of the cumulusci codebase
Add a never changing __location__ attribute to cumulusci to get the root of the cumulusci codebase
Python
bsd-3-clause
SalesforceFoundation/CumulusCI,e02d96ec16/CumulusCI,SalesforceFoundation/CumulusCI,e02d96ec16/CumulusCI
ca4b4732b4eacb6e1ac0e70bbc384982007d92de
custos/notify/http.py
custos/notify/http.py
import logging import requests from .base import Notifier log = logging.getLogger(__name__) class HTTPNotifier(Notifier): ''' A Notifier that sends http post request to a given url ''' def __init__(self, auth=None, json=True, **kwargs): ''' Create a new HTTPNotifier :param auth: If ...
import logging import requests from .base import Notifier log = logging.getLogger(__name__) class HTTPNotifier(Notifier): ''' A Notifier that sends http post request to a given url ''' def __init__(self, auth=None, json=True, **kwargs): ''' Create a new HTTPNotifier :param auth: If ...
Fix exception handling in HTTPNotifier
Fix exception handling in HTTPNotifier
Python
mit
fact-project/pycustos
2142db8de793382bdfc56de9133b320b5d6f2690
tests/test_vector2_isclose.py
tests/test_vector2_isclose.py
from ppb_vector import Vector2 from utils import vectors from hypothesis import assume, given, note, example from hypothesis.strategies import floats @given(x=vectors(), abs_tol=floats(min_value=0), rel_tol=floats(min_value=0)) def test_isclose_to_self(x, abs_tol, rel_tol): assert x.isclose(x, abs_tol=abs_tol, re...
from ppb_vector import Vector2 from pytest import raises # type: ignore from utils import vectors from hypothesis import assume, given, note, example from hypothesis.strategies import floats @given(x=vectors(), abs_tol=floats(min_value=0), rel_tol=floats(min_value=0)) def test_isclose_to_self(x, abs_tol, rel_tol): ...
Test Vector2.isclose with invalid values
Test Vector2.isclose with invalid values
Python
artistic-2.0
ppb/ppb-vector,ppb/ppb-vector
acbd2db59024f6b6847193329ca5b83ace9f1202
refactor/tests/dnstamper.py
refactor/tests/dnstamper.py
from dns import resolver import gevent import os def lookup(hostname, ns): res = resolver.Resolver(configure=False) res.nameservers = [ns] answer = res.query(hostname) ret = [] for data in answer: ret.append(data.address) return ret def compare_lookups(address): exp = l...
from dns import resolver import gevent import os def lookup(hostname, ns): res = resolver.Resolver(configure=False) res.nameservers = [ns] answer = res.query(hostname) ret = [] for data in answer: ret.append(data.address) return ret def compare_lookups(args): # this is ...
Clean up the DNS test
Clean up the DNS test
Python
bsd-2-clause
0xPoly/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,juga0/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,hackerberry/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmur...
e5c1cccaa08b519a19b6900db1376f2b75113668
admin/urls.py
admin/urls.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from .views import AdminHandler, CubeHandler, ConnectionHandler INCLUDE_URLS = [ (r"/admin", AdminHandler), (r"/admin/connection", ConnectionHandler), (r"/admin/cube/?(?P<slug>[\w-]+)?", CubeHandler), ]
#!/usr/bin/env python # -*- coding: utf-8 -*- from .views import AdminHandler, CubeHandler, ConnectionHandler from .views import ElementHandler INCLUDE_URLS = [ (r"/admin", AdminHandler), (r"/admin/connection", ConnectionHandler), (r"/admin/cube/?(?P<slug>[\w-]+)?", CubeHandler), (r"/admin/element/?(?...
Add Element admin view in admin url
Add Element admin view in admin url
Python
mit
jgabriellima/mining,AndrzejR/mining,mining/mining,mlgruby/mining,seagoat/mining,mlgruby/mining,jgabriellima/mining,mlgruby/mining,avelino/mining,chrisdamba/mining,seagoat/mining,AndrzejR/mining,chrisdamba/mining,avelino/mining,mining/mining
afb97310cba3c32d28f3b21b0895c53183914326
interface.py
interface.py
import npyscreen class App(npyscreen.NPSApp): def main(self): form = npyscreen.FormBaseNew(name='EKOiE') form.add_widget(npyscreen.TitleSelectOne, name='Track number', values=[1, 2, 3, 4, 5]) form.edit() if __name__ == '__main__': app = App() app.run()
from contextlib import contextmanager import os import sys import npyscreen @contextmanager def use_xterm(): """Helper setting proper TERM value Required for colors to work under 16-color tmux. """ old_value = os.environ.get('TERM') os.environ['TERM'] = 'xterm' yield if old_value is not ...
Quit popup, NPSAppManaged and TERM
Quit popup, NPSAppManaged and TERM Main class (App) now extends NPSAppManaged, and forms are added in kosher way. Quit popup is also implemented and available upon pressing `q` key (`Q` key too!). Additionally, application sets TERM env variable to proper value (`xterm`) in order for colors to properly show up under ...
Python
mit
modrzew/ekoie
71b2f82d99ffeda9d9435d279c7512fcbaaf108f
trackpy/tests/test_misc.py
trackpy/tests/test_misc.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import os import unittest import warnings import trackpy import trackpy.diag path, _ = os.path.split(os.path.abspath(__file__)) class DiagTests(unittest.TestCase): def test_performance_report(s...
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import os import unittest import warnings import pims import trackpy import trackpy.diag path, _ = os.path.split(os.path.abspath(__file__)) class DiagTests(unittest.TestCase): def test_performa...
Fix pims warning test under Py3
TST: Fix pims warning test under Py3
Python
bsd-3-clause
daniorerio/trackpy,daniorerio/trackpy
f49276f78b1b303df5fed063e226ee78165baff5
spam_lists/exceptions.py
spam_lists/exceptions.py
# -*- coding: utf-8 -*- ''' This module contains all classes of exceptions raised by the library ''' from __future__ import unicode_literals class SpamListsError(Exception): '''There was an error during testing a url or host''' class SpamListsValueError(SpamListsError, ValueError): '''An inapropriate value ...
# -*- coding: utf-8 -*- ''' This module contains all classes of exceptions raised by the library ''' from __future__ import unicode_literals class SpamListsError(Exception): '''There was an error during testing a url or host''' class SpamListsValueError(SpamListsError, ValueError): '''An inapropriate value ...
Change bases of exception classes extending SpamListsError and ValueError
Change bases of exception classes extending SpamListsError and ValueError This commit removes SpamListsError and ValueError as direct base classes of other exception classes (except SpamListsValueError), and replaces them with SpamListsValueError.
Python
mit
piotr-rusin/spam-lists
b0c2262bb50fb51bcc2f5eadb86b353cc9eb38a3
bin/Bullet.py
bin/Bullet.py
from tkinter import Label import threading class Bullet(Label): def __init__(self, x, y, space): self.space = space self.bullet_timer = 0.01 self.bullet_indicator = "'" self.damage = -100 Label.__init__(self, text=self.bullet_indicator) self.pack() self._x =...
from tkinter import Label import threading class Bullet(Label): def __init__(self, x, y, space): self.space = space self.bullet_timer = 0.01 self.bullet_indicator = "'" self.damage = -100 Label.__init__(self, text=self.bullet_indicator) self.pack() self._x =...
Add bullet hit function to destroy self.
Add bullet hit function to destroy self.
Python
mit
emreeroglu/DummyShip