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, "log") if not os.path.isdir(logdir): log("logger: creating log directory:", logdir) os.makedirs(logdir) logfile = os.path.join(logdir, "messages") else: logfile = os.path.join(analysis_path, "messages") # log a message to messages files (and to stdout by default) def log(*args, quiet=False): global logbuf # timestamp now = datetime.now() timestamp = str(now) + ": " # assemble message line msg = [] for a in args: msg.append(str(a)) logbuf.append(timestamp + " ".join(msg)) if logfile: # flush log buffer f = open(logfile, "a") for line in logbuf: f.write(line) f.write("\n") f.close() logbuf = [] if not quiet: print(*msg) # log quietly (log to file, but not to stdout) def qlog(*args): log(*args, quiet=True)
# 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, "log") if not os.path.isdir(logdir): log("logger: creating log directory:", logdir) os.makedirs(logdir) logfile = os.path.join(logdir, "messages") else: logfile = os.path.join(analysis_path, "messages") # log a message to messages files (and to stdout by default) def log(*args, quiet=False, fancy=False): global logbuf # timestamp now = datetime.now() timestamp = str(now) + ": " # assemble message line msg = [] for a in args: msg.append(str(a)) if not fancy: logbuf.append(timestamp + " ".join(msg)) else: logbuf.append("") logbuf.append("############################################################################") logbuf.append("### " + timestamp + " ".join(msg)) logbuf.append("############################################################################") logbuf.append("") if logfile: # flush log buffer f = open(logfile, "a") for line in logbuf: f.write(line) f.write("\n") f.close() logbuf = [] if not quiet: print(*msg) # log quietly (log to file, but not to stdout) def qlog(*args): log(*args, quiet=True)
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') version_py[0] = "PLUGIN_VERSION = '%s'" % version with open('floo/version.py', 'w') as fd: fd.write('\n'.join(version_py)) os.system('git add packages.json floo/version.py') os.system('git commit -m "Tag new release: %s"' % version) os.system('git tag %s' % version) os.system('git push --tags') os.system('git push') if __name__ == "__main__": main()
#!/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)] versions.sort(key=StrictVersion) print(versions[-1]) sys.exit() version = sys.argv[1] with open('floo/version.py', 'r') as fd: version_py = fd.read().split('\n') version_py[0] = "PLUGIN_VERSION = '%s'" % version with open('floo/version.py', 'w') as fd: fd.write('\n'.join(version_py)) os.system('git add packages.json floo/version.py') os.system('git commit -m "Tag new release: %s"' % version) os.system('git tag %s' % version) os.system('git push --tags') os.system('git push') if __name__ == "__main__": main()
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', 'response', 'session', 'tmpl_context', 'url'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
"""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.controllers.util import Response __all__ = ['app_globals', 'cache', 'config', 'request', 'response', 'session', 'tmpl_context', 'url', 'Request', 'Response'] def __figure_version(): try: from pkg_resources import require import os # NOTE: this only works when the package is either installed, # or has an .egg-info directory present (i.e. wont work with raw # SVN checkout) info = require('pylons')[0] if os.path.dirname(os.path.dirname(__file__)) == info.location: return info.version else: return '(not installed)' except: return '(not installed)' __version__ = __figure_version() app_globals = StackedObjectProxy(name="app_globals") cache = StackedObjectProxy(name="cache") request = StackedObjectProxy(name="request") response = StackedObjectProxy(name="response") session = StackedObjectProxy(name="session") tmpl_context = StackedObjectProxy(name="tmpl_context or C") url = StackedObjectProxy(name="url") translator = StackedObjectProxy(name="translator")
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 are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj]
# 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__, meaning that in in Python2.7 MarathonObjects are hashable, but in Python3 they're not, This test ensures that we are hashable in all versions of python """ obj = MarathonObject() collection = {} collection[obj] = True assert collection[obj] class MarathonResourceHashable(unittest.TestCase): def test_hashable(self): """ Regression test for issue #203 MarathonResource defined __eq__ but not __hash__, meaning that in in Python2.7 MarathonResources are hashable, but in Python3 they're not This test ensures that we are hashable in all versions of python """ obj = MarathonResource() collection = {} collection[obj] = True assert collection[obj]
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]) locus_idx = int(cols[1]) phi = float(cols[2]) if last_iter_idx != iter_idx: last_iter_idx = iter_idx current_iter_idx += 1 sampled_phis[current_iter_idx, locus_idx] = phi fl.close() return sampled_phis if __name__ == "__main__": bamova_phi_output_flname = sys.argv[1] n_steps = int(sys.argv[2]) n_loci = int(sys.argv[3]) npy_flname = sys.argv[4] matrix = read_phi(bamova_phi_output_flname, n_steps, n_loci) np.save(matrix, npy_flname)
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]) locus_idx = int(cols[1]) phi = float(cols[2]) if last_iter_idx != iter_idx: last_iter_idx = iter_idx current_iter_idx += 1 sampled_phis[current_iter_idx, locus_idx] = phi fl.close() return sampled_phis if __name__ == "__main__": bamova_phi_output_flname = sys.argv[1] n_steps = int(sys.argv[2]) n_loci = int(sys.argv[3]) npy_flname = sys.argv[4] matrix = read_phi(bamova_phi_output_flname, n_steps, n_loci) np.save(npy_flname, matrix)
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') self.analysis = AnalyseiDynomics(self.directory) def test_init(self): assert_is(self.directory, self.analysis.directory) def test_solute_names(self): actual_solutes = self.analysis.solute_names assert_list_equal(self.expected_solutes, actual_solutes) def test_species_names(self): actual_species = self.analysis.species_names assert_list_equal(self.expected_species, actual_species)
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): with self.assertRaises(Exception): loc = 'Somewhere, On, Mars' w = vane.fetch_weather(loc) def test_wund_good_fetch(self): api_key = os.environ['WUND_API'] loc = 'New York, NY' w = vane.fetch_weather(location=loc, provider='wund', api_key=api_key) self.assertTrue('temperature' in w['current']) self.assertTrue('summary' in w['current']) def test_wund_bad_fetch(self): api_key = os.environ['WUND_API'] with self.assertRaises(Exception): loc = '0' w = vane.fetch_weather( location=loc, provider='wund', api_key=api_key) def test_geolocation(self): w = vane.fetch_weather() self.assertTrue('temperature' in w['current']) self.assertTrue('summary' in w['current']) if __name__ == '__main__': unittest.main()
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): with self.assertRaises(Exception): loc = 'Somewhere, On, Mars' w = vane.fetch_weather(loc) def test_wund_good_fetch(self): api_key = os.environ['WUND_API'] loc = 'New York, NY' w = vane.fetch_weather(location=loc, provider='wund', api_key=api_key) self.assertTrue('temperature' in w['current']) self.assertTrue('summary' in w['current']) def test_wund_bad_fetch(self): api_key = os.environ['WUND_API'] with self.assertRaises(Exception): loc = '0' w = vane.fetch_weather( location=loc, provider='wund', api_key=api_key) if __name__ == '__main__': unittest.main()
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', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '125122c', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'} xml = template.toXML(version) ova_xml = open("ova.xml", "w") ova_xml.write(xml) ova_xml.close() # Generate tarball containing ova.xml template_name = os.path.splitext(fname)[0] tar = tarfile.open("%s.tar" % template_name, "w") tar.add("ova.xml") tar.close() os.remove("ova.xml") # Import XS template uuid = subprocess.check_output(["xe", "vm-import", "filename=%s.tar" % template_name, "preserve=true"]) # Set default_template = true out = subprocess.check_output(["xe", "template-param-set", "other-config:default_template=true", "uuid=%s" % uuid.strip()])
#!/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', 'product_version': '7.0.0', 'product_brand': 'XenServer', 'build_number': '0x', 'xapi_major': '1', 'xapi_minor': '9', 'export_vsn': '2'} xml = template.toXML(version) ova_xml = open("ova.xml", "w") ova_xml.write(xml) ova_xml.close() # Generate tarball containing ova.xml template_name = os.path.splitext(fname)[0] tar = tarfile.open("%s.tar" % template_name, "w") tar.add("ova.xml") tar.close() os.remove("ova.xml") # Import XS template uuid = subprocess.check_output(["xe", "vm-import", "filename=%s.tar" % template_name, "preserve=true"]) # Set default_template = true out = subprocess.check_output(["xe", "template-param-set", "other-config:default_template=true", "uuid=%s" % uuid.strip()])
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 def upgrade(): op.execute( "DELETE FROM torsion_init_mol_association a USING \ (SELECT MIN(ctid) as ctid, torsion_id, molecule_id \ FROM torsion_init_mol_association \ GROUP BY torsion_id, molecule_id HAVING COUNT(*) > 1 \ ) b \ WHERE a.torsion_id = b.torsion_id and a.molecule_id = b.molecule_id \ AND a.ctid <> b.ctid" ) op.execute("alter table add primary key (torsion_id, molecule_id)") def downgrade(): op.execute("alter table drop constraint torsion_init_mol_association_pkey")
"""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 def upgrade(): # Removes (harmless) duplicate rows op.execute( "DELETE FROM torsion_init_mol_association a USING \ (SELECT MIN(ctid) as ctid, torsion_id, molecule_id \ FROM torsion_init_mol_association \ GROUP BY torsion_id, molecule_id HAVING COUNT(*) > 1 \ ) b \ WHERE a.torsion_id = b.torsion_id and a.molecule_id = b.molecule_id \ AND a.ctid <> b.ctid" ) op.execute("alter table torsion_init_mol_association add primary key (torsion_id, molecule_id)") def downgrade(): op.execute("alter table torsion_init_mol_association drop constraint torsion_init_mol_association_pkey")
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(AWSObject): resource_type = "AWS::IVS::Channel" props = { "Authorized": (boolean, False), "LatencyMode": (str, False), "Name": (str, False), "Tags": (Tags, False), "Type": (str, False), } class PlaybackKeyPair(AWSObject): resource_type = "AWS::IVS::PlaybackKeyPair" props = { "Name": (str, False), "PublicKeyMaterial": (str, True), "Tags": (Tags, False), } class StreamKey(AWSObject): resource_type = "AWS::IVS::StreamKey" props = { "ChannelArn": (str, True), "Tags": (Tags, False), }
# 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 Channel(AWSObject): resource_type = "AWS::IVS::Channel" props = { "Authorized": (boolean, False), "LatencyMode": (str, False), "Name": (str, False), "RecordingConfigurationArn": (str, False), "Tags": (Tags, False), "Type": (str, False), } class PlaybackKeyPair(AWSObject): resource_type = "AWS::IVS::PlaybackKeyPair" props = { "Name": (str, False), "PublicKeyMaterial": (str, True), "Tags": (Tags, False), } class S3DestinationConfiguration(AWSProperty): props = { "BucketName": (str, True), } class DestinationConfiguration(AWSProperty): props = { "S3": (S3DestinationConfiguration, True), } class RecordingConfiguration(AWSObject): resource_type = "AWS::IVS::RecordingConfiguration" props = { "DestinationConfiguration": (DestinationConfiguration, True), "Name": (str, False), "Tags": (Tags, False), } class StreamKey(AWSObject): resource_type = "AWS::IVS::StreamKey" props = { "ChannelArn": (str, True), "Tags": (Tags, False), }
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 in string char_count = 1 # reset count to 1
# 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 in string char_count = 1 # reset count to 1 else: # add to repeated count if there is a match char_count += 1
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 NotPermittedVoiceNotConnected(VoiceNotConnected): '''Voice Not Connected, and Not Permitted''' pass class MissingPermissions(CommandError): '''Missing Permissions''' pass class NotPermitted(CommandError): '''Not Permitted''' pass class AudioError(CommandError): '''Audio Error''' pass
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 NotPermittedVoiceNotConnected(VoiceNotConnected): '''Voice Not Connected, and Not Permitted''' pass class NotPermitted(CommandError): '''Not Permitted''' pass class AudioError(CommandError): '''Audio Error''' pass
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): """ Overrides work on ConditionBlock from the factory task to set next workflow tasks. """ def __init__(self, conditions, workflow): super().__init__(conditions) self._workflow = workflow def condition_validated(self, condition, data): """ Set next workflow tasks upon validating a condition. """ self._workflow.set_next_tasks(condition['tasks']) @register('task_selector', 'execute') class TaskSelector(TaskHolder): SCHEMA = generate_schema(tasks={ 'type': 'object', 'properties': { 'type': {'type': 'string', 'enum': ['task-selector']}, 'tasks': { 'type': 'array', 'items': { 'type': 'string', 'minLength': 1, 'uniqueItems': True } } } }) async def execute(self, event): data = event.data workflow = Workflow.current_workflow() for block in self.config['rules']: if block['type'] == 'task-selector': workflow.set_next_tasks(block['tasks']) elif block['type'] == 'condition-block': TaskConditionBlock(block['conditions'], workflow).apply(data) return data
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): """ Overrides work on ConditionBlock from the factory task to set next workflow tasks. """ def __init__(self, conditions, workflow): super().__init__(conditions) self._workflow = workflow def condition_validated(self, condition, data): """ Set next workflow tasks upon validating a condition. """ if condition['rules']: self._workflow.set_next_tasks(condition['rules'][0]['tasks']) @register('task_selector', 'execute') class TaskSelector(TaskHolder): SCHEMA = generate_schema(tasks={ 'type': 'object', 'properties': { 'type': {'type': 'string', 'enum': ['task-selector']}, 'tasks': { 'type': 'array', 'items': { 'type': 'string', 'minLength': 1, 'uniqueItems': True } } } }) async def execute(self, event): data = event.data workflow = Workflow.current_workflow() for block in self.config['rules']: if block['type'] == 'task-selector': workflow.set_next_tasks(block['tasks']) elif block['type'] == 'condition-block': TaskConditionBlock(block['conditions'], workflow).apply(data) return data
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(text_model.make_sentence() == None) def test_sherlock(): text_model = markovify.Text(sherlock) sent = text_model.make_sentence() assert(len(sent) != 0) def test_json(): text_model = markovify.Text(sherlock) json_model = text_model.chain.to_json() stored_chain = markovify.Chain.from_json(json_model) new_text_model = markovify.Text(sherlock, chain=stored_chain) sent = text_model.make_sentence() assert(len(sent) != 0)
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(text) assert(text_model.make_sentence() == None) def test_sherlock(): text_model = markovify.Text(sherlock) sent = text_model.make_sentence() assert(len(sent) != 0) def get_sorted(chain_json): return sorted(chain_json, key=operator.itemgetter(0)) def test_json(): text_model = markovify.Text(sherlock) chain_json = text_model.chain.to_json() stored_chain = markovify.Chain.from_json(chain_json) assert(get_sorted(stored_chain.to_json()) == get_sorted(chain_json)) new_text_model = markovify.Text(sherlock, chain=stored_chain) sent = text_model.make_sentence() assert(len(sent) != 0)
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() entry.level = record.levelname entry.message = self.format(record) entry.module = record.name try: entry.event = record.event except: pass try: entry.user = record.user except: pass entry.save()
# -*- 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() entry.level = record.levelname entry.message = self.format(record) entry.module = record.name try: entry.event = record.event except: try: entry.event_id = record.event_id except: pass try: entry.user = record.user except: pass entry.save()
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): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) def path(self, name): """ if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") """ return super(TenantStaticFilesStorage, self).path(name)
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): """ Implementation that extends core Django's StaticFilesStorage. """ def __init__(self, location=None, base_url=None, *args, **kwargs): super(TenantStaticFilesStorage, self).__init__(location, base_url, *args, **kwargs) if hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT"): self.location = os.path.join(self.location, settings.MULTITENANT_RELATIVE_STATIC_ROOT) """ def path(self, name): if not hasattr(settings, "MULTITENANT_RELATIVE_STATIC_ROOT") or \ not settings.MULTITENANT_RELATIVE_STATIC_ROOT: raise ImproperlyConfigured("You're using the TenantStaticFilesStorage " "without having set the MULTITENANT_RELATIVE_STATIC_ROOT " "setting to a filesystem path.") return super(TenantStaticFilesStorage, self).path(name) """
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) return HttpResponse(orig_rendition.img_tag()) else: return HttpResponse('')
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.get_or_create(spec='original') orig_rendition = image.get_rendition(filter) return HttpResponse(orig_rendition.img_tag()) else: return HttpResponse('')
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( mock_run.call_args_list, [ mock.call('python setup.py sdist bdist_wheel'), mock.call('twine upload -u username -p password dist/*'), mock.call('rm -rf build dist') ] )
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( mock_run.call_args_list, [ mock.call('rm -rf build dist'), mock.call('python setup.py sdist bdist_wheel'), mock.call('twine upload -u username -p password dist/*'), mock.call('rm -rf build dist') ] )
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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from project_generator.util import * def test_unicode_detection(): try: print(u'\U0001F648') except UnicodeEncodeError: assert not unicode_available() else: assert unicode_available() def test_flatten(): l1 = [['aa', 'bb', ['cc', 'dd', 'ee'], ['ee', 'ff'], 'gg']] assert list(flatten(l1)) == ['aa', 'bb', 'cc', 'dd', 'ee', 'ee', 'ff', 'gg'] assert uniqify(flatten(l1)) == ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg'] def test_uniqify(): l1 = ['a', 'b', 'b', 'c', 'b', 'd', 'c', 'e', 'f', 'a'] assert uniqify(l1) == ['a', 'b', 'c', 'd', 'e', 'f']
# 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from project_generator.util import * def test_flatten(): l1 = [['aa', 'bb', ['cc', 'dd', 'ee'], ['ee', 'ff'], 'gg']] assert list(flatten(l1)) == ['aa', 'bb', 'cc', 'dd', 'ee', 'ee', 'ff', 'gg'] assert uniqify(flatten(l1)) == ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg'] def test_uniqify(): l1 = ['a', 'b', 'b', 'c', 'b', 'd', 'c', 'e', 'f', 'a'] assert uniqify(l1) == ['a', 'b', 'c', 'd', 'e', 'f']
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 = parser.parse_args() metric = args.metric model_path = args.model_path
#!/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", choices=metrics.keys()) parser.add_argument("model_path", help="path to the pickled DBM model") args = parser.parse_args() metric = metrics[args.metric] model = serial.load(args.model_path) metric(model)
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,jamessergeant/pylearn2,fyffyt/pylearn2,hantek/pylearn2,kose-y/pylearn2,cosmoharrigan/pylearn2,matrogers/pylearn2,chrish42/pylearn,JesseLivezey/plankton,pkainz/pylearn2,mkraemer67/pylearn2,JesseLivezey/plankton,chrish42/pylearn,caidongyun/pylearn2,nouiz/pylearn2,w1kke/pylearn2,daemonmaker/pylearn2,lisa-lab/pylearn2,theoryno3/pylearn2,mkraemer67/pylearn2,ddboline/pylearn2,kastnerkyle/pylearn2,sandeepkbhat/pylearn2,lamblin/pylearn2,theoryno3/pylearn2,cosmoharrigan/pylearn2,pombredanne/pylearn2,jeremyfix/pylearn2,junbochen/pylearn2,fishcorn/pylearn2,pombredanne/pylearn2,ddboline/pylearn2,nouiz/pylearn2,fishcorn/pylearn2,KennethPierce/pylearnk,JesseLivezey/plankton,bartvm/pylearn2,pombredanne/pylearn2,lunyang/pylearn2,hantek/pylearn2,goodfeli/pylearn2,goodfeli/pylearn2,matrogers/pylearn2,pkainz/pylearn2,Refefer/pylearn2,lamblin/pylearn2,TNick/pylearn2,KennethPierce/pylearnk,TNick/pylearn2,hantek/pylearn2,hantek/pylearn2,kastnerkyle/pylearn2,lancezlin/pylearn2,alexjc/pylearn2,sandeepkbhat/pylearn2,lisa-lab/pylearn2,junbochen/pylearn2,JesseLivezey/pylearn2,w1kke/pylearn2,mclaughlin6464/pylearn2,lancezlin/pylearn2,hyqneuron/pylearn2-maxsom,fulmicoton/pylearn2,lamblin/pylearn2,pkainz/pylearn2,jamessergeant/pylearn2,woozzu/pylearn2,JesseLivezey/pylearn2,TNick/pylearn2,fishcorn/pylearn2,goodfeli/pylearn2,theoryno3/pylearn2,hyqneuron/pylearn2-maxsom,mclaughlin6464/pylearn2,lancezlin/pylearn2,lunyang/pylearn2,se4u/pylearn2,w1kke/pylearn2,chrish42/pylearn,TNick/pylearn2,daemonmaker/pylearn2,woozzu/pylearn2,kastnerkyle/pylearn2,lisa-lab/pylearn2,msingh172/pylearn2,hyqneuron/pylearn2-maxsom,lunyang/pylearn2,theoryno3/pylearn2,sandeepkbhat/pylearn2,chrish42/pylearn,w1kke/pylearn2,skearnes/pylearn2,ashhher3/pylearn2,abergeron/pylearn2,CIFASIS/pylearn2,KennethPierce/pylearnk,junbochen/pylearn2,fulmicoton/pylearn2,Refefer/pylearn2,skearnes/pylearn2,sandeepkbhat/pylearn2,goodfeli/pylearn2,kose-y/pylearn2,se4u/pylearn2,JesseLivezey/plankton,Refefer/pylearn2,shiquanwang/pylearn2,CIFASIS/pylearn2,JesseLivezey/pylearn2,mclaughlin6464/pylearn2,fulmicoton/pylearn2,se4u/pylearn2,kose-y/pylearn2,shiquanwang/pylearn2,caidongyun/pylearn2,mkraemer67/pylearn2,aalmah/pylearn2,JesseLivezey/pylearn2,hyqneuron/pylearn2-maxsom,aalmah/pylearn2,ddboline/pylearn2,jeremyfix/pylearn2,fyffyt/pylearn2,fishcorn/pylearn2,alexjc/pylearn2,junbochen/pylearn2,daemonmaker/pylearn2,daemonmaker/pylearn2,nouiz/pylearn2,CIFASIS/pylearn2,Refefer/pylearn2,abergeron/pylearn2,cosmoharrigan/pylearn2,woozzu/pylearn2,lancezlin/pylearn2,msingh172/pylearn2,skearnes/pylearn2,bartvm/pylearn2,ddboline/pylearn2,caidongyun/pylearn2,msingh172/pylearn2,woozzu/pylearn2,ashhher3/pylearn2,aalmah/pylearn2,jamessergeant/pylearn2,msingh172/pylearn2,shiquanwang/pylearn2,caidongyun/pylearn2,shiquanwang/pylearn2,jamessergeant/pylearn2,aalmah/pylearn2,jeremyfix/pylearn2,ashhher3/pylearn2,bartvm/pylearn2,CIFASIS/pylearn2,kastnerkyle/pylearn2,jeremyfix/pylearn2,nouiz/pylearn2,fyffyt/pylearn2,fyffyt/pylearn2,matrogers/pylearn2,lunyang/pylearn2,mkraemer67/pylearn2,kose-y/pylearn2
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'); parser.add_argument('--plink_in', type=argparse.FileType('r'), help='Path to a plink association file https://www.cog-genomics.org/plink2/formats#assoc') return parser.parse_args() def input_files(parsed_args): """Returns a list of input files that were passed on the command line parsed_args: the result of parsing the command-line arguments """ if parsed_args.plink_in: print "Plink input: "+str(parsed_args.plink_in.name); parsed = parsed_command_line() input_files(parsed)
#!/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 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'); parser.add_argument('--plink_assoc_in', type=argparse.FileType('r'), help='Path to a plink association file https://www.cog-genomics.org/plink2/formats#assoc') return parser.parse_args() def input_files(parsed_args): """Returns a list of input files that were passed on the command line parsed_args: the result of parsing the command-line arguments """ files=[] if parsed_args.plink_assoc_in: files.append(InputFile("plink_assoc", parsed_args.plink_assoc_in.name)) return files def plink_assoc_to_networkx(input_path, output_path): """Create a new networkx formatted file at output_path""" pass converters = {('plink_assoc','networkx'):plink_assoc_to_networkx} parsed = parsed_command_line() print ",".join([str(i) for i in input_files(parsed)])
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 not be necessary for standard use cases. Args: name (str): Name of this analysis. If ``signals`` is not specified, this also becomes the namespace for the Socket.IO connection and has to match the frontend's :js:class:`Databench` ``name``. import_name (str): Usually the file name ``__name__`` where this analysis is instantiated. signals (optional): Inject an instance of :class:`databench.Signals`. blueprint (optional): Inject an instance of a :class:`flask.Blueprint`. """ def __init__( self, name, import_name, signals=None, blueprint=None ): LIST_ALL.append(self) self.name = name self.import_name = import_name if not signals: self.signals = databench.signals.Signals(name) else: self.signals = signals if not blueprint: self.blueprint = Blueprint( name, import_name, template_folder='templates', static_folder='static', ) else: self.blueprint = blueprint self.show_in_index = True @self.blueprint.route('/') def render_index(): """Renders the main analysis frontend template.""" return render_template(self.name+'.html')
"""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 not be necessary for standard use cases. Args: name (str): Name of this analysis. If ``signals`` is not specified, this also becomes the namespace for the Socket.IO connection and has to match the frontend's :js:class:`Databench` ``name``. import_name (str): Usually the file name ``__name__`` where this analysis is instantiated. signals (optional): Inject an instance of :class:`databench.Signals`. blueprint (optional): Inject an instance of a :class:`flask.Blueprint`. """ def __init__( self, name, import_name, signals=None, blueprint=None ): LIST_ALL.append(self) self.show_in_index = True self.name = name self.import_name = import_name if not signals: self.signals = databench.signals.Signals(name) else: self.signals = signals if not blueprint: self.blueprint = Blueprint( name, import_name, template_folder='templates', static_folder='static', ) else: self.blueprint = blueprint self.blueprint.add_url_rule('/', 'render_index', self.render_index) def render_index(self): """Renders the main analysis frontend template.""" return render_template(self.name+'.html')
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.lock = None logger = logging.getLogger(__name__) logger.addHandler(NullHandler()) del logging, logger, NullHandler
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 when mandatory kernel module not found. """ class TcCommandExecutionError(Exception): """ Exception raised when failed to execute a ``tc`` command. """ class TcAlreadyExist(TcCommandExecutionError): """ Exception raised when a traffic shaping rule already exist. """ class EmptyParameterError(ValueError): """ Exception raised when a parameter value is empty value. """ class InvalidParameterError(ValueError): """ Exception raised when an invalid parameter specified for a traffic shaping rule. """ class UnitNotFoundError(InvalidParameterError): """ """
# 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 when mandatory kernel module not found. """ class TcCommandExecutionError(Exception): """ Exception raised when failed to execute a ``tc`` command. """ class TcAlreadyExist(TcCommandExecutionError): """ Exception raised when a traffic shaping rule already exist. """ class EmptyParameterError(ValueError): """ Exception raised when a parameter value is empty value. """ class InvalidParameterError(ValueError): """ Exception raised when an invalid parameter specified for a traffic shaping rule. """ def __init__(self, *args, **kwargs): self.__value = kwargs.pop("value", None) self.__expected = kwargs.pop("expected", None) super(ValueError, self).__init__(*args) def __str__(self, *args, **kwargs): item_list = [ValueError.__str__(self, *args, **kwargs)] extra_item_list = [] if self.__expected: extra_item_list.append("expected={}".format(self.__expected)) if self.__value: extra_item_list.append("value={}".format(self.__value)) if extra_item_list: item_list.extend([":", ", ".join(extra_item_list)]) return " ".join(item_list) def __repr__(self, *args, **kwargs): return self.__str__(*args, **kwargs) class UnitNotFoundError(InvalidParameterError): """ """
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[position - 1] > current_value: a_list[position] = a_list[position - 1] position -= 1 a_list[position] = current_value def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('a_list: \n{}'.format(a_list)) print('By insertion sort: ') insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
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 while position > 0 and a_list[position - 1] > current_value: a_list[position] = a_list[position - 1] position -= 1 a_list[position] = current_value def main(): a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] print('a_list: \n{}'.format(a_list)) print('By insertion sort: ') insertion_sort(a_list) print(a_list) if __name__ == '__main__': main()
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.DateTimeField(null=True) raw = JsonField() normalized = JsonField() class HarvesterResponse(models.Model): method = models.TextField(primary_key=True) url = models.TextField(primary_key=True, required=True) # Raw request data ok = models.BooleanField() content = models.BinaryField() encoding = models.TextField() headers_str = models.TextField() status_code = models.IntegerField() time_made = models.DateTimeField(auto_now=True) def json(self): return json.loads(self.content) @property def headers(self): return CaseInsensitiveDict(json.loads(self.headers_str)) @property def text(self): return six.u(self.content)
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: return list.get(language=language) except ObjectDoesNotExist: try: return list.get(language='en') except ObjectDoesNotExist: return list.all()[0]
"""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: return queryset.get(language=language) except ObjectDoesNotExist: try: return queryset.get(language='en') except ObjectDoesNotExist: return queryset.all()[0]
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(ciphertext) assert result['key'] == 88 assert result['plaintext'] == b"Cooking MC's like a pound of bacon" def test_hamming_distance(): assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37 def test_fixed_xor(): input = bytes.fromhex("1c0111001f010100061a024b53535009181c") key = bytes.fromhex("686974207468652062756c6c277320657965") assert fixed_xor(input, key) == b"the kid don't play"
#!/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_singlechar_key(ciphertext) assert result['key'] == 88 assert result['plaintext'] == b"Cooking MC's like a pound of bacon" def test_hamming_distance(): assert hamming_distance(b"this is a test", b"wokka wokka!!!") == 37 def test_fixed_xor(): input = bytes.fromhex("1c0111001f010100061a024b53535009181c") key = bytes.fromhex("686974207468652062756c6c277320657965") assert fixed_xor(input, key) == b"the kid don't play" def test_transpose(): chunks = [b'adg', b'beh', b'cfi'] assert transpose(chunks) == b'abcdefghi'
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.phonenumber import to_python class PhoneNumberField(CharField): default_error_messages = { 'invalid': _('Enter a valid phone number.'), } default_validators = [validate_international_phonenumber] def to_python(self, value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): raise ValidationError(self.error_messages['invalid']) return phone_number
# -*- 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.phonenumber import to_python class PhoneNumberField(CharField): default_error_messages = { 'invalid': _('Enter a valid phone number.'), } default_validators = [validate_international_phonenumber] def __init__(self, *args, **kwargs): super(PhoneNumberField, self).__init__(*args, **kwargs) self.widget.input_type = 'tel' def to_python(self, value): phone_number = to_python(value) if phone_number and not phone_number.is_valid(): raise ValidationError(self.error_messages['invalid']) return phone_number
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_renderer() interval = 0.5 print '{"version": 1, "custom_workspace": true}' print '[' print ' [[],[]]' lock = Lock() def render( event=None, data=None, sub=None ): global lock lock.acquire() s = '[\n' + powerline.render(side='right')[:-2] + '\n]\n' s += ',[\n' + powerline.render(side='left' )[:-2] + '\n]' print ',[\n' + s + '\n]' sys.stdout.flush() lock.release() sub = i3.Subscription( render, 'workspace' ) while True: start_time = monotonic() render() time.sleep(max(interval - (monotonic() - start_time), 0.1))
#!/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_renderer() interval = 0.5 print '{"version": 1, "custom_workspace": true}' print '[' print ' [[],[]]' lock = Lock() def render( event=None, data=None, sub=None ): global lock with lock: s = '[\n' + powerline.render(side='right')[:-2] + '\n]\n' s += ',[\n' + powerline.render(side='left' )[:-2] + '\n]' print ',[\n' + s + '\n]' sys.stdout.flush() sub = i3.Subscription( render, 'workspace' ) while True: start_time = monotonic() render() time.sleep(max(interval - (monotonic() - start_time), 0.1))
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/powerline,xxxhycl2010/powerline,EricSB/powerline,firebitsbr/powerline,cyrixhero/powerline,russellb/powerline,wfscheper/powerline,wfscheper/powerline,cyrixhero/powerline,seanfisk/powerline,firebitsbr/powerline,magus424/powerline,dragon788/powerline,junix/powerline,magus424/powerline,kenrachynski/powerline,blindFS/powerline,magus424/powerline,EricSB/powerline,areteix/powerline,lukw00/powerline,bartvm/powerline,prvnkumar/powerline,bezhermoso/powerline,blindFS/powerline,QuLogic/powerline,DoctorJellyface/powerline,dragon788/powerline,s0undt3ch/powerline,QuLogic/powerline,xxxhycl2010/powerline,IvanAli/powerline,firebitsbr/powerline,bezhermoso/powerline,bartvm/powerline,keelerm84/powerline,xfumihiro/powerline,s0undt3ch/powerline,S0lll0s/powerline,xxxhycl2010/powerline,russellb/powerline,Liangjianghao/powerline,kenrachynski/powerline,Luffin/powerline,wfscheper/powerline,prvnkumar/powerline,Luffin/powerline,lukw00/powerline,bezhermoso/powerline,junix/powerline,S0lll0s/powerline,Luffin/powerline,darac/powerline,S0lll0s/powerline,seanfisk/powerline,dragon788/powerline,EricSB/powerline,DoctorJellyface/powerline,lukw00/powerline,Liangjianghao/powerline,areteix/powerline,xfumihiro/powerline,junix/powerline,prvnkumar/powerline
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 is given?""" run_nbgrader([], retcode=1) def test_generate_config(self): """Is the config file properly generated?""" # it already exists, because we create it in conftest.py os.remove("nbgrader_config.py") # try recreating it run_nbgrader(["--generate-config"]) assert os.path.isfile("nbgrader_config.py") # does it fail if it already exists? run_nbgrader(["--generate-config"], retcode=1) def test_check_version(self, capfd): """Is the version the same regardless of how we run nbgrader?""" out1 = '\n'.join( run_command(["nbgrader", "--version"]).splitlines()[-3:] ).strip() out2 = '\n'.join( run_nbgrader(["--version"], stdout=True).splitlines()[-3:] ).strip() assert out1 == out2
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 is given?""" run_nbgrader([], retcode=1) def test_generate_config(self): """Is the config file properly generated?""" # it already exists, because we create it in conftest.py os.remove("nbgrader_config.py") # try recreating it run_nbgrader(["--generate-config"]) assert os.path.isfile("nbgrader_config.py") # does it fail if it already exists? run_nbgrader(["--generate-config"], retcode=1) def test_check_version(self, capfd): """Is the version the same regardless of how we run nbgrader?""" out1 = '\n'.join( run_command([sys.executable, "-m", "nbgrader", "--version"]).splitlines()[-3:] ).strip() out2 = '\n'.join( run_nbgrader(["--version"], stdout=True).splitlines()[-3:] ).strip() assert out1 == out2
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 django.shortcuts import get_object_or_404, render_to_response, render from tviit.models import Tviit, TviitForm class IndexView(View): @method_decorator(login_required(login_url='/login/')) def get(self, request, *args, **kwargs): template = loader.get_template('tviit/index.html') context = { 'tviit_form': TviitForm, } return HttpResponse(template.render(context, request))
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 django.shortcuts import get_object_or_404, render_to_response, render from tviit.models import Tviit, TviitForm from django.contrib.auth.models import User from user_profile.models import UserProfile class IndexView(View): @method_decorator(login_required(login_url='/login/')) def get(self, request, *args, **kwargs): template = loader.get_template('tviit/index.html') profile = UserProfile.objects.get(user=request.user) tviits = get_latest_tviits(profile) print(tviits) context = { 'profile': profile, 'tviit_form': TviitForm, 'tviits': tviits, } return HttpResponse(template.render(context, request)) # Get all the tviits, which aren't replies def get_latest_tviits(profile): follows = User.objects.filter(pk__in=profile.follows.all()) tviits = Tviit.objects.filter(sender__in=follows) return tviits
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 ghswitches def make_github_markdown_collector(opts): """ Creates a Collector object used for parsing Markdown files with a GitHub style anchor transformation :param opts: Namespace object of options for the AnchorHub program. Usually created from command-line arguments. It must contain a 'wrapper_regex' attribute :return: a Collector object designed for collecting tag/anchor pairs from Markdown files using GitHub style anchors """ assert hasattr(opts, 'wrapper_regex') atx = MarkdownATXCollectorStrategy(opts) code_block_switch = ghswitches.code_block_switch strategies = [atx] switches = [code_block_switch] return Collector(converter.create_anchor_from_header, strategies, switches=switches)
""" 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 anchorhub.builtin.github.switches as ghswitches def make_github_markdown_collector(opts): """ Creates a Collector object used for parsing Markdown files with a GitHub style anchor transformation :param opts: Namespace object of options for the AnchorHub program. Usually created from command-line arguments. It must contain a 'wrapper_regex' attribute :return: a Collector object designed for collecting tag/anchor pairs from Markdown files using GitHub style anchors """ assert hasattr(opts, 'wrapper_regex') atx = MarkdownATXCollectorStrategy(opts) setext = MarkdownSetextCollectorStrategy(opts) code_block_switch = ghswitches.code_block_switch strategies = [atx, setext] switches = [code_block_switch] return Collector(converter.create_anchor_from_header, strategies, switches=switches)
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 import BuildStep from chromeos_build_step import ChromeOSBuildStep from install import Install from utils import ssh_utils import os import sys class ChromeOSInstall(ChromeOSBuildStep, Install): def _PutSCP(self, executable): ssh_utils.PutSCP(local_path=os.path.join('out', 'config', 'chromeos-' + self._args['board'], self._configuration, executable), remote_path='/usr/local/bin/skia_%s' % executable, username=self._ssh_username, host=self._ssh_host, port=self._ssh_port) def _Run(self): super(ChromeOSInstall, self)._Run() self._PutSCP('tests') self._PutSCP('gm') self._PutSCP('render_pictures') self._PutSCP('render_pdfs') self._PutSCP('bench') self._PutSCP('bench_pictures') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSInstall))
#!/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 import BuildStep from chromeos_build_step import ChromeOSBuildStep from install import Install from utils import ssh_utils import os import sys class ChromeOSInstall(ChromeOSBuildStep, Install): def _PutSCP(self, executable): # First, make sure that the program isn't running. ssh_utils.RunSSH(self._ssh_username, self._ssh_host, self._ssh_port, ['killall', 'skia_%s' % executable]) ssh_utils.PutSCP(local_path=os.path.join('out', 'config', 'chromeos-' + self._args['board'], self._configuration, executable), remote_path='/usr/local/bin/skia_%s' % executable, username=self._ssh_username, host=self._ssh_host, port=self._ssh_port) def _Run(self): super(ChromeOSInstall, self)._Run() self._PutSCP('tests') self._PutSCP('gm') self._PutSCP('render_pictures') self._PutSCP('render_pdfs') self._PutSCP('bench') self._PutSCP('bench_pictures') if '__main__' == __name__: sys.exit(BuildStep.RunBuildStep(ChromeOSInstall))
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 2bbb7eff-a529-9590-31e7-b0007b416f81
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-buildbot,google/skia-buildbot
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 ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 fake = Factory.create('it_IT') for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') website_name = website_name.replace("'", '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
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 ('{}', '{}', '{}', '{}', '{}'); ''' MAX_MEDIA=100 fake = Factory.create() for i in xrange(MAX_MEDIA): # Generate random data for the media media_name = fake.name() + ' Media ' + str(i) website_name = media_name.lower().replace(' ', '') website_url = 'https://{}.com'.format(website_name) cat_txt = website_name cat_img = 'http://lorempixel.com/500/500/cats/{}'.format(cat_txt) logo_url = cat_img facebookpage_url = 'https://facebook.com/{}'.format(website_name) slogan = ' '.join(fake.text().split()[:5]) # Parse the SQL command insert_sql = sql.format(media_name, website_url, logo_url, facebookpage_url, slogan) # insert to the database try: cursor.execute(insert_sql) db.commit() except mysql.Error as err: print("Something went wrong: {}".format(err)) db.rollback() # Close the DB connection db.close()
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,CodeRiderz/rojak,rawgni/rojak,pyk/rojak,rawgni/rojak,rawgni/rojak,rawgni/rojak,pyk/rojak,reinarduswindy/rojak,reinarduswindy/rojak,CodeRiderz/rojak,CodeRiderz/rojak,rawgni/rojak,rawgni/rojak,reinarduswindy/rojak,reinarduswindy/rojak,bobbypriambodo/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) token = Column(String(128), unique=True, nullable=False) def __repr__(self): return '<Speaker %r>' % self.id
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 = Column(String(128), unique=True, nullable=False) def __repr__(self): return '<Speaker %r>' % self.id
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_datasets(datasets, task, bert_version): bert_str = bert_version.replace("-", "_") filename = f"{task}_{bert_str}_spacy_datasets" filepath = f"{os.environ['GLUEDATA']}/datasets/{filename}.dill" with open(filepath, "wb") as f: dill.dump(datasets, f) return True if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--task", type=str) parser.add_argument("--bert_version", type=str, default="bert-base-uncased") args = parser.parse_args() assert args.task.isupper() datasets = make_datasets(args.task, args.bert_version) if pickle_datasets(datasets, args.task, args.bert_version): print(f"FINISHED: {args.task}") else: print(f"FAILED: {args.task}")
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 ) return datasets def pickle_datasets(datasets, task, bert_version): bert_str = bert_version.replace("-", "_") filename = f"{task}_{bert_str}_spacy_datasets" filepath = f"{os.environ['GLUEDATA']}/datasets/{filename}.dill" with open(filepath, "wb") as f: dill.dump(datasets, f) return True if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--task", type=str) parser.add_argument("--bert_version", type=str, default="bert-base-uncased") args = parser.parse_args() assert args.task.isupper() datasets = make_datasets(args.task, args.bert_version) if pickle_datasets(datasets, args.task, args.bert_version): print(f"FINISHED: {args.task}") else: print(f"FAILED: {args.task}")
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") text_content = models.CharField(max_length=400) display_from = models.DateField() display_until = models.DateField() active = models.BooleanField(default=True) text_theme = models.CharField(max_length=10, choices=settings.EDITOS_THEMES, default=settings.EDITOS_DEFAULT_THEME) def __unicode__(self): return self.title
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") text_content = models.CharField(max_length=400) display_from = models.DateField() display_until = models.DateField() active = models.BooleanField(default=True) text_theme = models.CharField(max_length=10, choices=settings.EDITOS_THEMES, default=settings.EDITOS_DEFAULT_THEME) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) def __unicode__(self): return self.title
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, box_size=20): name = sha1(f'{data}-{box_size}'.encode('utf-8')).hexdigest() filename = f'{name}.svg' filepath = QR_CACHE_PATH.joinpath(filename) if not filepath.exists(): img = qr.make(data, image_factory=SvgPathImage, box_size=box_size) img.save(str(filepath)) with filepath.open() as fp: return Markup(fp.read())
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 = sha1(f'{data}-{box_size}'.encode('utf-8')).hexdigest() filename = f'{name}.svg' filepath = QR_CACHE_PATH.joinpath(filename) if not filepath.exists(): img = qr.make(data, image_factory=SvgPathImage, box_size=box_size) img.save(str(filepath)) with filepath.open() as fp: return Markup(fp.read())
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/bedrock,sylvestre/bedrock,mozilla/bedrock,flodolo/bedrock,flodolo/bedrock,sylvestre/bedrock,MichaelKohler/bedrock,pascalchevrel/bedrock,mozilla/bedrock,alexgibson/bedrock,craigcook/bedrock,sylvestre/bedrock
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) file_path = settings.BASE_DIR + '/OIDC_RSA_KEY.pem' with open(file_path, 'w') as f: f.write(key.exportKey('PEM')) self.stdout.write('RSA key successfully created at: ' + file_path) except Exception as e: self.stdout.write('Something goes wrong: ' + e.message)
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) file_path = settings.BASE_DIR + '/OIDC_RSA_KEY.pem' with open(file_path, 'w') as f: f.write(key.exportKey('PEM')) self.stdout.write('RSA key successfully created at: ' + file_path) except Exception as e: self.stdout.write('Something goes wrong: {0}'.format(e))
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-oidc-provider,juanifioren/django-oidc-provider,wayward710/django-oidc-provider
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 == 'WeatherPathParameter': config = current_app.cea_config locator = cea.inputlocator.InputLocator(config.scenario) params['choices'] = {wn: locator.get_weather( wn) for wn in locator.get_weather_names()} elif p.typename == 'DatabasePathParameter': params['choices'] = p._choices return params
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"] = "" if isinstance(p, cea.config.ChoiceParameter): params['choices'] = p._choices if p.typename == 'WeatherPathParameter': config = current_app.cea_config locator = cea.inputlocator.InputLocator(config.scenario) params['choices'] = {wn: locator.get_weather( wn) for wn in locator.get_weather_names()} elif p.typename == 'DatabasePathParameter': params['choices'] = p._choices return params
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): fk = getattr(instance, f.name) if hasattr(fk, 'get_absolute_url'): value = mark_safe(u'<a href="%s">%s</a>' % ( fk.get_absolute_url(), fk)) else: value = unicode(fk) elif f.choices: value = getattr(instance, 'get_%s_display' % f.name)() else: value = unicode(getattr(instance, f.name)) yield (f.verbose_name, value)
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.FieldDoesNotExist: attr = getattr(instance, name) if hasattr(attr, '__call__'): yield (name, attr()) yield (name, attr) continue if isinstance(f, models.ForeignKey): fk = getattr(instance, f.name) if hasattr(fk, 'get_absolute_url'): value = mark_safe(u'<a href="%s">%s</a>' % ( fk.get_absolute_url(), fk)) else: value = unicode(fk) elif f.choices: value = getattr(instance, 'get_%s_display' % f.name)() else: value = unicode(getattr(instance, f.name)) yield (f.verbose_name, value)
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(ast, Node): # ast = Node(data=ast) return ast def let_star(ast, env=None): from eche.env import get_default_env from eche.eval import eval_ast inner_env = get_default_env() inner_env.outer = env _, new_bindings, commands_in_new_env = ast new_bindings = partition(2, list(new_bindings.data)) for binding in new_bindings: key, val = binding inner_env[key] = val commands_in_new_env = eval_ast(commands_in_new_env, inner_env) new_ast = eval_ast(commands_in_new_env, inner_env) return new_ast special_forms = { Symbol('def!'): def_exclamation_mark, Symbol('let*'): let_star }
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 isinstance(ast, Node): # ast = Node(data=ast) return ast def let_star(ast, env=None): from eche.env import get_default_env from eche.eval import eval_ast inner_env = get_default_env() inner_env.outer = env _, new_bindings, commands_in_new_env = ast new_bindings = partition(2, list(new_bindings.data)) for binding in new_bindings: key, val = binding inner_env[key] = val commands_in_new_env = eval_ast(commands_in_new_env, inner_env) new_ast = eval_ast(commands_in_new_env, inner_env) return new_ast special_forms = { Symbol('def!'): def_exclamation_mark, Symbol('let*'): let_star }
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 config', unique_for_month='pub_date') text = models.TextField() pub_date = models.DateField( 'date published', auto_now_add=True) tags = models.ManyToManyField( Tag, related_name='blog_posts') startups = models.ManyToManyField( Startup, related_name='blog_posts') def __str__(self): return "{} on {}".format( self.title, self.pub_date.strftime('%Y-%m-%d'))
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 config', unique_for_month='pub_date') text = models.TextField() pub_date = models.DateField( 'date published', auto_now_add=True) tags = models.ManyToManyField( Tag, related_name='blog_posts') startups = models.ManyToManyField( Startup, related_name='blog_posts') class Meta: verbose_name = 'blog post' ordering = ['-pub_date', 'title'] get_latest_by = 'pub_date' def __str__(self): return "{} on {}".format( self.title, self.pub_date.strftime('%Y-%m-%d'))
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 def test_scalar_grid(): """Testing creating a scalar grid.""" bmi = ScalarBmi() grid = Scalar(bmi, grid_id) assert grid.ndim == 0 assert grid.metadata["type"] == "scalar" assert isinstance(grid, xr.Dataset) class TestVector: def get_grid_rank(self, grid_id): return 1 class VectorBmi(_BmiCap): _cls = TestVector def test_vector_grid(): """Testing creating a vector grid.""" bmi = VectorBmi() grid = Vector(bmi, grid_id) assert grid.ndim == 1 assert grid.metadata["type"] == "vector" assert isinstance(grid, xr.Dataset)
"""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 def test_scalar_grid(): """Testing creating a scalar grid.""" bmi = ScalarBmi() grid = Scalar(bmi, grid_id) assert grid.ndim == 0 assert grid.metadata["type"] == "scalar" assert grid.data_vars["mesh"].attrs["type"] == "scalar" assert isinstance(grid, xr.Dataset) class TestVector: def get_grid_rank(self, grid_id): return 1 class VectorBmi(_BmiCap): _cls = TestVector def test_vector_grid(): """Testing creating a vector grid.""" bmi = VectorBmi() grid = Vector(bmi, grid_id) assert grid.ndim == 1 assert grid.metadata["type"] == "vector" assert grid.data_vars["mesh"].attrs["type"] == "vector" assert isinstance(grid, xr.Dataset)
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,*args,**kwargs): multiprocessing.Process.__init__(self,*args,**kwargs) self.queue_pack=shelltoprocess.make_queue_pack() # Put whatever code you want here def run(self): # Put whatever code you want here self.console = shelltoprocess.Console(queue_pack=self.queue_pack) self.console.interact() custom_process = CustomProcess() custom_process.start() 2. Set up the shell in the appropriate part of your code: self.shell = shelltoprocess.Shell(parent_window, queue_pack=custom_process.queue_pack) """ import multiprocessing def make_queue_pack(): """ Creates a "queue pack". This is the one object that connects between the Shell and the Console. The same queue_pack must be fed into both. See package documentation for more info. """ return [multiprocessing.Queue() for _ in range(4)] __all__ = ["Shell", "Console", "make_queue_pack"]
""" 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,*args,**kwargs): multiprocessing.Process.__init__(self,*args,**kwargs) self.queue_pack=shelltoprocess.make_queue_pack() # Put whatever code you want here def run(self): # Put whatever code you want here self.console = shelltoprocess.Console(queue_pack=self.queue_pack) self.console.interact() custom_process = CustomProcess() custom_process.start() 2. Set up the shell in the appropriate part of your code: self.shell = shelltoprocess.Shell(parent_window, queue_pack=custom_process.queue_pack) """ import multiprocessing from shell import Shell from console import Console def make_queue_pack(): """ Creates a "queue pack". This is the one object that connects between the Shell and the Console. The same queue_pack must be fed into both. See package documentation for more info. """ return [multiprocessing.Queue() for _ in range(4)] __all__ = ["Shell", "Console", "make_queue_pack"]
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', 'update_challenges'] def create_token(*args, **kwargs): raise NotImplementedError def delete_token(*args, **kwargs): raise NotImplementedError def add_file(*args, **kwargs): raise NotImplementedError def remove_file(*args, **kwargs): raise NotImplementedError def gen_challenges(filepath, root_seed): secret = getattr(config, 'HEARTBEAT_SECRET') hb = Heartbeat(filepath, secret=secret) hb.generate_challenges(1000, root_seed) files = Files(name=filepath) db.session.add(files) for challenge in hb.challenges: chal = Challenges( filename=filepath, rootseed=root_seed, block=challenge.block, seed=challenge.seed, response=challenge.response, ) db.session.add(chal) db.session.commit() def update_challenges(*args, **kwargs): raise NotImplementedError
#!/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_challenges', 'update_challenges'] def create_token(*args, **kwargs): raise NotImplementedError def delete_token(*args, **kwargs): raise NotImplementedError def add_file(*args, **kwargs): raise NotImplementedError def remove_file(*args, **kwargs): raise NotImplementedError def gen_challenges(filepath, root_seed): secret = getattr(config, 'HEARTBEAT_SECRET') hb = Heartbeat(filepath, secret=secret) hb.generate_challenges(1000, root_seed) files = Files(name=os.path.split(filepath)[1]) db.session.add(files) for challenge in hb.challenges: chal = Challenges( filename=filepath, rootseed=root_seed, block=challenge.block, seed=challenge.seed, response=challenge.response, ) db.session.add(chal) db.session.commit() def update_challenges(*args, **kwargs): raise NotImplementedError
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_folder, *args, **options): news_count = 0 root = Page.get_first_root_node() if root is None: root = Page.add_root(title='Root page') news = import_news(news_folder) for news_story in news: root.add_child(instance=NewsStory( title=news_story['title'], date=news_story['date'], blurb=news_story['blurb'], body=news_story['body'], )) self.stdout.write('Successfully imported %d news items\n' % news_count)
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_folder, *args, **options): news_count = 0 root = Page.get_first_root_node() if root is None: root = Page.add_root(title='Root page') news = import_news(news_folder) for news_story in news: root.add_child(instance=NewsStory( title=news_story['title'], date=news_story['date'], blurb=news_story['blurb'], body=news_story['body'], )) news_count += 1 self.stdout.write('Successfully imported %d news items\n' % news_count)
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.models import Bookmark from bookmarks.serializers import BookmarkSerializer class BookmarkListCreateAPIView(ListAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer resource_name = 'bookmark' action = 'list' renderer_classes = (JSONRenderer,) filter_backends = (SearchFilter, OrderingFilter) search_fields = ('url', 'title') ordering_fields = ('id', 'url', 'title', 'bookmarked_at') class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer lookup_field = 'bookmark_id'
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 bookmarks.serializers import BookmarkSerializer class BookmarkListCreateAPIView(ListCreateAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer resource_name = 'bookmark' action = 'list' renderer_classes = (JSONRenderer,) filter_backends = (SearchFilter, OrderingFilter) search_fields = ('url', 'title') ordering_fields = ('id', 'url', 'title', 'bookmarked_at') class BookmarkRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView): queryset = Bookmark.objects.all() serializer_class = BookmarkSerializer lookup_field = 'bookmark_id'
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', data={'action': 'check_online'}) if r: # status: OK infos = r.text.split(',') if len(infos) == 5: # Decode successfully return dict(username=infos[1], byte=infos[2], duration=infos[4]) # Failed to get infos return False def arp_scan(): """Generate (IP, MAC) pairs using arp-scan""" proc = subprocess.Popen(['sudo', 'arp-scan', '-lq'], stdout=subprocess.PIPE) out = proc.stdout # Skip the first two lines. next(out) next(out) # Parse IPs & MACs for line in out: infos = line.split() if not infos: # Empty line at the end of the output return if len(infos) < 2: raise RuntimeError('Invalid output of arp-scan: "%s"' % line) yield (infos[0], infos[1]) # Generate (IP, MAC)
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', data={'action': 'check_online'}) if r: # status: OK infos = r.text.split(',') if len(infos) == 5: # Decode successfully return dict(username=infos[1], byte=infos[2], duration=infos[4]) # Failed to get infos return False def arp_scan(): """Generate (IP, MAC) pairs using arp-scan""" proc = subprocess.Popen(['sudo', 'arp-scan', '-lq'], stdout=subprocess.PIPE) out = proc.stdout # Skip the first two lines. next(out) next(out) # Parse IPs & MACs for line in out: infos = line.split() if not infos: # Empty line at the end of the output return if len(infos) < 2: raise RuntimeError('Invalid output of arp-scan: "%s"' % line) yield (infos[0], infos[1]) # Generate (IP, MAC)
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 language. :param lang: ISO 639-1 language code specifying language to try to retrieve :param key: name of the command :return: description in `lang` for `key` """ if os.path.getmtime('help.json') > HelpManager._last_modified: HelpManager.load_help() lang = lang.lower() key = key.lower() if lang not in HelpManager._help_dict: print(f"[ERROR] tried to access `_help_dict[{lang}]`") lang = 'en' if key not in HelpManager._help_dict[lang]: print(f"[ERROR] tried to access `_help_dict[{lang}][{key}]`") return None return HelpManager._help_dict[lang][key] @staticmethod def load_help(): try: with open('help.json', 'r', encoding='utf-8') as infile: HelpManager._help_dict = json.load(infile) HelpManager._last_modified = os.path.getmtime('help.json') except OSError as ex: print("[ERROR] Cannot find `help.json`") print(ex) print(HelpManager._help_dict)
"""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 language. :param lang: ISO 639-1 language code specifying language to try to retrieve :param key: name of the command :return: description in `lang` for `key` """ if os.path.getmtime('help.json') > HelpManager._last_modified: HelpManager.load_help() lang = lang.lower() key = key.lower() if lang not in HelpManager._help_dict: print(f"[ERROR] tried to access `_help_dict[{lang}]`") lang = 'en' if key not in HelpManager._help_dict[lang]: print(f"[ERROR] tried to access `_help_dict[{lang}][{key}]`") return None return HelpManager._help_dict[lang][key] @staticmethod def load_help(): try: with open('help.json', 'r', encoding='utf-8') as infile: HelpManager._help_dict = json.load(infile) HelpManager._last_modified = os.path.getmtime('help.json') except OSError as ex: print("[ERROR] Cannot find `help.json`") print(ex)
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 = dict( time = patch('time.sleep'), rtm = patch('rtm.createRTM'), ) self.mocks = dict() for (k, v) in self.patches.items(): self.mocks[k] = v.start() def test_sleep_before_rtm(self): imp = rtmimp(['task']) imp._rtm = Mock() assert not self.mocks['time'].called # assert that it is our mock object assert_equal(imp.rtm, imp._rtm) self.mocks['time'].assert_called_once_with(1) # test calling other methods imp.rtm.foo.bar self.mocks['time'].assert_has_calls([ call(1), call(1) ]) # not used this time assert not self.mocks['rtm'].called def test_deobfuscator(self): imp = rtmimp(['task']) imp.key = 'a92' assert imp.key == '21a' imp.secret = 'deadbeef' assert imp.secret == '56253667'
# 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 = patch('time.sleep'), rtm = patch('rtm.createRTM'), ) self.mocks = dict() for (k, v) in self.patches.items(): self.mocks[k] = v.start() def test_sleep_before_rtm(self): imp = Importer(['task']) imp._rtm = Mock() assert not self.mocks['time'].called # Assert that it is in fact our mock object. assert_equal(imp.rtm, imp._rtm) self.mocks['time'].assert_called_once_with(1) # Test chaining method calls. imp.rtm.foo.bar self.mocks['time'].assert_has_calls([ call(1), call(1) ]) # Not used this time. assert not self.mocks['rtm'].called def test_deobfuscator(self): imp = Importer(['task']) imp.key = 'a92' assert imp.key == '21a' imp.secret = 'deadbeef' assert imp.secret == '56253667'
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 from sqlalchemy.dialects import postgresql def upgrade(): op.alter_column('equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=True) def downgrade(): op.alter_column( 'equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=False )
""" 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 from sqlalchemy.dialects import postgresql def upgrade(): op.alter_column('equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=True) def downgrade(): op.execute("UPDATE equipments_provider SET instances = '{null_instance}';") op.alter_column( 'equipments_provider', 'instances', existing_type=postgresql.ARRAY(sa.TEXT()), nullable=False )
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': # pragma: no cover from .windows_events import * else: from .unix_events import * # pragma: no cover __all__ = (futures.__all__ + events.__all__ + locks.__all__ + transports.__all__ + protocols.__all__ + streams.__all__ + tasks.__all__)
"""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 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': # pragma: no cover from .windows_events import * else: from .unix_events import * # pragma: no cover __all__ = (futures.__all__ + events.__all__ + locks.__all__ + transports.__all__ + protocols.__all__ + streams.__all__ + tasks.__all__)
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,Martiusweb/asyncio,1st1/asyncio,gvanrossum/asyncio,manipopopo/asyncio,jashandeep-sohi/asyncio,vxgmichel/asyncio,haypo/trollius,gsb-eng/asyncio,gvanrossum/asyncio,jashandeep-sohi/asyncio,haypo/trollius
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_sql(filename, nb_users): with open(filename, "w") as sql_file: header = """DROP DATABASE tests; CREATE DATABASE tests; USE tests; CREATE TABLE accounts (user VARCHAR(20),password VARCHAR(20));""" sql_file.write(header) for x in xrange(nb_users): line = """INSERT into accounts (user, password) VALUES ("{uname}", "{uname}");\n""".format(uname=str(1000+x)) sql_file.write(line) def main(argv=None): if argv == None: argv = sys.argv argparser = argparse.ArgumentParser(description="Prepare load tests for Flexisip.") argparser.add_argument('-N', '--users', help="How many different users should be registering to flexisip", dest="users", default=5000) args, additional_args = argparser.parse_known_args() write_csv("users.csv", args.users) write_sql("users.sql", args.users) if __name__ == '__main__': main()
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_sql(filename, nb_users): with open(filename, "w") as sql_file: header = """DROP DATABASE IF EXISTS tests; CREATE DATABASE tests; USE tests; CREATE TABLE accounts (user VARCHAR(20),password VARCHAR(20));""" sql_file.write(header) for x in xrange(nb_users): line = """INSERT into accounts (user, password) VALUES ("{uname}", "{uname}");\n""".format(uname=str(1000+x)) sql_file.write(line) def main(argv=None): if argv == None: argv = sys.argv argparser = argparse.ArgumentParser(description="Prepare load tests for Flexisip.") argparser.add_argument('-N', '--users', help="How many different users should be registering to flexisip", dest="users", default=5000) args, additional_args = argparser.parse_known_args() write_csv("users.csv", args.users) write_sql("users.sql", args.users) if __name__ == '__main__': main()
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 def delete(self, data): """ Delete external plugin resources """ pass def render(self, data): """ Render plugin """ 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): """ Persist external plugin resources and return content string for plugin data """ return data def delete(self, data): """ Delete external plugin resources """ pass def render(self, data): """ Render plugin """ return 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): pass device = mock.MagicMock() AsyncioTransport(device, loop, callback=handler) loop._run_once() device.write.assert_has_call(bytearray(RESET_PACKET)) device.write.assert_has_call(bytearray(STATUS_PACKET))
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.http_method_names = list(handler.http_method_names.keys()) return injector.let(as_view=handler.as_view) def create_handler(from_class): class Handler(from_class): http_method_names = OrderedDict.fromkeys(["head", "options"]) return Handler def apply_http_methods(handler, injector): for method in ["get", "post", "put", "patch", "delete", "head", "options", "trace"]: if method in injector: def __view(self, request, *args, **kwargs): return injector.let( view=self, request=request, args=args, kwargs=kwargs, user=this.request.user, ).trace() handler.http_method_names[method] = None setattr(handler, method, __view)
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_http_methods(handler) return injector.let(as_view=handler.as_view) def create_handler(from_class): class Handler(from_class): http_method_names = OrderedDict.fromkeys(["head", "options"]) return Handler def apply_http_methods(handler, injector): for method in ["get", "post", "put", "patch", "delete", "head", "options", "trace"]: if method in injector: def __view(self, request, *args, **kwargs): ns = injector.let( view=self, request=request, args=args, kwargs=kwargs, user=this.request.user, ) return getattr(ns, __view.method)() __view.method = method handler.http_method_names[method] = None setattr(handler, method, __view) def finalize_http_methods(handler): handler.http_method_names = list(handler.http_method_names.keys())
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' not in kwargs: kwargs['headers'] = {} kwargs['headers']['user-agent'] = USER_AGENT return func(*args, **kwargs) return wrapper get = add_args(requests.get) post = add_args(requests.post) put = add_args(requests.put)
''' 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: kwargs['headers']['user-agent'] = USER_AGENT except KeyError: kwargs['headers'] = {'user-agent': USER_AGENT} if 'token' in kwargs: token = kwargs.pop('token') kwargs['headers']['Authorization'] = 'Token %s' % token return func(*args, **kwargs) return wrapper get = add_args(requests.get) post = add_args(requests.post) put = add_args(requests.put)
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, widget=forms.TextInput(attrs=attributes), label="Username", error_message={'invalid': "This value may contain only letters, numbers and @.+- characters."} ) email = forms.EmailField() def clean_username(self): username = self.cleaned_data["username"] existing = User.objects.filter(username__iexact=username) if existing.exists(): raise forms.ValidationError("A user with that username already exists.") else: return self.cleaned_data["username"] class SettingsForm(forms.Form): email = forms.EmailField() xsede_username = forms.CharField(max_length=50, required=False, label="XSEDE Username") new_ssh_keypair = forms.BooleanField(required=False) def clean(self): if "password1" in self.cleaned_data and "password2" in self.cleaned_data: if self.cleaned_data["password1"] != self.cleaned_data["password2"]: raise forms.ValidationError("The two password fields did not match.") return self.cleaned_data class UserProfileForm(forms.ModelForm): private_key = forms.CharField(widget=forms.Textarea) public_key = forms.CharField(widget=forms.Textarea) class Meta: model = UserProfile fields = ("xsede_username", "public_key", "activation_key", "password_reset_key", "reset_expires")
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, widget=forms.TextInput(attrs=attributes), label="Username", error_message={'invalid': "This value may contain only letters, numbers and @.+- characters."} ) email = forms.EmailField() def clean_username(self): username = self.cleaned_data["username"] existing = User.objects.filter(username__iexact=username) if existing.exists(): raise forms.ValidationError("A user with that username already exists.") else: return self.cleaned_data["username"] class SettingsForm(forms.Form): email = forms.EmailField() xsede_username = forms.CharField(max_length=50, required=False, label="XSEDE Username") new_ssh_keypair = forms.BooleanField(required=False) class UserProfileForm(forms.ModelForm): private_key = forms.CharField(widget=forms.Textarea) public_key = forms.CharField(widget=forms.Textarea) class Meta: model = UserProfile fields = ("xsede_username", "public_key", "activation_key", "password_reset_key", "reset_expires")
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[key] def addChild(self, child) : self._children.add(child)
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) : return self._data[key] def addChild(self, child) : self._children.add(child) def setParent(self, parent) : self._parent = parent def parent(self) : return self._parent
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') class DockingEventSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location')
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') class SpaceStationSerializerForDockingEvent(serializers.HyperlinkedModelSerializer): class Meta: model = SpaceStation fields = ('id', 'url', 'name', 'image_url') class DockingEventSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True) docking_location = serializers.StringRelatedField(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location') class DockingEventDetailedSerializer(serializers.HyperlinkedModelSerializer): flight_vehicle = SpacecraftFlightSerializerForDockingEvent(read_only=True, many=False) docking_location = serializers.StringRelatedField(many=False, read_only=True) space_station = SpaceStationSerializerForDockingEvent(many=False, read_only=True) class Meta: model = DockingEvent fields = ('id', 'url', 'docking', 'departure', 'flight_vehicle', 'docking_location', 'space_station')
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'] if 'page' in response['meta']['query']: self.page = response['meta']['query']['page'] def _annotate(self): for service in self.search_results: self._replace_lot(service) self._add_highlighting(service) def _replace_lot(self, service): # replace lot slug with reference to dict containing all the relevant lot data service['lot'] = self._lots.get(service['lot']) def _add_highlighting(self, service): if 'highlight' in service: if 'serviceSummary' in service['highlight']: service['serviceSummary'] = Markup( ''.join(service['highlight']['serviceSummary']) ) class AggregationResults(object): """Provides access to the aggregation results information""" def __init__(self, response): self.results = response['aggregations'] self.total = response['meta']['total'] if 'page' in response['meta']['query']: self.page = response['meta']['query']['page']
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'] if 'page' in response['meta']['query']: self.page = response['meta']['query']['page'] def _annotate(self): for service in self.search_results: self._replace_lot(service) self._add_highlighting(service) def _replace_lot(self, service): # replace lot slug with reference to dict containing all the relevant lot data service['lot'] = self._lots.get(service['lot']) def _add_highlighting(self, service): if 'highlight' in service: for highlighted_field in ['serviceSummary', 'serviceDescription']: if highlighted_field in service['highlight']: service[highlighted_field] = Markup( ''.join(service['highlight'][highlighted_field]) ) class AggregationResults(object): """Provides access to the aggregation results information""" def __init__(self, response): self.results = response['aggregations'] self.total = response['meta']['total'] if 'page' in response['meta']['query']: self.page = response['meta']['query']['page']
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, lfn_to_pfn
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.""" engine = engine_from_config(settings, "sqlalchemy.") init_session(engine) config = Configurator(settings=settings) config.add_route("ca", "/root.crt", request_method="GET") config.add_route("cabundle", "/bundle.crt", request_method="GET") config.add_route("csr", "/{sha256:[0-9a-f]{64}}", request_method="POST") config.add_route("cert", "/{sha256:[0-9a-f]{64}}", request_method="GET") config.scan() return config.make_wsgi_app()
#! /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.""" engine = engine_from_config(settings, "sqlalchemy.") init_session(engine) config = Configurator(settings=settings) config.include("pyramid_tm") config.add_route("ca", "/root.crt", request_method="GET") config.add_route("cabundle", "/bundle.crt", request_method="GET") config.add_route("csr", "/{sha256:[0-9a-f]{64}}", request_method="POST") config.add_route("cert", "/{sha256:[0-9a-f]{64}}", request_method="GET") config.scan() return config.make_wsgi_app()
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 separate dataset. """ from __future__ import division, absolute_import, print_function from km3pipe import version def tohdf5(input_file, output_file, separate_events=False): """Convert ROOT file to HDF5 file""" from km3pipe import Pipeline # noqa from km3pipe.pumps import AanetPump, HDF5Sink, HDF5SinkLegacy # noqa sink = HDF5Sink if separate_events else HDF5SinkLegacy pipe = Pipeline() pipe.attach(AanetPump, filename=input_file) pipe.attach(sink, filename=output_file, separate_events=separate_events) pipe.drain() def main(): from docopt import docopt arguments = docopt(__doc__, version=version) if arguments['tohdf5']: tohdf5(arguments['-i'], arguments['-o'], arguments['-s'])
# 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 separate dataset. """ from __future__ import division, absolute_import, print_function from km3pipe import version def tohdf5(input_file, output_file, use_tables=True): """Convert ROOT file to HDF5 file""" from km3pipe import Pipeline # noqa from km3pipe.pumps import AanetPump, HDF5Sink, HDF5TableSink # noqa sink = HDF5TableSink if use_tables else HDF5Sink pipe = Pipeline() pipe.attach(AanetPump, filename=input_file) pipe.attach(sink, filename=output_file, separate_events=separate_events) pipe.drain() def main(): from docopt import docopt arguments = docopt(__doc__, version=version) if arguments['tohdf5']: tohdf5(arguments['-i'], arguments['-o'], arguments['-s'])
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 = Tag.objects.all() serializer_class = TagSummarySerializer max_paginate_by = 1000 def perform_create(self, serializer): serializer.save(user=self.request.user) def get_permissions(self): if self.request.method in ["POST", "PUT", "DELETE"]: self.permission_classes = (CloudAdminRequired,) return super(TagViewSet, self).get_permissions()
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 that allows tags to be viewed or edited. """ queryset = Tag.objects.all() serializer_class = TagSummarySerializer max_paginate_by = 1000 def perform_create(self, serializer): same_name_tags = Tag.objects.filter( name__iexact=serializer.validated_data.get("name")) if same_name_tags: raise serializers.ValidationError( "A tag with this name already exists: %s" % same_name_tags.first().name) serializer.save(user=self.request.user) def get_permissions(self): if self.request.method is "": self.permission_classes = (ApiAuthRequired, InMaintenance,) if self.request.method in ["PUT", "DELETE"]: self.permission_classes = (CloudAdminRequired, InMaintenance,) return super(TagViewSet, self).get_permissions()
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_intake'), url(r'^profile/surveys/$', views.survey_management, name='survey_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), #url(r'^survey_data/(?P<survey_shortname>.+)/(?P<id>\d+)/$', views.survey_data, name='survey_data'), url(r'^intake/$', views.survey_data, name='survey_data'), url(r'^monthly/(?P<id>\d+)/$', views.survey_data_monthly ,name='survey_data_monthly'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), )
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_management'), url(r'^main/$', views.main_index), url(r'^survey_management/$', views.survey_management, name='survey_management'), url(r'^intake/view/$', views.survey_intake_view, name='survey_intake_view'), url(r'^intake/update/$', views.survey_intake_update, name='survey_intake_update'), url(r'^monthly/(?P<id>\d+)/$', views.survey_monthly ,name='survey_monthly'), url(r'^monthly/(?P<id>\d+)/update/$', views.survey_monthly_update ,name='survey_monthly_update'), url(r'^thanks_profile/$', views.thanks_profile, name='profile_thanks'), #url(r'^select/$', views.select_user, name='survey_select_user'), url(r'^$', views.index, name='survey_index'), )
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 or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from twisted.web.resource import Resource import json import nacl.encoding class Ed25519Servlet(Resource): isLeaf = True def __init__(self, syd): self.sydent = syd def render_GET(self, request): pubKey = self.sydent.signers.ed25519.signing_key.verify_key pubKeyHex = pubKey.encode(encoder=nacl.encoding.HexEncoder) return json.dumps({'public_key':pubKeyHex})
# -*- 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 or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from twisted.web.resource import Resource import json import nacl.encoding class Ed25519Servlet(Resource): isLeaf = True def __init__(self, syd): self.sydent = syd def render_GET(self, request): pubKey = self.sydent.keyring.ed25519.verify_key pubKeyHex = pubKey.encode(encoder=nacl.encoding.HexEncoder) return json.dumps({'public_key':pubKeyHex})
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<slug>[\w-]+)$', OppsDetail.as_view(), name='open'), url(r'^(?P<channel__long_slug>[\w\b//-]+)/$', OppsList.as_view(), name='channel'), )
#!/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/', Search(), name='search'), url(r'^(?P<channel__long_slug>[\w//-]+)/(?P<slug>[\w-]+)$', cache_page(60 * 15)(OppsDetail.as_view()), name='open'), url(r'^(?P<channel__long_slug>[\w\b//-]+)/$', cache_page(60 * 2)(OppsList.as_view()), name='channel'), )
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', 'terms': [{ 'name': '2013-2014', 'sessions': ['2013'], 'start_year': 2013, 'end_year': 2014 }], 'provides': ['people'], 'parties': [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ], 'session_details': { '2013': {'_scraped_name': '2013'} }, 'feature_flags': [], } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['2013']
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'], 'start_year': 2013, 'end_year': 2014 }] provides = ['people'], parties = [ {'name': 'Independent' }, {'name': 'Green' }, {'name': 'Bull-Moose'} ] session_details = { '2013': {'_scraped_name': '2013'} } def get_scraper(self, term, session, scraper_type): if scraper_type == 'people': return PersonScraper def scrape_session_list(self): return ['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 = config.rss['link'] async def enroll(user): enroll = begin_registration(facet, user.get('_u2f_devices_', [])) user['_u2f_enroll_'] = enroll.json return user, json.dumps(enroll.data_for_client) async def bind(user, data): response = data['tokenResponse'] enroll = user.pop('_u2f_enroll_') device, cert = complete_registration(enroll, response, [facet]) patch = device patch['deviceName'] = data['deviceName'] patch['registerDate'] = data['date'] user.setdefault('_u2f_devices_', []).append(json.dumps(patch)) # cert = x509.load_der_x509_certificate(cert, default_backend()) return user, True async def sign(user): challenge = begin_authentication(facet, user.get('_u2f_devices_', [])) user['_u2f_challenge_'] = challenge.json return user, json.dumps(challenge.data_for_client) async def verify(user, data): challenge = user.pop('_u2f_challenge_') try: complete_authentication(challenge, data, [facet]) except AttributeError: return user, False return user, True
#!/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 = config.rss['link'] async def enroll(user): enroll = begin_registration(facet, user.get('_u2f_devices_', [])) user['_u2f_enroll_'] = enroll.json return user, json.dumps(enroll.data_for_client) async def bind(user, data): response = data['tokenResponse'] enroll = user.pop('_u2f_enroll_') device, cert = complete_registration(enroll, response, [facet]) patch = device patch['deviceName'] = data['deviceName'] patch['registerDate'] = data['date'] user.setdefault('_u2f_devices_', []).append(json.dumps(patch)) # cert = x509.load_der_x509_certificate(cert, default_backend()) return user, True async def sign(user): challenge = begin_authentication(facet, user.get('_u2f_devices_', [])) user['_u2f_challenge_'] = challenge.json return user, json.dumps(challenge.data_for_client) async def verify(user, data): print(user) challenge = user.pop('_u2f_challenge_') try: complete_authentication(challenge, data, [facet]) except AttributeError: return user, False return user, True
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): return tf.train.string_input_producer(tf.train.match_filenames_once(pattern), num_epochs=FLAGS.num_epochs, capacity=FLAGS.filename_queue_capacity)
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( *READERS[file_format](_file_pattern_to_names(file_pattern))) @func_scope def _file_pattern_to_names(pattern): return tf.train.string_input_producer(tf.train.match_filenames_once(pattern), num_epochs=FLAGS.num_epochs, capacity=FLAGS.filename_queue_capacity) @func_scope def monitored_batch_queue(*tensors): queue = tf.FIFOQueue(FLAGS.batch_queue_capacity, [tensor.dtype for tensor in tensors]) collections.add_metric(queue.size(), "batches_in_queue") tf.train.add_queue_runner( tf.train.QueueRunner(queue, [queue.enqueue(tensors)])) results = queue.dequeue() for tensor, result in zip(tensors, results): result.set_shape(tensor.get_shape()) return results
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!" attempts += 1
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", attempts, "Attempts!" if attempts > 1 else "Attempt!" break elif guess > number: print "That Guess Is Too High!" elif guess < number: print "That Guess Is Too Low!" else: print "Guesses Must Be Between 1 And 100!" else: print "That's Not A Number!" attempts += 1
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' label = 'wagtailsearch' verbose_name = _("Wagtail search") default_auto_field = 'django.db.models.AutoField' def ready(self): register_signal_handlers() if connection.vendor == 'postgresql': # Only PostgreSQL has support for tsvector weights from wagtail.search.backends.database.postgres.weights import set_weights set_weights() from wagtail.search.models import IndexEntry IndexEntry.add_generic_relations() @register(Tags.compatibility, Tags.database) def check_if_sqlite_version_is_supported(app_configs, **kwargs): if connection.vendor == 'sqlite': import sqlite3 if sqlite3.sqlite_version_info < (3, 19, 0): return [Warning('Your SQLite version is older than 3.19.0. A fallback search backend will be used instead.', hint='Upgrade your SQLite version to at least 3.19.0', id='wagtailsearch.W002', obj=WagtailSearchAppConfig)] return []
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' label = 'wagtailsearch' verbose_name = _("Wagtail search") default_auto_field = 'django.db.models.AutoField' def ready(self): register_signal_handlers() if connection.vendor == 'postgresql': # Only PostgreSQL has support for tsvector weights from wagtail.search.backends.database.postgres.weights import set_weights set_weights() from wagtail.search.models import IndexEntry IndexEntry.add_generic_relations() @register(Tags.compatibility, Tags.database) def check_if_sqlite_version_is_supported(app_configs, **kwargs): if connection.vendor == 'sqlite': import sqlite3 from wagtail.search.backends.database.sqlite.utils import fts5_available if sqlite3.sqlite_version_info < (3, 19, 0): return [Warning('Your SQLite version is older than 3.19.0. A fallback search backend will be used instead.', hint='Upgrade your SQLite version to at least 3.19.0', id='wagtailsearch.W002', obj=WagtailSearchAppConfig)] elif not fts5_available(): return [Warning('Your SQLite installation is missing the fts5 extension. A fallback search backend will be used instead.', hint='Upgrade your SQLite installation to a version with fts5 enabled', id='wagtailsearch.W003', obj=WagtailSearchAppConfig)] return []
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 """ assert not parent or not parent.is_file, 'Parent must be a folder' cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent cloned.versions.add(*fileversions[1:]) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() cloned.versions.add(new_fileversion) else: cloned.versions.add(*src.versions.all()) if not src.is_file: for child in src.children: copy_files(child, target_node, parent=cloned) return cloned
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 """ assert not parent or not parent.is_file, 'Parent must be a folder' cloned = src.clone() cloned.parent = parent cloned.target = target_node cloned.name = name or cloned.name cloned.copied_from = src cloned.save() if src.is_file and src.versions.exists(): fileversions = src.versions.select_related('region').order_by('-created') most_recent_fileversion = fileversions.first() if most_recent_fileversion.region and most_recent_fileversion.region != target_node.osfstorage_region: # add all original version except the most recent cloned.versions.add(*fileversions[1:]) # create a new most recent version and update the region before adding new_fileversion = most_recent_fileversion.clone() new_fileversion.region = target_node.osfstorage_region new_fileversion.save() cloned.versions.add(new_fileversion) else: cloned.versions.add(*src.versions.all()) if not src.is_file: for child in src.children: copy_files(child, target_node, parent=cloned) return cloned
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/osf.io,mattclark/osf.io,mfraezz/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,felliott/osf.io,adlius/osf.io,brianjgeiger/osf.io,mfraezz/osf.io,baylee-d/osf.io,mattclark/osf.io,felliott/osf.io,HalcyonChimera/osf.io,baylee-d/osf.io,mfraezz/osf.io,caseyrollins/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,brianjgeiger/osf.io,aaxelb/osf.io,aaxelb/osf.io,pattisdr/osf.io,pattisdr/osf.io,saradbowman/osf.io,cslzchen/osf.io,adlius/osf.io,CenterForOpenScience/osf.io,cslzchen/osf.io,caseyrollins/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,aaxelb/osf.io,Johnetordoff/osf.io
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 '' @register.tag def fake_request(parser, token): """ Create a fake request object in the context """ return FakeRequestNode()
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 = [] req.user = AnonymousUser() context['request'] = req return '' @register.tag def fake_request(parser, token): """ Create a fake request object in the context """ return FakeRequestNode()
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_after_bounce) def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs): if not should_deactivate: return if not bounce.user: return bounce.user.deactivate()
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 import user_email_bounced user_email_bounced.connect(deactivate_user_after_bounce) menu_registry.register(get_settings_menu_item) menu_registry.register(get_request_menu_item) def deactivate_user_after_bounce(sender, bounce, should_deactivate=False, **kwargs): if not should_deactivate: return if not bounce.user: return bounce.user.deactivate() def get_request_menu_item(request): return MenuItem( section='before_request', order=999, url=reverse('account-show'), label=_('My requests') ) def get_settings_menu_item(request): return MenuItem( section='after_settings', order=-1, url=reverse('account-settings'), label=_('Settings') )
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: "event teams", EVENT_MATCHES: "event matches", EVENT_RANKINGS: "event rankings", EVENT_ALLIANCES: "event alliances", EVENT_AWARDS: "event awrads" }
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", MATCH_VIDEO: "match video", EVENT_TEAMS: "event teams", EVENT_MATCHES: "event matches", EVENT_RANKINGS: "event rankings", EVENT_ALLIANCES: "event alliances", EVENT_AWARDS: "event awrads" }
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-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,josephbisch/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,synth3tk/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,verycumbersome/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,synth3tk/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,bvisness/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,josephbisch/the-blue-alliance,synth3tk/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,nwalters512/the-blue-alliance,bvisness/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,bvisness/the-blue-alliance,verycumbersome/the-blue-alliance,synth3tk/the-blue-alliance,nwalters512/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,josephbisch/the-blue-alliance,the-blue-alliance/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,verycumbersome/the-blue-alliance,josephbisch/the-blue-alliance,verycumbersome/the-blue-alliance
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 = channel.loop self._channel = channel self.state = TransactionStates.created # type: TransactionStates @property def channel(self) -> aiormq.Channel: if self._channel is None: raise RuntimeError("Channel not opened") if self._channel.is_closed: raise RuntimeError("Closed channel") return self._channel async def select(self, timeout=None) -> aiormq.spec.Tx.SelectOk: result = await asyncio.wait_for( self.channel.tx_select(), timeout=timeout, ) self.state = TransactionStates.started return result async def rollback(self, timeout=None): result = await asyncio.wait_for( self.channel.tx_rollback(), timeout=timeout, ) self.state = TransactionStates.rolled_back return result async def commit(self, timeout=None): result = await asyncio.wait_for( self.channel.tx_commit(), timeout=timeout, ) self.state = TransactionStates.commited return result async def __aenter__(self): return await self.select() async def __aexit__(self, exc_type, exc_val, exc_tb): if exc_type: await self.rollback() else: await self.commit()
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 = channel.loop self._channel = channel self.state = TransactionStates.created # type: TransactionStates @property def channel(self) -> aiormq.Channel: if self._channel is None: raise RuntimeError("Channel not opened") if self._channel.is_closed: raise RuntimeError("Closed channel") return self._channel async def select(self, timeout=None) -> aiormq.spec.Tx.SelectOk: result = await asyncio.wait_for( self.channel.tx_select(), timeout=timeout, ) self.state = TransactionStates.started return result async def rollback(self, timeout=None): result = await asyncio.wait_for( self.channel.tx_rollback(), timeout=timeout, ) self.state = TransactionStates.rolled_back return result async def commit(self, timeout=None): result = await asyncio.wait_for( self.channel.tx_commit(), timeout=timeout, ) self.state = TransactionStates.commited return result async def __aenter__(self): await self.select() return self async def __aexit__(self, exc_type, exc_val, exc_tb): if exc_type: await self.rollback() else: await self.commit()
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: sequences[name] = {} if what in sequences[name]: print("Warning: Got duplicate '{}' marker for sequence '{}' at frame {} (first was at frame {}), ignoring".format(what, name, marker.frame, sequences[name][what].frame)) continue sequences[name][what] = marker if "Sequences" in bpy.data.texts: for line in bpy.data.texts["Sequences"].as_string().split("\n"): line = line.strip() if not line: continue if ":" not in line: print("Invalid line in 'Sequences':", line) continue name, flags = line.split(":", 1) if flags.lstrip(): flags = tuple(map(lambda f: f.strip(), flags.split(","))) else: flags = () sequence_flags[name] = flags return sequences, sequence_flags
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 name not in sequences: sequences[name] = {} if what in sequences[name]: print("Warning: Got duplicate '{}' marker for sequence '{}' at frame {} (first was at frame {}), ignoring".format(what, name, marker.frame, sequences[name][what].frame)) continue sequences[name][what] = marker if "Sequences" in bpy.data.texts: for line in bpy.data.texts["Sequences"].as_string().split("\n"): line = line.strip() if not line: continue if ":" not in line: print("Invalid line in 'Sequences':", line) continue name, flags = line.split(":", 1) if flags.lstrip(): flags = tuple(map(lambda f: f.strip(), flags.split(","))) else: flags = () sequence_flags[name] = flags return sequences, sequence_flags
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 winton_kafka_streams.processor.topology import TopologyBuilder class MyTestProcessor(BaseProcessor): pass def test_Given_StreamAlreadyStarted_When_CallStartAgain_Then_RaiseError(): kafka_config.NUM_STREAM_THREADS = 0 topology_builder = TopologyBuilder() topology_builder.source('my-source', ['my-input-topic-1']) topology_builder.processor('my-processor', MyTestProcessor, 'my-source') topology_builder.sink('my-sink', 'my-output-topic-1', 'my-processor') topology = topology_builder.build() kafka_streams = KafkaStreams(topology, kafka_config) kafka_streams.start() with pytest.raises(KafkaStreamsError, message='KafkaStreams already started.'): kafka_streams.start()
""" 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 winton_kafka_streams.processor.topology import TopologyBuilder class MyTestProcessor(BaseProcessor): pass def test__given__stream_already_started__when__call_start_again__then__raise_error(): kafka_config.NUM_STREAM_THREADS = 0 topology_builder = TopologyBuilder() topology_builder.source('my-source', ['my-input-topic-1']) topology_builder.processor('my-processor', MyTestProcessor, 'my-source') topology_builder.sink('my-sink', 'my-output-topic-1', 'my-processor') topology = topology_builder.build() kafka_streams = KafkaStreams(topology, kafka_config) kafka_streams.start() with pytest.raises(KafkaStreamsError, message='KafkaStreams already started.'): kafka_streams.start()
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.join('/', 'var', 'praekelt', PROJECT) def restart(): sudo('/etc/init.d/nginx restart') sudo('supervisorctl reload') def deploy(): with cd(env.path): sudo('git pull', user=USER) sudo('ve/bin/python manage.py syncdb --migrate --noinput', user=USER) sudo('ve/bin/python manage.py collectstatic --noinput', user=USER) def install_packages(force=False): with cd(env.path): sudo('ve/bin/pip install %s -r requirements.pip' % ( '--upgrade' if force else '',), user=USER)
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(): with cd(env.path): sudo('git pull', user=DEPLOY_USER) sudo('ve/bin/python manage.py syncdb --migrate --noinput', user=DEPLOY_USER) sudo('ve/bin/python manage.py collectstatic --noinput', user=DEPLOY_USER) def install_packages(force=False): with cd(env.path): sudo('ve/bin/pip install %s -r requirements.pip' % ( '--upgrade' if force else '',), user=DEPLOY_USER)
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/nginx/sites-available/startthedark.com /etc/nginx/sites-enabled/startthedark.com') sudo('/etc/init.d/nginx reload') def deploy(): 'Deploy startthedark.' local('bash make_prod_css.sh') set(fab_fail = 'ignore') local('git commit -a -m "Rebuilt Prod CSS For Commit"') local('git push origin master') set(fab_fail = 'abort') run('cd /var/www/startthedark.com/startthedark; git pull;') run('cd /var/www/startthedark.com/startthedark; /usr/bin/python manage.py syncdb') sudo('/etc/init.d/apache2 reload')
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/nginx/sites-available/startthedark.com /etc/nginx/sites-enabled/startthedark.com') sudo('/etc/init.d/nginx reload') def rebuild_prod_css(): local('bash make_prod_css.sh') local('git commit -a -m "Rebuilt Prod CSS For Commit"') local('git push origin master') def deploy(): 'Deploy startthedark.' run('cd /var/www/startthedark.com/startthedark; git pull;') run('cd /var/www/startthedark.com/startthedark; /usr/bin/python manage.py syncdb') sudo('/etc/init.d/apache2 reload')
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 the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) if not tenant_dir: return for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format(tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): return local_path return
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 the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) if not tenant_dir: return [] for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format(tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): if all: return [local_path] return local_path return []
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', 'interesting', 'piece'] ''' clean_sentence = ''.join([char for char in sentence if ord(char) in xrange(97, 123) or ord(char) in xrange(75, 91) or ord(char) == 32]) segments = clean_sentence.split(' ') words = [word for word in segments if not word == ''] return words
''' 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', 'interesting', 'piece'] ''' clean_sentence = ''.join([char for char in sentence if char.isalpha() or char.isspace()]) segments = clean_sentence.split(' ') words = [word for word in segments if not word == ''] return words
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__.__name__ @property def status_url(self): raise NotImplemented() @property def name(self): raise NotImplemented() def get_status(self): raise NotImplemented()
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__.__name__ @property def status_url(self): raise NotImplemented() @property def icon_url(self): raise NotImplemented() @property def name(self): raise NotImplemented() def get_status(self): raise NotImplemented()
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) d = self.calendar.from_date(vd) self.assertIsNotNone(d) def test_first_date(self): vd = vanilla_date(1, 1, 1) d = self.calendar.from_date(vd) self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)') def compare_date_and_number(self, year, month, day, number): vd = vanilla_date(year, month, day) d = self.calendar.from_date(vd) self.assertEqual(d.native_representation(), {'day_number': number}) def test_other_date(self): self.compare_date_and_number(2013, 1, 1, 2456293)
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) d = self.calendar.from_date(vd) self.assertIsNotNone(d) def test_first_date(self): vd = vanilla_date(1, 1, 1) d = self.calendar.from_date(vd) self.assertEqual(str(d), 'Day 1721423 (Julian Day Number)') def compare_date_and_number(self, year, month, day, number): vd = vanilla_date(year, month, day) d = self.calendar.from_date(vd) self.assertEqual(d.native_representation(), {'day_number': number}) def test_every_400_years(self): days_in_400_years = 400 * 365 + 97 for i in range(25): self.compare_date_and_number(1 + 400 * i, 1, 1, 1721423 + days_in_400_years * i) def test_another_date(self): self.compare_date_and_number(2013, 1, 1, 2456293)
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", # browse "browse", # settings_proxy "OverrideAuditOpenFileCommand", "OverrideAuditEditSettingsCommand", # events/contexts "OverrideAuditEventListener", "OverrideAuditContextListener", # commands/* "OverrideAuditPackageReportCommand", "OverrideAuditOverrideReportCommand", "OverrideAuditDiffReportCommand", "OverrideAuditRefreshReportCommand", "OverrideAuditToggleOverrideCommand", "OverrideAuditCreateOverrideCommand", "OverrideAuditDiffOverrideCommand", "OverrideAuditRevertOverrideCommand", "OverrideAuditDiffExternallyCommand", "OverrideAuditEditOverrideCommand", "OverrideAuditDeleteOverrideCommand", "OverrideAuditFreshenOverrideCommand", "OverrideAuditDiffPackageCommand", "OverrideAuditFreshenPackageCommand", "OverrideAuditDiffSingleCommand", "OverrideAuditModifyMarkCommand" ]
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", # browse "browse", # settings_proxy "OverrideAuditOpenFileCommand", "OverrideAuditEditSettingsCommand", # events/contexts "OverrideAuditEventListener", "CreateOverrideEventListener", "OverrideAuditContextListener", # commands/* "OverrideAuditPackageReportCommand", "OverrideAuditOverrideReportCommand", "OverrideAuditDiffReportCommand", "OverrideAuditRefreshReportCommand", "OverrideAuditToggleOverrideCommand", "OverrideAuditCreateOverrideCommand", "OverrideAuditDiffOverrideCommand", "OverrideAuditRevertOverrideCommand", "OverrideAuditDiffExternallyCommand", "OverrideAuditEditOverrideCommand", "OverrideAuditDeleteOverrideCommand", "OverrideAuditFreshenOverrideCommand", "OverrideAuditDiffPackageCommand", "OverrideAuditFreshenPackageCommand", "OverrideAuditDiffSingleCommand", "OverrideAuditModifyMarkCommand" ]
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'): if vol['fstype'] == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % vol, not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol) if vol.get('mount_point'): Mount(vol['mount_point'], device = vol['device'], fstype = vol.get('fstype'), options = vol.get('fsoptions', ["noatime"]), action = ["mount", "enable"])
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 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'): if vol['fstype'] == "xfs": Package("xfsprogs") Execute("mkfs.%(fstype)s -f %(device)s" % vol, not_if = """if [ "`file -s %(device)s`" = "%(device)s: data" ]; then exit 1; fi""" % vol) if vol.get('mount_point'): Mount(vol['mount_point'], device = vol['device'], fstype = vol.get('fstype'), options = vol.get('fsoptions', ["noatime"]), action = ["mount", "enable"])
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, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs.get('instance', None) if instance: self.fields['grade'].choices += ((instance.grade, instance.grade), ('none', 'Ukendt'))
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 = forms.ChoiceField(GRADES, required=True, label='Klasse') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = kwargs.get('instance', None) if instance: self.fields['grade'].choices += ((instance.grade, instance.grade), ('none', 'Ukendt'))
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 None
# 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 IOError: warnings.warn("Cannot mount FAT filesystems with FUSE") else: with fatfs as tmpdir: yield assert_true, os.path.exists(tmpdir)
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.DoesNotExist: return None if '$' in user.password: if user.check_password(password): user.password = sha1(password).hexdigest() user.save() return user else: if user.password == sha1(password).hexdigest(): return user return None
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=None, password=None): try: user = User.objects.get(username=username) except User.DoesNotExist: return None if '$' in user.password: if user.check_password(password): user.password = sha1(password).hexdigest() user.save() return user else: if user.password == sha1(password).hexdigest(): return user return None
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 setUp(self): super(BaseTestCase, self).setUp() # Add custom setUp code for your tests AFTER the super().setUp() def tearDown(self): # Add custom tearDown code for your tests BEFORE the super().tearDown() super(BaseTestCase, self).tearDown() def login(self): # <<< Placeholder. Add your code here. >>> # Reduce duplicate code in tests by having reusable methods like this. # If the UI changes, the fix can be applied in one place. pass def example_method(self): # <<< Placeholder. Add your code here. >>> pass ''' # Now you can do something like this in your test files: from base_test_case import BaseTestCase class MyTests(BaseTestCase): def test_example(self): self.login() self.example_method() '''
''' 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 setUp(self): super(BaseTestCase, self).setUp() # <<< Add custom setUp code for tests AFTER the super().setUp() >>> def tearDown(self): self.save_teardown_screenshot() # <<< Add custom tearDown code BEFORE the super().tearDown() >>> super(BaseTestCase, self).tearDown() def login(self): # <<< Placeholder. Add your code here. >>> # Reduce duplicate code in tests by having reusable methods like this. # If the UI changes, the fix can be applied in one place. pass def example_method(self): # <<< Placeholder. Add your code here. >>> pass ''' # Now you can do something like this in your test files: from base_test_case import BaseTestCase class MyTests(BaseTestCase): def test_example(self): self.login() self.example_method() '''
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