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
b3d9696d02855ba7a3243b4dc10e931f22a587b8
changes/utils/locking.py
changes/utils/locking.py
from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): key = '{0}:{1}:{2}'.format( func.__module__, func.__name__, ...
from flask import current_app from functools import wraps from hashlib import md5 from changes.ext.redis import UnableToGetLock from changes.config import redis def lock(func): @wraps(func) def wrapped(**kwargs): key = '{0}:{1}:{2}'.format( func.__module__, func.__name__, ...
Raise exception when we fail to grab a redis lock.
Raise exception when we fail to grab a redis lock. Summary: I might be missing something but it seems odd that we don't raise an error when we fail to grab a lock and consequently not run the wrapped function. We wrap all our tracked tasks with this lock function so failing to grab the lock will appear as if the task ...
Python
apache-2.0
dropbox/changes,dropbox/changes,dropbox/changes,dropbox/changes
c7689244b6de2cc9a01568e7cdab543cf8790214
setup.py
setup.py
import os import subprocess from distutils.core import setup try: if os.path.exists(".git"): s = subprocess.Popen(["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = s.communicate()[0] GIT_REVISION = out.strip() else: GIT_REVISIO...
import os import subprocess from distutils.core import setup try: if os.path.exists(".git"): s = subprocess.Popen(["git", "rev-parse", "HEAD"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) out = s.communicate()[0] GIT_REVISION = out.strip() else: GIT_REVISIO...
Improve the version information string
ENH: Improve the version information string
Python
bsd-3-clause
sahg/SAHGutils
c31bf6447f7b373ecbcc79e161dc406907887344
commandcenter/app_test.py
commandcenter/app_test.py
from tornado.testing import AsyncHTTPTestCase from tornado.websocket import websocket_connect from . import app class TestMyApp(AsyncHTTPTestCase): def get_app(self): return app.get_app() def test_homepage(self): response = self.fetch('/') self.assertEqual(response.code, 200) ...
from tornado.testing import AsyncHTTPTestCase from tornado.websocket import websocket_connect from . import app class TestMyApp(AsyncHTTPTestCase): def get_app(self): return app.get_app() def test_homepage(self): response = self.fetch('/') self.assertEqual(response.code, 200) ...
Add another test to check that the "See new artists" page is basically rendered correctly
Add another test to check that the "See new artists" page is basically rendered correctly
Python
apache-2.0
chirpradio/command-center,chirpradio/command-center
bb951b655ca49b341fec3f6cb813f2b07c118696
app/utils.py
app/utils.py
from urllib.parse import urlparse, urljoin from flask import request def get_or_create(model, **kwargs): """ Returns an instance of model and whether or not it already existed in a tuple. """ instance = model.query.filter_by(**kwargs).first() if instance: return instance, False else: in...
from urllib.parse import urlparse, urljoin from flask import request def get_or_create(model, **kwargs): """ Returns an instance of model and whether or not it already existed in a tuple. """ instance = model.query.filter_by(**kwargs).first() if instance: return instance, False else: in...
Add utility function for getting the redirect target
Add utility function for getting the redirect target
Python
mit
Encrylize/MyDictionary,Encrylize/MyDictionary,Encrylize/MyDictionary
02faa67481e0902501e9e269c17351d9b8f05afa
tests/python/pipeline_util/test-export_.py
tests/python/pipeline_util/test-export_.py
#!/usr/bin/env python #ckwg +5 # Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to # KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, # Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. def log(msg): import sys sys.stderr.write("%s\n" % msg) def test_imp...
#!/usr/bin/env python #ckwg +5 # Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to # KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, # Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. def log(msg): import sys sys.stderr.write("%s\n" % msg) def test_imp...
Add a test for exporting to dot from python
Add a test for exporting to dot from python
Python
bsd-3-clause
mathstuf/sprokit,Kitware/sprokit,Kitware/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,linus-sherrill/sprokit,Kitware/sprokit,Kitware/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,mathstuf/sprokit,linus-sherrill/sprokit
499defc47f0647afda47be8a8a25d04095b07e1b
nn/slmc/accuracy.py
nn/slmc/accuracy.py
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert ...
import tensorflow as tf from ..util import static_shape, static_rank def accuracy(output_layer, true_label): assert static_rank(output_layer) == 2 #assert static_shape(output_layer)[0] == (batch size) #assert static_shape(output_layer)[1] == (number of classes) assert static_rank(true_label) == 1 #assert ...
Use to_float instead of cast
Use to_float instead of cast
Python
unlicense
raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten
edd4cfd5cf4102ab77e889c680306f25280e6165
lingcod/bookmarks/forms.py
lingcod/bookmarks/forms.py
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput(...
from lingcod.features.forms import FeatureForm from lingcod.bookmarks.models import Bookmark from django import forms class BookmarkForm(FeatureForm): name = forms.CharField(label='Bookmark Name') latitude = forms.FloatField(widget=forms.HiddenInput()) longitude = forms.FloatField(widget=forms.HiddenInput(...
Hide IP from input form
Hide IP from input form
Python
bsd-3-clause
Alwnikrotikz/marinemap,google-code-export/marinemap,google-code-export/marinemap,Alwnikrotikz/marinemap,Alwnikrotikz/marinemap,Alwnikrotikz/marinemap,google-code-export/marinemap,google-code-export/marinemap
51346025b638159c69fe2c8da85170784d065d60
test_passgen.py
test_passgen.py
#!/usr/bin/env python3 import argparse from passgen import make_parser, sanitize_input import unittest class PassGenTestCase(unittest.TestCase): def setUp(self): self.parse_args = make_parser().parse_args def test_duplicate_flags(self): for duplicate_flag in ['dd', 'll', 'uu', 'pp', 'ss']: ...
#!/usr/bin/env python3 import argparse from passgen import make_parser, sanitize_input import unittest class PassGenTestCase(unittest.TestCase): def setUp(self): self.parse_args = make_parser().parse_args def test_duplicate_flags(self): for duplicate_flag in ['dd', 'll', 'uu', 'pp', 'ss']: ...
Add unit test for valid blacklist
Add unit test for valid blacklist
Python
mit
Videonauth/passgen
6e8efdbb31c8713eeee0105ddafbd88d6286cfc9
ganttcharts/cli/send_summary_emails.py
ganttcharts/cli/send_summary_emails.py
import datetime import time from .. import emails from ..database import get_sql_connection from ..models import Account, Session as SqlSession __description__ = 'Send out summary emails.' def send_out_emails(): session = SqlSession() today = datetime.date.today() accounts = session.query(Account) \ ...
import datetime import time from .. import emails from ..database import get_sql_connection from ..models import Account, Session as SqlSession __description__ = 'Send out summary emails.' def send_out_emails(): session = SqlSession() today = datetime.date.today() accounts = session.query(Account) \ ...
Add check for no tasks
Add check for no tasks
Python
mit
thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts,thomasleese/gantt-charts
fbae1592e9a94a4b6faec0896abfc38acb06d5d2
top40.py
top40.py
import click import requests url = 'http://ben-major.co.uk/labs/top40/api/singles/' response = requests.get(url) print response.json()
#/usr/bin/env python # -*- coding: utf-8 -*- import click import requests url = 'http://ben-major.co.uk/labs/top40/api/singles/' @click.command() @click.option('--count', default=10, help='Number of songs to show. Maximum is 40') def get_charts(count): """Prints the top COUNT songs in the UK Top 40 char...
Implement basic printing of the singles chart
Implement basic printing of the singles chart
Python
mit
kevgathuku/top40,andela-kndungu/top40
d60b16912cc3aa5c0a4f231b63b564683b2b8f64
parameters/enums.py
parameters/enums.py
# -*- coding: utf-8 -*- # standard library import collections # django from django.utils.translation import ugettext_lazy as _ ParameterDefinition = collections.namedtuple( 'Parameter', [ 'name', 'default', 'kind', 'verbose_name', ] ) class ParameterDefinitionList(object...
# -*- coding: utf-8 -*- # standard library import collections # django from django.utils.translation import ugettext_lazy as _ ParameterDefinition = collections.namedtuple( 'Parameter', [ 'name', 'default', 'kind', 'verbose_name', ] ) class ParameterDefinitionList(object...
Rename parameter DEFAULT_PROTOCOL to DEFAULT_URL_PROTOCOL
Rename parameter DEFAULT_PROTOCOL to DEFAULT_URL_PROTOCOL
Python
mit
magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3,magnet-cl/django-project-template-py3
fcc2a190a50327a2349dfbb8e93d3157a6c1f1e8
src/sentry/utils/versioning.py
src/sentry/utils/versioning.py
from __future__ import absolute_import import warnings from collections import namedtuple from sentry.exceptions import InvalidConfiguration class Version(namedtuple('Version', 'major minor patch')): def __str__(self): return '.'.join(map(str, self)) def make_upgrade_message(service, modality, version...
from __future__ import absolute_import import warnings from collections import namedtuple from sentry.exceptions import InvalidConfiguration class Version(namedtuple('Version', 'major minor patch')): def __str__(self): return '.'.join(map(str, self)) def make_upgrade_message(service, modality, version...
Fix strange wording in version check docstring.
Fix strange wording in version check docstring.
Python
bsd-3-clause
zenefits/sentry,BuildingLink/sentry,ifduyue/sentry,beeftornado/sentry,beeftornado/sentry,jean/sentry,jean/sentry,ifduyue/sentry,JackDanger/sentry,nicholasserra/sentry,gencer/sentry,fotinakis/sentry,mvaled/sentry,mvaled/sentry,daevaorn/sentry,jean/sentry,ifduyue/sentry,JamesMura/sentry,alexm92/sentry,daevaorn/sentry,fot...
87a07437c2481f92286f01f988405b4f3cfc5d37
apps/accounts/models.py
apps/accounts/models.py
from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_length = 30) eclass_username = models.Cha...
from apps.teilar.models import Departments from django.contrib.auth.models import User from django.db import models class UserProfile(models.Model): user = models.ForeignKey(User, unique = True) dionysos_username = models.CharField(max_length = 15, unique = True) dionysos_password = models.CharField(max_le...
Make school field foreign key of Departments table
Make school field foreign key of Departments table
Python
agpl-3.0
LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr
85db39e36c99e800e1008605213d1c25108b035d
angr/paths.py
angr/paths.py
import logging l = logging.getLogger('angr.states') class PathGenerator(object): def __init__(self, project): self._project = project def blank_path(self, state=None, *args, **kwargs): ''' blank_point - Returns a start path, representing a clean start of symbolic execution. ''...
import logging l = logging.getLogger('angr.states') class PathGenerator(object): def __init__(self, project): self._project = project def blank_path(self, state=None, jumpkind='Ijk_Boring', *args, **kwargs): ''' blank_point - Returns a start path, representing a clean start of symboli...
Allow specifying jumpkind with creating a Path via PathGenerator.blank_path()
Allow specifying jumpkind with creating a Path via PathGenerator.blank_path()
Python
bsd-2-clause
angr/angr,GuardianRG/angr,iamahuman/angr,cureHsu/angr,tyb0807/angr,mingderwang/angr,fjferrer/angr,angr/angr,zhuyue1314/angr,axt/angr,cureHsu/angr,chubbymaggie/angr,schieb/angr,lowks/angr,fjferrer/angr,zhuyue1314/angr,schieb/angr,chubbymaggie/angr,GuardianRG/angr,axt/angr,mingderwang/angr,avain/angr,schieb/angr,angr/ang...
6ae83f01eacceb140435e72a216fa88bd97f2b0c
pyswarms/utils/console_utils.py
pyswarms/utils/console_utils.py
# -*- coding: utf-8 -*- """ console_utils.py: various tools for printing into console """ def cli_print(message, verbosity, threshold): """Helper function to print console output Parameters ---------- message : str the message to be printed into the console verbosity : int verbosi...
# -*- coding: utf-8 -*- """ console_utils.py: various tools for printing into console """ # Import from __future__ from __future__ import with_statement from __future__ import absolute_import from __future__ import print_function # Import modules import logging def cli_print(message, verbosity, threshold, logger): ...
Add support for logging module
Add support for logging module This package now prints using the logging module. It can still print onto the console, but an additional tag like INFO, DEBUG, etc. are now being used. Author: ljvmiranda921
Python
mit
ljvmiranda921/pyswarms,ljvmiranda921/pyswarms
5f30d91d35d090e28925613365d5d1f31f0259d2
daapserver/bonjour.py
daapserver/bonjour.py
import zeroconf import socket class Bonjour(object): """ """ def __init__(self): """ """ self.zeroconf = zeroconf.Zeroconf() self.servers = {} def publish(self, server): """ """ if server in self.servers: self.unpublish(server) ...
import zeroconf import socket class Bonjour(object): """ """ def __init__(self): """ """ self.zeroconf = zeroconf.Zeroconf() self.servers = {} def publish(self, server): """ """ if server in self.servers: self.unpublish(server) ...
Fix for broken zeroconf publishing.
Fix for broken zeroconf publishing.
Python
mit
ties/flask-daapserver,basilfx/flask-daapserver
eed21e06dbb61899e9c14352750258aa81cc5d3c
doc/en/example/nonpython/conftest.py
doc/en/example/nonpython/conftest.py
# content of conftest.py import pytest def pytest_collect_file(parent, path): if path.ext == ".yml" and path.basename.startswith("test"): return YamlFile(path, parent) class YamlFile(pytest.File): def collect(self): import yaml # we need a yaml parser, e.g. PyYAML raw = yaml.safe_load...
# content of conftest.py import pytest def pytest_collect_file(parent, path): if path.ext == ".yml" and path.basename.startswith("test"): return YamlFile(path, parent) class YamlFile(pytest.File): def collect(self): import yaml # we need a yaml parser, e.g. PyYAML raw = yaml.safe_load...
Sort yml items to get same results for regendoc runs
Sort yml items to get same results for regendoc runs
Python
mit
The-Compiler/pytest,pfctdayelise/pytest,malinoff/pytest,tomviner/pytest,hackebrot/pytest,rmfitzpatrick/pytest,nicoddemus/pytest,tomviner/pytest,RonnyPfannschmidt/pytest,skylarjhdownes/pytest,etataurov/pytest,hpk42/pytest,alfredodeza/pytest,nicoddemus/pytest,markshao/pytest,ddboline/pytest,hpk42/pytest,jaraco/pytest,The...
a3fce3124168cde5dec925c3346bab59f4e6d59c
blog/forms.py
blog/forms.py
from .models import BlogPost from django import forms class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost exclude = ('user',)
from .models import BlogPost, Comment from django.forms import ModelForm class BlogPostForm(ModelForm): class Meta: model = BlogPost exclude = ('user',) class CommentForm(ModelForm): class Meta: model = Comment exclude = ('post',)
Add the form for Comment
Add the form for Comment
Python
mit
andreagrandi/bloggato,andreagrandi/bloggato
296005cae2af44e7e14a7e7ee9a99a2deab8c924
pyvarnish/remote.py
pyvarnish/remote.py
# -*- coding: utf-8 -*- __author__ = 'John Moylan' import sys from paramiko import SSHClient, SSHConfig, AutoAddPolicy from pyvarnish.settings import SSH_CONFIG class Varnish_admin(): def __init__(self, server=''): self.server = server self.conf = self.config() def config(self): s...
# -*- coding: utf-8 -*- __author__ = 'John Moylan' import sys from paramiko import SSHClient, SSHConfig, AutoAddPolicy from pyvarnish.settings import SSH_CONFIG class Varnish_admin(): def __init__(self, server=''): self.server = server self.conf = { 'hostname': server, ...
Make the SSH configuration more resilient.
Make the SSH configuration more resilient. If you don't have certain values specified in your ~/.ssh/config, use the defaults instead of erroring out.
Python
bsd-3-clause
redsnapper8t8/pyvarnish
3a8ea034e43985d4358b9f3e54c9bfc59ee6e99b
djangocms_spa_vue_js/templatetags/router_tags.py
djangocms_spa_vue_js/templatetags/router_tags.py
import json from django import template from django.utils.safestring import mark_safe from ..menu_helpers import get_vue_js_router register = template.Library() @register.simple_tag(takes_context=True) def vue_js_router(context): if 'vue_js_router' in context: router = context['vue_js_router'] else...
import json from django import template from django.utils.safestring import mark_safe from ..menu_helpers import get_vue_js_router register = template.Library() @register.simple_tag(takes_context=True) def vue_js_router(context): if 'vue_js_router' in context: router = context['vue_js_router'] else...
Remove single quote escaping for router js
Remove single quote escaping for router js This used to be a html field which crippled the json when a single quote was present. In the current usage it's required to print this json in a script tag so this quote issue doesn't exist anymore
Python
mit
dreipol/djangocms-spa-vue-js
8514d379ac3a9d75722b3ccccd0a9da40d2c5819
__openerp__.py
__openerp__.py
# -*- coding: utf-8 -*- { 'name': "l10n_fr_ebics", 'summary': """Implementation of the EBICS banking protocol""", 'description': """ This module provides an interface to echanges files with banks. It's curently a beta version. This program is distributed in the hope that it will be useful, b...
# -*- coding: utf-8 -*- { 'name': "l10n_fr_ebics", 'summary': """Implementation of the EBICS banking protocol""", 'description': """ This module provides an interface to echanges files with banks. It's curently a beta version. This module isbased on the library ebicsPy. It maps Odoo with the eb...
Add EbicsPy Launchpad repository url
Add EbicsPy Launchpad repository url
Python
agpl-3.0
yuntux/l10n_fr_ebics
3e91ff11f93e491963f6e38965672a9694ea0786
optimize/__init__.py
optimize/__init__.py
from __future__ import absolute_import from .optimization import ParameterManager, minimize from .jacobian import FunctionWithApproxJacobian, FunctionWithApproxJacobianCentral
from __future__ import absolute_import from .optimization import ParameterManager, minimize from .jacobian import FunctionWithApproxJacobian, FunctionWithApproxJacobianCentral try: from .ipopt_wrapper import minimize_ipopt except: import logging logging.error("Could not import ipopt wrapper. Maybe ipopt i...
Make sure package works even if ipopt is not installed
Make sure package works even if ipopt is not installed Signed-off-by: Matthias Kümmerer <e388d34fd3c0456122779e95f262c0d70198a168@matthias-k.org>
Python
mit
matthias-k/optpy
e99855e31c30d0b554d24b14d98ae8b76e1fc0a0
create_tables.py
create_tables.py
from models.base_model import db from models.user_model import UserModel from models.waifu_model import WaifuModel from models.waifu_message_model import WaifuMessageModel def create_tables(): db.connect() db.create_tables(( UserModel, WaifuModel, WaifuMessageModel, ), True) db...
from models.base_model import db from models.user_model import UserModel from models.waifu_model import WaifuModel from models.waifu_message_model import WaifuMessageModel def create_tables(): db.connect() db.create_tables(( UserModel, WaifuModel, WaifuMessageModel, ), True) if __...
Fix close connection only when called as script.
Fix close connection only when called as script.
Python
cc0-1.0
sketchturnerr/WaifuSim-backend,sketchturnerr/WaifuSim-backend
95cb5fc25b3fb1470c4631b93fea11d6172240a4
MeetingMinutes.py
MeetingMinutes.py
import sublime, sublime_plugin import os import re from .mistune import markdown HTML_START = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' HTML_END = '</body></html>' class CreateMinuteCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region(0, self.view.size()) md_s...
import sublime, sublime_plugin import os import re from subprocess import call from .mistune import markdown HTML_START = '<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>' HTML_END = '</body></html>' class CreateMinuteCommand(sublime_plugin.TextCommand): def run(self, edit): region = sublime.Region...
Add save as pdf feature.
Add save as pdf feature.
Python
mit
Txarli/sublimetext-meeting-minutes,Txarli/sublimetext-meeting-minutes
085bc7787eac2d44fd4c19c8161709b20dc324be
finny/commands/generate_structure.py
finny/commands/generate_structure.py
import os from finny.command import Command class GenerateStructure(Command): def __init__(self, name, path): self.name = name self.path = path def run(self): os.mkdir(self.path, 0755) """ You need to create: .gitignore requirements.txt README.md manage.py {{ app_name...
import os from finny.command import Command BASE_FOLDER_TEMPLATES = [ ".gitignore", "requirements.txt", "README.md", "manage.py" ] CONFIG_INITIALIZERS_TEMPLATES = [ "app.py" ] CONFIG_RUNNERS_TEMPLATES = [ "default.py" ] CONFIG_TEMPLATES = [ "boot.py", "development.py.sample" "test.py.sample", "produc...
Copy template structure for the create command
Copy template structure for the create command
Python
mit
hurrycane/finny
4dcca124835655ddbcf34b9d661b63f43eadf4a6
cms/manage.py
cms/manage.py
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized t...
#!/usr/bin/env python from django.core.management import execute_manager import imp try: imp.find_module('settings') # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. " "It app...
Fix string layout for readability
Fix string layout for readability
Python
agpl-3.0
jamesblunt/edx-platform,hkawasaki/kawasaki-aio8-0,sameetb-cuelogic/edx-platform-test,zofuthan/edx-platform,mtlchun/edx,zerobatu/edx-platform,carsongee/edx-platform,devs1991/test_edx_docmode,dkarakats/edx-platform,franosincic/edx-platform,Lektorium-LLC/edx-platform,dkarakats/edx-platform,procangroup/edx-platform,gsehub/...
38ac22c8380e91777c22f7dcb9a5297e9737d522
pymatgen/io/cp2k/tests/test_outputs.py
pymatgen/io/cp2k/tests/test_outputs.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import unittest from pathlib import Path from pymatgen.util.testing import PymatgenTest from pymatgen.io.cp2k.outputs import Cp2kOutput MODULE_DIR = Path(__file__).resolve().parent class SetTest(PymatgenTes...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import unittest from pathlib import Path from pymatgen.util.testing import PymatgenTest from pymatgen.io.cp2k.outputs import Cp2kOutput TEST_FILES = Path(__file__).parent.parent.joinpath("test_files").resolve...
Switch output to to use TEST_FILES path
Switch output to to use TEST_FILES path
Python
mit
davidwaroquiers/pymatgen,davidwaroquiers/pymatgen,gmatteo/pymatgen,richardtran415/pymatgen,davidwaroquiers/pymatgen,gVallverdu/pymatgen,fraricci/pymatgen,davidwaroquiers/pymatgen,gmatteo/pymatgen,gVallverdu/pymatgen,fraricci/pymatgen,richardtran415/pymatgen,vorwerkc/pymatgen,gVallverdu/pymatgen,vorwerkc/pymatgen,fraric...
229b8161f690154620faffd700335920648e1a96
services/netflix.py
services/netflix.py
import foauth.providers class Netflix(foauth.providers.OAuth1): # General info about the provider provider_url = 'https://www.netflix.com/' docs_url = 'http://developer.netflix.com/docs' # URLs to interact with the API request_token_url = 'http://api.netflix.com/oauth/request_token' authorize...
import foauth.providers from oauthlib.oauth1.rfc5849 import SIGNATURE_TYPE_QUERY class Netflix(foauth.providers.OAuth1): # General info about the provider provider_url = 'https://www.netflix.com/' docs_url = 'http://developer.netflix.com/docs' # URLs to interact with the API request_token_url = '...
Fix token retrieval for Netflix
Fix token retrieval for Netflix
Python
bsd-3-clause
foauth/foauth.org,foauth/foauth.org,foauth/foauth.org
19de35d8124a67e459a69080156bd310bb3814ea
rate_delta_point.py
rate_delta_point.py
#!/usr/bin/env python3 from numpy import * from scipy import * from scipy.interpolate import interp1d from scipy.interpolate import pchip import sys import os import argparse import json a = flipud(loadtxt(sys.argv[1])); b = flipud(loadtxt(sys.argv[2])); for m in range(0,4): ya = a[:,3+m] yb = b[:,3+m] r...
#!/usr/bin/env python3 from numpy import * from scipy import * from scipy.interpolate import interp1d from scipy.interpolate import pchip import sys import os import argparse import json a = flipud(loadtxt(sys.argv[1])); b = flipud(loadtxt(sys.argv[2])); for m in range(0,11): try: ya = a[:,3+m] y...
Support all metrics for points.
Support all metrics for points.
Python
mit
tdaede/awcy,tdaede/awcy,tdaede/awcy,tdaede/awcy,tdaede/awcy,tdaede/awcy
0ce9a29f83bb9c87df04f49b5e927d7a6aa4c53c
pdfminer/pdfcolor.py
pdfminer/pdfcolor.py
from .psparser import LIT import six #Python 2+3 compatibility ## PDFColorSpace ## LITERAL_DEVICE_GRAY = LIT('DeviceGray') LITERAL_DEVICE_RGB = LIT('DeviceRGB') LITERAL_DEVICE_CMYK = LIT('DeviceCMYK') class PDFColorSpace(object): def __init__(self, name, ncomponents): self.name = name self.nc...
import collections from .psparser import LIT import six #Python 2+3 compatibility ## PDFColorSpace ## LITERAL_DEVICE_GRAY = LIT('DeviceGray') LITERAL_DEVICE_RGB = LIT('DeviceRGB') LITERAL_DEVICE_CMYK = LIT('DeviceCMYK') class PDFColorSpace(object): def __init__(self, name, ncomponents): self.name = na...
Fix colorspace determinism with OrderedDict
Fix colorspace determinism with OrderedDict
Python
mit
pdfminer/pdfminer.six,goulu/pdfminer
fc2085e3c86e1596f5dc9c032e445887430602b5
rotational-cipher/rotational_cipher.py
rotational-cipher/rotational_cipher.py
import string UPPER = string.ascii_uppercase LOWER = string.ascii_lowercase def rotate(s, n): return "".join(rot_gen(s,n)) def shift_rules(n): shifted = UPPER[n:] + UPPER[:n] + LOWER[n:] + LOWER[:n] return {k:v for k,v in zip(UPPER+LOWER, shifted)} def rot_gen(s, n): rules = shift_rules(n) f...
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)}
Use lambda function with method
Use lambda function with method
Python
agpl-3.0
CubicComet/exercism-python-solutions
8d18df92373c1fd4c2cfa2fb59f5f49a4f89b78f
djoauth2/conf.py
djoauth2/conf.py
# coding: utf-8 from django.config import settings from appconf import AppConf class DJOAuthConf(AppConf): class Meta: prefix = 'djoauth' ACCESS_TOKEN_LENGTH = 30 ACCESS_TOKEN_LIFETIME = 3600 ACCESS_TOKENS_REFRESHABLE = True AUTHORIZATION_CODE_LENGTH = 30 AUTHORIZATION_CODE_LIFETIME = 120 CLIENT_K...
# coding: utf-8 from django.config import settings from appconf import AppConf class DJOAuthConf(AppConf): class Meta: prefix = 'djoauth' ACCESS_TOKEN_LENGTH = 30 ACCESS_TOKEN_LIFETIME = 3600 ACCESS_TOKENS_REFRESHABLE = True AUTHORIZATION_CODE_LENGTH = 30 AUTHORIZATION_CODE_LIFETIME = 120 CLIENT_K...
Add option for determining requirement of 'state' parameter.
Add option for determining requirement of 'state' parameter.
Python
mit
vden/djoauth2-ng,Locu/djoauth2,seler/djoauth2,vden/djoauth2-ng,seler/djoauth2,Locu/djoauth2
1e91b4ad94dd4a986adce22350cec8bd24fa4865
test/test_connection.py
test/test_connection.py
# -*- coding: utf-8 -*- """ test/test_connection ~~~~~~~~~~~~~~~~~~~~~ Tests for the SPDYConnection object. """ import spdypy import spdypy.connection class TestSPDYConnection(object): def test_can_create_connection(self): conn = spdypy.SPDYConnection(None) assert conn class TestSPDYConnectionS...
# -*- coding: utf-8 -*- """ test/test_connection ~~~~~~~~~~~~~~~~~~~~~ Tests for the SPDYConnection object. """ import spdypy import spdypy.connection from .test_stream import MockConnection class TestSPDYConnection(object): def test_can_create_connection(self): conn = spdypy.SPDYConnection(None) ...
Test correctly incrementing stream IDs.
Test correctly incrementing stream IDs.
Python
mit
Lukasa/spdypy
deb5775d0c8adad078ce5d0976f7f6f49963ca2e
accounts/features/steps/logout.py
accounts/features/steps/logout.py
from behave import * # Unique to Scenario: User logs out @when('I click on the logout link') def impl(context): context.browser.find_link_by_text('Logout').first.click() @then('I am no longer authenticated') def impl(context): pass
from behave import * # Unique to Scenario: User logs out @when('I click on the logout link') def impl(context): context.browser.find_link_by_text('Logout').first.click() @then('I am no longer authenticated') def impl(context): #Try to visit my profile page context.browser.visit(context.server_url + 'acco...
Test that the user is logged out
Test that the user is logged out
Python
bsd-3-clause
f3r3nc/connect,nlhkabu/connect,nlhkabu/connect,f3r3nc/connect,f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect
dd50a2b3fb157eaa3add329d90de3641ef9ea1ec
flocker/docs/test/test_version_extensions.py
flocker/docs/test/test_version_extensions.py
from textwrap import dedent from twisted.python.filepath import FilePath from twisted.trial.unittest import SynchronousTestCase from flocker import __version__ as version from flocker.common.version import get_installable_version from flocker.testtools import run_process class VersionExtensionsTest(SynchronousTestC...
from textwrap import dedent from twisted.python.filepath import FilePath from twisted.trial.unittest import SynchronousTestCase from flocker import __version__ as version from flocker.common.version import get_installable_version from flocker.testtools import run_process class VersionExtensionsTest(SynchronousTestC...
Remove unneeded variable from test.
Remove unneeded variable from test.
Python
apache-2.0
w4ngyi/flocker,mbrukman/flocker,w4ngyi/flocker,w4ngyi/flocker,AndyHuu/flocker,hackday-profilers/flocker,hackday-profilers/flocker,wallnerryan/flocker-profiles,hackday-profilers/flocker,mbrukman/flocker,mbrukman/flocker,AndyHuu/flocker,AndyHuu/flocker,wallnerryan/flocker-profiles,wallnerryan/flocker-profiles
6b38ca9283b3b367aa19a2722f9f6eea22c6c90b
cms_chunks/models.py
cms_chunks/models.py
from django.db import models from cms.models.fields import PlaceholderField from managers import ChunkManager class Chunk(models.Model): tags = models.CharField(max_length=200) code = PlaceholderField('chunk_placeholder', related_name="chunks") priority = models.IntegerField() objects = ChunkManager(...
from django.db import models from cms.models.fields import PlaceholderField from managers import ChunkManager class Chunk(models.Model): tags = models.CharField(max_length=200) code = PlaceholderField('chunk_placeholder', related_name="chunks") priority = models.IntegerField() objects = ChunkManager(...
Add useful method to know if a chunk has a tag
Add useful method to know if a chunk has a tag
Python
mit
devartis/django-cms-chunks
971a180a5afab6ee53a9b15413341c649cda0a1c
dtags/config.py
dtags/config.py
import os import json from dtags.utils import halt, expand_path TAGS = os.path.expanduser('~/.dtags') def load_tags(): """Load the tags from disk.""" if not os.path.exists(TAGS): try: with open(TAGS, "w") as config_file: json.dump({}, config_file) except (IOError,...
import os import json from dtags.utils import halt, expand_path TAGS = os.path.expanduser('~/.dtags') def load_tags(): """Load the tags from disk.""" if not os.path.exists(TAGS): try: with open(TAGS, "w") as config_file: json.dump({}, config_file) except (IOError,...
Fix a bug in load_tags function
Fix a bug in load_tags function
Python
mit
joowani/dtags
9f95715cc7260d02d88781c208f6a6a167496015
aiohttp_json_api/jsonpointer/__init__.py
aiohttp_json_api/jsonpointer/__init__.py
""" Extended JSONPointer from python-json-pointer_ ============================================== .. _python-json-pointer: https://github.com/stefankoegl/python-json-pointer """ import typing from jsonpointer import JsonPointer as BaseJsonPointer class JSONPointer(BaseJsonPointer): def __init__(self, pointer):...
""" Extended JSONPointer from python-json-pointer_ ============================================== .. _python-json-pointer: https://github.com/stefankoegl/python-json-pointer """ import typing from jsonpointer import JsonPointer as BaseJsonPointer class JSONPointer(BaseJsonPointer): def __init__(self, pointer):...
Fix bug with JSONPointer if part passed via __truediv__ is integer
Fix bug with JSONPointer if part passed via __truediv__ is integer
Python
mit
vovanbo/aiohttp_json_api
fb61c3c64d2426e4e7a6e454cbf57b15e003ce66
etl/__init__.py
etl/__init__.py
from base import BaseCSV, get_local_handles, ingest_feeds, create_seasons from overview import (ClubIngest, CountryIngest, CompetitionIngest, PlayerIngest, PersonIngest) from financial import (AcquisitionIngest, PlayerSalaryIngest, PartialTenureIngest) from statistics import (FieldStatIngest, GoalkeeperStatIngest, Leag...
from base import BaseCSV, get_local_handles, ingest_feeds, create_seasons from overview import (ClubIngest, CountryIngest, CompetitionIngest, PlayerIngest, PersonIngest) from financial import (AcquisitionIngest, PlayerSalaryIngest, PartialTenureIngest) from statistics import (FieldStatIngest, GoalkeeperStatIngest, Leag...
Add list of entities and ETL classes for CSV files
Add list of entities and ETL classes for CSV files
Python
mit
soccermetrics/marcotti-mls
0da19042c74d2a85ef4652b36186a1ee6c4fc247
tilequeue/format/mvt.py
tilequeue/format/mvt.py
from mapbox_vector_tile.encoder import on_invalid_geometry_make_valid from mapbox_vector_tile import encode as mvt_encode def encode(fp, feature_layers, coord, bounds_merc): tile = mvt_encode(feature_layers, quantize_bounds=bounds_merc, on_invalid_geometry=on_invalid_geometry_make_valid) ...
from mapbox_vector_tile.encoder import on_invalid_geometry_make_valid from mapbox_vector_tile import encode as mvt_encode def encode(fp, feature_layers, coord, bounds_merc): tile = mvt_encode( feature_layers, quantize_bounds=bounds_merc, on_invalid_geometry=on_invalid_geometry_make_valid, ...
Use round_fn to specify built-in round function
Use round_fn to specify built-in round function
Python
mit
mapzen/tilequeue,tilezen/tilequeue
464bc1b511415459e99700b94101776d00b23796
indra/pre_assemble_for_db/pre_assemble_script.py
indra/pre_assemble_for_db/pre_assemble_script.py
import indra.tools.assemble_corpus as ac def process_statements(stmts): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False) return stmts
import indra.tools.assemble_corpus as ac from indra.db.util import get_statements, insert_pa_stmts def process_statements(stmts, num_procs=1): stmts = ac.map_grounding(stmts) stmts = ac.map_sequence(stmts) stmts = ac.run_preassembly(stmts, return_toplevel=False, poolsize=num...
Create function to handle full pipeline.
Create function to handle full pipeline.
Python
bsd-2-clause
bgyori/indra,johnbachman/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/indra,pvtodorov/indra,pvtodorov/indra
f54e7d2da0ba321bdd5900c9893f6fe76adad12f
telegramschoolbot/database.py
telegramschoolbot/database.py
""" Interact with your school website with telegram! Copyright (c) 2016-2017 Paolo Barbolini <paolo@paolo565.org> Released under the MIT license """ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import threading # Temporary logging """ import logging logging.basicConfi...
""" Interact with your school website with telegram! Copyright (c) 2016-2017 Paolo Barbolini <paolo@paolo565.org> Released under the MIT license """ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import threading # Temporary logging """ import logging logging.basicConfi...
Put the session factory in threadLocal, not the session
Put the session factory in threadLocal, not the session
Python
mit
paolobarbolini/TelegramSchoolBot
08522cc9c14dca4ea18cd96bf47a43e2f1285248
kai/controllers/tracs.py
kai/controllers/tracs.py
import logging from pylons import response, config, tmpl_context as c from pylons.controllers.util import abort # Monkey patch the lazywriter, since mercurial needs that on the stdout import paste.script.serve as serve serve.LazyWriter.closed = False # Conditionally import the trac components in case things trac isn...
import logging from pylons import response, config, tmpl_context as c from pylons.controllers.util import abort # Monkey patch the lazywriter, since mercurial needs that on the stdout import paste.script.serve as serve serve.LazyWriter.closed = False # Conditionally import the trac components in case things trac isn...
Add proper timezone data for trac
Add proper timezone data for trac
Python
bsd-3-clause
Pylons/kai,Pylons/kai
e11b3c344b52c84b5e86bdc381df2f359fe63dae
fparser/setup.py
fparser/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('fparser',parent_package,top_path) return config
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('fparser',parent_package,top_path) config.add_data_files('log.config') return config
Add log.config to data files to fix installed fparser.
Add log.config to data files to fix installed fparser.
Python
bsd-3-clause
dagss/f2py-g3,dagss/f2py-g3
9e41011a5f164732ffd33ba5ca5edc7813735aeb
bundle_data.py
bundle_data.py
#!/usr/bin/env python import pickle import os.path import glob import uuid import sys import os.path import numpy as np def main(): if len(sys.argv) != 4: print('Usage: bundle_data.py <input dir> <output dir> <samples per bundle>') exit(1) p = sys.argv[1] b = sys.argv[2] lim = int(sys...
#!/usr/bin/env python import pickle import os.path import glob import uuid import sys import os.path import numpy as np def pack(b, x, y): name = str(uuid.uuid4()) pack = os.path.join(b, name + '.npz') with open(pack, 'wb') as f: np.savez(f, images=np.stack(x), offsets=np.stack(y)) print('pa...
Fix saving when number of items is less than configured bundle size
Fix saving when number of items is less than configured bundle size
Python
apache-2.0
baudm/HomographyNet
1bf6211f2fd5aef99e529fdc0e714b1a36ace346
gallery/util.py
gallery/util.py
import os from addict import Dict from gallery.models import File def get_dir_file_contents(dir_id): print(File.query.filter(File.parent == dir_id).all()) return File.query.filter(File.parent == dir_id).all() def get_dir_tree_dict(): path = os.path.normpath("/gallery-data/root") file_tree = Dict() ...
import os from addict import Dict from gallery.models import File def get_dir_file_contents(dir_id): print(File.query.filter(File.parent == dir_id).all()) return File.query.filter(File.parent == dir_id).all() def get_dir_tree_dict(): path = os.path.normpath("/gallery-data/root") file_tree = Dict() ...
Add CR2 to allowed files
Add CR2 to allowed files
Python
mit
liam-middlebrook/gallery,liam-middlebrook/gallery,liam-middlebrook/gallery,liam-middlebrook/gallery
84fbe1eebc2c19b72ab4bba8017e1cb37818afc1
scripts/reactions.py
scripts/reactions.py
import argparse from lenrmc.nubase import System from lenrmc.terminal import TerminalView, StudiesTerminalView class App(object): def __init__(self, **kwargs): self.kwargs = kwargs if 'studies' == self.kwargs.get('view'): self.view_cls = StudiesTerminalView else: ...
import argparse from lenrmc.nubase import System from lenrmc.terminal import TerminalView, StudiesTerminalView class App(object): def __init__(self, **kwargs): self.kwargs = kwargs if 'studies' == self.kwargs.get('view') or kwargs.get('studies'): self.view_cls = StudiesTerminalView ...
Add --studies as an alias for --view studies.
Add --studies as an alias for --view studies.
Python
mit
emwalker/lenrmc
530297a29150736208cd30c018a427f9d7e2d2eb
swift3/__init__.py
swift3/__init__.py
# Copyright (c) 2012-2014 OpenStack Foundation. # # 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 agre...
# Copyright (c) 2012-2014 OpenStack Foundation. # # 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 agre...
Remove pbr dependency at run time
Remove pbr dependency at run time This change is based on the following commit in the Swift tree. 0717133 Make pbr a build-time only dependency Change-Id: I43956f531a9928ade296236b3b605e52dc2f86f3
Python
apache-2.0
swiftstack/swift3-stackforge,stackforge/swift3,stackforge/swift3,tumf/swift3,KoreaCloudObjectStorage/swift3,KoreaCloudObjectStorage/swift3,swiftstack/swift3-stackforge,tumf/swift3
f731cef20b07998dd5ec76e20af20cb9e60d9afb
UM/Operations/RemoveSceneNodeOperation.py
UM/Operations/RemoveSceneNodeOperation.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import Operation from UM.Scene.SceneNode import SceneNode ## An operation that removes an list of SceneNode from the scene. class RemoveSceneNodeOperation(Operation.Operation): def __init__(self, node): ...
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. from . import Operation from UM.Scene.SceneNode import SceneNode from UM.Scene.Selection import Selection ## An operation that removes an list of SceneNode from the scene. class RemoveSceneNodeOperation(Operation.Oper...
Remove the object from selection if it is selected
Remove the object from selection if it is selected This cleans up any leftovers due to the object being selected. Fixes #42
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
59055a9f8d6093e2fc82bb4f656200b71279da1c
tml/rules/contexts/genders.py
tml/rules/contexts/genders.py
from .gender import Gender from _ctypes import ArgumentError class Genders(object): @classmethod def match(cls, data): """ Check is data list of genders """ if type(data) is str: raise ArgumentError('String is not genders list', data) try: ret = [] ...
from .gender import Gender from _ctypes import ArgumentError class Genders(object): """ List of objects having gender """ @classmethod def match(cls, data): """ Check is data list of genders """ if type(data) is str: raise ArgumentError('String is not genders list', data) ...
Add comment to gender class
Add comment to gender class
Python
mit
translationexchange/tml-python,translationexchange/tml-python
d70014d317f7abc9dffe674aca5eaf77d20a002f
djangosaml2/urls.py
djangosaml2/urls.py
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # 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 # # ...
# Copyright (C) 2010-2012 Yaco Sistemas (http://www.yaco.es) # Copyright (C) 2009 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # 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 # # ...
Fix imports for Django 1.6 and above
Fix imports for Django 1.6 and above
Python
apache-2.0
bernii/djangosaml2,azavea/djangosaml2
c62b42eb528babebf96e56738031dcda97868e80
flowfairy/app.py
flowfairy/app.py
import tensorflow as tf import numpy as np import itertools as it import importlib from flowfairy.conf import settings from flowfairy.utils import take from flowfairy import data from flowfairy.feature import FeatureManager from flowfairy.core.queue import FlowQueue from flowfairy.core.stage import stage def load_ne...
import tensorflow as tf import numpy as np import itertools as it import importlib from flowfairy.conf import settings from flowfairy.utils import take from flowfairy import data from flowfairy.feature import FeatureManager from flowfairy.core.queue import FlowQueue from flowfairy.core.stage import stage def load_ne...
Set name_scope of entire network to the dataset it handles
Set name_scope of entire network to the dataset it handles
Python
mit
WhatDo/FlowFairy
9a64f7b08704f2f343564698d83dd73bb1f0d4b2
slackbot_settings.py
slackbot_settings.py
DEFAULT_REPLY = "Sorry, I did not understand you." ERRORS_TO = 'general' PLUGINS = [ 'plugins.witai' ]
DEFAULT_REPLY = "Sorry, I did not understand you." PLUGINS = [ 'plugins.witai' ]
Remove sending error to general channel
Remove sending error to general channel
Python
mit
sanjaybv/netbot
827644a143a0fae0a1fa34ce2c624b199d0c1b63
bisnode/models.py
bisnode/models.py
from django.db import models from .constants import COMPANY_RATING_REPORT, RATING_CHOICES from .bisnode import get_bisnode_company_report class BisnodeRatingReport(models.Model): organization_number = models.CharField(max_length=10) rating = models.CharField(max_length=3, choices=RATING_CHOICES, ...
from datetime import datetime, date from django.db import models from .constants import COMPANY_RATING_REPORT, RATING_CHOICES from .bisnode import get_bisnode_company_report def bisnode_date_to_date(bisnode_date): formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d") return formatted_datetime.date(...
Save dates from Bisnode correctly
Save dates from Bisnode correctly
Python
mit
FundedByMe/django-bisnode
a6c6175c6d15cd9d7fd711431a6741afa35e78fb
smartbot/storage.py
smartbot/storage.py
import yaml class _Storage: def __getitem__(self, key): pass def __setitem__(self, key, value): pass def __delitem__(self, key): pass class _DictionaryStorage(_Storage): def __init__(self): self.data = {} def __del__(self): self.commit() def commit...
import yaml class _Storage: def __getitem__(self, key): pass def __setitem__(self, key, value): pass def __delitem__(self, key): pass class _DictionaryStorage(_Storage): def __init__(self): self.data = {} def __del__(self): self.commit() def commit...
Update setdefault to ensure commit is called
Update setdefault to ensure commit is called
Python
mit
Cyanogenoid/smartbot,Muzer/smartbot,thomasleese/smartbot-old,tomleese/smartbot
617ac4a745afb07299c73977477f52911f3e6e4c
flask_skeleton_api/app.py
flask_skeleton_api/app.py
from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it ha...
from flask import Flask, g, request import uuid import requests app = Flask(__name__) app.config.from_pyfile("config.py") @app.before_request def before_request(): # Sets the transaction trace id into the global object if it has been provided in the HTTP header from the caller. # Generate a new one if it ha...
Add API version into response header
Add API version into response header
Python
mit
matthew-shaw/thing-api
bcf4c5e632ae3ee678ac10e93887b14c63d4eb4a
examples/plain_actor.py
examples/plain_actor.py
#!/usr/bin/env python3 import pykka class PlainActor(pykka.ThreadingActor): def __init__(self): super().__init__() self.stored_messages = [] def on_receive(self, message): if message.get('command') == 'get_messages': return self.stored_messages else: s...
#!/usr/bin/env python3 import pykka GetMessages = object() class PlainActor(pykka.ThreadingActor): def __init__(self): super().__init__() self.stored_messages = [] def on_receive(self, message): if message is GetMessages: return self.stored_messages else: ...
Use custom message instead of dict
examples: Use custom message instead of dict
Python
apache-2.0
jodal/pykka
3dda5003b3ce345a08369b15fc3447d2a4c7d1ad
examples/plotting_2d.py
examples/plotting_2d.py
from bluesky.examples import * from bluesky.standard_config import RE from matplotlib import pyplot as plt from xray_vision.backend.mpl.cross_section_2d import CrossSection import numpy as np import filestore.api as fsapi import time as ttime from filestore.handlers import NpyHandler fsapi.register_handler('npy', NpyH...
from bluesky.examples import * from bluesky.tests.utils import setup_test_run_engine from matplotlib import pyplot as plt from xray_vision.backend.mpl.cross_section_2d import CrossSection import numpy as np import filestore.api as fsapi import time as ttime from filestore.handlers import NpyHandler fsapi.register_hand...
Set up RunEngine with required metadata.
FIX: Set up RunEngine with required metadata.
Python
bsd-3-clause
ericdill/bluesky,sameera2004/bluesky,sameera2004/bluesky,klauer/bluesky,klauer/bluesky,dchabot/bluesky,ericdill/bluesky,dchabot/bluesky
c02dc4c0717d15f4f042c992b4b404056e0e0a14
braubuddy/tests/thermometer/test_dummy.py
braubuddy/tests/thermometer/test_dummy.py
""" Braubuddy Dummy thermometer unit tests """ import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import dummy from braubuddy.thermometer import DeviceError from braubuddy.thermometer import ReadError class TestDummy(unittest.TestCase): def test_within_bounds(self): """Du...
""" Braubuddy Dummy thermometer unit tests """ import unittest from mock import patch, call, MagicMock from braubuddy.thermometer import dummy class TestDummy(unittest.TestCase): def test_within_bounds(self): """Dummy thermometer returns values within bounds.""" lower_bound = 20 upper_b...
Remove unnecessary imports form dummy tests.
Remove unnecessary imports form dummy tests.
Python
bsd-3-clause
amorphic/braubuddy,amorphic/braubuddy,amorphic/braubuddy
e543a6e12f34dfdde4f55630fcd1514d7622e0ee
countBob.py
countBob.py
""" Q7- Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print Number of times bob occurs is: 2 """ def countBob( string ): count = 0 start = 0 while string.find( "bob" ) !...
""" Q7- Assume s is a string of lower case characters. Write a program that prints the number of times the string 'bob' occurs in s. For example, if s = 'azcbobobegghakl', then your program should print Number of times bob occurs is: 2 """ def countBob( string ): count = 0 start = 0 while string.find( "bob" ) ...
Add the answer of seventh question of Assignment 3
Add the answer of seventh question of Assignment 3
Python
mit
SuyashD95/python-assignments
09418ae8fa652a5f8d2d3b3058e4acc774cbcbe9
genes/nginx/main.py
genes/nginx/main.py
from genes.apt import commands as apt from genes.brew import commands as brew from genes.debian.traits import is_debian from genes.mac.traits import is_osx from genes.ubuntu.traits import is_ubuntu def main(): if is_ubuntu() or is_debian(): apt.update() apt.install('nginx') elif is_osx(): ...
from typing import Callable, Optional from genes.apt import commands as apt from genes.brew import commands as brew from genes.debian.traits import is_debian from genes.mac.traits import is_osx from genes.ubuntu.traits import is_ubuntu def main(config: Optional[Callable[[], None]]=None): # Install nginx if is...
Add config option for nginx
Add config option for nginx
Python
mit
hatchery/genepool,hatchery/Genepool2
aed4d20d4e101891d2dd1149a6c111f06036ec73
libnacl/utils.py
libnacl/utils.py
# -*- coding: utf-8 -*- # Import nacl libs import libnacl import libnacl.encode # Import python libs import datetime import binascii class BaseKey(object): ''' Include methods for key management convenience ''' def hex_sk(self): if hasattr(self, 'sk'): return libnacl.encode.hex_e...
# -*- coding: utf-8 -*- # Import nacl libs import libnacl import libnacl.encode # Import python libs import time import binascii class BaseKey(object): ''' Include methods for key management convenience ''' def hex_sk(self): if hasattr(self, 'sk'): return libnacl.encode.hex_encod...
Make the nonce more secure and faster to generate
Make the nonce more secure and faster to generate
Python
apache-2.0
cachedout/libnacl,saltstack/libnacl,mindw/libnacl,johnttan/libnacl,RaetProtocol/libnacl,coinkite/libnacl
73e50feae8fb6c06ace5f268e11c8df985e5eace
login/routers.py
login/routers.py
# List of apps that will use the users database USERS_DATABASE_APPS = ['auth','login','sessions'] class UserRouter(object): """ A router to control all database operations on models in the login application. """ def db_for_read(self, model, **hints): """ Attempts to read login model...
# List of apps that will use the users database USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites'] class UserRouter(object): """ A router to control all database operations on models in the login application. """ def db_for_read(self, model, **hints): """ A...
Add apps on list that will be used on the test databases
[login] Add apps on list that will be used on the test databases Added apps sites and contenttypes to the list. These apps were causing troubles on the test databases. Signed off by: Heitor Reis <marcheing@gmail.com> Signed off by: Filipe Vaz <vazfilipe92@gmail.com>
Python
agpl-3.0
SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova,SuperNovaPOLIUSP/supernova
6f5e4ff4f8e4002566a9ac18bcb22778be9409bd
electro/api.py
electro/api.py
# -*- coding: utf-8 -*- from electro.errors import ResourceDuplicatedDefinedError class API(object): def __init__(self, app=None, decorators=None, catch_all_404s=None): self.app = app self.endpoints = set() self.decorators = decorators or [] self.catch_all_404s = catch...
# -*- coding: utf-8 -*- from electro.errors import ResourceDuplicatedDefinedError class API(object): def __init__(self, app=None, decorators=None, catch_all_404s=None): self.app = app self.endpoints = set() self.decorators = decorators or [] self.catch_all_404s = catch...
Add endpoint for flask app.
Add endpoint for flask app.
Python
mit
soasme/electro
d0ae974d737ff173cd8af159f869be7d69db08cd
tests/functional/test_l10n.py
tests/functional/test_l10n.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import random import pytest from ..pages.home import HomePage @pytest.mark.nondestructive def test_change_language(b...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import random import pytest from ..pages.home import HomePage @pytest.mark.nondestructive def test_change_language(b...
Exclude redirected locales from homepage language selector functional tests
Exclude redirected locales from homepage language selector functional tests
Python
mpl-2.0
MichaelKohler/bedrock,glogiotatidis/bedrock,gerv/bedrock,pascalchevrel/bedrock,sylvestre/bedrock,gerv/bedrock,mkmelin/bedrock,sgarrity/bedrock,alexgibson/bedrock,gauthierm/bedrock,TheJJ100100/bedrock,CSCI-462-01-2017/bedrock,glogiotatidis/bedrock,gerv/bedrock,mkmelin/bedrock,mkmelin/bedrock,mermi/bedrock,analytics-pros...
6daa585138413b38e04cae940d973bb9e13aa387
registration/__init__.py
registration/__init__.py
VERSION = (0, 9, 0, 'beta', 1) def get_version(): from django.utils.version import get_version as django_get_version return django_get_version(VERSION) # pragma: no cover
VERSION = (1, 0, 0, 'final', 0) def get_version(): "Returns a PEP 386-compliant version number from VERSION." assert len(VERSION) == 5 assert VERSION[3] in ('alpha', 'beta', 'rc', 'final') # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases...
Fix version number reporting so we can be installed before Django.
Fix version number reporting so we can be installed before Django.
Python
bsd-3-clause
stillmatic/django-registration,matejkloska/django-registration,yorkedork/django-registration,wda-hb/test,alawnchen/django-registration,PSU-OIT-ARC/django-registration,memnonila/django-registration,kazitanvirahsan/django-registration,allo-/django-registration,PetrDlouhy/django-registration,Geffersonvivan/django-registra...
a2444bd563b2e8e5b774e2f229583532f4d454ed
myhdl/_compat.py
myhdl/_compat.py
import sys import types PY2 = sys.version_info[0] == 2 PYPY = hasattr(sys, 'pypy_translation_info') _identity = lambda x: x if not PY2: string_types = (str,) integer_types = (int,) long = int class_types = (type,) from io import StringIO import builtins def to_bytes(s): return s...
from __future__ import print_function from __future__ import division import sys import types from ast import PyCF_ONLY_AST PY2 = sys.version_info[0] == 2 PYPY = hasattr(sys, 'pypy_translation_info') _identity = lambda x: x if not PY2: string_types = (str,) integer_types = (int,) long = int class_typ...
Create a compatible ast.parse with PY3
Create a compatible ast.parse with PY3 Created a function compatible with both PY2 and PY3 equivalent to ast.parse.
Python
lgpl-2.1
jmgc/myhdl-numeric,jmgc/myhdl-numeric,jmgc/myhdl-numeric
c5e2b375cc722f717c2b159451b8ca1e45060e83
models.py
models.py
from django.db import models from django.conf import settings import urllib, urllib2 C2DM_URL = 'https://android.apis.google.com/c2dm/send' class C2DMProfile(models.Model): deviceId = models.CharField(max_length = 64) registrationId = models.CharField(max_length = 140) collapseKey = models.CharField(max_...
from django.db import models from django.conf import settings import urllib, urllib2 C2DM_URL = 'https://android.apis.google.com/c2dm/send' class C2DMProfile(models.Model): ''' Profile of a c2dm-enabled Android device device_id - Unique ID for the device. Simply used as a default method to specify a de...
Add documentation and utility functions
Add documentation and utility functions
Python
bsd-3-clause
scottferg/django-c2dm
d042f4ced40d8d03bd65edf798a29058f26e98c6
test/test_wsstat.py
test/test_wsstat.py
import hashlib from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection class Tests(object): def setup(self): self.client = WebsocketTestingClient('wss://testserver/', total_connections=1, max_connecting_sockets=1) def teardown(self): pass class TestConnectedWebsocketConn...
import hashlib from wsstat.main import WebsocketTestingClient, ConnectedWebsocketConnection class Tests(object): def setup(self): self.client = WebsocketTestingClient('wss://testserver/', total_connections=3, max_connecting_sockets=3) def test_coroutines(self): print(self.client) asse...
Add a test for running tasks
Add a test for running tasks
Python
mit
Fitblip/wsstat
c9f2ecea38711db75235aca2879f9a0b14762c9f
tests/test_spell.py
tests/test_spell.py
# -*- coding: utf-8 -*- import datetime import os import sys import unittest from pythainlp.spell import NorvigSpellChecker, correct, spell class TestSpellPackage(unittest.TestCase): def test_spell(self): self.assertEqual(spell(None), [""]) self.assertEqual(spell(""), [""]) result = sp...
# -*- coding: utf-8 -*- import datetime import os import sys import unittest from pythainlp.spell import NorvigSpellChecker, correct, spell class TestSpellPackage(unittest.TestCase): def test_spell(self): self.assertEqual(spell(None), [""]) self.assertEqual(spell(""), [""]) result = sp...
Add unittest for correct function in spell module
Add unittest for correct function in spell module
Python
apache-2.0
PyThaiNLP/pythainlp
f5d9fbf618f44e8572344e04e9a09c7cae3302bb
neurodsp/plts/__init__.py
neurodsp/plts/__init__.py
"""Plotting functions.""" from .time_series import plot_time_series, plot_bursts from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response from .rhythm import plot_swm_pattern, plot_lagged_coherence from .spectral import plot_power_spectra, plot_scv, plot_scv_rs_lines, plot_scv_rs_matrix...
"""Plotting functions.""" from .time_series import plot_time_series, plot_bursts, plot_instantaneous_measure from .filt import plot_filter_properties, plot_frequency_response, plot_impulse_response from .rhythm import plot_swm_pattern, plot_lagged_coherence from .spectral import plot_power_spectra, plot_scv, plot_scv_...
Make plot_instantaneous_measure accessible from root of plots
Make plot_instantaneous_measure accessible from root of plots
Python
apache-2.0
voytekresearch/neurodsp
372cb5cfb74e207c169bec473eeed48497748d51
nipype/utils/setup.py
nipype/utils/setup.py
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('utils', parent_package, top_path) config.add_data_dir('tests') return config if __name__ == '__main__': from numpy.distutils.core import setup ...
from os.path import join def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('utils', parent_package, top_path) config.add_data_dir('tests') try: # If the user has IPython installed, this will install the # nip...
Add install for nipype ipython profile.
Add install for nipype ipython profile. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@1352 ead46cd0-7350-4e37-8683-fc4c6f79bf00
Python
bsd-3-clause
wanderine/nipype,JohnGriffiths/nipype,iglpdc/nipype,blakedewey/nipype,Leoniela/nipype,FredLoney/nipype,arokem/nipype,Leoniela/nipype,mick-d/nipype,glatard/nipype,dmordom/nipype,pearsonlab/nipype,pearsonlab/nipype,rameshvs/nipype,pearsonlab/nipype,sgiavasis/nipype,grlee77/nipype,arokem/nipype,wanderine/nipype,iglpdc/nip...
259b212c68233ed56f9bc3123d85ea28f885af78
dijkstraNew.py
dijkstraNew.py
class DijkstraNew: def __init__(self,edges,start): self.edges = edges self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen self.start = start self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht self.visible_edges = [] # Sichtbare Kanten self.visibl...
class DijkstraNew: def __init__(self,edges,start): self.edges = edges self.take_shorter_edges() # Bei doppelten Kanten kürzere nehmen self.start = start self.edges_in_dijkstra = [] # Kanten, über die Dijkstra geht self.visible_edges = [] # Sichtbare Kanten self.visibl...
Delete long edges if there are multiple edges between the same two nodes
Delete long edges if there are multiple edges between the same two nodes
Python
apache-2.0
NWuensche/DijkstraInPython
b5871e451955e993ea368cb832714612a6dd48d1
fog-aws-testing/scripts/test_all.py
fog-aws-testing/scripts/test_all.py
#!/usr/bin/python from threading import Thread import subprocess from functions import * def runTest(branch,os): subprocess.call(test_script + " " + branch + " " + os, shell=True) for branch in branches: threads = [] for os in OSs: instance = get_instance("Name","fogtesting-" + os) sna...
#!/usr/bin/python from threading import Thread import subprocess from functions import * def runTest(branch,os): subprocess.call(test_script + " " + branch + " " + os, shell=True) from functions import * threads = [] for os in OSs: instance = get_instance("Name","fogtesting-" + os) snapshot = get_snapsho...
Use threading when restoring snapshots during testing
Use threading when restoring snapshots during testing
Python
mit
FOGProject/fog-community-scripts,FOGProject/fog-community-scripts,FOGProject/fog-community-scripts
30a81d64c513d23aae6dc6cc51fa047d6479150f
halo/_utils.py
halo/_utils.py
"""Utilities for Halo library. """ import platform import six import codecs from colorama import init, Fore from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean Whether operating sys...
"""Utilities for Halo library. """ import platform import six import codecs from colorama import init, Fore from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean Whether operating sys...
Remove support for windows till fully tested
Halo: Remove support for windows till fully tested
Python
mit
ManrajGrover/halo,manrajgrover/halo
a2f13a262e22187adaf9586aac951005f43c81b3
searchlight/opts.py
searchlight/opts.py
import itertools import searchlight.common.wsgi def list_opts(): return [ ('DEFAULT', itertools.chain(searchlight.common.wsgi.bind_opts, searchlight.common.wsgi.socket_opts, searchlight.common.wsgi.eventlet_opts)), ('profiler', i...
import itertools import searchlight.common.wsgi import searchlight.common.property_utils import searchlight.common.config def list_opts(): return [ ('DEFAULT', itertools.chain(searchlight.common.wsgi.bind_opts, searchlight.common.wsgi.socket_opts, ...
Add some common config options
Add some common config options
Python
apache-2.0
openstack/searchlight,openstack/searchlight,lakshmisampath/searchlight,openstack/searchlight
6e6aa02907b3d156174cfe1a5f8e9c274c080778
SegNetCMR/helpers.py
SegNetCMR/helpers.py
import tensorflow as tf def add_output_images(images, logits, labels): cast_labels = tf.cast(labels, tf.uint8) * 128 cast_labels = cast_labels[...,None] tf.summary.image('input_labels', cast_labels, max_outputs=3) classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1] output_image_gb = im...
import tensorflow as tf def add_output_images(images, logits, labels): cast_labels = tf.cast(labels, tf.uint8) * 128 cast_labels = cast_labels[...,None] tf.summary.image('input_labels', cast_labels, max_outputs=3) classification1 = tf.nn.softmax(logits = logits, dim=-1)[...,1] output_image_gb = im...
Add output with images mixed with binary version of output labels
Add output with images mixed with binary version of output labels
Python
mit
mshunshin/SegNetCMR,mshunshin/SegNetCMR
0751ee8ea1153ca1227fafcfbca1dc00fc148c4b
qual/calendar.py
qual/calendar.py
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
from datetime import date, timedelta class DateWithCalendar(object): def __init__(self, calendar_class, date): self.calendar = calendar_class self.date = date def convert_to(self, calendar): return calendar.from_date(self.date) def __eq__(self, other): return self.calendar...
Move from_date() into an abstract base class.
Move from_date() into an abstract base class.
Python
apache-2.0
jwg4/qual,jwg4/calexicon
43f4d3394e184f9984f10cbeec51ca561a8d548c
shellish/logging.py
shellish/logging.py
""" A logging handler that's tty aware. """ import logging from . import rendering class VTMLHandler(logging.StreamHandler): """ Parse VTML messages to colorize and embolden logs. """ log_format = '[<blue>%(asctime)s</blue>] [%(levelname)s] %(message)s' level_fmt = { 10: '<dim>%s</dim>', ...
""" A logging handler that's tty aware. """ import logging from . import rendering class VTMLHandler(logging.StreamHandler): """ Parse VTML messages to colorize and embolden logs. """ log_format = '[<blue>%(asctime)s</blue>] [<cyan>%(name)s</cyan>] ' \ '[%(levelname)s] %(message)s' level_fmt = {...
Add logger name to default log format.
Add logger name to default log format.
Python
mit
mayfield/shellish
71a182665e0e131f14bcefe52e8a8e7b2ffe674d
server/run.py
server/run.py
"""Run a server that takes all GET requests and dumps them.""" from flask import Flask, request, send_from_directory from flask_cors import CORS from w3lib.html import replace_entities app = Flask(__name__) CORS(app) @app.route('/') def route(): """Get all GET and POST requests and dump them to logs.""" # ...
"""Run a server that takes all GET requests and dumps them.""" from flask import Flask, request, send_from_directory from flask_cors import CORS from w3lib.html import replace_entities app = Flask(__name__) CORS(app) @app.route('/') def route(): """Get all GET and POST requests and dump them to logs.""" # ...
Add seperate key log handler
Add seperate key log handler
Python
apache-2.0
umisc/listenserv
bb195d3290d2e9921df8b989ac0d2123a6b9a7f8
server/run.py
server/run.py
"""Run a server that takes all GET requests and dumps them.""" from flask import Flask, request, send_from_directory from flask_cors import CORS from w3lib.html import replace_entities app = Flask(__name__) CORS(app) @app.route('/') def route(): """Get all GET and POST requests and dump them to logs.""" # ...
"""Run a server that takes all GET requests and dumps them.""" from json import loads from flask import Flask, request, send_from_directory from flask_cors import CORS from w3lib.html import replace_entities app = Flask(__name__) CORS(app) @app.route('/') def route(): """Get all GET and POST requests and dump...
Make it yet even easier to read key logger output
Make it yet even easier to read key logger output
Python
apache-2.0
umisc/listenserv
7d8c724abc4b5a692bd046313774921bc288f7a4
src/unittest/python/daemonize_tests.py
src/unittest/python/daemonize_tests.py
from __future__ import print_function, absolute_import, division from unittest2 import TestCase from mock import patch from succubus import Daemon class TestDaemonize(TestCase): @patch('succubus.daemonize.sys') def test_must_pop_sys_argv_before_loading_config(self, mock_sys): """The sys.argv.pop() ...
from __future__ import print_function, absolute_import, division from unittest2 import TestCase from mock import patch from succubus import Daemon class TestDaemonize(TestCase): @patch('succubus.daemonize.sys') def test_must_pop_sys_argv_before_loading_config(self, mock_sys): """The sys.argv.pop() ...
Test that set_(g|u)id actually changes the id
Test that set_(g|u)id actually changes the id
Python
apache-2.0
ImmobilienScout24/succubus
a894e53d48737f5b9ddc3cc2f5ffe4de98b558dd
forum/forms.py
forum/forms.py
from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( ...
from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( ...
Allow Markdown editor to be resized
Allow Markdown editor to be resized
Python
mit
Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/akwriters
53a442ac37bf58bca16dee2ad0787bdf2df98555
nltk/test/gluesemantics_malt_fixt.py
nltk/test/gluesemantics_malt_fixt.py
# -*- coding: utf-8 -*- from __future__ import absolute_import def setup_module(module): from nose import SkipTest from nltk.parse.malt import MaltParser try: depparser = MaltParser() except LookupError: raise SkipTest("MaltParser is not available")
# -*- coding: utf-8 -*- from __future__ import absolute_import def setup_module(module): from nose import SkipTest from nltk.parse.malt import MaltParser try: depparser = MaltParser('maltparser-1.7.2') except LookupError: raise SkipTest("MaltParser is not available")
Add the malt parser directory name in the unittest
Add the malt parser directory name in the unittest Fixes https://nltk.ci.cloudbees.com/job/nltk/TOXENV=py34-jenkins,jdk=jdk8latestOnlineInstall/lastCompletedBuild/testReport/%3Cnose/suite/ContextSuite_context_gluesemantics_malt_fixt__setup/
Python
apache-2.0
nltk/nltk,nltk/nltk,nltk/nltk
a1300dc059bd4eeb44654b75132c3e542caa29cc
staticgen_demo/blog/staticgen_views.py
staticgen_demo/blog/staticgen_views.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from staticgen.staticgen_pool import staticgen_pool from staticgen.staticgen_views import StaticgenView from .models import Post class BlogPostListView(StaticgenView): is_paginated = True i18n = True def items(self): return ('blog...
Add print statements to debug BlogPostListView
Add print statements to debug BlogPostListView
Python
bsd-3-clause
mishbahr/staticgen-demo,mishbahr/staticgen-demo,mishbahr/staticgen-demo
79f60cdb3853a60fd2cf6e69a141ed7b756f86cb
giphy_magic.py
giphy_magic.py
from IPython.display import Image import requests API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random' API_KEY = 'dc6zaTOxFJmzC' def giphy(tag): params = { 'api_key': API_KEY, 'tag': tag } r = requests.get(API_ENDPOINT, params=params) json = r.json() data = json['data'] retu...
from IPython.display import Image import requests API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random' # This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI API_KEY = 'dc6zaTOxFJmzC' def giphy(tag): params = { 'api_key': API_KEY, 'tag': tag } r = requests.get(...
Call out public beta key
Call out public beta key
Python
mit
AustinRochford/giphy-ipython-magic,AustinRochford/giphy-ipython-magic
aaaf8ef7433418f7a195c79674db56e03fc58f10
apps/bplan/models.py
apps/bplan/models.py
from django.db import models from adhocracy4.models.base import TimeStampedModel from adhocracy4.modules import models as module_models from apps.extprojects.models import ExternalProject class Bplan(ExternalProject): office_worker_email = models.EmailField() class AnonymousItem(TimeStampedModel): module =...
from django.contrib.auth.models import AnonymousUser from django.db import models from adhocracy4.models.base import TimeStampedModel from adhocracy4.modules import models as module_models from apps.extprojects.models import ExternalProject class Bplan(ExternalProject): office_worker_email = models.EmailField() ...
Add mockup creator property to AnonymousItems
Add mockup creator property to AnonymousItems
Python
agpl-3.0
liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin
d25167937a6e0f923d9c03cd94c227e96fdf12ba
pyalysis/analysers/raw.py
pyalysis/analysers/raw.py
# coding: utf-8 """ pyalysis.analysers.raw ~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2014 by Daniel Neuhäuser and Contributors :license: BSD, see LICENSE.rst for details """ import codecs from pyalysis.utils import detect_encoding from pyalysis.warnings import LineTooLong class LineAnalyser(object): ""...
# coding: utf-8 """ pyalysis.analysers.raw ~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2014 by Daniel Neuhäuser and Contributors :license: BSD, see LICENSE.rst for details """ import codecs from blinker import Signal from pyalysis.utils import detect_encoding from pyalysis.warnings import LineTooLong class ...
Switch to signal based dispatch in LineAnalyser
Switch to signal based dispatch in LineAnalyser
Python
bsd-3-clause
DasIch/pyalysis,DasIch/pyalysis
91162995c6425307cb586e663d4bf0241f68d588
alg_fibonacci.py
alg_fibonacci.py
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import absolute_import from __future__ import print_function from __future__ import division def fibonacci_recur(n): """Get nth number of Fibonacci series by recursion.""" if n <= 1...
"""Fibonacci series: 0, 1, 1, 2, 3, 5, 8,... - Fib(0) = 0 - Fib(1) = 1 - Fib(n) = Fib(n - 1) + Fib(n - 2) """ from __future__ import absolute_import from __future__ import print_function from __future__ import division def fibonacci_recur(n): """Get nth number of Fibonacci series by recursion.""" if n <= 1...
Complete fiboncci_dp() by dynamic programming
Complete fiboncci_dp() by dynamic programming
Python
bsd-2-clause
bowen0701/algorithms_data_structures
28a35d1434cb8dfdc9da130bd86518df4e8c6d4a
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"] ...
Improve formatting of resend action description
Improve formatting of resend action description
Python
bsd-3-clause
praekelt/hellomama-registration,praekelt/hellomama-registration
d55dfc5152f6ebeabe761b627a26a9f00cc4e37c
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/libs/templatetags/url_tags.py
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/libs/templatetags/url_tags.py
# encoding: utf-8 from django import template from django.http import QueryDict from classytags.core import Tag, Options from classytags.arguments import MultiKeywordArgument, MultiValueArgument from libs.utils import canonical_url register = template.Library() @register.filter('canonical') def _get_canonical_url...
# encoding: utf-8 from django import template from django.http import QueryDict from classytags.core import Tag, Options from classytags.arguments import MultiKeywordArgument, MultiValueArgument register = template.Library() class QueryParameters(Tag): name = 'query' options = Options( MultiKeyword...
Remove an old filter reference
Remove an old filter reference
Python
mit
dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp,dulaccc/cookiecutter-django-herokuapp
128a9a98879fdd52f1f3fb04355fc3094f3769ba
scipy/signal/setup.py
scipy/signal/setup.py
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('signal', parent_package, top_path) config.add_data_dir('tests') config.add_extension('sigtools', sources=['sigtoolsmodule.c',...
#!/usr/bin/env python def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('signal', parent_package, top_path) config.add_data_dir('tests') config.add_extension('sigtools', sources=['sigtoolsmodule.c',...
Add newsig.c as a dependency to sigtools module.
Add newsig.c as a dependency to sigtools module. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@5176 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
lesserwhirls/scipy-cwt,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn
64b4abde42b653e66444876dee0700afa64e6c6b
releasetasks/test/__init__.py
releasetasks/test/__init__.py
import os import yaml def read_file(path): with open(path) as f: return f.read() PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa") PVT_KEY = read_file(PVT_KEY_FILE) PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub")) OTHER_PUB_KEY = read_file(os.path.join(os.path.di...
import os import yaml def read_file(path): with open(path) as f: return f.read() PVT_KEY_FILE = os.path.join(os.path.dirname(__file__), "id_rsa") PVT_KEY = read_file(PVT_KEY_FILE) PUB_KEY = read_file(os.path.join(os.path.dirname(__file__), "id_rsa.pub")) OTHER_PUB_KEY = read_file(os.path.join(os.path.di...
Remove redundant keyword argument from create_test_args
Remove redundant keyword argument from create_test_args
Python
mpl-2.0
mozilla/releasetasks,bhearsum/releasetasks,rail/releasetasks
effbffd67d52561ca1ba09201782aafc6cfc52f7
blog/posts/models.py
blog/posts/models.py
from django.db import models # Create your models here.
from django.db import models class Author(models.Model): name = models.CharField(max_length=20) email = models.EmailField(max_length=254) def __unicode__(self): return self.name class Post(models.Model): body = models.TextField() title = models.CharField(max_length=50) author = models...
Set up the DB schema for posts.
Set up the DB schema for posts.
Python
mit
Lukasa/minimalog
8cfe4d9ef565502b247b7ac3b438b49f257c7012
enable/layout/ab_constrainable.py
enable/layout/ab_constrainable.py
#------------------------------------------------------------------------------ # Copyright (c) 2012, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ from abc import ABCMeta class ABConstrainable(object): """ An abstract base class for objec...
#------------------------------------------------------------------------------ # Copyright (c) 2012, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ from abc import ABCMeta class ABConstrainable(object): """ An abstract base class for objec...
Fix a small docstring bug.
Fix a small docstring bug.
Python
bsd-3-clause
tommy-u/enable,tommy-u/enable,tommy-u/enable,tommy-u/enable
62abb800b1b40cfbce120c0f3fb5169e32daaa60
accounts/management/__init__.py
accounts/management/__init__.py
from accounts import models, names def ensure_core_accounts_exists(sender, **kwargs): # We only create core accounts the first time syncdb is run if models.Account.objects.all().count() > 0: return # Create asset accounts assets = models.AccountType.add_root(name='Assets') assets.accounts...
from accounts import models, names def ensure_core_accounts_exists(sender, **kwargs): # We only create core accounts the first time syncdb is run if models.Account.objects.all().count() > 0: return # Create asset accounts assets = models.AccountType.add_root(name='Assets') assets.accounts...
Change code-account name triggered during creation
Change code-account name triggered during creation
Python
bsd-3-clause
Jannes123/django-oscar-accounts,amsys/django-account-balances,michaelkuty/django-oscar-accounts,michaelkuty/django-oscar-accounts,Mariana-Tek/django-oscar-accounts,machtfit/django-oscar-accounts,carver/django-account-balances,machtfit/django-oscar-accounts,amsys/django-account-balances,Mariana-Tek/django-oscar-accounts...
e6d4ca44f3f71468c40842c53e3963b425ac2527
mss/factory.py
mss/factory.py
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSMixin # noqa def mss(**kwargs): # type: (Any) -...
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSMixin # noqa def mss(**kwargs): # type: (Any) -...
Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)
MSS: Fix pylint: Import outside toplevel (%s) (import-outside-toplevel)
Python
mit
BoboTiG/python-mss
760a543cf13552ce951fee12c6e9a9d5d335a168
formation/output_specification.py
formation/output_specification.py
# -*- coding: utf-8 -*- import json from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH class OutputSpecification(object): def __init__( self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH, ref_specification_path=REF_SPECIFICATION_PATH ): self.attr...
# -*- coding: utf-8 -*- import json from . import ATTRIBUTE_SPECIFICATION_PATH, REF_SPECIFICATION_PATH class OutputSpecification(object): def __init__( self, attribute_specification_path=ATTRIBUTE_SPECIFICATION_PATH, ref_specification_path=REF_SPECIFICATION_PATH ): self.attr...
Handle resources with no outputs
Handle resources with no outputs
Python
apache-2.0
jamesroutley/formation
7a7afea2539048d172b1d5abfc4a4d9dff0827e7
runtests.py
runtests.py
#!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if not settings.configured: settings.configure( DATABASE_ENGINE = 'sqlite3', SITE_ID = 1, TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', ...
#!/usr/bin/env python import sys from os.path import dirname, abspath from django.conf import settings if len(sys.argv) > 1 and 'postgres' in sys.argv: sys.argv.remove('postgres') db_engine = 'postgresql_psycopg2' db_name = 'test_main' else: db_engine = 'sqlite3' db_name = '' if not settings.conf...
Allow running tests with postgres
Allow running tests with postgres
Python
mit
coleifer/django-relationships,maroux/django-relationships,coleifer/django-relationships,maroux/django-relationships
039d326907d88e24a48100b7f3cb0b8e0eb843d0
rocket_snake/__init__.py
rocket_snake/__init__.py
# -*- coding: utf-8 -*- __author__ = 'Hugo Berg' __email__ = 'hb11002@icloud.com' __version__ = '0.1.0' from rocket_snake.constants import *
# -*- coding: utf-8 -*- __author__ = 'Hugo Berg' __email__ = 'hb11002@icloud.com' __version__ = '0.1.0' from rocket_snake.client import RLS_Client from rocket_snake.constants import *
Add the RLS client import to init file
Add the RLS client import to init file Signed-off-by: drummersbrother <d12fd520b57756512907f841763cabff8eb36464@icloud.com>
Python
apache-2.0
Drummersbrother/rocket-snake