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 |
|---|---|---|---|---|---|---|---|---|---|
34fbab0a31956af0572c31612f359608a8819360 | models/phase3_eval/assemble_cx.py | models/phase3_eval/assemble_cx.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assembler."""
stmts = ac.filter_belief(stm... | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from os.path import join as pjoin
from indra.assemblers import CxAssembler
import indra.tools.assemble_corpus as ac
def assemble_cx(stmts, out_file):
"""Return a CX assembler."""
stmts = ac.filter_belief(stm... | Remove strip context for CX assembly | Remove strip context for CX assembly
| Python | bsd-2-clause | pvtodorov/indra,bgyori/indra,pvtodorov/indra,johnbachman/belpy,pvtodorov/indra,johnbachman/belpy,johnbachman/belpy,sorgerlab/indra,sorgerlab/indra,pvtodorov/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy |
f4286480f0fa157eb1b88b144ee57ffef7d1fc03 | barython/tests/hooks/test_bspwm.py | barython/tests/hooks/test_bspwm.py |
from collections import OrderedDict
import pytest
from barython.hooks.bspwm import BspwmHook
def test_bspwm_hook_parse_event():
bh = BspwmHook()
status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:"
"mDVI-I-0:Od:LT")
expected = OrderedDict([
('HDMI-0', {'desktops':... |
from collections import OrderedDict
import pytest
from barython.hooks.bspwm import BspwmHook
def test_bspwm_hook_parse_event():
bh = BspwmHook()
status = ("WmHDMI-0:Ou:LT:MDVI-D-0:fo:f7:fDesktop2:os:Of:fp:oq:fi:LT:"
"mDVI-I-0:Od:LT")
expected = OrderedDict([
('HDMI-0', {'desktops':... | Add test for bspwm widget | Add test for bspwm widget
| Python | bsd-3-clause | Anthony25/barython |
ae583132ade7370595d6d9d14dba2b720c5415d6 | cinemair/favorites/serializers.py | cinemair/favorites/serializers.py | from rest_framework import serializers as drf_serializers
from cinemair.common.api import serializers
from cinemair.shows.serializers import ShowRelatedSerializer
from . import models
class FavoriteSerializer(serializers.ModelSerializer):
show_info = drf_serializers.SerializerMethodField()
class Meta:
... | from rest_framework import serializers as drf_serializers
from cinemair.common.api import serializers
from cinemair.shows.serializers import ShowRelatedSerializer
from . import models
class FavoriteSerializer(serializers.ModelSerializer):
show_info = drf_serializers.SerializerMethodField()
class Meta:
... | Validate user when favorite a show | Validate user when favorite a show
| Python | mit | Cinemair/cinemair-server,Cinemair/cinemair-server |
d4d73fe7d5e83c65d9abbf59ea14ed60eb23a83f | poem_reader.py | poem_reader.py | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Reader for the newspaper XML files
"""
import argparse
from lxml import etree
argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@')
argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory")
args = a... | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""
Reader for the newspaper XML files
"""
import argparse
import glob
from lxml import etree
argparser = argparse.ArgumentParser(description="Newspaper XML parser", fromfile_prefix_chars='@')
argparser.add_argument("dataroot", help="Path to DHH 17 newspapers directory"... | Read XML files from a directory and find textblock by id | Read XML files from a directory and find textblock by id
| Python | mit | dhh17/categories_norms_genres,dhh17/categories_norms_genres,dhh17/categories_norms_genres |
51bbc760d0be6f21b1526752f1b4ab5a76c82917 | diff_array/diff_array.py | diff_array/diff_array.py | def array_diff(a, b):
return a if not b else [x for x in a if x != b[0]]
| def array_diff(a, b):
return [x for x in a if x not in set(b)]
| Change code because failed the random test | Change code because failed the random test
| Python | mit | lowks/codewars-katas-python |
65c712464813ba41b564aa3e0116e60805f6681e | storyboard/api/v1/system_info.py | storyboard/api/v1/system_info.py | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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... | # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# 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... | Add example commands for the Systeminfo api | Add example commands for the Systeminfo api
Currently the api documentation does not include example commands.
It would be very friendly for our users to have some example commands
to follow and use the api.
This patch adds examples to the Systeminfo section of the api documentation.
Change-Id: Ic3d56d207db696100754... | Python | apache-2.0 | ColdrickSotK/storyboard,ColdrickSotK/storyboard,ColdrickSotK/storyboard |
81cc39ca4c9348732a18d2f1ee7edcdbc4c61479 | tests/tags/test_div.py | tests/tags/test_div.py | # -*- coding: utf-8 -*-
from riot.layout import render_layout, patch_layout
def test_render_div():
assert render_layout([
'div', {}, []
]) == [
'div',
{
'div_char': u' ',
'top': 0,
'bottom': 0,
}
]
def test_render_div_with_div_char():
... | # -*- coding: utf-8 -*-
from riot.layout import render_layout, patch_layout
def test_render_div():
assert render_layout([
'div', {}, []
]) == [
'div',
{
'div_char': u' ',
'top': 0,
'bottom': 0,
}
]
def test_render_div_with_opts():
as... | Allow render opts to div. | Allow render opts to div.
| Python | mit | soasme/riotpy |
c3d094074a6c4224efb39489110fe99b491d1108 | utils/swift_build_support/swift_build_support/compiler_stage.py | utils/swift_build_support/swift_build_support/compiler_stage.py | # ===--- compiler_stage.py -----------------------------------------------===#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https:#swift.org/LICENSE.txt... | # ===--- compiler_stage.py -----------------------------------------------===#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https:#swift.org/LICENSE.txt... | Make sure that StageArgs are never passed a StageArgs as their args. | [build-script] Make sure that StageArgs are never passed a StageArgs as their args.
No good reason to do this and simplifies the state space.
| Python | apache-2.0 | hooman/swift,ahoppen/swift,gregomni/swift,benlangmuir/swift,gregomni/swift,glessard/swift,ahoppen/swift,glessard/swift,hooman/swift,roambotics/swift,apple/swift,rudkx/swift,hooman/swift,ahoppen/swift,xwu/swift,xwu/swift,xwu/swift,JGiola/swift,rudkx/swift,apple/swift,hooman/swift,roambotics/swift,atrick/swift,benlangmui... |
f86ca97dc1ba22b5fab0c7a4605ab2a51367b365 | openassessment/assessment/migrations/0002_staffworkflow.py | openassessment/assessment/migrations/0002_staffworkflow.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('assessment', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='StaffW... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('assessment', '0004_edited_content_migration'),
]
operations = [
migrations.CreateModel(
... | Update migration history to include trackchanges migrations | Update migration history to include trackchanges migrations
| Python | agpl-3.0 | Stanford-Online/edx-ora2,Stanford-Online/edx-ora2,Stanford-Online/edx-ora2,Stanford-Online/edx-ora2 |
77e9d92e040b60cc5e894a59ecfde0a91a8f1f8c | coop_cms/apps/email_auth/forms.py | coop_cms/apps/email_auth/forms.py | # -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth import authenticate
from django.utils.translation import ugettext as _
class EmailAuthForm(forms.Form):
email = forms.EmailField(required=True, label=_(u"Email"))
password = forms.CharField(label=_("Password"), widget=forms.PasswordInpu... | # -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth import authenticate
from django.utils.translation import ugettext as _, ugettext_lazy as __
class EmailAuthForm(forms.Form):
email = forms.EmailField(required=True, label=__(u"Email"))
password = forms.CharField(label=__("Password"), wi... | Fix translation issue on EmailAuthForm | Fix translation issue on EmailAuthForm
| Python | bsd-3-clause | ljean/coop_cms,ljean/coop_cms,ljean/coop_cms |
027e9dabb3270a3b9e3135f8a399ae4eb114a217 | package_name/module.py | package_name/module.py | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
Returns
-------
numpy.ndarray
Elementwise, the cube of `x` where it is p... | """
Module provides a simple cubic_rectification function.
"""
import numpy as np
def cubic_rectification(x, verbose=False):
"""
Rectified cube of an array.
Parameters
----------
x : numpy.ndarray
Input array.
verbose : bool, optional
Whether to print out details. Default is ... | Add verbose argument to cubic_rectification | ENH: Add verbose argument to cubic_rectification
| Python | mit | scottclowe/python-ci,scottclowe/python-ci,scottclowe/python-continuous-integration,scottclowe/python-continuous-integration |
aa8c94bfa63aab1779e280d6695c3a259e290c8b | test/test_flvlib.py | test/test_flvlib.py | import unittest
import test_primitives, test_astypes
def get_suite():
primitives = unittest.TestLoader().loadTestsFromModule(test_primitives)
astypes = unittest.TestLoader().loadTestsFromModule(test_astypes)
return unittest.TestSuite([primitives, astypes])
def main():
unittest.TextTestRunner(verbosity... | import unittest
import test_primitives, test_astypes, test_helpers
def get_suite():
modules = (test_primitives, test_astypes, test_helpers)
suites = [unittest.TestLoader().loadTestsFromModule(module) for
module in modules]
return unittest.TestSuite(suites)
def main():
unittest.TextTestRu... | Include the helpers module tests in the full library testsuite. | Include the helpers module tests in the full library testsuite.
| Python | mit | wulczer/flvlib |
aafff9f089b92137c8827addaff278da94edec45 | base/components/people/constants.py | base/components/people/constants.py | from model_utils import Choices
from ohashi.constants import OTHER
BLOOD_TYPE = Choices('A', 'B', 'O', 'AB')
CLASSIFICATIONS = Choices(
(1, 'major', 'Major Unit'),
(2, 'minor', 'Minor Unit'),
(3, 'shuffle', 'Shuffle Unit'),
(4, 'temporary', 'Temporary Unit'),
(5, 'subunit', 'Sub-Unit'),
(6, ... | from model_utils import Choices
from ohashi.constants import OTHER
BLOOD_TYPE = Choices('A', 'B', 'O', 'AB')
CLASSIFICATIONS = Choices(
(1, 'major', 'Major Unit'),
(2, 'minor', 'Minor Unit'),
(3, 'shuffle', 'Shuffle Unit'),
(4, 'temporary', 'Temporary Unit'),
(5, 'subunit', 'Sub-Unit'),
(6, ... | Make the Satoyama Movement a scope. | Make the Satoyama Movement a scope.
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web |
fb335ed74d9d924816fe6bf712844023abf62e30 | address_book/person.py | address_book/person.py | __all__ = ['Person']
class Person(object):
pass | __all__ = ['Person']
class Person(object):
def __init__(self, first_name, last_name, addresses, phone_numbers):
self.first_name = first_name
self.last_name = last_name
self.addresses = addresses
self.phone_numbers = phone_numbers
| Add constructor with required arguments to the `Person` class | Add constructor with required arguments to the `Person` class
| Python | mit | dizpers/python-address-book-assignment |
74ec59b48b8a0bd7bac9d0eada4caa463a897d08 | playground/settings.py | playground/settings.py | """
Eve playground settings
"""
DOMAIN = {
"accounts": {
"schema": {
"name": {
"type": "string",
},
"can_manage": {
"type": "list",
"schema": {
"type": "objectid",
"data_relation": {
... | """
Eve playground settings
"""
DOMAIN = {
"accounts": {
"schema": {
"name": {
"type": "string",
},
"can_manage": {
"type": "list",
"schema": {
"type": "objectid",
"data_relation": {
... | Add example of a scoped resource | Add example of a scoped resource
Add the Project resource and set the `url` setting in the domain to allow it to sit as a sub resource under accounts. See: http://python-eve.org/features.html#sub-resources
| Python | mit | proxama/eve-playground |
4ff709f80999bfc512d23a25d4236108c067cc31 | poppinsbag/__init__.py | poppinsbag/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = "0.1.0"
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Mary Poppins always has what you need in her bag.
This is a set of tools and helpers to deals with common things.
Give it a try !
"""
__version__ = "0.1.0"
| Add a docstring to the poppinsbag module | Add a docstring to the poppinsbag module
| Python | mit | avcreation/pyPoppins |
3873fe6b33665267a04f80faec63eaaa19ea00bd | portal/pages/models.py | portal/pages/models.py | from django.db import models
from wagtail.wagtailcore.models import Page as WagtailPage
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
class Page(WagtailPage):
parent_page_types = ['home.HomePage', 'Page']
body = RichTextField()
indexed_fie... | from django.db import models
from wagtail.wagtailcore.models import Page as WagtailPage
from wagtail.wagtailcore.fields import RichTextField
from wagtail.wagtailadmin.edit_handlers import FieldPanel
class Page(WagtailPage):
body = RichTextField()
indexed_fields = ('body', )
content_panels = [
Fi... | Allow pages to appear anywhere they aren't excluded | Allow pages to appear anywhere they aren't excluded
| Python | isc | Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,Ecotrust/marineplanner-core,MidAtlanticPortal/marco-portal2,MidAtlanticPortal/marco-portal2,MidAtlanticPortal/marco-portal2,MidAtlanticPortal/marco-portal2,Ecotrust/marineplanner-core |
c0c902cc356d1a3142a6d260e7b768114449013e | tutorials/models.py | tutorials/models.py | from django.db import models
from markdownx.models import MarkdownxField
# Create your models here.
class Tutorial(models.Model):
# ToDo: Fields that are out-commented are missing according to the mockup -> datamodel ??
# Category = models.TextField()
title = models.TextField()
html = models.TextFie... | from django.db import models
from django.urls import reverse
from markdownx.models import MarkdownxField
# add options if needed
CATEGORY_OPTIONS = [('io', 'I/O'), ('intro', 'Introduction')]
LEVEL_OPTIONS = [(1, '1'), (2, '2'), (3, '3')]
# Create your models here.
class Tutorial(models.Model):
# ToDo: Fields th... | Add options for choices fields, Add new fields to Tutorial model | Add options for choices fields, Add new fields to Tutorial model
| Python | agpl-3.0 | openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform |
6153f18bda4dcf3601df91b60787453af1517b78 | falmer/auth/types.py | falmer/auth/types.py | import graphene
from django.contrib.auth.models import Permission as DjangoPermission
from graphene_django import DjangoObjectType
from . import models
class ClientUser(DjangoObjectType):
name = graphene.String()
has_cms_access = graphene.Boolean()
user_id = graphene.Int()
permissions = graphene.List(... | import graphene
from django.contrib.auth.models import Permission as DjangoPermission
from graphene_django import DjangoObjectType
from . import models
class ClientUser(DjangoObjectType):
name = graphene.String()
has_cms_access = graphene.Boolean()
user_id = graphene.Int()
permissions = graphene.List(... | Add additional fields to permission type | Add additional fields to permission type
| Python | mit | sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer,sussexstudent/falmer |
c5bcd270e8422ba23bcb29dd4a00ce4fa9e7d437 | anki.py | anki.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.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 os
import re
import yaml
import lib.genanki.genanki as genanki
class Anki:
def generate_id():
"""Gener... | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v2.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 os
import re
import yaml
import lib.genanki.genanki as genanki
class Anki:
def generate_id():
"""Gener... | Document new {{import:file.txt}} command for Anki card definitions. | Document new {{import:file.txt}} command for Anki card definitions.
| Python | mpl-2.0 | holocronweaver/wanikani2anki,holocronweaver/wanikani2anki,holocronweaver/wanikani2anki |
f5885a2644a21def7340e0d34b809a98472b366c | heufybot/modules/commands/nick.py | heufybot/modules/commands/nick.py | from twisted.plugin import IPlugin
from heufybot.moduleinterface import IBotModule
from heufybot.modules.commandinterface import BotCommand
from zope.interface import implements
class NickCommand(BotCommand):
implements(IPlugin, IBotModule)
name = "Nick"
def triggers(self):
return ["nick"]
... | from twisted.plugin import IPlugin
from heufybot.moduleinterface import IBotModule
from heufybot.modules.commandinterface import BotCommand
from zope.interface import implements
class NickCommand(BotCommand):
implements(IPlugin, IBotModule)
name = "Nick"
def triggers(self):
return ["nick"]
... | Fix the Nick command help text | Fix the Nick command help text
| Python | mit | Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot |
f11c489f6b28edc1ec9b399bbff1f1d0831d23bb | grab.py | grab.py | #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('run_ids', help = 'IDs of runs to analyze... | #!/usr/bin/env python
# Grab runs from S3 and do analysis
#
# Daniel Klein, 2015-08-14
import sys
import subprocess
import glob
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('remote_dir', help = 'S3 directory with completed runs')
parser.add_argument('output_dir', help = 'Local destination f... | Add specification of output directory from command line | Add specification of output directory from command line
| Python | mit | othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel,othercriteria/StochasticBlockmodel |
b5fc62d022cd773a0333560f30d8c8c0d6dbd25e | txircd/utils.py | txircd/utils.py | def unescapeEndpointDescription(desc):
result = []
escape = []
depth = 0
desc = iter(desc)
for char in desc:
if char == "\\":
try:
char = desc.next()
except StopIteration:
raise ValueError ("Endpoint description not valid: escaped end o... | def _enum(**enums):
return type('Enum', (), enums)
ModeType = _enum(List=0, ParamOnUnset=1, Param=2, NoParam=3, Status=4)
def unescapeEndpointDescription(desc):
result = []
escape = []
depth = 0
desc = iter(desc)
for char in desc:
if char == "\\":
try:
char ... | Add a ModeType enum for later benefit | Add a ModeType enum for later benefit
| Python | bsd-3-clause | ElementalAlchemist/txircd,Heufneutje/txircd |
c79a3d368b1727b02e97600b17ac3da28a2107b4 | project/apps/forum/serializers.py | project/apps/forum/serializers.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from machina.core.db.models import get_model
from rest_framework import serializers
Forum = get_model('forum', 'Forum')
class ForumSerializer(serializers.ModelSerializer):
description = serializers.SerializerMethodField()
previous_sibling = se... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from machina.core.db.models import get_model
from rest_framework import serializers
Forum = get_model('forum', 'Forum')
class ForumSerializer(serializers.ModelSerializer):
description = serializers.SerializerMethodField()
class Meta:
... | Remove forum siblings from forum serializer | Remove forum siblings from forum serializer
| Python | mit | ellmetha/machina-singlepageapp,ellmetha/machina-singlepageapp |
0242e64799ebd992b5bec715da956b00e1bddccd | examples/load_ui_base_instance.py | examples/load_ui_base_instance.py | import sys
import os
os.environ["QT_PREFERRED_BINDING"] = "PySide"
from Qt import QtWidgets, load_ui
def setup_ui(uifile, base_instance=None):
ui = load_ui(uifile)
if not base_instance:
return ui
else:
for member in dir(ui):
if not member.startswith('__') and \
... | import sys
import os
# Set preferred binding
# os.environ["QT_PREFERRED_BINDING"] = "PySide"
from Qt import QtWidgets, load_ui
def setup_ui(uifile, base_instance=None):
ui = load_ui(uifile)
if not base_instance:
return ui
else:
for member in dir(ui):
if not member.startswith(... | Remove preffered binding, use obj.__class__ instead of type() | Remove preffered binding, use obj.__class__ instead of type()
| Python | mit | mottosso/Qt.py,mottosso/Qt.py,fredrikaverpil/Qt.py,fredrikaverpil/Qt.py |
8258848f42142a9b539e3674e3cdaae2ffac09a1 | app/main/views/root.py | app/main/views/root.py | import os
import markdown
import yaml
from flask import render_template, render_template_string, session
from .. import main
from application import application
@main.route('/', methods=['GET'])
def root():
return render_template('index.html')
@main.route('/patterns/')
@main.route('/patterns/<pattern>')
def patte... | import os
import markdown
import yaml
from flask import render_template, render_template_string, session
from .. import main
from application import application
@main.route('/', methods=['GET'])
def root():
return render_template('index.html')
@main.route('/patterns/')
@main.route('/patterns/<pattern>')
def pat... | Fix to pass python linter, this slipped through as the master branch wasnt protected | Fix to pass python linter, this slipped through as the master branch wasnt protected
| Python | mit | ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner,ONSdigital/eq-survey-runner |
054c283d1cdccdf8277acc96435672480587f6b9 | devicehive/api_subscribe_request.py | devicehive/api_subscribe_request.py | class ApiSubscribeRequest(object):
"""Api request class."""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
... | class ApiSubscribeRequest(object):
"""Api request class."""
def __init__(self):
self._action = None
self._request = {}
self._params = {'method': 'GET',
'url': None,
'params': {},
'headers': {},
... | Add params_timestamp_key and response_timestamp_key methods | Add params_timestamp_key and response_timestamp_key methods
| Python | apache-2.0 | devicehive/devicehive-python |
c730184a6ec826f9773fa4130e59121c0fd06e4d | api_v3/misc/oauth2.py | api_v3/misc/oauth2.py | from urlparse import urljoin
from django.conf import settings
import jwt
from social_core.backends.oauth import BaseOAuth2
class KeycloakOAuth2(BaseOAuth2):
"""Keycloak OAuth authentication backend"""
name = 'keycloak'
ID_KEY = 'email'
BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE
USERINFO_URL ... | from urlparse import urljoin
from django.conf import settings
import jwt
from social_core.backends.oauth import BaseOAuth2
class KeycloakOAuth2(BaseOAuth2):
"""Keycloak OAuth authentication backend"""
name = 'keycloak'
ID_KEY = 'email'
BASE_URL = settings.SOCIAL_AUTH_KEYCLOAK_BASE
USERINFO_URL ... | Remove `username` from keycloack payload. | Remove `username` from keycloack payload.
| Python | mit | occrp/id-backend |
5208429f8e684d8604fe9a8a7eda3709ace0755c | bin/cros_repo_sync_all.py | bin/cros_repo_sync_all.py | #!/usr/bin/python
# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Stop gap sync function until cbuildbot is integrated into all builders"""
import cbuildbot
import optparse
import sys
"""Numbe... | #!/usr/bin/python
# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Stop gap sync function until cbuildbot is integrated into all builders"""
import cbuildbot_comm
import cbuildbot
import optpars... | Fix circ dep issue with cbuildbot | TBR: Fix circ dep issue with cbuildbot
| Python | bsd-3-clause | sigma/coreos-scripts,smilart/scripts,nicescale/scripts,mjg59/scripts,crawford/scripts,coreos/scripts,bcwaldon/coreos-scripts,bcwaldon/coreos-scripts,endocode/scripts,zhang0137/scripts,zhang0137/scripts,mjg59/scripts,gtank/scripts,gtank/scripts,gtank/scripts,glevand/coreos--scripts,sigma/coreos-scripts,smilart/scripts,m... |
1e7c53398e6a4a72d4027524622b32ee1819f154 | zpr.py | zpr.py | #!bin/python
import json
import lib_zpr
from flask import Flask, jsonify, make_response
app = Flask(__name__)
api_version = 'v1.0'
api_base = str('/zpr/{v}'.format(v=api_version))
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
# @app.route('/zpr/job')
#... | #!bin/python
import json
import lib_zpr
from flask import Flask, jsonify, make_response
app = Flask(__name__)
api_version = 'v1.0'
api_base = str('/zpr/{v}'.format(v=api_version))
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
# @app.route('/zpr/job')
#... | Add host and remove debug | Add host and remove debug
| Python | apache-2.0 | mattkirby/zpr-api |
8605b07f2f5951f8a0b85d3d77baa1758723fb64 | auth0/v2/authentication/users.py | auth0/v2/authentication/users.py | from .base import AuthenticationBase
class Users(AuthenticationBase):
def __init__(self, domain):
self.domain = domain
def userinfo(self, access_token):
return self.get(
url='https://%s/userinfo' % self.domain,
headers={'Authorization': 'Bearer %s' % access_token}
... | from .base import AuthenticationBase
class Users(AuthenticationBase):
"""Userinfo related endpoints.
Args:
domain (str): Your auth0 domain (e.g: username.auth0.com)
"""
def __init__(self, domain):
self.domain = domain
def userinfo(self, access_token):
"""Returns the us... | Add docstrings to Users class | Add docstrings to Users class
| Python | mit | auth0/auth0-python,auth0/auth0-python |
67d08d61186f7d9bc0026c1d867039f58872fee7 | main.py | main.py | import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, ar... | import cmd
import argparse
from Interface import *
class Lexeme(cmd.Cmd):
intro = "Welcome to Lexeme! Input '?' for help and commands."
prompt = "Enter command: "
def do_list(self, arg):
'List word database.'
listwords()
def do_quit(self, arg):
quit()
def do_add(self, ar... | Clear screen at start of program | Clear screen at start of program
| Python | mit | kdelwat/Lexeme |
68e67cee8969dbf360ed685dd8e6e76562d085d3 | examples/regression_marginals.py | examples/regression_marginals.py | """
Linear regression with marginal distributions
=============================================
"""
import seaborn as sns
sns.set(style="darkgrid")
tips = sns.load_dataset("tips")
color = sns.color_palette()[2]
g = sns.jointplot("total_bill", "tip", data=tips, kind="reg",
color=color, size=7)
g.ax_j... | """
Linear regression with marginal distributions
=============================================
"""
import seaborn as sns
sns.set(style="darkgrid")
tips = sns.load_dataset("tips")
color = sns.color_palette()[2]
g = sns.jointplot("total_bill", "tip", data=tips, kind="reg",
xlim=(0, 60), ylim=(0, 12),... | Set jointplot example axis limits in main call | Set jointplot example axis limits in main call
| Python | bsd-3-clause | uhjish/seaborn,anntzer/seaborn,lukauskas/seaborn,mwaskom/seaborn,sauliusl/seaborn,oesteban/seaborn,q1ang/seaborn,mia1rab/seaborn,aashish24/seaborn,parantapa/seaborn,cwu2011/seaborn,huongttlan/seaborn,lypzln/seaborn,dimarkov/seaborn,arokem/seaborn,clarkfitzg/seaborn,phobson/seaborn,mwaskom/seaborn,nileracecrew/seaborn,j... |
f4bf065dac9ee40e89f02115042e86c75ea3f22c | tests/basics/generator-args.py | tests/basics/generator-args.py | # Handling of "complicated" arg forms to generators
# https://github.com/micropython/micropython/issues/397
def gen(v=5):
for i in range(v):
yield i
print(list(gen()))
# Still not supported, ditto for *args and **kwargs
#print(list(gen(v=10)))
| # Handling of "complicated" arg forms to generators
# https://github.com/micropython/micropython/issues/397
def gen(v=5):
for i in range(v):
yield i
print(list(gen()))
print(list(gen(v=10)))
def g(*args, **kwargs):
for i in args:
yield i
for k, v in kwargs.items():
yield (k, v)
p... | Add testcases for "complicated" args to generator functions. | tests: Add testcases for "complicated" args to generator functions.
| Python | mit | xhat/micropython,puuu/micropython,emfcamp/micropython,hosaka/micropython,torwag/micropython,selste/micropython,MrSurly/micropython,tuc-osg/micropython,ceramos/micropython,ahotam/micropython,jmarcelino/pycom-micropython,tralamazza/micropython,ganshun666/micropython,stonegithubs/micropython,lbattraw/micropython,ceramos/m... |
c1b8f935801ca8925c0f3b001a2582136cb861ad | nani.py | nani.py | #!/usr/bin/env python3
"""Information overview for command line tools.
Usage:
nani <command>
nani -h | --help
nani --version
Options:
-h, --help Print this message and exit.
--version Print version info and exit.
"""
from docopt import docopt
import subprocess
if __name__ == '__main__':
arguments =... | #!/usr/bin/env python3
"""Information overview for command line tools.
Usage:
nani <command>
nani -h | --help
nani --version
Options:
-h, --help Print this message and exit.
--version Print version info and exit.
"""
from docopt import docopt
import sys
import subprocess
if __name__ == '__main__':
... | Call type instead of which | Call type instead of which
| Python | mit | fenhl/nani |
001a50b236e60358cf1fbe371d6d20ea72003ceb | noms.py | noms.py | #!/usr/bin/env python3
from config import WOLFRAM_KEY
import wolframalpha
POD_TITLE = 'Average nutrition facts'
QUERY = input()
def get_macros(pod_text):
items = pod_text.split("|")
for t in items:
chunks = t.split()
if 'protein' in chunks:
protein = tuple(chunks[-2::])
el... | #!/usr/bin/env python3
from config import WOLFRAM_KEY
import sys
import wolframalpha
POD_TITLE = 'Average nutrition facts'
QUERY = input()
def get_macros(pod_text):
items = pod_text.split("|")
for t in items:
chunks = t.split()
if 'protein' in chunks:
protein = chunks[-2::]
... | Add some basic error handling and remove tuples. | Add some basic error handling and remove tuples.
No need for tuples when the lists are going to be
so small. The speed difference between the two
will be minimal.
| Python | mit | brotatos/noms |
ab5d343a91374119b1983e93a57fd47ab09ebc63 | plinyproj/__version__.py | plinyproj/__version__.py | <<<<<<< HEAD
__version_info__ = (0, 6, 0)
=======
__version_info__ = (0, 5, 7)
>>>>>>> hotfix/0.5.7
__version__ = '.'.join([str(i) for i in __version_info__])
| __version_info__ = (0, 6, 0)
__version__ = '.'.join([str(i) for i in __version_info__])
| Fix version conflict and bump to 0.6 | Fix version conflict and bump to 0.6
| Python | mit | bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject,bwhicks/PlinyProject |
b2ffa1616c1ca31916047e1524e73395f0f45936 | bokeh/charts/tests/test_stats.py | bokeh/charts/tests/test_stats.py | import pytest
from bokeh.charts.stats import Bins
from bokeh.models import ColumnDataSource
@pytest.fixture
def ds(test_data):
return ColumnDataSource(test_data.auto_data)
def test_explicit_bin_count(ds):
b = Bins(source=ds, column='mpg', bin_count=2)
assert len(b.bins) == 2
def test_auto_bin_count(d... | import pytest
from bokeh.charts.stats import Bins
from bokeh.models import ColumnDataSource
@pytest.fixture
def ds(test_data):
return ColumnDataSource(test_data.auto_data)
def test_explicit_bin_count(ds):
b = Bins(source=ds, column='mpg', bin_count=2)
assert len(b.bins) == 2
def test_auto_bin_count(d... | Add auto binning test to stats. | Add auto binning test to stats.
| Python | bsd-3-clause | percyfal/bokeh,msarahan/bokeh,schoolie/bokeh,mindriot101/bokeh,Karel-van-de-Plassche/bokeh,timsnyder/bokeh,dennisobrien/bokeh,aiguofer/bokeh,phobson/bokeh,ericmjl/bokeh,phobson/bokeh,draperjames/bokeh,timsnyder/bokeh,stonebig/bokeh,timsnyder/bokeh,stonebig/bokeh,ptitjano/bokeh,maxalbert/bokeh,jakirkham/bokeh,DuCorey/bo... |
ea7b84d4685a48e13bd58cfd52d14fff4ed7001a | main.py | main.py | from game import Game
from self_play import SelfPlay
g = Game()
runtime = SelfPlay(g)
runtime.play()
| from game import Game
from self_play import SelfPlay
import game_stats_tree
g = Game()
runtime = SelfPlay(g)
runtime.play()
game_stats_tree = game_stats_tree.Node()
update_game_stats(game_stats_tree, runtime.log) | Add log to self play | Add log to self play
| Python | mit | misterwilliam/connect-four |
df4967b5e71e32f70e97d52a320d9b32d70095b7 | main.py | main.py | #!/usr/bin/env python3
import sys
from appscript import *
from termcolor import colored, cprint
def open(itunes):
return itunes.activate()
def close(itunes):
return itunes.quit()
def now_playing(itunes):
track = itunes.current_track.get()
return print('{} - {}\n{}'.format(colored(track.name(), at... | #!/usr/bin/env python3
import sys
from appscript import *
from termcolor import colored, cprint
def open(itunes):
return itunes.activate()
def close(itunes):
return itunes.quit()
def is_playing(itunes):
return itunes.player_state.get() == k.playing
def now_playing(itunes):
if not is_playing(itu... | Check if song is_playing before play | Check if song is_playing before play
| Python | mit | kshvmdn/nowplaying |
8ef4417a95fdd9b5dde26583a9624181639df600 | nix/__init__.py | nix/__init__.py | # Copyright (c) 2014, German Neuroinformatics Node (G-Node)
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the BSD License. See
# LICENSE file in the root of the Project.
from nix.core import File, FileMode, Block, DataTy... | # Copyright (c) 2014, German Neuroinformatics Node (G-Node)
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted under the terms of the BSD License. See
# LICENSE file in the root of the Project.
from nix.core import File, FileMode, Block, DataTy... | Remove mixins from namespace after monkey patching | Remove mixins from namespace after monkey patching
After their job is done, they can go home ;-)
| Python | bsd-3-clause | stoewer/nixpy,stoewer/nixpy |
69d6d87688d9f805689407b839c4fb88f397269e | cla_backend/apps/status/views.py | cla_backend/apps/status/views.py | from django.db import connection, DatabaseError
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from cla_common.smoketest import smoketest
from moj_irat.views import PingJsonView as BasePingJsonView
class JSONResponse(HttpRes... | from django.db import connection, DatabaseError
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from cla_common.smoketest import smoketest
from moj_irat.views import PingJsonView as BasePingJsonView
class JSONResponse(HttpRes... | Revert "Deliberately break status check" | Revert "Deliberately break status check"
This reverts commit da7f671ec287afc0c42f58794053b8bf69ddf620.
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend |
661c9413900d74baa308feec3232bc3c9edee361 | repl.py | repl.py | #!/usr/bin/python3
"""Command line runtime for Tea."""
from runtime import tokenizer, parser, ast, std
TEA_VERSION = "0.0.3-dev"
TEA_TITLE = "Tea @" + TEA_VERSION
CLI_SYMBOL = "#> "
CLI_SPACE = " " * 3
CLI_RESULT = "<- "
def interpret(expression, context):
"""Interpret an expression by tokenizing, parsing and e... | #!/usr/bin/python3
"""Command line runtime for Tea."""
import runtime.lib
from runtime import tokenizer, parser, env
TEA_VERSION = "0.0.4-dev"
TEA_TITLE = "Tea @" + TEA_VERSION
CLI_SYMBOL = "#> "
CLI_SPACE = " " * 3
CLI_RESULT = "<- "
def interpret(expression, context):
"""Interpret an expression by tokenizing,... | Fix bugs and increment version number | Fix bugs and increment version number
| Python | mit | lnsp/tea,lnsp/tea |
542ec659bf8545fcb50d0a4df068aa28d073dacc | cmsplugin_zinnia/forms.py | cmsplugin_zinnia/forms.py | """Forms for cmsplugin-zinnia"""
from django import forms
from django.utils.translation import ugettext as _
from cmsplugin_zinnia.models import CalendarEntriesPlugin
class CalendarEntriesAdminForm(forms.ModelForm):
"""
Admin Form for CalendarEntriesPlugin
"""
def clean(self):
data = self.cl... | """Forms for cmsplugin-zinnia"""
from django import forms
from django.utils.translation import ugettext as _
from cmsplugin_zinnia.models import CalendarEntriesPlugin
class CalendarEntriesAdminForm(forms.ModelForm):
"""
Admin Form for CalendarEntriesPlugin
"""
def clean(self):
data = self.cl... | Add fields attribute to CalendarEntriesAdminForm. | Add fields attribute to CalendarEntriesAdminForm.
Django 1.8 requires either the 'fields' or 'exclude' attribute to be set for modelForm. Omitting any definition of the fields to use will result in an ImproperlyConfigured exception. See https://docs.djangoproject.com/en/1.8/ref/forms/models/. | Python | bsd-3-clause | bittner/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,django-blog-zinnia/cmsplugin-zinnia,bittner/cmsplugin-zinnia,bittner/cmsplugin-zinnia |
97418e6815faacbaa46a3a29bef0c4c0454bede1 | urls.py | urls.py | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import url, include
urlpatterns = [
url(r'^auth/', include('helios_auth.urls')),
url(r'^helios/', include('helios.urls')),
# SHOULD BE REPLACED BY APACHE STATIC PATH
url(r'booth/(?P<path>.*)$', 'django.views.static.serve', ... | # -*- coding: utf-8 -*-
from django.conf import settings
from django.conf.urls import url, include
from django.views.static import serve
urlpatterns = [
url(r'^auth/', include('helios_auth.urls')),
url(r'^helios/', include('helios.urls')),
# SHOULD BE REPLACED BY APACHE STATIC PATH
url(r'booth/(?P<pat... | Support for string view arguments to url() will be removed | [DJ1.10] Support for string view arguments to url() will be removed
| Python | apache-2.0 | benadida/helios-server,shirlei/helios-server,shirlei/helios-server,benadida/helios-server,benadida/helios-server,shirlei/helios-server,benadida/helios-server,shirlei/helios-server,shirlei/helios-server,benadida/helios-server |
96a2839da4963303ace6e147bb436d2e24a5efd4 | main.py | main.py | from crawler import tasks
from crawler.db import db_mongodb as db
from time import sleep
from celery.app.control import Control
from crawler.celery import app
# Temporal solution
db.insert_url("http://www.inf.upol.cz")
def is_worker_running():
inspect = app.control.inspect()
active = inspect.active()
s... | from crawler import tasks
from crawler.db import db_mongodb as db
from time import sleep
from celery.app.control import Control
from crawler.celery import app
# Temporal solution
db.insert_url("http://www.upol.cz")
db.insert_url("http://www.cmtf.upol.cz")
db.insert_url("http://www.lf.upol.cz")
db.insert_url("http://w... | Fix is_worker_running + new seed | Fix is_worker_running + new seed
| Python | mit | UPOLSearch/UPOL-Search-Engine,UPOLSearch/UPOL-Search-Engine,UPOLSearch/UPOL-Search-Engine,UPOLSearch/UPOL-Search-Engine |
dc87229eeeef35325d72a1b97e0790204673a5aa | main.py | main.py | from curses import wrapper
from ui import ChatUI
from client import Client
import ConfigParser
def main(stdscr):
cp = ConfigParser.ConfigParser()
cp.read('config.cfg')
username = cp.get('credentials', 'username')
password = cp.get('credentials', 'password')
stdscr.clear()
ui = ChatUI(stdscr)
... | from curses import wrapper
from ui import ChatUI
from client import Client
import configparser
def main(stdscr):
cp = configparser.ConfigParser()
cp.read('config.cfg')
username = cp.get('credentials', 'username')
password = cp.get('credentials', 'password').encode('utf-8')
stdscr.clear()
ui = ... | Make it work with Py3 | Make it work with Py3
| Python | mit | vhf/kwak_cli |
1fa3c49f692e311e67db4f128928ac93e51830ff | babybuddy/tests/tests_commands.py | babybuddy/tests/tests_commands.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth.models import User
from django.core.management import call_command
from core.models import Child
class CommandsTestCase(TestCase):
def test_migrate(self):
call_command('migrate', ver... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TransactionTestCase
from django.contrib.auth.models import User
from django.core.management import call_command
from core.models import Child
class CommandsTestCase(TransactionTestCase):
def test_migrate(self):
call_... | Fix and re-enable the reset management command test. | Fix and re-enable the reset management command test.
Not 100% sure of why this fixes the issue - it appears that changes to django.test.TestCase in Django 2.0 led to the test failing.
| Python | bsd-2-clause | cdubz/babybuddy,cdubz/babybuddy,cdubz/babybuddy |
3157151d835377a4ddf80d5514ea1edc0a2a8203 | account/decorators.py | account/decorators.py | import functools
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.utils.decorators import available_attrs
from account.utils import handle_redirect_to_login
def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Decorator for views that checks that the use... | import functools
from django.contrib.auth import REDIRECT_FIELD_NAME
from account.utils import handle_redirect_to_login
def login_required(func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
"""
Decorator for views that checks that the user is logged in, redirecting
to the log in page i... | Fix a 3.0 compat issue | Fix a 3.0 compat issue
| Python | mit | pinax/django-user-accounts,pinax/django-user-accounts |
b1ffe99226cae1da873d249d8299b4b6b721dde3 | go_contacts/server.py | go_contacts/server.py | """
Cyclone application for Vumi Go contacts API.
"""
from go_api.cyclone import ApiApplication
from go_contacts.backends.riak import RiakContactsBackend
class ContactsApi(ApiApplication):
"""
:param IContactsBackend backend:
A backend that provides a contact collection factory.
"""
def __in... | """
Cyclone application for Vumi Go contacts API.
"""
from go_api.cyclone.handlers import ApiApplication
from go_contacts.backends.riak import RiakContactsBackend
class ContactsApi(ApiApplication):
"""
:param IContactsBackend backend:
A backend that provides a contact collection factory.
"""
... | Read config file passed as --appopts param. | Read config file passed as --appopts param.
| Python | bsd-3-clause | praekelt/go-contacts-api,praekelt/go-contacts-api |
63a79aaea5aa7124d753a2d7b70645bd2e1f4419 | globus_cli/parser/parse_cmd.py | globus_cli/parser/parse_cmd.py | from globus_cli.parser.shared_parser import GlobusCLISharedParser
from globus_cli.parser.command_tree import build_command_tree
def _gen_parser():
"""
Produces a top-level argument parser built out of all of the various
subparsers for different services.
"""
# create the top parser and give it sub... | from __future__ import print_function
import sys
from globus_cli.parser.shared_parser import GlobusCLISharedParser
from globus_cli.parser.command_tree import build_command_tree
def _gen_parser():
"""
Produces a top-level argument parser built out of all of the various
subparsers for different services.
... | Add special handling for NotImplementedError | Add special handling for NotImplementedError
If the function called by run_command() raises a NotImplementedError,
don't print the full stacktrace. Do a mild amount of custom formatting,
then exit with status 1 (failure).
| Python | apache-2.0 | globus/globus-cli,globus/globus-cli |
c104880b195ade7e202894de424bd8f5c1764251 | scripts/2a-set-aircraft-poses.py | scripts/2a-set-aircraft-poses.py | #!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import os.path
sys.path.append('../lib')
import Pose
import ProjectMgr
# for all the images in the project image_dir, detect features using the
# specifi... | #!/usr/bin/python
import sys
sys.path.insert(0, "/usr/local/opencv-2.4.11/lib/python2.7/site-packages/")
import argparse
import commands
import cv2
import fnmatch
import os.path
sys.path.append('../lib')
import Pose
import ProjectMgr
# for all the images in the project image_dir, detect features using the
# specifi... | Add support for pix4d meta file format. | Add support for pix4d meta file format.
Former-commit-id: 7330412d726bf8cc4bd9d8659fb067e4921af798 | Python | mit | UASLab/ImageAnalysis |
2799b5f2cf9222313ccfe70d0663070a9950788a | sublimelinter/modules/php.py | sublimelinter/modules/php.py | # -*- coding: utf-8 -*-
# php.py - sublimelint package for checking php files
import re
from base_linter import BaseLinter
CONFIG = {
'language': 'php',
'executable': 'php',
'lint_args': ('-l', '-d display_errors=On')
}
class Linter(BaseLinter):
def parse_errors(self, view, errors, lines, errorUnde... | # -*- coding: utf-8 -*-
# php.py - sublimelint package for checking php files
import re
from base_linter import BaseLinter
CONFIG = {
'language': 'php',
'executable': 'php',
'lint_args': ('-l', '-d display_errors=On')
}
class Linter(BaseLinter):
def parse_errors(self, view, errors, lines, errorUnde... | Change PHP error matching regex | Change PHP error matching regex
On my system (OS X 10.7 w/stock PHP 5.3.8), the PHP lint frequently
misses errors due to over-specificity in the regex. This one is
catching them.
| Python | mit | uschmidt83/SublimeLinter-for-ST2,SublimeLinter/SublimeLinter-for-ST2,benesch/sublime-linter,benesch/sublime-linter,uschmidt83/SublimeLinter-for-ST2,tangledhelix/SublimeLinter-for-ST2,biodamasceno/SublimeLinter-for-ST2,biodamasceno/SublimeLinter-for-ST2,tangledhelix/SublimeLinter-for-ST2,SublimeLinter/SublimeLinter-for-... |
2473c714bb89cbd1d741b5e20b32397ffc6b6bd7 | samp_client/constants.py | samp_client/constants.py | from __future__ import unicode_literals, absolute_import
# Opcode definitions
OPCODE_INFO = 'i'
OPCODE_RULES = 'r'
OPCODE_CLIENTS = 'c'
OPCODE_CLIENTS_DETAILED = 'd'
OPCODE_RCON = 'x'
OPCODE_PSEUDORANDOM = 'p'
| from __future__ import unicode_literals, absolute_import
# Opcode definitions
OPCODE_INFO = 'i'
OPCODE_RULES = 'r'
OPCODE_CLIENTS = 'c'
OPCODE_CLIENTS_DETAILED = 'd'
OPCODE_RCON = 'x'
OPCODE_PSEUDORANDOM = 'p'
RCON_CMDLIST = 'cmdlist'
RCON_VARLIST = 'varlist'
RCON_EXIT = 'exit'
RCON_ECHO = 'echo'
RCON_HOSTNAME = 'hos... | Define constatns for rcon commands | Define constatns for rcon commands
| Python | mit | mick88/samp-client |
51701b35d9ef9401abf0d86fd5726e669326390d | scripts/nipy_4dto3D.py | scripts/nipy_4dto3D.py | #!/usr/bin/env python
''' Tiny script to write 4D files in any format that we read (nifti,
analyze, MINC, at the moment, as nifti 3D files '''
import os
import sys
import nipy.io.imageformats as nii
if __name__ == '__main__':
try:
fname = sys.argv[1]
except IndexError:
raise OSError('Expecti... | #!/usr/bin/env python
''' Tiny script to write 4D files in any format that we read (nifti,
analyze, MINC, at the moment, as nifti 3D files '''
import os
import nipy.externals.argparse as argparse
import nipy.io.imageformats as nii
def main():
# create the parser
parser = argparse.ArgumentParser()
# add ... | Use argparse for 4D to 3D | Use argparse for 4D to 3D | Python | bsd-3-clause | nipy/nipy-labs,arokem/nipy,bthirion/nipy,alexis-roche/register,arokem/nipy,alexis-roche/niseg,bthirion/nipy,alexis-roche/nipy,bthirion/nipy,nipy/nireg,alexis-roche/nireg,nipy/nipy-labs,alexis-roche/nipy,alexis-roche/nipy,bthirion/nipy,alexis-roche/register,alexis-roche/nireg,nipy/nireg,alexis-roche/register,alexis-roch... |
3220b356297ec5fe61888a906543d0ee993f9f31 | website/tests/test_database.py | website/tests/test_database.py | import database
def test_encode_csv():
attributes = (
# strand, ref, alt, cdna_pos, exon, protein_id, is_ptm
'+', 'R', 'H', 204, 'exon1', 123, False
)
result = database.encode_csv(*attributes)
assert result == '+RH0cc:exon1:7b'
def test_decode_csv():
encoded_csv = '+RH0cc:exon1:7... | import database
def test_encode_csv():
test_data = (
# strand, ref, alt, cdna_pos, exon, protein_id, is_ptm
(('+', 'R', 'H', 204, 'exon1', 123, False), '+RH0cc:exon1:7b'),
(('-', 'R', 'H', 204, 'exon1', 123, True), '-RH1cc:exon1:7b'),
)
for attributes, correct_result in test_data:
... | Add more tests to database | Add more tests to database
| Python | lgpl-2.1 | reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visu... |
6398f7ad03aaa8547eaa860ba7ef5d2051ca2955 | src/newspeak/urls.py | src/newspeak/urls.py | from django.conf.urls import patterns, url
from surlex.dj import surl
from .feeds import NewspeakRSSFeed, NewspeakAtomFeed
urlpatterns = patterns('',
# surl(r'^$', SomeView.as_view(),
# name='newspeak_home'
# ),)
# Static redirect to the RSS feed, until we have a
# page to show here.
(... | from django.conf.urls import patterns, url
from django.views.generic.base import RedirectView
from surlex.dj import surl
from .feeds import NewspeakRSSFeed, NewspeakAtomFeed
urlpatterns = patterns('',
# surl(r'^$', SomeView.as_view(),
# name='newspeak_home'
# ),)
# Static redirect to the RSS f... | Use class-based generic view for redirect. | Use class-based generic view for redirect.
Fixes #29; legacy method-based generic views are deprecated in Django. | Python | bsd-3-clause | bitsoffreedom/newspeak |
090a11c08839eae78e0ca6ec963b66ac3876ba35 | circuits/web/events.py | circuits/web/events.py | # Module: events
# Date: 3rd February 2009
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Events
This module implements the necessary Events needed.
"""
from circuits import Event
class WebEvent(Event):
channels = ("web",)
class Request(WebEvent):
"""Request(WebEvent) -> Reques... | # Module: events
# Date: 3rd February 2009
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Events
This module implements the necessary Events needed.
"""
from circuits import Event
class WebEvent(Event):
channels = ("web",)
success = True
failure = True
class Request(WebEv... | Move success/failure properties into WebEvent base class. | Move success/failure properties into WebEvent base class.
| Python | mit | nizox/circuits,eriol/circuits,eriol/circuits,treemo/circuits,eriol/circuits,treemo/circuits,treemo/circuits |
3222f720cc46a0e21f2ae5b2a9e8d4695c71a24e | changes/api/author_build_index.py | changes/api/author_build_index.py | from __future__ import absolute_import, division, unicode_literals
from flask import session
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
if author_id == 'me':... | from __future__ import absolute_import, division, unicode_literals
from flask import session
from sqlalchemy.orm import joinedload
from changes.api.base import APIView
from changes.models import Author, Build
class AuthorBuildIndexAPIView(APIView):
def _get_author(self, author_id):
if author_id == 'me':... | Add source to author build index query | Add source to author build index query
| Python | apache-2.0 | dropbox/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes |
bf46826e2e81ee071350c69ccc136ccedff330aa | UCP/news_event/api.py | UCP/news_event/api.py | """
API file for news and event app
consists of the news list, detail and add api
events list, detail and add api
"""
from django.utils import timezone
from rest_framework import status, mixins
from rest_framework.authentication import TokenAuthentication, BasicAuthentication
from rest_framework.permissions import I... | """
API file for news and event app
consists of the news list, detail and add api
events list, detail and add api
"""
from django.utils import timezone
from rest_framework import status, mixins
from rest_framework.authentication import TokenAuthentication, BasicAuthentication
from rest_framework.permissions import I... | Switch from modelviewset to mixins | Switch from modelviewset to mixins
| Python | bsd-3-clause | BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP,BuildmLearn/University-Campus-Portal-UCP |
43103f59b4409ef15913d0394327d25959721afa | bin/trigger_upload.py | bin/trigger_upload.py | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | #!/bin/env python
# -*- coding: utf8 -*-
""" Triggers an upload process with the specified raw.xz URL. """
import argparse
import logging
import logging.config
import multiprocessing.pool
import fedmsg.config
import fedimg.uploader
logging.config.dictConfig(fedmsg.config.load_config()['logging'])
log = logging.getLo... | Move logic inside the main function | scripts: Move logic inside the main function
Signed-off-by: Sayan Chowdhury <5f0367a2b3b757615b57f51d912cf16f2c0ad827@gmail.com>
| Python | agpl-3.0 | fedora-infra/fedimg,fedora-infra/fedimg |
7711e9d04d81c4b948599f7454b87274a8f5ad9e | src/py3flowtools/flowd_wrapper.py | src/py3flowtools/flowd_wrapper.py | # flowtools_wrapper.py
# Copyright 2014 Bo Bayles (bbayles@gmail.com)
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import ... | # flowtools_wrapper.py
# Copyright 2014 Bo Bayles (bbayles@gmail.com)
# See http://github.com/bbayles/py3flowtools for documentation and license
from __future__ import division, print_function, unicode_literals
import io
import os
import sys
from .flow_line import FlowLine
if sys.version_info.major < 3:
import ... | Fix up error handling for flowd | Fix up error handling for flowd
| Python | mit | bbayles/py3flowtools |
423243bce63da26ca4c5ea784376488ea8997873 | reg/__init__.py | reg/__init__.py | # flake8: noqa
#from .registry import Registry, CachingKeyLookup, Lookup
from .dispatch import dispatch, dispatch_method, auto_methodify
from .mapply import mapply
from .arginfo import arginfo
from .argextract import KeyExtractor
from .sentinel import Sentinel, NOT_FOUND
from .error import RegistrationError, KeyExtract... | # flake8: noqa
from .dispatch import (dispatch, dispatch_method,
auto_methodify, clean_dispatch_methods)
from .mapply import mapply
from .arginfo import arginfo
from .argextract import KeyExtractor
from .sentinel import Sentinel, NOT_FOUND
from .error import RegistrationError, KeyExtractorError
f... | Clean dispatch methods exposed to api. | Clean dispatch methods exposed to api.
| Python | bsd-3-clause | taschini/reg,morepath/reg |
b706c8130c8f9aa56a78338a078a737fbb8ca28d | run.py | run.py | from bucky import create_app
app = create_app('development')
if __name__ == "__main__":
app.run(debug=True)
| from bucky import create_app
app = create_app('development')
if __name__ == "__main__":
app.run()
| Remove debug mode default setting of true | Remove debug mode default setting of true
| Python | mit | JoshuaOndieki/buckylist,JoshuaOndieki/buckylist |
eac0b6cb28e86b43d6459d631f10fd3d7a7b2287 | cli/hdfs.py | cli/hdfs.py | #!/usr/local/bin/python2.7
# -*- coding: utf-8 -*-
"""
Intelligence Platform CLI Fabric File
"""
__author__ = 'Dongjoon Hyun (dongjoon@apache.org)'
__license__ = 'Apache License'
__version__ = '0.2'
from fabric.api import *
@task
def ls(inpath='/'):
"""
fab hdfs.ls:/sample
"""
cmd = '/usr/bin/hadoop... | #!/usr/local/bin/python2.7
# -*- coding: utf-8 -*-
"""
Intelligence Platform CLI Fabric File
"""
__author__ = 'Dongjoon Hyun (dongjoon@apache.org)'
__license__ = 'Apache License'
__version__ = '0.2'
from fabric.api import *
@task
def ls(inpath='/'):
"""
fab hdfs.ls:/sample
"""
cmd = '/usr/bin/hadoop... | Change default value for line number | Change default value for line number
| Python | apache-2.0 | dongjoon-hyun/tools,dongjoon-hyun/tools,dongjoon-hyun/tools,dongjoon-hyun/tools,dongjoon-hyun/tools |
94c149f950a24a5034082c9b177037307f9ed809 | hdfs.py | hdfs.py | import sys, os
import shlex, subprocess
def hdfs_fetch_file(hdfs_path, local_path):
print "Getting %s..."
command = "hadoop fs -get %s %s" % (hdfs_path, local_path)
subprocess.call(shlex.split(command))
print "Done getting %s..."
def hdfs_push_file(local_path, hdfs_path):
print "Putting %s..."
command = "... | import sys, os
import shlex, subprocess
import time
def hdfs_fetch_file(hdfs_path, local_path):
print "Getting %s..." % (hdfs_path)
start = time.time()
command = "hadoop fs -get %s %s" % (hdfs_path, local_path)
subprocess.call(shlex.split(command))
end = time.time()
print "Done getting %s, took %d seconds"... | Add some timing and fix debug output from HDFS client. | Add some timing and fix debug output from HDFS client.
| Python | mit | ms705/napper |
ee362795318507b757795e0be4c45d68c17cd28f | roll.py | roll.py | #!/usr/bin/env python
"""roll simulates rolling polyhedral dice."""
# roll.py
# Michael McMahon
from random import randrange
# Die roll function
# This function rolls polyhedral dice. Example: To roll a d8, use roll(8).
def roll(diefaces):
"""Simulate rolling polyhedral dice"""
return randrange(1, int(die... | #!/usr/bin/env python
"""roll simulates rolling polyhedral dice."""
# roll.py
# roll v1.0
# Michael McMahon
from random import randrange
# Die roll function
# This function rolls polyhedral dice. Example: To roll a d8, use roll(8).
def roll(diefaces):
"""Simulate rolling polyhedral dice"""
assert isinsta... | Add assert to prevent invalid input | Add assert to prevent invalid input
| Python | agpl-3.0 | TechnologyClassroom/dice-mechanic-sim,TechnologyClassroom/dice-mechanic-sim |
59c29cbf7f41221b412253ec1f0444496bd934fa | tube.py | tube.py | """Configuration for testtube.
Automatically run tests when files change by running: stir
See: https://github.com/thomasw/testtube
For flake8, don't forget to install:
* flake8-quotes
"""
from testtube.helpers import Flake8, Helper, Nosetests
class ScreenClearer(Helper):
command = 'clear'
def success(self, ... | """Configuration for testtube.
Automatically run tests when files change by running: stir
See: https://github.com/thomasw/testtube
For flake8, don't forget to install:
* flake8-quotes
"""
from testtube.helpers import Flake8, Helper, Nosetests
class ScreenClearer(Helper):
command = 'clear'
def success(self, ... | Remove dirty lies from doctstring | Remove dirty lies from doctstring
This was a leftover from wherever I originally copied this config from.
| Python | mit | blaix/tdubs |
2c6ff2b65ea291816221fe996fb282c2c4a74dd7 | install_steps/create_bosh_cert.py | install_steps/create_bosh_cert.py | def do_step(context):
call("mkdir -p ./bosh", shell=True)
call("mkdir -p ./bosh/manifests", shell=True)
# Generate the private key and certificate
call("sh create_cert.sh", shell=True)
call("cp bosh.key ./bosh/bosh", shell=True)
with open ('bosh_cert.pem', 'r') as tmpfile:
ssh_cert = t... | from subprocess import call
from os import makedirs
from shutil import copy
def do_step(context):
makedirs("bosh/manifests")
# Generate the private key and certificate
call("sh create_cert.sh", shell=True)
copy("bosh.key", "./bosh/bosh")
with open ('bosh_cert.pem', 'r') as tmpfile:
ssh_ce... | Use python libs to do file operations | Use python libs to do file operations
| Python | apache-2.0 | cf-platform-eng/bosh-azure-template,cf-platform-eng/bosh-azure-template |
21f3d1957258f87e45ddcb39a17ecf2143c203b0 | kindred/pycorenlp.py | kindred/pycorenlp.py | # Temporary inclusion of pycorenlp code for easier edits
# https://github.com/smilli/py-corenlp
import json, requests
import six
class StanfordCoreNLP:
def __init__(self, server_url):
self.server_url = server_url
def annotate(self, text, properties={}):
assert isinstance(text, six.string_types),"text must be ... | # Temporary inclusion of pycorenlp code for easier edits
# https://github.com/smilli/py-corenlp
import json, requests
import six
class StanfordCoreNLP:
useSessions = True
sessions = {}
def __init__(self, server_url):
self.server_url = server_url
if StanfordCoreNLP.useSessions:
if not server_url in Stanfor... | Add experimental sessions code for CoreNLP requests | Add experimental sessions code for CoreNLP requests
| Python | mit | jakelever/kindred,jakelever/kindred |
539f78c8ea4ca1692ae27a2d0bdc01004b5ad471 | examples/plot_humidity.py | examples/plot_humidity.py | import matplotlib.pyplot as plt
from aux2mongodb import MagicWeather
from datetime import date
m = MagicWeather(auxdir='/fact/aux')
df = m.read_date(date(2015, 12, 31))
df.plot(x='timestamp', y='humidity', legend=False)
plt.ylabel('Humidity / %')
plt.show()
| import matplotlib.pyplot as plt
from aux2mongodb import MagicWeather, PfMini
import pandas as pd
from tqdm import tqdm
import datetime
plt.style.use('ggplot')
magic_weather = MagicWeather(auxdir='/fact/aux')
pf_mini = PfMini(auxdir='/fact/aux')
dates = pd.date_range('2015-10-20', datetime.date.today())
outside = pd... | Modify example to make camera vs. outside humidity plot | Modify example to make camera vs. outside humidity plot
| Python | mit | fact-project/aux2mongodb |
58e5a7e332015e05498edf0f4012fc6b817b99b9 | longclaw/longclawproducts/tests.py | longclaw/longclawproducts/tests.py | from wagtail.tests.utils import WagtailPageTests
from longclaw.utils import maybe_get_product_model
from longclaw.tests.products.models import ProductIndex
from longclaw.tests.utils import ProductVariantFactory
from longclaw.longclawproducts.serializers import ProductVariantSerializer
class TestProducts(WagtailPageTes... | from wagtail.tests.utils import WagtailPageTests
from longclaw.utils import maybe_get_product_model
from longclaw.tests.products.models import ProductIndex
from longclaw.tests.utils import ProductVariantFactory
from longclaw.longclawproducts.serializers import ProductVariantSerializer
class TestProducts(WagtailPageTes... | Add a test for product title | Add a test for product title
| Python | mit | JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw,JamesRamm/longclaw |
e0c9f12463f1e4cc17eefbf8909118604695a23d | oscar/apps/search/search_indexes.py | oscar/apps/search/search_indexes.py | from haystack import indexes
from django.db.models import get_model
class ProductIndex(indexes.SearchIndex, indexes.Indexable):
"""
Base class for products solr index definition. Overide by creating your
own copy of oscar.search_indexes.py
"""
text = indexes.EdgeNgramField(document=True, use_tem... | from haystack import indexes
from django.db.models import get_model
class ProductIndex(indexes.SearchIndex, indexes.Indexable):
"""
Base class for products solr index definition. Overide by creating your
own copy of oscar.search_indexes.py
"""
text = indexes.EdgeNgramField(document=True, use_tem... | Fix issue with latest changes in haystack | Fix issue with latest changes in haystack
A merge into haystack has resulted in an additional argument for
``index_queryset``, I updated the search index for Oscar's product
to fix the issue.
| Python | bsd-3-clause | MatthewWilkes/django-oscar,jmt4/django-oscar,michaelkuty/django-oscar,jlmadurga/django-oscar,rocopartners/django-oscar,sonofatailor/django-oscar,django-oscar/django-oscar,makielab/django-oscar,Bogh/django-oscar,jinnykoo/christmas,WadeYuChen/django-oscar,faratro/django-oscar,eddiep1101/django-oscar,jinnykoo/christmas,it... |
957c74c5083eaab466fc72e21afc929267191676 | openedx/features/job_board/views.py | openedx/features/job_board/views.py | from django.views.generic.list import ListView
from edxmako.shortcuts import render_to_response
from .models import Job
class JobListView(ListView):
model = Job
context_object_name = 'job_list'
paginate_by = 10
template_name = 'features/job_board/job_list.html'
ordering = ['-created']
templ... | from django.views.generic.list import ListView
from edxmako.shortcuts import render_to_response
from .models import Job
class JobListView(ListView):
model = Job
context_object_name = 'job_list'
paginate_by = 10
template_name = 'features/job_board/job_list.html'
ordering = ['-created']
templ... | Remove get_context_data override and use the paginator total count instead | Remove get_context_data override and use the paginator total count instead
| Python | agpl-3.0 | philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform,philanthropy-u/edx-platform |
7eac938f0a4726beb1eb01d32486dfeb0e57ff3a | h2o-hadoop/tests/python/pyunit_s3_import_export.py | h2o-hadoop/tests/python/pyunit_s3_import_export.py | #! /usr/env/python
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
from tests import pyunit_utils
from datetime import datetime
import h2o
from pandas.util.testing import assert_frame_equal
def s3_import_export():
local_frame = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.cs... | #! /usr/env/python
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
from tests import pyunit_utils
from datetime import datetime
import h2o
import uuid
from pandas.util.testing import assert_frame_equal
def s3_import_export():
local_frame = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg... | Fix flaky Hadoop smoke tests - make sure the exported files are unique | Fix flaky Hadoop smoke tests - make sure the exported files are unique
| Python | apache-2.0 | h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-3,michalkurka/h2o-3,h2oai/h2o-3,h2oai/h2o-dev,h2oai/h2o-dev,michalkurka/h2o-3,michalkurka/h2o-3,h2oai/h2o-dev,michalkurka/h2o-3,michalkurka/h2o-3 |
00feeb0d9515d5f47a9c22244edd817c629a96e6 | conftest.py | conftest.py | import os
import sys
from django.conf import settings
def pytest_configure():
sys.path.append(os.path.join(os.path.dirname(__file__), 'tests'))
settings.configure(
INSTALLED_APPS = (
'caspy',
'rest_framework',
'testapp',
),
ROOT_URLCONF = 'caspy.urls... | import os
import sys
from django.conf import settings
def pytest_configure():
sys.path.append(os.path.join(os.path.dirname(__file__), 'tests'))
settings.configure(
INSTALLED_APPS = (
'caspy',
'rest_framework',
'testapp',
),
ROOT_URLCONF = 'caspy.urls... | Set MIDDLEWARE_CLASSES so Django will stop complaining | Set MIDDLEWARE_CLASSES so Django will stop complaining
| Python | bsd-3-clause | altaurog/django-caspy,altaurog/django-caspy,altaurog/django-caspy |
d869b5b31eddcbc1303affb1555c2117a365b64a | models/recordsfields_artemplate.py | models/recordsfields_artemplate.py | from openerp import fields, models, api
from base_olims_model import BaseOLiMSModel
schema = (fields.Many2one(string='Services',
comodel_name='olims.analysis_service',
domain="[('category', '=', Category)]",
relation='recordfield_service'),
fields.Bool... | from openerp import fields, models, api
from base_olims_model import BaseOLiMSModel
schema = (fields.Many2one(string='Services',
comodel_name='olims.analysis_service',
domain="[('category', '=', Category)]",
relation='recordfield_service'),
fields.Bool... | Define a model for 'Analyses' in Analysis Request inherit from records_field_artemplate. | Define a model for 'Analyses' in Analysis Request inherit from records_field_artemplate.
| Python | agpl-3.0 | sciCloud/OLiMS,sciCloud/OLiMS,yasir1brahim/OLiMS,sciCloud/OLiMS |
a7534be2fdc147321f180aee38c8d5879bd3f4ad | stestr/tests/base.py | stestr/tests/base.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | Make unit test attachment fixtures always enabled | Make unit test attachment fixtures always enabled
The code used in the base test class was copied from other projects and
made the stdout, stderr, and logging attachments enabled optionally by
env variables. However there is no reason to do that since if there is
any output it is best to capture it instead of dropping... | Python | apache-2.0 | mtreinish/stestr,mtreinish/stestr,masayukig/stestr,masayukig/stestr |
1091d541db93f533f1e078118825257bc3789371 | data/streaming_test.py | data/streaming_test.py | #!/usr/bin/env python
#
# test a streaming app by dumping files from one directory
# into another, at a specified rate
#
# <streaming_test> srcPath targetPath waitTime
#
# example:
# data/streaming_test.py /groups/ahrens/ahrenslab/Misha/forJeremy_SparkStreamingSample/ /nobackup/freeman/buffer/ 1
#
import sys, os, tim... | #!/usr/bin/env python
#
# test a streaming app by dumping files from one directory
# into another, at a specified rate
#
# <streaming_test> srcPath targetPath waitTime
#
# example:
# data/streaming_test.py /groups/ahrens/ahrenslab/Misha/forJeremy_SparkStreamingSample/ /nobackup/freeman/buffer/ 1
#
import sys, os, tim... | Sort files by modification date when testing streaming to preserve order | Sort files by modification date when testing streaming to preserve order
| Python | apache-2.0 | kcompher/thunder,zhwa/thunder,kcompher/thunder,pearsonlab/thunder,kunallillaney/thunder,poolio/thunder,j-friedrich/thunder,poolio/thunder,j-friedrich/thunder,oliverhuangchao/thunder,thunder-project/thunder,jwittenbach/thunder,broxtronix/thunder,pearsonlab/thunder,oliverhuangchao/thunder,kunallillaney/thunder,broxtronix... |
4976931febdbddec362411b62c7574d4a26368d5 | launch_instance.py | launch_instance.py | # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None):
'''
'''
if not isinstance(security_groups, list):
... | # License under the MIT License - see LICENSE
import boto.ec2
import os
import time
def launch(key_name, region='us-west-2', image_id='ami-5189a661',
instance_type='t2.micro', security_groups='launch-wizard-1',
user_data=None, initial_check=True):
'''
'''
if not isinstance(security... | Make the initialization wait optional | Make the initialization wait optional
| Python | mit | Astroua/aws_controller,Astroua/aws_controller |
ccc2a583ca2365609e0da0d4bdc5e00d49cd172b | bob/templatetags/bob.py | bob/templatetags/bob.py |
from django import template
from django.template.loaders import select_template
register = template.Library()
class PlaceholderNode(template.Node):
def __init__(self, name, **kwargs):
self.name = name
self.kwargs = kwargs
def render(self, context):
name = self.name.resolve(context)
... |
from django import template
from django.template.loaders import select_template
register = template.Library()
class PlaceholderNode(template.Node):
def __init__(self, name, **kwargs):
self.name = name
self.kwargs = kwargs
def render(self, context):
name = self.name.resolve(context)
... | Copy the template name list from the fragment so we don't mutate it | Copy the template name list from the fragment so we don't mutate it
| Python | mit | funkybob/bobcms,funkybob/bobcms |
e3a95d00444fb981d7aaf6d3beffca8796a8891f | mycroft/frontends/tts/mimic_tts.py | mycroft/frontends/tts/mimic_tts.py | from subprocess import call
from mycroft.frontends.tts.tts_plugin import TtsPlugin
class MimicTts(TtsPlugin):
def read(self, text):
call(['mimic', '-t', text, '-voice', self.config['voice']])
| from subprocess import call
from os.path import isdir
from mycroft.frontends.tts.tts_plugin import TtsPlugin
from mycroft.util.git_repo import GitRepo
class MimicTts(TtsPlugin):
def __init__(self, rt):
super().__init__(rt)
if not isdir(self.rt.paths.mimic_exe):
self.download_mimic()... | Add download and compile step to mimic | Add download and compile step to mimic
| Python | apache-2.0 | MatthewScholefield/mycroft-simple,MatthewScholefield/mycroft-simple |
345794f454642d3a313b8da4c87a874ed9521c09 | preprocessing/collect_unigrams.py | preprocessing/collect_unigrams.py | # -*- coding: utf-8 -*-
"""
Execute via:
python -m preprocessing/collect_unigrams
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import os
from model.unigrams import Unigrams
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
ARTICLES_FILEPATH = "/media/aj/gra... | # -*- coding: utf-8 -*-
"""
File to collect all unigrams and all name-unigrams (label PER) from a corpus file.
The corpus file must have one document/article per line. The words must be labeled in the
form word/LABEL.
Example file content:
Yestarday John/PER Doe/PER said something amazing.
... | Add documentation, refactor to use config | Add documentation, refactor to use config
| Python | mit | aleju/ner-crf |
400828c8606e614dcc11b1e7c7d1fb7336ab5082 | corehq/apps/es/sms.py | corehq/apps/es/sms.py | from .es_query import HQESQuery
from . import filters
class SMSES(HQESQuery):
index = 'sms'
@property
def builtin_filters(self):
return [
incoming_messages,
outgoing_messages,
to_commcare_user,
to_commcare_case,
to_web_user,
... | from .es_query import HQESQuery
from . import filters
class SMSES(HQESQuery):
index = 'sms'
@property
def builtin_filters(self):
return [
incoming_messages,
outgoing_messages,
to_commcare_user,
to_commcare_case,
to_web_user,
... | Add user facet for SMS | Add user facet for SMS
| Python | bsd-3-clause | puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
2a5cc95cc08f90659a6d18db3a9e60c02f7ec4b7 | lib/servo_process.py | lib/servo_process.py | from multiprocessing import Process, Value
import os
import config
import servo
import signal
class ServoProcess(Process):
def __init__(self):
signal.signal(signal.SIGINT, signal.SIG_IGN)
print '----> Checking servo driver...'
if not os.path.exists('/dev/servoblaster'):
raise Ex... | from multiprocessing import Process, Value
import os
import config
import servo
import signal
class ServoProcess(Process):
def __init__(self):
print '----> Checking servo driver...'
if not os.path.exists('/dev/servoblaster'):
raise Exception('Servo driver was not found. Is servoblaster ... | Move signal ignore to run | Move signal ignore to run
| Python | mit | mlensment/rebot,mlensment/rebot |
fbc0a83bc9a72c57ba56cecd9fa06e7e86ea7589 | nbgrader/auth/base.py | nbgrader/auth/base.py | """Base formgrade authenticator."""
from traitlets.config.configurable import LoggingConfigurable
class BaseAuth(LoggingConfigurable):
"""Base formgrade authenticator."""
def __init__(self, ip, port, base_directory, **kwargs):
super(BaseAuth, self).__init__(**kwargs)
self._ip = ip
sel... | """Base formgrade authenticator."""
from traitlets.config.configurable import LoggingConfigurable
class BaseAuth(LoggingConfigurable):
"""Base formgrade authenticator."""
def __init__(self, ip, port, base_directory, **kwargs):
self._ip = ip
self._port = port
self._base_url = ''
... | Set instances variables in auth before init | Set instances variables in auth before init
| Python | bsd-3-clause | ellisonbg/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,ellisonbg/nbgrader,ellisonbg/nbgrader,ellisonbg/nbgrader,jupyter/nbgrader |
4c813a82d0035c9f49e0b07f54150676c5dd8faf | run_tests.py | run_tests.py | #!/usr/bin/python
import optparse
import sys
import unittest2
USAGE = """%prog SDK_PATH TEST_PATH <THIRD_PARTY>
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation
TEST_PATH Path to package containing test modules
THIRD_PARTY Optional path to third party python modules to include."""
def ... | #!/usr/bin/python
import optparse
import sys
import unittest2
USAGE = """%prog SDK_PATH TEST_PATH <THIRD_PARTY>
Run unit tests for App Engine apps.
SDK_PATH Path to the SDK installation
TEST_PATH Path to package containing test modules
THIRD_PARTY Optional path to third party python modules to include."""
def ... | Make sure the tests exit with status 1 when there are errors or failures | Make sure the tests exit with status 1 when there are errors or failures | Python | apache-2.0 | google/gae-secure-scaffold-python,google/gae-secure-scaffold-python3,google/gae-secure-scaffold-python,google/gae-secure-scaffold-python |
43a8043054dc5f942a04efe7273b3b1743db89ca | test.py | test.py | import time
import urllib
import RPi.GPIO as GPIO
# GPIO input pin to use
LPR_PIN = 3
# URL to get image from
SOURCE = 'http://192.168.0.13:8080/photoaf.jpg'
# Path to save image locally
FILE = 'img.jpg'
# Use GPIO pin numbers
GPIO.setmode(GPIO.BCM)
# Disable "Ports already in use" warning
GPIO.setwarnings(False)
# ... | import time
import urllib
import RPi.GPIO as gpio
# GPIO input pin to use
LPR_PIN = 3
# URL to get image from
SOURCE = 'http://192.168.0.13:8080/photoaf.jpg'
# Path to save image locally
FILE = 'img.jpg'
# Use GPIO pin numbers
gpio.setmode(gpio.BCM)
# Disable "Ports already in use" warning
gpio.setwarnings(False)
# ... | Revert GPIO setup to be optimized for GPIO3 (with internal pull up resistor) | Revert GPIO setup to be optimized for GPIO3 (with internal pull up resistor)
| Python | mit | adampiskorski/lpr_poc |
8e5ad2138d0685e4322156b3f545be46a3f0c99f | util.py | util.py | #!/usr/bin/env python
import glob
import os.path
import random
def pick_random(directory, k=None):
"""Pick randomly some files from a directory."""
all_files = glob.glob(os.path.join(directory, '*'))
random.shuffle(all_files)
return all_files if k is None else all_files[:k]
| #!/usr/bin/env python
import glob
import os.path
import random
import re
def pick(directory, k=None, randomized=True):
"""Pick some thread files from a thread directory."""
all_files = glob.glob(os.path.join(directory, '*'))
if randomized:
random.shuffle(all_files)
else:
pattern = '([... | Modify to pick either randomly or sequentially | Modify to pick either randomly or sequentially
| Python | mit | kemskems/otdet |
0da7e65a5def18ae6f2562b7e30d710b4a71de1a | repl.py | repl.py | #!/usr/bin/python3
"""Command line runtime for Tea."""
import runtime.lib
from runtime import lexer, parser, env
TEA_VERSION = "0.0.5-dev"
TEA_TITLE = "Tea @" + TEA_VERSION
CLI_SYMBOL = "#> "
CLI_SPACE = " " * 3
CLI_RESULT = "<- "
def interpret(expression, context):
"""Interpret an expression by tokenizing, par... | #!/usr/bin/python3
"""Command line runtime for Tea."""
import runtime.lib
from runtime import lexer, parser, env
TEA_VERSION = "0.0.5-dev"
TEA_TITLE = "Tea @" + TEA_VERSION
CLI_SYMBOL = "#> "
CLI_SPACE = " " * 3
CLI_RESULT = "<- "
def interpret(expression, context):
"""Interpret an expression by tokenizing, par... | Reduce print statement console clustering | Reduce print statement console clustering
| Python | mit | lnsp/tea,lnsp/tea |
90db6286cdfb493de5dc944783aa65b4fbce38b8 | ghettoq/backends/pyredis.py | ghettoq/backends/pyredis.py | from redis import Redis as Redis
from ghettoq.backends.base import BaseBackend
class RedisBackend(BaseBackend):
def establish_connection(self):
return Redis(host=self.host, port=self.port, db=self.database,
password=self.password)
def put(self, queue, message):
self.clie... | from redis import Redis as Redis
from ghettoq.backends.base import BaseBackend
DEFAULT_PORT = 6379
class RedisBackend(BaseBackend):
def establish_connection(self):
self.port = self.port or DEFAULT_PORT
return Redis(host=self.host, port=self.port, db=self.database,
password=s... | Use rpop/rpush instead of deprecated pop/push (conforming to redis 1.x) | Use rpop/rpush instead of deprecated pop/push (conforming to redis 1.x)
| Python | bsd-3-clause | ask/ghettoq |
02668b8dfda3c00f4ae74846d7c14c5dde64e17c | asciitree/__init__.py | asciitree/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from legacy import draw_tree, _draw_tree
def ascii_tree(node,
get_node_children=lambda t: t[1].items(),
get_node_text=lambda t: t[0],
get_root=lambda d: d.items()[0]):
return _draw_tree(get_root(node), '', get_node_childre... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from legacy import draw_tree, _draw_tree
def left_aligned(tree,
get_node_children=lambda t: t[1].items(),
get_node_text=lambda t: t[0],
get_root=lambda d: d.items()[0]):
return '\n'.join(_left_aligned(get_root(tree),... | Remove now obsolete ascii_tree function. | Remove now obsolete ascii_tree function.
| Python | mit | mbr/asciitree |
77579ff7d7a63539d350c40d49eedeb21e61bd61 | acute/schema.py | acute/schema.py | """
Define acute schemas.
"""
from acute import models
list_columns = [
models.Demographics,
models.Location,
models.PastMedicalHistory,
models.Diagnosis,
models.Plan,
models.Rescuscitation
]
list_columns_take = [
models.Demographics,
models.Location,
models.Clerking,
models.Pa... | """
Define acute schemas.
"""
from acute import models
list_columns = [
models.Demographics,
models.Location,
models.Diagnosis,
models.PastMedicalHistory,
models.Plan,
models.Rescuscitation
]
list_columns_take = [
models.Demographics,
models.Location,
models.Clerking,
models.Di... | Make Diagnosis come before PMH | Make Diagnosis come before PMH
closes #5
| Python | agpl-3.0 | openhealthcare/acute,openhealthcare/acute,openhealthcare/acute |
f7788bf9cb2d8d762689a24b63aaeaec3f076d72 | app/__init__.py | app/__init__.py | from flask import Flask
from config import config as configs
from flask.ext.bootstrap import Bootstrap
from flask.ext.elasticsearch import FlaskElasticsearch
from dmutils import init_app, flask_featureflags
bootstrap = Bootstrap()
feature_flags = flask_featureflags.FeatureFlag()
elasticsearch_client = FlaskElasticsear... | from flask import Flask
from config import config as configs
from flask.ext.bootstrap import Bootstrap
from flask.ext.elasticsearch import FlaskElasticsearch
from dmutils import init_app, flask_featureflags
bootstrap = Bootstrap()
feature_flags = flask_featureflags.FeatureFlag()
elasticsearch_client = FlaskElasticsear... | Validate TLS certificate for connections to Elastsearch | Validate TLS certificate for connections to Elastsearch
By default Python elasticsearch client 1.x sets verify_certs to
False, which means it doesn't verify TLS certificates when connecting
to Elasticsearch over HTTPS and urllib3 prints an InsecureRequestWarning
on each request.
Setting `verify_certs=True` explicitly... | Python | mit | alphagov/digitalmarketplace-search-api,alphagov/digitalmarketplace-search-api |
2ad2d488b4d7b0997355c068646a6a38b2668dae | meetuppizza/tests.py | meetuppizza/tests.py | from django.test import TestCase
class Test(TestCase):
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
| from django.test import TestCase
class Test(TestCase):
def test_landing_page_is_there(self):
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
def test_page_contains_pizza(self):
response = self.client.get('/')
self.assertContains(response, "Pizza")
| Add test that checks if landing page contains the word Pizza. | Add test that checks if landing page contains the word Pizza.
| Python | mit | nicole-a-tesla/meetup.pizza,nicole-a-tesla/meetup.pizza |
e654cea816be8c4a79da66efbc50a5698a51ba5b | plantcv/plantcv/print_results.py | plantcv/plantcv/print_results.py | # Print Numerical Data
import json
import os
from plantcv.plantcv import outputs
def print_results(filename):
"""Print result table
Inputs:
filename = filename
:param filename: str
:return:
"""
if os.path.isfile(filename):
with open(filename, 'r') as f:
hierarchical... | # Print Numerical Data
from plantcv.plantcv import outputs
def print_results(filename):
"""Print result table
Inputs:
filename = filename
:param filename: str
:return:
"""
print("""Deprecation warning: plantcv.print_results will be removed in a future version.
Please use pl... | Add deprecation warning and use new method | Add deprecation warning and use new method
| Python | mit | stiphyMT/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,stiphyMT/plantcv,danforthcenter/plantcv |
ee1c890df7c2c86192b68bd442e41226f70a3850 | setup.py | setup.py | # -*- coding: utf-8 -*-
#!/usr/bin/env python
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re... | # -*- coding: utf-8 -*-
#!/usr/bin/env python
import os
import re
from distutils.core import setup
version_re = re.compile(
r'__version__ = (\(.*?\))')
cwd = os.path.dirname(os.path.abspath(__file__))
fp = open(os.path.join(cwd, 'face_client', '__init__.py'))
version = None
for line in fp:
match = version_re... | Remove the obsolte comment, library is licensed under BSD. | Remove the obsolte comment, library is licensed under BSD.
| Python | bsd-3-clause | Liuftvafas/python-face-client,Kami/python-face-client |
6311df0e55fe234c39cecf6112091e65c1baf52b | tnrs.py | tnrs.py | import sys
import caching
import urllib
import urllib2
import re
from pyquery import PyQuery as p
try: cache = caching.get_cache('tnrs')
except: cache = {}
def tnrs_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on the TNRS web service. If a most likely standard name can be identified,
return... | import sys
import caching
import urllib
import urllib2
import re
import json
from pyquery import PyQuery as p
try: cache = caching.get_cache('tnrs')
except: cache = {}
def tnrs_lookup(name, TIMEOUT=10, CACHE=True):
'''
Look up "name" on the TNRS web service. If a most likely standard name can be identified,... | Use json library instead of eval. | Use json library instead of eval.
| Python | mit | bendmorris/tax_resolve |
4a4eca6fb920d7ba50e97a5bcb0ae8161715ff7a | citenet/neighborrank.py | citenet/neighborrank.py | import networkx as nx
import util
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest indegree (most often cited).
nodes = util.top_n_from_dict(graph.in_degree(), n=n)
... | import networkx as nx
import util
def neighborrank(graph, n=100, neighborhood_depth=2):
"""Compute the NeighborRank of the top n nodes in graph, using the
specified neighborhood_depth."""
# Get top n nodes with highest outdegree (most often cited).
nodes = util.top_n_from_dict(graph.out_degree(), n=n)
... | Switch in/out degree for neighbor rank | Switch in/out degree for neighbor rank
Edges point in the direction of time, or influence. That means we're
concerned with outdegree (amount of nodes influenced by the current
node), not indegree (amount of nodes that influence the current node).
| Python | mit | Pringley/citenet |
8228a862654dfd0418d1e756042fa8f8746b57b9 | ideascube/conf/kb_usa_wmapache.py | ideascube/conf/kb_usa_wmapache.py | # -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wiktionary',
... | # -*- coding: utf-8 -*-
"""KoomBook conf"""
from .kb import * # noqa
LANGUAGE_CODE = 'en'
IDEASCUBE_NAME = 'WHITE MOUNTAIN APACHE'
HOME_CARDS = STAFF_HOME_CARDS + [
{
'id': 'blog',
},
{
'id': 'mediacenter',
},
{
'id': 'gutenberg',
},
{
'id': 'wikipedia',
... | Remove Ted and add Wikiepdia | Remove Ted and add Wikiepdia
| Python | agpl-3.0 | ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.