commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
c65607ba08bcfb2c939a37354ba6dcace5179e4e | add control flows in main() | oeg8168/PTT-ID-correlator | PTT-ID-correlator.py | PTT-ID-correlator.py | import argparse
from src.PTTcrawler import PTTcrawler
from src.PTTpushAnalyser import PTTpushAnalyser
def main():
args = parseArguments()
pushAnalyser = PTTpushAnalyser()
if args.update:
print('=== update ===')
crawler = PTTcrawler()
crawler.crawlHotBoards()
elif args.run_s... | import argparse
def parseArguments():
cmdArgsParser = argparse.ArgumentParser()
cmdGroup = cmdArgsParser.add_mutually_exclusive_group(required=True)
cmdGroup.add_argument('--update', action='store_true',
help='Update database')
cmdGroup.add_argument('--run_save_all', action... | mit | Python |
b07fb6df50384709f3708fe060b4f50ac3516fa7 | Read words from the database instead of a static list | scottferg/Profanity-Modifier | ProfanityModifier.py | ProfanityModifier.py | from waveapi import events
from waveapi import model
from waveapi import robot
from google.appengine.ext import db
from ProfanityDatabase import ProfaneWord
def OnBlipSubmitted( properties, context ):
"""Invoked when a new blip has been submitted"""
blip = context.GetBlipById( properties['blipId'] )
conte... | from waveapi import events
from waveapi import model
from waveapi import robot
def OnBlipSubmitted( properties, context ):
"""Invoked when a new blip has been submitted"""
blip = context.GetBlipById( properties['blipId'] )
ReplaceProfanity( blip )
def OnWaveletBlipCreated( properties, context ):
"""In... | bsd-3-clause | Python |
90c2a47b7732ffed01a58624852b5be59a6f0051 | make Equation visible | olivierverdier/SpecTraVVave | travwave/equations/__init__.py | travwave/equations/__init__.py | from .base import Equation
from . import kdv
from . import whitham
from . import benjamin
| from . import kdv
from . import whitham
from . import benjamin
| bsd-3-clause | Python |
6f4db3a59e1f5c918cb04a13fba7270f7edea583 | test refactor of gate class | cjwfuller/quantum-circuits | test_gate.py | test_gate.py | import numpy as np
import unittest
import gate
class TestGate(unittest.TestCase):
def test_standard_gates_implemented(self):
gate.QuantumGate('paulix')
gate.QuantumGate('pauliy')
gate.QuantumGate('pauliz')
gate.QuantumGate('swap')
gate.QuantumGate('cnot')
gate.Quantu... | import numpy as np
import unittest
import gate
class TestGate(unittest.TestCase):
def test_paulix_is_unitary(self):
qg = gate.QuantumGate(np.matrix('0 1; 1 0', np.complex_))
def test_pauliy_is_unitary(self):
qg = gate.QuantumGate(np.matrix('0 -1i; 1i 0', np.complex_))
def test_pauliz_is_u... | mit | Python |
80416d89b01bba03eab3d4f97058fd030629d32c | Add more test vectors (still unstable) | hajimes/mmh3,hajimes/mmh3,hajimes/mmh3 | test_mmh3.py | test_mmh3.py | # -*- coding: utf-8 -*-
import mmh3
# see also https://stackoverflow.com/a/1375939
def u32_to_s32(v):
if(v & 0x80000000):
return -0x100000000 + v
else:
return v
# Note that MurmurHash3 is endian-sensitive.
# In big-endian environments, these tests may fail.
def test_hash_value():
assert mm... | import mmh3
# Note that MurmurHash3 is endian-sensitive.
# In big-endian environments, these tests may fail.
def test_hash_value():
assert mmh3.hash('foo') == -156908512
# Several test vectors devised by Ian Boyd
# https://stackoverflow.com/a/31929528
assert mmh3.hash('', seed=0) == 0
assert ... | cc0-1.0 | Python |
bcd43672cc69f1a6650a5ae9d728da6b3e1c4878 | Clean up relative imports | rmcgurrin/PyQLab,calebjordan/PyQLab,Plourde-Research-Lab/PyQLab,BBN-Q/PyQLab | tests/QGL.py | tests/QGL.py | import unittest
import numpy as np
from ..QGL import *
class SingleQubit(unittest.TestCase):
def test_Ramsey(self):
'''
Test simple Ramsey sequence
'''
q1 = Qubit('q1', piAmp=1.0, pi2Amp=0.5, pulseLength=30e-9)
ramsey = [[X90(q1), Id(q1, delay), X90(q1)] for delay in np.l... | import unittest
import numpy as np
class SingleQubit(unittest.TestCase):
def test_Ramsey(self):
'''
Test simple Ramsey sequence
'''
q1 = Qubit('q1', piAmp=1.0, pi2Amp=0.5, pulseLength=30e-9)
ramsey = [[X90(q1), Id(q1, delay), X90(q1)] for delay in np.linspace(0.0, 1e-6, 11... | apache-2.0 | Python |
fe5e14e836c117059c9095379599efaeb8ad6fd5 | Make answer_image read only | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | app/grandchallenge/reader_studies/admin.py | app/grandchallenge/reader_studies/admin.py | from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from grandchallenge.reader_studies.models import (
Answer,
Question,
ReaderStudy,
ReaderStudyPermissionRequest,
)
class ReaderStudyAdmin(GuardedModelAdmin):
exclude = ("images",)
class AnswersAdmin(GuardedModelAdmin):... | from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from grandchallenge.reader_studies.models import (
Answer,
Question,
ReaderStudy,
ReaderStudyPermissionRequest,
)
class ReaderStudyAdmin(GuardedModelAdmin):
exclude = ("images",)
class AnswersAdmin(GuardedModelAdmin):... | apache-2.0 | Python |
f8504c615f135fb6fd4443d026b8425e6818e3a1 | Speed up the API view | comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django,comic/comic-django | app/grandchallenge/reader_studies/views.py | app/grandchallenge/reader_studies/views.py | from django.views.generic import ListView, CreateView, DetailView, UpdateView
from rest_framework.viewsets import ReadOnlyModelViewSet
from grandchallenge.cases.forms import UploadRawImagesForm
from grandchallenge.cases.models import RawImageUploadSession
from grandchallenge.core.permissions.mixins import UserIsStaffM... | from django.views.generic import ListView, CreateView, DetailView, UpdateView
from rest_framework.viewsets import ReadOnlyModelViewSet
from grandchallenge.cases.forms import UploadRawImagesForm
from grandchallenge.cases.models import RawImageUploadSession
from grandchallenge.core.permissions.mixins import UserIsStaffM... | apache-2.0 | Python |
673817c007c4b863257df7e9ca1747dc28ed2331 | Complete documentation for can_write | Ghostkeeper/Luna | plugins/storage/localstorage/local_storage.py | plugins/storage/localstorage/local_storage.py | #!/usr/bin/env python
#This is free and unencumbered software released into the public domain.
#
#Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
#software, either in source code form or as a compiled binary, for any purpose,
#commercial or non-commercial, and by any means.
#
#In jurisd... | #!/usr/bin/env python
#This is free and unencumbered software released into the public domain.
#
#Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
#software, either in source code form or as a compiled binary, for any purpose,
#commercial or non-commercial, and by any means.
#
#In jurisd... | cc0-1.0 | Python |
09f7de801532cc877a7e887e00d91f1cd3cb1b77 | fix org invite api client | alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin | app/notify_client/org_invite_api_client.py | app/notify_client/org_invite_api_client.py | from app.notify_client import NotifyAdminAPIClient, _attach_current_user
from app.notify_client.models import InvitedOrgUser
class OrgInviteApiClient(NotifyAdminAPIClient):
def __init__(self):
super().__init__("a" * 73, "b")
def init_app(self, app):
super().init_app(app)
self.admin_u... | from app.notify_client import NotifyAdminAPIClient, _attach_current_user
from app.notify_client.models import InvitedOrgUser
class OrgInviteApiClient(NotifyAdminAPIClient):
def __init__(self):
super().__init__("a" * 73, "b")
def init_app(self, app):
self.base_url = app.config['API_HOST_NAME']... | mit | Python |
3589103bb13c7eeffef3012711b71f9133e453c4 | reset sample client | nabla-c0d3/nassl,nabla-c0d3/nassl,nabla-c0d3/nassl | sample_client.py | sample_client.py | from pathlib import Path
from nassl.ssl_client import OpenSslVersionEnum, SslClient, OpenSslVerifyEnum
import socket
mozilla_store = Path("tests") / "mozilla.pem"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect(("www.yahoo.com", 443))
ssl_client = SslClient(
ssl_version=O... | from pathlib import Path
from nassl.ssl_client import OpenSslVersionEnum, SslClient, OpenSslVerifyEnum
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect(("localhost", 443))
ssl_client = SslClient(
ssl_version=OpenSslVersionEnum.TLSV1_2,
underlying_socket=s... | agpl-3.0 | Python |
bde5b888f12f4079cd6e2158eb53740ae6c8efb7 | Add batch tag | benjspriggs/tumb-borg | tumb_borg.py | tumb_borg.py | #!/usr/bin/python
import sys
from process import *
from config import *
from authorize import *
from pprint import pprint
from interactive import *
BATCH = "poem, poetry, spilled ink"
def authorize_from_config(filename):
c = app_config(filename)
return authorize(c['key'], c['secret'], c['callback'])
def po... | #!/usr/bin/python
import sys
from process import *
from config import *
from authorize import *
from pprint import pprint
from interactive import *
def authorize_from_config(filename):
c = app_config(filename)
return authorize(c['key'], c['secret'], c['callback'])
def post_poems(auth, ident, poem_generator)... | apache-2.0 | Python |
e258462635626a32995475b6455eb694b87633a8 | Support completely custom codecs for strings | gulopine/steel-experiment | steel/fields/strings.py | steel/fields/strings.py | import codecs
from gettext import gettext as _
from steel.fields import Field
from steel.fields.mixin import Fixed
__all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString']
class Bytes(Field):
_("A stream of bytes that should be left unconverted")
# Nothing to do here
pass
class Stri... | import codecs
from gettext import gettext as _
from steel.fields import Field
from steel.fields.mixin import Fixed
__all__ = ['Bytes', 'String', 'FixedBytes', 'FixedString']
class Bytes(Field):
_("A stream of bytes that should be left unconverted")
# Nothing to do here
pass
class Stri... | bsd-3-clause | Python |
8f11010226c233c99a0c7ea9cca44a233f192616 | Bump version | stellargraph/stellargraph,stellargraph/stellargraph | stellargraph/version.py | stellargraph/version.py | # -*- coding: utf-8 -*-
#
# Copyright 2018-2020 Data61, CSIRO
#
# 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 applicabl... | # -*- coding: utf-8 -*-
#
# Copyright 2018-2020 Data61, CSIRO
#
# 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 applicabl... | apache-2.0 | Python |
837b767036f580a8c9d523e0f6c175a75d1dc3b2 | Add get_config as GPIO action | HydAu/ProjectWeekds_Pi-Control-Service,projectweekend/Pi-Control-Service | pi_control_service/gpio_service.py | pi_control_service/gpio_service.py | from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read', 'get_config')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
... | from rpc import RPCService
from pi_pin_manager import PinManager
ALLOWED_ACTIONS = ('on', 'off', 'read')
class GPIOService(RPCService):
def __init__(self, rabbit_url, device_key, pin_config):
self.pins = PinManager(config_file=pin_config)
super(GPIOService, self).__init__(
rabbit_ur... | mit | Python |
e5a103d223976523a5af2c42117ace90a7fa9233 | Allow connections from container subnets to database instance | tobiasmcnulty/aws-container-basics,caktus/aws-web-stacks | stack/database.py | stack/database.py | from troposphere import (
ec2,
rds,
Ref,
AWS_STACK_NAME,
)
from .template import template
from .vpc import (
vpc,
container_a_subnet,
container_a_subnet_cidr,
container_b_subnet,
container_b_subnet_cidr,
)
db_security_group = ec2.SecurityGroup(
'DatabaseSecurityGroup',
tem... | from troposphere import (
rds,
Ref,
AWS_STACK_NAME,
)
from .template import template
from .vpc import (
container_a_subnet,
container_b_subnet,
)
db_subnet_group = rds.DBSubnetGroup(
"DatabaseSubnetGroup",
template=template,
DBSubnetGroupDescription="Subnets available for the RDS DB I... | mit | Python |
1d4e4d73fbe787678a20f984dfb028b84c4ac204 | update didn't switch branches properly | sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary,sassoftware/conary | updatecmd.py | updatecmd.py | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import changeset
import database
import helper
import log
import os
import repository
import sys
import util
def doUpdate(repos, db, cfg, pkg, versionStr = None, replaceFiles = False):
cs = None
if not os.path.exists(cfg.root):
util.mkdirCha... | #
# Copyright (c) 2004 Specifix, Inc.
# All rights reserved
#
import changeset
import database
import helper
import log
import os
import repository
import sys
import util
def doUpdate(repos, db, cfg, pkg, versionStr = None, replaceFiles = False):
cs = None
if not os.path.exists(cfg.root):
util.mkdirCha... | apache-2.0 | Python |
f39969e84eee39aaa7eab44b86db6cce02d38ffc | Add owner permission | migonzalvar/teamroulette,mfernandezmsistemas/phyton1 | teams/viewsets.py | teams/viewsets.py | from rest_framework.viewsets import ModelViewSet
from . import models
from rest_framework.permissions import BasePermission
class IsOwnerPermission(BasePermission):
def has_object_permission(self, request, view, obj):
return request.user == obj.owner
class TeamViewSet(ModelViewSet):
model = models.Te... | from rest_framework.viewsets import ModelViewSet
from . import models
class TeamViewSet(ModelViewSet):
model = models.Team
class PlayerViewSet(ModelViewSet):
model = models.Player
| mit | Python |
e57ed43a391088d087eef2a798fc080fb2ede6bb | Use the iterative task iterator for the ProgramConversion update. | MatthewWilkes/mw4068-packaging,MatthewWilkes/mw4068-packaging,MatthewWilkes/mw4068-packaging,MatthewWilkes/mw4068-packaging | app/soc/tasks/updates/module_conversion.py | app/soc/tasks/updates/module_conversion.py | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | #!/usr/bin/python2.5
#
# Copyright 2009 the Melange authors.
#
# 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... | apache-2.0 | Python |
9992d5cab23aef885f1e03f61954020802ce6d96 | Update states-pelican.py | lvl1/salt-formulas | states-pelican.py | states-pelican.py | import salt.exceptions
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_state = __salt__['pelican.current_... | import salt.exceptions
import subprocess
def build_site(name, output="/srv/www"):
# /srv/salt/_states/pelican.py
# Generates static site with pelican -o $output $name
# Sorry.
# -- Jadon Bennett, 2015
ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''}
current_state = __salt__... | mit | Python |
0b32d49b3d271969d5c4d98708398804e074ac30 | add print statement so that we know what's happening. | camswords/raspberry-pi-instagram-printer,camswords/raspberry-pi-instagram-printer | src/instagram-printer.py | src/instagram-printer.py | #!/usr/bin/env python
from lib.system import System
from lib.media_repository import MediaRepository
from lib.media_server import MediaServer
from lib.support_team import SupportTeam
import signal
import traceback
import time
import os
class InstagramPrinter:
def __init__(self):
signal.signal(signal.SIGIN... | #!/usr/bin/env python
from lib.system import System
from lib.media_repository import MediaRepository
from lib.media_server import MediaServer
from lib.support_team import SupportTeam
import signal
import traceback
import time
import os
class InstagramPrinter:
def __init__(self):
signal.signal(signal.SIGIN... | mit | Python |
f8fa22fa557f8a36516b1b4cf3890eacd2d6be08 | Add hash | Wanderfalke/stellar,fastmonkeys/stellar,orf/stellar | stellar/models.py | stellar/models.py | import sqlalchemy as sa
from datetime import datetime
from database import Base
import uuid
import hashlib
def get_unique_hash():
return hashlib.md5(str(uuid.uuid4())).hexdigest()
class Snapshot(Base):
__tablename__ = 'snapshot'
id = sa.Column(sa.Integer, sa.Sequence('snapshot_id_seq'), primary_key=True... | import sqlalchemy as sa
from datetime import datetime
from database import Base
class Snapshot(Base):
__tablename__ = 'snapshot'
id = sa.Column(sa.Integer, sa.Sequence('snapshot_id_seq'), primary_key=True)
snapshot_name = sa.Column(sa.String(255), nullable=False)
project_name = sa.Column(sa.String(255... | mit | Python |
28656a72521e436b1ad27ae3c07d98b5468ce082 | fix sleep | floort/buienbadge | testbuienradar.py | testbuienradar.py | import urequests
import ugfx
import network
import badge
import time
sta_if = network.WLAN(network.STA_IF); sta_if.active(True) # Activate standalone interface
sta_if.scan() # Scan for available access points
sta_if.connect("SHA2017-insecure") ... | import urequests
import ugfx
import network
import badge
sta_if = network.WLAN(network.STA_IF); sta_if.active(True) # Activate standalone interface
sta_if.scan() # Scan for available access points
sta_if.connect("SHA2017-insecure") # ... | unlicense | Python |
16b59ba419ff2c7643bbdcfdc6a7a07bf9800c25 | add test user creation support covering MySQL versions 5.6-8.0+ | eywalker/datajoint-python,dimitri-yatsenko/datajoint-python,datajoint/datajoint-python | tests/__init__.py | tests/__init__.py | """
Package for testing datajoint. Setup fixture will be run
to ensure that proper database connection and access privilege
exists. The content of the test database will be destroyed
after the test.
"""
import logging
from os import environ, remove
import datajoint as dj
from distutils.version import StrictVersion
__... | """
Package for testing datajoint. Setup fixture will be run
to ensure that proper database connection and access privilege
exists. The content of the test database will be destroyed
after the test.
"""
import logging
from os import environ, remove
import datajoint as dj
__author__ = 'Edgar Walker, Fabian Sinz, Dimit... | lgpl-2.1 | Python |
98e9e04019ebc6f9b3959b180356513877113a28 | add the note for some StorageAbstractAdapter method | free-free/pyblog,free-free/pyblog,free-free/pyblog,free-free/pyblog | app/tools/storage/storage_abstract.py | app/tools/storage/storage_abstract.py | #-*- coding:utf-8 -*-
import logging
logging.basicConfig(level=logging.ERROR)
class StorageAbstractAdapter(object):
r'''
A abatract interface class ,that provides a common interface to access it for different third party service
'''
def __init__(self,*args,**kw):
r'''
The init parameter is unique for diffe... | #-*- coding:utf-8 -*-
import logging
logging.basicConfig(level=logging.ERROR)
class StorageAbstractAdapter(object):
def __init__(self,*args,**kw):
pass
def move(self,src,dest):
pass
def copy(self,src,dest):
pass
def delete(self,src):
pass
def file_size(self,file_name):
pass
def file_hash(self,file_nam... | mit | Python |
aef64d59b34e4485b79812f6e623c17d28d27324 | Work around pytest change to markers | moble/spherical_functions | tests/conftest.py | tests/conftest.py | # Copyright (c) 2019, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
import os
import pytest
import numpy as np
import quaternion
from spherical_functions import ell_max as ell_max_default
def pytest_addoption(parser):
parser.addoption("--ell_max"... | # Copyright (c) 2019, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/spherical_functions/blob/master/LICENSE>
import os
import pytest
import numpy as np
import quaternion
from spherical_functions import ell_max as ell_max_default
def pytest_addoption(parser):
parser.addoption("--ell_max"... | mit | Python |
23fbfbcf08f49c26b4edef9fd5fbec65246ba8e0 | add snapshot and guest property callback setters | mjdorma/pyvbox | virtualbox/library_ext/vbox.py | virtualbox/library_ext/vbox.py | import virtualbox
from virtualbox import library
"""
Add helper code to the default ISession class.
"""
# Configure IVirtualBox bootstrap to build from vboxapi getVirtualBox
class IVirtualBox(library.IVirtualBox):
__doc__ = library.IVirtualBox.__doc__
def __init__(self, interface=None, manager=None):
... | import virtualbox
from virtualbox import library
"""
Add helper code to the default ISession class.
"""
# Configure IVirtualBox bootstrap to build from vboxapi getVirtualBox
class IVirtualBox(library.IVirtualBox):
__doc__ = library.IVirtualBox.__doc__
def __init__(self, interface=None, manager=None):
... | apache-2.0 | Python |
b360b18a2e544d2d75006c9215570894ff111826 | use tmpdir.open | eugene-eeo/scell | tests/conftest.py | tests/conftest.py | from sys import stdout, stderr
from scell import Selector
from pytest import fixture
@fixture(params=['w', 'r', 'rw'])
def mode(request):
return request.param
@fixture
def handle(request, tmpdir):
fp = tmpdir.join('file')
fp.write('')
return fp.open(mode='r+')
@fixture(params=['stdio', 'files'])
d... | from sys import stdout, stderr
from scell import Selector
from pytest import fixture
@fixture(params=['w', 'r', 'rw'])
def mode(request):
return request.param
@fixture
def handle(request, tmpdir):
fp = tmpdir.join('file')
fp.write('')
return open(str(fp), mode='r+')
@fixture(params=['stdio', 'file... | mit | Python |
6f8b5950a85c79ed33c1d00a35a1def2efc7bff5 | Make the tests run just via py.test | kalasjocke/hyp | tests/conftest.py | tests/conftest.py | from factories import post_factory, post
import os
import sys
root = os.path.join(os.path.dirname(__file__))
package = os.path.join(root, '..')
sys.path.insert(0, os.path.abspath(package))
| from factories import post_factory, post
| mit | Python |
e6a3f69d61a49a5d7ae2b053cdd79289e11a8a73 | Fix compatibility issues in Django 1.8. | charettes/django-sundial | sundial/fields.py | sundial/fields.py | from __future__ import unicode_literals
import django
from django.db import models
from django.utils.encoding import force_text
from django.utils.six import with_metaclass
from . import forms
from .utils import coerce_timezone
TimezoneFieldBase = type if django.VERSION >= (1, 8) else models.SubfieldBase
class Tim... | from __future__ import unicode_literals
import django
from django.db import models
from django.utils.encoding import force_text
from django.utils.six import with_metaclass
from . import forms
from .utils import coerce_timezone
TimezoneFieldBase = type if django.VERSION >= (1, 8) else models.SubfieldBase
class Tim... | mit | Python |
df41a1ba43c6ebb94951f0228ee68287ad4c0e60 | set handler name for tests.waiter.handler dynamically | treemo/circuits,nizox/circuits,eriol/circuits,eriol/circuits,eriol/circuits,treemo/circuits,treemo/circuits | tests/conftest.py | tests/conftest.py | # Module: conftest
# Date: 6th December 2010
# Author: James Mills, prologic at shortcircuit dot net dot au
"""py.test config"""
from time import sleep
import collections
from circuits import Component
class Waiter(Component):
flag = False
def handler(self, *args, **kwargs):
self.flag = Tr... | # Module: conftest
# Date: 6th December 2010
# Author: James Mills, prologic at shortcircuit dot net dot au
"""py.test config"""
from time import sleep
import collections
from circuits import Component
class Waiter(Component):
flag = False
def handler(self, *args, **kwargs):
self.flag = Tr... | mit | Python |
df8f136c2635afedf263e023c8b9e05a757b8d20 | Remove database session and tables after pytest fixture-based test runs, too | homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps | tests/conftest.py | tests/conftest.py | """
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from contextlib import contextmanager
import pytest
from byceps.database import db as _db
from tests.base import CONFIG_FILENAME_TEST_ADMIN, \
CONFIG_FILENAME_TEST_PARTY, create_app
from tests.helpers import crea... | """
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from contextlib import contextmanager
import pytest
from byceps.database import db as _db
from tests.base import CONFIG_FILENAME_TEST_ADMIN, \
CONFIG_FILENAME_TEST_PARTY, create_app
from tests.helpers import crea... | bsd-3-clause | Python |
508e78f7f35562f1f49a120de43eaa7331657531 | Refactor scripts/index.py | yeonghoey/yeonghoey,yeonghoey/yeonghoey,yeonghoey/notes,yeonghoey/yeonghoey,yeonghoey/yeonghoey | scripts/index.py | scripts/index.py | from collections import defaultdict
from pathlib import Path
import re
from string import Template
import sys
def tree():
return defaultdict(tree)
root = tree()
for src in Path('content').glob('**/README.org'):
path = re.sub(r'^content/(.*)/README.org$', r'\1', str(src))
segments = path.split('/')
... | from pathlib import Path
import re
from string import Template
import sys
with open('README.org') as f:
main = f.read()
def to_link(src):
return re.sub(r'^content/(.*)/README.org$', r'./\1', src)
def to_name(link):
_, _, name = link.rpartition('/')
return name
def to_indent(link):
_, n = re.s... | mit | Python |
26ab3b3d2ec2b456586a1962da3bfd9729ff7830 | use alignment_score in unit test | lowerquality/gentle,lowerquality/gentle,lowerquality/gentle,lowerquality/gentle | tests/e2e_test.py | tests/e2e_test.py | # -*- coding: utf-8 -*-
import json
import os
import unittest
from nose.tools import assert_greater, assert_less
from gentle.language_model_transcribe import lm_transcribe
from gentle.alignment_score import alignment_score
@unittest.skipIf(os.environ.get('SHORT') == 'true', 'skipping for short test')
def test_metas... | # -*- coding: utf-8 -*-
from nose.tools import assert_equals
import json
import os
import unittest
from gentle.language_model_transcribe import lm_transcribe
@unittest.skipIf(os.environ.get('SHORT') == 'true', 'skipping for short test')
def test_metasentence_tokenization():
with open("tests/data/lucier_golden.json"... | mit | Python |
4d402b74e95be19c823b1e5a1f5f0cc8eb297e7a | Fix too-long line | opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme,opendatazurich/ckanext-stadtzh-theme | ckanext/stadtzhtheme/logic.py | ckanext/stadtzhtheme/logic.py | import pysolr
from ckan.plugins.toolkit import get_or_bust, side_effect_free
from ckan.logic import ActionError
from ckan.lib.search.common import make_connection
import ckan.plugins.toolkit as tk
import logging
log = logging.getLogger(__name__)
@side_effect_free
def ogdzh_autosuggest(context, data_dict):
"""
... | import pysolr
from ckan.plugins.toolkit import get_or_bust, side_effect_free
from ckan.logic import ActionError
from ckan.lib.search.common import make_connection
import ckan.plugins.toolkit as tk
import logging
log = logging.getLogger(__name__)
@side_effect_free
def ogdzh_autosuggest(context, data_dict):
"""
... | agpl-3.0 | Python |
11bcc53bc80409a0458e3a5b72014c9837561b65 | Add MIT license that shows up in `pip show rlbot` | drssoccer55/RLBot,drssoccer55/RLBot | src/main/python/setup.py | src/main/python/setup.py | import setuptools
__version__ = None # This will get replaced when reading version.py
exec(open('rlbot/version.py').read())
with open("README.md", "r") as readme_file:
long_description = readme_file.read()
setuptools.setup(
name='rlbot',
packages=setuptools.find_packages(),
install_requires=['psuti... | import setuptools
__version__ = None # This will get replaced when reading version.py
exec(open('rlbot/version.py').read())
with open("README.md", "r") as readme_file:
long_description = readme_file.read()
setuptools.setup(
name='rlbot',
packages=setuptools.find_packages(),
install_requires=['psuti... | mit | Python |
6e7639bc318b55eca2c9215f73f1075dd1e9b609 | Update settings.py | raiderrobert/django-webhook | tests/settings.py | tests/settings.py | """
Testing mini-project and tests in one
"""
from __future__ import unicode_literals
from django.conf import settings
if __name__ == '__main__':
settings.configure()
DEBUG = True
ROOT_URLCONF = 'tests.urls'
DATABASES = {'default': {}}
SECRET_KEY = "not so secret"
| """
Testing mini-project and tests in one
"""
from __future__ import unicode_literals
from django.conf import settings
if __name__ == '__main__':
settings.configure()
DEBUG = True
ROOT_URLCONF = 'tests.urls'
DATABASES = {'default': {}}
SECRET_KEY = "not so secret"
| mit | Python |
18e9b8bc088e892ffc7a3c433cd6ea736c5a6536 | add convert_dict_to_tuple test, add more cases to argument hash tests | tkaemming/autocache | tests/unit.py | tests/unit.py | from autocache.hashing import argument_hash, bytecode_hash, source_hash
from autocache.utils import convert_dict_to_tuple
def test_callable_hashing():
"""
Test callable hashing implementations.
"""
def foo(x):
return x
def bar(x):
return x
# assert runtime determinism
ass... | from autocache.hashing import argument_hash, bytecode_hash, source_hash
def test_callable_hashing():
"""
Test callable hashing implementations.
"""
def foo(x):
return x
def bar(x):
return x
# assert runtime determinism
assert bytecode_hash(foo) == bytecode_hash(foo)
a... | mit | Python |
2d2761b5633d1f81d5a4bc0683b5bfbf2c72aef1 | Update util.py | adobe-apiplatform/user-sync.py,adorton-adobe/user-sync.py,adobe-apiplatform/user-sync.py,adorton-adobe/user-sync.py | tests/util.py | tests/util.py | import collections
def update_dict(d, ks, u):
k, ks = ks[0], ks[1:]
v = d.get(k)
if ks and isinstance(v, collections.Mapping):
d[k] = update_dict(v, ks, u)
else:
d[k] = u
return d
| import collections
def update_dict(d, ks, u):
k, ks = ks[0], ks[1:]
v = d.get(k)
if isinstance(v, collections.Mapping) and ks:
d[k] = update_dict(v, ks, u)
else:
d[k] = u
return d
| mit | Python |
c7991ca7149e0152fc9c092473ac8d136ca01265 | Use a new ALE instance for each tests case | toslunar/chainerrl,toslunar/chainerrl | tests/test_ale.py | tests/test_ale.py | import unittest
import random
import tempfile
import sys
from PIL import Image
import numpy as np
import ale
class TestALE(unittest.TestCase):
def setUp(self):
pass
def test_state(self):
env = ale.ALE('breakout.bin')
self.assertEquals(env.state.shape, (4, 84, 84))
self.asse... | import unittest
import random
import tempfile
import sys
from PIL import Image
import numpy as np
import ale
class TestALE(unittest.TestCase):
def setUp(self):
self.env = ale.ALE('pong.bin')
def test_state(self):
self.env.initialize()
self.assertEquals(self.env.state.shape, (4, 84,... | mit | Python |
3314464c414187de572888a6d4996bf0ed1a0e6e | test new alert | guardian/alerta,skob/alerta,guardian/alerta,mrkeng/alerta,guardian/alerta,mrkeng/alerta,skob/alerta,guardian/alerta,mrkeng/alerta,skob/alerta,mrkeng/alerta,skob/alerta | tests/test_app.py | tests/test_app.py | import json
import unittest
from alerta.app import app
class AppTestCase(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.app = app.test_client()
self.alert = {
'event': 'Foo',
'resource': 'Bar',
'environment': 'Production',
... |
import unittest
from alerta.app import app
class AppTestCase(unittest.TestCase):
def setUp(self):
app.config['TESTING'] = True
self.app = app.test_client()
def tearDown(self):
pass
def test_debug_output(self):
response = self.app.get('/_')
self.assertEqual(r... | apache-2.0 | Python |
60d6e576d7b1ee2ca114e4a4e2e7484fe2b981a8 | Remove test_collect_inventory_complex_from_directory() as the exact same test exists in test_model.py | dejacode/about-code-tool,dejacode/about-code-tool | tests/test_cmd.py | tests/test_cmd.py | #!/usr/bin/env python
# -*- coding: utf8 -*-
# ============================================================================
# Copyright (c) 2014 nexB Inc. http://www.nexb.com/ - All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wi... | #!/usr/bin/env python
# -*- coding: utf8 -*-
# ============================================================================
# Copyright (c) 2014 nexB Inc. http://www.nexb.com/ - All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wi... | apache-2.0 | Python |
197b77c0d4a7a4bb9f8f326c9d08e605a8ce1280 | fix env | mhinz/neovim-remote,mhinz/neovim-remote | tests/test_nvr.py | tests/test_nvr.py | #!/usr/bin/env python3
import os
import time
import signal
import subprocess
import nvr
env = {'NVIM_LISTEN_ADDRESS': '/tmp/pytest_nvimsock'}
testfile = '/tmp/pytest_file'
class Nvim:
nvim = None
def start(self, env=env):
env.update(os.environ)
self.nvim = subprocess.Popen(['nvim', '-nu', '... | #!/usr/bin/env python3
import os
import time
import signal
import subprocess
import nvr
env = {'NVIM_LISTEN_ADDRESS': '/tmp/pytest_nvimsock'}
testfile = '/tmp/pytest_file'
class Nvim:
nvim = None
def start(self, env={}):
env.update(os.environ)
self.nvim = subprocess.Popen(['nvim', '-nu', 'N... | mit | Python |
eb75dc830536254360fb3d9d4a9d8a4c505ee542 | Revert "tests: disable bitbucket tests because Travis-CI chooses the obsolete TLS 1.0 protocol" | lilydjwg/nvchecker | tests/test_vcs.py | tests/test_vcs.py | # MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import os
import shutil
import pytest
pytestmark = pytest.mark.asyncio
@pytest.mark.skipif(shutil.which("git") is None,
reason="requires git command")
async def test_git(get_version):
os.path.exists("example") or o... | # MIT licensed
# Copyright (c) 2013-2017 lilydjwg <lilydjwg@gmail.com>, et al.
import os
import shutil
import pytest
pytestmark = pytest.mark.asyncio
@pytest.mark.skipif(shutil.which("git") is None,
reason="requires git command")
async def test_git(get_version):
os.path.exists("example") or o... | mit | Python |
255ca4e517fc54cdaec789490b8578f8e3b065fb | add docstring, allow pep8 style guide | toruta39/blender-datablock-translator | translator.py | translator.py | import urllib.request
import urllib.parse
import json
import time
import xml.etree.ElementTree as ET
access_token = ""
access_token_expires_at = time.time()
def get_access_token():
"""Get access token from Azure Marketplace.
If there's no existed access token, it'll try request a new one.
Returns: strin... | import urllib.request
import urllib.parse
import json
import time
import xml.etree.ElementTree as ET
access_token = ""
access_token_expires_at = time.time()
def get_access_token():
global access_token
if (not bool(access_token)) or time.time() > access_token_expires_at:
access_token = req_access_toke... | mit | Python |
27154bcabbfd2281915a731506462c671980c4ac | Correct form instantiation on validation | mvaled/sentry,JamesMura/sentry,songyi199111/sentry,ngonzalvez/sentry,TedaLIEz/sentry,pauloschilling/sentry,llonchj/sentry,beeftornado/sentry,BuildingLink/sentry,gg7/sentry,JamesMura/sentry,ewdurbin/sentry,ngonzalvez/sentry,gencer/sentry,looker/sentry,mvaled/sentry,1tush/sentry,zenefits/sentry,kevinastone/sentry,BayanGr... | src/sentry/rules/base.py | src/sentry/rules/base.py | """
sentry.rules.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
Rules apply either before an event gets stored, or immediately after.
Basic actions:
- I want to get notified when [X]
- I want to group events when [X]
- ... | """
sentry.rules.base
~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
Rules apply either before an event gets stored, or immediately after.
Basic actions:
- I want to get notified when [X]
- I want to group events when [X]
- ... | bsd-3-clause | Python |
8a8d8a36280f9b4818ac85cc9cf54415608f2af1 | Add IPFType compatibility tests | anton-golubkov/Garland,anton-golubkov/Garland | src/test/test_ipftype.py | src/test/test_ipftype.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os, sys
cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__)))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
import ipf.ipftype.ipfinttype
import ipf.ipftype.ipfimage1ctype
import ipf.ipftype.ipfimage3ctype
import... | #!/usr/bin/python
# -*- coding: utf-8 -*-
import unittest
import os, sys
cmd_folder, f = os.path.split(os.path.dirname(os.path.abspath(__file__)))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
import ipf.ipftype.ipfinttype
import ipf.ipftype.ipfimage1ctype
import ipf.ipftype.ipfimage3ctype
import... | lgpl-2.1 | Python |
67ea3ebdf13720eab4948c36f0255517ee9e1d71 | Add case docstring | AlexCatarino/pythonnet,yagweb/pythonnet,yagweb/pythonnet,yagweb/pythonnet,QuantConnect/pythonnet,AlexCatarino/pythonnet,pythonnet/pythonnet,yagweb/pythonnet,pythonnet/pythonnet,AlexCatarino/pythonnet,QuantConnect/pythonnet,pythonnet/pythonnet,QuantConnect/pythonnet,AlexCatarino/pythonnet | src/tests/test_import.py | src/tests/test_import.py | # -*- coding: utf-8 -*-
"""Test the import statement."""
import pytest
import sys
def test_relative_missing_import():
"""Test that a relative missing import doesn't crash.
Some modules use this to check if a package is installed.
Relative import in the site-packages folder"""
with pytest.raises(Impor... | # -*- coding: utf-8 -*-
"""Test the import statement."""
import pytest
import sys
def test_relative_missing_import():
"""Test that a relative missing import doesn't crash.
Some modules use this to check if a package is installed.
Relative import in the site-packages folder"""
with pytest.raises(Impor... | mit | Python |
86f08272cb9e57bfe32ea0ad3f42dea893f52532 | increase SYMPY_MIN_VERSION to 0.7.2 | BubuLK/sfepy,rc/sfepy,lokik/sfepy,rc/sfepy,BubuLK/sfepy,sfepy/sfepy,RexFuzzle/sfepy,rc/sfepy,vlukes/sfepy,RexFuzzle/sfepy,lokik/sfepy,BubuLK/sfepy,sfepy/sfepy,RexFuzzle/sfepy,lokik/sfepy,lokik/sfepy,vlukes/sfepy,RexFuzzle/sfepy,sfepy/sfepy,vlukes/sfepy | sfepy/version.py | sfepy/version.py | # SfePy version
__version__ = '2015.2'
# "Minimal" supported versions.
NUMPY_MIN_VERSION = '1.3'
SCIPY_MIN_VERSION = '0.7'
MATPLOTLIB_MIN_VERSION = '0.99.0'
PYPARSING_MIN_VERSION = '1.5.0'
PYTABLES_MIN_VERSION = '2.1.2'
MAYAVI_MIN_VERSION = '3.3.0'
SYMPY_MIN_VERSION = '0.7.2'
IGAKIT_MIN_VERSION = '0.1'
PETSC4PY_MIN_VE... | # SfePy version
__version__ = '2015.2'
# "Minimal" supported versions.
NUMPY_MIN_VERSION = '1.3'
SCIPY_MIN_VERSION = '0.7'
MATPLOTLIB_MIN_VERSION = '0.99.0'
PYPARSING_MIN_VERSION = '1.5.0'
PYTABLES_MIN_VERSION = '2.1.2'
MAYAVI_MIN_VERSION = '3.3.0'
SYMPY_MIN_VERSION = '0.6.7'
IGAKIT_MIN_VERSION = '0.1'
PETSC4PY_MIN_VE... | bsd-3-clause | Python |
c93f97365f0a98cbf3d9164ccd364c68753ffeff | increase version | aliyun/aliyun-cli,aliyun/aliyun-cli | aliyuncli/__init__.py | aliyuncli/__init__.py | __author__ = 'haowei.yao@alibaba-inc.com'
__version__ = '2.1.10'
| __author__ = 'zhaoyang.szy & zikuan.ly'
__version__ = '2.1.9'
| apache-2.0 | Python |
a4cc0a34dd36aaa25bcde14d9e6ae05da61691f5 | Fix tabbing | cleett/plyer,kivy/plyer,cleett/plyer,kivy/plyer,KeyWeeUsr/plyer,kivy/plyer,johnbolia/plyer,KeyWeeUsr/plyer,kostyll/plyer,kived/plyer,kostyll/plyer,KeyWeeUsr/plyer,johnbolia/plyer,kived/plyer | plyer/platforms/macosx/uniqueid.py | plyer/platforms/macosx/uniqueid.py | from subprocess import Popen, PIPE
from plyer.facades import UniqueID
class OSXUniqueID(UniqueID):
def _get_uid(self):
ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE)
grep_process = Popen(["grep", "IOPlatformSerialNumber"],
stdin=ioreg_process.stdout, stdout=PIPE)
ioreg_pro... | from subprocess import Popen, PIPE
from plyer.facades import UniqueID
class OSXUniqueID(UniqueID):
def _get_uid(self):
ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE)
grep_process = Popen(["grep", "IOPlatformSerialNumber"],
stdin=ioreg_process.stdout, stdout=PIPE)
ioreg_process.stdout.close()
outpu... | mit | Python |
da613a8aeb73ea6852ad26eec74aa45215097f63 | Add more url-poking tools. | arkadini/twimp | twimp/urls.py | twimp/urls.py | # Copyright (c) 2010 Arek Korbik
#
# 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... | # Copyright (c) 2010 Arek Korbik
#
# 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... | apache-2.0 | Python |
4584b3fe02460401500a5f0654e0281ddddf57c2 | Fix version to 0.1 (no bug-fix yet) | mesnardo/snake | snake/version.py | snake/version.py | # file: version.py
# author: Olivier Mesnard (mesnardo@gwu.edu)
# description: Set up the version.
import os
_version_major = 0
_version_minor = 1
_version_micro = ''
_version_extra = ''
# construct full version string
_ver = [_version_major, _version_minor]
if _version_micro:
_ver.append(_version_micro)
if _ver... | # file: version.py
# author: Olivier Mesnard (mesnardo@gwu.edu)
# description: Set up the version.
import os
_version_major = 0
_version_minor = 1
_version_micro = 1
_version_extra = ''
# construct full version string
_ver = [_version_major, _version_minor]
if _version_micro:
_ver.append(_version_micro)
if _vers... | mit | Python |
39c777d6fc5555534628113190bb543c6225c07e | Read from stdin if available. | weinerjm/uncurl,spulec/uncurl | uncurl/bin.py | uncurl/bin.py | from __future__ import print_function
import sys
from .api import parse
def main():
if sys.stdin.isatty():
result = parse(sys.argv[1])
else:
result = parse(sys.stdin.read())
print(result)
| from __future__ import print_function
import sys
from .api import parse
def main():
result = parse(sys.argv[1])
print(result)
| apache-2.0 | Python |
3e2b7f78f7b0bdb857ade35f56252c9298bd6a4d | use e.sx not e.bokeh.sx in tool extension example | ericmjl/bokeh,bokeh/bokeh,timsnyder/bokeh,stonebig/bokeh,timsnyder/bokeh,ericmjl/bokeh,aavanian/bokeh,jakirkham/bokeh,dennisobrien/bokeh,ericmjl/bokeh,bokeh/bokeh,bokeh/bokeh,Karel-van-de-Plassche/bokeh,Karel-van-de-Plassche/bokeh,mindriot101/bokeh,ericmjl/bokeh,timsnyder/bokeh,dennisobrien/bokeh,stonebig/bokeh,jakirkh... | sphinx/source/docs/user_guide/examples/extensions_example_tool.py | sphinx/source/docs/user_guide/examples/extensions_example_tool.py | from bokeh.core.properties import Instance
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, Tool
from bokeh.plotting import figure
output_file('tool.html')
JS_CODE = """
import * as p from "core/properties"
import {GestureTool, GestureToolView} from "models/tools/gestures/gesture_tool... | from bokeh.core.properties import Instance
from bokeh.io import output_file, show
from bokeh.models import ColumnDataSource, Tool
from bokeh.plotting import figure
output_file('tool.html')
JS_CODE = """
import * as p from "core/properties"
import {GestureTool, GestureToolView} from "models/tools/gestures/gesture_tool... | bsd-3-clause | Python |
9c963baf6c69fd2193f70047e92f2d29a39add83 | Remove extension from removed_files | neoliberal/css-updater | source/update.py | source/update.py | """updates subreddit css with compiled sass"""
import os
import time
from typing import List, Dict, Any, Tuple
import praw
import sass
WebhookResponse = Dict[str, Any] # pylint: disable=C0103
def css() -> str:
"""compiles sass and returns css"""
return sass.compile(filename="index.scss", output_style="compr... | """updates subreddit css with compiled sass"""
import os
import time
from typing import List, Dict, Any, Tuple
import praw
import sass
WebhookResponse = Dict[str, Any] # pylint: disable=C0103
def css() -> str:
"""compiles sass and returns css"""
return sass.compile(filename="index.scss", output_style="compr... | mit | Python |
23800b8f76eaf1c72d4493327cd2eaf9d3f1e913 | Clarify the output of 'serve' and 'serveany' | jandecaluwe/urubu,jandecaluwe/urubu | urubu/main.py | urubu/main.py | # Copyright 2014 Jan Decaluwe
#
# This file is part of Urubu.
#
# Urubu is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Urub... | # Copyright 2014 Jan Decaluwe
#
# This file is part of Urubu.
#
# Urubu is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Urub... | agpl-3.0 | Python |
d00d23f083437cf0715ab599f5e758217fa0b57e | allow to work w/ py2.7 | DocNow/twarc,edsu/twarc,remagio/twarc,remagio/twarc,hugovk/twarc | utils/foaf.py | utils/foaf.py | #!/usr/bin/env python
"""
This is a utility for getting the friend-of-a-friend network for a
given twitter user. The network is expressed as tuples of user identifiers for
the user and their friend (who they follow).
User identifiers are used rather than the handles or screen_name, since the
handles can change, and... | #!/usr/bin/env python
"""
This is a utility for getting the friend-of-a-friend network for a
given twitter user. The network is expressed as tuples of user identifiers for
the user and their friend (who they follow).
User identifiers are used rather than the handles or screen_name, since the
handles can change, and... | mit | Python |
a1389ddf1a4e16ffb48fd99418671ac010b8e6fd | Update ip_to_country.py | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research,andyzsf/edx_data_research,andyzsf/edx_data_research | reporting_scripts/ip_to_country.py | reporting_scripts/ip_to_country.py | '''
This module retrieve IP addresses for each student and maps their IP to a country
This is to determine the diversity of students who took a given course
The geoip module and GeoIP.dat file was used to map the IP address to a country
Each user may have multiple ips, so this module retrieves all the countries mapped... | '''
This module maps the ip address of a student to a corresponding country using the
geoip module found online
Each user may have multiple ips, so this module retrieves all the countries mapped to those ips
Disclaimer: The accuracy of the IP to Country cannot be determined as it is difficult to determine
if the IP i... | mit | Python |
d1d56ae4978885778beeabc32c738b4b725888ee | add like_video_set field in Client model | jupiny/abacus-edu,jupiny/abacus-edu,jupiny/abacus-edu | abacus_edu/abacus_edu/models/client.py | abacus_edu/abacus_edu/models/client.py | from django.db import models
from abacus_edu.behaviors import Timestampable
class Client(Timestampable, models.Model):
token = models.TextField(
verbose_name="토큰값",
)
like_video_set = models.ManyToManyField(
'Video',
related_name="liked_by_set",
)
def __str__(self):
... | from django.db import models
from abacus_edu.behaviors import Timestampable
class Client(Timestampable, models.Model):
token = models.TextField(
verbose_name="토큰값",
)
def __str__(self):
return self.token[:10]
class Meta:
verbose_name = "Client"
verbose_name_plural = ... | mit | Python |
b12758583141db2597300dd5348b11bd020a1245 | fix merge mistake | JNeiger/robocup-software,RoboJackets/robocup-software,RoboJackets/robocup-software,JNeiger/robocup-software,RoboJackets/robocup-software,JNeiger/robocup-software,RoboJackets/robocup-software,JNeiger/robocup-software,JNeiger/robocup-software | soccer/gameplay/plays/testing/test_capture.py | soccer/gameplay/plays/testing/test_capture.py | import play
import behavior
import skills.move
import skills.capture
import enum
import robocup
import role_assignment
# this test repeatedly runs the capture behavior
class TestCapture(play.Play):
class State(enum.Enum):
setup = 1
capturing = 2
def __init__(self):
super().__init__(c... | import play
import behavior
import skills.move
import skills.capture
import single_robot_composite_behavior
import enum
import robocup
import role_assignment
# this test repeatedly runs the capture behavior
- class TestCapture(play.Play):
class State(enum.Enum):
setup = 1
capturing = 2
def __... | apache-2.0 | Python |
899f28e2cd7dbeb6227e8c56eef541cce1a424f4 | Add check that heartbeat timeout is integer | alerta/python-alerta-client,alerta/python-alerta-client,alerta/python-alerta | alertaclient/commands/cmd_heartbeat.py | alertaclient/commands/cmd_heartbeat.py | import os
import platform
import sys
import click
prog = os.path.basename(sys.argv[0])
@click.command('heartbeat', short_help='Send a heartbeat')
@click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1]))
@click.option('--tag', '-T', 'tags', multiple=True)
@click.option('--timeout', metavar='EXPIR... | import os
import platform
import sys
import click
prog = os.path.basename(sys.argv[0])
@click.command('heartbeat', short_help='Send a heartbeat')
@click.option('--origin', default='{}/{}'.format(prog, platform.uname()[1]))
@click.option('--tag', '-T', 'tags', multiple=True)
@click.option('--timeout', metavar='EXPIR... | apache-2.0 | Python |
7a89a3ba0707095824367749fbced4ee71ea37c3 | Remove unused import. | eugeniy/pytest-tornado | test/create_cert.py | test/create_cert.py | # -*- coding: utf-8 -*-
"""
Create a cert with pyOpenSSL for tests.
Heavily based on python-opsi's OPSI.Util.Task.Certificate.
Source: https://github.com/opsi-org/python-opsi/blob/stable/OPSI/Util/Task/Certificate.py
"""
import argparse
import os
import random
import socket
from tempfile import NamedTemporaryFile
fro... | # -*- coding: utf-8 -*-
"""
Create a cert with pyOpenSSL for tests.
Heavily based on python-opsi's OPSI.Util.Task.Certificate.
Source: https://github.com/opsi-org/python-opsi/blob/stable/OPSI/Util/Task/Certificate.py
"""
import argparse
import os
import random
import shutil
import socket
from tempfile import NamedTemp... | apache-2.0 | Python |
36a54857fe98e0e63b4e93cb4b774df33e6cc701 | Update import in anonymize plugin | mociepka/saleor,mociepka/saleor,mociepka/saleor | saleor/plugins/anonymize/plugin.py | saleor/plugins/anonymize/plugin.py | from typing import TYPE_CHECKING, Any, Optional
from ...core.anonymize import obfuscate_address, obfuscate_email
from ..base_plugin import BasePlugin
from . import obfuscate_order
if TYPE_CHECKING:
from ...account.models import Address, User
from ...order.models import Order
class AnonymizePlugin(BasePlugin... | from typing import TYPE_CHECKING, Any, Optional
from ..base_plugin import BasePlugin
from . import obfuscate_address, obfuscate_email, obfuscate_order
if TYPE_CHECKING:
from ...account.models import Address, User
from ...order.models import Order
class AnonymizePlugin(BasePlugin):
"""Anonymize all user ... | bsd-3-clause | Python |
500d5c9420410e028d2dbdeeeb0f9bdd43a216a3 | Add test for arithmetic | adambrenecki/vc2xlsx | test_cell_parser.py | test_cell_parser.py | import parser
def do_test(inv, outv):
try:
tree = parser.parse(inv)
actual_output = tree.excel()
except Exception as e:
print("ERROR")
print(e)
else:
if actual_output != outv:
print("FAIL")
print("Input : {}".format(inv))
... | import parser
def do_test(inv, outv):
try:
tree = parser.parse(inv)
actual_output = tree.excel()
except Exception as e:
print("ERROR")
print(e)
else:
if actual_output != outv:
print("FAIL")
print("Input : {}".format(inv))
... | agpl-3.0 | Python |
844d0717fba47450df331512e144b1598d2b2a46 | add settings to django admin | 2gis/badger-api,2gis/badger-api | testreport/admin.py | testreport/admin.py | import logging
from django.contrib import admin
from common.models import Project
from common.models import Settings
from testreport.models import Launch
from testreport.models import TestPlan
from testreport.models import TestResult
from testreport.models import LaunchItem
from testreport.models import Bug
log = l... | import logging
from django.contrib import admin
from common.models import Project
from testreport.models import Launch
from testreport.models import TestPlan
from testreport.models import TestResult
from testreport.models import LaunchItem
from testreport.models import Bug
log = logging.getLogger(__name__)
admin.s... | mit | Python |
e3dff37ed52d8460d39ea5af68b7aedd296e38a2 | Make the rpc server usable outside of the command line | ConsenSys/testrpc,Firescar96/eth-testrpc,ryepdx/eth-testrpc,ConsenSys/eth-testrpc,pipermerriam/eth-testrpc | testrpc/__main__.py | testrpc/__main__.py | import argparse
from testrpc import *
from ethereum.tester import accounts
parser = argparse.ArgumentParser(
description='Simulate an Ethereum blockchain JSON-RPC server.'
)
parser.add_argument('-p', '--port', dest='port', type=int,
nargs='?', default=8545)
parser.add_argument('-d', '--domain',... | import argparse
from testrpc import *
from ethereum.tester import accounts
parser = argparse.ArgumentParser(
description='Simulate an Ethereum blockchain JSON-RPC server.'
)
parser.add_argument('-p', '--port', dest='port', type=int,
nargs='?', default=8545)
parser.add_argument('-d', '--domain',... | mit | Python |
b9ac662d3c51ba21e43a860663452c06aa0df29e | hide cursor | ponty/pyscreenshot,ponty/pyscreenshot,ponty/pyscreenshot | tests/fillscreen.py | tests/fillscreen.py | import pygame
from entrypoint2 import entrypoint
@entrypoint
def main(size=None):
pygame.init()
pygame.mixer.quit() # to avoid 100 CPU load
pygame.mouse.set_visible(0)
if size:
size = map(int, size.split(":"))
size = tuple(size)
disp = pygame.display.set_mode(size)
el... | import pygame
from entrypoint2 import entrypoint
@entrypoint
def main(size=None):
pygame.init()
pygame.mixer.quit() # to avoid 100 CPU load
if size:
size = map(int, size.split(":"))
size = tuple(size)
disp = pygame.display.set_mode(size)
else:
disp = pygame.display.se... | bsd-2-clause | Python |
58c09b73108c36007e401145b95c7e3dc2d176f9 | add a test to validate to and from minus80 | LinkageIO/LocusPocus,schae234/LocusPocus | tests/test_Fasta.py | tests/test_Fasta.py | '''
Tests
'''
import pytest
import locuspocus as lp
def test_init(smpl_fasta):
assert len(smpl_fasta['chr1']) == 500000
assert len(smpl_fasta['chr2']) == 500000
assert len(smpl_fasta['chr3']) == 500000
assert len(smpl_fasta['chr4']) == 500000
def test_to_minus_80(smpl_fasta):
smpl = smpl_fast... | '''
Tests
'''
import pytest
def test_init(smpl_fasta):
assert len(smpl_fasta['chr1']) == 500000
assert len(smpl_fasta['chr2']) == 500000
assert len(smpl_fasta['chr3']) == 500000
assert len(smpl_fasta['chr4']) == 500000
| mit | Python |
aff438aa933193032a8db57e93a0ad459518fe26 | Update tests | slundberg/shap,slundberg/shap,slundberg/shap,slundberg/shap | tests/test_basic.py | tests/test_basic.py | import matplotlib
matplotlib.use('Agg')
import shap
import numpy as np
def test_null_model_small():
explainer = shap.KernelExplainer(lambda x: np.zeros(x.shape[0]), np.ones((2,4)), nsamples=100)
e = explainer.explain(np.ones((1,4)))
assert np.sum(np.abs(e.effects)) < 1e-8
def test_null_model():
explai... | import matplotlib
matplotlib.use('Agg')
import shap
import numpy as np
def test_null_model_small():
explainer = shap.KernelExplainer(lambda x: np.zeros(x.shape[0]), np.ones((2,4)), nsamples=100)
e = explainer.explain(np.ones((1,4)))
assert np.sum(np.abs(e.effects)) < 1e-8
def test_null_model():
explai... | mit | Python |
e11cbf85ae49fbc5581fe04dd865b61a9dbb9069 | Test properties.files | 3ptscience/properties,aranzgeo/properties | tests/test_files.py | tests/test_files.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import png
import unittest
import properties
class FileClass(properties.PropertyClass):
dat = properties.File("My file")
img = properties.Image("My i... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest, numpy as np, os
import properties
# class FileClass(properties.PropertyClass):
# dat = properties.File("My location")
# image = properties.Im... | mit | Python |
a1c93f454d093be27dac737ed48e2d157f7b6866 | Fix test to work on a Friday :-) (#92) | MikeFair/www.gittip.com,studio666/gratipay.com,mccolgst/www.gittip.com,gratipay/gratipay.com,eXcomm/gratipay.com,MikeFair/www.gittip.com,studio666/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,MikeFair/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gra... | tests/test_stats.py | tests/test_stats.py | from datetime import datetime
from mock import patch
from gittip.billing.payday import Payday
from gittip import testing
from gittip import wireup
from tests import serve_request
class TestStatsPage(testing.GittipBaseTest):
def get_stats_page(self):
response = serve_request('/about/stats.html')
... | from datetime import datetime
from mock import patch
from gittip.billing.payday import Payday
from gittip import testing
from gittip import wireup
from tests import serve_request
class TestStatsPage(testing.GittipBaseTest):
def get_stats_page(self):
response = serve_request('/about/stats.html')
... | cc0-1.0 | Python |
4007517e45a589e10a6111d5066f0a96694e2d6d | create libvirtvms tests | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | tests/modules/contrib/test_libvirtvms.py | tests/modules/contrib/test_libvirtvms.py | import sys
import pytest
from unittest.mock import Mock
import core.config
sys.modules['libvirt'] = Mock()
import modules.contrib.libvirtvms
def build_module():
return modules.contrib.libvirtvms.Module(
config=core.config.Config([]),
theme=None
)
def test_load_module():
__import__("modu... | import pytest
pytest.importorskip("libvirt")
def test_load_module():
__import__("modules.contrib.libvirtvms")
| mit | Python |
8931ded3e82620223a4ea5a2b02201d2fbe1c654 | fix plot closure test | GeoscienceAustralia/PyRate,GeoscienceAustralia/PyRate | tests/phase_closure/test_plot_closure.py | tests/phase_closure/test_plot_closure.py | # This Python module is part of the PyRate software package.
#
# Copyright 2021 Geoscience Australia
#
# 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/... | # This Python module is part of the PyRate software package.
#
# Copyright 2021 Geoscience Australia
#
# 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/... | apache-2.0 | Python |
df3dfff6d5566a15e94d53a3ecfac8b864afdd38 | Fix syntax error in local_settings.example.py | MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets,MTG/freesound-datasets | freesound_datasets/local_settings.example.py | freesound_datasets/local_settings.example.py | # Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials ... | # Freesound keys for download script
# Get credentials at http://www.freesound.org/apiv2/apply
# Set callback url to https://www.freesound.org/home/app_permissions/permission_granted/
FS_CLIENT_ID = 'FREESOUND_KEY'
FS_CLIENT_SECRET = 'FREESOUND_SECRET'
# Freesound keys for "login with" functionality
# Get credentials ... | agpl-3.0 | Python |
da745fdede38efcff88e8c05c7e7694d4af42626 | Remove whitespace from `=` in keyword arguments. | rmcgibbo/conda-build,frol/conda-build,rmcgibbo/conda-build,sandhujasmine/conda-build,dan-blanchard/conda-build,dan-blanchard/conda-build,shastings517/conda-build,mwcraig/conda-build,rmcgibbo/conda-build,shastings517/conda-build,ilastik/conda-build,frol/conda-build,mwcraig/conda-build,shastings517/conda-build,mwcraig/co... | tests/test-recipes/test-package/setup.py | tests/test-recipes/test-package/setup.py | from distutils.core import setup
setup(
name="conda-build-test-project",
version='1.0',
author="Continuum Analytics, Inc.",
url="https://github.com/conda/conda-build",
license="BSD",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Oper... | from distutils.core import setup
setup(
name = "conda-build-test-project",
version='1.0',
author = "Continuum Analytics, Inc.",
url = "https://github.com/conda/conda-build",
license = "BSD",
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
... | bsd-3-clause | Python |
fab7151c1982db510c247cb98fd7eba4f8af1f21 | Add a dummy 'files' for flash_player 'copies'. | meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-u... | third_party/adobe/flash/flash_player.gyp | third_party/adobe/flash/flash_player.gyp | # Copyright (c) 2010 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.
{
# Always provide a target, so we can put the logic about whether there's
# anything to be done in this file (instead of a higher-level .gyp file).
... | # Copyright (c) 2010 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.
{
# Always provide a target, so we can put the logic about whether there's
# anything to be done in this file (instead of a higher-level .gyp file).
... | bsd-3-clause | Python |
86a130850687d680cb497ebdcb8a24a91a1a5b39 | Add a dummy 'files' for flash_player 'copies'. | gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,Crystaln... | third_party/adobe/flash/flash_player.gyp | third_party/adobe/flash/flash_player.gyp | # Copyright (c) 2010 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.
{
# Always provide a target, so we can put the logic about whether there's
# anything to be done in this file (instead of a higher-level .gyp file).
... | # Copyright (c) 2010 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.
{
# Always provide a target, so we can put the logic about whether there's
# anything to be done in this file (instead of a higher-level .gyp file).
... | bsd-3-clause | Python |
5669cd24f7f391187d4df06c9ffdf95677af0322 | update tut | micronicstraining/python,micronicstraining/python,micronicstraining/python,micronicstraining/python | day_2/lesson2/read_file.py | day_2/lesson2/read_file.py | # go over tut. here 1st
# http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
f = open("input.txt", "r") # here we open file "input.txt". Second argument used to identify that we want to read file
# Note: if you want to write to the file use "w" as second argument... |
# http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
f = open("input.txt", "r") # here we open file "input.txt". Second argument used to identify that we want to read file
# Note: if you want to write to the file use "w" as second argument
for line in f.readlin... | agpl-3.0 | Python |
04eee39390654ea6ca56447a95721471a97114b9 | Comment monitoring steps (temporarily) | globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service,globocom/database-as-a-service | dbaas/workflow/settings.py | dbaas/workflow/settings.py |
DEPLOY_MYSQL = (
'workflow.steps.build_databaseinfra.BuildDatabaseInfra',
'workflow.steps.create_virtualmachines.CreateVirtualMachine',
'workflow.steps.create_secondary_ip.CreateSecondaryIp',
'workflow.steps.create_dns.CreateDns',
'workflow.steps.create_nfs.C... |
DEPLOY_MYSQL = (
'workflow.steps.build_databaseinfra.BuildDatabaseInfra',
'workflow.steps.create_virtualmachines.CreateVirtualMachine',
'workflow.steps.create_secondary_ip.CreateSecondaryIp',
'workflow.steps.create_dns.CreateDns',
'workflow.steps.create_nfs.C... | bsd-3-clause | Python |
b44becdbd7b894b2acef87186066a6d1f61e3293 | support decimal.Decimal to transformat to json | zhoubangtao/dbsync,zhoubangtao/dbsync | dbsync/serializers/json.py | dbsync/serializers/json.py | # -*- coding:utf-8 -*-
__author__ = 'nathan'
import json
from datetime import date, datetime
from decimal import Decimal
from dbsync.serializers.base import BaseSerializer
class JSONSerializer(BaseSerializer):
""" serialize model to json """
def serialize(self, datum, *args, **kwargs):
"""
... | # -*- coding:utf-8 -*-
__author__ = 'nathan'
import json
from datetime import date, datetime
from dbsync.serializers.base import BaseSerializer
class JSONSerializer(BaseSerializer):
""" serialize model to json """
def serialize(self, model, ensure_ascii=True, cls=DatetimeJSONEncoder):
"""
... | apache-2.0 | Python |
3877eff4062a86a468524214db203bbd023b5d77 | Add CLI option to not fall back to the snapshot (#260) | john-kurkowski/tldextract | tldextract/cli.py | tldextract/cli.py | """tldextract CLI"""
import argparse
import logging
import sys
from ._version import version as __version__
from .tldextract import TLDExtract
def main() -> None:
"""tldextract CLI main command."""
logging.basicConfig()
parser = argparse.ArgumentParser(
prog="tldextract", description="Parse ho... | """tldextract CLI"""
import argparse
import logging
import sys
from ._version import version as __version__
from .tldextract import TLDExtract
def main() -> None:
"""tldextract CLI main command."""
logging.basicConfig()
parser = argparse.ArgumentParser(
prog="tldextract", description="Parse ho... | bsd-3-clause | Python |
ee8cb600c772e4a0f795a0fe00b1e612cb8a8e37 | Sort files into dict with dir as key | claudemuller/masfir | dirmuncher.py | dirmuncher.py | #!/usr/bin/env python
# -*- Coding: utf-8 -*-
import os
class Dirmuncher:
def __init__(self, directory):
self.directory = directory
def getFiles(self):
result = {}
for dirname, dirnames, filenames in os.walk(self.directory):
# Subdirectories
for subdirname in ... | #!/usr/bin/env python
# -*- Coding: utf-8 -*-
import os
class Dirmuncher:
def __init__(self, directory):
self.directory = directory
def directoryListing(self):
for dirname, dirnames, filenames in os.walk(self.directory):
# Subdirectories
for subdirname in dirnames:
... | mit | Python |
92cd5d3b812f224d6a339f7785de5732e39e487d | fix test of atom with pint | dschick/udkm1Dsim,dschick/udkm1Dsim | test/test_atom.py | test/test_atom.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from udkm1Dsim.atoms import Atom, AtomMixed
import numpy as np
def test_atom():
Dy = Atom('Dy')
assert Dy.symbol == 'Dy'
assert Dy.id == 'Dy'
assert Dy.ionicity == 0
assert Dy.name == 'Dysprosium'
assert Dy.atomic_number_z == 66
assert Dy.mass... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from udkm1Dsim.atoms import Atom, AtomMixed
import numpy as np
def test_atom():
Dy = Atom('Dy')
assert Dy.symbol == 'Dy'
assert Dy.id == 'Dy'
assert Dy.ionicity == 0
assert Dy.name == 'Dysprosium'
assert Dy.atomic_number_z == 66
assert Dy.mass... | mit | Python |
db2c23ef12ba1cacff811fc694b039e8f261a642 | Add tests for slicing | thunder-project/thunder,j-friedrich/thunder,j-friedrich/thunder,jwittenbach/thunder | test/test_data.py | test/test_data.py | import pytest
from numpy import allclose, array, asarray, add
from thunder import series, images
pytest.mark.usefixtures("eng")
def test_first(eng):
data = series.fromlist([array([1, 2, 3]), array([4, 5, 6])], engine=eng)
assert allclose(data.first(), [1, 2, 3])
data = images.fromlist([array([[1, 2], [3... | import pytest
from numpy import allclose, array, asarray, add
from thunder import series, images
pytest.mark.usefixtures("eng")
def test_first(eng):
data = series.fromlist([array([1, 2, 3]), array([4, 5, 6])], engine=eng)
assert allclose(data.first(), [1, 2, 3])
data = images.fromlist([array([[1, 2], [3... | apache-2.0 | Python |
67c3e461a705a4deee4c7e58d3accdeaa3ccbf65 | Convert to fortran array when reading npy | OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz | tomviz/python/tomviz/io/formats/numpy.py | tomviz/python/tomviz/io/formats/numpy.py | # -*- coding: utf-8 -*-
###############################################################################
# This source file is part of the Tomviz project, https://tomviz.org/.
# It is released under the 3-Clause BSD License, see "LICENSE".
###############################################################################
... | # -*- coding: utf-8 -*-
###############################################################################
# This source file is part of the Tomviz project, https://tomviz.org/.
# It is released under the 3-Clause BSD License, see "LICENSE".
###############################################################################
... | bsd-3-clause | Python |
f9c51c592483ab08417d4df33898d32f7700ffe9 | Fix exception handling in management command. Clean up. | salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal,salopensource/sal | sal/management/commands/update_admin_user.py | sal/management/commands/update_admin_user.py | """Creates an admin user if there aren't any existing superusers."""
from optparse import make_option
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Creates/Updates an Admin user'
def add_arguments(self, par... | '''
Creates an admin user if there aren't any existing superusers
'''
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from optparse import make_option
class Command(BaseCommand):
help = 'Creates/Updates an Admin user'
def add_arguments(self, pars... | apache-2.0 | Python |
b6788063629d0fe1f440a45bb8bc34e4a51b89b3 | Fix tests | rolepoint/flump | test/test_init.py | test/test_init.py | from flask import Flask
from marshmallow import fields
from flump import FlumpSchema, FlumpView, FlumpBlueprint
def test_flump_blueprint():
blueprint = FlumpBlueprint(
'test_flump', __name__,
flump_views=[FlumpView(None, 'blah', '/endpoint/')]
)
assert blueprint.name == 'test_flump'
... | from flask import Flask
from marshmallow import fields
from flump import FlumpSchema, FlumpView, FlumpBlueprint
def test_flump_blueprint():
blueprint = FlumpBlueprint(
'test_flump', __name__,
flump_views=[FlumpView(None, 'blah', '/endpoint/')]
)
assert blueprint.name == 'test_flump'
... | mit | Python |
abd3985b3bf89834aa3ffe4217748a60b12caef9 | fix particular case of #, for path relative to top | tuttleofx/sconsProject | tools/unittest.py | tools/unittest.py | from SCons.Script.SConscript import SConsEnvironment
import os
import sys
import subprocess
windows = os.name.lower() == "nt" and sys.platform.lower().startswith("win")
ld_library_path = 'LD_LIBRARY_PATH' if not windows else 'PATH'
mpsep = ':' if not windows else ';'
#
# Function taken from scons Wiki
#
def builde... | from SCons.Script.SConscript import SConsEnvironment
import os
import sys
import subprocess
windows = os.name.lower() == "nt" and sys.platform.lower().startswith("win")
ld_library_path = 'LD_LIBRARY_PATH' if not windows else 'PATH'
mpsep = ':' if not windows else ';'
#
# Function taken from scons Wiki
#
def builde... | mit | Python |
d40d28423833d7ff67961cdeb96d5b5636f66b0b | update init | murphycj/AGFusion,murphycj/AGFusion | agfusion/__init__.py | agfusion/__init__.py | """ __init__.py
Initialises when agfusion module is loaded.
"""
__version__ = "1.252"
| """ __init__.py
Initialises when agfusion module is loaded.
"""
| mit | Python |
aa7a71c9d1238ece42773b2edf36ff173cfefd0e | handle without filter | alephdata/aleph,OpenGazettes/aleph,OpenGazettes/aleph,gazeti/aleph,alephdata/aleph,alephdata/aleph,OpenGazettes/aleph,OpenGazettes/aleph,pudo/aleph,alephdata/aleph,gazeti/aleph,gazeti/aleph,pudo/aleph,gazeti/aleph,alephdata/aleph,pudo/aleph | aleph/search/util.py | aleph/search/util.py | import re
from copy import deepcopy
from elasticsearch.helpers import scan
from aleph.core import es, es_index
MARKS = re.compile(r'[_\.;,/]{2,}')
def add_filter(q, filter_):
"""Add the given filter ``filter_`` to the given query."""
q = deepcopy(q)
if 'bool' not in q:
q = {'bool': {'must': [q]}... | import re
from copy import deepcopy
from elasticsearch.helpers import scan
from aleph.core import es, es_index
MARKS = re.compile(r'[_\.;,/]{2,}')
def add_filter(q, filter_):
"""Add the given filter ``filter_`` to the given query."""
q = deepcopy(q)
if 'bool' not in q:
q = {
'bool': ... | mit | Python |
c6fcd0999bf94d6f1edf4ee856ca87d7d34a23fd | Use global levenshtein check | Code4SA/mma-dexter,Code4SA/mma-dexter,Code4SA/mma-dexter | dexter/models/utterance.py | dexter/models/utterance.py | from __future__ import division
from sqlalchemy import (
Column,
DateTime,
ForeignKey,
Integer,
Text,
func,
Index
)
from sqlalchemy.orm import relationship, backref
from .support import db
from ..utils import levenshtein
class Utterance(db.Model):
"""
A quotation by an entity ... | from __future__ import division
from sqlalchemy import (
Column,
DateTime,
ForeignKey,
Integer,
Text,
func,
Index
)
from sqlalchemy.orm import relationship, backref
import nltk
from .support import db
class Utterance(db.Model):
"""
A quotation by an entity in a document.
... | apache-2.0 | Python |
1088eba6981d27641059ae90793713f4fe848b3b | load CDNs when viewing under file:// | altair-viz/altair,ellisonbg/altair,jakevdp/altair | altair/utils/html.py | altair/utils/html.py | import json
def to_html(json_dict, template=None, title=None, local_file=True, **kwargs):
"""Embed a Vega-Lite JSON into an HTML document.
Parameters
----------
json_dict : dict
A dictionary describing the Vega-Lite specification.
template : string
The HTML template to use. This s... | import json
def to_html(json_dict, template=None, title=None, **kwargs):
"""Embed a Vega-Lite JSON into an HTML document
Parameters
----------
json_dict : dict
A dictionary describing the Vega-Lite specification.
template : string
The HTML template to use. This should have a forma... | bsd-3-clause | Python |
da7d07b890a7b67c8d8bd34d712ba8f6d0ec5db0 | Set the UUIDField to auto_add. | hello-base/web,hello-base/web,hello-base/web,hello-base/web | base/components/merchandise/models.py | base/components/merchandise/models.py | from datetime import date
from model_utils import Choices
from model_utils.models import TimeStampedModel
from ohashi.db import models
from components.accounts.models import ContributorMixin
from components.people.models import ParticipationMixin
class Merchandise(ContributorMixin, ParticipationMixin):
# Shared... | from datetime import date
from model_utils import Choices
from model_utils.models import TimeStampedModel
from ohashi.db import models
from components.accounts.models import ContributorMixin
from components.people.models import ParticipationMixin
class Merchandise(ContributorMixin, ParticipationMixin):
# Shared... | apache-2.0 | Python |
449f69e3a01d77307d33988bca47276f5d483c9d | Update dsub version | DataBiosphere/dsub,DataBiosphere/dsub | dsub/_dsub_version.py | dsub/_dsub_version.py | # Copyright 2017 Google 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 law or a... | # Copyright 2017 Google 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 law or a... | apache-2.0 | Python |
5907413f77d2a9e7e0b59072cb96674db41e1312 | Update makeExamples.py | guilindner/VortexFitting | makeExamples.py | makeExamples.py | import os
import sys
is_windows = sys.platform.startswith('win')
if is_windows:
print("Running on Windows ...")
else:
print("Running on Linux ...")
if sys.version_info[0] < 3:
raise Exception("Must be using Python 3")
else:
cmd = 'python3 run.py -i data/example_Ub_planeZ_0.01.raw ' \
'-ft o... | import os
import sys
is_windows = sys.platform.startswith('win')
if is_windows:
print("Running on Windows ...")
else:
print("Running on Linux ...")
cmd = 'python run.py -i data/example_Ub_planeZ_0.01.raw ' \
'-ft openfoam -o results/example_openfoam -rmax 0'
os.system(cmd)
cmd = 'python run.py -i data... | mit | Python |
2e01e7aa989a641144472688ac966362978dd5bc | add request | silenius/amnesia,silenius/amnesia,silenius/amnesia | amnesia/resources.py | amnesia/resources.py | # -*- coding: utf-8 -*-
import logging
log = logging.getLogger(__name__)
from sqlalchemy import orm
from pyramid.httpexceptions import HTTPNotFound
from amnesia.modules.content import Content
from amnesia.modules.folder import Folder
from amnesia.modules.folder import FolderResource
from amnesia.modules.page import... | # -*- coding: utf-8 -*-
import logging
log = logging.getLogger(__name__)
from sqlalchemy import orm
from pyramid.httpexceptions import HTTPNotFound
from amnesia.modules.content import Content
from amnesia.modules.folder import Folder
from amnesia.modules.folder import FolderResource
from amnesia.modules.page import... | bsd-2-clause | Python |
a5f60d664e7758b113abc31b405657952dd5eccd | Implement test data JSON loader | sherlocke/pywatson | tests/conftest.py | tests/conftest.py | import json
import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username'... | import os
import pytest
from pywatson.watson import Watson
@pytest.fixture
def config():
"""Get Watson configuration from the environment
:return: dict with keys 'url', 'username', and 'password'
"""
try:
return {
'url': os.environ['WATSON_URL'],
'username': os.environ... | mit | Python |
feb3d7eca9ab78ad95f2b7b538f6866bc4a528b4 | test for parse_service_name added | bird-house/pywps-proxy,bird-house/twitcher,bird-house/pywps-proxy | twitcher/tests/test_registry.py | twitcher/tests/test_registry.py | import pytest
import unittest
import mock
from twitcher.registry import ServiceRegistry
from twitcher.registry import parse_service_name
class ServiceRegistryTestCase(unittest.TestCase):
def setUp(self):
self.service = dict(name="loving_flamingo", url="http://somewhere.over.the/ocean", type="wps", public... | import unittest
import mock
from twitcher.registry import ServiceRegistry
class ServiceRegistryTestCase(unittest.TestCase):
def setUp(self):
self.service = dict(name="loving_flamingo", url="http://somewhere.over.the/ocean", type="wps", public=False)
self.service_public = dict(name="open_pingu", u... | apache-2.0 | Python |
904db705daf24d68fcc9ac6010b55b93c7dc4544 | Add automatic sending of 900/901 numerics for account status | Heufneutje/txircd,ElementalAlchemist/txircd | txircd/modules/core/accounts.py | txircd/modules/core/accounts.py | from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
# Numerics and names are taken from the IRCv3.1 SASL specification at http://ircv3.net/specs/extensions/sasl-3.1... | from twisted.plugin import IPlugin
from txircd.module_interface import IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
class Accounts(ModuleData):
implements(IPlugin, IModuleData)
name = "Accounts"
core = True
def actions(self):
return [ ("usercansetmetadata", ... | bsd-3-clause | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.