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 |
|---|---|---|---|---|---|---|---|---|---|
24e2e391dece37c245d8a459456f3e30cd2346a8 | openxc/vehicle.py | openxc/vehicle.py | from .measurements import Measurement
from .sinks.base import MeasurementNotifierSink
class Vehicle(object):
def __init__(self, source=None):
self.sources = set()
self.sinks = set()
self.measurements = {}
self.add_source(source)
self.notifier = MeasurementNotifierSink()
... | from .measurements import Measurement
from .sinks.base import MeasurementNotifierSink
class Vehicle(object):
def __init__(self, interface=None):
self.sources = set()
self.sinks = set()
self.measurements = {}
if interface is not None:
self.add_source(interface)
... | Change constructor of Vehicle to accept an Interface instead of just Source. | Change constructor of Vehicle to accept an Interface instead of just Source.
| Python | bsd-3-clause | openxc/openxc-python,openxc/openxc-python,openxc/openxc-python |
ffd429281ed6695457304646467a6d9e0a0301a4 | src/nyc_trees/apps/core/tasks.py | src/nyc_trees/apps/core/tasks.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from celery import task
from django.core.files.storage import default_storage
@task(bind=True, max_retries=15, default_retry_delay=2)
def wait_... | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from celery import task
from django.core.files.storage import default_storage
@task(bind=True, max_retries=15, default_retry_delay=2)
def wait_... | Send RSVP email even if PDF doesn't exist | Send RSVP email even if PDF doesn't exist
If the PDF can't be found on the disk after the maximum number of
retries, return None, instead of raising an exception. This ensures that
the RSVP email notification still sends even without the PDF attachment.
Refs #1655
| Python | agpl-3.0 | azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,azavea/nyc-trees,maurizi/nyc-trees,kdeloach/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees,kdeloach/nyc-trees,maurizi/nyc-trees,azavea/nyc-trees |
3bad6c23fad5525628db1c3c1b99f3f86c08db63 | cloudmeta/apps/metadata/models.py | cloudmeta/apps/metadata/models.py | from django.db import models
KEYTYPE_CHOICES = (
('RSA', 'ssh-rsa'),
('DSA', 'ssh-dsa'),
('ECC-256', 'ecdsa-sha2-nistp256'),
('ECC-521', 'ecdsa-sha2-nistp521'),
)
class Node(models.Model):
name = models.CharField(unique=True, primary_key=True, max_length=256)
hostname = models.CharField(blank=... | from django.db import models
KEYTYPE_CHOICES = (
('RSA', 'ssh-rsa'),
('DSA', 'ssh-dsa'),
('ECC-256', 'ecdsa-sha2-nistp256'),
('ECC-384', 'ecdsa-sha2-nistp384'),
('ECC-521', 'ecdsa-sha2-nistp521'),
)
class Node(models.Model):
name = models.CharField(unique=True, primary_key=True, max_length=256... | Allow ecdsa 384 bit keys too | Allow ecdsa 384 bit keys too
| Python | agpl-3.0 | bencord0/cloudmeta,bencord0/cloudmeta |
6932164f20ced80ff6d08402b84aba954a983e2d | iota/commands/extended/get_transaction_objects.py | iota/commands/extended/get_transaction_objects.py | # coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from typing import Iterable, List, Optional
import filters as f
from iota import Transaction, TransactionHash
from iota.commands.core import GetTrytesCommand
from iota.commands import FilterCommand, RequestFilter
... | # coding=utf-8
from __future__ import absolute_import, division, print_function, \
unicode_literals
from typing import Iterable, List, Optional
import filters as f
from iota import Transaction, TransactionHash
from iota.commands.core import GetTrytesCommand
from iota.commands import FilterCommand, RequestFilter
... | Use filter macro for request validation | Use filter macro for request validation
StringifiedTrytesArray(Type) filter macro was
introduced in #243. Becasue of this, no request
filter test case is needed, hence the macro is
covered already in other test cases.
| Python | mit | iotaledger/iota.lib.py |
0a0ebdde63628d9504ac9834ef20b996ab595d7d | stock_quant_package_product_packaging/models/stock_move_line.py | stock_quant_package_product_packaging/models/stock_move_line.py | # Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import models
class StockMoveLine(models.Model):
_inherit = "stock.move.line"
def _action_done(self):
res = super()._action_done()
for line in self.filtered(lambda l: l.result_package_id):... | # Copyright 2019 Camptocamp SA
# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl)
from odoo import models
class StockMoveLine(models.Model):
_inherit = "stock.move.line"
def _action_done(self):
res = super()._action_done()
# _action_done in stock module sometimes delete a move li... | Fix "record does not exist" when validating move line | Fix "record does not exist" when validating move line
When _action_done is called on a transfer, it may delete a part of
the move lines. The extension of `_action_done()` that assigns
a packaging fails with "Record does not exist or has been deleted".
Check if the if lines still exist before writing on them.
| Python | agpl-3.0 | BT-ojossen/stock-logistics-workflow,OCA/stock-logistics-workflow,BT-ojossen/stock-logistics-workflow,OCA/stock-logistics-workflow |
92d0a09cfb232270d04f82eccc451ee63bd7901a | dev/TOPSECRET/SirBot/lib/sirbot/shutdown.py | dev/TOPSECRET/SirBot/lib/sirbot/shutdown.py | # -*- coding: utf-8 -*-
#script containing all pertinent tasks to prepare for software termination.
#successful completion of this process at last runtime, will skip extra validation
#steps on next run
from json import dumps
def shutdown(config,interinput=None,interoutput=None):
#check for lingering runtime erro... | # -*- coding: utf-8 -*-
#script containing all pertinent tasks to prepare for software termination.
#successful completion of this process at last runtime, will skip extra validation
#steps on next run
def shutdown(config,interinput,interoutput):
#check for lingering runtime errors
#finishing writing log queu... | Revert "changes to config during runtime are now saved" | Revert "changes to config during runtime are now saved"
This reverts commit e09a780da17bb2f97d20aafc2c007fe3fc3051bb.
| Python | mit | SirRujak/SirBot |
411813bafe4b2af57aa7695f035e3e02b20ae85e | src/syntax/infix_coordination.py | src/syntax/infix_coordination.py | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
self.result_string = ""
# Break the tree
def break_tree(self, tree):
... | __author__ = 's7a'
# All imports
from nltk.tree import Tree
# The infix coordination class
class InfixCoordination:
# Constructor for the infix coordination
def __init__(self):
self.has_infix_coordination = False
# Break the tree
def break_tree(self, tree):
self.has_infix_coordinati... | Change the rules for infix coordinario | Change the rules for infix coordinario
| Python | mit | Somsubhra/Simplify,Somsubhra/Simplify,Somsubhra/Simplify |
b154eef7d36359d0fbcc11a165371d3a54f40682 | libtbx_refresh.py | libtbx_refresh.py | from __future__ import division
def run():
from dials.util.config import CompletionGenerator
gen = CompletionGenerator()
gen.generate()
try:
run()
except Exception, e:
pass
| from __future__ import division
def run():
from dials.util.config import CompletionGenerator
gen = CompletionGenerator()
gen.generate()
try:
run()
except Exception, e:
pass
try:
from glob import glob
import os
filenames = glob("extensions/*.pyc")
if len(filenames) > 0:
print "Cleaning up 'dials... | Delete *.pyc files from dials/extensions when doing libtbx.refresh | Delete *.pyc files from dials/extensions when doing libtbx.refresh | Python | bsd-3-clause | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials |
89454b1e83e01a4d523b776f74429a81467762da | redis/utils.py | redis/utils.py | try:
import hiredis
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
def from_url(url, db=None, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the path url fragment, if
none is provide... | from contextlib import contextmanager
try:
import hiredis
HIREDIS_AVAILABLE = True
except ImportError:
HIREDIS_AVAILABLE = False
def from_url(url, db=None, **kwargs):
"""
Returns an active Redis client generated from the given database URL.
Will attempt to extract the database id from the p... | Move import statement on top for PEP8 compliancy. | Move import statement on top for PEP8 compliancy.
| Python | mit | MegaByte875/redis-py,fengshao0907/redis-py,sigma-random/redis-py,sunminghong/redis-py,garnertb/redis-py,softliumin/redis-py,sirk390/redis-py,barseghyanartur/redis-py,zhangyancoder/redis-py,LTD-Beget/redis-py,boyxuper/redis-py,barseghyanartur/redis-py,dmugtasimov/redis-py,LTD-Beget/redis-py,yuruidong/redis-py,sigma-rand... |
a42ffdcd34876bcd1df81ce00dbfd6426580bd82 | gaphor/UML/classes/copypaste.py | gaphor/UML/classes/copypaste.py | import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Interface, Operation
@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
yield element.id, copy_named_element(element)
for feature in itertools.chain(
element... | import itertools
from gaphor.diagram.copypaste import copy, copy_named_element
from gaphor.UML import Association, Class, Enumeration, Interface, Operation
@copy.register(Class)
@copy.register(Interface)
def copy_class(element):
yield element.id, copy_named_element(element)
for feature in itertools.chain(
... | Copy enumeration literals when pasting an Enumeration | Copy enumeration literals when pasting an Enumeration
Signed-off-by: Dan Yeaw <2591e5f46f28d303f9dc027d475a5c60d8dea17a@yeaw.me>
| Python | lgpl-2.1 | amolenaar/gaphor,amolenaar/gaphor |
e72156f50b0bab241b90b0f0c53414529740acd6 | ds_binary_heap.py | ds_binary_heap.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BinaryHeap(object):
def __init__(self):
# Put single zero as the 1st element, so that
# integer division can be used in later methods.
self.heap_ls = [0]
self.current_... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class BinaryHeap(object):
def __init__(self):
# Put single zero as the 1st element, so that
# integer division can be used in later methods.
self.heap_ls = [0]
self.current_... | Add delete_min() and its helper func’s | Add delete_min() and its helper func’s
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
59536a70ef39e34a5aea57131492a475e05cd227 | lg_cms_director/setup.py | lg_cms_director/setup.py | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.packages import find_packages
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=['trollius', 'pulsar'],
package_dir={'': 'src'},
scripts=[],
requires=[]
)
setup(**d)
# vim: tabsto... | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.packages import find_packages
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup(
packages=find_packages('src'),
package_dir={'': 'src'},
scripts=[],
requires=[]
)
setup(**d)
# vim: tabstop=... | Revert to previous packaging of director's dependencies thx to @mvollrath | Revert to previous packaging of director's dependencies thx to @mvollrath
| Python | apache-2.0 | EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes,EndPointCorp/lg_ros_nodes |
cc4a17db1e4ba81019ed312cbe324874430b9814 | billybot/tests/test_billybot.py | billybot/tests/test_billybot.py | import time
import datetime
import unittest
from unittest.mock import patch, call
from billybot.billybot import MessageTriage
class TestMessageTriage(unittest.TestCase):
def setUp(self):
self.thread1 = MessageTriage('USERID1', 'user1', 'Warren', 'testchanl')
self.thread1.daemon = True
s... | import time
import datetime
import unittest
from unittest.mock import patch, call
from billybot.billybot import MessageTriage
class TestMessageTriage(unittest.TestCase):
def setUp(self):
self.thread1 = MessageTriage('USERID1', 'user1', 'Warren', 'testchanl')
self.thread1.daemon = True
s... | Use a lambda to add a time delay function onto the mocked run method | Use a lambda to add a time delay function onto the mocked run method
| Python | mit | mosegontar/billybot |
4949b1051656566ce544a8240b0328a61259868a | migrations/versions/139_add_ns_index_to_contact_and_event.py | migrations/versions/139_add_ns_index_to_contact_and_event.py | """Add compound index to Contact and Event
Revision ID: 1fd7b3e0b662
Revises: 5305d4ae30b4
Create Date: 2015-02-17 18:11:30.726188
"""
# revision identifiers, used by Alembic.
revision = '1fd7b3e0b662'
down_revision = '2d8a350b4885'
from alembic import op
def upgrade():
op.create_index(
'ix_contact_ns... | """Add compound index to Contact and Event
Revision ID: 1fd7b3e0b662
Revises: 5305d4ae30b4
Create Date: 2015-02-17 18:11:30.726188
"""
# revision identifiers, used by Alembic.
revision = '1fd7b3e0b662'
down_revision = '5305d4ae30b4'
from alembic import op
def upgrade():
op.create_index(
'ix_contact_ns... | Fix migration history bug introduced with merge | Fix migration history bug introduced with merge
| Python | agpl-3.0 | wakermahmud/sync-engine,EthanBlackburn/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,gale320/sync-engine,wakermahmud/sync-engine,nylas/sync-engine,jobscore/sync-engine,nylas/sync-engine,jobscore/sync-engine,closeio/nylas,gale320/sync-engine,wakermahmud/sync-engine,closeio/nylas,PriviPK/privipk-sync-engine... |
de89049649fe720d45b271f519674845104f1941 | flow_workflow/petri_net/future_nets/base.py | flow_workflow/petri_net/future_nets/base.py | from flow.petri_net.future_net import FutureNet
from flow.petri_net.success_failure_net import SuccessFailureNet
class SimplifiedSuccessFailureNet(FutureNet):
def __init__(self, name=''):
FutureNet.__init__(self, name=name)
# Internal -- subclasses should connect to these
self.internal_st... | from flow.petri_net.future_net import FutureNet
from flow.petri_net.success_failure_net import SuccessFailureNet
class GenomeNetBase(SuccessFailureNet):
def __init__(self, name, operation_id, parent_operation_id=None):
SuccessFailureNet.__init__(self, name=name)
self.operation_id = operation_id
... | Make GenomeNetBase a SuccessFailureNet again | Make GenomeNetBase a SuccessFailureNet again
| Python | agpl-3.0 | genome/flow-workflow,genome/flow-workflow,genome/flow-workflow |
3486d3cb7122ba59c64d9af5b6eb6b12bc97e193 | brew/utilities/efficiency.py | brew/utilities/efficiency.py | # -*- coding: utf-8 -*-
from .sugar import sg_to_gu
__all__ = [
u'calculate_brew_house_yield',
]
def calculate_brew_house_yield(wort_volume, sg, grain_additions):
"""
Calculate Brew House Yield
:param float wort_volume: The volume of the wort
:param float sg: THe specific gravity of the wort
... | # -*- coding: utf-8 -*-
from ..constants import GRAIN_TYPE_DME
from ..constants import GRAIN_TYPE_LME
from .sugar import sg_to_gu
__all__ = [
u'calculate_brew_house_yield',
]
def calculate_brew_house_yield(wort_volume, sg, grain_additions):
"""
Calculate Brew House Yield
:param float wort_volume: T... | Clean up brew house yield calculator to deal with DME and LME additions | Clean up brew house yield calculator to deal with DME and LME additions
| Python | mit | chrisgilmerproj/brewday,chrisgilmerproj/brewday |
e65a8c057d9dbd156222542a0e544d294292de00 | thinglang/lexer/symbols/base.py | thinglang/lexer/symbols/base.py | from thinglang.utils.type_descriptors import ValueType
from thinglang.lexer.symbols import LexicalSymbol
class LexicalQuote(LexicalSymbol): # "
EMITTABLE = False
@classmethod
def next_operator_set(cls, current, original):
if current is original:
return {'"': LexicalQuote}
ret... | from thinglang.utils.type_descriptors import ValueType
from thinglang.lexer.symbols import LexicalSymbol
class LexicalQuote(LexicalSymbol): # "
EMITTABLE = False
@classmethod
def next_operator_set(cls, current, original):
if current is original:
return {'"': LexicalQuote}
ret... | Use new resolver in LexicalID resolution | Use new resolver in LexicalID resolution
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
e559c897cec534c58ab7940e2623a1decfb4958a | numpy/distutils/command/install_clib.py | numpy/distutils/command/install_clib.py | import os
from distutils.core import Command
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
description = "Command to install installable C libraries"
user_options = []
def initialize_options(self):
self.install_dir = None
self.outfiles = []
def finalize_o... | import os
from distutils.core import Command
from distutils.ccompiler import new_compiler
from numpy.distutils.misc_util import get_cmd
class install_clib(Command):
description = "Command to install installable C libraries"
user_options = []
def initialize_options(self):
self.install_dir = None
... | Move import at the top of module. | Move import at the top of module.
| Python | bsd-3-clause | jorisvandenbossche/numpy,MichaelAquilina/numpy,b-carter/numpy,sonnyhu/numpy,GrimDerp/numpy,dch312/numpy,githubmlai/numpy,astrofrog/numpy,brandon-rhodes/numpy,joferkington/numpy,CMartelLML/numpy,rajathkumarmp/numpy,ahaldane/numpy,MaPePeR/numpy,empeeu/numpy,pelson/numpy,nguyentu1602/numpy,jakirkham/numpy,jakirkham/numpy,... |
1d96f8a1456d902fe5a9e6ce5410a41b1468a810 | thinglang/parser/tokens/logic.py | thinglang/parser/tokens/logic.py | from thinglang.lexer.symbols.logic import LexicalEquality
from thinglang.parser.tokens import BaseToken
class Conditional(BaseToken):
ADVANCE = False
COMPARATORS = {
LexicalEquality: lambda lhs, rhs: lhs == rhs
}
def __init__(self, slice):
super(Conditional, self).__init__(slice)
... | from thinglang.lexer.symbols.logic import LexicalEquality
from thinglang.parser.tokens import BaseToken
class Conditional(BaseToken):
ADVANCE = False
def __init__(self, slice):
super(Conditional, self).__init__(slice)
_, self.value = slice
def describe(self):
return 'if {}'.form... | Complete migration from conditional to arithmetic operation | Complete migration from conditional to arithmetic operation
| Python | mit | ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang |
5606e8d56b7f6441eeb121795b0f400d65858b3b | tests/integration/test_fanout.py | tests/integration/test_fanout.py | import uuid
import diesel
from diesel.util.queue import Fanout
class FanoutHarness(object):
def setup(self):
self.fan = Fanout()
self.subscriber_data = {}
for x in xrange(10):
diesel.fork(self.subscriber)
diesel.sleep()
for i in xrange(10):
self.fan... | import uuid
import diesel
from diesel.util.queue import Fanout
from diesel.util.event import Countdown
class FanoutHarness(object):
def setup(self):
self.done = Countdown(10)
self.fan = Fanout()
self.subscriber_data = {}
for x in xrange(10):
diesel.fork(self.subscriber... | Add "done" tracking for fanout test. | Add "done" tracking for fanout test.
| Python | bsd-3-clause | dieseldev/diesel |
76deb311dbb981501a1fa2686ec2cf4c92d7b83b | taggit/admin.py | taggit/admin.py | from django.contrib import admin
from taggit.models import Tag, TaggedItem
class TaggedItemInline(admin.StackedInline):
model = TaggedItem
class TagAdmin(admin.ModelAdmin):
inlines = [
TaggedItemInline
]
ordering = ['name']
admin.site.register(Tag, TagAdmin)
| from django.contrib import admin
from taggit.models import Tag, TaggedItem
class TaggedItemInline(admin.StackedInline):
model = TaggedItem
extra = 0
class TagAdmin(admin.ModelAdmin):
inlines = [
TaggedItemInline
]
ordering = ['name']
admin.site.register(Tag, TagAdmin)
| Remove extra inlines from django-taggit | Remove extra inlines from django-taggit | Python | bsd-3-clause | theatlantic/django-taggit,theatlantic/django-taggit2,theatlantic/django-taggit2,theatlantic/django-taggit,decibyte/django-taggit,decibyte/django-taggit |
1862317c3b463704c8264f71007e7b910772b44e | tests/test_pprint.py | tests/test_pprint.py | import pytest
from mappyfile.pprint import PrettyPrinter
def test_print_map():
mf = {}
pp = PrettyPrinter() # expected
txt = pp.pprint(mf)
assert(expected == txt)
def run_tests():
#pytest.main(["tests/test_pprint.py::test_print_map"])
pytest.main(["tests/test_pprint.py"])
if __name__ ... | import pytest
from mappyfile.pprint import PrettyPrinter
import mappyfile
def test_format_list():
s = """
CLASS
STYLE
COLOR 173 216 230
END
STYLE
OUTLINECOLOR 2 2 2
WIDTH 1
LINECAP BUTT
PATT... | Add pair list formatting test | Add pair list formatting test
| Python | mit | Jenselme/mappyfile,geographika/mappyfile,geographika/mappyfile |
207bb83a7a41a36dbe27cb4b75f93fe0ae3a5625 | sgext/util/aws.py | sgext/util/aws.py | # -*- coding: utf-8 -*-
#
# © 2011 SimpleGeo, Inc. All rights reserved.
# Author: Paul Lathrop <paul@simplegeo.com>
#
"""Utility functions for AWS-related tasks."""
from getpass import getpass
import boto.pyami.config as boto_config
def get_credentials(batch=False):
"""Return a tuple (key, secret) of AWS crede... | # -*- coding: utf-8 -*-
#
# © 2011 SimpleGeo, Inc. All rights reserved.
# Author: Paul Lathrop <paul@simplegeo.com>
#
"""Utility functions for AWS-related tasks."""
from getpass import getpass
import boto.pyami.config as boto_config
def get_credentials(batch=False):
"""Return a dictionary of AWS credentials. C... | Fix get_credentials so it returns a dict. | Fix get_credentials so it returns a dict.
| Python | bsd-2-clause | simplegeo/clusto-sgext |
20a92ff1ffe143193d95235c7a5ea8e9edb0df64 | yowsup/layers/protocol_acks/protocolentities/ack_outgoing.py | yowsup/layers/protocol_acks/protocolentities/ack_outgoing.py | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):
'''
<ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
</ack>
'''
def __init__(self, _id, _class, _ty... | from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .ack import AckProtocolEntity
class OutgoingAckProtocolEntity(AckProtocolEntity):
'''
<ack type="{{delivery | read}}" class="{{message | receipt | ?}}" id="{{MESSAGE_ID}} to={{TO_JID}}">
</ack>
<ack to="{{GROUP_JID}}" participant="{{JID}... | Include participant in outgoing ack | Include participant in outgoing ack
| Python | mit | ongair/yowsup,biji/yowsup |
30907bbfc1b6d38034867070075a28fd3c5d3c6b | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/cli.py | {{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/cli.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.environ["KIVY_NO_ARGS"] = "1"
import click
from {{cookiecutter.repo_name}} import {{cookiecutter.app_class_name}}
@click.command()
@click.option(
'-l', '--language', help='Default language of the App', default='en',
type=click.Choice(['en', 'es', '... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.environ["KIVY_NO_ARGS"] = "1"
import click
from {{cookiecutter.repo_name}}.{{cookiecutter.repo_name}} import {{cookiecutter.app_class_name}}
@click.command()
@click.option(
'-l', '--language', help='Default language of the App', default='en',
type=... | Use absolute path for app import | Use absolute path for app import
| Python | mit | hackebrot/cookiedozer,hackebrot/cookiedozer |
f872bd95e9a26b326ea49922a373f90d73d0df2f | show_usbcamera.py | show_usbcamera.py | #! /usr/bin/env python
#
# Show the USB camera
#
#
# External dependencies
#
import sys
from PySide import QtGui
import VisionToolkit as vtk
#
# Main application
#
if __name__ == '__main__' :
application = QtGui.QApplication( sys.argv )
widget = vtk.UsbCameraWidget()
widget.show()
sys.exit( appli... | #! /usr/bin/env python
# -*- coding:utf-8 -*-
#
# Show the images from a USB camera
#
#
# External dependencies
#
import sys
from PySide import QtGui
import VisionToolkit as vtk
#
# Main application
#
if __name__ == '__main__' :
application = QtGui.QApplication( sys.argv )
widget = vtk.UsbCameraWidget()
... | Change character coding and a comment. | Change character coding and a comment.
| Python | mit | microy/StereoVision,microy/VisionToolkit,microy/StereoVision,microy/PyStereoVisionToolkit,microy/PyStereoVisionToolkit,microy/VisionToolkit |
fc0ee0d418496f0ec8da01e8bd8e2d12024accaa | simulate_loads.py | simulate_loads.py | import random
import itertools as it
from sklearn.externals import joblib
def simulate_loads(nfrag, ngt, q):
loads = [1] * nfrag
active = set(range(nfrag))
for k in range(1, len(loads)):
i0, i1 = random.sample(active, k=2)
active.remove(i0)
active.remove(i1)
active.add(len(l... | import pickle
import random
import itertools as it
from sklearn.externals import joblib
def simulate_loads(nfrag, ngt, q):
loads = [1] * nfrag
active = set(range(nfrag))
for k in range(1, len(loads)):
i0, i1 = random.sample(active, k=2)
active.remove(i0)
active.remove(i1)
ac... | Add main script to CSR simulations | Add main script to CSR simulations
| Python | bsd-3-clause | jni/gala-scripts |
bdae1f203f3d5d600dd62470dea3d2ddb3048b9d | turbustat/tests/test_wavelet.py | turbustat/tests/test_wavelet.py | # Licensed under an MIT open source license - see LICENSE
'''
Test function for Wavelet
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import wt2D, Wavelet_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class tes... | # Licensed under an MIT open source license - see LICENSE
'''
Test function for Wavelet
'''
from unittest import TestCase
import numpy as np
import numpy.testing as npt
from ..statistics import Wavelet, Wavelet_Distance
from ._testing_data import \
dataset1, dataset2, computed_data, computed_distances
class ... | Change class name in tests | Change class name in tests
| Python | mit | e-koch/TurbuStat,Astroua/TurbuStat |
293f44e211e4f26a0b7eca842dd2af515957a4bd | octavia/certificates/generator/cert_gen.py | octavia/certificates/generator/cert_gen.py | # Copyright (c) 2014 Rackspace US, 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 req... | # Copyright (c) 2014 Rackspace US, 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 req... | Add Cert+PK generation to Certificate Interface | Add Cert+PK generation to Certificate Interface
Change-Id: I82aa573c7db13c7a491b18540379b234c1023eb9
| Python | apache-2.0 | openstack/octavia,openstack/octavia,openstack/octavia |
44d103359cff312865f409ff34f528f63e441ef4 | graphapi/views.py | graphapi/views.py | from simplekeys.verifier import verify_request
from graphene_django.views import GraphQLView
from django.conf import settings
class KeyedGraphQLView(GraphQLView):
graphiql_template = "graphene/graphiql-keyed.html"
def get_response(self, request, data, show_graphiql=False):
# check key only if we're n... | from simplekeys.verifier import verify_request
from graphene_django.views import GraphQLView
from django.conf import settings
class KeyedGraphQLView(GraphQLView):
graphiql_template = "graphene/graphiql-keyed.html"
def get_response(self, request, data, show_graphiql=False):
# check key only if we're n... | Revert "Reimplement using explicit variable lookup" | Revert "Reimplement using explicit variable lookup"
This reverts commit 94683e6c
| Python | mit | openstates/openstates.org,openstates/openstates.org,openstates/openstates.org,openstates/openstates.org |
fc508462e3fa9b03f0ee55df21c44863fbd8bae0 | tests/providers/phone_number.py | tests/providers/phone_number.py | # coding=utf-8
from __future__ import unicode_literals
import unittest
from faker import Factory
from .. import string_types
class TestJaJP(unittest.TestCase):
""" Tests phone_number in the ja_JP locale """
def setUp(self):
self.factory = Factory.create('ja')
def test_phone_number(self):
... | # coding=utf-8
from __future__ import unicode_literals
import unittest
from faker import Factory
from .. import string_types
class TestJaJP(unittest.TestCase):
""" Tests phone_number in the ja_JP locale """
def setUp(self):
self.factory = Factory.create('ja')
def test_phone_number(self):
... | Add the msisdn provider test | Add the msisdn provider test
| Python | mit | joke2k/faker,danhuss/faker,joke2k/faker |
48081a925d5b69e18a1f04c74cbe98b590e77c5b | tests/unit/test_pylama_isort.py | tests/unit/test_pylama_isort.py | import os
from isort.pylama_isort import Linter
class TestLinter:
instance = Linter()
def test_allow(self):
assert not self.instance.allow("test_case.pyc")
assert not self.instance.allow("test_case.c")
assert self.instance.allow("test_case.py")
def test_run(self, src_dir, tmpdir... | import os
from isort.pylama_isort import Linter
class TestLinter:
instance = Linter()
def test_allow(self):
assert not self.instance.allow("test_case.pyc")
assert not self.instance.allow("test_case.c")
assert self.instance.allow("test_case.py")
def test_run(self, src_dir, tmpdir... | Add a test for skip functionality | Add a test for skip functionality
| Python | mit | PyCQA/isort,PyCQA/isort |
ca0d9e9651e51797ad317e54c58a174bcb351610 | channels/__init__.py | channels/__init__.py | __version__ = "0.9"
default_app_config = 'channels.apps.ChannelsConfig'
DEFAULT_CHANNEL_LAYER = 'default'
from .asgi import channel_layers # NOQA isort:skip
from .channel import Channel, Group # NOQA isort:skip
| __version__ = "0.9"
default_app_config = 'channels.apps.ChannelsConfig'
DEFAULT_CHANNEL_LAYER = 'default'
try:
from .asgi import channel_layers # NOQA isort:skip
from .channel import Channel, Group # NOQA isort:skip
except ImportError: # No django installed, allow vars to be read
pass
| Fix version import during pip install | Fix version import during pip install
| Python | bsd-3-clause | raphael-boucher/channels,Coread/channels,Coread/channels,django/channels,Krukov/channels,andrewgodwin/channels,Krukov/channels,andrewgodwin/django-channels,raiderrobert/channels,linuxlewis/channels |
b7bb933b23b5b86a2555e5fdd8919f852960a4cb | firecares/firestation/management/commands/export-building-fires.py | firecares/firestation/management/commands/export-building-fires.py | from django.core.management.base import BaseCommand
from firecares.firestation.models import FireDepartment
class Command(BaseCommand):
"""
This command is used to export data that department heat maps visualize.
"""
help = 'Creates a sql file to export building fires from.'
def handle(self, *ar... | from django.core.management.base import BaseCommand
from firecares.firestation.models import FireDepartment
class Command(BaseCommand):
"""
This command is used to export data that department heat maps visualize.
"""
help = 'Creates a sql file to export building fires from.'
def handle(self, *ar... | Update export building fires script. | Update export building fires script.
| Python | mit | FireCARES/firecares,FireCARES/firecares,FireCARES/firecares,FireCARES/firecares,FireCARES/firecares |
289be31dff1bbff200054e5acffc4d6640caaa97 | civis/utils/_jobs.py | civis/utils/_jobs.py | from civis import APIClient
from civis.futures import CivisFuture
def run_job(job_id, api_key=None):
"""Run a job.
Parameters
----------
job_id : str or int
The ID of the job.
api_key : str, optional
Your Civis API key. If not given, the :envvar:`CIVIS_API_KEY`
environment... | from civis import APIClient
from civis.futures import CivisFuture
def run_job(job_id, api_key=None):
"""Run a job.
Parameters
----------
job_id : str or int
The ID of the job.
api_key : str, optional
Your Civis API key. If not given, the :envvar:`CIVIS_API_KEY`
environment... | Set poll_on_creation to False for run_job | Set poll_on_creation to False for run_job
| Python | bsd-3-clause | civisanalytics/civis-python |
0ac671d554f322524741a795f4a3250ef705f872 | server/ec2spotmanager/migrations/0010_extend_instance_types.py | server/ec2spotmanager/migrations/0010_extend_instance_types.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-08-24 14:55
from __future__ import unicode_literals
from django.db import migrations, models
import ec2spotmanager.models
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0009_add_instance_size'),
]
operati... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-08-24 14:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ec2spotmanager', '0009_add_instance_size'),
]
operations = [
migrations.Al... | Fix Flake8 error in migration. | Fix Flake8 error in migration.
| Python | mpl-2.0 | MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager |
0b3a414be19546df348ebca148362bf370c61c15 | zerver/migrations/0127_disallow_chars_in_stream_and_user_name.py | zerver/migrations/0127_disallow_chars_in_stream_and_user_name.py | # -*- coding: utf-8 -*-
from django.db import models, migrations
from django.db.backends.postgresql_psycopg2.schema import DatabaseSchemaEditor
from django.db.migrations.state import StateApps
from typing import Text
def remove_special_chars_from_streamname(apps, schema_editor):
# type: (StateApps, DatabaseSchemaE... | # -*- coding: utf-8 -*-
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('zerver', '0126_prereg_remove_users_without_realm'),
]
operations = [
# There was a migration here, which wasn't ready for wide deployment
# and was backed out. This ... | Revert "migrations: Replace special chars in stream & user names with space." | Revert "migrations: Replace special chars in stream & user names with space."
This reverts commit acebd3a5e, as well as a subsequent fixup commit
0975bebac "quick fix: Fix migrations to be linear."
These changes need more work and thought before they're ready to
deploy on any large established Zulip server, such as z... | Python | apache-2.0 | showell/zulip,andersk/zulip,tommyip/zulip,hackerkid/zulip,timabbott/zulip,synicalsyntax/zulip,brainwane/zulip,zulip/zulip,shubhamdhama/zulip,shubhamdhama/zulip,brainwane/zulip,jackrzhang/zulip,eeshangarg/zulip,rishig/zulip,rishig/zulip,eeshangarg/zulip,brainwane/zulip,rishig/zulip,zulip/zulip,rishig/zulip,eeshangarg/zu... |
e1dc2c3e2515daf3aae51242221fab4fbd5c553f | aim/db/migration/alembic_migrations/versions/72fa5bce100b_tree_model.py | aim/db/migration/alembic_migrations/versions/72fa5bce100b_tree_model.py | # Copyright (c) 2016 Cisco Systems
# 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 require... | # Copyright (c) 2016 Cisco Systems
# 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 require... | Fix db migration for tree model | Fix db migration for tree model
| Python | apache-2.0 | noironetworks/aci-integration-module,noironetworks/aci-integration-module |
f2000016a9e2acd4cad28b1ea301620723140a4e | sheldon/bot.py | sheldon/bot.py | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
... | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
from sheldon.utils import logger
... | Change error status with config problems to critical | Change error status with config problems to critical
| Python | mit | lises/sheldon |
450cbc7d0cb9a2477b80e94c874de1da4a00e431 | source/services/rotten_tomatoes_service.py | source/services/rotten_tomatoes_service.py | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self... | import requests
from bs4 import BeautifulSoup
from source.models.rt_rating import RTRating
class RottenTomatoesService:
__URL = 'http://www.rottentomatoes.com/m/'
__SEPERATOR = '_'
def __init__(self, title):
self.title = title
def get_rt_rating(self):
search_url = self.__URL + self... | Remove colon from title for RT search | Remove colon from title for RT search
| Python | mit | jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu |
ec244cc9c56fec571502529ef24af2ca18d9f5f5 | spirit/templatetags/tags/utils/gravatar.py | spirit/templatetags/tags/utils/gravatar.py | #-*- coding: utf-8 -*-
import hashlib
from django.utils.http import urlencode, urlquote
from .. import register
@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
url = "http://www.gravatar.com/avatar/"
hash = hashlib.md5(user.email.strip().lower()).hexdigest()
d... | #-*- coding: utf-8 -*-
import hashlib
from django.utils.http import urlencode, urlquote
from django.utils.encoding import force_bytes
from .. import register
@register.simple_tag()
def get_gravatar_url(user, size, rating='g', default='identicon'):
url = "http://www.gravatar.com/avatar/"
hash = hashlib.md5... | Use django utils force_bytes to arguments of hashlib | Use django utils force_bytes to arguments of hashlib
| Python | mit | alesdotio/Spirit,a-olszewski/Spirit,raybesiga/Spirit,a-olszewski/Spirit,dvreed/Spirit,ramaseshan/Spirit,adiyengar/Spirit,battlecat/Spirit,ramaseshan/Spirit,gogobook/Spirit,dvreed/Spirit,nitely/Spirit,mastak/Spirit,battlecat/Spirit,nitely/Spirit,a-olszewski/Spirit,alesdotio/Spirit,mastak/Spirit,alesdotio/Spirit,gogobook... |
85d71d8a5d7cdf34c12791b84c9f1bdec4ad1ed1 | partner_compassion/wizards/portal_wizard.py | partner_compassion/wizards/portal_wizard.py | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py... | Fix bug, set notify_email to always after create portal user | Fix bug, set notify_email to always after create portal user
| Python | agpl-3.0 | ecino/compassion-switzerland,CompassionCH/compassion-switzerland,ecino/compassion-switzerland,CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland,ecino/compassion-switzerland |
8e3beda427e2edc2bc7b8f7f96f8ef1c7dd571c7 | downloads/urls.py | downloads/urls.py | from django.conf.urls import patterns, url
from django.utils.translation import ugettext_lazy as _
from problems.models import UserSolution
from .views import download_protected_file
urlpatterns = patterns('',
url(_(r'solutions/(?P<path>.*)$'), download_protected_file,
dict(path_prefix='solutions/', mode... | from django.conf.urls import patterns, url
from django.utils.translation import ugettext_lazy as _
from problems.models import UserSolution
from .views import download_protected_file
urlpatterns = patterns('',
url(_(r'solutions/(?P<path>.*)$'), download_protected_file,
dict(path_prefix='solutions/', mode... | Add view for displaying corrected solutions | downloads: Add view for displaying corrected solutions
| Python | mit | matus-stehlik/roots,tbabej/roots,tbabej/roots,matus-stehlik/roots,rtrembecky/roots,matus-stehlik/roots,rtrembecky/roots,tbabej/roots,rtrembecky/roots |
5dece3e052a1bebda6b1e1af63855399435f2e49 | src/mailflow/settings.py | src/mailflow/settings.py | SQLALCHEMY_DATABASE_URI = "postgres://@/mailflow"
SECRET_KEY = 'Chi6riup1gaetiengaShoh=Wey1pohph0ieDaes7eeph'
INBOX_LOGIN_LENGTH = 16
INBOX_PASSWORD_LENGTH = 16
INBOX_PAGE_SIZE = 50
INBOX_HOST = 'mailflow.openpz.org'
INBOX_PORT = 25
RAW_EMAIL_FOLDER = "/var/tmp"
RABBITMQ_URI = 'amqp://mailflow:youneverguess@localho... | SQLALCHEMY_DATABASE_URI = "postgres://@/mailflow"
SECRET_KEY = 'Chi6riup1gaetiengaShoh=Wey1pohph0ieDaes7eeph'
INBOX_LOGIN_LENGTH = 16
INBOX_PASSWORD_LENGTH = 16
INBOX_PAGE_SIZE = 50
INBOX_HOST = 'mailflow.openpz.org'
INBOX_PORT = 25
RAW_EMAIL_FOLDER = "/var/tmp"
RABBITMQ_URI = 'amqp://mailflow:youneverguess@localho... | Set CSRF token expirtion time to 6 hours | Set CSRF token expirtion time to 6 hours
| Python | apache-2.0 | zzzombat/mailflow,zzzombat/mailflow |
08d83313d2e077e760adc9a4bfd7c181d9f8a60a | cal_pipe/update_pipeline_paths.py | cal_pipe/update_pipeline_paths.py |
'''
Update EVLA pipeline variables to the current system.
'''
def update_paths(pipe_dict, ms_path, pipepath):
pipe_dict['ms_active'] = ms_path
pipe_dict['SDM_name'] = ms_path[:-3] # Cutoff '.ms'
pipe_dict['pipepath'] = pipepath
return pipe_dict
if __name__ == '__main__':
import sys
pipe... |
'''
Update EVLA pipeline variables to the current system.
'''
def update_paths(pipe_dict, ms_path, pipepath):
pipe_dict['ms_active'] = ms_path
pipe_dict['SDM_name'] = ms_path[:-3] # Cutoff '.ms'
pipe_dict['pipepath'] = pipepath
return pipe_dict
if __name__ == '__main__':
import sys
pipe... | Print out changed paths in pipeline file | Print out changed paths in pipeline file
| Python | mit | e-koch/canfar_scripts,e-koch/canfar_scripts |
cc08888a527dac321f88cbe9da27508aee62e51e | examples/lab/main.py | examples/lab/main.py | """
Copyright (c) Jupyter Development Team.
Distributed under the terms of the Modified BSD License.
"""
import os
from jinja2 import FileSystemLoader
from notebook.base.handlers import IPythonHandler, FileFindHandler
from notebook.notebookapp import NotebookApp
from traitlets import Unicode
class ExampleHandler(IPy... | """
Copyright (c) Jupyter Development Team.
Distributed under the terms of the Modified BSD License.
"""
import os
from jinja2 import FileSystemLoader
from notebook.base.handlers import IPythonHandler, FileFindHandler
from notebook.notebookapp import NotebookApp
from traitlets import Unicode
class ExampleHandler(IPy... | Enable terminals in the lab example | Enable terminals in the lab example
| Python | bsd-3-clause | eskirk/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,charnpreetsingh185/jupyterlab,jupyter/jupyterlab,jupyter/jupyterlab,eskirk/jupyterlab,charnpreetsingh185/jupyterlab,eskirk/jupyterlab,charnpreetsingh... |
e53d324f2ac4874c1f56bbf00dfee47c6b059e5d | fluidreview/admin.py | fluidreview/admin.py | """Admin interface for fluidreview"""
from django.contrib import admin
from bootcamp.utils import get_field_names
from fluidreview.models import WebhookRequest, OAuthToken
class WebhookRequestAdmin(admin.ModelAdmin):
"""Admin for WebhookRequest"""
model = WebhookRequest
readonly_fields = get_field_names(... | """Admin interface for fluidreview"""
from django.contrib import admin
from bootcamp.utils import get_field_names
from fluidreview.models import WebhookRequest, OAuthToken
class WebhookRequestAdmin(admin.ModelAdmin):
"""Admin for WebhookRequest"""
model = WebhookRequest
readonly_fields = get_field_names(... | Sort webhook requests by date | Sort webhook requests by date
| Python | bsd-3-clause | mitodl/bootcamp-ecommerce,mitodl/bootcamp-ecommerce,mitodl/bootcamp-ecommerce,mitodl/bootcamp-ecommerce |
678ddb9813edbc8a0013e8cf9ae5ff17cf3c72f7 | test/test_grid.py | test/test_grid.py | import pytest
import torch
from torch import Tensor
import syft as sy
def test_virtual_grid(workers):
"""This tests our ability to simplify tuple types.
This test is pretty simple since tuples just serialize to
themselves, with a tuple wrapper with the correct ID (1)
for tuples so that the detailer k... | import pytest
import torch
from torch import Tensor
import syft as sy
def test_virtual_grid(workers):
"""This tests our ability to simplify tuple types.
This test is pretty simple since tuples just serialize to
themselves, with a tuple wrapper with the correct ID (1)
for tuples so that the detailer k... | Fix test on grid search | Fix test on grid search
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft |
49cd32a7d1b3f70da19ed6f90d930646914d9756 | testTwitterAPI.py | testTwitterAPI.py | '''
Created on Apr 25, 2015
@author: Sherry
'''
from json import dumps
from twitterDataAcquisition import TwitterDataAcquisition
def main():
twitterData = TwitterDataAcquisition()
#jsonFile = ("twitter_data.json", "w")
#jsonFile.write(str(twitterData))
#jsonFile.close()
print dumps... | '''
Created on Apr 25, 2015
@author: Sherry
'''
from json import dumps
from twitterDataAcquisition import TwitterDataAcquisition
from twitterScreenScrape import TwitterScreenScrape
def main():
appsList = ["Messenger", "Criminal Case", "Facebook", "Pandora Radio", "Instagram",
"Snapchat", "Dubsmash"... | Include call for screen scraping | Include call for screen scraping
| Python | apache-2.0 | WenTr/TrendingApps |
2b477a2f4cbbcb1ac25c48ace0597d3d5713cafd | tastytaps/urls.py | tastytaps/urls.py | from django.conf.urls import include, url
from django.contrib import admin
from .views import HomePageView
urlpatterns = [
url(r'^$', HomePageView.as_view(), name='home'),
url(r'^admin/', include(admin.site.urls)),
]
| from django.conf.urls import url
from .views import HomePageView
urlpatterns = [
url(r'^$', HomePageView.as_view(), name='home'),
]
| Drop the admin for srs this time | Drop the admin for srs this time
| Python | bsd-3-clause | tastybrew/tastytaps,tastybrew/tastytaps |
8b321c2aa37d57cc3cfc092ab2d887ce685284b6 | junction/conferences/serializers.py | junction/conferences/serializers.py | from rest_framework import serializers
from .models import Conference, ConferenceVenue, Room
class ConferenceSerializer(serializers.HyperlinkedModelSerializer):
status = serializers.CharField(source='get_status_display')
class Meta:
model = Conference
fields = ('id', 'name', 'slug', 'descrip... | from rest_framework import serializers
from .models import Conference, ConferenceVenue, Room
class ConferenceSerializer(serializers.HyperlinkedModelSerializer):
status = serializers.CharField(source='get_status_display')
class Meta:
model = Conference
fields = ('id', 'name', 'slug', 'descrip... | Add id in the room, venue endpoint | Add id in the room, venue endpoint
| Python | mit | praba230890/junction,nava45/junction,ChillarAnand/junction,farhaanbukhsh/junction,praba230890/junction,praba230890/junction,ChillarAnand/junction,farhaanbukhsh/junction,farhaanbukhsh/junction,pythonindia/junction,ChillarAnand/junction,nava45/junction,ChillarAnand/junction,praba230890/junction,pythonindia/junction,pytho... |
1a88833845776d7592bbdef33571cd2da836cb91 | ookoobah/tools.py | ookoobah/tools.py | class BaseTool (object):
draw_locks = False
def update_cursor(self, mouse):
mouse.set_cursor(None)
class DrawTool (BaseTool):
def __init__(self, block_class):
self.block_class = block_class
def apply(self, pos, game, editor):
old = game.grid.get(pos)
if old.__class__ ==... | class BaseTool (object):
draw_locks = False
def update_cursor(self, mouse):
mouse.set_cursor(None)
class DrawTool (BaseTool):
def __init__(self, block_class):
self.block_class = block_class
def apply(self, pos, game, editor):
old = game.grid.get(pos)
if old.__class__ ==... | Return update flag from erase tool. | Return update flag from erase tool.
Fixes a bug introduced a couple commits earlier.
| Python | mit | vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah,vickenty/ookoobah |
2190e8dbdda5ed926fe9ab1875c0ad0d9bab690b | webparticipation/apps/send_token/tasks.py | webparticipation/apps/send_token/tasks.py | from celery import task
from django.core.mail import EmailMessage
from webparticipation.apps.ureporter.models import delete_user_from_rapidpro as delete_from
@task()
def send_verification_token(ureporter):
if ureporter.token:
subject = 'Hello'
body = 'Welcome to ureport. To complete the registrati... | from celery import task
from django.core.mail import EmailMessage
from webparticipation.apps.ureporter.models import delete_user_from_rapidpro as delete_from
@task()
def send_verification_token(ureporter):
if ureporter.token:
subject = 'U-Report Registration'
body = 'Thank you for registering with... | Change subject and content of registration email. | Change subject and content of registration email.
| Python | agpl-3.0 | rapidpro/ureport-web-participation,rapidpro/ureport-web-participation,rapidpro/ureport-web-participation |
7a6cd5ebe2e2fc357bc4f58409ca177f36814859 | glanceclient/common/exceptions.py | glanceclient/common/exceptions.py | # This is here for compatibility purposes. Once all known OpenStack clients
# are updated to use glanceclient.exc, this file should be removed
from glanceclient.exc import * # noqa
| # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed u... | Add Apache 2.0 license to source file | Add Apache 2.0 license to source file
As per OpenStack licensing guide lines [1]:
[H102 H103] Newly contributed Source Code should be licensed under
the Apache 2.0 license.
[H104] Files with no code shouldn't contain any license header nor
comments, and must be left completely empty.
[1] http://docs.openstack.org/dev... | Python | apache-2.0 | openstack/python-glanceclient,openstack/python-glanceclient |
853bfc4d010f6c80bef6878a356df73a60f09596 | test_config.py | test_config.py | import tempfile
import shutil
import os
from voltgrid import ConfigManager
def test_config_manager():
c = ConfigManager('voltgrid.conf.example')
c.write_envs()
def test_config_is_empty():
with tempfile.NamedTemporaryFile() as tmp_f:
c = ConfigManager(tmp_f.name)
def test_config_not_exist():
... | import tempfile
import shutil
import os
from voltgrid import ConfigManager
VG_CFG = 'voltgrid.conf.example'
def test_config_manager():
c = ConfigManager(VG_CFG)
c.write_envs()
def test_config_is_empty():
with tempfile.NamedTemporaryFile() as tmp_f:
c = ConfigManager(tmp_f.name)
def test_conf... | Fix test loading wrong config | Fix test loading wrong config
| Python | bsd-3-clause | voltgrid/voltgrid-pie |
0d7db5b134aaed2721dff8f7be300878fffa0c44 | genestack_client/__init__.py | genestack_client/__init__.py | # -*- coding: utf-8 -*-
import sys
if not ((2, 7, 5) <= sys.version_info < (3, 0)):
sys.stderr.write(
'Python version "%s" is not supported. Required version 2.7.5+, Python 3 is not supported\n' % sys.version
)
exit(1)
from version import __version__
from genestack_exceptions import (GenestackAu... | # -*- coding: utf-8 -*-
import sys
if not ((2, 7, 5) <= sys.version_info < (3, 0)):
sys.stderr.write(
'Python version "%s" is not supported. Required version 2.7.5+, Python 3 is not supported\n' % sys.version
)
exit(1)
from version import __version__
from genestack_exceptions import (GenestackAu... | Delete findMetainfoRelatedTerms method from Genestack Core findMetainfoRelatedTerms is deleted | [JBKB-996] Delete findMetainfoRelatedTerms method from Genestack Core
findMetainfoRelatedTerms is deleted
| Python | mit | genestack/python-client |
ac5b065e948a923f71b5f3bc9e98bcb8791a46c9 | git_code_debt/write_logic.py | git_code_debt/write_logic.py | from __future__ import absolute_import
from __future__ import unicode_literals
def insert_metric_ids(db, metric_ids):
for metric_id in metric_ids:
db.execute(
"INSERT INTO metric_names ('name') VALUES (?)", [metric_id],
)
def insert_metric_values(db, metric_values, metric_mapping, co... | from __future__ import absolute_import
from __future__ import unicode_literals
def insert_metric_ids(db, metric_ids):
values = [[x] for x in metric_ids]
db.executemany("INSERT INTO metric_names ('name') VALUES (?)", values)
def insert_metric_values(db, metric_values, metric_mapping, commit):
values = [
... | Use executemany instead of execute in write logic | Use executemany instead of execute in write logic
| Python | mit | Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt,Yelp/git-code-debt |
9a746c3ea33057efaf01cb8b700d4ea5d38863bf | tests/regression_test.py | tests/regression_test.py | """
A regression test for computing three kinds of spectrogram.
Just to ensure we didn't break anything.
"""
import numpy as np
import os
from tfr.files import load_wav
from tfr.spectrogram_features import spectrogram_features
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
def test_spec... | """
A regression test for computing three kinds of spectrogram.
Just to ensure we didn't break anything.
"""
import numpy as np
import os
from tfr.files import load_wav
from tfr.spectrogram_features import spectrogram_features
DATA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
def test_spec... | Print the error in the regression test. | Print the error in the regression test.
| Python | mit | bzamecnik/tfr,bzamecnik/tfr |
6f6199240009ac91da7e663030125df439d8fe7e | tests/test_trust_list.py | tests/test_trust_list.py | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import unittest
import sys
from oscrypto import trust_list
from asn1crypto.x509 import Certificate
if sys.version_info < (3,):
byte_cls = str
else:
byte_cls = bytes
class TrustListTests(unittest.TestCase):
... | # coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
import unittest
import sys
from oscrypto import trust_list
from asn1crypto.x509 import Certificate
if sys.version_info < (3,):
byte_cls = str
else:
byte_cls = bytes
class TrustListTests(unittest.TestCase):
... | Add more sanity checks to the trust list test | Add more sanity checks to the trust list test
| Python | mit | wbond/oscrypto |
1aaa2034020297fe78c2a0e12b713b835e13a156 | thumborizeme/settings.py | thumborizeme/settings.py | import os
# REDIS
REDIS_HOST = '127.0.0.1'
REDIS_PORT = 6379
HOST = os.environ.get('HOST', 'http://localhost:9000')
THUMBOR_HOST = os.environ.get('HOST', 'http://localhost:8001')
| import os
# REDIS
REDIS_HOST = os.environ.get('REDIS_URL', '127.0.0.1')
REDIS_PORT = os.environ.get('REDIS_PORT', 6379)
HOST = os.environ.get('HOST', 'http://localhost:9000')
THUMBOR_HOST = os.environ.get('HOST', 'http://localhost:8001')
| Change redis url and redis port | Change redis url and redis port
| Python | mit | heynemann/thumborizeme,heynemann/thumborizeme,heynemann/thumborizeme |
cd70e1150d3822a0f158e06c382ad8841760040e | mla_game/apps/transcript/management/commands/update_stats_for_all_eligible_transcripts.py | mla_game/apps/transcript/management/commands/update_stats_for_all_eligible_transcripts.py | from django.core.management.base import BaseCommand
from django.db.models import Prefetch
from mla_game.apps.transcript.tasks import update_transcript_stats
from ...models import (
Transcript, TranscriptPhraseVote, TranscriptPhraseCorrection,
)
class Command(BaseCommand):
help = '''Find all Transcripts with... | from django.core.management.base import BaseCommand
from django.db.models import Prefetch
from mla_game.apps.transcript.tasks import update_transcript_stats
from ...models import (
Transcript, TranscriptPhraseVote, TranscriptPhraseCorrection,
)
class Command(BaseCommand):
help = '''Find all Transcripts with... | Update management command for various changes | Update management command for various changes
| Python | mit | WGBH/FixIt,WGBH/FixIt,WGBH/FixIt |
850d5be6b5a53bafd0197e1454da2583abb6db77 | test/test_pipeline/components/regression/test_random_forests.py | test/test_pipeline/components/regression/test_random_forests.py | import unittest
from autosklearn.pipeline.components.regression.random_forest import RandomForest
from autosklearn.pipeline.util import _test_regressor, _test_regressor_iterative_fit
import sklearn.metrics
class RandomForestComponentTest(unittest.TestCase):
def test_default_configuration(self):
for i in... | import unittest
from autosklearn.pipeline.components.regression.random_forest import RandomForest
from autosklearn.pipeline.util import _test_regressor, _test_regressor_iterative_fit
import sklearn.metrics
class RandomForestComponentTest(unittest.TestCase):
def test_default_configuration(self):
for i in... | ADD test to test iterative fit sparse | ADD test to test iterative fit sparse
| Python | bsd-3-clause | automl/auto-sklearn,automl/auto-sklearn |
c9abba3a9ca6ccf1a9bed5fad5cda12557b3266c | tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py | tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py | import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
available = False
... | import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
available = False
... | Use plot_report._available instead of available() | Use plot_report._available instead of available()
| Python | mit | hvy/chainer,jnishi/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,okuta/chainer,chainer/chainer,hvy/chainer,ktnyt/chainer,ktnyt/chainer,wkentaro/chainer,jnishi/ch... |
94737c504ffdf55ddc8a0a24561f52fc531b6047 | djangorest_alchemy/apibuilder.py | djangorest_alchemy/apibuilder.py | """
API Builder
Build dynamic API based on the provided SQLAlchemy model
"""
from managers import AlchemyModelManager
from viewsets import AlchemyModelViewSet
from rest_framework_nested import routers
class APIModelBuilder(object):
def __init__(self,
models,
base_managers,
... | """
API Builder
Build dynamic API based on the provided SQLAlchemy model
"""
from managers import AlchemyModelManager
from viewsets import AlchemyModelViewSet
from routers import ReadOnlyRouter
class APIModelBuilder(object):
def __init__(self,
models,
base_managers,
... | Change to use read-only router for data-apis | Change to use read-only router for data-apis
| Python | mit | dealertrack/djangorest-alchemy,pombredanne/djangorest-alchemy |
6dcd30cba47798e8d6f2ef99f2b6c13cf7d60cad | migrations/versions/216_add_folder_separator_column_for_generic_.py | migrations/versions/216_add_folder_separator_column_for_generic_.py | """add folder_separator column for generic imap
Revision ID: 4f8e995d1dba
Revises: 31aae1ecb374
Create Date: 2016-02-02 01:17:24.746355
"""
# revision identifiers, used by Alembic.
revision = '4f8e995d1dba'
down_revision = '4bfecbcc7dbd'
from alembic import op
from sqlalchemy.sql import text
def upgrade():
co... | """add folder_separator column for generic imap
Revision ID: 4f8e995d1dba
Revises: 31aae1ecb374
Create Date: 2016-02-02 01:17:24.746355
"""
# revision identifiers, used by Alembic.
revision = '4f8e995d1dba'
down_revision = '4bfecbcc7dbd'
from alembic import op
from sqlalchemy.sql import text
def upgrade():
co... | Revert "merge alter statements together." | Revert "merge alter statements together."
This reverts commit 0ed919a86c835956596e9e897423e6176625f158.
Reverting all IMAP folder handling patches.
| Python | agpl-3.0 | closeio/nylas,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,nylas/sync-engine,jobscore/sync-engine,nylas/sync-engine,closeio/nylas,nylas/sync-engine,jobscore/sync-engine,jobscore/sync-engine,closeio/nylas |
f72b7ec93401bc817245c49790303fd925adb2c4 | server/plugins/remoteconnection/machine_detail_remote_connection.py | server/plugins/remoteconnection/machine_detail_remote_connection.py | """Machine detail plugin to allow easy VNC or SSH connections."""
import sal.plugin
from server.models import Machine, SalSetting
from server.utils import get_setting
class RemoteConnection(sal.plugin.DetailPlugin):
description = "Initiate VNC or SSH connections from a machine detail page."
supported_os_fa... | """Machine detail plugin to allow easy VNC or SSH connections."""
import sal.plugin
from server.models import Machine, SalSetting
from server.utils import get_setting
class RemoteConnection(sal.plugin.DetailPlugin):
description = "Initiate VNC or SSH connections from a machine detail page."
supported_os_fa... | Fix user account prepending to machine detail remote connection plugin. | Fix user account prepending to machine detail remote connection plugin.
| Python | apache-2.0 | salopensource/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal,salopensource/sal,sheagcraig/sal,sheagcraig/sal |
707f09d7d8f2c1e3ad37947a3084acb90faf84cf | IPython/extensions/tests/test_storemagic.py | IPython/extensions/tests/test_storemagic.py | import tempfile, os
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip.magic('store bar')
# Check stor... | import tempfile, os
import nose.tools as nt
ip = get_ipython()
ip.magic('load_ext storemagic')
def test_store_restore():
ip.user_ns['foo'] = 78
ip.magic('alias bar echo "hello"')
tmpd = tempfile.mkdtemp()
ip.magic('cd ' + tmpd)
ip.magic('store foo')
ip.magic('store bar')
# Check stor... | Store magic test. On MacOSX the temp dir in /var is symlinked into /private/var thus making this comparison fail. This is solved by using os.path.realpath to expand the tempdir into is's real directory. | Store magic test. On MacOSX the temp dir in /var is symlinked into /private/var thus making this comparison fail. This is solved by using os.path.realpath to expand the tempdir into is's real directory.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython |
617437824c875f368e8244bc6d9373217f15cb7d | website/project/utils.py | website/project/utils.py | from .views import node
# Alias the project serializer
serialize_node = node._view_project
| # -*- coding: utf-8 -*-
"""Various node-related utilities."""
from website.project.views import node
from website.project.views import file as file_views
# Alias the project serializer
serialize_node = node._view_project
# File rendering utils
get_cache_content = file_views.get_cache_content
get_cache_path = file_vi... | Add aliases for MFR-related utilites | Add aliases for MFR-related utilites
| Python | apache-2.0 | revanthkolli/osf.io,Johnetordoff/osf.io,chrisseto/osf.io,felliott/osf.io,barbour-em/osf.io,emetsger/osf.io,njantrania/osf.io,danielneis/osf.io,caseyrygt/osf.io,emetsger/osf.io,crcresearch/osf.io,danielneis/osf.io,caseyrygt/osf.io,zachjanicki/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,jmcarp/osf.io,leb2dg/osf.io,jinl... |
57ab42c16ddc8591153980b2f3bb8c4ba6090160 | tests/conftest.py | tests/conftest.py | """Module grouping session scoped PyTest fixtures."""
import pytest
from _pytest.monkeypatch import MonkeyPatch
import pydov
def pytest_runtest_setup():
pydov.hooks = []
@pytest.fixture(scope='module')
def monkeymodule():
mpatch = MonkeyPatch()
yield mpatch
mpatch.undo()
| """Module grouping session scoped PyTest fixtures."""
import pytest
from _pytest.monkeypatch import MonkeyPatch
import pydov
def pytest_runtest_setup():
pydov.hooks = []
def pytest_configure(config):
config.addinivalue_line("markers",
"online: mark test that requires internet ac... | Add pytest hook to register online marker | Add pytest hook to register online marker
| Python | mit | DOV-Vlaanderen/pydov |
b9f40dd83a603f7457588190bd7d968e30fa74a7 | frigg/settings/rest_framework.py | frigg/settings/rest_framework.py | REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '5000/day',
}
}
| REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
),
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '5000/day',
}
}
| Set drf to onyl render json response on all requests | Set drf to onyl render json response on all requests
| Python | mit | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq |
2f14d64e73dba23a62e82fe3f4f06e6539356117 | demo/datasetGeneration.py | demo/datasetGeneration.py | from demo7 import get_answer
import json
class TripleError(Exception):
"""
Raised when a triple contains connectors (e.g. AND, FIRST).
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
def string_of_triple(t,missing,separator):
if ... | from demo7 import get_answer
import json
class TripleError(Exception):
"""
Raised when a triple contains connectors (e.g. AND, FIRST).
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
def string_of_triple(t,missing,separator):
if ... | Revert "Do not display quesitons in script." | Revert "Do not display quesitons in script."
This reverts commit 5c7286c1dc6348f2212266871876376df15592c0.
| Python | agpl-3.0 | ProjetPP/PPP-QuestionParsing-Grammatical,ProjetPP/PPP-QuestionParsing-Grammatical |
0036095ed79c3ea6b14732555dbed9a987172366 | ue-crash-dummy.py | ue-crash-dummy.py | from flask import Flask
from flask_socketio import SocketIO
## Instanciate Flask (Static files and REST API)
app = Flask(__name__)
## Instanciate SocketIO (Websockets, used for events) on top of it
socketio = SocketIO(app)
@socketio.on('testEvent')
def test_event():
print "Got test event"
@socketio.on('testEve... | from flask import Flask
from flask_socketio import SocketIO
## Instanciate Flask (Static files and REST API)
app = Flask(__name__)
## Instanciate SocketIO (Websockets, used for events) on top of it
socketio = SocketIO(app)
@socketio.on('testEvent')
def test_event(_=None):
print "Got test event"
@socketio.on('t... | Add dummy parameter for UE4. | [Bugfix] Add dummy parameter for UE4.
Signed-off-by: Juri Berlanda <5bfdca9e82c53adb0603ce7083f4ba4f2da5cacf@hotmail.com>
| Python | mit | j-be/ue4-socketio-crash |
a4825083c9a18fe8665d750bfad00a9d6fa40944 | tartpy/eventloop.py | tartpy/eventloop.py | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import threading
import time
from .singleton import Singleton
class EventLoop(object, metaclas... | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(obj... | Use Python scheduler rather than the home-made one | Use Python scheduler rather than the home-made one | Python | mit | waltermoreira/tartpy |
3d5c68421b889abb4f56319b082aaff554ebaa0e | tests/test_parse.py | tests/test_parse.py | import json
import logging
import os
import unittest
import ptn
class ParseTest(unittest.TestCase):
def test_parser(self):
with open('files/input.json') as input_file:
torrents = json.load(input_file)
with open('files/output.json') as output_file:
results = json.load(out... | import json
import os
import unittest
import ptn
class ParseTest(unittest.TestCase):
def test_parser(self):
with open(os.path.join(
os.path.dirname(__file__),
'files/input.json'
)) as input_file:
torrents = json.load(input_file)
with o... | Fix minor syntax error in test | Fix minor syntax error in test
| Python | mit | divijbindlish/parse-torrent-name,nivertech/parse-torrent-name |
da51183e64875119377d3dd5ffe85c958c23fc16 | moksha/api/widgets/flot/flot.py | moksha/api/widgets/flot/flot.py | # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it... | # This file is part of Moksha.
#
# Moksha is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Moksha is distributed in the hope that it... | Make our LiveFlotWidget not pull in jQuery | Make our LiveFlotWidget not pull in jQuery
| Python | apache-2.0 | lmacken/moksha,ralphbean/moksha,pombredanne/moksha,ralphbean/moksha,ralphbean/moksha,mokshaproject/moksha,pombredanne/moksha,pombredanne/moksha,lmacken/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha,mokshaproject/moksha |
99be93029ecec0ed4c1e17e0fc2f199c2ad0f6c6 | go/apps/dialogue/dialogue_api.py | go/apps/dialogue/dialogue_api.py | """Go API action dispatcher for dialogue conversations."""
from go.api.go_api.action_dispatcher import ConversationActionDispatcher
class DialogueActionDispatcher(ConversationActionDispatcher):
def handle_get_poll(self, conv):
pass
def handle_save_poll(self, conv, poll):
pass
| """Go API action dispatcher for dialogue conversations."""
from go.api.go_api.action_dispatcher import ConversationActionDispatcher
class DialogueActionDispatcher(ConversationActionDispatcher):
def handle_get_poll(self, conv):
return {"poll": conv.config.get("poll")}
def handle_save_poll(self, conv,... | Implement poll saving and getting. | Implement poll saving and getting.
| Python | bsd-3-clause | praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go |
d831826ec23114a3f56b5f327205257c7ca4ac58 | gym/configuration.py | gym/configuration.py | import logging
import sys
import gym
logger = logging.getLogger(__name__)
root_logger = logging.getLogger()
requests_logger = logging.getLogger('requests')
# Set up the default handler
formatter = logging.Formatter('[%(asctime)s] %(message)s')
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(formatt... | import logging
import sys
import gym
logger = logging.getLogger(__name__)
root_logger = logging.getLogger()
requests_logger = logging.getLogger('requests')
# Set up the default handler
formatter = logging.Formatter('[%(asctime)s] %(message)s')
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(formatt... | Downgrade to just setting the gym logger | Downgrade to just setting the gym logger
| Python | mit | dianchen96/gym,Farama-Foundation/Gymnasium,Farama-Foundation/Gymnasium,dianchen96/gym |
0b80b573049b771f551b2fa47e570d849cd14ea4 | packages/syft/src/syft/core/node/common/node_manager/node_route_manager.py | packages/syft/src/syft/core/node/common/node_manager/node_route_manager.py | # third party
from sqlalchemy.engine import Engine
# relative
from ..node_table.node_route import NodeRoute
from .database_manager import DatabaseManager
class NodeRouteManager(DatabaseManager):
schema = NodeRoute
def __init__(self, database: Engine) -> None:
super().__init__(schema=NodeRouteManager... | # third party
from sqlalchemy.engine import Engine
# relative
from ..node_table.node_route import NodeRoute
from .database_manager import DatabaseManager
class NodeRouteManager(DatabaseManager):
schema = NodeRoute
def __init__(self, database: Engine) -> None:
super().__init__(schema=NodeRouteManager... | UPDATE update_route_for_node method to accept new parameters (vpn_endpoint/vpn_key) | UPDATE update_route_for_node method to accept new parameters (vpn_endpoint/vpn_key)
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft |
9bb0e3b082b509b5498d25df248d4c74be53bcc3 | oppia/tests/javascript_tests.py | oppia/tests/javascript_tests.py | # Copyright 2012 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 ... | # Copyright 2012 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 ... | Make failing Karma tests actually count as failures. | Make failing Karma tests actually count as failures.
| Python | apache-2.0 | sunu/oppia,directorlive/oppia,michaelWagner/oppia,jestapinski/oppia,kennho/oppia,mit0110/oppia,himanshu-dixit/oppia,zgchizi/oppia-uc,won0089/oppia,brianrodri/oppia,leandrotoledo/oppia,fernandopinhati/oppia,rackstar17/oppia,aldeka/oppia,Dev4X/oppia,amgowano/oppia,oulan/oppia,raju249/oppia,aldeka/oppia,dippatel1994/oppia... |
f9223d3e12881dd638a2815bb1019071d1857541 | laalaa/apps/advisers/geocoder.py | laalaa/apps/advisers/geocoder.py | import re
import postcodeinfo
import pc_fallback
class GeocoderError(Exception):
pass
class PostcodeNotFound(GeocoderError):
def __init__(self, postcode, *args, **kwargs):
super(PostcodeNotFound, self).__init__(*args, **kwargs)
self.postcode = postcode
def geocode(postcode):
try:
... | import re
import postcodeinfo
import pc_fallback
class GeocoderError(Exception):
pass
class PostcodeNotFound(GeocoderError):
def __init__(self, postcode, *args, **kwargs):
super(PostcodeNotFound, self).__init__(*args, **kwargs)
self.postcode = postcode
def geocode(postcode):
try:
... | Increase default timeout for postcodeinfo to 30s | Increase default timeout for postcodeinfo to 30s
It seems that the current default of 5 seconds is too low for most of
the "legal provider upload" use cases.
| Python | mit | ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api,ministryofjustice/laa-legal-adviser-api |
57e66ae6cd833b1b0da5b71e1c4b6e223c8ca062 | test/test_data.py | test/test_data.py | """Tests for coverage.data"""
import unittest
from coverage.data import CoverageData
class DataTest(unittest.TestCase):
def test_reading(self):
covdata = CoverageData()
covdata.read()
self.assertEqual(covdata.summary(), {})
| """Tests for coverage.data"""
from coverage.data import CoverageData
from coveragetest import CoverageTest
class DataTest(CoverageTest):
def test_reading(self):
covdata = CoverageData()
covdata.read()
self.assertEqual(covdata.summary(), {})
| Use our CoverageTest base class to get isolation (in a new directory) for the data tests. | Use our CoverageTest base class to get isolation (in a new directory) for the data tests.
| Python | apache-2.0 | 7WebPages/coveragepy,larsbutler/coveragepy,7WebPages/coveragepy,jayhetee/coveragepy,nedbat/coveragepy,7WebPages/coveragepy,blueyed/coveragepy,jayhetee/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,larsbutler/coveragepy,blueyed/coveragepy,larsbutler/coveragepy,7WebPages/coveragepy,hugovk/coveragepy,hugovk/coverage... |
dfdcbda02ad2fcc744e90d437051afe911e47c60 | gapipy/resources/booking/agent.py | gapipy/resources/booking/agent.py | from __future__ import unicode_literals
from ..base import Resource
from .agency import Agency
class Agent(Resource):
_resource_name = 'agents'
_is_listable = False
_as_is_fields = [
'id', 'href', 'role', 'first_name', 'last_name', 'email',
'phone_numbers', 'username', 'active',
]
... | from __future__ import unicode_literals
from ..base import BaseModel, Resource
from .agency import Agency
class AgentRole(BaseModel):
_as_is_fields = ['id', 'name']
class AgentPhoneNumber(BaseModel):
_as_is_fields = ['number', 'type']
class Agent(Resource):
_resource_name = 'agents'
_is_listable... | Update Agent to use BaseModel classes to... | Update Agent to use BaseModel classes to...
represent Agent.role & Agent.phone_numbers fields
This will enable attribute access semantics for these fields
i.e.
> agent = client.agent.get(1234)
> agent.role['id']
> agent.phone_numbers[0]['number']
> agent.role.id
> agent.phone_numbers[0].number
| Python | mit | gadventures/gapipy |
6b1ebf85ec2b76bee889936726c3caac45203675 | pubsubpull/tests/test_config.py | pubsubpull/tests/test_config.py | from slumber.connector.ua import get
from django.test import TestCase
from pubsubpull.models import *
class TestConfiguration(TestCase):
def test_slumber(self):
response, json = get('/slumber/')
self.assertEquals(response.status_code, 200, response)
| from slumber.connector.ua import get
from django.test import TestCase
from pubsubpull.models import *
class TestConfiguration(TestCase):
def test_slumber(self):
response, json = get('/slumber/')
self.assertEquals(response.status_code, 200, response)
self.assertTrue(json.has_key('apps'),... | Make sure pubsubpull is installed. | Make sure pubsubpull is installed.
| Python | mit | KayEss/django-pubsubpull,KayEss/django-pubsubpull,KayEss/django-pubsubpull |
9014dfde50d5f54cf79c544ce01e81266effa87d | game_info/tests/test_commands.py | game_info/tests/test_commands.py | from django.core.management import call_command
from django.test import TestCase
class ServerTest(TestCase):
def test_update_game_info(self):
call_command('update_game_info')
| from django.core.management import call_command
from django.test import TestCase
from game_info.models import Server
class ServerTest(TestCase):
def create_server(self, title="Test Server", host="example.org", port=27015):
return Server.objects.create(title=title, host=host, port=port)
def test_updat... | Fix testing on update_game_info management command | Fix testing on update_game_info management command
| Python | bsd-3-clause | Azelphur-Servers/django-game-info |
bee8527854577f2c663cd43719bbb2cd05cdbf1a | TwitterStatsLib/Output.py | TwitterStatsLib/Output.py | """ Module providing standard output classes """
from abc import ABCMeta, abstractmethod
from mako.template import Template
from mako.lookup import TemplateLookup
class Output(object):
""" Abstract class base for output classes """
__metaclass__ = ABCMeta
@abstractmethod
def render(self, d... | """ Module providing standard output classes """
import re
from abc import ABCMeta, abstractmethod
from mako.template import Template
from mako.lookup import TemplateLookup
class Output(object):
""" Abstract class base for output classes """
__metaclass__ = ABCMeta
@abstractmethod
def ren... | Use regex instead of replace for Mako template preprocess | Use regex instead of replace for Mako template preprocess
| Python | mit | pecet/pytosg,pecet/pytosg |
28cf62f316e2e726331f9b0773270db64c4869c8 | grammpy/IsMethodsRuleExtension.py | grammpy/IsMethodsRuleExtension.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .Rule import Rule
class IsMethodsRuleExtension(Rule):
@classmethod
def is_regular(cls):
raise NotImplementedError()
@classmethod
def is_contextfree(cls):
raise NotImpl... | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
"""
from .Rule import Rule
class IsMethodsRuleExtension(Rule):
@classmethod
def is_regular(cls):
raise NotImplementedError()
@classmethod
def is_contextfree(cls):
raise NotImpl... | Add Rule.validate class method that will raise exceptions | Add Rule.validate class method that will raise exceptions
| Python | mit | PatrikValkovic/grammpy |
e99c63af5c0143c95f9af10e3a79083235bb7da4 | lc0340_longest_substring_with_at_most_k_distinct_characters.py | lc0340_longest_substring_with_at_most_k_distinct_characters.py | """Leetcode 340. Longest Substring with At Most K Distinct Characters
Hard
URL: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
Given a string, find the length of the longest substring T that contains at most k
distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Ex... | """Leetcode 340. Longest Substring with At Most K Distinct Characters
Hard
URL: https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/
Given a string, find the length of the longest substring T that contains at most k
distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Ex... | Complete two pointers char count dict sol w/ time/space complexity | Complete two pointers char count dict sol w/ time/space complexity
| Python | bsd-2-clause | bowen0701/algorithms_data_structures |
a3425b010cb252db7dcb19ca6023f1e09999912e | leetcode/389-Find-the-Difference/FindtheDifference_Bit_and_Hash.py | leetcode/389-Find-the-Difference/FindtheDifference_Bit_and_Hash.py | class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
chrs = {}
res = 0
for w in t:
if w not in chrs:
chrs[w] = 1 << (ord(w) - 97)
res += chrs[w]
for w i... | class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
chrs = {}
res = 0
for w in t:
if w not in chrs:
chrs[w] = 1 << (ord(w) - 97)
res += chrs[w] # it can be ove... | Comment overflow problem on FindtheDiff_BitHash | Comment overflow problem on FindtheDiff_BitHash | Python | mit | Chasego/codi,Chasego/cod,cc13ny/algo,Chasego/codi,Chasego/codirit,cc13ny/Allin,Chasego/codi,cc13ny/Allin,Chasego/codi,cc13ny/Allin,Chasego/codi,cc13ny/Allin,Chasego/cod,Chasego/cod,Chasego/codirit,cc13ny/Allin,Chasego/codirit,Chasego/cod,cc13ny/algo,cc13ny/algo,cc13ny/algo,Chasego/cod,Chasego/codirit,Chasego/codirit,cc... |
b0fd7fc1866cd85e9d68d5716d8f5aeaff1218c1 | tests/__init__.py | tests/__init__.py | """Unit test suite for HXL proxy."""
import os
import re
import hxl
import unittest.mock
TEST_DATA_FILE = os.path.join(os.path.dirname(__file__), 'test-data.sql')
#
# Mock URL access for local testing
#
def mock_open_url(url, allow_local=False, timeout=None, verify=True):
"""
Open local files instead of URL... | """Unit test suite for HXL proxy."""
import os
import re
import hxl
import unittest.mock
TEST_DATA_FILE = os.path.join(os.path.dirname(__file__), 'test-data.sql')
#
# Mock URL access for local testing
#
def mock_open_url(url, allow_local=False, timeout=None, verify=True):
"""
Open local files instead of URL... | Update mock method to match changed return value for libhxl | Update mock method to match changed return value for libhxl
| Python | unlicense | HXLStandard/hxl-proxy,HXLStandard/hxl-proxy,HXLStandard/hxl-proxy,HXLStandard/hxl-proxy |
0b4562d15c1c8b544847e7988d26120556a3110d | tests/conftest.py | tests/conftest.py | import os
TEST_CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cosmoconfig_test.yaml')
# Check to make sure that the test config file is being used. If not, don't run the tests
if os.environ['COSMO_CONFIG'] != TEST_CONFIG:
raise TypeError('Tests should only be executed with the testing configur... | import os
import pytest
TEST_CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'cosmoconfig_test.yaml')
# Check to make sure that the test config file is being used. If not, don't run the tests
if os.environ['COSMO_CONFIG'] != TEST_CONFIG:
raise TypeError('Tests should only be executed with the te... | Add session-scope clean up that removes the test database | Add session-scope clean up that removes the test database
| Python | bsd-3-clause | justincely/cos_monitoring |
056f794012033fdb6c1eeecfd48dbf3aa76f036a | tests/runtests.py | tests/runtests.py | #!/usr/bin/env python
import os
import sys
from unittest import defaultTestLoader, TextTestRunner, TestSuite
TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n')
def make_suite(prefix='', extra=()):
tests = TESTS + extra
test_names = list(prefix + x for ... | #!/usr/bin/env python
import os
import sys
from unittest import defaultTestLoader, TextTestRunner, TestSuite
TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n')
def make_suite(prefix='', extra=()):
tests = TESTS + extra
test_names = list(prefix + x for ... | Add back in running of extra tests | Add back in running of extra tests
| Python | bsd-3-clause | Khan/wtforms |
07c7f18733bad651ef110b529422fd42bdcf27aa | src/encoded/views/__init__.py | src/encoded/views/__init__.py | from pyramid.httpexceptions import HTTPNotFound
from pyramid.view import view_config
from random import randint
from ..contentbase import (
Root,
location_root,
)
def includeme(config):
# Random processid so etags are invalidated after restart.
config.registry['encoded.processid'] = randint(0, 2 ** 32... | import os
from pyramid.httpexceptions import HTTPNotFound
from pyramid.view import view_config
from random import randint
from ..contentbase import (
Root,
location_root,
)
def includeme(config):
config.registry['encoded.processid'] = os.getppid()
config.add_route('schema', '/profiles/{item_type}.json... | Use parent process id, that of the apache process. | Use parent process id, that of the apache process.
| Python | mit | T2DREAM/t2dream-portal,kidaa/encoded,T2DREAM/t2dream-portal,ENCODE-DCC/encoded,4dn-dcic/fourfront,ENCODE-DCC/encoded,ClinGen/clincoded,philiptzou/clincoded,hms-dbmi/fourfront,kidaa/encoded,4dn-dcic/fourfront,ClinGen/clincoded,T2DREAM/t2dream-portal,kidaa/encoded,kidaa/encoded,ENCODE-DCC/snovault,T2DREAM/t2dream-portal,... |
0bfee1fff698a984130a99c7ccbff4a787a68eca | cla_backend/apps/status/tests/smoketests.py | cla_backend/apps/status/tests/smoketests.py | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
... | import unittest
from celery import Celery
from django.conf import settings
from django.db import connection
class SmokeTests(unittest.TestCase):
def setUp(self):
pass
def test_can_access_db(self):
"access the database"
cursor = connection.cursor()
cursor.execute('SELECT 1')
... | Use same settings in smoke test as in real use | Use same settings in smoke test as in real use
| Python | mit | ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend,ministryofjustice/cla_backend |
186d3c637760668d960c50c9f94fad7ff4769598 | molly/utils/management/commands/generate_cache_manifest.py | molly/utils/management/commands/generate_cache_manifest.py | import os
import os.path
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
cache_manifest_path = os.path.join(settings.STATIC_ROOT,
... | import os
import os.path
from django.core.management.base import NoArgsCommand
from django.conf import settings
class Command(NoArgsCommand):
can_import_settings = True
def handle_noargs(self, **options):
cache_manifest_path = os.path.join(settings.STATIC_ROOT,
... | Revert "Revert "Don't cache markers, admin files or uncompressed JS/CSS"" | Revert "Revert "Don't cache markers, admin files or uncompressed JS/CSS""
This reverts commit 6c488d267cd5919eb545855a522d5cd7ec7d0fec.
| Python | apache-2.0 | mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject |
223c268d58645fbecdddb24ff84587dc803bfc87 | braubuddy/tests/thermometer/test_auto.py | braubuddy/tests/thermometer/test_auto.py | """
Braubuddy Dummy thermometer unit tests.
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import auto
from braubuddy.thermometer import dummy
from braubuddy.thermometer import ds18b20_gpio
from braubuddy.thermometer import temper_usb
from braubuddy.thermometer import Device... | """
Braubuddy Auto thermometer unit tests.
"""
import unittest
from mock import patch, call, MagicMock
from braubuddy.thermometer import auto
from braubuddy.thermometer import dummy
from braubuddy.thermometer import ds18b20_gpio
from braubuddy.thermometer import temper_usb
class TestAuto(unittest.TestCase):
... | Fix docstring and remove unnecessary imports. | Fix docstring and remove unnecessary imports.
| Python | bsd-3-clause | amorphic/braubuddy,amorphic/braubuddy,amorphic/braubuddy |
53c751e86b6ca2dd5076e0a09e7c0e4663c1fcbc | edx_data_research/cli/commands.py | edx_data_research/cli/commands.py | """
In this module we define the interface between the cli input provided
by the user and the analytics required by the user
"""
from edx_data_research.reporting.basic import (user_info, ip_to_country,
course_completers)
from edx_data_research.reporting.edx_base import EdX... | """
In this module we define the interface between the cli input provided
by the user and the analytics required by the user
"""
from edx_data_research.reporting.basic import (user_info, ip_to_country,
course_completers)
from edx_data_research.reporting.edx_base import EdX... | Add function to call problem_ids report generation | Add function to call problem_ids report generation
| Python | mit | McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research |
fe715bb784326a661b14d01e02189074228e7c13 | securedrop/tests/test_manage.py | securedrop/tests/test_manage.py | # -*- coding: utf-8 -*-
import manage
import unittest
class TestManagePy(unittest.TestCase):
def test_parse_args(self):
# just test that the arg parser is stable
manage.get_args()
| # -*- coding: utf-8 -*-
import manage
import mock
from StringIO import StringIO
import sys
import unittest
import __builtin__
import utils
class TestManagePy(unittest.TestCase):
def test_parse_args(self):
# just test that the arg parser is stable
manage.get_args()
class TestManagementCommand(u... | Add unit test to check duplicate username error is handled in manage.py | Add unit test to check duplicate username error is handled in manage.py
| Python | agpl-3.0 | heartsucker/securedrop,conorsch/securedrop,ageis/securedrop,garrettr/securedrop,heartsucker/securedrop,conorsch/securedrop,conorsch/securedrop,ehartsuyker/securedrop,micahflee/securedrop,heartsucker/securedrop,micahflee/securedrop,ehartsuyker/securedrop,ehartsuyker/securedrop,ageis/securedrop,ehartsuyker/securedrop,gar... |
c0cecdc7e754090f25f48637de88d2d07a3ef58f | ctypeslib/test/test_dynmodule.py | ctypeslib/test/test_dynmodule.py | # Basic test of dynamic code generation
import unittest
import os, glob
import stdio
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
def tearDown(self):
for fnm in glob.glob(stdio._gen_basename + ".*"):
try:
os.remove(fnm)
except IOError:
... | # Basic test of dynamic code generation
import unittest
import os, glob
import stdio
from ctypes import POINTER, c_int
class DynModTest(unittest.TestCase):
def test_fopen(self):
self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE))
self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING... | Remove now useless TearDown method. | Remove now useless TearDown method. | Python | mit | sugarmanz/ctypeslib |
dbbbb763db09fdf777558b781a29d4b8a71b3e62 | src/DeepLearn/venv/Lab/Array.py | src/DeepLearn/venv/Lab/Array.py | import numpy as np
arr1 = np.array([[1,2],[3,4]])
arr2 = np.array([[5,6],[7,8]])
arr3 = np.array([[1,2],[3,4],[5,6]])
arr4 = np.array([7,8])
# 列出矩陣的維度
# print(arr1.shape)
# print(arr1.shape[0])
# 矩陣乘積
# print(np.dot(arr1,arr2))
print(np.dot(arr3,arr4))
# print(arr1*arr2)
| import numpy as np
arr1 = np.array([[1,2],[3,4]])
arr2 = np.array([[5,6],[7,8]])
arr3 = np.array([[1,2],[3,4],[5,6]])
arr4 = np.array([7,8])
# 列出矩陣的維度
# print(arr1.shape)
# print(arr1.shape[0])
# 矩陣乘積
# print(np.dot(arr1,arr2))
print(np.dot(arr3,arr4))
print(1*7+2*7)
# print(arr1*arr2)
| Create 3 layer nt sample | Create 3 layer nt sample
| Python | mit | KarateJB/Python.Practice,KarateJB/Python.Practice,KarateJB/Python.Practice,KarateJB/Python.Practice |
9756366d7bca75c0ea89ce1fface6a7d224f54f7 | web/api/__init__.py | web/api/__init__.py | from flask import Blueprint
from . import v0
bp = Blueprint('api', __name__)
v0.api.init_app(bp)
def errorpage(e):
code = getattr(e, 'code', 500)
if code == 404:
return jsonify(msg=str(e))
return jsonify(msg="error", code=code)
| from flask import Blueprint
from . import v0
bp = Blueprint('api', __name__)
v0.api.init_app(bp)
def errorpage(e):
return v0.api.handle_error(e)
| Improve error handling of sipa API | Improve error handling of sipa API
| Python | apache-2.0 | agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.