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 |
|---|---|---|---|---|---|---|---|---|---|
e3d8b836681a0cb4795d317c7a23defd6004c967 | pytest_run.py | pytest_run.py | # coding=utf-8
"""This is a script for running pytest from the command line.
This script exists so that the project directory gets added to sys.path, which
prevents us from accidentally testing the globally installed willie version.
pytest_run.py
Copyright 2013, Ari Koivula, <ari@koivu.la>
Licensed under the Eiffel F... | #!/usr/bin/env python
# coding=utf-8
"""This is a script for running pytest from the command line.
This script exists so that the project directory gets added to sys.path, which
prevents us from accidentally testing the globally installed willie version.
pytest_run.py
Copyright 2013, Ari Koivula, <ari@koivu.la>
Licen... | Add shebang to testing script | Add shebang to testing script
| Python | mit | Uname-a/knife_scraper,Uname-a/knife_scraper,Uname-a/knife_scraper |
d5a5e46b2fbc9284213aef3ec45f0605b002b7b1 | axes/management/commands/axes_reset.py | axes/management/commands/axes_reset.py | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
... | from django.core.management.base import BaseCommand
from axes.utils import reset
class Command(BaseCommand):
help = ("resets any lockouts or failed login records. If called with an "
"IP, resets only for that IP")
def add_arguments(self, parser):
parser.add_argument('ip', nargs='*')
... | Reset all attempts when ip not specified | Reset all attempts when ip not specified
When no ip address positional arguments are specified, reset all attempts, as with reset() and per documentation. | Python | mit | svenhertle/django-axes,django-pci/django-axes,jazzband/django-axes |
132932747a1f7da67413b9c0cf7916707c1e3d19 | src/python/services/CVMFSAppVersions.py | src/python/services/CVMFSAppVersions.py | """CVMFS Servcice."""
import os
import re
import cherrypy
import html
from natsort import natsorted
version_re = re.compile(r"^release-(\d{1,3}\.\d{1,3}\.\d{1,3})$")
@cherrypy.popargs('appid')
class CVMFSAppVersions(object):
"""
CVMFS App Version checking service.
CVMFS Service to get the list of versio... | """CVMFS Servcice."""
import os
import re
import cherrypy
import html
from natsort import natsorted
VERSION_RE = re.compile(r"^release-(\d{1,3}\.\d{1,3}\.\d{1,3})$")
@cherrypy.popargs('appid')
class CVMFSAppVersions(object):
"""
CVMFS App Version checking service.
CVMFS Service to get the list of versio... | Change the re const name to uppercase. | Change the re const name to uppercase.
| Python | mit | alexanderrichards/LZProduction,alexanderrichards/LZProduction,alexanderrichards/LZProduction,alexanderrichards/LZProduction |
b26047600202a9776c99323813cf17b0aa951dcd | app/routes.py | app/routes.py | from flask import jsonify
from . import app
import mapper
import utils
from predict import predictor
@app.route("/", methods=["GET"])
def index():
firebase_dump = mapper.get_dump_firebase()
response = firebase_dump.get_all()
response = response or {}
return jsonify(response)
@app.route("/build", met... | from flask import jsonify
from . import app
import mapper
import utils
from predict import predictor
@app.route("/", methods=["GET"])
def index():
return app.send_static_file("index.html")
@app.route("/build", methods=["POST"])
def build_model():
predictor.preprocess_airports()
if not predictor.model:
... | Return index.html in root and transform /status results | Return index.html in root and transform /status results
| Python | mit | MachineLearningProject/flight-delay-prediction,MachineLearningProject/flight-delay-prediction,MachineLearningProject/flight-delay-prediction |
600839e3c51d2091a6c434ac31ea11dc9ed2db85 | foialist/forms.py | foialist/forms.py | from django import forms
from foialist.models import *
class FileForm(forms.ModelForm):
class Meta:
model = File
exclude = ('entry', 'size')
class EntryForm(forms.ModelForm):
govt_entity = forms.CharField(label="Gov't. entity")
class Meta:
model = Entry
# exc... | from django import forms
from foialist.models import *
class FileForm(forms.ModelForm):
class Meta:
model = File
exclude = ('entry', 'size')
class EntryForm(forms.ModelForm):
govt_entity = forms.CharField(label="Gov't. entity")
class Meta:
model = Entry
fiel... | Correct mismatched field names in EntryForm. | Correct mismatched field names in EntryForm.
| Python | bsd-3-clause | a2civictech/a2docs-sources,a2civictech/a2docs-sources,a2civictech/a2docs-sources |
059230327fcebb35c881f8a6bc2ee12fed29d442 | mcp/config.py | mcp/config.py | #
# Copyright (c) 2005-2006 rPath, Inc.
#
# All rights reserved
#
import os
from conary import conarycfg
from conary.lib import cfgtypes
class MCPConfig(conarycfg.ConfigFile):
basePath = os.path.join(os.path.sep, 'srv', 'rbuilder', 'mcp')
logPath = os.path.join(basePath, 'logs')
queueHost = '127.0.0.1'
... | #
# Copyright (c) 2005-2006 rPath, Inc.
#
# All rights reserved
#
import os
from conary import conarycfg
from conary.lib import cfgtypes
class MCPConfig(conarycfg.ConfigFile):
basePath = os.path.join(os.path.sep, 'srv', 'rbuilder', 'mcp')
logPath = os.path.join(os.path.sep, 'var', 'log', 'rbuilder')
que... | Move default location for MCP logs into /var/log/rbuilder/ | Move default location for MCP logs into /var/log/rbuilder/
| Python | apache-2.0 | sassoftware/mcp,sassoftware/mcp |
520ad6a456cbd94e176bb54373669baf5e8cfbd9 | sprockets/mixins/correlation/__init__.py | sprockets/mixins/correlation/__init__.py | from .mixins import HandlerMixin
version_info = (1, 0, 2)
__version__ = '.'.join(str(v) for v in version_info[:3])
| try:
from .mixins import HandlerMixin
except ImportError as error:
class HandlerMixin(object):
def __init__(self, *args, **kwargs):
raise error
version_info = (1, 0, 2)
__version__ = '.'.join(str(v) for v in version_info[:3])
| Fix retrieving __version__ without Tornado installed. | Fix retrieving __version__ without Tornado installed.
| Python | bsd-3-clause | sprockets/sprockets.mixins.correlation |
99eafe1fb8ed3edce0d8d025b74ffdffa3bf8ae6 | fabfile.py | fabfile.py | import sys
import sh
from fabric import api as fab
sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'
def is_dirty():
return "" != sh.git.status(porcelain=True).strip()
def release(language, message):
if is_dirty():
sys.exit("Repo must be i... | import sys
import sh
from fabric import api as fab
sed = sh.sed.bake('-i bak -e')
TRAVIS_YAML = '.travis.yml'
REPLACE_LANGUAGE = 's/language: .*/language: {}/'
def is_dirty():
return "" != sh.git.status(porcelain=True).strip()
def release(language, message):
if is_dirty():
sys.exit("Repo must be i... | Print if nothing to update | Print if nothing to update
| Python | bsd-3-clause | datamicroscopes/release,jzf2101/release,jzf2101/release,datamicroscopes/release |
70f0be172801ee5fd205a90c78e2bf66f8e4ae07 | playserver/webserver.py | playserver/webserver.py | import flask
from . import track
app = flask.Flask(__name__)
@app.route("/")
def root():
song = track.getCurrentSong()
artist = track.getCurrentArtist()
album = track.getCurrentAlbum()
return "{} by {} - {}".format(song, artist, album)
| import flask
import json
from . import track
app = flask.Flask(__name__)
@app.route("/")
def root():
song = track.getCurrentSong()
artist = track.getCurrentArtist()
album = track.getCurrentAlbum()
return "{} by {} - {}".format(song, artist, album)
@app.route("/get_song_info")
def getSongInfo():
return json.dump... | Add basic routes for controls and song info | Add basic routes for controls and song info
| Python | mit | ollien/playserver,ollien/playserver,ollien/playserver |
76d60adabc44fd3bbd432ee2cdad011b542a2fee | nel/features/mapping.py | nel/features/mapping.py | import math
import numpy
class FeatureMapper(object):
def __init__(self, features):
self.features = features
def map(self, fv):
raise NotImplementedError
def __call__(self, doc):
for chain in doc.chains:
for c in chain.candidates:
c.fv = self.map(nu... | import math
import numpy
class FeatureMapper(object):
def __init__(self, features):
self.features = features
def map(self, fv):
raise NotImplementedError
def __call__(self, doc):
for chain in doc.chains:
for c in chain.candidates:
c.fv = self.map(nu... | Add feature vector size calculation method to mapper interface | Add feature vector size calculation method to mapper interface
| Python | mit | wikilinks/nel,wikilinks/nel |
141ad63b28eff5c7a034d479b98c83334ff1f0a3 | provokator/site/util.py | provokator/site/util.py | #!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
__all__ = ['internal_origin_only']
from urllib.parse import urlparse
from functools import wraps
from werkzeug.exceptions import Forbidden
import flask
import re
def internal_origin_only(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
h = urlparse('http:... | #!/usr/bin/python3 -tt
# -*- coding: utf-8 -*-
__all__ = ['internal_origin_only']
from urllib.parse import urlparse
from functools import wraps
from werkzeug.exceptions import Forbidden
import flask
import re
def internal_origin_only(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
host = flask.reques... | Change cross-origin check to work behind proxies | Change cross-origin check to work behind proxies
Signed-off-by: Jan Dvořák <86df5a4870880bf501c926309e3bcfbe57789f3f@anilinux.org>
| Python | mit | techlib/provokator,techlib/provokator |
5545bd1df34e6d3bb600b78b92d757ea12e3861b | printer/PlatformPhysicsOperation.py | printer/PlatformPhysicsOperation.py | from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation
## A specialised operation designed specifically to modify the previous operation.
class PlatformPhysicsOperation(Operation):
def __in... | from UM.Operations.Operation import Operation
from UM.Operations.AddSceneNodeOperation import AddSceneNodeOperation
from UM.Operations.TranslateOperation import TranslateOperation
from UM.Operations.GroupedOperation import GroupedOperation
## A specialised operation designed specifically to modify the previous operat... | Use GroupedOperation for merging PlatformPhyisicsOperation | Use GroupedOperation for merging PlatformPhyisicsOperation
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
f733300f622a4ffc1f0179c90590d543dc37113e | weber_utils/pagination.py | weber_utils/pagination.py | import functools
from flask import jsonify, request
from flask.ext.sqlalchemy import Pagination
from .request_utils import dictify_model, error_abort
def paginate_query(query, default_page_size=100, renderer=dictify_model):
try:
page_size = int(request.args.get("page_size", default_page_size))
pag... | import functools
from flask import jsonify, request
from flask.ext.sqlalchemy import Pagination
from .request_utils import dictify_model, error_abort
def paginate_query(query, default_page_size=100, renderer=dictify_model):
try:
page_size = int(request.args.get("page_size", default_page_size))
pag... | Allow renderer argument to paginated_view decorator | Allow renderer argument to paginated_view decorator
| Python | bsd-3-clause | vmalloc/weber-utils |
574b4d95a48f4df676ed5f23f0c83a9df2bc241d | pydux/log_middleware.py | pydux/log_middleware.py | """
logging middleware example
"""
def log_middleware(store):
"""log all actions to console as they are dispatched"""
def wrapper(next_):
def log_dispatch(action):
print('Dispatch Action:', action)
return next_(action)
return log_dispatch
return wrapper
| from __future__ import print_function
"""
logging middleware example
"""
def log_middleware(store):
"""log all actions to console as they are dispatched"""
def wrapper(next_):
def log_dispatch(action):
print('Dispatch Action:', action)
return next_(action)
return log_dis... | Use from __future__ import for print function | Use from __future__ import for print function | Python | mit | usrlocalben/pydux |
d80ee56ea6259265a534231a52146f9fd04c9689 | taskflow/engines/__init__.py | taskflow/engines/__init__.py | # -*- coding: utf-8 -*-
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# 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... | # -*- coding: utf-8 -*-
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
#
# 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... | Use oslo_utils eventletutils to warn about eventlet patching | Use oslo_utils eventletutils to warn about eventlet patching
Change-Id: I86ba0de51b5c5789efae187ebc1c46ae32ff8b8b
| Python | apache-2.0 | jimbobhickville/taskflow,openstack/taskflow,jimbobhickville/taskflow,openstack/taskflow,junneyang/taskflow,pombredanne/taskflow-1,junneyang/taskflow,pombredanne/taskflow-1 |
20ad5bf3b814b57035ed92358e7a8cad25e5a7ee | gcm/api.py | gcm/api.py | import urllib2
import json
def send_gcm_message(api_key, regs_id, data, collapse_key=None):
"""
Send a GCM message for one or more devices, using json data
api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in
Google Cloud Messaging for Android... | import requests
import json
def send_gcm_message(api_key, regs_id, data, collapse_key=None):
"""
Send a GCM message for one or more devices, using json data
api_key: The API_KEY from your console (https://code.google.com/apis/console, locate Key for Server Apps in
Google Cloud Messaging for Androi... | Use requests package instead of urllib2 | Use requests package instead of urllib2
| Python | bsd-2-clause | johnofkorea/django-gcm,johnofkorea/django-gcm,bogdal/django-gcm,bogdal/django-gcm |
dd9f5980ded9b10210ea524169ef769a6eff3993 | utils/paginate.py | utils/paginate.py | import discord
import asyncio
from typing import List, Tuple
from discord.ext.commands import Context
EMOJI_MAP = {"back": "⬅️", "forward": "➡️"}
async def paginate(ctx: Context, embeds: List[discord.Embed], timeout=30.0) -> None:
msg = ctx.message
emojis = EMOJI_MAP.values()
for reaction in emojis:
... | import discord
import asyncio
from typing import List
from discord.ext.commands import Context
EMOJI_MAP = {"back": "⬅️", "forward": "➡️"}
async def paginate(ctx: Context, embeds: List[discord.Embed], timeout=30.0) -> None:
msg = ctx.message
emojis = EMOJI_MAP.values()
for emoji in emojis:
await... | Fix pagination logic & typo | Fix pagination logic & typo
| Python | mit | Naught0/qtbot |
7fd7e2e8c9472a9dadf7d33991d11de6a68a2736 | refmanage/refmanage.py | refmanage/refmanage.py | # -*- coding: utf-8 -*-
import os
import argparse
import fs_utils
from pybtex.database.input import bibtex
def main():
"""
Command-line interface
"""
parser = argparse.ArgumentParser(description="Manage BibTeX files")
parser.add_argument("-t", "--test",
action="store_true",
help="... | # -*- coding: utf-8 -*-
import os
import argparse
import fs_utils
from pybtex.database.input import bibtex
def main():
"""
Command-line interface
"""
parser = argparse.ArgumentParser(description="Manage BibTeX files")
parser.add_argument("-t", "--test",
action="store_true",
help="... | Add functionality to print list of parseable files | Add functionality to print list of parseable files
| Python | mit | jrsmith3/refmanage |
22ab67a2c5a3bf3f7d1696a35b5fe029b848d63e | virtool/models.py | virtool/models.py | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String
Base = declarative_base()
class Label(Base):
__tablename__ = 'labels'
id = Column(String, primary_key=True)
name = Column(String, unique=True)
color = Column(String)
description = Column(String)
de... | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Sequence, Integer
Base = declarative_base()
class Label(Base):
__tablename__ = 'labels'
id = Column(Integer, Sequence('labels_id_seq'), primary_key=True)
name = Column(String, unique=True)
color = Column(S... | Use serial integer IDs for SQL records | Use serial integer IDs for SQL records
| Python | mit | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool |
64d599d6f7ca0aae6d95bf753a8421c7978276a2 | subliminal/__init__.py | subliminal/__init__.py | # -*- coding: utf-8 -*-
__title__ = 'subliminal'
__version__ = '1.0.dev0'
__author__ = 'Antoine Bertin'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, Antoine Bertin'
import logging
from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles,
list... | # -*- coding: utf-8 -*-
__title__ = 'subliminal'
__version__ = '1.0.dev0'
__author__ = 'Antoine Bertin'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015, Antoine Bertin'
import logging
from .api import (ProviderPool, check_video, provider_manager, download_best_subtitles, download_subtitles,
list... | Add compute_score to subliminal namespace | Add compute_score to subliminal namespace
| Python | mit | juanmhidalgo/subliminal,h3llrais3r/subliminal,getzze/subliminal,hpsbranco/subliminal,kbkailashbagaria/subliminal,oxan/subliminal,ratoaq2/subliminal,ofir123/subliminal,SickRage/subliminal,pums974/subliminal,Elettronik/subliminal,goll/subliminal,bogdal/subliminal,fernandog/subliminal,Diaoul/subliminal,neo1691/subliminal,... |
7f8a2e8e3b2721111c2de506d2d3bdea415e9b2d | markups/common.py | markups/common.py | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2015
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.environ.get('XDG_CONFIG_HOME') or
os.path.expanduser('~/.config'... | # This file is part of python-markups module
# License: BSD
# Copyright: (C) Dmitry Shachnev, 2012-2015
import os.path
# Some common constants and functions
(LANGUAGE_HOME_PAGE, MODULE_HOME_PAGE, SYNTAX_DOCUMENTATION) = range(3)
CONFIGURATION_DIR = (os.getenv('XDG_CONFIG_HOME') or os.getenv('APPDATA') or
os.path.exp... | Use %APPDATA% for CONFIGURATION_DIR on Windows | Use %APPDATA% for CONFIGURATION_DIR on Windows
References retext-project/retext#156.
| Python | bsd-3-clause | retext-project/pymarkups,mitya57/pymarkups |
90abb9f68ed32fd5affe8200dfd3bb4836f1c69e | test/os_win7.py | test/os_win7.py | #!/usr/bin/env python
"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited
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 ... | #!/usr/bin/env python
"""
mbed SDK
Copyright (c) 2011-2015 ARM Limited
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 ... | Revert "Add test for mbed parsing" | Revert "Add test for mbed parsing"
This reverts commit d37dc009f1c4f6e8855657dd6dbf17df9332f765.
| Python | apache-2.0 | mtmtech/mbed-ls,mtmtech/mbed-ls,mazimkhan/mbed-ls,jupe/mbed-ls,mazimkhan/mbed-ls,jupe/mbed-ls |
175c72d97d073a64714cebef05bd37f0221f94fa | test_octave_kernel.py | test_octave_kernel.py | """Example use of jupyter_kernel_test, with tests for IPython."""
import sys
import unittest
import jupyter_kernel_test as jkt
class OctaveKernelTests(jkt.KernelTests):
kernel_name = "octave"
language_name = "octave"
code_hello_world = "disp('hello, world')"
code_display_data = [
{'code': ... | """Example use of jupyter_kernel_test, with tests for IPython."""
import sys
import unittest
import jupyter_kernel_test as jkt
class OctaveKernelTests(jkt.KernelTests):
kernel_name = "octave"
language_name = "octave"
code_hello_world = "disp('hello, world')"
code_display_data = [
{'code': ... | Fix tests with Octave 5. | Fix tests with Octave 5.
| Python | bsd-3-clause | Calysto/octave_kernel,Calysto/octave_kernel |
826e5cffbfc7ac3e3b3a138f290f3fcc50e2a187 | scripts/insert_demo.py | scripts/insert_demo.py | """Insert the demo into the codemirror site."""
import os
import fileinput
import shutil
proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
code_mirror_path = os.path.join(
proselint_path,
"plugins",
"webeditor")
code_mirror_demo_path = os.path.join(code_mirror_path, "index.ht... | """Insert the demo into the codemirror site."""
import os
import fileinput
import shutil
proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
code_mirror_path = os.path.join(
proselint_path,
"plugins",
"webeditor")
code_mirror_demo_path = os.path.join(code_mirror_path, "index.ht... | Replace the placeholder in the live demo | Replace the placeholder in the live demo
| Python | bsd-3-clause | jstewmon/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint |
39eea826a1f29c2bd77d5f4f5bead7011b47f0bb | sed/engine/__init__.py | sed/engine/__init__.py | from sed.engine.StreamEditor import StreamEditor
from sed.engine.sed_file_util import call_main
from sed.engine.match_engine import ACCEPT, REJECT, NEXT, REPEAT, CUT
from sed.engine.sed_regex import ANY
__all__ = [
"StreamEditor",
"call_main",
"ACCEPT", "REJECT", "NEXT", "REPEAT",
"ANY",
]
| """
Interface to sed engine
- defines objects exported from this module
"""
from sed.engine.StreamEditor import StreamEditor
from sed.engine.sed_file_util import call_main
from sed.engine.match_engine import (
ACCEPT,
REJECT,
NEXT,
REPEAT,
CUT,
)
from sed.engine.sed_regex import ANY
__all__ = [
... | Add CUT to list of externally visible objects | Add CUT to list of externally visible objects
| Python | mit | hughdbrown/sed,hughdbrown/sed |
8b3a5bd9c28ba15e82215d4410b2952bcc81b917 | tests/conftest.py | tests/conftest.py | # -*- coding: utf-8 -*-
import pytest
@pytest.yield_fixture
def tmpfile(request, tmpdir):
yield tmpdir.join('file.tmp').ensure().strpath
| # -*- coding: utf-8 -*-
import pytest
from blox.file import File
@pytest.yield_fixture
def tmpfile(request, tmpdir):
filename = tmpdir.join('file.tmp').ensure().strpath
File(filename, 'w').close()
yield filename
| Create a valid blox file in tmpfile fixture | Create a valid blox file in tmpfile fixture
| Python | mit | aldanor/blox |
1e8f2c38cd83d23ad86ca898da9f6c7f7012da55 | tests/get_data.py | tests/get_data.py | #!/usr/bin/env python
#
# PyUSBtmc
# get_data.py
#
# Copyright (c) 2011 Mike Hadmack
# This code is distributed under the MIT license
import numpy
import sys
import os
from matplotlib import pyplot
sys.path.append(os.path.expanduser('~/Source'))
sys.path.append(os.path.expanduser('~/src'))
sys.path.append('/var/local/s... | #!/usr/bin/env python
#
# PyUSBtmc
# get_data.py
#
# Copyright (c) 2011 Mike Hadmack
# This code is distributed under the MIT license
import numpy
import sys
import os
from matplotlib import pyplot
sys.path.append(os.path.expanduser('.'))
from oscope import RigolScope
from oscope import Waverunner
from oscope import ma... | Adjust paths and module name | Adjust paths and module name
| Python | mit | niun/pyoscope,pklaus/pyoscope |
bf4717f39aaf3cf70bf99648afd38cd8dd5c8ad3 | src/main/python/systemml/__init__.py | src/main/python/systemml/__init__.py | # -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | # -------------------------------------------------------------
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you unde... | Allow access to classloaders methods | [MINOR] Allow access to classloaders methods
| Python | apache-2.0 | apache/incubator-systemml,niketanpansare/incubator-systemml,apache/incubator-systemml,apache/incubator-systemml,apache/incubator-systemml,niketanpansare/incubator-systemml,niketanpansare/systemml,niketanpansare/incubator-systemml,apache/incubator-systemml,niketanpansare/systemml,apache/incubator-systemml,niketanpansare... |
71251ba62843b4842055783941929884df38267d | tests/helper.py | tests/helper.py | import sublime
from unittest import TestCase
class TestHelper(TestCase):
def setUp(self):
self.view = sublime.active_window().new_file()
def tearDown(self):
if self.view:
self.view.set_scratch(True)
self.view.window().run_command('close_file')
def set_text(self, lines):
for line in line... | import sublime
from unittest import TestCase
class TestHelper(TestCase):
def setUp(self):
self.view = sublime.active_window().new_file()
self.view.settings().set("tab_size", 2)
def tearDown(self):
if self.view:
self.view.set_scratch(True)
self.view.window().run_command('close_file')
def... | Fix tests failing from different tab_size | Fix tests failing from different tab_size
| Python | mit | mwean/sublime_jump_along_indent |
89a001a1c4b5f8726c710c0dd4046ceb8df1fe5b | tests/test_fields_virtual.py | tests/test_fields_virtual.py | # -*- coding: utf-8 -*-
import pytest
import odin
class MultiPartResource(odin.Resource):
id = odin.IntegerField()
code = odin.StringField()
two_parts = odin.MultiPartField(('id', 'code'), separator=':')
class TestFields(object):
def test_multipartfield__get_value(self):
target = MultiPartRe... | # -*- coding: utf-8 -*-
import pytest
import odin
class MultiPartResource(odin.Resource):
id = odin.IntegerField()
code = odin.StringField()
two_parts = odin.MultiPartField(('id', 'code'), separator=':')
class TestFields(object):
def test_multipartfield__get_value(self):
target = MultiPartRe... | Fix test for python 3 | Fix test for python 3
| Python | bsd-3-clause | python-odin/odin |
74fde273d79248d4ad1c0cfd47d2861c83b50cbd | kolibri/auth/migrations/0007_auto_20171226_1125.py | kolibri/auth/migrations/0007_auto_20171226_1125.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-12-26 19:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kolibriauth', '0006_auto_20171206_1207'),
]
operations = [
migrations.Alter... | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-12-26 19:25
from __future__ import unicode_literals
from django.db import migrations, models
# This is necessary because:
# 1. The list generator has an unpredictable order, and when items swap places
# then this would be picked up as a change in Django ... | Fix for dynamic value of FacilityDataset.preset.choices causing migration inconsistencies | Fix for dynamic value of FacilityDataset.preset.choices causing migration inconsistencies
| Python | mit | christianmemije/kolibri,christianmemije/kolibri,indirectlylit/kolibri,benjaoming/kolibri,lyw07/kolibri,learningequality/kolibri,mrpau/kolibri,mrpau/kolibri,lyw07/kolibri,indirectlylit/kolibri,christianmemije/kolibri,jonboiser/kolibri,jonboiser/kolibri,DXCanas/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,benjaoming... |
a5ac21234cd8970112be12b1209886dd1208ad9c | troposphere/cloud9.py | troposphere/cloud9.py | # Copyright (c) 2012-2017, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, AWSProperty
from .validators import integer
class Repository(AWSProperty):
props = {
"PathComponent": (str, True),
"RepositoryUrl": (str, True),
}
clas... | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 35.0.0
from troposphere import Tags
from . import AWSObject, AWSProperty
from .validators import integer
class ... | Update Cloud9 per 2021-04-01 changes | Update Cloud9 per 2021-04-01 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
ca8349a897c233d72ea74128dabdd1311f00c13c | tests/unittest.py | tests/unittest.py | # -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# 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 la... | # -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# 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 la... | Allow a TestCase to set a 'loglevel' attribute, which overrides the logging level while that testcase runs | Allow a TestCase to set a 'loglevel' attribute, which overrides the logging level while that testcase runs
| Python | apache-2.0 | illicitonion/synapse,TribeMedia/synapse,howethomas/synapse,iot-factory/synapse,howethomas/synapse,TribeMedia/synapse,rzr/synapse,rzr/synapse,illicitonion/synapse,illicitonion/synapse,illicitonion/synapse,TribeMedia/synapse,TribeMedia/synapse,iot-factory/synapse,rzr/synapse,rzr/synapse,matrix-org/synapse,iot-factory/syn... |
ab84c37195feb7ea19be810a7d1a899e5e53ee78 | tests/test_pdfbuild.py | tests/test_pdfbuild.py | from latex import build_pdf
def test_generates_something():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
pdf = build_pdf(min_latex)
assert pdf
| from latex import build_pdf
from latex.exc import LatexBuildError
import pytest
def test_generates_something():
min_latex = r"""
\documentclass{article}
\begin{document}
Hello, world!
\end{document}
"""
pdf = build_pdf(min_latex)
assert pdf
def test_raises_correct_exception_on_fail():
broken_late... | Test whether or not the right exception is thrown. | Test whether or not the right exception is thrown.
| Python | bsd-3-clause | mbr/latex |
98c7f3afb2276012f22ad50e77fef60d7d71ee5f | qtpy/QtSvg.py | qtpy/QtSvg.py | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provi... | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © 2009- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provi... | Use star imports again instead of direct ones | QtSvG: Use star imports again instead of direct ones
| Python | mit | goanpeca/qtpy,davvid/qtpy,spyder-ide/qtpy,goanpeca/qtpy,davvid/qtpy |
4ebdd73bab19e83d52e03ac4afb7e1b3f78004f5 | drftutorial/catalog/views.py | drftutorial/catalog/views.py | from django.http import HttpResponse
from django.http import Http404
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from .permissions import IsAdminOrReadOnly
from .models import Product
from .serializers import... | from rest_framework import generics
from .permissions import IsAdminOrReadOnly
from .models import Product
from .serializers import ProductSerializer
class ProductList(generics.ListCreateAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
permission_classes = (IsAdminOrReadOnly... | Implement ProductDetail with a generic RetrieveUpdateDestroyAPIView class | Implement ProductDetail with a generic RetrieveUpdateDestroyAPIView class
| Python | mit | andreagrandi/drf-tutorial |
b3670094a44fc0fb07a91e1dc0ffb1a17001f855 | botcommands/vimtips.py | botcommands/vimtips.py | # coding: utf-8
import requests
from redis_wrap import get_hash
from rq.decorators import job
def vimtips(msg=None):
try:
existing_tips = get_hash('vimtips')
_len = len(existing_tips)
if _len > 0:
_index = randint(0, _len - 1)
_k = existing_tips.keys()[_index]
... | # coding: utf-8
from random import randint
import requests
from redis_wrap import get_hash, SYSTEMS
from rq.decorators import job
def vimtips(msg=None):
try:
existing_tips = get_hash('vimtips')
_len = len(existing_tips)
if _len > 0:
_index = randint(0, _len - 1)
_k ... | Fix import and use queue the right way | Fix import and use queue the right way
| Python | bsd-2-clause | JokerQyou/bot |
0ad0004d6460908d8b882d7da1086fc77e6c9635 | src/reversion/middleware.py | src/reversion/middleware.py | """Middleware used by Reversion."""
from __future__ import unicode_literals
from reversion.revisions import revision_context_manager
REVISION_MIDDLEWARE_FLAG = "reversion.revision_middleware_active"
class RevisionMiddleware(object):
"""Wraps the entire request in a revision."""
def process_reque... | """Middleware used by Reversion."""
from __future__ import unicode_literals
from reversion.revisions import revision_context_manager
REVISION_MIDDLEWARE_FLAG = "reversion.revision_middleware_active"
class RevisionMiddleware(object):
"""Wraps the entire request in a revision."""
def process_reque... | Fix bug handling exceptions in RevisionMiddleware | Fix bug handling exceptions in RevisionMiddleware
Recently the RevisionMiddleware was modified to avoid accessing
request.user unncessarily for caching purposes. This works well
except in some cases it can obscure errors generated elsewhere in a
project.
The RevisionContextManager has "active" and "inactive" states.... | Python | bsd-3-clause | ixc/django-reversion,etianen/django-reversion,etianen/django-reversion,adonm/django-reversion,MikeAmy/django-reversion,ixc/django-reversion,Beauhurst/django-reversion,MikeAmy/django-reversion,mkebri/django-reversion,adonm/django-reversion,blag/django-reversion,talpor/django-reversion,Govexec/django-reversion,mkebri/dja... |
bd4b122f72ad09245ba57acbd717e7e6d1126b88 | src/calc_perplexity.py | src/calc_perplexity.py | #! /usr/bin/python2
from __future__ import division
import numpy
# JAKE
def calc_perplexity(test_counts_dict, trigram_probs_dict):
'''
# Calculates perplexity of contents of file_string
# according to probabilities in trigram_probs_dict.
'''
test_probs = []
for trigram, count in test_count... | #! /usr/bin/python2
from __future__ import division
import numpy
# JAKE
def calc_perplexity(test_counts_dict, trigram_probs_dict):
'''
# Calculates perplexity of contents of file_string
# according to probabilities in trigram_probs_dict.
'''
test_probs = []
for trigram, count in test_count... | Use log2 instead of log10. | Use log2 instead of log10.
| Python | unlicense | jvasilakes/language_detector,jvasilakes/language_detector |
b98d7312019d041415d3d10d003267f03dddbf38 | eva/layers/residual_block.py | eva/layers/residual_block.py | from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from eva.layers.masked_convolution2d import MaskedConvolution2D
def ResidualBlock(model, filters):
# 2h -> h
block = PReLU()(model)
block = MaskedConvolution2D(filters//2, 1, 1)(block)
# h 3x3 -> h
b... | from keras.layers import Convolution2D, Merge
from keras.layers.advanced_activations import PReLU
from eva.layers.masked_convolution2d import MaskedConvolution2D
class ResidualBlock(object):
def __init__(self, filters):
self.filters = filters
def __call__(self, model):
# 2h -> h
block... | Rewrite residual block as class rather than method | Rewrite residual block as class rather than method
| Python | apache-2.0 | israelg99/eva |
f2ab04ec2eb870e661223fd397d7c5a23935a233 | src/apps/employees/schema/types.py | src/apps/employees/schema/types.py | import graphene
from graphene_django.types import DjangoObjectType, ObjectType
from graphene_django_extras import (
DjangoFilterPaginateListField, LimitOffsetGraphqlPagination
)
from apps.employees import models
class EmployeeType(DjangoObjectType):
class Meta:
model = models.Employee
filte... | import graphene
from graphene_django.types import DjangoObjectType, ObjectType
from graphene_django_extras import (
DjangoFilterPaginateListField, LimitOffsetGraphqlPagination
)
from apps.employees import models
class EmployeeType(DjangoObjectType):
class Meta:
model = models.Employee
filte... | Remove Node interfaces (use origin id for objects) | Remove Node interfaces (use origin id for objects)
| Python | mit | wis-software/office-manager |
866af848f8468966ea7d9a020d46e88d7d780b2d | pytac/cs.py | pytac/cs.py | """
Template module to define control systems.
"""
class ControlSystem(object):
""" Define a control system to be used with a device.
It uses channel access to comunicate over the network with
the hardware.
"""
def __init__(self):
raise NotImplementedError()
def get(self, pv):
... | """
Template module to define control systems.
"""
class ControlSystem(object):
""" Define a control system to be used with a device.
It uses channel access to comunicate over the network with
the hardware.
"""
def __init__(self):
raise NotImplementedError()
def get(self, pv):
... | Remove the null control system | Remove the null control system
| Python | apache-2.0 | willrogers/pytac,willrogers/pytac |
3977b36760afa2407c5e98926a6c3c1f926f5493 | x64/expand.py | x64/expand.py | import sys
def expand(filename):
for dir in ('.', '../common', '../anstests/'):
try:
f = open(dir + "/" + filename)
except IOError:
continue
for line in f:
line = line.replace('\r', '')
if line.strip().startswith('#bye'):
sys.e... | import sys
def expand(filename):
for dir in ('.', '../common', '../anstests/'):
try:
f = open(dir + "/" + filename)
except IOError:
continue
for line in f:
line = line.replace('\r', '')
if line.strip().startswith('#bye'):
sys.e... | Fix missing newlines with Python3 | Fix missing newlines with Python3
| Python | bsd-3-clause | jamesbowman/swapforth,zuloloxi/swapforth,jamesbowman/swapforth,zuloloxi/swapforth,zuloloxi/swapforth,zuloloxi/swapforth,RGD2/swapforth,jamesbowman/swapforth,RGD2/swapforth,jamesbowman/swapforth,RGD2/swapforth,RGD2/swapforth |
d8d9b16e7264a6b2936b4920ca97f4dd923f29a3 | crankycoin/services/queue.py | crankycoin/services/queue.py | import zmq
from crankycoin import config, logger
class Queue(object):
QUEUE_BIND_IN = config['user']['queue_bind_in']
QUEUE_BIND_OUT = config['user']['queue_bind_out']
QUEUE_PROCESSING_WORKERS = config['user']['queue_processing_workers']
@classmethod
def start_queue(cls):
try:
... | import sys
import zmq
from crankycoin import config, logger
WIN32 = 'win32' in sys.platform
class Queue(object):
QUEUE_BIND_IN = config['user']['queue_bind_in'] if not WIN32 else config['user']['win_queue_bind_in']
QUEUE_BIND_OUT = config['user']['queue_bind_out'] if not WIN32 else config['user']['win_queue_... | Fix `protocol not supported` on Windows | Fix `protocol not supported` on Windows | Python | mit | cranklin/crankycoin |
0b845f6beaec8f7ce8e4cd473ed50fe1202b5139 | seabird/qc.py | seabird/qc.py | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
from cotede.qc import ProfileQC
from . import fCNV
from .exceptions import CNVError
class fProfileQC(ProfileQC):
""" Apply ProfileQC from CoTeDe straight from a file.
"""
def __init__(self, inputfile, ... | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
from os.path import basename
from cotede.qc import ProfileQC
from . import fCNV
from .exceptions import CNVError
class fProfileQC(ProfileQC):
""" Apply ProfileQC from CoTeDe straight from a file.
"""
d... | Add filename in attrs if fails to load it. | Add filename in attrs if fails to load it.
Filename in attrs helps to debug.
| Python | bsd-3-clause | castelao/seabird |
e8cf948ec22312e61548f5cb96bea3669a64f33c | id/migrations/0012_delete_externaldatabase.py | id/migrations/0012_delete_externaldatabase.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
import django.db
class Migration(migrations.Migration):
dependencies = [
('id', '0011_auto_20150916_1546'),
]
database_operations = [
migrations.AlterModelTable('ExternalDatabase', 'databases_... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('id', '0011_auto_20150916_1546'),
]
database_operations = [
migrations.AlterModelTable('ExternalDatabase', 'databases_externaldatabase'... | Revoke earlier change: This migration has already been applied. | Revoke earlier change: This migration has already been applied.
| Python | mit | occrp/id-backend |
573055a80ef19f2b743ef3bfc08c40e8738c5bb1 | libtree/utils.py | libtree/utils.py | # Copyright (c) 2016 Fabian Kochem
import collections
from copy import deepcopy
def recursive_dict_merge(left, right, first_run=True):
"""
Merge ``right`` into ``left`` and return a new dictionary.
"""
if first_run is True:
left = deepcopy(left)
for key in right:
if key in left:... | # Copyright (c) 2016 Fabian Kochem
import collections
from copy import deepcopy
def recursive_dict_merge(left, right, create_copy=True):
"""
Merge ``right`` into ``left`` and return a new dictionary.
"""
if create_copy is True:
left = deepcopy(left)
for key in right:
if key in l... | Rename 'first_run' -> 'create_copy' in recursive_dict_merge() | Rename 'first_run' -> 'create_copy' in recursive_dict_merge()
| Python | mit | conceptsandtraining/libtree |
19733452008845419aea36e13d68494d931e44e6 | settings.py | settings.py | """settings.py - settings and configuration used over all modules :
Copyright (c) 2018 Heinrich Widmann (DKRZ)
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN N... | """settings.py - settings and configuration used over all modules :
Copyright (c) 2018 Heinrich Widmann (DKRZ)
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN N... | Set the right CKAN organization | Set the right CKAN organization
| Python | mit | EUDAT-Training/B2FIND-Training |
56ca0dce01ad76934ae850ea20ab25adbcc751d1 | conf_site/proposals/admin.py | conf_site/proposals/admin.py | from django.contrib import admin
from .models import Proposal, ProposalKeyword
@admin.register(ProposalKeyword)
class KeywordAdmin(admin.ModelAdmin):
list_display = ("name", "slug", "official",)
list_filter = ("official",)
@admin.register(Proposal)
class ProposalAdmin(admin.ModelAdmin):
exclude = (
... | from django.contrib import admin
from .models import Proposal, ProposalKeyword
@admin.register(ProposalKeyword)
class KeywordAdmin(admin.ModelAdmin):
list_display = ("name", "slug", "official",)
list_filter = ("official",)
@admin.register(Proposal)
class ProposalAdmin(admin.ModelAdmin):
exclude = (
... | Remove speaker email field from proposal listing. | Remove speaker email field from proposal listing.
Save space in admin proposal listing by removing the speaker email
field.
| Python | mit | pydata/conf_site,pydata/conf_site,pydata/conf_site |
f81ddc6297b1372cdba3a5161b4f30d0a42d2f58 | src/factor.py | src/factor.py | from collections import Counter
from functools import (
lru_cache,
reduce,
)
from itertools import combinations
from prime import Prime
@lru_cache(maxsize=None)
def get_prime_factors(n):
""" Returns the counts of each prime factor of n
"""
if n == 1:
return Counter()
divisor = 2
wh... | from collections import Counter
from functools import (
lru_cache,
reduce,
)
from itertools import combinations
from prime import Prime
@lru_cache(maxsize=None)
def get_prime_factors(n):
""" Returns the counts of each prime factor of n
"""
if n < 1:
raise ValueError
if n == 1:
... | Raise ValueError if n < 1 | Raise ValueError if n < 1
| Python | mit | mackorone/euler |
caf48c98f0cb176c2cd0302d1667d2272a192c91 | WebSphere/checkAppStatus.py | WebSphere/checkAppStatus.py | # Author: Christoph Stoettner
# E-Mail: christoph.stoettner@stoeps.de
# Blog: http://www.stoeps.de
# Check if applications are running
print "Getting application status of all installed applications..."
applications = AdminApp.list().splitlines();
for application in applications:
applName = AdminControl.complete... | # Author: Christoph Stoettner
# E-Mail: christoph.stoettner@stoeps.de
# Blog: http://www.stoeps.de
# Check if applications are running
print "Getting application status of all installed applications..."
applications = AdminApp.list().splitlines();
runningApps = []
stoppedApps = []
for application in applications:
... | Print running and stopped Applications | Print running and stopped Applications | Python | apache-2.0 | stoeps13/ibmcnxscripting,stoeps13/ibmcnxscripting,stoeps13/ibmcnxscripting |
2fec68d8cf1bf2726488730c369aad7b8b96b167 | openacademy/wizard/openacademy_wizard.py | openacademy/wizard/openacademy_wizard.py | # -*- coding: utf-8 -*-
from openerp import fields, models, api
"""
This module create model of Wizard
"""
class Wizard(models.TransientModel):
""""
This class create model of Wizard
"""
_name = 'openacademy.wizard'
def _default_sessions(self):
return self.env['openacademy.session'].brow... | # -*- coding: utf-8 -*-
"""
This module create model of Wizard
"""
from openerp import fields, models, api
class Wizard(models.TransientModel):
""""
This class create model of Wizard
"""
_name = 'openacademy.wizard'
def _default_sessions(self):
return self.env['openacademy.session'].bro... | Fix error String statement has no effect | [FIX] pylint: Fix error String statement has no effect
| Python | apache-2.0 | JesusZapata/openacademy |
f00cb6c748e2eda022a7f9f739b60b98a0308eb7 | github3/search/repository.py | github3/search/repository.py | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class RepositorySearchResult(GitHubCore):
def __init__(self, data, session=None):
result = data.copy()
#: Score of the result
self.score = result.pop('score')
#: Text matches
... | # -*- coding: utf-8 -*-
from github3.models import GitHubCore
from github3.repos import Repository
class RepositorySearchResult(GitHubCore):
def __init__(self, data, session=None):
result = data.copy()
#: Score of the result
self.score = result.pop('score')
#: Text matches
... | Add a __repr__ for RepositorySearchResult | Add a __repr__ for RepositorySearchResult
| Python | bsd-3-clause | ueg1990/github3.py,icio/github3.py,christophelec/github3.py,jim-minter/github3.py,agamdua/github3.py,krxsky/github3.py,itsmemattchung/github3.py,sigmavirus24/github3.py,h4ck3rm1k3/github3.py,balloob/github3.py,wbrefvem/github3.py,degustaf/github3.py |
e66bd19fc4baae27f40b1b63bdc0a3280d8d25e9 | src/heap.py | src/heap.py | # -*- coding: utf-8 -*-
class Heap(object):
"""Implements a heap data structure in Python.
The underlying data structure used to hold the data is an array.
"""
__heap = []
def __init__(self, initial=[]):
"""Creates a new heap.
Args:
initial: (Optional): A continguous array containing the d... | # -*- coding: utf-8 -*-
class Heap(object):
"""Implements a heap data structure in Python.
The underlying data structure used to hold the data is an array.
"""
__heap = []
def __init__(self, initial=None):
"""Creates a new heap.
Args:
initial: (Optional): A continguous array containing the... | Fix massive bug in initialization | Fix massive bug in initialization
| Python | mit | DasAllFolks/PyAlgo |
54d5db67523deea7e34f784df667ffb705f3bb16 | TWLight/resources/admin.py | TWLight/resources/admin.py | from django.contrib import admin
from .models import Partner, Stream, Contact, Language
class LanguageAdmin(admin.ModelAdmin):
search_fields = ('language',)
list_display = ('language',)
admin.site.register(Language, LanguageAdmin)
class PartnerAdmin(admin.ModelAdmin):
search_fields = ('company_name',)... | from django import forms
from django.contrib import admin
from TWLight.users.groups import get_coordinators
from .models import Partner, Stream, Contact, Language
class LanguageAdmin(admin.ModelAdmin):
search_fields = ('language',)
list_display = ('language',)
admin.site.register(Language, LanguageAdmin)
... | Improve usability of coordinator designation interaction | Improve usability of coordinator designation interaction
I'm limiting the dropdown to actual coordinators so that admins don't
have to scroll through a giant list. I don't want to enforce/validate
this on the database level, though, as people may proceed through the
coordinator designation process in different orders,... | Python | mit | WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight |
35b965a645955bbb757f4e6854edc7744a42e3bc | tests/test_settings.py | tests/test_settings.py | SECRET_KEY = 'dog'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'asgiref.inmemory.ChannelLayer',
'ROUTING': [],
},
}
MIDDLEWARE_CLASSES = []
INSTALLED_APPS = ('tests', )
| SECRET_KEY = 'dog'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'asgiref.inmemory.ChannelLayer',
'ROUTING': [],
},
}
MIDDLEWARE_CLASSES = []
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.... | Add contrib.auth to test settings | Add contrib.auth to test settings
| Python | mit | linuxlewis/channels-api,linuxlewis/channels-api |
0471c689bbe4e5b1116c25a6ccea58588c09d4d7 | jasmin_notifications/urls.py | jasmin_notifications/urls.py | """
URL configuration for the JASMIN notifications app.
"""
__author__ = "Matt Pryor"
__copyright__ = "Copyright 2015 UK Science and Technology Facilities Council"
from django.conf.urls import url, include
from . import views
app_name = 'jasmin_notifications'
urlpatterns = [
url(r'^(?P<uuid>[a-zA-Z0-9-]+)/$', v... | """
URL configuration for the JASMIN notifications app.
"""
__author__ = "Matt Pryor"
__copyright__ = "Copyright 2015 UK Science and Technology Facilities Council"
from django.conf.urls import url, include
from . import views
app_name = 'jasmin_notifications'
urlpatterns = [
url(
r'^(?P<uuid>[0-9a-f]{8}... | Update regex to match only UUIDs | Update regex to match only UUIDs
| Python | mit | cedadev/jasmin-notifications,cedadev/jasmin-notifications |
2e3119b5f45a65f585e34b1239764d73b41c65fd | misp_modules/modules/expansion/__init__.py | misp_modules/modules/expansion/__init__.py | from . import _vmray
__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl', 'countrycode', 'cve', 'dns',
'eupi', 'ipasn', 'passivetotal', 'sourcecache', 'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
| from . import _vmray
__all__ = ['vmray_submit', 'asn_history', 'circl_passivedns', 'circl_passivessl',
'countrycode', 'cve', 'dns', 'domaintools', 'eupi', 'ipasn', 'passivetotal', 'sourcecache',
'virustotal', 'whois', 'shodan', 'reversedns', 'wiki']
| Add domaintools to the import list | Add domaintools to the import list
| Python | agpl-3.0 | Rafiot/misp-modules,MISP/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,Rafiot/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,VirusTotal/misp-modules,MISP/misp-modules,amuehlem/misp-modules,VirusTotal/misp-modules,MISP/misp-modules |
a4a8e3a8ed6753c5d4a51c90c5f68f76e7372f2a | selvbetjening/sadmin2/tests/ui/common.py | selvbetjening/sadmin2/tests/ui/common.py |
from splinter import Browser
import urlparse
from django.core.urlresolvers import reverse
from django.test import LiveServerTestCase
class UITestCase(LiveServerTestCase):
@classmethod
def setUpClass(cls):
cls.wd = Browser()
super(UITestCase, cls).setUpClass()
@classmethod
def tearD... | from selenium.common.exceptions import WebDriverException
from splinter import Browser
import urlparse
from django.core.urlresolvers import reverse
from django.test import LiveServerTestCase
class UITestCase(LiveServerTestCase):
@classmethod
def setUpClass(cls):
try:
cls.wd = Browser('ph... | Switch to headless UI testing by default | Switch to headless UI testing by default
| Python | mit | animekita/selvbetjening,animekita/selvbetjening,animekita/selvbetjening,animekita/selvbetjening |
de66fe28d2bd3e118a468257601d2bdfcc4341ed | niche_vlaanderen/__init__.py | niche_vlaanderen/__init__.py | from .acidity import Acidity # noqa
from .niche import Niche, NicheDelta # noqa
from .nutrient_level import NutrientLevel # noqa
from .vegetation import Vegetation # noqa
from .version import __version__ # noqa
| from .acidity import Acidity # noqa
from .niche import Niche, NicheDelta # noqa
from .nutrient_level import NutrientLevel # noqa
from .vegetation import Vegetation # noqa
from .version import __version__ # noqa
from .floodplain import FloodPlain | Add FloodPlain class to module namespace | Add FloodPlain class to module namespace
| Python | mit | johanvdw/niche_vlaanderen |
b1c67321e5eec29b9fd91d728bd8e63382dc063a | src/keybar/conf/test.py | src/keybar/conf/test.py | from keybar.conf.base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keybar_test',
}
}
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermed... | from keybar.conf.base import *
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'keybar_test',
}
}
certificates_dir = os.path.join(BASE_DIR, 'tests', 'resources', 'certificates')
KEYBAR_SERVER_CERTIFICATE = os.path.join(certificates_dir, 'KEYBAR-intermed... | Remove duplicate keybar host value | Remove duplicate keybar host value
| Python | bsd-3-clause | keybar/keybar |
7f0ab3d1db2257a630df44ad92b4f094f6a61894 | application.py | application.py | import os
import sentry_sdk
from flask import Flask
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.redis import RedisIntegration
from sentry_sdk.integrations import logging
from app import create_app
sentry_sdk.init(
dsn=os.environ['SENTRY_DSN'],
integrations=[FlaskIn... | import os
import sentry_sdk
from flask import Flask
from sentry_sdk.integrations.flask import FlaskIntegration
from sentry_sdk.integrations.redis import RedisIntegration
from sentry_sdk.integrations import logging
from app import create_app
if 'SENTRY_DSN' in os.environ:
sentry_sdk.init(
dsn=os.environ['... | Tweak Sentry config to work in development | Tweak Sentry config to work in development
This makes a couple of changes:
- Most importantly, it wraps the setup code in a conditional so that
developers don't need to have a DSN set to start the app locally.
- Secondly, it removes the redundant call to "set_level". Originally
I thought the integration was sending ... | Python | mit | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin |
d945090bda715d1d3b8c610f4017542eed06e73e | src/runtime/pcode_io.py | src/runtime/pcode_io.py | # pcode_io.py 19/01/2016 D.J.Whale
# simplest possible implementation. Only really works well
# for small files.
def readline(filename, lineno):
f = open(filename)
lines = f.readlines()
f.close()
return lines[lineno-1] # runtime error if does not exist
def writeline(filename, lineno, data):
# r... | # pcode_io.py 19/01/2016 D.J.Whale
# simplest possible implementation. Only really works well
# for small files. Poor efficiency on large files.
def readline(filename, lineno):
f = open(filename)
lines = f.readlines()
f.close()
return lines[lineno-1] # runtime error if does not exist
def writeline(... | Test cases specified for io | Test cases specified for io
| Python | mit | whaleygeek/pc_parser,whaleygeek/pc_parser |
539f4baccb968d9d222f2f62573da34d85699f91 | comment_parser/parsers/common.py | comment_parser/parsers/common.py | #!/usr/bin/python
"""This module provides constructs common to all comment parsers."""
class Error(Exception):
"""Base Error class for all comment parsers."""
pass
class FileError(Error):
"""Raised if there is an issue reading a given file."""
pass
class UnterminatedCommentError(Error):
"""Rai... | #!/usr/bin/python
"""This module provides constructs common to all comment parsers."""
class Error(Exception):
"""Base Error class for all comment parsers."""
pass
class FileError(Error):
"""Raised if there is an issue reading a given file."""
pass
class UnterminatedCommentError(Error):
"""Rai... | Add __repr__ to Comment class. | comment_parser: Add __repr__ to Comment class.
| Python | mit | jeanralphaviles/comment_parser |
1290bc59774aac7756658c3480d6a5293c7a3467 | planner/models.py | planner/models.py | from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
origin = models.CharField(max_length=63)
destination = models.CharField(max_length=63)
def __unicode__(self):
return "{} to {}".format(
self.origin,
s... | from django.db import models
# Route model
# Start and end locations with additional stop-overs
class Route(models.Model):
start = models.CharField(max_length=63)
end = models.CharField(max_length=63)
def __unicode__(self):
return "{} to {}".format(
self.start,
self.end
... | Rename Route model's start and end fields to be consistent with front end identification | Rename Route model's start and end fields to be consistent with front end identification
| Python | apache-2.0 | jwarren116/RoadTrip,jwarren116/RoadTrip,jwarren116/RoadTrip |
42402aa72fdaf3bd5430505a1ceb86631aea97b8 | scripts/slave/chromium/dart_buildbot_run.py | scripts/slave/chromium/dart_buildbot_run.py | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for the dartium buildbots.
This script is called from buildbot and reports results using the buildbot
annotation sc... | Move hackish clobbering to the script that calls the dartium annotated steps | Move hackish clobbering to the script that calls the dartium annotated steps
Also clean it up, we don't have any builders that starts with release
I will remove this functionality from the dartium annotated step since it does not work correctly. This change allow us to use the normal chromium_utils function which we ... | Python | bsd-3-clause | eunchong/build,eunchong/build,eunchong/build,eunchong/build |
9d4647dca6f5e356f807d6885019d41a4b6d4847 | skimage/measure/__init__.py | skimage/measure/__init__.py | from .find_contours import find_contours
from ._regionprops import regionprops, perimeter
from ._structural_similarity import structural_similarity
from ._polygon import approximate_polygon, subdivide_polygon | from .find_contours import find_contours
from ._regionprops import regionprops, perimeter
from ._structural_similarity import structural_similarity
from ._polygon import approximate_polygon, subdivide_polygon
__all__ = ['find_contours',
'regionprops',
'perimeter',
'structural_similarit... | Add __all__ to measure package | Add __all__ to measure package
| Python | bsd-3-clause | robintw/scikit-image,ClinicalGraphics/scikit-image,vighneshbirodkar/scikit-image,newville/scikit-image,bennlich/scikit-image,paalge/scikit-image,chriscrosscutler/scikit-image,michaelaye/scikit-image,rjeli/scikit-image,rjeli/scikit-image,keflavich/scikit-image,pratapvardhan/scikit-image,oew1v07/scikit-image,bennlich/sci... |
1aa75af659daac62fdef423beac16aef1f057afb | test/testCore.py | test/testCore.py | import pyfits
import sys
def test_with_statement():
if sys.hexversion >= 0x02050000:
exec("""from __future__ import with_statement
with pyfits.open("ascii.fits") as f: pass""")
def test_naxisj_check():
hdulist = pyfits.open("o4sp040b0_raw.fits")
hdulist[1].header.update("NAXIS3", 500)
assert... | import pyfits
import numpy as np
import sys
def test_with_statement():
if sys.hexversion >= 0x02050000:
exec("""from __future__ import with_statement
with pyfits.open("ascii.fits") as f: pass""")
def test_naxisj_check():
hdulist = pyfits.open("o4sp040b0_raw.fits")
hdulist[1].header.update("NAXIS3... | Add test for byteswapping bug resolved in r514. | Add test for byteswapping bug resolved in r514.
git-svn-id: 5305e2c1a78737cf7dd5f8f44e9bbbd00348fde7@543 ed100bfc-0583-0410-97f2-c26b58777a21
| Python | bsd-3-clause | embray/PyFITS,spacetelescope/PyFITS,embray/PyFITS,embray/PyFITS,spacetelescope/PyFITS,embray/PyFITS |
fbc42057c647e4e42825b0b4e33d69e5967901f0 | cid/locals/thread_local.py | cid/locals/thread_local.py | from threading import local
from django.conf import settings
from .base import build_cid
_thread_locals = local()
def set_cid(cid):
"""Set the correlation id for the current request."""
setattr(_thread_locals, 'CID', cid)
def get_cid():
"""Return the currently set correlation id (if any).
If no... | from threading import local
from django.conf import settings
from .base import build_cid
_thread_locals = local()
def set_cid(cid):
"""Set the correlation id for the current request."""
setattr(_thread_locals, 'CID', cid)
def get_cid():
"""Return the currently set correlation id (if any).
If no... | Remove ancient FIXME in `get_cid()` | Remove ancient FIXME in `get_cid()`
Maybe I had a great idea in mind when I wrote the comment. Or maybe it
was just a vague thought. I guess we'll never know.
| Python | bsd-3-clause | snowball-one/cid |
370507fc48636417a10e4075917783169f3653c3 | test_edelbaum.py | test_edelbaum.py | from astropy import units as u
from numpy.testing import assert_almost_equal
from poliastro.bodies import Earth
from edelbaum import extra_quantities
def test_leo_geo_time_and_delta_v():
a_0 = 7000.0 # km
a_f = 42166.0 # km
i_f = 0.0 # deg
i_0 = 28.5 # deg
f = 3.5e-7 # km / s2
k = Ear... | from astropy import units as u
from numpy.testing import assert_almost_equal
from poliastro.bodies import Earth
from edelbaum import extra_quantities
def test_leo_geo_time_and_delta_v():
a_0 = 7000.0 # km
a_f = 42166.0 # km
i_f = 0.0 # rad
i_0 = (28.5 * u.deg).to(u.rad).value # rad
f = 3.5e... | Fix unit error, improve precision | Fix unit error, improve precision
| Python | mit | Juanlu001/pfc-uc3m |
2b70b4d2ca40cfbf36265a650ca04855999c5a03 | elm_open_in_browser.py | elm_open_in_browser.py | import sublime
import os.path as fs
if int(sublime.version()) < 3000:
from elm_project import ElmProject
from ViewInBrowserCommand import ViewInBrowserCommand
else:
from .elm_project import ElmProject
ViewInBrowserCommand = __import__('View In Browser').ViewInBrowserCommand.ViewInBrowserCommand
class ... | import sublime
import os.path as fs
if int(sublime.version()) < 3000:
from elm_project import ElmProject
from ViewInBrowserCommand import ViewInBrowserCommand as OpenInBrowserCommand
else:
from .elm_project import ElmProject
try:
from SideBarEnhancements.SideBar import SideBarOpenInBrowserComma... | Add alternative support for open in browser | Add alternative support for open in browser
Integrate SideBarEnhancements for ST3 for poplarity and browser detection
| Python | mit | deadfoxygrandpa/Elm.tmLanguage,deadfoxygrandpa/Elm.tmLanguage,rtfeldman/Elm.tmLanguage,rtfeldman/Elm.tmLanguage,sekjun9878/Elm.tmLanguage,sekjun9878/Elm.tmLanguage |
65529690d8fecbf81087c6f43316f054288785ec | twenty3.py | twenty3.py | from pync import Notifier
from time import sleep
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--min', type=int, help="Minutes before break", default="20")
args = parser.parse_args()
if not args.min:
raise ValueError("Invalid minutes")
while True:
... | from pync import Notifier
from time import sleep
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--min', type=int, help="Timeout before sending alert (minutes)", default="20")
parser.add_argument('--duration', type=int, help="Duration of break (seconds)", default="20")
... | Add break duration argument and sleep timeout. Add notification when it is time to get back to work | Add break duration argument and sleep timeout. Add notification when it is time to get back to work
| Python | mit | mgalang/twenty3 |
2ad4dd2fe877248b33aefa4465352710f95d953a | djlotrek/decorators.py | djlotrek/decorators.py | from functools import wraps
from django.conf import settings
import requests
def check_recaptcha(view_func):
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':
recaptcha_response = request.POST.get('g-recap... | from functools import wraps
from django.conf import settings
import requests
def check_recaptcha(view_func):
"""Chech that the entered recaptcha data is correct"""
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
request.recaptcha_is_valid = None
if request.method == 'POST':... | Add docstring to recaptcha check | Add docstring to recaptcha check | Python | mit | lotrekagency/djlotrek,lotrekagency/djlotrek |
ad9ad98b27c1640c5c5a336e62b9e8c3c805259f | api/serializers.py | api/serializers.py | from django.contrib.auth.models import User
from rest_framework import serializers
from api.models import UserPreferences, HelpLink
class HelpLinkSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = HelpLink
fields = (
'link_key',
'topic',
'h... | from django.contrib.auth.models import User
from rest_framework import serializers
from api.models import UserPreferences, HelpLink
class HelpLinkSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = HelpLink
fields = (
'link_key',
'href'
)
clas... | Reduce response data for HelpLink | Reduce response data for HelpLink
| Python | apache-2.0 | CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend |
da5269713a444c8a506535cd88f21fea8f1ffc83 | antxetamedia/multimedia/handlers.py | antxetamedia/multimedia/handlers.py | from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=False)
bucket.strip('-')
try:
... | from __future__ import unicode_literals
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket
from boto.exception import S3CreateError
from django.conf import settings
def upload(user, passwd, bucket, metadata, key, fd):
conn = S3Connection(user, passwd, host=settings.S3_HOST, is_secure=... | Prepend S3 account username to buckets | Prepend S3 account username to buckets
| Python | agpl-3.0 | GISAElkartea/antxetamedia,GISAElkartea/antxetamedia,GISAElkartea/antxetamedia |
ceb88623b55cd572d4ef45ec2fb7d81639e07878 | fancypages/__init__.py | fancypages/__init__.py | __version__ = (0, 0, 1, 'alpha', 1)
| import os
__version__ = (0, 0, 1, 'alpha', 1)
FP_MAIN_TEMPLATE_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__))
)
| Add setting for fancypages base template dir | Add setting for fancypages base template dir
| Python | bsd-3-clause | socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,tangentlabs/django-fancypages |
72655f0b0c7edfd3f51fe0ea847d45f9acd5ba42 | hoomd/triggers.py | hoomd/triggers.py | # Copyright (c) 2009-2019 The Regents of the University of Michigan
# This file is part of the HOOMD-blue project, released under the BSD 3-Clause
# License.
from hoomd import _hoomd
class Trigger(_hoomd.Trigger):
pass
class PeriodicTrigger(_hoomd.PeriodicTrigger):
def __init__(self, period, phase=0):
... | # Copyright (c) 2009-2019 The Regents of the University of Michigan
# This file is part of the HOOMD-blue project, released under the BSD 3-Clause
# License.
from hoomd import _hoomd
class Trigger(_hoomd.Trigger):
pass
class PeriodicTrigger(_hoomd.PeriodicTrigger, Trigger):
def __init__(self, period, phase... | Make ``PeriodicTrigger`` inherent from ``Trigger`` | Make ``PeriodicTrigger`` inherent from ``Trigger``
Fixes bug in checking state and preprocessing ``Triggers`` for duck
typing.
| Python | bsd-3-clause | joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue |
990e33af851172ea3d79e591bde52af554d0eb50 | common/util.py | common/util.py | #!/usr/bin/python
"""
common.py
"""
import sys
def log(msg, *args):
if args:
msg = msg % args
print >>sys.stderr, 'webpipe:', msg
| """
util.py
"""
import os
import sys
basename = os.path.basename(sys.argv[0])
prefix, _ = os.path.splitext(basename)
def log(msg, *args):
if args:
msg = msg % args
print >>sys.stderr, prefix + ': ' + msg
| Use the program name as the prefix. | Use the program name as the prefix.
| Python | bsd-3-clause | andychu/webpipe,andychu/webpipe,andychu/webpipe,andychu/webpipe,andychu/webpipe |
0e376d987dd8d513354a840da6bee6d5a2752f89 | django_countries/widgets.py | django_countries/widgets.py | from django.conf import settings
from django.forms import widgets
from django.utils.safestring import mark_safe
COUNTRY_CHANGE_HANDLER = """
this.nextSibling.src = this.nextSibling.src.replace(/[a-z_]*\.gif/, (this.value.toLowerCase() || '__') + '.gif');
"""
FLAG_IMAGE = """<img style="margin: 6px 4px; position: abso... | from django.conf import settings
from django.forms import widgets
from django.utils.safestring import mark_safe
COUNTRY_CHANGE_HANDLER = """
this.nextSibling.src = this.nextSibling.src.replace(/[a-z_]{2}(\.[a-zA-Z]*)$/, (this.value.toLowerCase() || '__') + '$1');
"""
FLAG_IMAGE = """<img style="margin: 6px 4px; posit... | Make the regular expression not require a gif image. | Make the regular expression not require a gif image.
| Python | mit | SmileyChris/django-countries,schinckel/django-countries,rahimnathwani/django-countries,jrfernandes/django-countries,velfimov/django-countries,fladi/django-countries,pimlie/django-countries |
6664f77b8193343fe840b2542a84cc2bf585108a | check_version.py | check_version.py | import re
import sys
changes_file = open('CHANGES.txt', 'r')
changes_first_line = changes_file.readline()
changes_version = re.match(r'v(\d\.\d\.\d).*', changes_first_line).group(1)
setup_file = open('setup.py', 'r')
setup_content = setup_file.read()
setup_version = re.search(r'version=\'(\d\.\d\.\d)\'', setup_conten... | import re
import sys
changes_file = open('CHANGES.txt', 'r')
changes_first_line = changes_file.readline()
changes_version = re.match(r'v(\d\.\d\.\d).*',
changes_first_line).group(1)
setup_file = open('setup.py', 'r')
setup_content = setup_file.read()
setup_version = re.search(r'version=\'(\... | Update release version checking to include documentation | Update release version checking to include documentation
| Python | unlicense | mmurdoch/Vengeance,mmurdoch/Vengeance |
b0bfbe3bcab7f55dd2ed742d945d0f950bca0a2b | ckeditor/urls.py | ckeditor/urls.py | from django.conf.urls.defaults import patterns, url
from django.contrib import admin
from ckeditor import views
urlpatterns = patterns(
'',
url(r'^upload/', admin.site.admin_view(views.upload), name='ckeditor_upload'),
url(r'^browse/', admin.site.admin_view(views.browse), name='ckeditor_browse'),
)
| try:
from django.conf.urls import patterns, url
except ImportError: # django < 1.4
from django.conf.urls.defaults import patterns, url
from django.contrib import admin
from ckeditor import views
urlpatterns = patterns(
'',
url(r'^upload/', admin.site.admin_view(views.upload), name='ckeditor_upload'),
... | Fix the file url for Django 1.6 | Fix the file url for Django 1.6
| Python | bsd-3-clause | gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3 |
2758c1086e06a77f9676d678a3d41a53a352ec01 | testfixtures/seating.py | testfixtures/seating.py | # -*- coding: utf-8 -*-
"""
testfixtures.seating
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.seating.models.seat_group import SeatGroup
def create_seat_group(party_id, seat_category, title, *, seat_quantity=4):
return... | # -*- coding: utf-8 -*-
"""
testfixtures.seating
~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2016 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from byceps.services.seating.models.category import Category
from byceps.services.seating.models.seat_group import SeatGroup
def create_seat_category... | Add function to create a seat category test fixture | Add function to create a seat category test fixture
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps |
b3c2a47b049f97de0367f012fb35d247f2f1510b | oscar/apps/offer/managers.py | oscar/apps/offer/managers.py | from django.utils.timezone import now
from django.db import models
class ActiveOfferManager(models.Manager):
"""
For searching/creating offers within their date range
"""
def get_query_set(self):
cutoff = now()
return super(ActiveOfferManager, self).get_query_set().filter(
... | from django.utils.timezone import now
from django.db import models
class ActiveOfferManager(models.Manager):
"""
For searching/creating offers within their date range
"""
def get_query_set(self):
cutoff = now()
return super(ActiveOfferManager, self).get_query_set().filter(
... | Fix bug in offer manager with new datetimes | Fix bug in offer manager with new datetimes
| Python | bsd-3-clause | rocopartners/django-oscar,WadeYuChen/django-oscar,sonofatailor/django-oscar,josesanch/django-oscar,mexeniz/django-oscar,faratro/django-oscar,michaelkuty/django-oscar,anentropic/django-oscar,jinnykoo/wuyisj,MatthewWilkes/django-oscar,sasha0/django-oscar,jlmadurga/django-oscar,Idematica/django-oscar,okfish/django-oscar,b... |
74816d4af07808009b89163060f97014b1a20ceb | tests/test_arguments.py | tests/test_arguments.py | import unittest
from mock import MagicMock, Mock
from nose.tools import *
from gargoyle.inputs.arguments import *
class BaseArgument(object):
def setUp(self):
self.argument = self.klass(self.valid_comparison_value)
@property
def interface_functions(self):
return ['__lt__', '__le__', '__e... | import unittest
from mock import MagicMock, Mock
from nose.tools import *
from gargoyle.inputs.arguments import *
class BaseArgument(object):
def setUp(self):
self.argument = self.klass(self.valid_comparison_value)
@property
def interface_functions(self):
return ['__lt__', '__le__', '__e... | Enforce that arguments must implement non-zero methods. | Enforce that arguments must implement non-zero methods. | Python | apache-2.0 | disqus/gutter,disqus/gutter,kalail/gutter,kalail/gutter,kalail/gutter |
15013c51f602786265b59c1d4a7e894eae090d90 | tests/test_normalize.py | tests/test_normalize.py | from hypothesis import assume, given
from utils import isclose, vectors
@given(v=vectors())
def test_normalize_length(v):
"""v.normalize().length == 1 and v == v.length * v.normalize()"""
assume(v)
assert isclose(v.normalize().length, 1)
assert v.isclose(v.length * v.normalize())
| from hypothesis import assume, given
from utils import isclose, vectors
@given(v=vectors())
def test_normalize_length(v):
"""v.normalize().length == 1 and v == v.length * v.normalize()"""
assume(v)
assert isclose(v.normalize().length, 1)
assert v.isclose(v.length * v.normalize())
@given(v=vectors()... | Test that direction is preserved | tests/normalize: Test that direction is preserved
| Python | artistic-2.0 | ppb/ppb-vector,ppb/ppb-vector |
65574a215e60811bb023edf3cc6a7bfb6ff201a1 | tiddlywebwiki/manage.py | tiddlywebwiki/manage.py | """
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all ... | """
TiddlyWebWiki-specific twanager commands
"""
from tiddlyweb.store import Store
from tiddlyweb.manage import make_command, usage
from tiddlywebwiki.tiddlywiki import import_wiki_file
from tiddlywebwiki.importer import import_list
def init(config):
@make_command()
def update(args):
"""Update all ... | Update the docs on twimport and imwiki to indicate that imwiki is deprecated. | Update the docs on twimport and imwiki to indicate that imwiki is deprecated.
| Python | bsd-3-clause | tiddlyweb/tiddlywebwiki,tiddlyweb/tiddlywebwiki,tiddlyweb/tiddlywebwiki |
e70f30758a501db12af4fbbfc4204e2858967c8b | conllu/compat.py | conllu/compat.py | try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
... | try:
from io import StringIO
except ImportError:
from StringIO import StringIO
try:
from contextlib import redirect_stdout
except ImportError:
import sys
import contextlib
@contextlib.contextmanager
def redirect_stdout(target):
original = sys.stdout
sys.stdout = target
... | Make fullmatch work on python 2.7. | Bug: Make fullmatch work on python 2.7.
| Python | mit | EmilStenstrom/conllu |
56e45a5146cfcde797be5cb8d3c52a1fbf874d88 | user_clipboard/forms.py | user_clipboard/forms.py | from django import forms
from .models import Clipboard
class ClipboardFileForm(forms.ModelForm):
class Meta:
model = Clipboard
fields = ('file',)
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._met... | from django import forms
from .models import Clipboard
class BaseClipboardForm(object):
def save(self, commit=True):
# Delete old file before saving the new one
if self.instance.pk:
old_instance = self._meta.model.objects.get(pk=self.instance.pk)
old_instance.file.delete(s... | Create BaseClipboardForm for easy extending if needed | Create BaseClipboardForm for easy extending if needed | Python | mit | IndustriaTech/django-user-clipboard,MagicSolutions/django-user-clipboard,IndustriaTech/django-user-clipboard,MagicSolutions/django-user-clipboard |
e05ea934335eac29c0b2f164eab600008546324c | recurring_contract/migrations/1.2/post-migration.py | recurring_contract/migrations/1.2/post-migration.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __ope... | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Coninckx David <david@coninckx.com>
#
# The licence is in the file __ope... | Remove wrong migration of contracts. | Remove wrong migration of contracts.
| Python | agpl-3.0 | CompassionCH/compassion-accounting,ndtran/compassion-accounting,ndtran/compassion-accounting,ecino/compassion-accounting,ecino/compassion-accounting,CompassionCH/compassion-accounting,ndtran/compassion-accounting |
d1d66c37419a85a4258f37201261d76a8f6a9e03 | ckeditor/fields.py | ckeditor/fields.py | from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formf... | from django.db import models
from django import forms
from ckeditor.widgets import CKEditorWidget
class RichTextField(models.TextField):
def __init__(self, *args, **kwargs):
self.config_name = kwargs.pop("config_name", "default")
super(RichTextField, self).__init__(*args, **kwargs)
def formf... | Fix Function RichTextFormField now received a new parameter max_lenght for django 1.7 | Fix Function RichTextFormField now received a new parameter max_lenght for django 1.7
| Python | bsd-3-clause | gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3,gian88/django-ckeditor-amazon-s3 |
b72c9a26c00ca31966be3ae8b529e9272d300290 | __main__.py | __main__.py | import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
self.single = sys.stdin.isatty() or args.print
def displ... | import sys
import argparse
from . import parse
from . import compile
from . import runtime
from .interactive import Interactive
class Interactive (Interactive):
def __init__(self, args):
super().__init__()
self.args = args
def traceback(self, trace):
# When running in non-interac... | Remove the -p command-line option. | Remove the -p command-line option.
It's pretty useless anyway. Use instead.
| Python | mit | pyos/dg |
5d8a37cdbd41af594f03d78092b78a22afc53c05 | __main__.py | __main__.py | #!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, help='GitHub user handle')
parser.add_argument('-f', '--forma... | #!/usr/bin/env python
import argparse
from githublist.parser import main as get_data
from githublist.serve import serve_content
parser = argparse.ArgumentParser(description='View repositories for any GitHub account.')
parser.add_argument('user', type=str, nargs='+', help='GitHub user handle')
parser.add_argument('-f... | Add support for multiple users, format types | Add support for multiple users, format types
| Python | mit | kshvmdn/github-list,kshvmdn/github-list,kshvmdn/github-list |
7dd94bf965fafafb279a4304108462e4060c729c | waterbutler/identity.py | waterbutler/identity.py | import asyncio
from waterbutler import settings
@asyncio.coroutine
def fetch_rest_identity(params):
response = yield from aiohttp.request(
'get',
settings.IDENTITY_API_URL,
params=params,
headers={'Content-Type': 'application/json'},
)
# TOOD Handle Errors nicely
if r... | import asyncio
import aiohttp
from waterbutler import settings
IDENTITY_METHODS = {}
def get_identity_func(name):
try:
return IDENTITY_METHODS[name]
except KeyError:
raise NotImplementedError('No identity getter for {0}'.format(name))
def register_identity(name):
def _register_identi... | Make use of a register decorator | Make use of a register decorator
| Python | apache-2.0 | Johnetordoff/waterbutler,RCOSDP/waterbutler,cosenal/waterbutler,rafaeldelucena/waterbutler,TomBaxter/waterbutler,icereval/waterbutler,chrisseto/waterbutler,Ghalko/waterbutler,rdhyee/waterbutler,CenterForOpenScience/waterbutler,hmoco/waterbutler,felliott/waterbutler,kwierman/waterbutler |
dd8176f26addcf36419f1723448ab1e3ae8d0e89 | metashare/repository/search_fields.py | metashare/repository/search_fields.py | """
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a labe... | """
Project: META-SHARE prototype implementation
Author: Christian Spurk <cspurk@dfki.de>
"""
from haystack.exceptions import SearchFieldError
from haystack.indexes import SearchField, CharField, MultiValueField
class LabeledField(SearchField):
"""
A kind of mixin class for creating `SearchField`s with a labe... | Order facets and add sub facet feature | Order facets and add sub facet feature
| Python | bsd-3-clause | MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,MiltosD/CEF-ELRC,JuliBakagianni/META-SHARE,MiltosD/CEFELRC,JuliBakagianni/CEF-ELRC,MiltosD/CEFELRC,zeehio/META-SHARE,zeehio/META-SHARE,MiltosD/CEF-ELRC,JuliBakagianni/CEF-ELRC,zeehio/META-... |
7577c51486169e8026a74cd680e2f4b58e4ea60a | models/phase3_eval/process_sparser.py | models/phase3_eval/process_sparser.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
from indra import sparser
base_folder = 'sources/sparser-20170330'
sentences_folder = 'sources/sparser-20170210'
def get_file_names(base_dir):
fnames = glob.glob(os.path.join(base_dir, '*.... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import glob
import json
from indra import sparser
from indra.statements import stmts_from_json, get_valid_location, \
get_valid_residue
base_folder = os.environ['HOME'] + \
... | Read and fix Sparser jsons | Read and fix Sparser jsons
| Python | bsd-2-clause | pvtodorov/indra,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,bgyori/indra,sorgerlab/indra,sorgerlab/belpy,pvtodorov/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,sorgerlab/belpy,pvtodorov/indra,johnbachman/indra,pvtodorov/indra,johnbachman/indra |
f99c2687786144d3c06d25705cc884199b962272 | microdrop/tests/update_dmf_control_board.py | microdrop/tests/update_dmf_control_board.py | import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board.git']... | import os
import subprocess
if __name__ == '__main__':
os.chdir('microdrop/plugins')
if not os.path.exists('dmf_control_board'):
print 'Clone dmf_control_board repository...'
subprocess.check_call(['git', 'clone',
'http://microfluidics.utoronto.ca/git/dmf_control_board... | Check that update script is successful | Check that update script is successful
| Python | bsd-3-clause | wheeler-microfluidics/microdrop |
2bfd89b7fe7c4ac4c70f324a745dedbd84dd0672 | __main__.py | __main__.py | from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
ps1 = term.bold_blue(ps1)
ps2 = term.bold_blue(ps2)
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
... | from . import *
import readline
ps1 = '\n% '
ps2 = '| '
try:
from blessings import Terminal
term = Terminal()
def fancy_movement():
print(term.move_up() + term.clear_eol() + term.move_up())
except ImportError:
def fancy_movement():
pass
def getfilefunc(mod, droplast=True):
return ... | Remove colors from REPL prompt | Remove colors from REPL prompt
They weren't playing nice with Readline.
There's still an optional dependency on Blessings, but that is only
used to strip away the trailing ps2.
| Python | isc | gvx/isle |
03ef4407612d553095f39694527d20543bc4405a | subiquity/core.py | subiquity/core.py | # Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | # Copyright 2015 Canonical, Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distribute... | Drop Installpath controller, whilst it's single option. | Drop Installpath controller, whilst it's single option.
| Python | agpl-3.0 | CanonicalLtd/subiquity,CanonicalLtd/subiquity |
add4824d69afc928790459129fffbdf72820971f | accloudtant/__main__.py | accloudtant/__main__.py | import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
if __name__ == "__main__":
usage = []
with open("tests/fixtures/2021/03/S3.csv") as f:
reader = csv.DictReader(f)
for row in reader:
usage.append(row)
print("Simple S... | import csv
def area(entry):
if entry[" UsageType"].startswith("EUC1-"):
return "EU (Frankfurt)"
def get_areas(entries):
areas = {}
for entry in entries:
area_name = area(entry)
if area_name not in areas:
areas[area_name] = []
areas[area_name].append(entry)
... | Print list of concepts per area | Print list of concepts per area
| Python | apache-2.0 | ifosch/accloudtant |
f704722d54092a6d9b65f726a6b83d208b3e1946 | chatroom.py | chatroom.py | class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
self.users.remove(user)
return len (self.users)
| class ChatRoom:
def __init__(self, name, user):
self.name = name
self.users = [user]
def add_user(self, user):
self.users.apend(user)
self.users.sort()
def remove_user(self, user):
if user in self.users:
self.users.remove(user)
return len (s... | Make sure user is in room's user list before removing | Make sure user is in room's user list before removing
| Python | mit | jtoelke/fenfirechat |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.