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
0224877de121cb7cb850ef51a75c1c3f8c1cb105
kala.py
kala.py
#!/usr/bin/python import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query....
#!/usr/bin/python import json import bottle from bottle_mongo import MongoPlugin app = bottle.Bottle() app.config.load_config('settings.ini') app.install(MongoPlugin( uri=app.config['mongodb.uri'], db=app.config['mongodb.db'], json_mongo=True)) def _get_json(name): result = bottle.request.query....
Sort needs to be an array of arrays in the query string but a list of tuples in python.
Bugfix: Sort needs to be an array of arrays in the query string but a list of tuples in python.
Python
mit
damoxc/kala,cheng93/kala,cloudbuy/kala
366da021d86466c8aa8389f6cfe80386172c3b8f
data_structures/tree/tree_node.py
data_structures/tree/tree_node.py
class TreeNode(object): def __init__(self, key=None, payload=None): self.key = key self.payload = payload self.left = None self.right = None self.parent = None def __str__(self): s = str(self.key) if self.payload: s += ": " + str(self.payloa...
class TreeNode(object): def __init__(self, key=None, payload=None): self.key = key self.payload = payload self.left = None self.right = None self.parent = None def __str__(self): s = str(self.key) if self.payload: s += ": " + str(self.payloa...
Add set_children function in TreeNode
Add set_children function in TreeNode
Python
mit
hongta/practice-python,hongta/practice-python
89dff1818183fa6c3e7f9c6f5a802842e4e3e797
demo/texture.py
demo/texture.py
#!/usr/bin/env python from VisionEgg.Core import * from VisionEgg.Textures import * from VisionEgg.AppHelper import * filename = "orig.bmp" if len(sys.argv) > 1: filename = sys.argv[1] try: texture = TextureFromFile(filename) except: print "Could not open image file '%s', generating texture."%filenam...
#!/usr/bin/env python from VisionEgg.Core import * from VisionEgg.Textures import * from VisionEgg.AppHelper import * filename = "orig.bmp" if len(sys.argv) > 1: filename = sys.argv[1] try: texture = TextureFromFile(filename) except: print "Could not open image file '%s', generating texture."%filenam...
Use new TextureStimulus parameter definitions.
Use new TextureStimulus parameter definitions. git-svn-id: 033d166fe8e629f6cbcd3c0e2b9ad0cffc79b88b@238 3a63a0ee-37fe-0310-a504-e92b6e0a3ba7
Python
lgpl-2.1
visionegg/visionegg,visionegg/visionegg,visionegg/visionegg,visionegg/visionegg,visionegg/visionegg
91f250485b86339b13f5a073e5879292525f9015
nbparameterise/code_drivers/python3.py
nbparameterise/code_drivers/python3.py
import ast import astcheck import astsearch from ..code import Parameter __all__ = ['extract_definitions', 'build_definitions'] def check_fillable_node(node, path): if isinstance(node, (ast.Num, ast.Str, ast.List)): return elif isinstance(node, ast.NameConstant) and (node.value in (True, False)): ...
import ast import astcheck import astsearch from ..code import Parameter __all__ = ['extract_definitions', 'build_definitions'] def check_list(node): def bool_check(node): return isinstance(node, ast.NameConstant) and (node.value in (True, False)) return all([(isinstance(n, (ast.Num, ast.Str)) ...
Add lists as valid parameters
Add lists as valid parameters
Python
mit
takluyver/nbparameterise
c6a65af70acfed68036914b983856e1cbe26a235
session2/translate_all.py
session2/translate_all.py
import argparse, logging, codecs from translation_model import TranslationModel def setup_args(): parser = argparse.ArgumentParser() parser.add_argument('model', help='trained model') parser.add_argument('input', help='input sentences') parser.add_argument('out', help='translated sentences') args ...
import argparse, logging, codecs from translation_model import TranslationModel from nltk.translate.bleu_score import sentence_bleu as bleu def setup_args(): parser = argparse.ArgumentParser() parser.add_argument('model', help='trained model') parser.add_argument('input', help='input sentences') parser...
Add option to check among 20 translations
Add option to check among 20 translations
Python
bsd-3-clause
vineetm/dl4mt-material,vineetm/dl4mt-material,vineetm/dl4mt-material,vineetm/dl4mt-material,vineetm/dl4mt-material
4fd0225ad318d05379d95c2184c4a78ed7fadcd8
recipe-server/normandy/recipes/migrations/0045_update_action_hashes.py
recipe-server/normandy/recipes/migrations/0045_update_action_hashes.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import hashlib from base64 import b64encode, urlsafe_b64encode from django.db import migrations def make_hashes_urlsafe_sri(apps, schema_editor): Action = apps.get_model('recipes', 'Action') for action in Action.objects.all(): data = a...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import hashlib from base64 import urlsafe_b64encode from django.db import migrations def make_hashes_urlsafe_sri(apps, schema_editor): Action = apps.get_model('recipes', 'Action') for action in Action.objects.all(): data = action.imple...
Fix lint checks in migration recipes/0045.
Fix lint checks in migration recipes/0045.
Python
mpl-2.0
mozilla/normandy,mozilla/normandy,mozilla/normandy,mozilla/normandy
2febb2e53a7f0b1a0a6952e4ea31c077f45b89f8
hooks/post_gen_project.py
hooks/post_gen_project.py
import os import subprocess project_dir = '{{cookiecutter.repo_name}}' hooks_dir = os.path.join(project_dir, '.git/hooks') src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py') dst = os.path.join(hooks_dir, 'prepare-commit-msg') process = subprocess.call(['git', 'init', project_dir]) os.mkdir('{{cookie...
import os import subprocess project_dir = '{{cookiecutter.repo_name}}' src = os.path.join(project_dir, 'src/utils/prepare-commit-msg.py') dst = os.path.join(project_dir, '.git/hooks/prepare-commit-msg') process = subprocess.call(['git', 'init', project_dir]) os.symlink(src, dst)
Remove creation of hooks directory
Remove creation of hooks directory
Python
mit
Empiria/matador-cookiecutter
df2d43e8ae84af605b845b3cbbb9c318f300e4e9
server.py
server.py
#!/usr/bin/python3 import subprocess import sys from flask import Flask, request app = Flask(__name__) SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass' def call_spass(name, master): p = subprocess.Popen([ SPASS, 'get', name], stdin=subprocess.PIPE, ...
#!/usr/bin/python3 import logging import subprocess import sys from flask import Flask, request app = Flask(__name__) SPASS=sys.argv[1] if len(sys.argv) > 1 else '/usr/local/bin/spass' @app.before_first_request def setup(): app.logger.addHandler(logging.StreamHandler()) app.logger.setLevel(logging.INFO) d...
Add logging for requested password and result
Add logging for requested password and result
Python
mit
iburinoc/spass-server,iburinoc/spass-server
75b82feac8ebc12450a44c5927579e30c604f973
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create documentation of DataSource Settings
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
69f19c4678b548f452f92ec29db0a3800c3c633d
cgi-bin/github_hook.py
cgi-bin/github_hook.py
#!/usr/bin/python from hashlib import sha1 import hmac import json import os import subprocess import sys def verify_signature(payload_body): x_hub_signature = os.getenv("HTTP_X_HUB_SIGNATURE") if not x_hub_signature: return False sha_name, signature = x_hub_signature.split('=') if sha_name...
#!/usr/bin/python from hashlib import sha1 import hmac import json import os import subprocess import sys import cgitb; cgitb.enable() def verify_signature(payload_body): x_hub_signature = os.getenv("HTTP_X_HUB_SIGNATURE") if not x_hub_signature: return False sha_name, signature = x_hub_signat...
Fix bug of error cwd when pulling.
Fix bug of error cwd when pulling.
Python
mit
zhchbin/Yagra,zhchbin/Yagra,zhchbin/Yagra
0bdd2df16823f129b39549a0e41adf1b29470d88
challenges/__init__.py
challenges/__init__.py
from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* ...
from os.path import dirname, basename, isfile import glob import sys modules = glob.glob(dirname(__file__)+"/c*[0-9].py") sys.path.append(dirname(__file__)) # Load all of the modules containing the challenge classes modules = [basename(path)[:-3] for path in modules] modules.sort() # Ensure that modules are in c1-c* ...
Fix bug in loading of c* modules
Fix bug in loading of c* modules
Python
mit
GunshipPenguin/billionaire_challenge,GunshipPenguin/billionaire_challenge
5ed364189b630d862ad9b9381e91f0e0e7268015
flask_mongorest/exceptions.py
flask_mongorest/exceptions.py
class MongoRestException(Exception): def __init__(self, message): self._message = message def _get_message(self): return self._message def _set_message(self, message): self._message = message message = property(_get_message, _set_message) class OperatorNotAllowed(MongoRestEx...
class MongoRestException(Exception): pass class OperatorNotAllowed(MongoRestException): def __init__(self, operator_name): self.op_name = operator_name def __unicode__(self): return u'"'+self.op_name+'" is not a valid operator name.' class InvalidFilter(MongoRestException): pass cla...
Reduce MongoRestException to pass for py3 compat
Reduce MongoRestException to pass for py3 compat
Python
bsd-3-clause
elasticsales/flask-mongorest,elasticsales/flask-mongorest
06aba23adbb281ff64a82059a07ffde95c361e6d
tests/app/test_cloudfoundry_config.py
tests/app/test_cloudfoundry_config.py
import json import os import pytest from app.cloudfoundry_config import ( extract_cloudfoundry_config, set_config_env_vars, ) @pytest.fixture def postgres_config(): return [ { 'credentials': { 'uri': 'postgres uri' } } ] @pytest.fixture def c...
import json import os import pytest from app.cloudfoundry_config import ( extract_cloudfoundry_config, set_config_env_vars, ) @pytest.fixture def cloudfoundry_config(): return { 'postgres': [{ 'credentials': { 'uri': 'postgres uri' } }], 'u...
Remove redundant postgres CloudFoundry fixture
Remove redundant postgres CloudFoundry fixture
Python
mit
alphagov/notifications-api,alphagov/notifications-api
e14ceda6370b506b80f65d45abd36c9f728e5699
pitchfork/manage_globals/forms.py
pitchfork/manage_globals/forms.py
# Copyright 2014 Dave Kludt # # 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, s...
# Copyright 2014 Dave Kludt # # 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, s...
Rework imports so not having to specify every type of field. Alter field definitions to reflect change
Rework imports so not having to specify every type of field. Alter field definitions to reflect change
Python
apache-2.0
rackerlabs/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork,rackerlabs/pitchfork,oldarmyc/pitchfork
233ce96d96caff3070f24d9d3dff3ed85be81fee
halaqat/settings/shaha.py
halaqat/settings/shaha.py
from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirnam...
from .base_settings import * import dj_database_url import os ALLOWED_HOSTS = ['0.0.0.0'] db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.9/howto/static-files/ PROJECT_ROOT = os.path.dirnam...
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
Fix The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
Python
mit
EmadMokhtar/halaqat,EmadMokhtar/halaqat,EmadMokhtar/halaqat
d99dd477d8b0849815bd5255d1eaedb2879294bb
general_itests/environment.py
general_itests/environment.py
# Copyright 2015-2016 Yelp Inc. # # 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 writin...
# Copyright 2015-2016 Yelp Inc. # # 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 writin...
Remove behave_pytest from general_itests too
Remove behave_pytest from general_itests too
Python
apache-2.0
somic/paasta,somic/paasta,Yelp/paasta,Yelp/paasta
db0253a228b3253e23bb5190fba9930a2f313d66
basictracer/context.py
basictracer/context.py
from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, ...
from __future__ import absolute_import import opentracing class SpanContext(opentracing.SpanContext): """SpanContext satisfies the opentracing.SpanContext contract. trace_id and span_id are uint64's, so their range is [0, 2^64). """ def __init__( self, trace_id=None, ...
Remove superfluous check for None baggage
Remove superfluous check for None baggage
Python
apache-2.0
opentracing/basictracer-python
efd1c945cafda82e48077e75e3231cac95d6e077
evesrp/util/fields.py
evesrp/util/fields.py
from __future__ import absolute_import import wtforms import wtforms.widgets import wtforms.fields class ImageInput(wtforms.widgets.Input): """WTForms widget for image inputs (<input type="image">) """ input_type = u'image' def __init__(self, src='', alt=''): self.src = src self.alt...
from __future__ import absolute_import import wtforms import wtforms.widgets import wtforms.fields from wtforms.utils import unset_value class ImageInput(wtforms.widgets.Input): """WTForms widget for image inputs (<input type="image">) """ input_type = u'image' def __init__(self, src='', alt=''): ...
Update customs ImageField to work with IE
Update customs ImageField to work with IE As opposed to Chrome, IE (and maybe other browsers) just returns the coordinates of where the click occurred.
Python
bsd-2-clause
paxswill/evesrp,paxswill/evesrp,paxswill/evesrp
e92339046fb47fc2275f432dfe3d998f702e40b2
pycalphad/tests/test_tdb.py
pycalphad/tests/test_tdb.py
""" This module tests the functionality of the TDB file parser. """ import nose.tools from pycalphad import Database from sympy import SympifyError @nose.tools.raises(SympifyError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAME...
""" This module tests the functionality of the TDB file parser. """ import nose.tools from pycalphad import Database @nose.tools.raises(ValueError, TypeError) def test_tdb_popen_exploit(): "Prevent execution of arbitrary code using Popen." tdb_exploit_string = \ """ PARAMETER G(L12_FCC,AL,CR,NI...
Fix unit test for py26
Fix unit test for py26
Python
mit
tkphd/pycalphad,tkphd/pycalphad,tkphd/pycalphad
ace1afc8491821c16311042d8115d31df119165d
build_chrome_webapp.py
build_chrome_webapp.py
try: from jinja2 import Template except: print "Could not import Jinja2, run 'easy_install Jinja2'" exit() def render_main_template(): f = open('./html/index.html') template = Template(f.read().decode('utf-8')) f.close() html = template.render(og_tag='', url='', ON_PRODUCTION=True, ON_DEV=...
from zipfile import ZipFile try: from jinja2 import Template except: print "Could not import Jinja2, run 'easy_install Jinja2'" exit() zipfile = ZipFile("webapp.zip", "w") def render_main_template(): f = open('./html/index.html') template = Template(f.read().decode('utf-8')) f.close() htm...
Write output to a zip file
Write output to a zip file
Python
mit
youtify/youtify,youtify/youtify,youtify/youtify
fe19fa7ac7f98525980e5b074bb17015531b2b58
buzzwordbingo/views.py
buzzwordbingo/views.py
from django.core.urlresolvers import reverse from djangorestframework.views import View class BuzzwordBingoView(View): def get(self, request): return [{'name': 'Buzzwords', 'url': reverse('buzzword-root')}, {'name': 'Win Conditions', 'url': reverse('win-condition-root')}, {'...
from django.core.urlresolvers import reverse from djangorestframework.views import View class BuzzwordBingoView(View): """The buzzword bingo REST API provides an interface to a collection of boards, which contain the buzzwords on the board and a list of win conditions, which are Python code which determine...
Add a description to the main view using Markdown.
Add a description to the main view using Markdown.
Python
bsd-3-clause
seanfisk/buzzword-bingo-server,seanfisk/buzzword-bingo-server
8d925147bf459021ca9735faec375608963d0269
gatekeeper/nodered.py
gatekeeper/nodered.py
import threading import socket NODE_RED_SERVER_PORT = 4445 NODE_RED_CLIENT_PORT = 4444 class NodeRedDoorbellServerThread(threading.Thread): """ Get doorbell triggers from NodeRed. """ def __init__(self, intercom): super(NodeRedDoorbellServerThread, self).__init__() self.intercom = inte...
import threading import socket NODE_RED_SERVER_PORT = 4445 NODE_RED_CLIENT_PORT = 4444 class NodeRedDoorbellServerThread(threading.Thread): """ Get doorbell triggers from NodeRed. """ def __init__(self, intercom): super(NodeRedDoorbellServerThread, self).__init__() self.intercom = inte...
Use with handler to safely close the server socket and connection
Use with handler to safely close the server socket and connection
Python
mit
git-commit/iot-gatekeeper,git-commit/iot-gatekeeper
eec72133d9245a4857c9a8954e235948a5fd9938
pokedex.py
pokedex.py
import json class NationalDex: def __init__(self, pathToNationalDex): dexfile = open(pathToNationalDex, 'r') self.dexdata = json.load(dexfile) self.numberOfPokemon = len(self.dexdata.keys()) self.pokemonNames = [] self.pokemonSlugs = [] for i in range (1, self.numbe...
import json class NationalDex: def __init__(self, pathToNationalDex): dexfile = open(pathToNationalDex, 'r') self.dexdata = json.load(dexfile) self.numberOfPokemon = len(self.dexdata.keys()) self.pokemonNames = [] self.pokemonSlugs = [] for i in range (1, self.numbe...
Remove unused method for getting PokΓ©mon names
Remove unused method for getting PokΓ©mon names
Python
bsd-2-clause
peterhajas/LivingDex,peterhajas/LivingDex,peterhajas/LivingDex,peterhajas/LivingDex
8f8b313a1b5118b6528e5152252128e075de0401
tests/test_terrain.py
tests/test_terrain.py
import unittest from randterrainpy import * class TerrainTesterPy(unittest.TestCase): def setUp(self): pass
import unittest from randterrainpy import * class TerrainTesterPy(unittest.TestCase): def setUp(self): self.ter1 = Terrain(1, 1) self.ter2 = Terrain(2, 4) self.ter3 = Terrain(1, 1) def test_getitem(self): self.assertEqual(self.ter1[0, 0], 0) self.assertEqual(self.ter2...
Add tests for indexing, equality and addition for Terrain
Add tests for indexing, equality and addition for Terrain
Python
mit
jackromo/RandTerrainPy
d3428351e005897f45bec1f4db61d776d2d9a962
tests/test_migrate.py
tests/test_migrate.py
from tinydb import TinyDB, where from tinydb.migrate import migrate v1_0 = """ { "_default": [{"key": "value", "_id": 1}], "table": [{"key": "value", "_id": 2}] } """ def test_upgrade(tmpdir): db_file = tmpdir.join('db.json') db_file.write(v1_0) # Run upgrade migrate(str(db_file)) db = T...
import pytest from tinydb import TinyDB, where from tinydb.migrate import migrate v1_0 = """ { "_default": [{"key": "value", "_id": 1}], "table": [{"key": "value", "_id": 2}] } """ def test_open_old(tmpdir): # Make sure that opening an old database results in an exception and not # in data loss ...
Test that opening an old database fails
Test that opening an old database fails
Python
mit
cagnosolutions/tinydb,Callwoola/tinydb,ivankravets/tinydb,raquel-ucl/tinydb,msiemens/tinydb
2509badb90a23c7c8b85c146f960bcc7bb8d57aa
postgresql/protocol/version.py
postgresql/protocol/version.py
## # .protocol.version ## 'PQ version class' from struct import Struct version_struct = Struct('!HH') class Version(tuple): """Version((major, minor)) -> Version Version serializer and parser. """ major = property(fget = lambda s: s[0]) minor = property(fget = lambda s: s[1]) def __new__(subtype, major_minor :...
## # .protocol.version ## """ PQ version class used by startup messages. """ from struct import Struct version_struct = Struct('!HH') class Version(tuple): """ Version((major, minor)) -> Version Version serializer and parser. """ major = property(fget = lambda s: s[0]) minor = property(fget = lambda s: s[1]) ...
Remove string annotation (likely incomprehensible to mypy) and minor doc-string formatting.
Remove string annotation (likely incomprehensible to mypy) and minor doc-string formatting.
Python
bsd-3-clause
python-postgres/fe,python-postgres/fe
61af785becd452facb92292260149b5e2b20a489
sheldon/__init__.py
sheldon/__init__.py
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ __author__ = 'Seva Zhidkov' __version__ = '0.1' __email__ = 'zhidkovseva@gmail.com' # Bot file contains bot's main class - Sheldon # Utils folder contains scripts for more # comfortable...
# -*- coding: utf-8 -*- """ @author: Seva Zhidkov @contact: zhidkovseva@gmail.com @license: The MIT license Copyright (C) 2015 """ __author__ = 'Seva Zhidkov' __version__ = '0.1' __email__ = 'zhidkovseva@gmail.com' # Bot file contains bot's main class - Sheldon # Utils folder contains scripts for more # comfortable...
Add sheldon hooks to init file
Add sheldon hooks to init file
Python
mit
lises/sheldon
94142e31d4189fbcf152eeb6b9ad89d684f1a6d0
autoload/splicelib/util/io.py
autoload/splicelib/util/io.py
import sys def error(m): sys.stderr.write(str(m) + '\n')
import sys import vim def error(m): sys.stderr.write(str(m) + '\n') def echomsg(m): vim.command('echomsg "%s"' % m)
Add a utility for echoing in the IO utils.
Add a utility for echoing in the IO utils.
Python
mit
sjl/splice.vim,sjl/splice.vim
8f3249904ede8e6ac4fd1398f3d059335a65c8c6
galpy/df.py
galpy/df.py
from galpy.df_src import diskdf from galpy.df_src import surfaceSigmaProfile from galpy.df_src import evolveddiskdf from galpy.df_src import quasiisothermaldf from galpy.df_src import streamdf from galpy.df_src import streamgapdf # # Classes # shudf= diskdf.shudf dehnendf= diskdf.dehnendf DFcorrection= diskdf.DFcorrec...
from galpy.df_src import diskdf from galpy.df_src import surfaceSigmaProfile from galpy.df_src import evolveddiskdf from galpy.df_src import quasiisothermaldf from galpy.df_src import streamdf from galpy.df_src import streamgapdf # # Functions # impulse_deltav_plummer= streamgapdf.impulse_deltav_plummer impulse_deltav_...
Add impulse functions to top level
Add impulse functions to top level
Python
bsd-3-clause
jobovy/galpy,jobovy/galpy,jobovy/galpy,jobovy/galpy
ae2c248cf1d3a2641b05a33d42077a2cace2e786
tests/scoring_engine/engine/test_execute_command.py
tests/scoring_engine/engine/test_execute_command.py
from scoring_engine.engine.execute_command import execute_command from scoring_engine.engine.job import Job class TestWorker(object): def test_basic_run(self): job = Job(environment_id="12345", command="echo 'HELLO'") task = execute_command.run(job) assert task['errored_out'] is False ...
import mock from billiard.exceptions import SoftTimeLimitExceeded from scoring_engine.engine.job import Job from scoring_engine.engine.execute_command import execute_command class TestWorker(object): def test_basic_run(self): job = Job(environment_id="12345", command="echo 'HELLO'") task = exec...
Add test for soft time limit reached
Add test for soft time limit reached
Python
mit
pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine
88d49172417ef7c99fa59313a10808c2b1a38b86
api/views.py
api/views.py
# -*- coding: utf-8 -*- from rest_framework import generics from rest_framework_extensions.cache.decorators import cache_response from api.serializers import EventListSerializers from api.processors import get_approved_events from api.serializers import ScoreboardSerializer from web.processors.event import count_appr...
# -*- coding: utf-8 -*- from hashlib import sha1 from rest_framework import generics from rest_framework_extensions.cache.decorators import cache_response from api.serializers import EventListSerializers from api.processors import get_approved_events from api.serializers import ScoreboardSerializer from web.processo...
Include the query string in the API cache key
Include the query string in the API cache key Otherwise, these two URLs would return the same data: /api/event/list/?format=json&past=yes /api/event/list/?format=json
Python
mit
codeeu/coding-events,codeeu/coding-events,codeeu/coding-events,codeeu/coding-events,codeeu/coding-events
3ced7839a9afbd96d23617f60804d5d580ceb9e6
sets/1/challenges/s1c5.py
sets/1/challenges/s1c5.py
import itertools def MultipleCharacterXOR(input, key): out = "" for i, j in itertools.izip_longest(range(len(input)), range(len(key))): vi = i vj = j if vi is None: vi = vj % len(input) elif vj is None: vj = vi % len(key) input_c = input[vi] key_c = key[vj] out += chr(ord(in...
import itertools def MultipleCharacterXOR(input, key): out = "" j = 0 while j < max(len(input), len(key)): i = j % len(input) k = j % len(key) j += 1 input_c = input[i] key_c = key[k] out += chr(ord(input_c) ^ ord(key_c)) return out.encode("hex") if __name__ == "__main__": input = ""...
Make the solution easier to read
Make the solution easier to read
Python
mit
aawc/cryptopals
44be93c5efb334297fc1bb10eaafec197018b241
python/render/render_tracks.py
python/render/render_tracks.py
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_lab...
__author__ = 'dcl9' from render import render_template import argparse import yaml def generate_track_dict(metadata): d = dict() d['track_name'] = '{}_{}({})'.format(metadata['protein'], metadata['serial_number'], metadata['author_identifier']) d['bigbed_url'] = metadata['track_filename'] d['short_lab...
Update formatting on track labels
Update formatting on track labels
Python
mit
Duke-GCB/TrackHubGenerator,Duke-GCB/TrackHubGenerator
9ce90b52bff35d5d0ad87d2402a5e8a946938cf7
sideloader/forms.py
sideloader/forms.py
from django.contrib.auth.models import User from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit import models class BaseModelForm(forms.ModelForm): helper = FormHelper() helper.form_class = 'form-horizontal' helper.add_input(Submit('submit', 'Submit'))...
from django.contrib.auth.models import User from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit import models class BaseModelForm(forms.ModelForm): helper = FormHelper() helper.form_class = 'form-horizontal' helper.add_input(Submit('submit', 'Submit'))...
Improve the project form a bit
Improve the project form a bit
Python
mit
praekelt/sideloader,praekelt/sideloader,praekelt/sideloader,praekelt/sideloader
cf6d82d9db90572d9a7350cb9d98f3619b86668f
examples/plot_quadtree_hanging.py
examples/plot_quadtree_hanging.py
""" QuadTree: Hanging Nodes ======================= You can give the refine method a function, which is evaluated on every cell of the TreeMesh. Occasionally it is useful to initially refine to a constant level (e.g. 3 in this 32x32 mesh). This means the function is first evaluated on an 8x8 mesh (2^3). """ import d...
""" QuadTree: Hanging Nodes ======================= You can give the refine method a function, which is evaluated on every cell of the TreeMesh. Occasionally it is useful to initially refine to a constant level (e.g. 3 in this 32x32 mesh). This means the function is first evaluated on an 8x8 mesh (2^3). """ import d...
Switch order (again) of legend for example
Switch order (again) of legend for example
Python
mit
simpeg/discretize,simpeg/discretize,simpeg/discretize
2a086200b7644c3b3b869359c23366e7a3f36141
show_usbcamera.py
show_usbcamera.py
#! /usr/bin/env python # -*- coding:utf-8 -*- # # Show the images from a USB camera # # # External dependencies # import sys from PySide import QtGui import VisionToolkit as vtk # # Main application # if __name__ == '__main__' : application = QtGui.QApplication( sys.argv ) widget = vtk.UsbCameraWidget() ...
#! /usr/bin/env python # -*- coding:utf-8 -*- # # Show the images from a USB camera # # # External dependencies # #import sys import cv2 #from PySide import QtGui import VisionToolkit as vt # # Image callback function # def Callback( image ) : #Β Display the stereo image cv2.imshow( 'Camera', image ) cv2.waitKe...
Add OpenCV viewer for debug.
Add OpenCV viewer for debug.
Python
mit
microy/StereoVision,microy/StereoVision,microy/VisionToolkit,microy/VisionToolkit,microy/PyStereoVisionToolkit,microy/PyStereoVisionToolkit
7ad3346759f53f57f233319e63361a0ed792535f
incrowd/notify/utils.py
incrowd/notify/utils.py
import logging from notify.models import Notification logger = logging.getLogger(__name__) def ping_filter(message, users, sending_user, notify_text, notify_type, notify_url=None): for user in users: if username_in_message(message, user.username): # Create notification ...
import logging from notify.models import Notification logger = logging.getLogger(__name__) def ping_filter(message, users, sending_user, notify_text, notify_type, notify_url=None): for user in users: if username_in_message(message, user.username): # Create notification ...
Fix pinging in chat throwing errors
Fix pinging in chat throwing errors
Python
apache-2.0
pcsforeducation/incrowd,pcsforeducation/incrowd,incrowdio/incrowd,incrowdio/incrowd,incrowdio/incrowd,pcsforeducation/incrowd,pcsforeducation/incrowd,incrowdio/incrowd
469c1dc9de1c986beda853b13909bdc5d3ff2b92
stagecraft/urls.py
stagecraft/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic.base import RedirectView from stagecraft.apps.datasets import views as datasets_views from stagecraft.libs.status import views as status_views admin.autodiscover() urlpatterns = patterns( '', url(r'...
from django.conf.urls import patterns, include, url from django.contrib import admin from django.views.generic.base import RedirectView from stagecraft.apps.datasets import views as datasets_views from stagecraft.libs.status import views as status_views admin.autodiscover() urlpatterns = patterns( '', url(r'...
Make redirect view pass the GET query string to the new location
Make redirect view pass the GET query string to the new location
Python
mit
alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft
018abd1a80bf0045d1f2d2c04d1caaa4db9433b8
froide/helper/search/paginator.py
froide/helper/search/paginator.py
from django.core.paginator import Paginator class ElasticsearchPaginator(Paginator): """ Paginator that prevents two queries to ES (for count and objects) as ES gives count with objects """ MAX_ES_OFFSET = 10000 def page(self, number): """ Returns a Page object for the given 1...
from django.core.paginator import Paginator, InvalidPage class ElasticsearchPaginator(Paginator): """ Paginator that prevents two queries to ES (for count and objects) as ES gives count with objects """ MAX_ES_OFFSET = 10000 def page(self, number): """ Returns a Page object fo...
Raise invalid page on paging error
Raise invalid page on paging error
Python
mit
stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide
2ca26d1d4d6ce578bf217741e9e8a32d3145c3df
tests/test_render.py
tests/test_render.py
import unittest import json import great_expectations as ge from great_expectations import render class TestPageRenderers(unittest.TestCase): def test_import(self): from great_expectations import render def test_prescriptive_expectation_renderer(self): results = render.render( re...
import unittest import json import great_expectations as ge from great_expectations import render class TestPageRenderers(unittest.TestCase): def test_import(self): from great_expectations import render def test_prescriptive_expectation_renderer(self): results = render.render( re...
Use the Titanic example data set
Use the Titanic example data set
Python
apache-2.0
great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations
56d7349a52f3a7928d3d67c89a086b54b2a3701d
elmo/moon_tracker/models.py
elmo/moon_tracker/models.py
from django.db import models from django.conf import settings from django.forms import Select from eve_sde.models import Moon # Create your models here. class ScanResult(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='scans', db_index=True ) moon ...
from django.db import models from django.conf import settings from django.forms import Select from eve_sde.models import Moon # Create your models here. class ScanResult(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='scans', db_index=True ) moon ...
Add all standard ore types with ID.
Add all standard ore types with ID.
Python
mit
StephenSwat/eve_lunar_mining_organiser,StephenSwat/eve_lunar_mining_organiser
03ee406800fb59ff3e7565397107fa9aad0d54d0
website/notifications/listeners.py
website/notifications/listeners.py
import logging from website.notifications.exceptions import InvalidSubscriptionError from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications from website.project.signals import contributor_added, project_created from framework.auth.signals import user_confirmed l...
import logging from website.notifications.exceptions import InvalidSubscriptionError from website.notifications.utils import subscribe_user_to_notifications, subscribe_user_to_global_notifications from website.project.signals import contributor_added, project_created from framework.auth.signals import user_confirmed l...
Revert "Remove incorrect check for institution_id"
Revert "Remove incorrect check for institution_id" This reverts commit 617df13670573b858b6c23249f4287786807d8b6.
Python
apache-2.0
hmoco/osf.io,cslzchen/osf.io,monikagrabowska/osf.io,cslzchen/osf.io,cslzchen/osf.io,Nesiehr/osf.io,aaxelb/osf.io,CenterForOpenScience/osf.io,chrisseto/osf.io,chennan47/osf.io,crcresearch/osf.io,Nesiehr/osf.io,felliott/osf.io,Johnetordoff/osf.io,acshi/osf.io,baylee-d/osf.io,HalcyonChimera/osf.io,brianjgeiger/osf.io,aaxe...
3318165728145a97a1b9b87ac212945d087c1e14
manifests/bin/db-add.py
manifests/bin/db-add.py
#!/usr/bin/env python import pymysql import os import syslog host = os.environ['DB_HOST'] user = os.environ['DB_USER'] password = os.environ['DB_PASSWORD'] db = os.environ['DB_DATABASE'] syslog.openlog(facility=syslog.LOG_USER) syslog.syslog("Inserting new business data into database.") connection = pymysql.connect(...
#!/usr/bin/env python import pymysql import os import syslog host = os.environ['DB_HOST'] user = os.environ['DB_USER'] password = os.environ['DB_PASSWORD'] db = os.environ['DB_DATABASE'] syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_USER) syslog.syslog("Inserting new business data into database.") con...
Set flag to log process id in syslog
Set flag to log process id in syslog
Python
apache-2.0
boundary/tsi-lab,boundary/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab
6f90c6543224155be1234de199c8b3c9775b72f3
zephyr/projects/brya/brya/BUILD.py
zephyr/projects/brya/brya/BUILD.py
# Copyright 2021 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. register_npcx_project( project_name="brya", zephyr_board="brya", dts_overlays=[ "battery.dts", "bb_retimer.dts", "cbi_...
# Copyright 2021 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. brya = register_npcx_project( project_name="brya", zephyr_board="brya", dts_overlays=[ "battery.dts", "bb_retimer.dts", ...
Add "ghost" variant of brya
zephyr: Add "ghost" variant of brya Right now using brya hardware to develop ghost EC. Initially it can be a simple rename of brya. Later we will change the charger chip, which will require a couple of DTS customizations. Eventually, this project will need to move to not be a brya variant at some point. BUG=b:2227...
Python
bsd-3-clause
coreboot/chrome-ec,coreboot/chrome-ec,coreboot/chrome-ec,coreboot/chrome-ec,coreboot/chrome-ec,coreboot/chrome-ec
c0a7554c7c8160d6a7b4023441c3cbe5e2f46ee5
tests/test_replwrap.py
tests/test_replwrap.py
import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap...
import sys import unittest import pexpect from pexpect import replwrap class REPLWrapTestCase(unittest.TestCase): def test_python(self): py = replwrap.python(sys.executable) res = py.run_command("5+6") self.assertEqual(res.strip(), "11") def test_multiline(self): py = replwrap...
Fix another unicode literal for Python 3.2
Fix another unicode literal for Python 3.2
Python
isc
dongguangming/pexpect,blink1073/pexpect,crdoconnor/pexpect,nodish/pexpect,Wakeupbuddy/pexpect,Depado/pexpect,crdoconnor/pexpect,quatanium/pexpect,crdoconnor/pexpect,nodish/pexpect,quatanium/pexpect,bangi123/pexpect,quatanium/pexpect,bangi123/pexpect,bangi123/pexpect,blink1073/pexpect,nodish/pexpect,Depado/pexpect,Wakeu...
ff435c335115262b38d66b912fe4e17b2861b45a
26-lazy-rivers/tf-26.py
26-lazy-rivers/tf-26.py
#!/usr/bin/env python import sys, operator, string def characters(filename): for line in open(filename): for c in line: yield c def all_words(filename): start_char = True for c in characters(filename): if start_char == True: word = "" if c.isalnum(): ...
#!/usr/bin/env python import sys, operator, string def characters(filename): for line in open(filename): for c in line: yield c def all_words(filename): start_char = True for c in characters(filename): if start_char == True: word = "" if c.isalnum(): ...
Make the last function also a generator, so that the explanation flows better
Make the last function also a generator, so that the explanation flows better
Python
mit
folpindo/exercises-in-programming-style,crista/exercises-in-programming-style,rajanvenkataguru/exercises-in-programming-style,panesofglass/exercises-in-programming-style,panesofglass/exercises-in-programming-style,wolfhesse/exercises-in-programming-style,jw0201/exercises-in-programming-style,kranthikumar/exercises-in-p...
73aa38a5d481a26278dd29364f16839cad0f22cf
manager/projects/ui/views/files.py
manager/projects/ui/views/files.py
from django.contrib.auth.decorators import login_required from django.http import HttpRequest, HttpResponse from django.shortcuts import render from projects.api.views.files import ProjectsFilesViewSet @login_required def list(request: HttpRequest, *args, **kwargs) -> HttpResponse: """ Get a list of project ...
from django.contrib.auth.decorators import login_required from django.http import HttpRequest, HttpResponse from django.shortcuts import render from projects.api.views.files import ProjectsFilesViewSet @login_required def list(request: HttpRequest, *args, **kwargs) -> HttpResponse: """ Get a list of project ...
Update view for change in viewset
refactor(Files): Update view for change in viewset
Python
apache-2.0
stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub
ff460f9a3c7df3322271eeb5de3bead72fe121bc
bmi_tester/tests_pytest/test_grid_uniform_rectilinear.py
bmi_tester/tests_pytest/test_grid_uniform_rectilinear.py
import warnings import numpy as np def test_get_grid_shape(new_bmi, gid): """Test the grid shape.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_g...
import warnings import numpy as np def test_get_grid_shape(new_bmi, gid): """Test the grid shape.""" gtype = new_bmi.get_grid_type(gid) if gtype == 'uniform_rectilinear': ndim = new_bmi.get_grid_rank(gid) shape = np.empty(ndim, dtype=np.int32) try: rtn = new_bmi.get_g...
Remove test for get_grid_shape for scalar grids.
Remove test for get_grid_shape for scalar grids.
Python
mit
csdms/bmi-tester
a19eac7104268865bd66bac520ffd41eacc30920
lifetimes/datasets/__init__.py
lifetimes/datasets/__init__.py
# -*- coding: utf-8 -*- # modified from https://github.com/CamDavidsonPilon/lifelines/ import pandas as pd from pkg_resources import resource_filename __all__ = [ 'load_cdnow', 'load_transaction_data', ] def load_dataset(filename, **kwargs): ''' Load a dataset from lifetimes.datasets Parameters...
# -*- coding: utf-8 -*- # modified from https://github.com/CamDavidsonPilon/lifelines/ import pandas as pd from pkg_resources import resource_filename __all__ = [ 'load_cdnow', 'load_transaction_data', ] def load_dataset(filename, **kwargs): ''' Load a dataset from lifetimes.datasets Parameters...
Add a doc string to make using this dataset easier
Add a doc string to make using this dataset easier
Python
mit
aprotopopov/lifetimes,CamDavidsonPilon/lifetimes,luke14free/lifetimes,statwonk/lifetimes
4622125a0f73a77ae0327deb886ac9d4b1c50791
events/views.py
events/views.py
from django.shortcuts import render_to_response from django.template import RequestContext import datetime from django.http import Http404 from events.models import Event from events.models import Calendar def index(request): calendars = Calendar.objects.all() return render_to_response( 'events/index....
from django.shortcuts import render_to_response from django.template import RequestContext from django.core.urlresolvers import resolve import datetime from django.http import Http404 from events.models import Event from events.models import Calendar def index(request): calendars = Calendar.objects.all() curr...
Add current_app to context for django-cms v3 support
Add current_app to context for django-cms v3 support
Python
bsd-3-clause
theherk/django-theherk-events
57b35933e3accc3013b2ba417ad78340c10ed807
lighty/wsgi/commands.py
lighty/wsgi/commands.py
from wsgiref.simple_server import make_server from . import WSGIApplication def run_server(settings): application = WSGIApplication(settings) httpd = make_server('', 8000, application) print("Serving on port 8000...") httpd.serve_forever()
def run_server(settings): '''Run application using wsgiref test server ''' from wsgiref.simple_server import make_server from . import WSGIApplication application = WSGIApplication(settings) httpd = make_server('', 8000, application) print("Serving on port 8000...") httpd.serve_forever...
Add base tornado server support
Add base tornado server support
Python
bsd-3-clause
GrAndSE/lighty
0356392b2933aa7c02f89bdf588a4ec0482db4a8
tests/main_test.py
tests/main_test.py
#!/usr/bin/env python3 from libpals.util import xor_find_singlechar_key def test_xor_find_singlechar_key(): input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' ciphertext = bytes.fromhex(input) result = xor_find_singlechar_key(ciphertext) assert result['key'] == 88 asse...
#!/usr/bin/env python3 from libpals.util import xor_find_singlechar_key, hamming_distance def test_xor_find_singlechar_key(): input = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' ciphertext = bytes.fromhex(input) result = xor_find_singlechar_key(ciphertext) assert result['key...
Add a test for hamming_distance()
Add a test for hamming_distance()
Python
bsd-2-clause
cpach/cryptopals-python3
bca6a06f6035e7a10c9726ef40e7aed4b4b7ee34
tests/test_init.py
tests/test_init.py
# archivebox init # archivebox add import os import subprocess from pathlib import Path import json from .fixtures import * def test_init(tmp_path, process): assert "Initializing a new ArchiveBox collection in this folder..." in process.stdout.decode("utf-8") def test_update(tmp_path, process): os.chdir...
# archivebox init # archivebox add import os import subprocess from pathlib import Path import json from .fixtures import * def test_init(tmp_path, process): assert "Initializing a new ArchiveBox collection in this folder..." in process.stdout.decode("utf-8") def test_update(tmp_path, process): os.chdir...
Fix test to reflect new API changes
test: Fix test to reflect new API changes
Python
mit
pirate/bookmark-archiver,pirate/bookmark-archiver,pirate/bookmark-archiver
d0d4491828942d22a50ee80110f38c54a1b5c301
services/disqus.py
services/disqus.py
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provide...
from oauthlib.oauth2.draft25 import utils import foauth.providers def token_uri(service, token, r): params = [((u'access_token', token)), ((u'api_key', service.client_id))] r.url = utils.add_params_to_uri(r.url, params) return r class Disqus(foauth.providers.OAuth2): # General info about the provide...
Rewrite Disqus to use the new scope selection system
Rewrite Disqus to use the new scope selection system
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
c530ea901c374fef97390260e66492f37fc90a3f
setman/__init__.py
setman/__init__.py
from setman.lazy import LazySettings __all__ = ('get_version', 'settings') VERSION = (0, 1, 'beta') settings = LazySettings() def get_version(version=None): """ Return setman version number in human readable form. You could call this function without args and in this case value from ``setman.VERS...
try: from setman.lazy import LazySettings except ImportError: # Do not care about "Settings cannot be imported, because environment # variable DJANGO_SETTINGS_MODULE is undefined." errors LazySettings = type('LazySettings', (object, ), {}) __all__ = ('get_version', 'settings') VERSION = (0, 1, 'beta...
Fix installing ``django-setman`` via PIP.
Fix installing ``django-setman`` via PIP.
Python
bsd-3-clause
playpauseandstop/setman,owais/django-setman,owais/django-setman
35d84021736f5509dc37f12ca92a05693cff5d47
twython/helpers.py
twython/helpers.py
from .compat import basestring def _transparent_params(_params): params = {} files = {} for k, v in _params.items(): if hasattr(v, 'read') and callable(v.read): files[k] = v elif isinstance(v, bool): if v: params[k] = 'true' else: ...
from .compat import basestring def _transparent_params(_params): params = {} files = {} for k, v in _params.items(): if hasattr(v, 'read') and callable(v.read): files[k] = v elif isinstance(v, bool): if v: params[k] = 'true' else: ...
Include ints in params too
Include ints in params too Oops ;P
Python
mit
vivek8943/twython,ping/twython,akarambir/twython,Fueled/twython,fibears/twython,Hasimir/twython,Devyani-Divs/twython,Oire/twython,joebos/twython,ryanmcgrath/twython
778df70d5e755d0681636cb401bbf33f17f247bc
uniqueids/admin.py
uniqueids/admin.py
from django.contrib import admin from .models import Record from .tasks import send_personnel_code class RecordAdmin(admin.ModelAdmin): list_display = [ "id", "identity", "write_to", "created_at", "updated_at"] list_filter = ["write_to", "created_at"] search_fields = ["identity", "write_to"] ...
from django.contrib import admin from .models import Record from .tasks import send_personnel_code class RecordAdmin(admin.ModelAdmin): list_display = [ "id", "identity", "write_to", "created_at", "updated_at"] list_filter = ["write_to", "created_at"] search_fields = ["identity", "write_to"] ...
Use Iterator to iterate through records
Use Iterator to iterate through records
Python
bsd-3-clause
praekelt/hellomama-registration,praekelt/hellomama-registration
978e09882f4fb19a8d31a9b91b0258751f745c21
mods/FleetAutoTarget/AutoTarget.py
mods/FleetAutoTarget/AutoTarget.py
import logmodule from eve.client.script.ui.shared.fleet.fleetbroadcast import FleetBroadcastView def PatchFn(fn): def wrapper(self): try: br = sm.GetService('fleet').GetBroadcastHistory()[0] logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br.name, br.charID, br.it...
import logmodule from eve.client.script.ui.shared.fleet.fleetbroadcast import FleetBroadcastView def PatchFn(fn): def wrapper(self): ret = fn(self) try: br = sm.GetService('fleet').GetBroadcastHistory()[0] logmodule.general.Log("GetBroadcastListEntry invoked: %s %d %d" % (br...
Adjust the order to reduce latency
Adjust the order to reduce latency
Python
mit
EVEModX/Mods
d2e41e3c03e71919aeeaa72766f6c4037424d3c1
tests/factories.py
tests/factories.py
from django.contrib.auth.models import User import factory class UserFactory(factory.DjangoModelFactory): username = factory.Sequence('User {}'.format) class Meta: model = User @factory.post_generation def password(self, create, extracted, **kwargs): self.raw_password = 'default_pass...
from django.contrib.auth.models import User import factory class UserFactory(factory.DjangoModelFactory): username = factory.Sequence('User {}'.format) class Meta: model = User @factory.post_generation def password(self, create, extracted, **kwargs): # By using this method password c...
Add comment about User factory post_generation
Add comment about User factory post_generation
Python
bsd-2-clause
incuna/incuna-test-utils,incuna/incuna-test-utils
94aec9e4a6501e875dbd6b59df57598f742a82da
ca_on_niagara/people.py
ca_on_niagara/people.py
from __future__ import unicode_literals from utils import CSVScraper COUNCIL_PAGE = 'http://www.niagararegion.ca/test/sherpa-list-to-csv.aspx?list=council-elected-officials-csv' class NiagaraPersonScraper(CSVScraper): csv_url = 'http://www.niagararegion.ca/test/sherpa-list-to-csv.aspx?list=council-elected-offici...
from __future__ import unicode_literals from utils import CSVScraper COUNCIL_PAGE = 'http://www.niagararegion.ca/test/sherpa-list-to-csv.aspx?list=council-elected-officials-csv' class NiagaraPersonScraper(CSVScraper): # The new data file: # * has underscores in headers # * yses "District_ID" instead of "...
Add comments about new file
ca_on_niagara: Add comments about new file
Python
mit
opencivicdata/scrapers-ca,opencivicdata/scrapers-ca
3c0f8899521465fcb2d4685b6e6e6e3e61c0eabc
kitchen/dashboard/graphs.py
kitchen/dashboard/graphs.py
"""Facility to render node graphs using pydot""" import os import pydot from kitchen.settings import STATIC_ROOT, REPO def generate_node_map(nodes): """Generates a graphviz nodemap""" graph = pydot.Dot(graph_type='digraph') graph_nodes = {} # Create nodes for node in nodes: label = node['...
"""Facility to render node graphs using pydot""" import os import pydot from kitchen.settings import STATIC_ROOT, REPO def generate_node_map(nodes): """Generates a graphviz nodemap""" graph = pydot.Dot(graph_type='digraph') graph_nodes = {} # Create nodes for node in nodes: label = node['...
Change to "ask for forgiveness", as the 'client_roles' condition could get too complicated
Change to "ask for forgiveness", as the 'client_roles' condition could get too complicated
Python
apache-2.0
edelight/kitchen,edelight/kitchen,edelight/kitchen,edelight/kitchen
9354bf323db14bf68d68a0af26d59b46d068af0f
seleniumbase/console_scripts/rich_helper.py
seleniumbase/console_scripts/rich_helper.py
from rich.console import Console from rich.markdown import Markdown from rich.syntax import Syntax def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap): syntax = Syntax( code, lang, theme=theme, line_numbers=line_numbers, code_width=code_width, ...
from rich.console import Console from rich.markdown import Markdown from rich.syntax import Syntax def process_syntax(code, lang, theme, line_numbers, code_width, word_wrap): syntax = Syntax( code, lang, theme=theme, line_numbers=line_numbers, code_width=code_width, ...
Update double_width_emojis list to improve "rich" printing
Update double_width_emojis list to improve "rich" printing
Python
mit
seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
d8d24b48d4956d569a0d0e37733c73db43015035
test_settings.py
test_settings.py
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', ...
from os.path import expanduser from foundry.settings import * # Postgis because we want to test full functionality DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'jmbo_spatial', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '', ...
Disable some apps for tests
Disable some apps for tests
Python
bsd-3-clause
praekelt/jmbo-foundry,praekelt/jmbo-foundry,praekelt/jmbo-foundry
b958d723f73f7743d646c2c6911bf8428583bf0e
tests/test_compound.py
tests/test_compound.py
import pytest from katana.storage import Node, Pair, prepare from katana.compound import sequence, group, repeat, option, maybe from katana.term import term A = term('a') B = term('b') C = term('c') node = lambda x: Node(x, 'data') def test_sequence(): na = node('a') nb = node('b') s = sequence(A, B) ...
import pytest from katana.storage import Node, Pair, prepare from katana.compound import sequence, group, repeat, option, maybe from katana.term import term Ta = term('a') Tb = term('b') Tc = term('c') Na = Node('a', 'data') Nb = Node('b', 'data') Nc = Node('c', 'data') def test_sequence(): s = sequence(Ta, Tb)...
Refactor test case for compound terms
Refactor test case for compound terms
Python
mit
eugene-eeo/katana
573d3d8b652527e0293321e09474f7a6e5b243f4
tests/test_dispatch.py
tests/test_dispatch.py
import accordian import pytest def test_unknown_event(loop): """ An exception should be thrown when trying to register a handler for an unknown event. """ dispatch = accordian.Dispatch(loop=loop) with pytest.raises(ValueError): dispatch.on("unknown") def test_clean_stop(loop): di...
import pytest def test_start_idempotent(loop, dispatch): loop.run_until_complete(dispatch.start()) assert dispatch.running loop.run_until_complete(dispatch.start()) assert dispatch.running def test_stop_idempotent(loop, dispatch): loop.run_until_complete(dispatch.start()) assert dispatch.ru...
Test dispatch (un)register, basic handler
Test dispatch (un)register, basic handler
Python
mit
numberoverzero/accordian
6794cc50e272d134900673ed4eaded73580b746c
tests/test_response.py
tests/test_response.py
import json import unittest from alerta.app import create_app, db class ApiResponseTestCase(unittest.TestCase): def setUp(self): test_config = { 'TESTING': True, 'BASE_URL': 'https://api.alerta.dev:9898/_' } self.app = create_app(test_config) self.client =...
import json import unittest from alerta.app import create_app, db class ApiResponseTestCase(unittest.TestCase): def setUp(self): test_config = { 'TESTING': True, 'BASE_URL': 'https://api.alerta.dev:9898/_' } self.app = create_app(test_config) self.client =...
Add test for custom id in response
Add test for custom id in response
Python
apache-2.0
guardian/alerta,guardian/alerta,guardian/alerta,guardian/alerta
906c48fc91fdf3518fecf79e957cd618fc117b5b
traw/__init__.py
traw/__init__.py
from pbr.version import VersionInfo __version__ = VersionInfo('instabrade').semantic_version().release_string() from .client import Client # NOQA
""" TRAW: TestRail API Wrapper TRAW is an API wrapper for Gurrock's TestRail test management suite The intended way to begin is to instantiate the TRAW Client: .. code-block:: python import traw testrail = traw.Client(username='username', user_api_key='api_key', ...
Update docstrings and help() messages
Update docstrings and help() messages
Python
mit
levi-rs/traw
5c0bee77329f68ed0b2e3b576747886492007b8c
neovim/tabpage.py
neovim/tabpage.py
from util import RemoteMap class Tabpage(object): @property def windows(self): if not hasattr(self, '_windows'): self._windows = RemoteSequence(self, self.Window, lambda: self.get_windows()) return...
from util import RemoteMap, RemoteSequence class Tabpage(object): @property def windows(self): if not hasattr(self, '_windows'): self._windows = RemoteSequence(self, self._vim.Window, lambda: self.get_wind...
Fix 'windows' property of Tabpage objects
Fix 'windows' property of Tabpage objects
Python
apache-2.0
bfredl/python-client,fwalch/python-client,Shougo/python-client,neovim/python-client,meitham/python-client,brcolow/python-client,traverseda/python-client,neovim/python-client,Shougo/python-client,meitham/python-client,starcraftman/python-client,brcolow/python-client,0x90sled/python-client,fwalch/python-client,zchee/pyth...
b5ecb9c41aacea5450966a2539dc5a6af56ef168
sale_order_mail_product_attach_prod_pack/__init__.py
sale_order_mail_product_attach_prod_pack/__init__.py
# -*- coding: utf-8 -*- ############################################################################## # # Ingenieria ADHOC - ADHOC SA # https://launchpad.net/~ingenieria-adhoc # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lice...
# -*- coding: utf-8 -*- ############################################################################## # # Ingenieria ADHOC - ADHOC SA # https://launchpad.net/~ingenieria-adhoc # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public Lice...
FIX sale order prod attach prod pack
FIX sale order prod attach prod pack
Python
agpl-3.0
ingadhoc/account-payment,ingadhoc/product,syci/ingadhoc-odoo-addons,ingadhoc/sale,ingadhoc/sale,jorsea/odoo-addons,ClearCorp/account-financial-tools,bmya/odoo-addons,HBEE/odoo-addons,bmya/odoo-addons,maljac/odoo-addons,maljac/odoo-addons,ingadhoc/odoo-addons,ingadhoc/partner,syci/ingadhoc-odoo-addons,dvitme/odoo-addons...
12a6c979c7648b9fa43165286afebac9e8df7101
src/app.py
src/app.py
''' The main app ''' from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return 'A work in progress, check back later' if __name__ == '__main__': app.run()
''' The main app ''' from flask import Flask app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): return 'A work in progress, check back later' @app.route('/add', methods=['POST']) def add_reminder(): return 'Use this method to POST new reminders to the database' @app.route('/show',...
Add method stubs for sending and receiving tasks to/ from the database
Add method stubs for sending and receiving tasks to/ from the database
Python
bsd-2-clause
ambidextrousTx/RPostIt
b7ea23ce3cfdcc41450a2512d62da17e67a316fd
test/test_driver.py
test/test_driver.py
#!/usr/bin/env python from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import os import sys driver = webdriver.Firefox() driver.get("file://%s" % (os.path.join(os.getcwd(...
#!/usr/bin/env python """ Selenium test runner. """ import os import sys from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait def main(): """ Main program. """ driver = webdriver.Firefox() driver.get( "file://%s" % (os.path.join(os.getcwd(), "test/test_...
Tidy up python test script
Tidy up python test script
Python
mit
johnelse/ocaml-webaudio,johnelse/ocaml-webaudio,johnelse/ocaml-webaudio
62cbc5025913b8d6dd2b5323ad027d6b5ff56efb
resources/migrations/0007_auto_20180306_1150.py
resources/migrations/0007_auto_20180306_1150.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtaildocs', '0007_merge'), ('core', '0026_auto_20180306_1150'), ('resources', '0006_add_fi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('wagtaildocs', '0007_merge'), ('resources', '0006_add_field_for_absolute_slideshare_url'), ] ...
Update migration file to lose dependency from discarded migration file
Update migration file to lose dependency from discarded migration file
Python
bsd-3-clause
PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari
cddc9b20855147541859976229e1dc34a611de26
twitterfunctions.py
twitterfunctions.py
#!/usr/bin/env python # twitterfunctions.py # description: This file contains all the functions that are used when connecting to Twitter. Almost all of them rely on Tweepy # copyrigtht: 2015 William Patton - PattonWebz # licence: GPLv3 import tweepy def authenticatetwitter(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, A...
#!/usr/bin/env python # twitterfunctions.py # description: This file contains all the functions that are used when connecting to Twitter. Almost all of them rely on Tweepy # copyrigtht: 2015 William Patton - PattonWebz # licence: GPLv3 import tweepy def authenticatetwitter(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, A...
Change the api.update_status() call to explicitly state the 'status' message.
Change the api.update_status() call to explicitly state the 'status' message. - A recent version of Tweepy required it to be explicit, no harm in always being so
Python
agpl-3.0
pattonwebz/ScheduledTweetBot
00c28d76d93331d7a501f0006cbadcaef48e499f
d1lod/tests/conftest.py
d1lod/tests/conftest.py
import pytest from d1lod import sesame @pytest.fixture(scope="module") def store(): return sesame.Store('localhost', 8080) @pytest.fixture(scope="module") def repo(store): return sesame.Repository(store, 'test') @pytest.fixture(scope="module") def interface(repo): return sesame.Interface(repo)
import pytest from d1lod import sesame @pytest.fixture(scope="module") def store(): return sesame.Store('localhost', 8080) @pytest.fixture(scope="module") def repo(store): namespaces = { 'owl': 'http://www.w3.org/2002/07/owl#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'rdf': '...
Add default set of namespaces to test repository instance
Add default set of namespaces to test repository instance
Python
apache-2.0
ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod
5a92874673f8dc5b08dd7826a10121a83fb2f0c6
rotational-cipher/rotational_cipher.py
rotational-cipher/rotational_cipher.py
import string UPPER = string.ascii_uppercase LOWER = string.ascii_lowercase def rotate(s, n): rules = shift_rules(n) return "".join(map(lambda k: rules.get(k, k), s)) def shift_rules(n): shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n] return {k:v for k,v in zip(UPPER+LOWER, shifted)}
import string UPPER = string.ascii_uppercase LOWER = string.ascii_lowercase def rotate(s, n): rules = shift_rules(n) return "".join(rules.get(ch, ch) for ch in s) def shift_rules(n): shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n] return {k:v for k,v in zip(UPPER+LOWER, shifted)}
Use a comprehension instead of a lambda function
Use a comprehension instead of a lambda function
Python
agpl-3.0
CubicComet/exercism-python-solutions
f3e0cc4b5a778b04373773dabd27be8782b1af93
cosmo_tester/test_suites/snapshots/conftest.py
cosmo_tester/test_suites/snapshots/conftest.py
import pytest from cosmo_tester.framework.test_hosts import Hosts from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list @pytest.fixture(scope='function', params=get_multi_tenant_versions_list()) def hosts(request, ssh_key, module_tmpdir, test_config, logger): hosts = Hosts( ssh_ke...
import pytest from cosmo_tester.framework.test_hosts import Hosts, get_image from cosmo_tester.test_suites.snapshots import get_multi_tenant_versions_list @pytest.fixture(scope='function', params=get_multi_tenant_versions_list()) def hosts(request, ssh_key, module_tmpdir, test_config, logger): hosts = Hosts( ...
Use specified images for snapshot fixture
Use specified images for snapshot fixture
Python
apache-2.0
cloudify-cosmo/cloudify-system-tests,cloudify-cosmo/cloudify-system-tests
b3c10f9cc4c53116c35e76dec184f4b44d28aaf4
views/main.py
views/main.py
from flask import redirect from flask import render_template from flask import request import database.link from database import db_txn from linkr import app from uri.link import * from uri.main import * @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) @db_txn def alias_route(alias): #...
from flask import redirect from flask import render_template from flask import request import database.link from linkr import app from uri.link import * from uri.main import * @app.route(LinkAliasRedirectURI.path, methods=LinkAliasRedirectURI.methods) def alias_route(alias): # Attempt to fetch the link mapping f...
Remove unnecessary @db_txn decorator on alias_route
Remove unnecessary @db_txn decorator on alias_route
Python
mit
LINKIWI/linkr,LINKIWI/linkr,LINKIWI/linkr
bc0022c32ef912eba9cc3d9683c1649443d6aa35
pyfibot/modules/module_btc.py
pyfibot/modules/module_btc.py
# -*- encoding: utf-8 -*- from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.spli...
# -*- encoding: utf-8 -*- from __future__ import unicode_literals, print_function, division def command_btc(bot, user, channel, args): """Display current BTC exchange rates from mtgox. Usage: btc [whitespace separated list of currency codes]""" currencies = ["EUR"] if args: currencies = args.spli...
Add support for LTC in mtgox
Add support for LTC in mtgox
Python
bsd-3-clause
rnyberg/pyfibot,EArmour/pyfibot,EArmour/pyfibot,aapa/pyfibot,lepinkainen/pyfibot,huqa/pyfibot,rnyberg/pyfibot,huqa/pyfibot,aapa/pyfibot,lepinkainen/pyfibot
aa97385399e358110e5fbacaaa41c9b7fb8c75be
src/nodeconductor_assembly_waldur/experts/filters.py
src/nodeconductor_assembly_waldur/experts/filters.py
import django_filters from nodeconductor.core import filters as core_filters from . import models class ExpertProviderFilter(django_filters.FilterSet): customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid') customer_uuid = django_filters.UUIDFilter(name='customer__uuid') ...
import django_filters from nodeconductor.core import filters as core_filters from . import models class ExpertProviderFilter(django_filters.FilterSet): customer = core_filters.URLFilter(view_name='customer-detail', name='customer__uuid') customer_uuid = django_filters.UUIDFilter(name='customer__uuid') ...
Add name filter to expert requests
Add name filter to expert requests [WAL-989]
Python
mit
opennode/waldur-mastermind,opennode/waldur-mastermind,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/nodeconductor-assembly-waldur,opennode/waldur-mastermind,opennode/waldur-mastermind
744c995ffe1faf55fda68405243551dbb078ae60
uchicagohvz/production_settings.py
uchicagohvz/production_settings.py
from local_settings import * # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'uchicagohvz', # Or path to database file if using sqlite3. 'USER': ...
from local_settings import * ALLOWED_HOSTS = ['uchicagohvz.org'] # Database DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'uchicagohvz', # Or path to database fi...
Add ALLOWED_HOSTS to production settings
Add ALLOWED_HOSTS to production settings
Python
mit
kz26/uchicago-hvz,kz26/uchicago-hvz,kz26/uchicago-hvz
00c3f1e3eb38a22d95c6e59f72e51a9b53723a31
brains/namelist/tasks.py
brains/namelist/tasks.py
from celery.task import task from namelist.scrape import get_user_profile_id, scrape_profile, NotFound from namelist.models import Player, Category @task() def import_user(user, profile_name_or_id, category=None): if isinstance(profile_name_or_id, basestring): try: profile_id = get_user_profile...
from celery.task import task from namelist.scrape import get_user_profile_id, scrape_profile, NotFound from namelist.models import Player, Category @task() def import_user(profile_name_or_id, category=None, user=None): if isinstance(profile_name_or_id, basestring): try: profile_id = get_user_pr...
Fix duplicate profile key errors with a less specific query.
Fix duplicate profile key errors with a less specific query.
Python
bsd-3-clause
crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains
480f1794d37c524893645e296e22a37490a2795e
frappe/patches/v12_0/update_print_format_type.py
frappe/patches/v12_0/update_print_format_type.py
import frappe def execute(): frappe.db.sql(''' UPDATE `tabPrint Format` SET `print_format_type` = "Jinja" WHERE `print_format_type` in ("Server", "Client") ''') frappe.db.sql(''' UPDATE `tabPrint Format` SET `print_format_type` = "JS" WHERE `print_format_type` = "Js" ''')
import frappe def execute(): frappe.db.sql(''' UPDATE `tabPrint Format` SET `print_format_type` = 'Jinja' WHERE `print_format_type` in ('Server', 'Client') ''') frappe.db.sql(''' UPDATE `tabPrint Format` SET `print_format_type` = 'JS' WHERE `print_format_type` = 'Js' ''')
Make db query postgres compatible
Make db query postgres compatible
Python
mit
mhbu50/frappe,saurabh6790/frappe,adityahase/frappe,vjFaLk/frappe,StrellaGroup/frappe,adityahase/frappe,saurabh6790/frappe,almeidapaulopt/frappe,yashodhank/frappe,StrellaGroup/frappe,StrellaGroup/frappe,frappe/frappe,yashodhank/frappe,yashodhank/frappe,adityahase/frappe,yashodhank/frappe,almeidapaulopt/frappe,vjFaLk/fra...
1de05b64363d6a99cceb3b047813893915c0842b
pyetherscan/settings.py
pyetherscan/settings.py
import os TESTING_API_KEY = 'YourApiKeyToken' ETHERSCAN_API_KEY = os.environ.get('ETHERSCAN_API_KEY', TESTING_API_KEY)
import os HOME_DIR = os.path.expanduser('~') CONFIG_FILE = '.pyetherscan.ini' PATH = os.path.join(HOME_DIR, CONFIG_FILE) TESTING_API_KEY = 'YourApiKeyToken' if os.path.isfile(PATH): from configparser import ConfigParser config = ConfigParser() config.read(PATH) ETHERSCAN_API_KEY = config['Credentials'...
Add support for a configuration file
Add support for a configuration file
Python
mit
Marto32/pyetherscan
f98ff54c363fc2f2b0885464afffcb92cdea8cfe
ubersmith/calls/device.py
ubersmith/calls/device.py
"""Device call classes. These classes implement any response cleaning and validation needed. If a call class isn't defined for a given method then one is created using ubersmith.calls.BaseCall. """ from ubersmith.calls import BaseCall, GroupCall from ubersmith.utils import prepend_base __all__ = [ 'GetCall', ...
"""Device call classes. These classes implement any response cleaning and validation needed. If a call class isn't defined for a given method then one is created using ubersmith.calls.BaseCall. """ from ubersmith.calls import BaseCall, GroupCall, FileCall from ubersmith.utils import prepend_base __all__ = [ 'G...
Make module graph call return a file.
Make module graph call return a file.
Python
mit
hivelocity/python-ubersmith,jasonkeene/python-ubersmith,hivelocity/python-ubersmith,jasonkeene/python-ubersmith
223be3e40e32564087095227e229c1b0649becd8
tests/test_feeds.py
tests/test_feeds.py
import pytest from django.core.urlresolvers import reverse from name.models import Name, Location pytestmark = pytest.mark.django_db def test_feed_has_georss_namespace(client): response = client.get(reverse('name_feed')) assert 'xmlns:georss' in response.content def test_feed_response_is_application_xml(...
import pytest from django.core.urlresolvers import reverse from name.feeds import NameAtomFeed from name.models import Name, Location pytestmark = pytest.mark.django_db def test_feed_has_georss_namespace(rf): request = rf.get(reverse('name_feed')) feed = NameAtomFeed() response = feed(request) asse...
Test the feed using the request factory instead of the client.
Test the feed using the request factory instead of the client.
Python
bsd-3-clause
damonkelley/django-name,unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,unt-libraries/django-name,damonkelley/django-name
0907bef1a0f92f9f7fef628afba75e1d02db1d70
thermof/__init__.py
thermof/__init__.py
# Date: August 2017 # Author: Kutay B. Sezginel """ Thermal conductivity calculations of porous crystals using Lammps """ from .simulation import Simulation from .trajectory import Trajectory from .mof import MOF
# Date: August 2017 # Author: Kutay B. Sezginel """ Thermal conductivity calculations of porous crystals using Lammps """ from .simulation import Simulation from .trajectory import Trajectory from .parameters import Parameters from .mof import MOF
Add parameter import to main module
Add parameter import to main module
Python
mit
kbsezginel/tee_mof,kbsezginel/tee_mof
21e5356e7092d6cd98ae2e3dd5befc98a36711d0
python_server/server.py
python_server/server.py
import flask import os current_dir = os.path.dirname(os.path.realpath(__file__)) parent_dir = os.path.dirname(current_dir) data_dir = os.path.join(parent_dir, "static-site", "data") app = flask.Flask(__name__) def add_data(file_name): return "data/" + file_name @app.route("/data_files") def data_files(): body =...
from flask.ext.cors import CORS import flask import os import csv current_dir = os.path.dirname(os.path.realpath(__file__)) parent_dir = os.path.dirname(current_dir) data_dir = os.path.join(parent_dir, "static-site", "data") app = flask.Flask(__name__) CORS(app) def reduce_to_json(json_data, next_data): labels = ...
Add endpoint to convert the csv datafiles to json
Add endpoint to convert the csv datafiles to json
Python
epl-1.0
jacqt/clojurescript-ode-solvers,jacqt/clojurescript-ode-solvers,jacqt/clojurescript-ode-solvers
96bf0e8dbf30650ba91e70a766071c6e348da6f3
reactive/nodemanager.py
reactive/nodemanager.py
from charms.reactive import when, when_not, set_state, remove_state from charms.hadoop import get_hadoop_base from jujubigdata.handlers import YARN from jujubigdata import utils @when('resourcemanager.ready') @when_not('nodemanager.started') def start_nodemanager(resourcemanager): hadoop = get_hadoop_base() y...
from charms.reactive import when, when_not, set_state, remove_state from charms.layer.hadoop_base import get_hadoop_base from jujubigdata.handlers import YARN from jujubigdata import utils @when('resourcemanager.ready') @when_not('nodemanager.started') def start_nodemanager(resourcemanager): hadoop = get_hadoop_b...
Update charms.hadoop reference to follow convention
Update charms.hadoop reference to follow convention
Python
apache-2.0
juju-solutions/layer-apache-hadoop-nodemanager
a41660f3ae7137bd4d391847b297ef9a4a281109
twixer-cli.py
twixer-cli.py
from twixer.twixer import main if __name__ == '__main__': main()
#!/user/bin/env python from twixer.twixer import main if __name__ == '__main__': main()
Add a command line launcher
Add a command line launcher
Python
mit
davidmogar/twixer,davidmogar/twixer
f5b13d16045e7e734a66bc13873ab5f4e8045f5a
skylines/views/about.py
skylines/views/about.py
import os.path from flask import Blueprint, render_template from flask.ext.babel import _ from skylines import app from skylines.lib.helpers import markdown about_blueprint = Blueprint('about', 'skylines') @about_blueprint.route('/') def about(): return render_template('about.jinja') @about_blueprint.route('...
import os.path from flask import Blueprint, render_template, current_app from flask.ext.babel import _ from skylines.lib.helpers import markdown about_blueprint = Blueprint('about', 'skylines') @about_blueprint.route('/') def about(): return render_template('about.jinja') @about_blueprint.route('/imprint') d...
Use current_app in Blueprint module
flask/views: Use current_app in Blueprint module
Python
agpl-3.0
RBE-Avionik/skylines,RBE-Avionik/skylines,Harry-R/skylines,Turbo87/skylines,snip/skylines,shadowoneau/skylines,TobiasLohner/SkyLines,TobiasLohner/SkyLines,TobiasLohner/SkyLines,kerel-fs/skylines,Harry-R/skylines,skylines-project/skylines,shadowoneau/skylines,Turbo87/skylines,snip/skylines,shadowoneau/skylines,RBE-Avion...
7fb46ddf6bab9d32908c8fb9c859fd8151fbd089
qipr/registry/forms/facet_form.py
qipr/registry/forms/facet_form.py
from registry.models import * from operator import attrgetter related_by_projects_Models = [ BigAim, ClinicalArea, ClinicalSetting, Descriptor, ] class FacetForm: def __init__(self): self.facet_categories = [model.__name__ for model in related_by_projects_Models] for model in rela...
from registry.models import * from operator import attrgetter related_by_projects_Models = [ BigAim, ClinicalArea, ClinicalSetting, Descriptor, ] class FacetForm: def __init__(self): self.facet_categories = [model.__name__ for model in related_by_projects_Models] for model in rela...
Change the facet to sort by name instead of project count
Change the facet to sort by name instead of project count
Python
apache-2.0
ctsit/qipr,ctsit/qipr,ctsit/qipr,ctsit/qipr,ctsit/qipr
ab12d9e847448750067e798ba1b5a4238451dfee
antfarm/views/static.py
antfarm/views/static.py
''' Helper for serving static content. ''' from antfarm import response import mimetypes class ServeStatic(object): def __init__(self, root): self.root = root def __call__(self, path): full_path = os.path.absdir(os.path.join(self.root, path)) if not full_path.startswith(self.root): ...
''' Helper for serving static content. ''' import os.path from antfarm import response import mimetypes class ServeStatic(object): def __init__(self, root): self.root = root def __call__(self, request, path): full_path = os.path.abspath(os.path.join(self.root, path)) if not full_pat...
Handle missing files gracefully in ServeStatic
Handle missing files gracefully in ServeStatic
Python
mit
funkybob/antfarm
c9275ff9859f28753e2e261054e7c0aacc4c28dc
monitoring/co2/local/k30.py
monitoring/co2/local/k30.py
#!/usr/bin/env python3 #Python app to run a K-30 Sensor import serial import time from optparse import OptionParser import sys ser = serial.Serial("/dev/ttyAMA0") print("Serial Connected!", file=sys.stderr) ser.flushInput() time.sleep(1) parser = OptionParser() parser.add_option("-t", "--average-time", dest="avgtime...
#!/usr/bin/env python #Python app to run a K-30 Sensor import serial import time from optparse import OptionParser import sys ser = serial.Serial("/dev/serial0") #print("Serial Connected!", file=sys.stderr) ser.flushInput() time.sleep(1) parser = OptionParser() parser.add_option("-t", "--average-time", dest="avgtime...
Revert to python2, python3 converted code isn't working as expected
Revert to python2, python3 converted code isn't working as expected
Python
mit
xopok/xopok-scripts,xopok/xopok-scripts
43f02a76b72f0ada55c39d1b5f131a5ec72d29e6
apps/core/decorators.py
apps/core/decorators.py
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals from functools import wraps class AuthenticationRequiredError(RuntimeError): pass def ajax_login_required(func): @wraps(func) def __wrapper(request, *args, **kwargs): # Check authenticatio...
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals from functools import wraps from django.core.exceptions import PermissionDenied def ajax_login_required(func): @wraps(func) def __wrapper(request, *args, **kwargs): # Check authentication ...
Return 403 Permission Denied error for unauthenticated AJAX requests
Return 403 Permission Denied error for unauthenticated AJAX requests
Python
agpl-3.0
strongswan/strongTNC,strongswan/strongTNC,strongswan/strongTNC,strongswan/strongTNC
1de19bed8b61b87c1f1afd1b2c8e5499a9e2da9a
backend/breach/tests.py
backend/breach/tests.py
from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint="http://di.uoa.gr/", prefix="test", alpha...
from django.test import TestCase from breach.models import SampleSet, Victim, Target from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', alpha...
Fix double quotes in analyzer testcase
Fix double quotes in analyzer testcase
Python
mit
dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dimriou/rupture,dionyziz/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dimkarako...
4a6b1eea0ceda8fb4e9753ba91e1a6ba60c9182a
utils/add_sample_feeds.py
utils/add_sample_feeds.py
from smoke_signal import app, init_db from smoke_signal.database.helpers import add_feed from utils.generate_feed import SampleFeed from os import walk feeds_dir = app.root_path + "/test_resources/feeds/" app.config['DATABASE_PATH'] = 'sqlite:///smoke_signal/test_resources/posts.db' def create_sample_feed_files(nu...
from smoke_signal import app, init_db from smoke_signal.database.helpers import add_feed from utils.generate_feed import SampleFeed import feedparser from os import walk, makedirs FEEDS_DIR = app.root_path + "/test_resources/feeds/" app.config['DATABASE_PATH'] = 'sqlite:///smoke_signal/test_resources/posts.db' def...
Make script for adding sample feeds more usable
Make script for adding sample feeds more usable
Python
mit
flacerdk/smoke-signal,flacerdk/smoke-signal,flacerdk/smoke-signal
9c3ad42fab1ac73a500e43c98026525d96c2121a
sci_lib.py
sci_lib.py
#!/usr/bin/python #Author: Scott T. Salesky #Created: 12.6.2014 #Purpose: Collection of functions, routines to use #Python for scientific work #----------------------------------------------
#!/usr/bin/python #Author: Scott T. Salesky #Created: 12.6.2014 #Purpose: Collection of useful Python classes, #routines, and functions for scientific work #---------------------------------------------- #Import all required packages import numpy as np from matplotlib.colors import Normalize def read_f90_bin(path,nx,...
Add the MidPointNormalize class, which allows one to define the midpoint of a colormap. Useful, e.g. if plotting data in the range [-6,3] with contourf and a diverging colormap, where zero still should be shaded in white.
Add the MidPointNormalize class, which allows one to define the midpoint of a colormap. Useful, e.g. if plotting data in the range [-6,3] with contourf and a diverging colormap, where zero still should be shaded in white.
Python
mit
ssalesky/Science-Library
493480f3a9d34e01d0a64442b29529d70a44a8ee
smugcli/stdout_interceptor.py
smugcli/stdout_interceptor.py
"""Context manager base class man-in-the-middling the global stdout.""" import sys class Error(Exception): """Base class for all exception of this module.""" class InvalidUsageError(Error): """Error raised on incorrect API uses.""" class StdoutInterceptor(): """Context manager base class man-in-the-middlin...
"""Context manager base class man-in-the-middling the global stdout.""" import sys class Error(Exception): """Base class for all exception of this module.""" class InvalidUsageError(Error): """Error raised on incorrect API uses.""" class StdoutInterceptor(): """Context manager base class man-in-the-middlin...
Fix invalid annotation. The type of `self` in base class should be left to be deduced to the child type.
Fix invalid annotation. The type of `self` in base class should be left to be deduced to the child type.
Python
mit
graveljp/smugcli
b207cd8005a0d3a56dc87cc1194458128f94a675
awacs/helpers/trust.py
awacs/helpers/trust.py
from awacs.aws import Statement, Principal, Allow, Policy from awacs import sts def get_default_assumerole_policy(region=''): """ Helper function for building the Default AssumeRole Policy Taken from here: https://github.com/boto/boto/blob/develop/boto/iam/connection.py#L29 Used to allow ec2 inst...
from awacs.aws import Statement, Principal, Allow, Policy from awacs import sts def make_simple_assume_statement(principal): return Statement( Principal=Principal('Service', [principal]), Effect=Allow, Action=[sts.AssumeRole]) def get_default_assumerole_policy(region=''): """ Helper ...
Simplify the code a little
Simplify the code a little
Python
bsd-2-clause
craigbruce/awacs,cloudtools/awacs
5923d751d9541758a67915db67ee799ba0d1cd6d
polling_stations/api/mixins.py
polling_stations/api/mixins.py
from rest_framework.decorators import list_route from rest_framework.response import Response class PollingEntityMixin(): def output(self, request): if not self.validate_request(): return Response( {'detail': 'council_id parameter must be specified'}, 400) queryset = ...
from rest_framework.decorators import list_route from rest_framework.pagination import LimitOffsetPagination from rest_framework.response import Response class LargeResultsSetPagination(LimitOffsetPagination): default_limit = 100 max_limit = 1000 class PollingEntityMixin(): pagination_class = LargeResu...
Use pagination on stations and districts endpoints with no filter
Use pagination on stations and districts endpoints with no filter If no filter is passed to /pollingstations or /pollingdistricts use pagination (when filtering, there is no pagination) This means: - HTML outputs stay responsive/useful - People can't tie up our server with a query that says 'give me boundaries for ...
Python
bsd-3-clause
chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,chris48s/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations,DemocracyClub/UK-Polling-Stations