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 |
|---|---|---|---|---|---|---|---|---|---|
0f1d10f452066fb304f24006ac641860f4f6b7d9 | bluebottle/utils/migrations/0007_auto_20210825_1018.py | bluebottle/utils/migrations/0007_auto_20210825_1018.py | # Generated by Django 2.2.20 on 2021-08-25 08:18
from django.db import migrations
from bluebottle.clients import properties
def set_default(apps, schema_editor):
try:
Language = apps.get_model('utils', 'Language')
language = Language.objects.get(code=properties.LANGUAGE_CODE)
except Language... | # Generated by Django 2.2.20 on 2021-08-25 08:18
from django.db import migrations
from bluebottle.clients import properties
def set_default(apps, schema_editor):
try:
Language = apps.get_model('utils', 'Language')
language = Language.objects.get(code=properties.LANGUAGE_CODE)
except Language... | Fix migration if no language exists | Fix migration if no language exists
| Python | bsd-3-clause | onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle |
1bc1c62b5d2bd5edd6c375c91540a6597b3c47cc | lc226_invert_binary_tree.py | lc226_invert_binary_tree.py | """Leetcode 226. Invert Binary Tree
Easy
URL: https://leetcode.com/problems/invert-binary-tree/
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
"""
# Definition for a binary tree node.
class TreeNode(object):
def ... | """Leetcode 226. Invert Binary Tree
Easy
URL: https://leetcode.com/problems/invert-binary-tree/
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
"""
# Definition for a binary tree node.
class TreeNode(object):
def ... | Complete recur w/ time/space complexity | Complete recur w/ time/space complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
15479b3baea8d0f5cb58bf7d22321646ac4513bc | spacy/lang/nl/lex_attrs.py | spacy/lang/nl/lex_attrs.py | # coding: utf8
from __future__ import unicode_literals
from ...attrs import LIKE_NUM
_num_words = set("""
nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien
veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd
duizend miljoen miljard biljoen biljard triljoen tril... | # coding: utf8
from __future__ import unicode_literals
from ...attrs import LIKE_NUM
_num_words = set("""
nul een één twee drie vier vijf zes zeven acht negen tien elf twaalf dertien
veertien twintig dertig veertig vijftig zestig zeventig tachtig negentig honderd
duizend miljoen miljard biljoen biljard triljoen tril... | Add comment to like_num re: future work | Add comment to like_num re: future work
| Python | mit | spacy-io/spaCy,spacy-io/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,aikramer2/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,honnibal/spaCy,recognai/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/s... |
f23a3bbddaf3ab650b8833bbb23fb9666819567c | project/project_name/settings/staticmedia.py | project/project_name/settings/staticmedia.py | from os.path import join, normpath
from .base import SITE_ROOT
class LocalStatic(object):
""" Static File Configuration """
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = normpath(join(SITE_ROOT, 'assets'))
# See: https://docs.djangoproject.com/en/dev/r... | from os.path import join, normpath
from .base import SITE_ROOT
class LocalStatic(object):
""" Static File Configuration """
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = normpath(join(SITE_ROOT, '.collectedstatic'))
# See: https://docs.djangoproject.co... | Call a spade a spade. | Call a spade a spade.
| Python | mit | bretth/django-pavlova-project,bretth/django-pavlova-project,bretth/django-pavlova-project |
dad7508aa6fc3f0b97975f0985c666fdfc191035 | api/__init__.py | api/__init__.py | from flask import Flask
DB_CONNECTION = "host='localhost' port=5432 user='postgres' password='secret' dbname='antismash'"
SQLALCHEMY_DATABASE_URI = 'postgres://postgres:secret@localhost:5432/antismash'
app = Flask(__name__)
app.config.from_object(__name__)
from .models import db
db.init_app(app)
from . import api
... | import os
from flask import Flask
SQLALCHEMY_DATABASE_URI = os.getenv('AS_DB_URI', 'postgres://postgres:secret@localhost:5432/antismash')
app = Flask(__name__)
app.config.from_object(__name__)
from .models import db
db.init_app(app)
from . import api
from . import error_handlers
| Allow overriding database URI from command line | api: Allow overriding database URI from command line
Signed-off-by: Kai Blin <ad3597797f6179d503c382b2627cc19939309418@biosustain.dtu.dk>
| Python | agpl-3.0 | antismash/db-api,antismash/db-api |
a264754c177237e2cfd10a1eb96994a3d4b8fd4a | quizzes.py | quizzes.py | from database import QuizDB
db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT)
class Quiz(Base):
def __init__(self, id):
self.id = id
QUESTION_HASH = "{0}:question".format(self.id)
ANSWER_HASH = "{0}:answer".format(self.id)
def new_card(self, question, answer):
assert db.hl... | from database import QuizDB
import config
db = QuizDB(host=config.REDIS_HOST, port=config.REDIS_PORT)
class Quiz:
QUESTION_HASH = ''
ANSWER_HASH = ''
def __init__(self, id):
self.id = id
self.QUESTION_HASH = "{0}:question".format(self.id)
self.ANSWER_HASH = "{0}:answer".format(se... | Fix problems w/ class variables and fix bug with max function on an empty set | Fix problems w/ class variables and fix bug with max function on an empty set
| Python | bsd-2-clause | estreeper/quizalicious,estreeper/quizalicious,estreeper/quizalicious |
0f6fc70278ce67dfcb0468d0913e349ec6b0a169 | tndata_backend/utils/decorators.py | tndata_backend/utils/decorators.py | from django.conf import settings
from django.core.cache import cache
from functools import wraps
def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT):
"""Cache a method, using it's first argument to set a cache key.
Params:
* cache_key is a format string used to set a cache key, e.g. "{}-foo"
... | from django.conf import settings
from django.core.cache import cache
from functools import wraps
def cached_method(cache_key, timeout=settings.CACHE_TIMEOUT):
"""Cache a method, using the ID attribute of it's first argument to set
a cache key. NOTE: If this first argument for the cached method doesn't
hav... | Update for cached_method so it doesn't try to do anythin if the first argument doesn't have an ID attribute | Update for cached_method so it doesn't try to do anythin if the first argument doesn't have an ID attribute
| Python | mit | izzyalonso/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend,tndatacommons/tndata_backend,izzyalonso/tndata_backend,tndatacommons/tndata_backend,tndatacommons/tndata_backend,izzyalonso/tndata_backend |
98b601953428fb4c77eafb4e06a018c4bb2b4391 | isort/files.py | isort/files.py | import os
from pathlib import Path
from typing import Iterable, Iterator, List, Set
from warnings import warn
from isort.settings import Config
def find(
paths: Iterable[str], config: Config, skipped: List[str], broken: List[str]
) -> Iterator[str]:
"""Fines and provides an iterator for all Python source fil... | import os
from pathlib import Path
from typing import Iterable, Iterator, List, Set
from isort.settings import Config
def find(
paths: Iterable[str], config: Config, skipped: List[str], broken: List[str]
) -> Iterator[str]:
"""Fines and provides an iterator for all Python source files defined in paths."""
... | Remove "recursive symlink detected" UserWarning | Remove "recursive symlink detected" UserWarning
| Python | mit | PyCQA/isort,PyCQA/isort |
f80febf88c3f045493e75efc788d88058f021f0f | merge_sort.py | merge_sort.py | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
def merge_sort(lyst):
buf = [len(lyst)]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst, buf, middle+1, high)... | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
def merge_sort(lyst):
buf = [None for x in range(len(lyst))]
_merge_sort(lyst, buf, 0, len(lyst)-1)
def _merge_sort(lyst, buf, low, high):
if low < high:
middle = (low + high) // 2
_merge_sort(lyst, buf, low, middle)
_merge_sort(lyst,... | Fix initial buf variable to act as an array | Fix initial buf variable to act as an array
| Python | mit | nbeck90/data_structures_2 |
62634879192e51b9f938da301534b08cf49d2e85 | methodMang.py | methodMang.py | #!python3
from methods import output, data
import tokenz
import interpreter
intp = interpreter.Interpreter()
class UndefinedFunctionError(Exception): pass
class Call:
def __init__(self, method, args):
self.method = method
self.a = args
self.vals = []
for t in self.a:
... | #!python3
from methods import io, data
import tokenz
import interpreter
intp = interpreter.Interpreter()
class UndefinedFunctionError(Exception): pass
def reg(it, c):
it.valid = it.valid + [(c().methods, c())]
class Call:
def __init__(self, method, args):
self.method = method
self.a = args... | Rename Output + smaller Register | Rename Output + smaller Register
| Python | mit | Icelys/Scotch-Language |
b42dddaa45a8915a653f4b145f2a58eb6996f28a | home/openbox/lib/helpers.py | home/openbox/lib/helpers.py | import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
return 'sudo -Hiu browser %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = [
'/usr/local/lib/firefox/fir... | import os.path, os
def run_as_browser(fn):
def wrapped(*args, **kwargs):
rv = fn(*args, **kwargs)
return 'sudo -Hiu browser env XAUTHORITY=/home/browser/.Xauthority %s' % rv
return wrapped
class Helpers:
@property
@run_as_browser
def default_firefox_bin(self):
candidates = ... | Fix firefox invocation as browser | Fix firefox invocation as browser
| Python | bsd-2-clause | p/pubfiles,p/pubfiles,p/pubfiles,p/pubfiles,p/pubfiles |
2e729b437434e6d355602f9fd74bc9bd3b42f120 | core/tests.py | core/tests.py | from django.test import TestCase
# Create your tests here.
| from django.test import TestCase
from core.models import Profile, User
class ProfileTestCase(TestCase):
"""This class defines the test suite for the Person model."""
def setUp(self):
"""Define the test variables."""
self.username = "some-test-user"
self.email = "some@test.user"
... | Add test to model Profile | Add test to model Profile
| Python | mit | desenho-sw-g5/service_control,desenho-sw-g5/service_control |
7dd0c64b4503ab32cf79864f4c23016518b1cdbd | electionleaflets/apps/api/tests/test_create_leaflet.py | electionleaflets/apps/api/tests/test_create_leaflet.py | import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.pa... | import os
import json
from django.core.urlresolvers import reverse
from rest_framework import status
from rest_framework.test import APITestCase
TEST_IMAGES = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '1.jpg',]
BASE_PATH = os.path.join(
os.path.dirname(__file__),
'test_images'
)
IMAGES = [(name, os.pa... | Remove some API tests for now | Remove some API tests for now
| Python | mit | JustinWingChungHui/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,DemocracyClub/electionleaflets,JustinWingChungHui/electionleaflets,JustinWingChungHui/electionleaflets,JustinWingChungHui/electionleaflets |
327c00fe5fe9211ac5ba3b33e807ec938ecc8311 | configstore/tests/test_docker_secret.py | configstore/tests/test_docker_secret.py | from unittest import TestCase
try:
from unittest import mock
except ImportError:
import mock
from configstore.backends.docker_secret import DockerSecretBackend
from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH
class TestDockerSecretBackend(TestCase):
@mock.patch('configstore.backends.docker... | from unittest import TestCase
try:
from unittest import mock
except ImportError:
import mock
from configstore.backends.docker_secret import DockerSecretBackend
from .test_data import DEFAULT_KEY, DEFAULT_VALUE, CUSTOM_PATH
class TestDockerSecretBackend(TestCase):
@mock.patch('configstore.backends.docker... | Make sure exists always resturns None in the non-existant test case | Make sure exists always resturns None in the non-existant test case
| Python | mit | caravancoop/configstore |
851fff051a194e061cdd110e32d0f88fe2d60587 | nodular/db.py | nodular/db.py | # -*- coding: utf-8 -*-
"""
Nodular provides a Flask-SQLAlchemy database object that all models in
your app must use. Typical usage::
from nodular import db
from coaster.sqlalchemy import BaseMixin
class MyModel(BaseMixin, db.Model):
pass
To initialize with an app::
from flask import Flask
... | # -*- coding: utf-8 -*-
"""
Nodular provides a Flask-SQLAlchemy database object that all models in
your app must use. Typical usage::
from nodular import db
from coaster.sqlalchemy import BaseMixin
class MyModel(BaseMixin, db.Model):
pass
To initialize with an app::
from flask import Flask
... | Fix for SQLite3 foreign keys. | Fix for SQLite3 foreign keys.
| Python | bsd-2-clause | hasgeek/nodular,hasgeek/nodular |
09309cbfb321dbf8d5e5c4e4754259b2cb1619ac | startup.py | startup.py | import tables
import tables as tb
import fipy
import fipy as fp
import numpy
import numpy as np
import scipy
import scipy as sp
import pylab
import pylab as pl
| import tables
import tables as tb
import fipy
import fipy as fp
import numpy
import numpy as np
import scipy
import scipy as spy
import matplotlib.pylot as plt
| Use canonical matplotlib.pyplot as plt. | Use canonical matplotlib.pyplot as plt.
| Python | mit | wd15/env,wd15/env,wd15/env |
b3d066e9ff5bc0508eec4fc9f317b7df112e2218 | test/test_url_subcommand.py | test/test_url_subcommand.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function
import path
import pytest
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from sqlite... | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import print_function
import responses
import simplesqlite
from click.testing import CliRunner
from sqlitebiter._enum import ExitCode
from sqlitebiter.sqlitebiter import cmd
from .common import print_traceback
... | Remove imports that no longer used | Remove imports that no longer used
| Python | mit | thombashi/sqlitebiter,thombashi/sqlitebiter |
0c7c19a9edffea9474b0aa6379bafef283425483 | reboot_router_claro3G.py | reboot_router_claro3G.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2 as http
# URL with GET to reboot router
url_get_reboot = 'http://10.11.12.254/log/in?un=admin&pw=admin12&rd=%2Fuir%2Frebo.htm?rc=&Nrd=0&Nsm=1'
# Handling HTTP Cookie - Session Cookie Router
cookieprocessor = http.HTTPCookieProcessor()
# Customize it Ope... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2 as http
# URL with GET to reboot router or status main page to tests
#url_get_reboot = 'http://10.11.12.254/log/in?un=admin&pw=admin12&rd=%2Fuir%2Frebo.htm?rc=&Nrd=0&Nsm=1'
url_get_status = 'http://10.11.12.254/log/in?un=admin&pw=admin12&rd=%2Fuir%2Fstatus... | Add variavel url_root to url of the reboot router and status mainpage router | Add variavel url_root to url of the reboot router and status mainpage router
| Python | apache-2.0 | cleitonbueno/reboot_router |
287a13d30ab70dd6dd9ee7e59021d309d10839bf | examples/tox21/tox21_tensorgraph_graph_conv.py | examples/tox21/tox21_tensorgraph_graph_conv.py | """
Script that trains graph-conv models on Tox21 dataset.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_to... | """
Script that trains graph-conv models on Tox21 dataset.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
np.random.seed(123)
import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc
from deepchem.molnet import load_to... | Fix GraphConvTensorGraph to GraphConvModel in tox21 | Fix GraphConvTensorGraph to GraphConvModel in tox21
| Python | mit | ktaneishi/deepchem,Agent007/deepchem,miaecle/deepchem,lilleswing/deepchem,ktaneishi/deepchem,Agent007/deepchem,Agent007/deepchem,deepchem/deepchem,peastman/deepchem,miaecle/deepchem,miaecle/deepchem,peastman/deepchem,lilleswing/deepchem,ktaneishi/deepchem,lilleswing/deepchem,deepchem/deepchem |
38254c64bf94f5c1570a129cfe41f94dd88fb780 | config/regenerate_launch_files.py | config/regenerate_launch_files.py | #!/usr/bin/env python2
# (C) 2015 Jean Nassar
# Released under BSD
import glob
import os
import subprocess as sp
import rospkg
import tqdm
def get_launch_dir(package):
return os.path.join(rospkg.RosPack().get_path(package), "launch")
def get_file_root(path):
"""
>>> get_file_root("/tmp/test.txt")
... | #!/usr/bin/env python2
# (C) 2015 Jean Nassar
# Released under BSD
import glob
import os
import subprocess as sp
import rospkg
import tqdm
def get_launch_dir(package):
return os.path.join(rospkg.RosPack().get_path(package), "launch")
def get_file_root(path):
"""
>>> get_file_root("/tmp/test.txt")
... | Change unit from "it" to "files" | Change unit from "it" to "files"
| Python | mit | masasin/spirit,masasin/spirit |
179ecf15c678c7d4d5e19cc453c4507481298747 | contrib/performance/httpclient.py | contrib/performance/httpclient.py | ##
# Copyright (c) 2010 Apple 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.0
#
# Unless required by applicable la... | ##
# Copyright (c) 2010 Apple 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.0
#
# Unless required by applicable la... | Make the response body available via readBody | Make the response body available via readBody
git-svn-id: 81e381228600e5752b80483efd2b45b26c451ea2@6660 e27351fd-9f3e-4f54-a53b-843176b1656c
| Python | apache-2.0 | trevor/calendarserver,trevor/calendarserver,trevor/calendarserver |
ba60384a1f4232a2d9e1d04fbf95a5841b183d3f | lymph/services/scheduler.py | lymph/services/scheduler.py | import gevent
import msgpack
import redis
import time
from lymph.core.interfaces import Interface
from lymph.core.decorators import rpc
class Scheduler(Interface):
service_type = 'scheduler'
schedule_key = 'schedule'
def __init__(self, *args, **kwargs):
super(Scheduler, self).__init__(*args, **k... | import gevent
import msgpack
import redis
import time
from lymph.core.interfaces import Interface
from lymph.core.decorators import rpc
from lymph.utils import make_id
class Scheduler(Interface):
service_type = 'scheduler'
schedule_key = 'schedule'
def __init__(self, *args, **kwargs):
super(Sche... | Include ids for scheduled events to make schedule data unique | Include ids for scheduled events to make schedule data unique
| Python | apache-2.0 | deliveryhero/lymph,alazaro/lymph,itakouna/lymph,lyudmildrx/lymph,itakouna/lymph,mamachanko/lymph,mamachanko/lymph,lyudmildrx/lymph,kstrempel/lymph,mouadino/lymph,emulbreh/lymph,dushyant88/lymph,alazaro/lymph,vpikulik/lymph,emulbreh/lymph,Drahflow/lymph,itakouna/lymph,mamachanko/lymph,torte/lymph,alazaro/lymph,mouadino/... |
d23ee11cb7deb9ae9ada7b3eca603d3589f9a343 | stagecraft/apps/datasets/admin/backdrop_user.py | stagecraft/apps/datasets/admin/backdrop_user.py | from __future__ import unicode_literals
from django.contrib import admin
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
class BackdropUserAdmin(reversion.VersionAdmin):
search_fields = ['email']
list_display = ('email')
admin.site.register(BackdropUser)
| from __future__ import unicode_literals
from django.contrib import admin
from django.db import models
import reversion
from stagecraft.apps.datasets.models.backdrop_user import BackdropUser
from stagecraft.apps.datasets.models.data_set import DataSet
class DataSetInline(admin.StackedInline):
model = DataSet
f... | Add user:dataset count to backdrop user admin | Add user:dataset count to backdrop user admin
- Sortable by number of data-sets the user has access to
- Vaguely useful, but mainly an exercise in seeing how easily we can customise the output of the manytomany field (not very easily)
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft |
7290b589219587e161380da2f323c581c2b436eb | manager/apps/brand/forms.py | manager/apps/brand/forms.py | from django import forms
class BrandProposalForm(forms.Form):
brand_nm = forms.CharField(max_length=255, label='Brand name')
brand_type = forms.ChoiceField(choices=(('test', '1'), ('test2', '2')))
owner_nm = forms.CharField(
max_length=255, label='Owner name', required=False)
brand_link = form... | from django import forms
from .models import BrandType
class BrandProposalForm(forms.Form):
brand_nm = forms.CharField(max_length=255, label='Brand name')
brand_type = forms.ModelChoiceField(queryset=BrandType.objects.all())
owner_nm = forms.CharField(
max_length=255, label='Owner name', required=... | Fix BrandProposalForm to use BrandType in a choice | Fix BrandProposalForm to use BrandType in a choice
| Python | mit | okfn/brand-manager,okfn/opd-brand-manager,okfn/brand-manager,okfn/opd-brand-manager |
e7d271c41dd713750a8224f0e8f65e2d3b119623 | polyaxon/auditor/service.py | polyaxon/auditor/service.py | import activitylogs
import tracker
from auditor.manager import default_manager
from event_manager.event_service import EventService
class AuditorService(EventService):
"""An service that just passes the event to author services."""
event_manager = default_manager
def get_event(self, event_type, instanc... | from auditor.manager import default_manager
from event_manager.event_service import EventService
class AuditorService(EventService):
"""An service that just passes the event to author services."""
event_manager = default_manager
def __init__(self):
self.tracker = None
self.activitylogs =... | Move event managers imports to setup in auditor | Move event managers imports to setup in auditor
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon |
6f8472bdd605a6815d40ae90c05cbb0032907b6c | tests/parse_token.py | tests/parse_token.py | """parse_token test case"""
import unittest
from lighty.templates.tag import parse_token
class FormFieldsTestCase(unittest.TestCase):
''' Test form fields '''
def setUp(self):
# Test Field class
pass
def testCleanBrackets(self):
parsed = parse_token('"test.html"')
needed... | """parse_token test case"""
import unittest
from lighty.templates.tag import parse_token
class ParseTokenTestCase(unittest.TestCase):
''' Test form fields '''
def setUp(self):
# Test Field class
pass
def testCleanBrackets(self):
parsed = parse_token('"test.html"')
needed... | Add tests for parser tokens | Add tests for parser tokens
| Python | bsd-3-clause | GrAndSE/lighty-template,GrAndSE/lighty |
267a36731b7f103bdc9318a2646b24dec520f9e6 | tests/test_cindex.py | tests/test_cindex.py | import sublime
import os.path
import time
from YetAnotherCodeSearch.tests import CommandTestCase
class CindexCommandTest(CommandTestCase):
def test_cindex(self):
self.window.run_command('cindex', {'index_project': True})
max_iters = 10
while max_iters > 0 and self.view.get_status('YetAnotherCodeSearc... | import sublime
import os.path
import shutil
import time
from YetAnotherCodeSearch.tests import CommandTestCase
class CindexCommandTest(CommandTestCase):
def test_cindex(self):
self.window.run_command('cindex', {'index_project': True})
max_iters = 10
while max_iters > 0 and self.view.get_status('YetAn... | Add explicit test to ensure cindex is present. | Add explicit test to ensure cindex is present.
| Python | mit | pope/SublimeYetAnotherCodeSearch,pope/SublimeYetAnotherCodeSearch |
9a474cbea3a2713a94e9e5dbc0b90762b4f354c6 | automated_ebs_snapshots/connection_manager.py | automated_ebs_snapshots/connection_manager.py | """ Handles connections to AWS """
import logging
import sys
from boto import ec2
from boto.utils import get_instance_metadata
logger = logging.getLogger(__name__)
def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None):
""" Connect to AWS ec2
:type region: str
:param region: AWS regio... | """ Handles connections to AWS """
import logging
import sys
from boto import ec2
from boto.utils import get_instance_metadata
logger = logging.getLogger(__name__)
def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None):
""" Connect to AWS ec2
:type region: str
:param region: AWS regio... | Fix for logging incorrect region information when using instance role for authentication. | Fix for logging incorrect region information when using instance role for authentication.
| Python | apache-2.0 | bkarakashev/automated-ebs-snapshots,skymill/automated-ebs-snapshots,CBitLabs/automated-ebs-snapshots |
b95cf9fce9c8c878ffb81767fea45b23c633eac5 | convert.py | convert.py | #!/usr/bin/python
import config, os, string
def format_filename(s):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
filename = s.replace('/','-')
filename = ''.join(c for c in filename if c in valid_chars)
filename = filename.replace(' ','_')
return filename
class RecordingInfo:... | #!/usr/bin/python
import config, os, string
def format_filename(s):
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
filename = s.replace('/','-')
filename = ''.join(c for c in filename if c in valid_chars)
filename = filename.replace(' ','_')
return filename
class RecordingInfo:... | Initialize title and description with empty string | Initialize title and description with empty string
| Python | apache-2.0 | andreasbehnke/vdr-handbrake |
d848143cdeb915029fefab7be34d0585296502c2 | castor/server.py | castor/server.py | """
This module defines the Castor server, that consumes the Docker events from
a given host. This module can be run as a command line script or get imported
by another Python script.
"""
import docker
import tasks
import settings
DOCKER_SETTINGS = settings.SETTINGS.get('docker', {})
# Customize the Docker client acc... | """
This module defines the Castor server, that consumes the Docker events from
a given host. This module can be run as a command line script or get imported
by another Python script.
"""
import docker
import redis
import settings
import tasks
def consume(docker_client, redis_client):
"""
Starts consuming Doc... | Add last event time in Redis | Add last event time in Redis
This makes sure events are not missed if the server restarts.
| Python | mit | sourcelair/castor |
72e8dbbac6f45e07dbd55c87aa9f0627e2639a98 | python/ball.py | python/ball.py | #!/usr/bin/env python
import sys, time
import math
class Ball:
gravity = -3 # Dots per second squared
def __init__(self):
self.r = 255
self.g = 0
self.b = 0
self.x = 0
self.y = 0
self.vx = 0
self.vy = 0
def updateValues(self, timeElapsed=1): # timeElapsed in seconds
self.x += self.vx * timeElapse... | #!/usr/bin/env python
import sys, time
import math
class Ball:
gravity = -3 # Dots per second squared
def __init__(self, x=0, y=0):
self.r = 255
self.g = 0
self.b = 0
self.x = 0
self.y = 0
self.vx = 0
self.vy = 0
def updateValues(self, timeElapsed=1): # timeElapsed in seconds
self.x += self.vx * ... | Add optional parameters for starting location | Add optional parameters for starting location
| Python | mit | DarkAce65/rpi-led-matrix,DarkAce65/rpi-led-matrix |
d078ec00d5553b0985d9c724a223c74b80b2c5ab | grains/grains.py | grains/grains.py | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
square = [x for x in range(1, 65)]
grain... | # File: grains.py
# Purpose: Write a program that calculates the number of grains of wheat
# on a chessboard given that the number on each square doubles.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Sunday 18 September 2016, 05:25 PM
square = [x for x in range(1, 65)]
grain... | Convert zipped list to dictionary | Convert zipped list to dictionary
| Python | mit | amalshehu/exercism-python |
3a703d05a85c275cbc02ec6ab19d621d7bc2f85a | accounts/forms.py | accounts/forms.py | from django.forms import ModelForm
from .models import CompsocUser, DatabaseAccount, ShellAccount
class CompsocUserForm(ModelForm):
class Meta:
model = CompsocUser
fields = ['nickname', 'website_title', 'website_url']
class ShellAccountForm(ModelForm):
class Meta:
model = ShellAccoun... | from django.forms import ModelForm
from .models import CompsocUser, DatabaseAccount, ShellAccount
class CompsocUserForm(ModelForm):
class Meta:
model = CompsocUser
fields = ['nickname', 'website_title', 'website_url']
class ShellAccountForm(ModelForm):
class Meta:
model = ShellAccoun... | Remove blank field from Meta class | Remove blank field from Meta class
| Python | mit | davidjrichardson/uwcs-zarya,davidjrichardson/uwcs-zarya |
bfd0058efdf362567cd4638244ab3ff47e078398 | opencog/python/examples/blending_agent_demo.py | opencog/python/examples/blending_agent_demo.py | __author__ = 'Keyvan'
from blending.agents import DummyBlendingAgent
from opencog.atomspace import AtomSpace
from opencog.cogserver import Server
if __name__ == '__main__':
server = Server()
server.add_mind_agent(DummyBlendingAgent())
server.run(AtomSpace()) | __author__ = 'Keyvan'
from blending.agents import DummyBlendingAgent
from opencog.atomspace import AtomSpace
from opencog.cogserver import Server
# Check if git shows the branch
if __name__ == '__main__':
server = Server()
server.add_mind_agent(DummyBlendingAgent())
server.run(AtomSpace()) | Check if git shows graph nicely | Check if git shows graph nicely
| Python | agpl-3.0 | shujingke/opencog,ArvinPan/atomspace,roselleebarle04/opencog,yantrabuddhi/atomspace,kim135797531/opencog,sanuj/opencog,printedheart/atomspace,ceefour/atomspace,cosmoharrigan/opencog,TheNameIsNigel/opencog,andre-senna/opencog,jlegendary/opencog,cosmoharrigan/atomspace,shujingke/opencog,ruiting/opencog,anitzkin/opencog,M... |
81fc712a28c44bc9aca2b7dd48449285dcd32bcc | satori.tools/satori/tools/console/__init__.py | satori.tools/satori/tools/console/__init__.py | # vim:ts=4:sts=4:sw=4:expandtab
def main():
from satori.tools import setup
setup()
import code
import readline
console = code.InteractiveConsole()
console.runcode('from satori.client.common import want_import')
console.runcode('want_import(globals(), "*")')
console.interact()
| # vim:ts=4:sts=4:sw=4:expandtab
def main():
from satori.tools import options, setup
options.add_argument('--ipython', help='Use IPython', action='store_true')
flags = setup()
from satori.client.common import want_import
want_import(globals(), "*")
if flags.ipython:
print 'IPython nee... | Add IPython support to satori.console | Add IPython support to satori.console
| Python | mit | zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori,zielmicha/satori |
a2c92c0be31e1d7a31625878e7bc68e23930224c | loop.py | loop.py | # Say anything you type, and write anything you say.
# Stops when you say "turn off" or type "turn off".
import speech
import sys
inputs = ["hi", "foo", "lemon", "hello world"]
output = []
current_run = []
def callback(phrase, listener):
speech.say(phrase)
if phrase == "turn off":
speech.say("Goodbye... | # Say anything you type, and write anything you say.
# Stops when you say "turn off" or type "turn off".
import speech
import sys
import time
lemon = "lemon"
output = []
current_run = []
waiting = False
hasDetect = False
print "Say something."
def callback(phrase, listener):
speech.say(phrase)
print phrase... | Change lemon if speech is detected | Change lemon if speech is detected
If speech is detected, change lemon to whatever was detected. Also print
it.
| Python | mit | powderblock/SpeechLooper |
8286198235e70a314bd924a2ee7ed29f717b599d | session_cleanup/tests.py | session_cleanup/tests.py |
from django.conf import settings
from django.core.cache import cache
from django.test import TestCase
from django.utils.importlib import import_module
from session_cleanup.tasks import cleanup
import datetime
class CleanupTest(TestCase):
def test_session_cleanup(self):
"""
Tests that sessions a... | from django.conf import settings
from django.core.cache import cache
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import timezone
from django.utils.importlib import import_module
from session_cleanup.tasks import cleanup
import datetime
class CleanupTest(TestCas... | Update test for timezones & file-based sessions. | Update test for timezones & file-based sessions.
| Python | bsd-2-clause | sandersnewmedia/django-session-cleanup |
76ae7716090fde2dfad03de1635082644ac8fbb4 | account_wallet_sale/hooks.py | account_wallet_sale/hooks.py | # Copyright 2021 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, SUPERUSER_ID
from openupgradelib import openupgrade
def _rename_cagnotte(env):
columns = {
"sale_order_line": [
("account_cagnotte_id", "account_wallet_id"),
],
}
... | # Copyright 2021 ACSONE SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import api, SUPERUSER_ID
from openupgradelib import openupgrade
def _rename_cagnotte(env):
if not openupgrade.column_exists(
env.cr, "sale_order_line", "account_cagnotte_id"):
return
col... | Migrate only if former column exist | [14.0][IMP] account_wallet_sale: Migrate only if former column exist
| Python | agpl-3.0 | acsone/acsone-addons,acsone/acsone-addons,acsone/acsone-addons |
e6de5c8f3204b14bc822c769712e1c1d4ba0ee69 | slave/skia_slave_scripts/chromeos_compile.py | slave/skia_slave_scripts/chromeos_compile.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.
""" Compile step """
from utils import shell_utils
from build_step import BuildStep
from slave import slave_utils
import os
import... | #!/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.
""" Compile step """
from utils import shell_utils
from build_step import BuildStep
from slave import slave_utils
import os
import... | Remove no longer used extra boto file parameter | Remove no longer used extra boto file parameter
This doesn't break anything, but it isn't needed.
(RunBuilders:Test-ChromeOS-Alex-GMA3150-x86-Debug,Test-ChromeOS-Alex-GMA3150-x86-Release,Perf-ChromeOS-Alex-GMA3150-x86-Release)
R=rmistry@google.com
Review URL: https://codereview.chromium.org/17575017
git-svn-id: 32f... | Python | bsd-3-clause | google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Ti... |
5efc9c9d8bc226759574bf2334fffffab340e4ff | boxsdk/auth/developer_token_auth.py | boxsdk/auth/developer_token_auth.py | # coding: utf-8
from __future__ import unicode_literals, absolute_import
from six.moves import input
from .oauth2 import OAuth2
class DeveloperTokenAuth(OAuth2):
ENTER_TOKEN_PROMPT = 'Enter developer token: '
def __init__(self, get_new_token_callback=None, **kwargs):
self._get_new_token = get_new_... | # coding: utf-8
from __future__ import unicode_literals, absolute_import
from six.moves import input # pylint:disable=redefined-builtin
from .oauth2 import OAuth2
class DeveloperTokenAuth(OAuth2):
ENTER_TOKEN_PROMPT = 'Enter developer token: '
def __init__(self, get_new_token_callback=None, **kwargs):
... | Fix pylint error for redefined builtin input. | Fix pylint error for redefined builtin input.
| Python | apache-2.0 | Frencil/box-python-sdk,box/box-python-sdk,Frencil/box-python-sdk |
00323935eb8ff1ba5171da56dbb1587d46c48885 | nodeconductor/core/perms.py | nodeconductor/core/perms.py | from django.contrib.auth import get_user_model
from nodeconductor.core.permissions import StaffPermissionLogic
User = get_user_model()
PERMISSION_LOGICS = (
(get_user_model(), StaffPermissionLogic(any_permission=True)),
)
| from django.contrib.auth import get_user_model
from rest_framework.authtoken.models import Token
from nodeconductor.core.permissions import StaffPermissionLogic
User = get_user_model()
PERMISSION_LOGICS = (
(get_user_model(), StaffPermissionLogic(any_permission=True)),
(Token, StaffPermissionLogic(any_pe... | Allow deletion of tokens from admin (NC-224) | Allow deletion of tokens from admin (NC-224)
| Python | mit | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor |
61148ba3a9d863034336ca0b220762b012e5ad55 | papermill/tests/test_cli.py | papermill/tests/test_cli.py | """ Test the command line interface """
import pytest
from ..cli import _is_float, _resolve_type
@pytest.mark.parametrize("test_input,expected", [
("True", True),
("False", False),
("None", None),
(13.3, 13.3),
(10, 10),
("hello world", "hello world"),
(u"😍", u"😍"),
])
def test_resolve... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Test the command line interface """
import pytest
from ..cli import _is_float, _resolve_type
@pytest.mark.parametrize("test_input,expected", [
("True", True),
("False", False),
("None", None),
(13.3, 13.3),
(10, 10),
("hello world", "hello w... | Add default encoding for py2 | Add default encoding for py2
| Python | bsd-3-clause | nteract/papermill,nteract/papermill |
6299103d9f53a9db26cbb5609a8b93996c55d556 | pyconde/attendees/management/commands/export_badges.py | pyconde/attendees/management/commands/export_badges.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from pyconde.attendees.exporters import BadgeExporter
from pyconde.attendees.models import VenueTicket
class Command(BaseCommand):
option_list = Bas... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from pyconde.attendees.exporters import BadgeExporter
from pyconde.attendees.models import VenueTicket
class Command(BaseCommand):
option_list = Bas... | Allow to exclude ticket types from badge export | Allow to exclude ticket types from badge export
7 and 22 are partner program
| Python | bsd-3-clause | pysv/djep,EuroPython/djep,EuroPython/djep,pysv/djep,pysv/djep,EuroPython/djep,pysv/djep,pysv/djep,EuroPython/djep |
86f7badc8913783eb559a61569fc2b80ceedf744 | src/nfc/archive/dummy_archive.py | src/nfc/archive/dummy_archive.py | """Module containing `DummyArchive` class."""
class DummyArchive(object):
"""Trivial archive implementation for testing purposes."""
@staticmethod
def create(dir_path, stations, detectors, clip_classes):
return DummyArchive(stations, detectors, clip_classes)
def __init... | """Module containing `DummyArchive` class."""
class DummyArchive(object):
"""Trivial archive implementation for testing purposes."""
@staticmethod
def create(dir_path, stations, detectors, clip_classes):
return DummyArchive(stations, detectors, clip_classes)
def __init... | Add open and close methods to dummy archive. | Add open and close methods to dummy archive. | Python | mit | HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper,HaroldMills/Vesper |
1709c602b8a423d1eee6521c5e74987db0fc8b81 | fancypages/contrib/oscar_fancypages/mixins.py | fancypages/contrib/oscar_fancypages/mixins.py | from ... import mixins
class OscarFancyPageMixin(mixins.FancyPageMixin):
node_attr_name = 'category'
slug_url_kwarg = 'category_slug'
context_object_name = 'fancypage'
def get_context_data(self, **kwargs):
ctx = super(OscarFancyPageMixin, self).get_context_data(**kwargs)
ctx[self.cont... | from ... import mixins
class OscarFancyPageMixin(mixins.FancyPageMixin):
node_attr_name = 'category'
slug_url_kwarg = 'category_slug'
context_object_name = 'products'
def get_context_data(self, **kwargs):
ctx = super(OscarFancyPageMixin, self).get_context_data(**kwargs)
ctx['fancypage... | Change context object for product list view in Oscar contrib | Change context object for product list view in Oscar contrib
| Python | bsd-3-clause | tangentlabs/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages,socradev/django-fancypages,socradev/django-fancypages,socradev/django-fancypages |
31c68ae56801377327e2cc0901222a9d961a6502 | tests/integration/test_skytap.py | tests/integration/test_skytap.py | """
Integration tests for the Skytap XBlock.
"""
from xblockutils.studio_editable_test import StudioEditableBaseTest
class TestSkytap(StudioEditableBaseTest):
"""
Integration tests for the Skytap XBlock.
"""
| """
Integration tests for the Skytap XBlock.
"""
from xblockutils.studio_editable_test import StudioEditableBaseTest
class TestSkytap(StudioEditableBaseTest):
"""
Integration tests for the Skytap XBlock.
"""
def test_keyboard_layouts(self):
"""
"""
pass
| Add stub for integration test. | Add stub for integration test.
| Python | agpl-3.0 | open-craft/xblock-skytap,open-craft/xblock-skytap,open-craft/xblock-skytap |
b764e2ed3edbc089c1fa51659ddab30b5091a6a5 | salt/utils/validate/user.py | salt/utils/validate/user.py | # -*- coding: utf-8 -*-
'''
Various user validation utilities
'''
# Import python libs
import re
import logging
log = logging.getLogger(__name__)
def valid_username(user):
'''
Validates a username based on the guidelines in `useradd(8)`
'''
if type(user) not str:
return False
if len(use... | # -*- coding: utf-8 -*-
'''
Various user validation utilities
'''
# Import python libs
import re
import logging
log = logging.getLogger(__name__)
VALID_USERNAME= re.compile(r'[a-z_][a-z0-9_-]*[$]?', re.IGNORECASE)
def valid_username(user):
'''
Validates a username based on the guidelines in `useradd(8)`
... | Move re compilation to the module load | Move re compilation to the module load
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
600f809805e5ade5ff2a4f0db27f2d274b46e08e | pystock_crawler/settings.py | pystock_crawler/settings.py | # Scrapy settings for pystock-crawler project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'pystock-crawler'
EXPORT_FIELDS = (
# Price columns
'symbol'... | # Scrapy settings for pystock-crawler project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'pystock-crawler'
EXPORT_FIELDS = (
# Price columns
'symbol'... | Use dbm cache instead of file system | Use dbm cache instead of file system
| Python | mit | hsd315/pystock-crawler,eliangcs/pystock-crawler |
f630a15fff5b0a6af3d3d7a9ee908f8159e2d4b4 | tests/unit/test_spec_set.py | tests/unit/test_spec_set.py | import unittest
from piptools.datastructures import SpecSet
class TestSpecSet(unittest.TestCase):
def test_adding_specs(self):
"""Adding specs to a set."""
specset = SpecSet()
specset.add_spec('Django>=1.3')
assert 'Django>=1.3' in map(str, specset)
specset.add_spec('djan... | import unittest
from piptools.datastructures import SpecSet
class TestSpecSet(unittest.TestCase):
def test_adding_specs(self):
"""Adding specs to a set."""
specset = SpecSet()
specset.add_spec('Django>=1.3')
assert 'Django>=1.3' in map(str, specset)
specset.add_spec('djan... | Add a simple test case. | Add a simple test case.
| Python | bsd-2-clause | suutari/prequ,suutari/prequ,suutari-ai/prequ |
4d4a639ba46cf72454497bc100b3e811e66af4b2 | tests/test_deprecations.py | tests/test_deprecations.py | # -*- coding: utf-8 -*-
"""
tests.deprecations
~~~~~~~~~~~~~~~~~~
Tests deprecation support. Not used currently.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
| # -*- coding: utf-8 -*-
"""
tests.deprecations
~~~~~~~~~~~~~~~~~~
Tests deprecation support. Not used currently.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import pytest
import flask
class TestRequestDeprecation(object):
def test_request_json(... | Add test for deprecated flask.Request properties. | Add test for deprecated flask.Request properties.
| Python | bsd-3-clause | moluzhang/flask,karen-wang/flask,happyspace/flask,alanhamlett/flask,kuhli/flask,auready/flask,margguo/flask,tcnoviembre2013/flask,rollingstone/flask,wudafucode/flask,mysweet/flask,drewja/flask,tcnoviembre2013/flask,karen-wang/flask,horica-ionescu/flask,nwags/flask,cgvarela/flask,sam-tsai/flask,postelin/flask,jiimaho/fl... |
83eef98bd8cf36e62718c60f2bba71337a9a9ea0 | kolibri/plugins/coach/kolibri_plugin.py | kolibri/plugins/coach/kolibri_plugin.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from . import hooks
from kolibri.core.auth.constants.user_kinds import COACH
from kolibri.core.hooks import NavigationHook
from kolibri.core.hooks import RoleBasedRedirectHook
from kolibri.core.webpack ... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from kolibri.core.auth.constants.user_kinds import COACH
from kolibri.core.hooks import NavigationHook
from kolibri.core.hooks import RoleBasedRedirectHook
from kolibri.core.webpack import hooks as webp... | Remove undefined import in coach plugin. | Remove undefined import in coach plugin.
| Python | mit | indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,mrpau/kolibri,mrpau/kolibri,learningequality/kolibri,indirectlylit/kolibri,indirectlylit/kolibri,learningequality/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri |
d18e4681ac4fb8465cc100f600a86063c71b96f3 | txircd/modules/cmd_names.py | txircd/modules/cmd_names.py | from twisted.words.protocols import irc
from txircd.modbase import Command
class NamesCommand(Command):
def onUse(self, user, data):
for chan in data["targetchan"]:
user.report_names(chan)
def processParams(self, user, params):
if user.registered > 0:
user.sendMessage(irc.ERR_NOTREGISTERED, "NAMES", ":Yo... | from twisted.words.protocols import irc
from txircd.modbase import Command
class NamesCommand(Command):
def onUse(self, user, data):
for chan in data["targetchan"]:
user.report_names(chan)
def processParams(self, user, params):
if user.registered > 0:
user.sendMessage(irc.ERR_NOTREGISTERED, "NAMES", ":Yo... | Send "no such channel" message on NAMES with a nonexistent channel | Send "no such channel" message on NAMES with a nonexistent channel
| Python | bsd-3-clause | Heufneutje/txircd,ElementalAlchemist/txircd,DesertBus/txircd |
b0edd701f2adbe5b62a1f87ae17474b1ba91d674 | hxl/commands/hxlvalidate.py | hxl/commands/hxlvalidate.py | """
Command function to schema-validate a HXL dataset.
David Megginson
November 2014
Can use a whitelist of HXL tags, a blacklist, or both.
Usage:
import sys
from hxl.scripts.hxlvalidate import hxlvalidate
hxlvalidate(sys.stdin, sys.stdout, open('MySchema.csv', 'r'))
License: Public Domain
Documentation: htt... | """
Command function to schema-validate a HXL dataset.
David Megginson
November 2014
Can use a whitelist of HXL tags, a blacklist, or both.
Usage:
import sys
from hxl.scripts.hxlvalidate import hxlvalidate
hxlvalidate(sys.stdin, sys.stdout, open('MySchema.csv', 'r'))
License: Public Domain
Documentation: htt... | Add callback to control output. | Add callback to control output.
| Python | unlicense | HXLStandard/libhxl-python,HXLStandard/libhxl-python |
563aba155f5df0465bd7f96734ae8b598e693465 | 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,
timeout=self.timeout)
def put(self, queue, message):
self.client... | 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... | Make redis backend work with redis-py 1.34.1 | Make redis backend work with redis-py 1.34.1
| Python | bsd-3-clause | ask/ghettoq |
cc9084c744b3ba3525f464adeaa7edaea64abf41 | torchtext/data/pipeline.py | torchtext/data/pipeline.py | class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
... | class Pipeline(object):
"""Defines a pipeline for transforming sequence data."""
def __init__(self, convert_token=None):
if convert_token is None:
self.convert_token = lambda x: x
elif callable(convert_token):
self.convert_token = convert_token
else:
... | Fix bug in Pipeline call where we run the whole Pipeline on list input | Fix bug in Pipeline call where we run the whole Pipeline on list input
| Python | bsd-3-clause | pytorch/text,pytorch/text,pytorch/text,pytorch/text |
d7cb638c8a9505623dced1811b48b32ab73ebc71 | hello/logo_grab.py | hello/logo_grab.py | import requests
from bs4 import BeautifulSoup
try:
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlparse
urlparse = urlparse.urlparse
try:
ConnectionError
except NameError:
ConnectionError = ValueError
YAHOO_ENDPOINT = "http://finance.yahoo.com/q/pr?s={}"
CLEARBIT_ENDP... | import requests
from bs4 import BeautifulSoup
try:
from urllib.parse import urlparse
except ImportError:
from urllib2 import urlparse
urlparse = urlparse.urlparse
try:
ConnectionError
except NameError:
ConnectionError = ValueError
YAHOO_ENDPOINT = "http://finance.yahoo.com/q/pr?s={}"
CLEARBIT_ENDP... | Raise exception on not found ticker | Raise exception on not found ticker
| Python | mit | qwergram/GroupProject1,qwergram/GroupProject1,qwergram/GroupProject1 |
d46d0b5a5392b6ca047b519a9d6280b5b0581e81 | system_maintenance/tests/functional/tests.py | system_maintenance/tests/functional/tests.py | from django.test import LiveServerTestCase
from selenium import webdriver
class FunctionalTest(LiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_app_home_title(self):
... | from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
class FunctionalTest(StaticLiveServerTestCase):
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def... | Switch to 'StaticLiveServerTestCase' to avoid having to set 'settings.STATIC_ROOT' | Switch to 'StaticLiveServerTestCase' to avoid having to set 'settings.STATIC_ROOT'
| Python | bsd-3-clause | mfcovington/django-system-maintenance,mfcovington/django-system-maintenance,mfcovington/django-system-maintenance |
f7f23a85931a2fb3ba3decafb9b8ebf2c1ec4594 | arxiv_vanity/sitemaps.py | arxiv_vanity/sitemaps.py | from django.contrib.sitemaps import Sitemap
from .papers.models import Paper
class PaperSitemap(Sitemap):
changefreq = "monthly"
priority = 0.5
limit = 2000
def items(self):
return Paper.objects.only("arxiv_id", "updated").all()
def lastmod(self, obj):
return obj.updated
sitema... | import datetime
from django.contrib.sitemaps import Sitemap
from django.utils import timezone
from .papers.models import Paper
class PaperSitemap(Sitemap):
priority = 0.5
limit = 2000
def items(self):
return Paper.objects.only("arxiv_id", "updated").all()
def lastmod(self, obj):
retu... | Index old papers less often | Index old papers less often
| Python | apache-2.0 | arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity,arxiv-vanity/arxiv-vanity |
ce28b359122475f544b9ae3bc9e05a5bc02377e4 | conda_kapsel/internal/py2_compat.py | conda_kapsel/internal/py2_compat.py | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... | # -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... | Fix unicode keys in addition to values for windows/py2 environment | Fix unicode keys in addition to values for windows/py2 environment
| Python | bsd-3-clause | conda/kapsel,conda/kapsel |
b5980bfef36d93413d2056e2bde74958fc1db6b4 | checks.d/linux_vm_extras.py | checks.d/linux_vm_extras.py | # project
from checks import AgentCheck
VM_COUNTS = {
'pgpgin': 'pages.in',
'pgpgout': 'pages.out',
'pswpin': 'pages.swapped_in',
'pswpout': 'pages.swapped_out',
'pgfault': 'pages.faults',
'pgmajfault': 'pages.major_faults'
}
class MoreLinuxVMCheck(AgentCheck):
def check(self, instance):
... | # project
from checks import AgentCheck
VM_COUNTS = {
'pgpgin': 'pages.in',
'pgpgout': 'pages.out',
'pswpin': 'pages.swapped_in',
'pswpout': 'pages.swapped_out',
'pgfault': 'pages.faults',
'pgmajfault': 'pages.major_faults'
}
class MoreLinuxVMCheck(AgentCheck):
def check(self, instance):
... | Fix bug that was causing this to not even work at all | Fix bug that was causing this to not even work at all
| Python | mit | stripe/datadog-checks,stripe/stripe-datadog-checks |
3ec54fbabd6f17eabb90ead66a87bc2723a00aa0 | mvw/generator.py | mvw/generator.py | import os
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(outputdir, root[... | import os
import shutil
class Generator:
def run(self, sourcedir, outputdir):
sourcedir = os.path.normpath(sourcedir)
outputdir = os.path.normpath(outputdir)
prefix = len(sourcedir)+len(os.path.sep)
for root, dirs, files in os.walk(sourcedir):
destpath = os.path.join(ou... | Create destination path if it does no exist and copy file using shutil | Create destination path if it does no exist and copy file using shutil
| Python | mit | kevinbeaty/mvw |
ebec31105582235c8aa74e9bbfd608b9bf103ad1 | calico_containers/tests/st/utils.py | calico_containers/tests/st/utils.py | import sh
from sh import docker
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
intf = sh.ifconfig.eth0()
return sh.perl(intf, "-ne", 's/dr:(\S+)/print $1/e')
def cleanup_inside(name):
"""
Clean the inside of a container by deleting the containers and images within it.... | import sh
from sh import docker
import socket
def get_ip():
"""Return a string of the IP of the hosts eth0 interface."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
def cleanup_inside(name):
"""
Clean the... | Use socket connection to get own IP. | Use socket connection to get own IP.
| Python | apache-2.0 | L-MA/calico-docker,webwurst/calico-docker,TrimBiggs/calico-containers,quater/calico-containers,quater/calico-containers,robbrockbank/calicoctl,caseydavenport/calico-containers,caseydavenport/calico-docker,TrimBiggs/calico-containers,projectcalico/calico-containers,projectcalico/calico-containers,robbrockbank/calico-con... |
3e3ead7d9eb05c2fd713d83510cf08b46cf21f15 | skimage/viewer/qt/QtCore.py | skimage/viewer/qt/QtCore.py | from . import qt_api
if qt_api == 'pyside':
from PySide.QtCore import *
elif qt_api == 'pyqt':
from PyQt4.QtCore import *
else:
# Mock objects
Qt = None
| from . import qt_api
if qt_api == 'pyside':
from PySide.QtCore import *
elif qt_api == 'pyqt':
from PyQt4.QtCore import *
else:
# Mock objects
Qt = None
pyqtSignal = None
| Add mock pyqtSignal to try to get Travis to build | Add mock pyqtSignal to try to get Travis to build
| Python | bsd-3-clause | Britefury/scikit-image,oew1v07/scikit-image,almarklein/scikit-image,Hiyorimi/scikit-image,GaZ3ll3/scikit-image,Hiyorimi/scikit-image,dpshelio/scikit-image,ofgulban/scikit-image,ClinicalGraphics/scikit-image,paalge/scikit-image,vighneshbirodkar/scikit-image,youprofit/scikit-image,jwiggins/scikit-image,chriscrosscutler/s... |
aa974a2d12020e324db222b022594d9e489e559f | convert.py | convert.py | import argparse
import numpy as np
from PIL import Image
lookup = " .,:-?X#"
def image_to_ascii(image):
"""
PIL image object -> 2d array of values
"""
quantised = image.quantize(len(lookup))
quantised.show()
array = np.asarray(quantised.resize((128,64)))
return [[lookup[k] for k in i... | import argparse
import numpy as np
from PIL import Image
lookup = " .,:-!?X#"
def image_to_ascii(image, width=128):
"""
PIL image object -> 2d array of values
"""
def scale_height(h, w, new_width):
print "original height: {}".format(h)
print "original width: {}".format(w)
pr... | CORRECT height/width conversion this time around | CORRECT height/width conversion this time around
| Python | mit | machineperson/fantastic-doodle |
d4c8b0f15cd1694b84f8dab7936571d9f9bca42f | tests/people/test_managers.py | tests/people/test_managers.py | import pytest
from components.people.factories import IdolFactory
from components.people.models import Idol
from components.people.constants import STATUS
pytestmark = pytest.mark.django_db
class TestIdols:
@pytest.fixture
def idols(self):
idols = []
[idols.append(IdolFactory(status=STATUS.a... | # -*- coding: utf-8 -*-
import datetime
import pytest
from components.people.constants import STATUS
from components.people.factories import GroupFactory, IdolFactory
from components.people.models import Group, Idol
pytestmark = pytest.mark.django_db
class TestIdols:
@pytest.fixture
def status(self):
... | Test group managers. Rename idols() => status(). | Test group managers. Rename idols() => status().
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web |
6bcd2ffc67dfbb1265d4df1f69de8e8b45376889 | src/foremast/slacknotify/slack_notification.py | src/foremast/slacknotify/slack_notification.py | """Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
self.inf... | """Notify Slack channel."""
import time
from ..utils import get_properties, get_template, post_slack_message
class SlackNotification:
"""Post slack notification.
Inform users about infrastructure changes to prod* accounts.
"""
def __init__(self, app=None, env=None, prop_path=None):
self.inf... | Resolve `message` variable missing error | fix: Resolve `message` variable missing error
| Python | apache-2.0 | gogoair/foremast,gogoair/foremast |
bf51352142f0ca2f2eed50c6862135d0d00baaa9 | corehq/tests/test_toggles.py | corehq/tests/test_toggles.py | from __future__ import absolute_import, unicode_literals
from corehq import toggles
from corehq.toggles import ALL_TAGS
def test_toggle_properties():
"""
Check toggle properties
"""
for toggle in toggles.all_toggles():
assert toggle.slug
assert toggle.label, 'Toggle "{}" label missing... | from __future__ import absolute_import, unicode_literals
from corehq import toggles
from corehq.toggles import ALL_TAGS
def test_toggle_properties():
"""
Check toggle properties
"""
for toggle in toggles.all_toggles():
assert toggle.slug
assert toggle.label, 'Toggle "{}" label missing... | Add comment to solutions sub-tags test | Add comment to solutions sub-tags test
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq |
3ca3f9473d7031ef9536f56c253ba0a4b7e1ee6e | test/unit/ggrc/converters/test_query_helper.py | test/unit/ggrc/converters/test_query_helper.py | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
import unittest
import mock
from ggrc.converters import query_helper
class TestQueryHelper(unittest.TestCase):
def test_expression_keys(self):
""" test expression keys function
Make sure it wo... | # Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
import unittest
import mock
from ggrc.converters import query_helper
class TestQueryHelper(unittest.TestCase):
def test_expression_keys(self):
""" test expression keys function
Make sure it wo... | Update unit tests with new query helper names | Update unit tests with new query helper names
| Python | apache-2.0 | j0gurt/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,edofic/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,josthkko/g... |
eb4322eb0744d07cb10442ab16d50384aabe1478 | cumulusci/core/tests/test_github.py | cumulusci/core/tests/test_github.py | import unittest
from cumulusci.core.github import get_github_api
class TestGithub(unittest.TestCase):
def test_github_api_retries(self):
gh = get_github_api('TestUser', 'TestPass')
adapter = gh._session.get_adapter('http://')
self.assertEqual(0.3, adapter.max_retries.backoff_factor)
... | from http.client import HTTPMessage
import io
import unittest
import mock
from cumulusci.core.github import get_github_api
class MockHttpResponse(mock.Mock):
def __init__(self, status):
super(MockHttpResponse, self).__init__()
self.status = status
self.strict = 0
self.version = ... | Test that github requests are actually retried | Test that github requests are actually retried
| Python | bsd-3-clause | SalesforceFoundation/CumulusCI,SalesforceFoundation/CumulusCI |
509990ffdaec354b09d34aae63e1851a2e8a2038 | tests/test_address_book.py | tests/test_address_book.py | from unittest import TestCase
from address_book import AddressBook, Person, Group
class AddressBookTestCase(TestCase):
def test_add_person(self):
address_book = AddressBook()
person = Person(
'John',
'Doe',
['Russian Federation, Kemerovo region, Kemerovo, Kiro... | from unittest import TestCase
from address_book import AddressBook, Person, Group
class AddressBookTestCase(TestCase):
def test_add_person(self):
address_book = AddressBook()
person = Person(
'John',
'Doe',
['Russian Federation, Kemerovo region, Kemerovo, Kiro... | Add test for finding a person by first name | Add test for finding a person by first name
| Python | mit | dizpers/python-address-book-assignment |
8bf27ff0e112781724d0a8a28b1b3d44976f0155 | lfs_order_numbers/models.py | lfs_order_numbers/models.py | # django imports
from django.utils.translation import ugettext_lazy as _
from django.db import models
# lfs imports
from lfs.plugins import OrderNumberGenerator as Base
class OrderNumberGenerator(Base):
"""Generates order numbers and saves the last one.
**Attributes:**
id
The primary key of the... | # django imports
from django.utils.translation import ugettext_lazy as _
from django.db import models
# lfs imports
from lfs.plugins import OrderNumberGenerator as Base
class OrderNumberGenerator(Base):
"""Generates order numbers and saves the last one.
**Attributes:**
id
The primary key of the... | Check whether there is a format given (this must be checked for validity though). | Check whether there is a format given (this must be checked for validity though).
| Python | bsd-3-clause | diefenbach/lfs-order-numbers |
ccc76f356a0480767eceff83d2b573aa922896f5 | package/management/commands/repo_updater.py | package/management/commands/repo_updater.py | import logging
import logging.config
from django.core.management.base import NoArgsCommand
from django.utils import timezone
from package.models import Package
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = "Updates all the packages in the system focusing on repo data"
def hand... | import logging
import logging.config
from django.core.management.base import NoArgsCommand
from django.utils import timezone
from package.models import Package
logger = logging.getLogger(__name__)
class Command(NoArgsCommand):
help = "Updates all the packages in the system focusing on repo data"
def hand... | Fix the last_fetched and repo commands | Fix the last_fetched and repo commands
| Python | mit | QLGu/djangopackages,QLGu/djangopackages,nanuxbe/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,nanuxbe/djangopackages,pydanny/djangopackages,pydanny/djangopackages,QLGu/djangopackages |
d0038096e800f7a25d848225ecb8f9c885ce5758 | adhocracy4/projects/views.py | adhocracy4/projects/views.py | from django.shortcuts import redirect
from django.views import generic
from rules.contrib import views as rules_views
from . import mixins, models
class ProjectDetailView(rules_views.PermissionRequiredMixin,
mixins.PhaseDispatchMixin,
generic.DetailView):
model = ... | from django.shortcuts import redirect
from django.views import generic
from rules.contrib import views as rules_views
from . import mixins, models
class ProjectDetailView(rules_views.PermissionRequiredMixin,
mixins.PhaseDispatchMixin,
generic.DetailView):
model = ... | Remove request membership feature from project | Remove request membership feature from project
- add in euth.memberships app
| Python | agpl-3.0 | liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4 |
2f5f2112c4c6b97b76fd268d1e79537dac696f0e | src/nyc_trees/apps/home/training/decorators.py | src/nyc_trees/apps/home/training/decorators.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from functools import wraps
from django.db import transaction
from django.http import Http404
from django.contrib.flatpages.views import flatpage
def render_flatpage(url):
def ... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from functools import wraps
from django.db import transaction
from django.http import Http404
from django.contrib.flatpages.views import flatpage
def render_flatpage(url):
def ... | Add support for arbitrary user actions on marking | Add support for arbitrary user actions on marking
| Python | agpl-3.0 | azavea/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees |
627ceb6adff6a2f954048b7641ac3b68d19ef019 | experiments/stop_motion_tool/stop_motion_tool.py | experiments/stop_motion_tool/stop_motion_tool.py | from cam import OpenCV_Cam
import cv2
cam = OpenCV_Cam(0)
cam.size = (1920, 1080)
KEY_ESC = 27
KEY_SPACE = ord(' ')
prevFrame = None
i = 0
fourcc = cv2.cv.CV_FOURCC(*'XVID')
video = cv2.VideoWriter('output.avi',fourcc, 3.0, (1920,1080), isColor =True)
while True:
# Capture frame-by-frame
frame = cam.read(... | from cam import OpenCV_Cam
import cv2
import os.path
cam = OpenCV_Cam(0)
cam.size = (1920, 1080)
KEY_ESC = 27
KEY_SPACE = ord(' ')
prevFrame = None
i = 0
fname="frame.png"
if os.path.isfile(fname):
prevFrame = cv2.imread(fname)
fourcc = cv2.cv.CV_FOURCC(*'XVID')
video = cv2.VideoWriter('output.avi',fourcc, 3... | Add support for presenter and continuing frame capture | Add support for presenter and continuing frame capture
Click the right click of the presenter will trigger frame capture.
| Python | mit | fatcloud/PyCV-time |
0050711d85ba4084e9d0f32d3bad1b3400350476 | name/feeds.py | name/feeds.py | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse_lazy
from django.utils.feedgenerator import Atom1Feed
from . import app_settings
from .models import Name
class NameAtomFeedType(Atom1Feed):
"""Create an Atom feed that sets the Content-Type response
header to appl... | from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse_lazy
from django.utils.feedgenerator import Atom1Feed
from . import app_settings
from .models import Name
class NameAtomFeedType(Atom1Feed):
"""Create an Atom feed that sets the Content-Type response
header to appl... | Add the location as a georss:point element. | Add the location as a georss:point element.
| Python | bsd-3-clause | damonkelley/django-name,damonkelley/django-name,unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,unt-libraries/django-name |
21f2a2a053c5d5cc24651a8aefd8c24357a85223 | demos/minimal.py | demos/minimal.py | #!/usr/bin/env python
from gi.repository import GtkClutter
GtkClutter.init([])
from gi.repository import GObject, Gtk, GtkChamplain
GObject.threads_init()
GtkClutter.init([])
window = Gtk.Window(type=Gtk.WindowType.TOPLEVEL)
window.connect("destroy", Gtk.main_quit)
widget = GtkChamplain.Embed()
widget.set_size_req... | #!/usr/bin/env python
# To run this example, you need to set the GI_TYPELIB_PATH environment
# variable to point to the gir directory:
#
# export GI_TYPELIB_PATH=$GI_TYPELIB_PATH:/usr/local/lib/girepository-1.0/
from gi.repository import GtkClutter
GtkClutter.init([])
from gi.repository import GObject, Gtk, GtkChampl... | Add description how to run the python demo | Add description how to run the python demo
| Python | lgpl-2.1 | Distrotech/libchamplain,Distrotech/libchamplain,Distrotech/libchamplain,Distrotech/libchamplain,Distrotech/libchamplain |
d174159ef6af50ec28146fd0a91ea3d677ee234f | tests/integration/test_redirection_absolute.py | tests/integration/test_redirection_absolute.py | """Check REDIRECTIONS"""
import io
import os
import pytest
import nikola.plugins.command.init
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test... | """Check REDIRECTIONS"""
import io
import os
import pytest
import nikola.plugins.command.init
from nikola import __main__
from .helper import append_config, cd
from .test_demo_build import prepare_demo_site
from .test_empty_build import ( # NOQA
test_archive_exists,
test_avoid_double_slash_in_rss,
test... | Refactor tests in preparation of the merge of redirect tests. | Refactor tests in preparation of the merge of redirect tests.
| Python | mit | getnikola/nikola,okin/nikola,getnikola/nikola,okin/nikola,getnikola/nikola,okin/nikola,okin/nikola,getnikola/nikola |
6d54cbe4eb1e946bdc96dc4701dd6d5ab164c63e | oshino/agents/subprocess_agent.py | oshino/agents/subprocess_agent.py | import asyncio
from . import Agent
from asyncio.subprocess import PIPE
class SubprocessAgent(Agent):
@property
def script(self):
return self._data["script"]
def is_valid(self):
return "script" in self._data
async def process(self, event_fn):
logger = self.get_logger()
... | import asyncio
from . import Agent
from asyncio.subprocess import PIPE
class SubprocessAgent(Agent):
@property
def script(self):
return self._data["script"]
def is_valid(self):
return "script" in self._data
async def process(self, event_fn):
logger = self.get_logger()
... | Add postfix for subprocess metric | Add postfix for subprocess metric
| Python | mit | CodersOfTheNight/oshino |
7db97c8d50091bd91bf8cb874fe3540eff499510 | fabfile.py | fabfile.py | from fabric.api import cd, sudo, env
env.path = '/var/praekelt/vumi-go'
def deploy_go():
with cd(env.path):
sudo('git pull', user='vumi')
_venv_command('./ve/bin/django-admin.py collectstatic --pythonpath=. '
'--settings=go.settings --noinput')
def deploy_vumi():
with ... | from fabric.api import cd, sudo, env
env.path = '/var/praekelt/vumi-go'
def deploy_go():
with cd(env.path):
sudo('git pull', user='vumi')
_venv_command('./ve/bin/django-admin.py collectstatic --pythonpath=. '
'--settings=go.settings --noinput')
def deploy_vumi():
with ... | Add command for updating the node.js modules needed by the JS sandbox. | Add command for updating the node.js modules needed by the JS sandbox.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
723d97a490a3d0d5e04d118343ac0574cda74476 | tests/matchers/test_equal.py | tests/matchers/test_equal.py | from robber import expect
from robber.matchers.equal import Equal, NotEqual
class TestEqual:
def test_matches(self):
expect(Equal(1, 1).matches()).to.eq(True)
expect(Equal(1, 2).matches()).to.eq(False)
def test_failure_message(self):
equal = Equal('actual', 'expected')
message... | from robber import expect
from robber.matchers.equal import Equal, NotEqual
class TestEqual:
def test_matches(self):
expect(Equal(1, 1).matches()).to.eq(True)
expect(Equal(1, 2).matches()).to.eq(False)
def test_failure_message(self):
equal = Equal('actual', 'expected')
message... | Add failure message test for not_to.be.eq | [f] Add failure message test for not_to.be.eq
| Python | mit | vesln/robber.py |
55a056346c2707b80663c56b59e58724cc72ace6 | django_react_templatetags/mixins.py | django_react_templatetags/mixins.py | class RepresentationMixin(object):
@property
def react_representation(self):
raise NotImplementedError(
'Missing property react_representation in class'
)
| class RepresentationMixin(object):
def to_react_representation(self, context=None):
raise NotImplementedError(
'Missing property to_react_representation in class'
)
| Switch NotImplementedError to to_react_represetnation in mixin | Switch NotImplementedError to to_react_represetnation in mixin
| Python | mit | Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags |
945bb3897abb55e1b0f4f9fc97644bc22dd54208 | simuvex/concretization_strategies/__init__.py | simuvex/concretization_strategies/__init__.py | from angr.concretization_strategies.any import SimConcretizationStrategyAny
from angr.concretization_strategies.max import SimConcretizationStrategyMax
from angr.concretization_strategies.nonzero import SimConcretizationStrategyNonzero
from angr.concretization_strategies.nonzero_range import SimConcretizationStrategyNo... | from angr.concretization_strategies import *
from angr.concretization_strategies.any import SimConcretizationStrategyAny
from angr.concretization_strategies.max import SimConcretizationStrategyMax
from angr.concretization_strategies.nonzero import SimConcretizationStrategyNonzero
from angr.concretization_strategies.non... | Fix compat bug in concretization_strategies | Fix compat bug in concretization_strategies
| Python | bsd-2-clause | angr/simuvex |
f2c8b94d35c5f0676dd99ad61df6daabf6d21d46 | recipe_site/urls.py | recipe_site/urls.py | """recipe_site URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | """recipe_site URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | Add homepage to the recipe site | Add homepage to the recipe site
| Python | mit | kgarrison343/recipe-site,kgarrison343/recipe-site |
0f83ba67a4db2cdacbd3679479d26dbb584da978 | testing/models/test_epic.py | testing/models/test_epic.py | from __future__ import with_statement, print_function
import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import models
@pytest.fixture
def epic():
return models.EPIC(epic_id=12345, ra=12.345, dec=67.894,
mag=None, campaign_id=1)
def test... | from __future__ import with_statement, print_function
import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import models
from k2catalogue import detail_object
@pytest.fixture
def epic():
return models.EPIC(epic_id=12345, ra=12.345, dec=67.894,
... | Add test for integration of DetailObject and EPIC | Add test for integration of DetailObject and EPIC
| Python | mit | mindriot101/k2catalogue |
132b354f03d10ebc5a55152fef30ffbfb4b82a28 | tests/dev/test_horoscope.py | tests/dev/test_horoscope.py | # coding=utf-8
from unittest import TestCase
from click.testing import CliRunner
import yoda
class TestHoroscope(TestCase):
"""
Test for the following commands:
| Module: dev
| command: horoscope
"""
def __init__(self, methodName='runTest'):
super(TestHoroscope, self).__... | # coding=utf-8
import sys
from unittest import TestCase
from click.testing import CliRunner
import yoda
class TestHoroscope(TestCase):
"""
Test for the following commands:
| Module: dev
| command: horoscope
"""
def __init__(self, methodName='runTest'):
super(TestHoroscop... | Fix broken test for Python 2.x/3.x | Fix broken test for Python 2.x/3.x
| Python | mit | dude-pa/dude |
58db8bc908c36522bdb781e61ee5fb7dd79a9911 | webapp/byceps/blueprints/shop_admin/service.py | webapp/byceps/blueprints/shop_admin/service.py | # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
from collections import Counter
def count_ordered_articles(article):
"""Count how often the article has been ordered, grouped by the
order's payment state.
... | # -*- coding: utf-8 -*-
"""
byceps.blueprints.shop_admin.service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2014 Jochen Kupperschmidt
"""
from collections import Counter
from ..shop.models import PaymentState
def count_ordered_articles(article):
"""Count how often the article has been ordered, grou... | Make sure every payment state is | Make sure every payment state is
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps |
0774388eec3e405966828d5e2137abbd3dd29f1c | createcppfiles.py | createcppfiles.py | #!/usr/bin/python
import sys
import os
def createHeader(guard, namespace):
return "#ifndef {}_HPP\n#define {}_HPP\n\n{}\n\n#endif".format(guard, guard, namespace)
def createSource(name, namespace):
return '#include "{}.hpp"\n\n{}'.format(name, namespace)
def createNamespace(namespace):
return "names... | #!/usr/bin/python
import sys
import os
def createHeader(guard, namespace):
return "#ifndef {}_HPP\n#define {}_HPP\n\n{}\n\n#endif".format(guard, guard, namespace)
def createSource(name, namespace):
return '#include "{}.hpp"\n\n{}'.format(name, namespace)
def createNamespace(namespace):
return "namespace... | Prepend namespace in include guards | Prepend namespace in include guards
| Python | mit | mphe/scripts,mall0c/scripts,mall0c/scripts,mphe/scripts |
e58c78fea4b604905333b490a22e640477d5e2d5 | django_pytest/test_runner.py | django_pytest/test_runner.py | def run_tests(test_labels, verbosity=1, interactive=True, extra_tests=[]):
import sys
from pkg_resources import load_entry_point
sys.argv[1:] = sys.argv[2:]
# Remove stop word (--) from argument list again. This separates Django
# command options from py.test ones.
try:
del sys.argv[sys... | class TestRunner(object):
def __init__(self, verbosity=1, interactive=True, failfast=True, **kwargs):
self.verbosity = verbosity
self.interactive = interactive
self.failfast = failfast
def run_tests(self, test_labels):
import pytest
import sys
if test_labels is ... | Add a new TestRunner class to remove Django deprecation warnings | Add a new TestRunner class to remove Django deprecation warnings
| Python | bsd-3-clause | buchuki/django-pytest,0101/django-pytest |
d4d25c87fc3eb9cfe1406d2a857b93c69d389850 | parser.py | parser.py | import os
import re
import json
class Parser(object):
"""Parse output from Speedtest CLI into JSON"""
def parse_all(self):
records = []
for file in os.listdir("data"):
if file.endswith(".speedtest.txt"):
records.append(self.parse("data/" + file))
return json... | import os
import re
import json
class Parser(object):
"""Parse output from Speedtest CLI into JSON"""
def parse_all(self):
# needs:
# labels (timestamps)
# data (ping/dl/ul speed)
records = []
labels = []
download_speeds = []
for file in os.listdir("data... | Format parsed speed data for use in Chart.js | Format parsed speed data for use in Chart.js
| Python | mit | ruralocity/speedchart,ruralocity/speedchart |
858a286b66fc3301acd93d847534c0d9ab2afcb5 | ckanext/stadtzhtheme/tests/test_validation.py | ckanext/stadtzhtheme/tests/test_validation.py | import nose
from ckanapi import LocalCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
lc = LocalCKAN()
try:
dataset = factories.Datas... | import nose
from ckanapi import TestAppCKAN, ValidationError
from ckan.tests import helpers, factories
eq_ = nose.tools.eq_
assert_true = nose.tools.assert_true
class TestValidation(helpers.FunctionalTestBase):
def test_invalid_url(self):
factories.Sysadmin(apikey="my-test-key")
app = self._get_t... | Use TestAppCKAN in test instead of LocalCKAN | Use TestAppCKAN in test instead of LocalCKAN
| Python | agpl-3.0 | opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme |
15beb35fff1ea343dc42cf4acc0e9ad5e64cef33 | abilian/testing/__init__.py | abilian/testing/__init__.py | """Base stuff for testing.
"""
from flask.ext.testing import TestCase
from abilian.application import Application
from abilian.core.entities import db
class TestConfig(object):
SQLALCHEMY_DATABASE_URI = "sqlite://"
SQLALCHEMY_ECHO = False
class BaseTestCase(TestCase):
config_class = TestConfig
def creat... | """Base stuff for testing.
"""
from flask.ext.testing import TestCase
from abilian.application import Application
from abilian.core.entities import db
class TestConfig(object):
SQLALCHEMY_DATABASE_URI = "sqlite://"
SQLALCHEMY_ECHO = False
TESTING = True
class BaseTestCase(TestCase):
config_class = TestCo... | Add TESTING-True in test config. | Add TESTING-True in test config.
| Python | lgpl-2.1 | abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core,abilian/abilian-core |
6dc0540bef999ca26d32a24fec39f2b4dde77bb5 | pjson/core.py | pjson/core.py | import json
import sys
if sys.version_info[0] == 2:
from StringIO import StringIO
else:
from io import StringIO
from pygments import highlight
from pygments.formatters import TerminalFormatter
from xml.etree import ElementTree as ET
import xmlformatter
def format_code(data, is_xml=False):
"""
Parses d... | import json
import sys
from pygments import highlight
from pygments.formatters import TerminalFormatter
from xml.etree import ElementTree as ET
import xmlformatter
def format_code(data, is_xml=False):
"""
Parses data and formats it
"""
if is_xml:
ET.fromstring(data) # Make sure XML is valid
... | Add support for special characters | Add support for special characters
| Python | mit | igorgue/pjson |
18ec52a1c34e263e4d909fc1ee19500f9adac26b | examples/django_example/example/app/models.py | examples/django_example/example/app/models.py | from django.db import models
# Create your models here.
| # Define a custom User class to work with django-social-auth
from django.contrib.auth.models import AbstractUser, UserManager
class CustomUser(AbstractUser):
objects = UserManager()
| Define a custom user model | Define a custom user model
| Python | bsd-3-clause | S01780/python-social-auth,tobias47n9e/social-core,falcon1kr/python-social-auth,ByteInternet/python-social-auth,muhammad-ammar/python-social-auth,contracode/python-social-auth,S01780/python-social-auth,clef/python-social-auth,lawrence34/python-social-auth,python-social-auth/social-storage-sqlalchemy,fearlessspider/pytho... |
c476cb5cf1bead63f19871fa1db9769e236fbe09 | siren_files.py | siren_files.py | #!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfile... | #!/usr/bin/python
#
source_files = ['check_siren.py', 'colours', 'credits', 'dataview', 'dijkstra_4',
'displayobject', 'displaytable', 'editini', 'flexiplot', 'floaters',
'getmap', 'getmerra2', 'getmodels', 'grid', 'indexweather', 'inisyntax',
'makegrid', 'makeweatherfile... | Remove makeweatherfiles, add template for Windows version file | Remove makeweatherfiles, add template for Windows version file
| Python | agpl-3.0 | ozsolarwind/siren,ozsolarwind/siren |
ecfa18b1c6d8dfd565ab625b3bb600d2d792310f | src/bitmessageqt/widgets.py | src/bitmessageqt/widgets.py | from PyQt4 import uic
import os.path
import sys
def resource_path(path):
try:
return os.path.join(sys._MEIPASS, path)
except:
return os.path.join(os.path.dirname(__file__), path)
def load(path, widget):
uic.loadUi(resource_path(path), widget)
| from PyQt4 import uic
import os.path
import sys
from shared import codePath
def resource_path(resFile):
baseDir = codePath()
for subDir in ["ui", "bitmessageqt"]:
if os.path.isdir(os.path.join(baseDir, subDir)) and os.path.isfile(os.path.join(baseDir, subDir, resFile)):
return os.path.join(... | Change UI loading for frozen | Change UI loading for frozen
| Python | mit | debguy0x/PyBitmessage,bmng-dev/PyBitmessage,hb9kns/PyBitmessage,hb9kns/PyBitmessage,timothyparez/PyBitmessage,torifier/PyBitmessage,hb9kns/PyBitmessage,debguy0x/PyBitmessage,debguy0x/PyBitmessage,torifier/PyBitmessage,timothyparez/PyBitmessage,torifier/PyBitmessage,timothyparez/PyBitmessage,bmng-dev/PyBitmessage,torifi... |
b94edbbb717313cc831fa97d3ccf9ab715ff3ade | testing/test_cffitsio.py | testing/test_cffitsio.py | from cffitsio import FitsFile
import os
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = FitsFile.create(filename)
assert os.path.isfile(filename)
| import pytest
import cffitsio
import os
@pytest.fixture
def test_dir():
return os.path.join(
os.path.dirname(__file__),
'data')
def test_create_file(tmpdir):
filename = str(tmpdir.join('test.fits'))
f = cffitsio.FitsFile.create(filename)
assert os.path.isfile(filename)
def test_open... | Add test for opening file | Add test for opening file
| Python | mit | mindriot101/fitsio-cffi |
1f10a9c4cf5e00a8290adfe6ee34542e35ffab9b | OpenPNM/Algorithms/__init__.py | OpenPNM/Algorithms/__init__.py | r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Clas... | r"""
###############################################################################
:mod:`OpenPNM.Algorithms` -- Algorithms on Networks
###############################################################################
Contents
--------
This submodule contains algorithms for performing simulations on pore networks
Clas... | Add new percolation alg to init - to be renamed later | Add new percolation alg to init - to be renamed later
| Python | mit | TomTranter/OpenPNM,PMEAL/OpenPNM |
7ab7154c1393491bd2874484e02c6af6eb3bb7e7 | tests/test_functional.py | tests/test_functional.py | """Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging font... | """Functional tests
Test will produce the following tuple of all path permutations
paths = ['path/to/font_a', 'path/to/font_b']
[
(path/to/font_a, path/to/font_b),
(path/to/font_b, path/to/font_a),
]
and run them through our main diff_fonts functions.
This test is slow and should be run on challenging font... | Call diff_fonts with correct params | Call diff_fonts with correct params
| Python | apache-2.0 | googlefonts/fontdiffenator,googlefonts/fontdiffenator |
4e4112b548cc263da2a455c2db9a2c82a3f84e45 | ecommerce/theming/models.py | ecommerce/theming/models.py | import logging
from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
logger = logging.getLogger(__name__)
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey)... | from django.conf import settings
from django.contrib.sites.models import Site
from django.db import models
class SiteTheme(models.Model):
"""
This is where the information about the site's theme gets stored to the db.
Fields:
site (ForeignKey): Foreign Key field pointing to django Site model
... | Revert "Added logging to SiteTheme.get_theme" | Revert "Added logging to SiteTheme.get_theme"
This reverts commit f1436a255bb22ecd7b9ddca803240262bf484981.
| Python | agpl-3.0 | edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce,edx/ecommerce,edx/ecommerce,edx/ecommerce,eduNEXT/edunext-ecommerce,eduNEXT/edunext-ecommerce |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.