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
64750693969bda63dae28db0b43eaca09c549ab4
scripts/lib/logger.py
scripts/lib/logger.py
# logger module from datetime import datetime import os logfile = None logbuf = [] def init(analysis_path): global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) use_log_dir = False if use_log_dir: logdir = os.path.join(analysis_path,...
# logger module from datetime import datetime import os logfile = None logbuf = [] def init(analysis_path): global logfile if not os.path.isdir(analysis_path): log("logger: analysis_path missing:", analysis_path) use_log_dir = False if use_log_dir: logdir = os.path.join(analysis_path,...
Add a fancy log mode.
Add a fancy log mode.
Python
mit
UASLab/ImageAnalysis
28d933b351f58fabad464deedb57af55b499b7c8
tag_release.py
tag_release.py
#!/usr/bin/env python import os import sys def main(): if len(sys.argv) != 2: print('Usage: %s version' % sys.argv[0]) os.system('git tag | sort -n | tail -n 1') sys.exit() version = sys.argv[1] with open('floo/version.py', 'r') as fd: version_py = fd.read().split('\n') ...
#!/usr/bin/env python import os import re import sys from distutils.version import StrictVersion def main(): if len(sys.argv) != 2: print('Usage: %s version' % sys.argv[0]) versions = os.popen('git tag').read().split('\n') versions = [v for v in versions if re.match("\\d\\.\\d\\.\\d", v)]...
Tag release script now works with semvers.
Tag release script now works with semvers.
Python
apache-2.0
Floobits/floobits-sublime,Floobits/floobits-sublime
e50b95143ce4a807c434eaa0e6ef38d36f91a77a
pylons/__init__.py
pylons/__init__.py
"""Base objects to be exported for use in Controllers""" # Import pkg_resources first so namespace handling is properly done so the # paste imports work import pkg_resources from paste.registry import StackedObjectProxy from pylons.configuration import config __all__ = ['app_globals', 'cache', 'config', 'request', 'r...
"""Base objects to be exported for use in Controllers""" # Import pkg_resources first so namespace handling is properly done so the # paste imports work import pkg_resources from paste.registry import StackedObjectProxy from pylons.configuration import config from pylons.controllers.util import Request from pylons.con...
Add Request/Response import points for pylons.
Add Request/Response import points for pylons. --HG-- branch : trunk
Python
bsd-3-clause
Pylons/pylons,Pylons/pylons,moreati/pylons,moreati/pylons,Pylons/pylons,moreati/pylons
0519824c537a96474e0501e1ac45f7a626391a31
tests/test_model_object.py
tests/test_model_object.py
# encoding: utf-8 from marathon.models.base import MarathonObject import unittest class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonObjects...
# encoding: utf-8 from marathon.models.base import MarathonObject from marathon.models.base import MarathonResource import unittest class MarathonObjectTest(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonObject defined __eq__ but not __hash__, me...
Add regression test for MarathonResource
Add regression test for MarathonResource
Python
mit
thefactory/marathon-python,thefactory/marathon-python
1e19a78652e8fed32eb6e315fca3346b3bc31044
bamova/bamov2npy.py
bamova/bamov2npy.py
import sys import numpy as np def read_phi(flname, n_steps, n_loci): sampled_phis = np.zeros((n_steps, n_loci)) fl = open(flname) current_iter_idx = 0 # index used for storage last_iter_idx = 0 # index used to identify when we finish a step for ln in fl: cols = ln.strip().split(",") iter_idx = int(cols[0]) ...
import sys import numpy as np def read_phi(flname, n_steps, n_loci): sampled_phis = np.zeros((n_steps, n_loci)) fl = open(flname) current_iter_idx = 0 # index used for storage last_iter_idx = 0 # index used to identify when we finish a step for ln in fl: cols = ln.strip().split(",") iter_idx = int(cols[0]) ...
Fix ordering of parameters to save
Fix ordering of parameters to save
Python
apache-2.0
rnowling/pop-gen-models
3747158af790a38ccfce217426ee5261877e9f0e
project/api/management/commands/seed_database.py
project/api/management/commands/seed_database.py
# Django from django.core.management.base import BaseCommand from api.factories import ( InternationalFactory, ) class Command(BaseCommand): help = "Command to seed database." def handle(self, *args, **options): InternationalFactory()
# Django from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Command to seed database." from api.factories import ( InternationalFactory, ) def handle(self, *args, **options): self.InternationalFactory()
Fix seeding in management command
Fix seeding in management command
Python
bsd-2-clause
barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore,dbinetti/barberscore-django,dbinetti/barberscore
13f78350b42e48bc8195d6ec05c8b4342866d8e3
unit_tests/test_analyse_idynomics.py
unit_tests/test_analyse_idynomics.py
from nose.tools import * from analyse_idynomics import * class TestAnalyseiDynomics: def setUp(self): self.directory = 'test_data' self.analysis = AnalyseiDynomics(self.directory) def test_init(self): assert_is(self.directory, self.analysis.directory)
from nose.tools import * from analyse_idynomics import * from os.path import join, dirname, realpath class TestAnalyseiDynomics: expected_solutes = ['MyAtmos', 'pressure'] expected_species = ['MyBact'] def setUp(self): self.directory = join(dirname(realpath(__file__)), 'test_data') sel...
Add unit tests for solute and species names
Add unit tests for solute and species names
Python
mit
fophillips/pyDynoMiCS
3fb41919ebfd73fe1199e95f7ee9b8fa7557ea18
tests/test_vane.py
tests/test_vane.py
import os import unittest import vane class TestFetch(unittest.TestCase): def test_owm_good_fetch(self): loc = 'New York, NY' w = vane.fetch_weather(loc) self.assertTrue('temperature' in w['current']) self.assertTrue('summary' in w['current']) def test_owm_bad_fetch(self): ...
import os import unittest import vane class TestFetch(unittest.TestCase): def test_owm_good_fetch(self): loc = 'New York, NY' w = vane.fetch_weather(loc) self.assertTrue('temperature' in w['current']) self.assertTrue('summary' in w['current']) def test_owm_bad_fetch(self): ...
Remove geolocation test for now
Remove geolocation test for now Geolocation doesn't always work, and since location is the one absolutely required parameter to get anything useful out of vane, there's no way to gracefully fall back. I'm going to leave the test out until I have time to write a proper one.
Python
bsd-3-clause
trevorparker/vane
78e6cd5fc57c338ac9c61b6e50a5ac4355a5d8b7
json-templates/create-template.py
json-templates/create-template.py
#!/bin/env python import blank_template import json import os import subprocess import sys import tarfile if __name__ == '__main__': # Load template fname = sys.argv[1] template = blank_template.load_template(fname) # Generate ova.xml version = {'hostname': 'golm-2', 'date': '2016-04-29', 'produ...
#!/bin/env python import blank_template import json import os import subprocess import sys import tarfile if __name__ == '__main__': # Load template fname = sys.argv[1] template = blank_template.load_template(fname) # Generate ova.xml version = {'hostname': 'localhost', 'date': '1970-01-01', 'pr...
Use more generic values for version
Use more generic values for version
Python
bsd-2-clause
xenserver/guest-templates,xenserver/guest-templates
842b128dd4fb3b93492578008de0969e85e3039a
qcfractal/alembic/versions/1604623c481a_id_pirmary_key_for_torsion_init_mol.py
qcfractal/alembic/versions/1604623c481a_id_pirmary_key_for_torsion_init_mol.py
"""id(pirmary key) for torsion_init_mol Revision ID: 1604623c481a Revises: fb5bd88ae2f3 Create Date: 2020-07-02 18:42:17.267792 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "1604623c481a" down_revision = "fb5bd88ae2f3" branch_labels = None depends_on = None ...
"""id(pirmary key) for torsion_init_mol Revision ID: 1604623c481a Revises: fb5bd88ae2f3 Create Date: 2020-07-02 18:42:17.267792 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "1604623c481a" down_revision = "fb5bd88ae2f3" branch_labels = None depends_on = None ...
Fix missing table name in alter_table
Fix missing table name in alter_table
Python
bsd-3-clause
psi4/mongo_qcdb,psi4/mongo_qcdb,psi4/DatenQM,psi4/DatenQM
ea0c9a977cdf7611138599c54e28ccc4848f2eb5
troposphere/ivs.py
troposphere/ivs.py
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 25.0.0 from troposphere import Tags from . import AWSObject from .validators import boolean class Channel(AWSOb...
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. # # *** Do not modify - this file is autogenerated *** # Resource specification version: 35.0.0 from troposphere import Tags from . import AWSObject, AWSProperty from .validators import boolean class ...
Update IVS per 2021-04-15 changes
Update IVS per 2021-04-15 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
61b38528b60203003b9595f7ba2204c287dc6970
string/compress.py
string/compress.py
# Compress string using counts of repeated characters def compress_str(str): output = "" curr_char = "" char_count = "" for i in str: if curr_char != str[i]: output = output + curr_char + char_count # add new unique character and its count to our output curr_char = str[i] # move on to the next character ...
# Compress string using counts of repeated characters def compress_str(str): output = "" curr_char = "" char_count = "" for i in str: if curr_char != str[i]: output = output + curr_char + char_count # add new unique character and its count to our output curr_char = str[i] # move on to the next character ...
Add to current count if there is a match
Add to current count if there is a match
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
58f5d541da1e9e234258985b3362967a9c0d7b67
Discord/utilities/errors.py
Discord/utilities/errors.py
from discord.ext.commands.errors import CommandError class NotServerOwner(CommandError): '''Not Server Owner''' pass class VoiceNotConnected(CommandError): '''Voice Not Connected''' pass class PermittedVoiceNotConnected(VoiceNotConnected): '''Permitted, but Voice Not Connected''' pass class NotPermittedVoice...
from discord.ext.commands.errors import CommandError class NotServerOwner(CommandError): '''Not Server Owner''' pass class VoiceNotConnected(CommandError): '''Voice Not Connected''' pass class PermittedVoiceNotConnected(VoiceNotConnected): '''Permitted, but Voice Not Connected''' pass class NotPermittedVoice...
Remove no longer used custom Missing Permissions error
[Discord] Remove no longer used custom Missing Permissions error
Python
mit
Harmon758/Harmonbot,Harmon758/Harmonbot
91ffbe22e56387491775a569e237c4e46495c6a9
nyuki/workflow/tasks/task_selector.py
nyuki/workflow/tasks/task_selector.py
import logging from tukio import Workflow from tukio.task import register from tukio.task.holder import TaskHolder from nyuki.utils.evaluate import ConditionBlock from nyuki.workflow.tasks.utils import generate_schema log = logging.getLogger(__name__) class TaskConditionBlock(ConditionBlock): """ Override...
import logging from tukio import Workflow from tukio.task import register from tukio.task.holder import TaskHolder from nyuki.utils.evaluate import ConditionBlock from nyuki.workflow.tasks.utils import generate_schema log = logging.getLogger(__name__) class TaskConditionBlock(ConditionBlock): """ Override...
Fix an issue with the child-task selector.
Fix an issue with the child-task selector.
Python
apache-2.0
optiflows/nyuki,gdraynz/nyuki,optiflows/nyuki,gdraynz/nyuki
417ffca6a10edc87fc36b1c7c47e7dea36cecd2e
test/test_basic.py
test/test_basic.py
import random import markovify import sys, os HERE = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(HERE, "texts/sherlock.txt")) as f: sherlock = f.read() def test_text_too_small(): text = u"Example phrase. This is another example sentence." text_model = markovify.Text(text) assert...
import random import markovify import sys, os import operator HERE = os.path.dirname(os.path.realpath(__file__)) with open(os.path.join(HERE, "texts/sherlock.txt")) as f: sherlock = f.read() def test_text_too_small(): text = u"Example phrase. This is another example sentence." text_model = markovify.Text(...
Add test for chain-JSON equality
Add test for chain-JSON equality
Python
mit
jsvine/markovify,orf/markovify
db13b52924a96bdfe8e38c20df07b62b6c455aa8
Instanssi/dblog/handlers.py
Instanssi/dblog/handlers.py
# -*- coding: utf-8 -*- from logging import Handler from datetime import datetime class DBLogHandler(Handler, object): def __init__(self): super(DBLogHandler, self).__init__() def emit(self, record): from models import DBLogEntry as _LogEntry entry = _LogEntry() ...
# -*- coding: utf-8 -*- from logging import Handler from datetime import datetime class DBLogHandler(Handler, object): def __init__(self): super(DBLogHandler, self).__init__() def emit(self, record): from models import DBLogEntry as _LogEntry entry = _LogEntry() ...
Allow event saving by id
dblog: Allow event saving by id
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
91b3891078b889db98d3832f0c06e465a86e52ef
django_tenants/staticfiles/storage.py
django_tenants/staticfiles/storage.py
import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implemen...
import os from django.contrib.staticfiles.storage import StaticFilesStorage from django_tenants.files.storages import TenantStorageMixin from django.conf import settings from django.core.exceptions import ImproperlyConfigured class TenantStaticFilesStorage(TenantStorageMixin, StaticFilesStorage): """ Implemen...
Fix regression in path handling of TenantStaticFileStorage.
Fix regression in path handling of TenantStaticFileStorage. Fixes #197.
Python
mit
tomturner/django-tenants,tomturner/django-tenants,tomturner/django-tenants
fccc7b59e742bc887580c91c2c2dbeae2c85caee
wagtailannotatedimage/views.py
wagtailannotatedimage/views.py
from django.http import HttpResponse from wagtail.wagtailimages.models import Filter, Image def get_full_image_url(request, image_id): image = Image.objects.get(id=image_id) if image: filter, _ = Filter.objects.get_or_create(spec='original') orig_rendition = image.get_rendition(filter) ...
from django.http import HttpResponse from django.shortcuts import get_object_or_404 from wagtail.wagtailimages.models import Filter, get_iamge_model Image = get_iamge_model() def get_full_image_url(request, image_id): image = get_object_or_404(Image, id=image_id) if image: filter, _ = Filter.objects....
Allow for custom image models, 404 on image not found intead of error
Allow for custom image models, 404 on image not found intead of error
Python
bsd-3-clause
takeflight/wagtailannotatedimage,takeflight/wagtailannotatedimage,takeflight/wagtailannotatedimage
202fba50c287d3df99b22a4f30a96a3d8d9c8141
tests/test_pypi.py
tests/test_pypi.py
from unittest import TestCase from semantic_release.pypi import upload_to_pypi from . import mock class PypiTests(TestCase): @mock.patch('semantic_release.pypi.run') def test_upload_without_arguments(self, mock_run): upload_to_pypi(username='username', password='password') self.assertEqual( ...
from unittest import TestCase from semantic_release.pypi import upload_to_pypi from . import mock class PypiTests(TestCase): @mock.patch('semantic_release.pypi.run') def test_upload_without_arguments(self, mock_run): upload_to_pypi(username='username', password='password') self.assertEqual( ...
Update test after adding cleaning of dist
test: Update test after adding cleaning of dist
Python
mit
relekang/python-semantic-release,relekang/python-semantic-release
fd2bd48ca9da96e894031f7979798672e1cebdea
tests/test_util.py
tests/test_util.py
# Copyright 2015 0xc0170 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
# Copyright 2015 0xc0170 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
Test util - unicode removal
Test util - unicode removal
Python
apache-2.0
ohagendorf/project_generator,project-generator/project_generator,sarahmarshy/project_generator,0xc0170/project_generator
2423958016d552a6f696b7124454c7b362c84a5f
pylearn2/scripts/dbm/dbm_metrics.py
pylearn2/scripts/dbm/dbm_metrics.py
#!/usr/bin/env python import argparse if __name__ == '__main__': # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", choices=["ais"]) parser.add_argument("model_path", help="path to the pickled DBM model") args = par...
#!/usr/bin/env python import argparse from pylearn2.utils import serial def compute_ais(model): pass if __name__ == '__main__': # Possible metrics metrics = {'ais': compute_ais} # Argument parsing parser = argparse.ArgumentParser() parser.add_argument("metric", help="the desired metric", ...
Make the script recuperate the correct method
Make the script recuperate the correct method
Python
bsd-3-clause
pkainz/pylearn2,KennethPierce/pylearnk,abergeron/pylearn2,alexjc/pylearn2,pombredanne/pylearn2,cosmoharrigan/pylearn2,bartvm/pylearn2,mclaughlin6464/pylearn2,ashhher3/pylearn2,se4u/pylearn2,abergeron/pylearn2,skearnes/pylearn2,lisa-lab/pylearn2,lamblin/pylearn2,fulmicoton/pylearn2,alexjc/pylearn2,matrogers/pylearn2,jam...
9c381721f4b4febef64276a2eb83c5a9169f7b8c
meta-analyze.py
meta-analyze.py
#!/usr/bin/env python import argparse def parsed_command_line(): """Returns an object that results from parsing the command-line for this program argparse.ArgumentParser(...).parse_ags() """ parser = argparse.ArgumentParser( description='Run multiple network snp analysis algorithms'); parse...
#!/usr/bin/env python import argparse class InputFile: """Represents a data in a specified format""" def __init__(self, file_format, path): self.file_format = file_format self.path = path def __repr__(self): return "InputFile('{}','{}')".format(self.file_format, self.path) def pa...
Add input file and converter abstraction
Add input file and converter abstraction
Python
cc0-1.0
NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs,NCBI-Hackathons/Network_SNPs
9a988056944700d6188f6e7164e68dcd35c342d8
databench/analysis.py
databench/analysis.py
"""Analysis module for Databench.""" from flask import Blueprint, render_template import databench.signals LIST_ALL = [] class Analysis(object): """Databench's analysis class. An optional :class:`databench.Signals` instance and :class:`flask.Blueprint` can be dependency-injected, however that should n...
"""Analysis module for Databench.""" from flask import Blueprint, render_template import databench.signals LIST_ALL = [] class Analysis(object): """Databench's analysis class. An optional :class:`databench.Signals` instance and :class:`flask.Blueprint` can be dependency-injected, however that should n...
Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask.
Move the render_index() function out of the constructor and use add_url_rule() instead of the route() decorator to connect it to Flask.
Python
mit
svenkreiss/databench,svenkreiss/databench,svenkreiss/databench,svenkreiss/databench
c23787680c40cc7f871f23e920486d07452d2cf3
traits/__init__.py
traits/__init__.py
from __future__ import absolute_import __version__ = '4.3.0'
from __future__ import absolute_import __version__ = '4.3.0' # Add a NullHandler so 'traits' loggers don't complain when they get used. import logging class NullHandler(logging.Handler): def handle(self, record): pass def emit(self, record): pass def createLock(self): self.loc...
Use a NullHandler for all 'traits' loggers per best practice for logging.
FIX: Use a NullHandler for all 'traits' loggers per best practice for logging.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
667294dcc3b8ab34618ad674c2b6ac8efeec0620
places/admin.py
places/admin.py
from django.contrib.gis import admin from models import Place admin.site.register(Place, admin.OSMGeoAdmin)
from django.contrib.gis import admin from models import Place try: _model_admin = admin.OSMGeoAdmin except AttributeError: _model_admin = admin.ModelAdmin admin.site.register(Place, _model_admin)
Make it possible to run dev server on my desktop.
Make it possible to run dev server on my desktop. While I'm accessing a suitable database remotely, I don't have enough stuff installed locally to have OSMGeoAdmin (no GDAL installed, for example).
Python
bsd-3-clause
MAPC/masshealth,MAPC/masshealth
e8b44733ff44162f4a01de76b66046af23a9c946
tcconfig/_error.py
tcconfig/_error.py
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import class NetworkInterfaceNotFoundError(Exception): """ Exception raised when network interface not found. """ class ModuleNotFoundError(Exception): """ Exception raised...
# encoding: utf-8 """ .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ from __future__ import absolute_import class NetworkInterfaceNotFoundError(Exception): """ Exception raised when network interface not found. """ class ModuleNotFoundError(Exception): """ Exception raised...
Add custom arguments for InvalidParameterError
Add custom arguments for InvalidParameterError
Python
mit
thombashi/tcconfig,thombashi/tcconfig
1dd8e7ddfccd657fde2697fc1e39da7fb9c3548f
alg_insertion_sort.py
alg_insertion_sort.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm.""" for index in range(1, len(a_list)): current_value = a_list[index] position = index while position > 0 and a_list[pos...
from __future__ import absolute_import from __future__ import print_function from __future__ import division def insertion_sort(a_list): """Insertion Sort algortihm. Time complexity: O(n^2). """ for index in range(1, len(a_list)): current_value = a_list[index] position = index ...
Add to doc string: time complexity
Add to doc string: time complexity
Python
bsd-2-clause
bowen0701/algorithms_data_structures
1cbab715a647689aeda4679d7dcf4e60ff9ab5b1
api/webview/models.py
api/webview/models.py
from django.db import models from django_pgjson.fields import JsonField class Document(models.Model): source = models.CharField(max_length=100) docID = models.CharField(max_length=100) providerUpdatedDateTime = models.DateTimeField(null=True) raw = JsonField() normalized = JsonField()
import json import six from requests.structures import CaseInsensitiveDict from django.db import models from django_pgjson.fields import JsonField class Document(models.Model): source = models.CharField(max_length=100) docID = models.CharField(max_length=100) providerUpdatedDateTime = models.DateTimeFi...
Add harvester response model in django ORM
Add harvester response model in django ORM
Python
apache-2.0
felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,mehanig/scrapi,felliott/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,fabianvf/scrapi
d1fd045791ad4d7c3544352faf68361637213f57
product_onepage/templatetags/onepage_tags.py
product_onepage/templatetags/onepage_tags.py
"""Gallery templatetags""" from django.template import Library from django.core.exceptions import ObjectDoesNotExist register = Library() @register.filter(name='divide') def divide(dividend, divisor): return dividend / divisor @register.filter(name='get_language') def get_language(list, language): try: ...
"""Gallery templatetags""" from django.template import Library from django.core.exceptions import ObjectDoesNotExist register = Library() @register.filter(name='divide') def divide(dividend, divisor): return dividend / divisor @register.filter(name='get_language') def get_language(queryset, language): try:...
Fix variable name in get_language tag
Fix variable name in get_language tag
Python
mit
emencia/emencia-product-onepage,emencia/emencia-product-onepage
b5785cbd9586a767b37da2e0c71bcb1fcfed0604
tests/main_test.py
tests/main_test.py
#!/usr/bin/env python3 from libpals.util import ( xor_find_singlechar_key, hamming_distance, fixed_xor ) def test_xor_find_singlechar_key(): input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' ciphertext = bytes.fromhex(input) result = xor_find_singlechar_key(ciphert...
#!/usr/bin/env python3 from libpals.util import ( xor_find_singlechar_key, hamming_distance, fixed_xor, transpose ) def test_xor_find_singlechar_key(): input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' ciphertext = bytes.fromhex(input) result = xor_find_singlec...
Add test for the transpose function.
Add test for the transpose function.
Python
bsd-2-clause
cpach/cryptopals-python3
2cc1f3dc699258fa7a571cde96a434b450bc0cf8
phonenumber_field/formfields.py
phonenumber_field/formfields.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.forms.fields import CharField from django.core.exceptions import ValidationError from phonenumber_field.validators import validate_international_phonenumber from phonenumber_field.phonen...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from django.forms.fields import CharField from django.core.exceptions import ValidationError from phonenumber_field.validators import validate_international_phonenumber from phonenumber_field.phonen...
Support HTML5's input type 'tel'
Support HTML5's input type 'tel'
Python
mit
hovel/django-phonenumber-field,hovel/django-phonenumber-field,stefanfoulis/django-phonenumber-field
21319fc8d22469911c1cbcc41ec7320b1d6141e9
powerline/bindings/i3/powerline-i3.py
powerline/bindings/i3/powerline-i3.py
#!/usr/bin/env python # vim:fileencoding=utf-8:noet from powerline import Powerline from powerline.lib.monotonic import monotonic import sys import time import i3 from threading import Lock name = 'wm' if len( sys.argv ) > 1: name = sys.argv[1] powerline = Powerline(name, renderer_module='i3bgbar') powerline.update...
#!/usr/bin/env python # vim:fileencoding=utf-8:noet from powerline import Powerline from powerline.lib.monotonic import monotonic import sys import time import i3 from threading import Lock name = 'wm' if len( sys.argv ) > 1: name = sys.argv[1] powerline = Powerline(name, renderer_module='i3bgbar') powerline.update...
Use 'with' instead of lock.acquire/release()
Use 'with' instead of lock.acquire/release()
Python
mit
DoctorJellyface/powerline,bartvm/powerline,areteix/powerline,russellb/powerline,seanfisk/powerline,s0undt3ch/powerline,IvanAli/powerline,cyrixhero/powerline,blindFS/powerline,keelerm84/powerline,kenrachynski/powerline,IvanAli/powerline,darac/powerline,xfumihiro/powerline,Liangjianghao/powerline,darac/powerline,QuLogic/...
5a39d00cf39e80a4e9f1ca8bbf0eac767d39f61d
nbgrader/tests/apps/test_nbgrader.py
nbgrader/tests/apps/test_nbgrader.py
import os import sys from .. import run_nbgrader, run_command from .base import BaseTestApp class TestNbGrader(BaseTestApp): def test_help(self): """Does the help display without error?""" run_nbgrader(["--help-all"]) def test_no_subapp(self): """Is the help displayed when no subapp...
import os import sys from .. import run_nbgrader, run_command from .base import BaseTestApp class TestNbGrader(BaseTestApp): def test_help(self): """Does the help display without error?""" run_nbgrader(["--help-all"]) def test_no_subapp(self): """Is the help displayed when no subapp...
Use sys.executable when executing nbgrader
Use sys.executable when executing nbgrader
Python
bsd-3-clause
jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader
5212d6eabf199ed9ddd34bd6fd2b159f7b2e6a02
tviserrys/views.py
tviserrys/views.py
from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import View from django.utils.decorators import method_decorator from django.template import RequestContext, loader from django.core.exceptions import PermissionDenied from django.contrib.auth.decorators import login_required from djan...
from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import View from django.utils.decorators import method_decorator from django.template import RequestContext, loader from django.core.exceptions import PermissionDenied from django.contrib.auth.decorators import login_required from djan...
Add functionality to get latest tviits
Add functionality to get latest tviits
Python
mit
DeWaster/Tviserrys,DeWaster/Tviserrys
409c69dd967f18ef99658ed63d54dc9723f84250
anchorhub/builtin/github/collector.py
anchorhub/builtin/github/collector.py
""" File that initializes a Collector object designed for GitHub style markdown files. """ from anchorhub.collector import Collector from anchorhub.builtin.github.cstrategies import MarkdownATXCollectorStrategy import anchorhub.builtin.github.converter as converter import anchorhub.builtin.github.switches as ghswitche...
""" File that initializes a Collector object designed for GitHub style markdown files. """ from anchorhub.collector import Collector from anchorhub.builtin.github.cstrategies import \ MarkdownATXCollectorStrategy, MarkdownSetextCollectorStrategy import anchorhub.builtin.github.converter as converter import anchorh...
Use Setext strategy in GitHub built in Collector
Use Setext strategy in GitHub built in Collector
Python
apache-2.0
samjabrahams/anchorhub
e9f25dd0c9028613ef7317ad3a8287dc60b9a217
slave/skia_slave_scripts/chromeos_install.py
slave/skia_slave_scripts/chromeos_install.py
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Install all executables, and any runtime resources that are needed by *both* Test and Bench builders. """ from build_step ...
#!/usr/bin/env python # Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Install all executables, and any runtime resources that are needed by *both* Test and Bench builders. """ from build_step ...
Kill running Skia processes in ChromeOS Install step
Kill running Skia processes in ChromeOS Install step (RunBuilders:Test-ChromeOS-Alex-GMA3150-x86-Debug,Test-ChromeOS-Alex-GMA3150-x86-Release,Perf-ChromeOS-Alex-GMA3150-x86-Release) R=rmistry@google.com Review URL: https://codereview.chromium.org/17599009 git-svn-id: 32fc27f4dcfb6c0385cd9719852b95fe6680452d@9748 2b...
Python
bsd-3-clause
google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbo...
182f070c69e59907eeda3c261d833a492af46967
rojak-database/generate_media_data.py
rojak-database/generate_media_data.py
import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}'...
import MySQLdb as mysql from faker import Factory # Open database connection db = mysql.connect('localhost', 'root', 'rojak', 'rojak_database') # Create new db cursor cursor = db.cursor() sql = ''' INSERT INTO `media`(`name`, `website_url`, `logo_url`, `facebookpage_url`, `slogan`) VALUES ('{}', '{}', '{}', '{}'...
Update the default language for the media generator
Update the default language for the media generator
Python
bsd-3-clause
CodeRiderz/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,CodeRiderz/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,bobbypriambodo/rojak,reinarduswindy/rojak,CodeRiderz/rojak,pyk/rojak,pyk/rojak,bobbypriambodo/rojak,pyk/rojak,bobbypriambodo/rojak,rawgni/rojak,bobbypriambodo/rojak,CodeRiderz/rojak,pyk/rojak,pyk/rojak,...
5bc0226fe1ad03495e97dc2933fa17d18cd38bb9
meetup_facebook_bot/models/speaker.py
meetup_facebook_bot/models/speaker.py
from sqlalchemy import Column, BIGINT, String, Integer from meetup_facebook_bot.models.base import Base class Speaker(Base): __tablename__ = 'speakers' id = Column(Integer, primary_key=True, autoincrement=True) page_scoped_id = Column(BIGINT, unique=True) name = Column(String(128), nullable=False) ...
from sqlalchemy import Column, BIGINT, String, Integer from meetup_facebook_bot.models.base import Base class Speaker(Base): __tablename__ = 'speakers' id = Column(Integer, primary_key=True, autoincrement=True) page_scoped_id = Column(BIGINT) name = Column(String(128), nullable=False) token = Col...
Remove uniqueness constraint from page_scoped_id
Remove uniqueness constraint from page_scoped_id
Python
mit
Stark-Mountain/meetup-facebook-bot,Stark-Mountain/meetup-facebook-bot
a87010c4c7ba6c9f1f295c8da688946d149c7fbd
metal/mmtl/glue/make_glue_datasets.py
metal/mmtl/glue/make_glue_datasets.py
import argparse import os import dill from metal.mmtl.glue.glue_datasets import get_glue_dataset def make_datasets(task, bert_version): datasets = {} for split in ["train", "dev", "test"]: datasets[split] = get_glue_dataset(task, split, bert_version, run_spacy=True) return datasets def pickle_...
import argparse import os import dill from metal.mmtl.glue.glue_datasets import get_glue_dataset def make_datasets(task, bert_version): datasets = {} for split in ["train", "dev", "test"]: datasets[split] = get_glue_dataset( task, split, bert_version, max_len=200, run_spacy=True ...
Set max_len default to 200 when making glue datasets
Set max_len default to 200 when making glue datasets
Python
apache-2.0
HazyResearch/metal,HazyResearch/metal
e5bda294e291a2d96b4f703a89128de9ee53a495
src/geelweb/django/editos/models.py
src/geelweb/django/editos/models.py
from django.db import models from geelweb.django.editos import settings class Edito(models.Model): title = models.CharField(max_length=100) link = models.URLField() button_label = models.CharField(max_length=20, default="Go !", Required=False) image = models.FileField(upload_to="editos") ...
from django.db import models from geelweb.django.editos import settings class Edito(models.Model): title = models.CharField(max_length=100) link = models.URLField() button_label = models.CharField(max_length=20, default="Go !", Required=False) image = models.FileField(upload_to="editos") ...
Add date_created and date_updated to editos.Edito model
Add date_created and date_updated to editos.Edito model
Python
mit
geelweb/django-editos,geelweb/django-editos
a292c87137386bfdc7bc09b1f16269fe1c382858
bedrock/mozorg/templatetags/qrcode.py
bedrock/mozorg/templatetags/qrcode.py
from hashlib import sha1 from django.conf import settings import qrcode as qr from django_jinja import library from jinja2 import Markup from qrcode.image.svg import SvgPathImage QR_CACHE_PATH = settings.DATA_PATH.joinpath('qrcode_cache') QR_CACHE_PATH.mkdir(exist_ok=True) @library.global_function def qrcode(data...
from hashlib import sha1 from pathlib import Path import qrcode as qr from django_jinja import library from jinja2 import Markup from qrcode.image.svg import SvgPathImage QR_CACHE_PATH = Path('/tmp/qrcode_cache') QR_CACHE_PATH.mkdir(exist_ok=True) @library.global_function def qrcode(data, box_size=20): name = ...
Move QR Code cache to /tmp
Move QR Code cache to /tmp
Python
mpl-2.0
sylvestre/bedrock,craigcook/bedrock,alexgibson/bedrock,flodolo/bedrock,mozilla/bedrock,mozilla/bedrock,craigcook/bedrock,MichaelKohler/bedrock,MichaelKohler/bedrock,craigcook/bedrock,alexgibson/bedrock,pascalchevrel/bedrock,flodolo/bedrock,pascalchevrel/bedrock,MichaelKohler/bedrock,pascalchevrel/bedrock,alexgibson/bed...
b89115165c55e51e76a533ba4eb9637897319e0a
oidc_provider/management/commands/creatersakey.py
oidc_provider/management/commands/creatersakey.py
from Crypto.PublicKey import RSA from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Randomly generate a new RSA key for the OpenID server' def handle(self, *args, **options): try: key = RSA.generate(1024) f...
from Crypto.PublicKey import RSA from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Randomly generate a new RSA key for the OpenID server' def handle(self, *args, **options): try: key = RSA.generate(1024) f...
Fix use of deprecated Exception.message in Python 3
Fix use of deprecated Exception.message in Python 3
Python
mit
torreco/django-oidc-provider,ByteInternet/django-oidc-provider,wojtek-fliposports/django-oidc-provider,wayward710/django-oidc-provider,bunnyinc/django-oidc-provider,juanifioren/django-oidc-provider,wojtek-fliposports/django-oidc-provider,ByteInternet/django-oidc-provider,torreco/django-oidc-provider,bunnyinc/django-oid...
4de72b4bd349ebf16c0046c4ed9034914c03ffb5
cea/interfaces/dashboard/api/utils.py
cea/interfaces/dashboard/api/utils.py
from flask import current_app import cea.config import cea.inputlocator def deconstruct_parameters(p): params = {'name': p.name, 'type': p.typename, 'value': p.get(), 'help': p.help} if isinstance(p, cea.config.ChoiceParameter): params['choices'] = p._choices if p.typename == 'We...
from flask import current_app import cea.config import cea.inputlocator def deconstruct_parameters(p: cea.config.Parameter): params = {'name': p.name, 'type': p.typename, 'help': p.help} try: params["value"] = p.get() except cea.ConfigError as e: print(e) params["value"] = "" ...
Fix `weather_helper` bug when creating new scenario
Fix `weather_helper` bug when creating new scenario
Python
mit
architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst,architecture-building-systems/CityEnergyAnalyst
a390f3b711df89b2552bf059c89b1fd4f7ab1fa7
towel/templatetags/modelview_list.py
towel/templatetags/modelview_list.py
from django import template from django.db import models from django.utils.safestring import mark_safe register = template.Library() @register.filter def model_row(instance, fields): for name in fields.split(','): f = instance._meta.get_field(name) if isinstance(f, models.ForeignKey): ...
from django import template from django.db import models from django.utils.safestring import mark_safe register = template.Library() @register.filter def model_row(instance, fields): for name in fields.split(','): try: f = instance._meta.get_field(name) except models.FieldDoesNotExis...
Handle methods and non-field attributes
model_row: Handle methods and non-field attributes
Python
bsd-3-clause
matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel
266105d371193ccf0f02a3975ebdca04980b675b
eche/special_forms.py
eche/special_forms.py
from funcy.seqs import partition from eche.eche_types import Symbol, List def def_exclamation_mark(ast): from eche.eval import eval_ast _, key, val = ast l = List() l.append(key) l.append(val) l.env = ast.env _, val = eval_ast(l, ast.env) ast.env[key] = val # if not isinstance(a...
from funcy.seqs import partition from eche.eche_types import Symbol, List def def_exclamation_mark(ast, env=None): from eche.eval import eval_ast _, key, val = ast l = List() l.append(key) l.append(val) l.env = ast.env _, val = eval_ast(l, ast.env) ast.env[key] = val # if not is...
Add missing env keyword arg.
Add missing env keyword arg.
Python
mit
skk/eche
e2e1ea416d38565a419fff75f6ad4b776b74bc8e
blog/models.py
blog/models.py
from django.db import models from organizer.models import Startup, Tag # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Post(models.Model): title = models.CharField(max_length=63) slug = models.SlugField( max_length=63, help_text='A label for URL conf...
from django.db import models from organizer.models import Startup, Tag # Model Field Reference # https://docs.djangoproject.com/en/1.8/ref/models/fields/ class Post(models.Model): title = models.CharField(max_length=63) slug = models.SlugField( max_length=63, help_text='A label for URL conf...
Declare Meta class in Post model.
Ch03: Declare Meta class in Post model. [skip ci]
Python
bsd-2-clause
jambonrose/DjangoUnleashed-1.8,jambonrose/DjangoUnleashed-1.8
8aa6b13ca491d65a0519e429727073f082993aac
tests/framework/test_bmi_ugrid.py
tests/framework/test_bmi_ugrid.py
"""Unit tests for the pymt.framwork.bmi_ugrid module.""" import xarray as xr from pymt.framework.bmi_ugrid import Scalar, Vector from pymt.framework.bmi_bridge import _BmiCap grid_id = 0 class TestScalar: def get_grid_rank(self, grid_id): return 0 class ScalarBmi(_BmiCap): _cls = TestScalar de...
"""Unit tests for the pymt.framwork.bmi_ugrid module.""" import xarray as xr from pymt.framework.bmi_ugrid import Scalar, Vector from pymt.framework.bmi_bridge import _BmiCap grid_id = 0 class TestScalar: def get_grid_rank(self, grid_id): return 0 class ScalarBmi(_BmiCap): _cls = TestScalar de...
Test that attrs are passed to 'mesh' DataArray
Test that attrs are passed to 'mesh' DataArray
Python
mit
csdms/pymt
b913963f58f2e3a6842518b1cf0344ca262ecdde
src/shelltoprocess/__init__.py
src/shelltoprocess/__init__.py
""" This package implements a wxPython shell, based on PyShell, which controls a seperate Python process, creating with the `multiprocessing` package. Here is the canonical way to use it: 1. Subclass multiprocessing.Process: import multiprocessing class CustomProcess(multiprocessing.Process): def __init__(self,*...
""" This package implements a wxPython shell, based on PyShell, which controls a seperate Python process, creating with the `multiprocessing` package. Here is the canonical way to use it: 1. Subclass multiprocessing.Process: import multiprocessing class CustomProcess(multiprocessing.Process): def __init__(self,*...
Add supposedly unused imports back again
Add supposedly unused imports back again
Python
mit
bittner/PythonTurtle,cool-RR/PythonTurtle
c668bf1179e91be66f12857fc7b31ef66d287a42
downstream_node/lib/node.py
downstream_node/lib/node.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from downstream_node.config import config from downstream_node.models import Challenges, Files from heartbeat import Heartbeat from downstream_node.startup import db __all__ = ['create_token', 'delete_token', 'add_file', 'remove_file', 'gen_challenges', 'updat...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from downstream_node.config import config from downstream_node.models import Challenges, Files from heartbeat import Heartbeat from downstream_node.startup import db __all__ = ['create_token', 'delete_token', 'add_file', 'remove_file', 'gen_challenge...
Insert filename only, not path
Insert filename only, not path
Python
mit
Storj/downstream-node,Storj/downstream-node
d754e44c725ff2b390d2f4ea52d29475b6e11f82
src/akllt/management/commands/akllt_importnews.py
src/akllt/management/commands/akllt_importnews.py
from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Page from akllt.dataimport.news import import_news from akllt.models import NewsStory class Command(BaseCommand): args = '<directory name>' help = 'Imports data from old akl.lt website' def handle(self, news_fold...
from django.core.management.base import BaseCommand from wagtail.wagtailcore.models import Page from akllt.dataimport.news import import_news from akllt.models import NewsStory class Command(BaseCommand): args = '<directory name>' help = 'Imports data from old akl.lt website' def handle(self, news_fold...
Increment item count in news import mgmt command
Increment item count in news import mgmt command
Python
agpl-3.0
python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt,python-dirbtuves/akl.lt
810961f65c37d27c5e2d99cf102064d0b4e300f3
project/apiv2/views.py
project/apiv2/views.py
from django.db.models import Q from django.shortcuts import render from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework.generics import ListAPIView from rest_framework_json_api.renderers import JSONRenderer from rest_framework.generics import RetrieveUpdateDestroyAPIView from bookmarks.m...
from django.db.models import Q from django.shortcuts import render from rest_framework.filters import OrderingFilter, SearchFilter from rest_framework_json_api.renderers import JSONRenderer from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from bookmarks.models import Bookmark from bo...
Use ListCreateAPIView as base class to support bookmark creation
Use ListCreateAPIView as base class to support bookmark creation
Python
mit
hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example,hnakamur/django-bootstrap-table-example
b5bb360a78eb3493a52a4f085bb7ae2ef1355cdd
scavenger/net_utils.py
scavenger/net_utils.py
import subprocess import requests def logged_in(): """Check whether the device has logged in. Return a dictionary containing: username byte duration (in seconds) Return False if no logged in """ r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login', ...
import subprocess import requests def check_online(): """Check whether the device has logged in. Return a dictionary containing: username byte duration (in seconds) Return False if no logged in """ r = requests.post('http://net.tsinghua.edu.cn/cgi-bin/do_login', ...
Change name: logged_in => check_online
Change name: logged_in => check_online
Python
mit
ThomasLee969/scavenger
643634e96554b00214ca4f0d45343e61b0df8e5a
foxybot/bot_help.py
foxybot/bot_help.py
"""Provide a class to load and parse the help file and Provide a simple interface for retrieving help entries""" import json import os class HelpManager(object): _help_dict = {} _last_modified = 0 @staticmethod def get_help(lang, key): """ Retrieve a given commands help text with given lang...
"""Provide a class to load and parse the help file and Provide a simple interface for retrieving help entries""" import json import os class HelpManager(object): _help_dict = {} _last_modified = 0 @staticmethod def get_help(lang, key): """ Retrieve a given commands help text with given lang...
Remove unneeded debug cod e
Remove unneeded debug cod e
Python
bsd-2-clause
6180/foxybot
c434cf202de60d052f61f8608e48b5d7645be1c0
dear_astrid/test/test_rtm_importer.py
dear_astrid/test/test_rtm_importer.py
# pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * from dear_astrid.rtm.importer import Importer as rtmimp class TestRTMImport(TestCase): def setUp(self): self.patches = di...
# pylint: disable=wildcard-import,unused-wildcard-import,missing-docstring from __future__ import absolute_import from unittest import TestCase from nose.tools import * from mock import * from dear_astrid.rtm.importer import * class TestRTMImport(TestCase): def setUp(self): self.patches = dict( time = ...
Clean up names and comments for consistency
Clean up names and comments for consistency
Python
mit
rwstauner/dear_astrid,rwstauner/dear_astrid
3a72b9164fc31e4e7f29715729160a48a7ce2f84
source/tyr/migrations/versions/266658781c00_instances_nullable_in_equipments_provider.py
source/tyr/migrations/versions/266658781c00_instances_nullable_in_equipments_provider.py
""" column 'instances' will be deleted later. Has to be nullable for transition Revision ID: 266658781c00 Revises: 204aae05372a Create Date: 2019-04-15 16:27:22.362244 """ # revision identifiers, used by Alembic. revision = '266658781c00' down_revision = '204aae05372a' from alembic import op import sqlalchemy as sa...
""" column 'instances' will be deleted later. Has to be nullable for transition Revision ID: 266658781c00 Revises: 204aae05372a Create Date: 2019-04-15 16:27:22.362244 """ # revision identifiers, used by Alembic. revision = '266658781c00' down_revision = '204aae05372a' from alembic import op import sqlalchemy as sa...
Add required default value before downgrade migration
Add required default value before downgrade migration
Python
agpl-3.0
xlqian/navitia,kinnou02/navitia,xlqian/navitia,Tisseo/navitia,kinnou02/navitia,xlqian/navitia,xlqian/navitia,Tisseo/navitia,Tisseo/navitia,CanalTP/navitia,kinnou02/navitia,Tisseo/navitia,CanalTP/navitia,CanalTP/navitia,xlqian/navitia,CanalTP/navitia,CanalTP/navitia,Tisseo/navitia,kinnou02/navitia
3328a58e7c81fb86af2424b851de05e7b409ec00
asyncio/__init__.py
asyncio/__init__.py
"""The asyncio package, tracking PEP 3156.""" import sys # This relies on each of the submodules having an __all__ variable. from .futures import * from .events import * from .locks import * from .transports import * from .protocols import * from .streams import * from .tasks import * if sys.platform == 'win32': # ...
"""The asyncio package, tracking PEP 3156.""" import sys # The selectors module is in the stdlib in Python 3.4 but not in 3.3. # Do this first, so the other submodules can use "from . import selectors". try: import selectors # Will also be exported. except ImportError: from . import selectors # This relies ...
Add fakery so "from asyncio import selectors" always works.
Add fakery so "from asyncio import selectors" always works.
Python
apache-2.0
jashandeep-sohi/asyncio,gsb-eng/asyncio,ajdavis/asyncio,vxgmichel/asyncio,gvanrossum/asyncio,manipopopo/asyncio,gsb-eng/asyncio,fallen/asyncio,1st1/asyncio,Martiusweb/asyncio,vxgmichel/asyncio,ajdavis/asyncio,haypo/trollius,ajdavis/asyncio,fallen/asyncio,manipopopo/asyncio,1st1/asyncio,fallen/asyncio,Martiusweb/asyncio...
09e4dd8736d6e829b779dd14b882e0e1d7f5abb9
tester/register/prepare_test.py
tester/register/prepare_test.py
import sys import os import argparse def write_csv(filename, nb_users): with open(filename, "w") as csv_file: csv_file.write("SEQUENTIAL\n") for x in xrange(nb_users): line = "{uname};localhost;[authentication username={uname} password={uname}];\n".format(uname=str(1000+x)) csv_file.write(line) def write...
import sys import os import argparse def write_csv(filename, nb_users): with open(filename, "w") as csv_file: csv_file.write("SEQUENTIAL\n") for x in xrange(nb_users): line = "{uname};localhost;[authentication username={uname} password={uname}];\n".format(uname=str(1000+x)) csv_file.write(line) def write...
DROP DATABASE IF EXISTS in tests.
DROP DATABASE IF EXISTS in tests.
Python
agpl-3.0
BelledonneCommunications/flexisip,BelledonneCommunications/flexisip,BelledonneCommunications/flexisip,BelledonneCommunications/flexisip
8be856ed565d9e961a4d24da74a13240e25f4ded
cio/plugins/base.py
cio/plugins/base.py
class BasePlugin(object): ext = None def load(self, content): """ Return plugin data for content string """ return content def save(self, data): """ Persist external plugin resources and return content string for plugin data """ return data ...
from cio.conf import settings class BasePlugin(object): ext = None @property def settings(self): return settings.get(self.ext.upper(), {}) def load(self, content): """ Return plugin data for content string """ return content def save(self, data): ...
Add support for plugin settings
Add support for plugin settings
Python
bsd-3-clause
5monkeys/content-io
e4696a04cbc003737d7ba28d58b14775e9fc2682
tests/transport/test_asyncio.py
tests/transport/test_asyncio.py
from unittest import TestCase class AsyncioTransportTestCase(TestCase): pass
from asyncio import get_event_loop from unittest import TestCase, mock from rfxcom.transport import AsyncioTransport from rfxcom.protocol import RESET_PACKET, STATUS_PACKET class AsyncioTransportTestCase(TestCase): def test_loop_once(self): loop = get_event_loop() def handler(*args, **kwargs)...
Add an initial ghetto asyncio test.
Add an initial ghetto asyncio test.
Python
bsd-3-clause
skimpax/python-rfxcom,kalfa/python-rfxcom,AndyA13/python-rfxcom,d0ugal-archive/python-rfxcom,kalfa/python-rfxcom,d0ugal-archive/python-rfxcom,AndyA13/python-rfxcom,skimpax/python-rfxcom
b2d06e068fbc7bad9ed0c8f22e751b6bb46d353d
dependencies/contrib/_django.py
dependencies/contrib/_django.py
from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) handler.h...
from __future__ import absolute_import from collections import OrderedDict from dependencies import this from django.views.generic import View def view(injector): """Create Django class-based view from injector class.""" handler = create_handler(View) apply_http_methods(handler, injector) finalize_...
Fix django view closure issue.
Fix django view closure issue.
Python
bsd-2-clause
proofit404/dependencies,proofit404/dependencies,proofit404/dependencies,proofit404/dependencies
5d5cb362410896927b6216deeb9421adfc3331c4
hatarake/net.py
hatarake/net.py
''' Wrappers around Python requests This allows us to handle all the custom headers in a single place ''' from __future__ import absolute_import import requests from functools import wraps from hatarake import USER_AGENT def add_args(func): @wraps(func) def wrapper(*args, **kwargs): if 'headers' no...
''' Wrappers around Python requests This allows us to handle all the custom headers in a single place ''' from __future__ import absolute_import import requests from functools import wraps from hatarake import USER_AGENT def add_args(func): @wraps(func) def wrapper(*args, **kwargs): try: ...
Support token as an argument to our requests wrapper
Support token as an argument to our requests wrapper
Python
mit
kfdm/hatarake
6d6d1af248ce555cca56521bba5e7c356817c74e
account/forms.py
account/forms.py
from django.contrib.auth.models import User from django import forms from account.models import UserProfile attributes = {"class": "required"} class RegistrationForm(forms.Form): username = forms.RegexField(regex=r'^[\w.@+-]+$', max_length=30, wid...
from django.contrib.auth.models import User from django import forms from account.models import UserProfile attributes = {"class": "required"} class RegistrationForm(forms.Form): username = forms.RegexField(regex=r'^[\w.@+-]+$', max_length=30, wid...
Remove unused section of SettingsForm
Remove unused section of SettingsForm
Python
mit
crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp,crcollins/chemtools-webapp
8c174388aefa3907aeb8733bb3d4c77c770eefe7
DataModelAdapter.py
DataModelAdapter.py
class DataModelAdapter(object) : def __init__(self, data) : self._data = data self._children = set() pass def numChildren(self) : return len(self._children) def hasData(self) : return self._data is not None def getData(self, key) : return self._data[k...
class DataModelAdapter(object) : def __init__(self, data) : self._data = data self._children = set() self._parent = None pass def numChildren(self) : return len(self._children) def hasData(self) : return self._data is not None def getData(self, key) :...
Add _parent field with setter/getter
Add _parent field with setter/getter
Python
apache-2.0
mattdeckard/wherewithal
e27f04e9c8d5d74afdd9cd7d6990cad5ff6f6cb5
api/v330/docking_event/serializers.py
api/v330/docking_event/serializers.py
from api.v330.common.serializers import * class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): spacecraft = SpacecraftSerializer(read_only=True, many=False) class Meta: model = SpacecraftFlight fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft...
from api.v330.common.serializers import * class SpacecraftFlightSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): spacecraft = SpacecraftSerializer(read_only=True, many=False) class Meta: model = SpacecraftFlight fields = ('id', 'url', 'destination', 'splashdown', 'spacecraft...
Add space_station field to detailed docking event
Add space_station field to detailed docking event
Python
apache-2.0
ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server,ItsCalebJones/SpaceLaunchNow-Server
e0becdd677c06c29834ecea73c28635553e18337
app/main/presenters/search_results.py
app/main/presenters/search_results.py
from flask import Markup class SearchResults(object): """Provides access to the search results information""" def __init__(self, response, lots_by_slug): self.search_results = response['services'] self._lots = lots_by_slug self._annotate() self.total = response['meta']['total'...
from flask import Markup class SearchResults(object): """Provides access to the search results information""" def __init__(self, response, lots_by_slug): self.search_results = response['services'] self._lots = lots_by_slug self._annotate() self.total = response['meta']['total'...
Add static highlighting on serviceDescription field
Add static highlighting on serviceDescription field
Python
mit
alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend
dbba6f10c867e64031ae07adb3d21becfe4a4e5a
law/contrib/cms/__init__.py
law/contrib/cms/__init__.py
# coding: utf-8 """ CMS-related contrib package. https://home.cern/about/experiments/cms """ __all__ = ["CMSJobDashboard", "BundleCMSSW"] # provisioning imports from law.contrib.cms.job import CMSJobDashboard from law.contrib.cms.tasks import BundleCMSSW
# coding: utf-8 """ CMS-related contrib package. https://home.cern/about/experiments/cms """ __all__ = ["CMSJobDashboard", "BundleCMSSW", "Site", "lfn_to_pfn"] # provisioning imports from law.contrib.cms.job import CMSJobDashboard from law.contrib.cms.tasks import BundleCMSSW from law.contrib.cms.util import Site,...
Load utils in cms contrib package.
Load utils in cms contrib package.
Python
bsd-3-clause
riga/law,riga/law
3c1357627bf1921fdee114b60f96f42c328120b4
caramel/__init__.py
caramel/__init__.py
#! /usr/bin/env python # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" ...
#! /usr/bin/env python # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" ...
Move pyramid_tm include to caramel.main
Caramel: Move pyramid_tm include to caramel.main Move the setting to include pyramid_tm to caramel.main from ini files. This is a vital setting that should never be changed by the user.
Python
agpl-3.0
ModioAB/caramel,ModioAB/caramel
409ad4af8a4ad933667d91709822a04dbbda77ac
km3pipe/cmd.py
km3pipe/cmd.py
# coding=utf-8 # Filename: cmd.py """ KM3Pipe command line utility. Usage: km3pipe test km3pipe tohdf5 [-s] -i FILE -o FILE km3pipe (-h | --help) km3pipe --version Options: -h --help Show this screen. -i FILE Input file. -o FILE Output file. -s Write each event in a sepa...
# coding=utf-8 # Filename: cmd.py """ KM3Pipe command line utility. Usage: km3pipe test km3pipe tohdf5 [-s] -i FILE -o FILE km3pipe (-h | --help) km3pipe --version Options: -h --help Show this screen. -i FILE Input file. -o FILE Output file. -s Write each event in a sepa...
Set HDF5TableSink as default sink
Set HDF5TableSink as default sink
Python
mit
tamasgal/km3pipe,tamasgal/km3pipe
16f531cb7e9d067725a4c25a4321773aada9616d
api/v2/views/tag.py
api/v2/views/tag.py
from core.models import Tag from api.permissions import CloudAdminRequired from api.v2.serializers.summaries import TagSummarySerializer from api.v2.views.base import AuthReadOnlyViewSet class TagViewSet(AuthReadOnlyViewSet): """ API endpoint that allows tags to be viewed or edited. """ queryset = T...
from threepio import logger from core.models import Tag from api.permissions import ApiAuthRequired, CloudAdminRequired,\ InMaintenance from api.v2.serializers.summaries import TagSummarySerializer from api.v2.views.base import AuthOptionalViewSet class TagViewSet(AuthOptionalViewSet): """ API endpoint t...
Address @jchansen's requests. No dupes. POST for authorized users, PUT DELETE for cloud admins and staff.
Address @jchansen's requests. No dupes. POST for authorized users, PUT DELETE for cloud admins and staff. modified: api/v2/views/tag.py
Python
apache-2.0
CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend,CCI-MOC/GUI-Backend
00a497b21b9c788cb38da6c92a985e1b5c22801a
apps/survey/urls.py
apps/survey/urls.py
from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), #url(r'^profile/intake/$', views.survey_intake, name='survey_profile_i...
from django.conf.urls.defaults import * from . import views urlpatterns = patterns('', url(r'^profile/$', views.profile_index, name='survey_profile'), url(r'^profile/electric/$', views.profile_electric, name='survey_profile_electric'), url(r'^profile/surveys/$', views.survey_management, name='survey_manag...
Add view and update decorators
Add view and update decorators
Python
agpl-3.0
chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork,chispita/epiwork
eef03e6c4eb6d80dd04ccbbea6b530d5679a8142
sydent/http/servlets/pubkeyservlets.py
sydent/http/servlets/pubkeyservlets.py
# -*- coding: utf-8 -*- # Copyright 2014 matrix.org # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
# -*- coding: utf-8 -*- # Copyright 2014 matrix.org # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
Update pubkey servlet to s/signers/keyring
Update pubkey servlet to s/signers/keyring
Python
apache-2.0
matrix-org/sydent,matrix-org/sydent,matrix-org/sydent
e6f19cc58f32b855fc1f71086dac0ad56b697ed3
opps/articles/urls.py
opps/articles/urls.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # from django.conf.urls import patterns, url from .views import OppsDetail, OppsList, Search urlpatterns = patterns( '', url(r'^$', OppsList.as_view(), name='home'), url(r'^search/', Search(), name='search'), url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<sl...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import patterns, url from django.views.decorators.cache import cache_page from .views import OppsDetail, OppsList, Search urlpatterns = patterns( '', url(r'^$', cache_page(60 * 2)(OppsList.as_view()), name='home'), url(r'^search/', Searc...
Add cache on article page (via url)
Add cache on article page (via url)
Python
mit
opps/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,opps/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps,williamroot/opps
fbc4247fc7b7d36286c3f25e6ae71dfb7ebb2d39
example/__init__.py
example/__init__.py
from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' def get_metadata(self): return { 'name': 'Example Legislature', 'url': 'http://example.com', ...
from pupa.scrape import Jurisdiction from .people import PersonScraper class Example(Jurisdiction): jurisdiction_id = 'ocd-jurisdiction/country:us/state:ex/place:example' name = 'Example Legislature' url = 'http://example.com' terms = [{ 'name': '2013-2014', 'sessions': ['2013'], ...
Use new-style metadata in example
Use new-style metadata in example
Python
bsd-3-clause
rshorey/pupa,rshorey/pupa,mileswwatkins/pupa,opencivicdata/pupa,datamade/pupa,mileswwatkins/pupa,influence-usa/pupa,influence-usa/pupa,datamade/pupa,opencivicdata/pupa
07da63a9ac95a054332297638df17fcf00ac4291
core/components/security/factor.py
core/components/security/factor.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from u2flib_server.u2f import (begin_registration, begin_authentication, complete_registration, complete_authentication) from components.eternity import config facet...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import json from u2flib_server.u2f import (begin_registration, begin_authentication, complete_registration, complete_authentication) from components.eternity import config facet...
Fix server error when login with u2f
Fix server error when login with u2f
Python
mit
chiaki64/Windless,chiaki64/Windless
4c484a29480ec9d85a87ac7c2aaf09ced7d15457
nn/file/__init__.py
nn/file/__init__.py
import functools import tensorflow as tf from . import cnn_dailymail_rc from ..flags import FLAGS READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files } def read_files(file_pattern, file_format): return READERS[file_format](_file_pattern_to_names(file_pattern)) def _file_pattern_to_names(pattern): re...
import functools import tensorflow as tf from . import cnn_dailymail_rc from .. import collections from ..flags import FLAGS from ..util import func_scope READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files } @func_scope def read_files(file_pattern, file_format): return monitored_batch_queue( *REA...
Monitor number of batches in a input batch queue
Monitor number of batches in a input batch queue
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
c0c59a9c5d3aa2d7ed50e8e895f1a3e02a4ae380
Basic-Number-Guessing-Game-Challenge.py
Basic-Number-Guessing-Game-Challenge.py
import random attempts = 1 number = str(random.randint(1, 100)) while True: print number if raw_input("Guess (1 - 100): ") == number: print "Correct!" print "It Only Took You", attempts, "Attempts!" if attempts > 1 else "Attempt!" break else: print "Incorrect, Guess Again!" ...
import random attempts = 1 number = random.randint(1, 100) while True: guess = raw_input("Guess (1 - 100): ") if guess.isdigit(): guess = int(guess) if 1 <= guess and guess <= 100: if guess == number: print "Correct!" print "It Only Took You", attempt...
Verify that the guess is a number, that it is between 1 and 100, and tells the user if the guessed number is too high or low.
Verify that the guess is a number, that it is between 1 and 100, and tells the user if the guessed number is too high or low.
Python
mit
RascalTwo/Basic-Number-Guessing-Game-Challenge
21e3eac740f54194954d01d517aca0eb841ca1b3
wagtail/search/apps.py
wagtail/search/apps.py
from django.apps import AppConfig from django.core.checks import Tags, Warning, register from django.db import connection from django.utils.translation import gettext_lazy as _ from wagtail.search.signal_handlers import register_signal_handlers class WagtailSearchAppConfig(AppConfig): name = 'wagtail.search' ...
from django.apps import AppConfig from django.core.checks import Tags, Warning, register from django.db import connection from django.utils.translation import gettext_lazy as _ from wagtail.search.signal_handlers import register_signal_handlers class WagtailSearchAppConfig(AppConfig): name = 'wagtail.search' ...
Add alternative warning if sqlite is >=3.19 but is missing fts5 support
Add alternative warning if sqlite is >=3.19 but is missing fts5 support
Python
bsd-3-clause
torchbox/wagtail,torchbox/wagtail,torchbox/wagtail,torchbox/wagtail
e12de19ae37a6f3fa0335ecfd0db00b18badf730
website/files/utils.py
website/files/utils.py
def copy_files(src, target_node, parent=None, name=None): """Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """ ass...
def copy_files(src, target_node, parent=None, name=None): """Copy the files from src to the target node :param Folder src: The source to copy children from :param Node target_node: The node to copy files to :param Folder parent: The parent of to attach the clone of src to, if applicable """ ass...
Check for a fileversion region before copying them to the source region
Check for a fileversion region before copying them to the source region This is mainly for test fileversions that are created without regions by default
Python
apache-2.0
aaxelb/osf.io,felliott/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,mattclark/osf.io,saradbowman/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,cslzchen/osf.io,cslzchen/osf.io,mfraezz/osf.io,HalcyonChimera/osf.io,adlius/osf.io,felliott/osf.io,Johnetordoff/osf.io,caseyrollins/os...
bf7626df74d78f2811f20173fb21c36a96cc9500
packages/gtk-doc.py
packages/gtk-doc.py
GnomePackage ('gtk-doc', version_major = '1', version_minor = '17', sources = [ 'http://ftp.gnome.org/pub/gnome/sources/%{name}/%{version}/%{name}-%{version}.tar.bz2' ])
GnomePackage ('gtk-doc', version_major = '1', version_minor = '17', configure_flags = ['--with-xml-catalog="%{prefix}/etc/xml/catalog"'], sources = [ 'http://ftp.gnome.org/pub/gnome/sources/%{name}/%{version}/%{name}-%{version}.tar.bz2' ])
Set xml catalog to the right prefix.
Set xml catalog to the right prefix.
Python
mit
BansheeMediaPlayer/bockbuild,mono/bockbuild,mono/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild
5be3d07995803d81e6238a561c772e856b81a367
icekit/templatetags/search_tags.py
icekit/templatetags/search_tags.py
from django.template import Library, Node from django.test.client import RequestFactory register = Library() factory = RequestFactory() class FakeRequestNode(Node): def render(self, context): req = factory.get('/') req.notifications = [] context['request'] = req return '' @reg...
from django.contrib.auth.models import AnonymousUser from django.template import Library, Node from django.test.client import RequestFactory register = Library() factory = RequestFactory() class FakeRequestNode(Node): def render(self, context): req = factory.get('/') req.notifications = [] ...
Add anonymous user to fake request object.
Add anonymous user to fake request object.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/django-icekit
94b6b97dc1e706a6560092aa29cbe4e21f052924
froide/account/apps.py
froide/account/apps.py
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class AccountConfig(AppConfig): name = 'froide.account' verbose_name = _("Account") def ready(self): from froide.bounce.signals import user_email_bounced user_email_bounced.connect(deactivate_user_a...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ from django.urls import reverse from .menu import menu_registry, MenuItem class AccountConfig(AppConfig): name = 'froide.account' verbose_name = _("Account") def ready(self): from froide.bounce.signals impo...
Make settings and requests menu items
Make settings and requests menu items
Python
mit
fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide
2538ca440620de8ed08510e0ae902c82184a9daa
consts/auth_type.py
consts/auth_type.py
class AuthType(object): """ An auth type defines what write privileges an authenticated agent has. """ MATCH_VIDEO = 0 EVENT_TEAMS = 1 EVENT_MATCHES = 2 EVENT_RANKINGS = 3 EVENT_ALLIANCES = 4 EVENT_AWARDS = 5 type_names = { MATCH_VIDEO: "match video", EVENT_TEAMS...
class AuthType(object): """ An auth type defines what write privileges an authenticated agent has. """ EVENT_DATA = 0 MATCH_VIDEO = 1 EVENT_TEAMS = 2 EVENT_MATCHES = 3 EVENT_RANKINGS = 4 EVENT_ALLIANCES = 5 EVENT_AWARDS = 6 type_names = { EVENT_DATA: "event data", ...
Revert "Remove AuthType.EVENT_DATA and renumber"
Revert "Remove AuthType.EVENT_DATA and renumber" This reverts commit 38248941eb47a04b82fe52e1adca7387dafcf7f3.
Python
mit
phil-lopreiato/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-bl...
e7df1e7f3e9d8afd5cf1892df2f136751b276136
aio_pika/transaction.py
aio_pika/transaction.py
import asyncio from enum import Enum import aiormq class TransactionStates(Enum): created = "created" commited = "commited" rolled_back = "rolled back" started = "started" class Transaction: def __str__(self): return self.state.value def __init__(self, channel): self.loop =...
import asyncio from enum import Enum import aiormq class TransactionStates(Enum): created = "created" commited = "commited" rolled_back = "rolled back" started = "started" class Transaction: def __str__(self): return self.state.value def __init__(self, channel): self.loop =...
Return self instead of select result in __aenter__
Return self instead of select result in __aenter__
Python
apache-2.0
mosquito/aio-pika
cbb0ed5ed66571feba22413472a5fe1a20824dbd
shared_export.py
shared_export.py
import bpy def find_seqs(scene, select_marker): sequences = {} sequence_flags = {} for marker in scene.timeline_markers: if ":" not in marker.name or (select_marker and not marker.select): continue name, what = marker.name.rsplit(":", 1) if name not in sequences: ...
import bpy def find_seqs(scene, select_marker): sequences = {} sequence_flags = {} for marker in scene.timeline_markers: if ":" not in marker.name or (select_marker and not marker.select): continue name, what = marker.name.rsplit(":", 1) what = what.lower() if...
Make sequence marker types (:type) case insensitive
Make sequence marker types (:type) case insensitive
Python
mit
qoh/io_scene_dts,portify/io_scene_dts
7ceba1f2b83628a2b89ffbdd30e435970e8c5e91
tests/test_kafka_streams.py
tests/test_kafka_streams.py
""" Test the top-level Kafka Streams class """ import pytest from winton_kafka_streams import kafka_config from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError from winton_kafka_streams.kafka_streams import KafkaStreams from winton_kafka_streams.processor.processor import BaseProcessor from ...
""" Test the top-level Kafka Streams class """ import pytest from winton_kafka_streams import kafka_config from winton_kafka_streams.errors.kafka_streams_error import KafkaStreamsError from winton_kafka_streams.kafka_streams import KafkaStreams from winton_kafka_streams.processor.processor import BaseProcessor from ...
Use more Pythonic name for test.
Use more Pythonic name for test.
Python
apache-2.0
wintoncode/winton-kafka-streams
3fb1800548ad421520bf3f2845aad4f51f6f5839
rapidsms_multimodem/tests/__init__.py
rapidsms_multimodem/tests/__init__.py
from test_utils import * # noqa from test_views import * # noqa
from test_outgoing import * # noqa from test_utils import * # noqa from test_views import * # noqa
Add import for older versions of Django
Add import for older versions of Django
Python
bsd-3-clause
caktus/rapidsms-multimodem
075b11aa830c9a5961e9ee63e42484192990f7d3
tools/misc/python/test-data-in-out.py
tools/misc/python/test-data-in-out.py
# TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.) # INPUT input TYPE GENERIC # OUTPUT output # OUTPUT OPTIONAL missing_output.txt import shutil shutil.copyfile('input', 'output')
# TOOL test-data-in-out.py: "Test data input and output in Python" (Data input output test.) # INPUT input TYPE GENERIC # OUTPUT output # PARAMETER delay: Delay TYPE INTEGER FROM 0 TO 1000 DEFAULT 1 (Delay in seconds) import shutil import time time.sleep(delay) shutil.copyfile('input', 'output')
Add delay to input-output test
Add delay to input-output test
Python
mit
chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools,chipster/chipster-tools
943d2648c17facb9dbfd4f26d335beef341e9c49
fabfile.py
fabfile.py
from fabric.api import local __author__ = 'derek' def deploy(version): local('python runtests.py') local("git tag -a %s -m %s" % (version, version)) local('python setup.py sdist upload')
from fabric.api import local __author__ = 'derek' def deploy(version): local('python runtests.py') local("git tag -a %s -m %s" % (version, version)) local("git push origin --tags") local('python setup.py sdist upload')
Make sure to push the tags
Make sure to push the tags
Python
mit
winfieldco/django-mail-queue,Goury/django-mail-queue,Goury/django-mail-queue,dstegelman/django-mail-queue,dstegelman/django-mail-queue,styrmis/django-mail-queue
e660d8e05e54adbd0ea199a02cc188dc7007089a
fabfile.py
fabfile.py
from fabric.api import cd, sudo, env import os expected_vars = [ 'PROJECT', ] for var in expected_vars: if var not in os.environ: raise Exception('Please specify %s environment variable' % ( var,)) PROJECT = os.environ['PROJECT'] USER = os.environ.get('USER', 'jmbo') env.path = os.path.j...
from fabric.api import cd, sudo, env import os PROJECT = os.environ.get('PROJECT', 'go-rts-zambia') DEPLOY_USER = os.environ.get('DEPLOY_USER', 'jmbo') env.path = os.path.join('/', 'var', 'praekelt', PROJECT) def restart(): sudo('/etc/init.d/nginx restart') sudo('supervisorctl reload') def deploy(): w...
Fix USER in fabric file (the deploy user and ssh user aren't necessarily the same). Set default value for PROJECT (this is the go-rts-zambia repo after all).
Fix USER in fabric file (the deploy user and ssh user aren't necessarily the same). Set default value for PROJECT (this is the go-rts-zambia repo after all).
Python
bsd-3-clause
praekelt/go-rts-zambia
04e8206a8610666c6027fc0f4be5e786e4bd5513
fabfile.py
fabfile.py
set( fab_hosts = ['startthedark.com'], fab_user = 'startthedark', ) def unlink_nginx(): 'Un-link nginx rules for startthedark.' sudo('rm -f /etc/nginx/sites-enabled/startthedark.com') sudo('/etc/init.d/nginx reload') def link_nginx(): 'Link nginx rules for startthedark' sudo('ln -s /etc/ng...
set( fab_hosts = ['startthedark.com'], fab_user = 'startthedark', ) def unlink_nginx(): 'Un-link nginx rules for startthedark.' sudo('rm -f /etc/nginx/sites-enabled/startthedark.com') sudo('/etc/init.d/nginx reload') def link_nginx(): 'Link nginx rules for startthedark' sudo('ln -s /etc/ng...
Split out the css rebuilding into its own fab method.
Split out the css rebuilding into its own fab method.
Python
bsd-3-clause
mvayngrib/startthedark,mvayngrib/startthedark,ericflo/startthedark,ericflo/startthedark,mvayngrib/startthedark,ericflo/startthedark
b575099c0d1f23916038172d46852a264a5f5a95
bluebottle/utils/staticfiles_finders.py
bluebottle/utils/staticfiles_finders.py
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in t...
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in t...
Fix static files finder errors
Fix static files finder errors
Python
bsd-3-clause
jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,jfterpstra/bluebottle
d52d8ce18745d5ec0e722340cf09735938c8a0c0
src/BaseUtils.py
src/BaseUtils.py
''' Base NLP utilities ''' def get_words(sentence): ''' Return all the words found in a sentence. Ignore whitespace and all punctuation >>> get_words('a most interesting piece') >>> ['a', 'most', 'interesting', 'piece'] >>> get_words('a, most$ **interesting piece') >>> ['a', 'most', 'interes...
''' Base NLP utilities ''' def get_words(sentence): ''' Return all the words found in a sentence. Ignore whitespace and all punctuation >>> get_words('a most interesting piece') >>> ['a', 'most', 'interesting', 'piece'] >>> get_words('a, most$ **interesting piece') >>> ['a', 'most', 'interes...
Replace ASCII checking chars and space with library methods
Replace ASCII checking chars and space with library methods
Python
bsd-2-clause
ambidextrousTx/RNLTK
716d967971d9ea23ab54d327231ba873b681a7c7
isserviceup/services/models/service.py
isserviceup/services/models/service.py
from enum import Enum class Status(Enum): ok = 1 # green maintenance = 2 # blue minor = 3 # yellow major = 4 # orange critical = 5 # red unavailable = 6 # gray class Service(object): @property def id(self): return self.__class_...
from enum import Enum class Status(Enum): ok = 1 # green maintenance = 2 # blue minor = 3 # yellow major = 4 # orange critical = 5 # red unavailable = 6 # gray class Service(object): @property def id(self): return self.__class_...
Add icon_url as abstract property
Add icon_url as abstract property
Python
apache-2.0
marcopaz/is-service-up,marcopaz/is-service-up,marcopaz/is-service-up
5233e6d7f7d4f494f62576206ede87d13e8f760d
calexicon/calendars/tests/test_other.py
calexicon/calendars/tests/test_other.py
from datetime import date as vanilla_date from calendar_testing import CalendarTest from calexicon.calendars.other import JulianDayNumber class TestJulianDayNumber(CalendarTest): def setUp(self): self.calendar = JulianDayNumber() def test_make_date(self): vd = vanilla_date(2010, 8, 1) ...
from datetime import date as vanilla_date from calendar_testing import CalendarTest from calexicon.calendars.other import JulianDayNumber class TestJulianDayNumber(CalendarTest): def setUp(self): self.calendar = JulianDayNumber() def test_make_date(self): vd = vanilla_date(2010, 8, 1) ...
Add a test to check the right number of days in 400 year cycles.
Add a test to check the right number of days in 400 year cycles.
Python
apache-2.0
jwg4/calexicon,jwg4/qual
03fb3e68f9ec9432a25c60bda06fcd49d604befc
src/__init__.py
src/__init__.py
from ..override_audit import reload reload("src", ["core", "events", "contexts", "browse", "settings_proxy"]) reload("src.commands") from . import core from .core import * from .events import * from .contexts import * from .settings_proxy import * from .commands import * __all__ = [ # core "core", # bro...
from ..override_audit import reload reload("src", ["core", "events", "contexts", "browse", "settings_proxy"]) reload("src.commands") from . import core from .core import * from .events import * from .contexts import * from .settings_proxy import * from .commands import * __all__ = [ # core "core", # bro...
Add missing event listener for new overrides
Add missing event listener for new overrides While rolling the test code for creating overrides into the base code, we remembered to make sure that we put the event handler used to handle override creation in place but forgot to export them to to the base plugin so that it would actually do something.
Python
mit
OdatNurd/OverrideAudit
f46770697d668e31518ada41d31fdb59a84f3cf6
kokki/cookbooks/aws/recipes/default.py
kokki/cookbooks/aws/recipes/default.py
from kokki import * Package("python-boto") # Mount volumes and format is necessary for vol in env.config.aws.volumes: env.cookbooks.aws.EBSVolume(vol['volume_id'], availability_zone = env.config.aws.availability_zone, device = vol['device'], action = "attach") if vol.get('fstype'): ...
import os from kokki import * # Package("python-boto") Execute("pip install git+http://github.com/boto/boto.git#egg=boto", not_if = 'python -c "import boto"') Execute("mv /usr/lib/pymodules/python2.6/boto /tmp/boto.orig", only_if = os.path.exists("/usr/lib/pymodules/python2.6/boto")) # Mount volumes and form...
Install github verison of boto in aws cookbook (for now)
Install github verison of boto in aws cookbook (for now)
Python
bsd-3-clause
samuel/kokki
15db774538b4fa18c0653fb741ba14c0373867c8
main/admin/forms.py
main/admin/forms.py
from django import forms from main.models import Profile, LanProfile class AdminLanProfileForm(forms.ModelForm): class Meta: model = LanProfile fields = '__all__' class AdminProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' def __init__(self, ...
from django import forms from main.models import Profile, LanProfile, GRADES class AdminLanProfileForm(forms.ModelForm): class Meta: model = LanProfile fields = '__all__' class AdminProfileForm(forms.ModelForm): class Meta: model = Profile fields = '__all__' grade = for...
Make that work with admin too
Make that work with admin too
Python
mit
bomjacob/htxaarhuslan,bomjacob/htxaarhuslan,bomjacob/htxaarhuslan
c557058a7a7206167108535129bc0b160e4fe62b
nipype/testing/tests/test_utils.py
nipype/testing/tests/test_utils.py
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Test testing utilities """ from nipype.testing.utils import TempFATFS from nose.tools import assert_true def test_tempfatfs(): with TempFATFS() as tmpdir: yield assert_true, tmpdir is not ...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Test testing utilities """ import os import warnings from nipype.testing.utils import TempFATFS from nose.tools import assert_true def test_tempfatfs(): try: fatfs = TempFATFS() except...
Add warning for TempFATFS test
TEST: Add warning for TempFATFS test
Python
bsd-3-clause
mick-d/nipype,carolFrohlich/nipype,FCP-INDI/nipype,sgiavasis/nipype,mick-d/nipype,FCP-INDI/nipype,FCP-INDI/nipype,carolFrohlich/nipype,carolFrohlich/nipype,FCP-INDI/nipype,mick-d/nipype,sgiavasis/nipype,mick-d/nipype,carolFrohlich/nipype,sgiavasis/nipype,sgiavasis/nipype
44547695f662c957f5242f7cfefd328b33d99830
sso/backends.py
sso/backends.py
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from hashlib import sha1 class SimpleHashModelBackend(ModelBackend): def authenticate(self, username=None, password=None): try: user = User.objects.get(username=username) except User.Does...
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User from hashlib import sha1 class SimpleHashModelBackend(ModelBackend): supports_anonymous_user = False supports_object_permissions = False supports_inactive_user = False def authenticate(self, username=No...
Update the authentication backend with upcoming features
Update the authentication backend with upcoming features
Python
bsd-3-clause
nikdoof/test-auth
2515b3402c671c2949e5f3c712cb284777f2accf
examples/boilerplates/base_test_case.py
examples/boilerplates/base_test_case.py
''' You can use this as a boilerplate for your test framework. Define your customized library methods in a master class like this. Then have all your test classes inherit it. BaseTestCase will inherit SeleniumBase methods from BaseCase. ''' from seleniumbase import BaseCase class BaseTestCase(BaseCase): def set...
''' You can use this as a boilerplate for your test framework. Define your customized library methods in a master class like this. Then have all your test classes inherit it. BaseTestCase will inherit SeleniumBase methods from BaseCase. ''' from seleniumbase import BaseCase class BaseTestCase(BaseCase): def set...
Update boilerplate to save a screenshot before the tearDown()
Update boilerplate to save a screenshot before the tearDown()
Python
mit
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase