commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
6d8e3d8c1edba34527a4919a1718f3ace022b52b | support multiple libpcap versions | est/pypcap,itxx00/pypcap,pombreda/pypcap,afghanistanyn/pypcap,est/pypcap,fasguard/fasguard-pcap,afghanistanyn/pypcap,pombreda/pypcap,FunctionAnalysis/pypcap,FunctionAnalysis/pypcap,fasguard/fasguard-pcap,itxx00/pypcap | test.py | test.py | #!/usr/bin/env python
import glob, sys, unittest
sys.path.insert(0, glob.glob('build/lib.*')[0])
import pcap
class PcapTestCase(unittest.TestCase):
def test_pcap_iter(self):
l = [ (x[0], len(x[1])) for x in pcap.pcap('test.pcap') ]
assert l == [(1092256609.9265549, 62), (1092256609.9265759, 54), (... | #!/usr/bin/env python
import glob, sys, unittest
sys.path.insert(0, glob.glob('build/lib.*')[0])
import pcap
class PcapTestCase(unittest.TestCase):
def test_pcap_iter(self):
l = [ (x[0], len(x[1])) for x in pcap.pcap('test.pcap') ]
assert l == [(1092256609.9265549, 62), (1092256609.9265759, 54), (... | bsd-3-clause | Python |
3f1ea92145cc3b4c55b89d73ff9b4fc264f2ac09 | remove unused imports | Kopachris/py-id003 | test.py | test.py | #!/usr/bin/env python3
import id003
import serial
import time
def main():
timeout = 0.2
baud = 9600
port = 'COM11' # JCM UAC device (USB serial adapter)
bv = id003BillVal(port, baud, serial.EIGHTBITS, serial.PARITY_EVEN, timeout=timeout)
bv.power_on()
if bv.init_status == id00... | #!/usr/bin/env python3
from id003 import BillVal
import id003
import serial.tools.list_ports
import serial
import time
def main():
timeout = 0.2
baud = 9600
port = 'COM11' # JCM UAC device (USB serial adapter)
bv = BillVal(port, baud, serial.EIGHTBITS, serial.PARITY_EVEN, timeout=timeout)
... | bsd-3-clause | Python |
5b625cc4cbad7fb98102c4bc8cda3bc62bf28524 | add missing copyright | nebulans/testfixtures,Simplistix/testfixtures | testfixtures/components.py | testfixtures/components.py | # Copyright (c) 2010-2011 Simplistix Ltd
# See license.txt for license details.
import atexit
import warnings
from zope.component import getSiteManager
from zope.component.registry import Components
class TestComponents:
"""
A helper for providing a sterile registry when testing
with :mod:`zope.component... | import atexit
import warnings
from zope.component import getSiteManager
from zope.component.registry import Components
class TestComponents:
"""
A helper for providing a sterile registry when testing
with :mod:`zope.component`.
Instantiation will install an empty registry that will be returned
by... | mit | Python |
7e2835f76474f6153d8972a983c5d45f9c4f11ee | Fix badly named test class | ulikoehler/UliEngineering | tests/Physics/TestLight.py | tests/Physics/TestLight.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal
from UliEngineering.Physics.Light import *
from UliEngineering.EngineerIO import auto_format
import unittest
class TestLight(unittest.TestCase):
def test_lumen_to_candela_by_apex_angle(self):
v = lumen_to_candela_b... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from numpy.testing import assert_approx_equal
from UliEngineering.Physics.Light import *
from UliEngineering.EngineerIO import auto_format
import unittest
class TestJohnsonNyquistNoise(unittest.TestCase):
def test_lumen_to_candela_by_apex_angle(self):
v = lume... | apache-2.0 | Python |
4ac019016a32bf1a2356490727d39c4f23156e89 | fix missing page ordering | lucmilland/mezzanine-onepage,lucmilland/mezzanine-onepage | onepage/templatetags/onepage_tags.py | onepage/templatetags/onepage_tags.py | from django.template import Context, RequestContext
from django.template.loader import get_template
from mezzanine import template
from mezzanine.forms.forms import FormForForm
from mezzanine.utils.urls import slugify
register = template.Library()
@register.inclusion_tag('includes/onepage.html', takes_context=True)... | from django.template import Context, RequestContext
from django.template.loader import get_template
from mezzanine import template
from mezzanine.forms.forms import FormForForm
from mezzanine.utils.urls import slugify
register = template.Library()
@register.inclusion_tag('includes/onepage.html', takes_context=True)... | bsd-2-clause | Python |
3c83e77c5a5a80a27eeb65ff2f32e71e6a9ccf74 | bump to 0.11.dev | khchine5/django-shop,nimbis/django-shop,nimbis/django-shop,khchine5/django-shop,divio/django-shop,nimbis/django-shop,divio/django-shop,awesto/django-shop,khchine5/django-shop,awesto/django-shop,awesto/django-shop,divio/django-shop,nimbis/django-shop,khchine5/django-shop | shop/__init__.py | shop/__init__.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
See PEP 386 (http://www.python.org/dev/peps/pep-0386/)
Release logic:
1. Remove ".devX" from __version__ (below)
2. git add shop/__init__.py
3. git commit -m 'Bump to <version>'
4. git tag <version>
5. git push
6. assure that all tests pass on h... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
See PEP 386 (http://www.python.org/dev/peps/pep-0386/)
Release logic:
1. Remove ".devX" from __version__ (below)
2. git add shop/__init__.py
3. git commit -m 'Bump to <version>'
4. git tag <version>
5. git push
6. assure that all tests pass on h... | bsd-3-clause | Python |
083aacdeecffcee6aa983695859bf370e938173b | Refactor file.__init__.py | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten | nn/file/__init__.py | nn/file/__init__.py | import functools
import tensorflow as tf
from . import cnn_dailymail_rc
from .. import collections
from ..flags import FLAGS
from ..util import func_scope, dtypes
from .util import batch_queue, add_queue_runner
READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files }
@func_scope()
def read_files(file_pattern... | import functools
import tensorflow as tf
from . import cnn_dailymail_rc
from .. import collections
from ..flags import FLAGS
from ..util import func_scope
READERS = { "cnn_dailymail_rc": cnn_dailymail_rc.read_files }
@func_scope()
def read_files(file_pattern, file_format):
return monitored_batch_queue(
*R... | unlicense | Python |
ca521c7687530a631a209a45b27ed18bd064f360 | Reduce likelihood of client caching | RNAer/qiita,biocore/qiita,biocore/qiita,antgonza/qiita,ElDeveloper/qiita,ElDeveloper/qiita,biocore/qiita,josenavas/QiiTa,squirrelo/qiita,antgonza/qiita,biocore/qiita,squirrelo/qiita,josenavas/QiiTa,adamrp/qiita,squirrelo/qiita,ElDeveloper/qiita,wasade/qiita,squirrelo/qiita,antgonza/qiita,ElDeveloper/qiita,josenavas/Qii... | qiita_pet/handlers/download.py | qiita_pet/handlers/download.py | from tornado.web import authenticated
from os.path import basename
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@... | from tornado.web import authenticated
from os.path import basename
from .base_handlers import BaseHandler
from qiita_pet.exceptions import QiitaPetAuthorizationError
from qiita_db.util import filepath_id_to_rel_path
from qiita_db.meta_util import get_accessible_filepath_ids
class DownloadHandler(BaseHandler):
@... | bsd-3-clause | Python |
31689330c13c5895ece82fa37f497a8efe70f0bc | add allure attachments to login page | skostya64/Selenium_tasks | pages/admin_panel_login_page.py | pages/admin_panel_login_page.py | from allure.constants import AttachmentType
from selenium.webdriver.support.wait import WebDriverWait
import allure
class AdminPanelLoginPage:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def open(self):
self.driver.get("http://localhost/lite... | from selenium.webdriver.support.wait import WebDriverWait
class AdminPanelLoginPage:
def __init__(self, driver):
self.driver = driver
self.wait = WebDriverWait(driver, 10)
def open(self):
self.driver.get("http://localhost/litecart/admin")
return self
def is_on_this_page(... | apache-2.0 | Python |
9299060a2cf5ea3da74fefae57426eee7d5244c7 | Update Message.py | corpnewt/CorpBot.py,corpnewt/CorpBot.py | Cogs/Message.py | Cogs/Message.py | import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000, maxPage = None):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
re... | import asyncio
import discord
import textwrap
from discord.ext import commands
async def say(bot, msg, target, requestor, maxMessage : int = 5, characters : int = 2000, maxPage = None):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
re... | mit | Python |
98d9e7070eefebc096be2fe2de94b1256eee6d3c | fix for unicode | DesertBot/DesertBot,Heufneutje/PyMoronBot,MatthewCox/PyMoronBot | Commands/LRR.py | Commands/LRR.py | from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from CommandInterface import CommandInterface
import Data.LRRChecker as DataStore
import WebUtils
import re, datetime
class Command(CommandInterface):
triggers = ['lrr', 'llr']
def help(self, message):
return "lrr (<... | from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from CommandInterface import CommandInterface
import Data.LRRChecker as DataStore
import WebUtils
import re, datetime
class Command(CommandInterface):
triggers = ['lrr', 'llr']
def help(self, message):
return "lrr (<... | mit | Python |
3db9f4dd5a6ee6f165b6fb76e72acf11ef014c9a | Add VERSION_TUPLE and VERSION to __init__.py | BuzzFeedNews/bikeshares | bikeshares/__init__.py | bikeshares/__init__.py | import program
import programs
VERSION_TUPLE = (0, 0, 0)
VERSION = ".".join(map(str, VERSION_TUPLE))
| import program
import programs
| mit | Python |
0bc1289febc70f1c66a6a759020f3dc8c8bf20e4 | Repair outdated methods | calston/xenzen,calston/xenzen,calston/xenzen,calston/xenzen | skeleton/urls.py | skeleton/urls.py | from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Index
url(r'^$', 'xenserver.views.index', name='home'),
url(r'^favicon\.i... | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Index
url(r'^$', 'xenserver.views.index', name='home'),
url(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to... | mit | Python |
3e596808a66ab2c23ce14fb6780c0b8c7440491c | clean up sample client script | eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog | 2017/async-socket-server/simple-client.py | 2017/async-socket-server/simple-client.py | import argparse
import logging
import socket
import sys
import threading
import time
class ReadThread(threading.Thread):
def __init__(self, name, sockobj):
super().__init__()
self.sockobj = sockobj
self.name = name
self.bufsize = 8 * 1024
def run(self):
fullbuf = b''
... | import argparse
import logging
import socket
import sys
import threading
import time
class ReadThread(threading.Thread):
def __init__(self, name, sockobj):
super().__init__()
self.sockobj = sockobj
self.name = name
self.bufsize = 8 * 1024
def run(self):
fullbuf = b''
... | unlicense | Python |
04ad128651a123fe4378327624d97a17d747422e | Fix CanICA test to work with old canica | abenicho/isvr | nisl/decomposition/tests/test_canica.py | nisl/decomposition/tests/test_canica.py | """Test CanICA"""
import nibabel
import numpy as np
from numpy.testing import assert_array_equal
from nisl.decomposition.old_canica import CanICA
def test_canica_square_img():
shape = (20, 20)
rng = np.random.RandomState(0)
# Create four images with "activated regions"
component1 = np.zeros(shape)
... | """Test CanICA"""
import nibabel
import numpy as np
from numpy.testing import assert_array_equal
from nisl.decomposition import CanICA
def test_canica_square_img():
shape = (20, 20, 1)
rng = np.random.RandomState(0)
mask_img = nibabel.Nifti1Image(np.ones(shape, dtype=np.int8), np.eye(4))
# Create fo... | bsd-3-clause | Python |
ae2fc5086137a9cb7c6b89fb99e5da706a876d61 | add patches for newer xerces-c, gcc (#24021) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/xqilla/package.py | var/spack/repos/builtin/packages/xqilla/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Xqilla(AutotoolsPackage, SourceforgePackage):
"""XQilla is an XQuery and XPath 2 library a... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Xqilla(AutotoolsPackage, SourceforgePackage):
"""XQilla is an XQuery and XPath 2 library a... | lgpl-2.1 | Python |
9f15e18c800f0bfdc1d2c0d1aced54ead4f27c84 | Fix the docstrings in util.py to read "API" instead of "main loop" | mitya57/secretstorage | secretstorage/util.py | secretstorage/util.py | # SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2013
# License: BSD
"""This module provides some utility functions, but these shouldn't
normally be used by external applications."""
import dbus
from secretstorage.defines import SECRETS, SS_PATH, SS_PREF... | # SecretStorage module for Python
# Access passwords using the SecretService DBus API
# Author: Dmitry Shachnev, 2013
# License: BSD
"""This module provides some utility functions, but these shouldn't
normally be used by external applications."""
import dbus
from secretstorage.defines import SECRETS, SS_PATH, SS_PREF... | bsd-3-clause | Python |
8ed2f778be32f0b285f0f30fefc57f44dc54cac8 | Make it die | bbqsrc/skog-python | skog/__main__.py | skog/__main__.py | # Copyright (c) 2016 Brendan Molloy <brendan+freebsd@bbqsrc.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice,... | # Copyright (c) 2016 Brendan Molloy <brendan+freebsd@bbqsrc.net>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice,... | bsd-2-clause | Python |
047f06ec082ac7358805d937beddccfb2a8b52be | Remove __repr__ from orm - better to use as_dict for debugging | lpenz/slickbird,lpenz/slickbird,lpenz/slickbird | slickbird/orm.py | slickbird/orm.py | '''ORM'''
import sqlalchemy as sqla
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
Base = declarative_base()
class AsDict(object):
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class Collection(Base,... | '''ORM'''
import sqlalchemy as sqla
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, backref
Base = declarative_base()
class AsDict(object):
def as_dict(self):
return {c.name: getattr(self, c.name) for c in self.__table__.columns}
class Collection(Base,... | apache-2.0 | Python |
18404d84a3ccb32dad86c419063582fdae48e8e2 | Change twitter presenter to take up less space. | chromakode/karmabot | src/facets/twitter.py | src/facets/twitter.py | import urllib
try:
import json
except ImportError:
import simplejson as json
import thing
import command
from utils import Cache
@thing.facet_classes.register
class TwitterFacet(thing.ThingFacet):
name = "twitter"
commands = command.thing.add_child(command.FacetCommandSet(name))
def __in... | import urllib
try:
import json
except ImportError:
import simplejson as json
import thing
import command
from utils import Cache
@thing.facet_classes.register
class TwitterFacet(thing.ThingFacet):
name = "twitter"
commands = command.thing.add_child(command.FacetCommandSet(name))
def __in... | bsd-3-clause | Python |
2983701c75a68eff490f309d44e4ad9eb8af4a1b | remove .pdb from symbol file names (#19483) | gerhardberger/electron,gerhardberger/electron,bpasero/electron,seanchas116/electron,gerhardberger/electron,bpasero/electron,electron/electron,bpasero/electron,bpasero/electron,bpasero/electron,electron/electron,gerhardberger/electron,seanchas116/electron,electron/electron,electron/electron,gerhardberger/electron,gerhar... | build/dump_syms.py | build/dump_syms.py | from __future__ import print_function
import collections
import os
import subprocess
import sys
import errno
# The BINARY_INFO tuple describes a binary as dump_syms identifies it.
BINARY_INFO = collections.namedtuple('BINARY_INFO',
['platform', 'arch', 'hash', 'name'])
def get_mo... | from __future__ import print_function
import collections
import os
import subprocess
import sys
import errno
# The BINARY_INFO tuple describes a binary as dump_syms identifies it.
BINARY_INFO = collections.namedtuple('BINARY_INFO',
['platform', 'arch', 'hash', 'name'])
def get_mo... | mit | Python |
58653ac9f4ccb51ce3845d2fb0a5ebd3b6d04091 | Remove organization private problems from sitemap | DMOJ/site,DMOJ/site,DMOJ/site,DMOJ/site | judge/sitemap.py | judge/sitemap.py | from django.contrib.auth.models import User
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from django.utils import timezone
from judge.models import Problem, Organization, Contest, BlogPost, Solution
class ProblemSitemap(Sitemap):
changefreq = 'daily'
priority = 0.8
def ite... | from django.contrib.auth.models import User
from django.contrib.sitemaps import Sitemap
from django.urls import reverse
from django.utils import timezone
from judge.models import Problem, Organization, Contest, BlogPost, Solution
class ProblemSitemap(Sitemap):
changefreq = 'daily'
priority = 0.8
def ite... | agpl-3.0 | Python |
e2c9d39dd30a60c5c54521d7d11773430cae1bd1 | Add manual experiment that replaces a RGB image with grayscale | pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf | tests/test_image_access.py | tests/test_image_access.py | import pytest
import imghdr
from io import BytesIO
from PIL import Image
import zlib
from pikepdf import Pdf, Object
def test_jpeg(resources, outdir):
pdf = Pdf.open(resources / 'congress.pdf')
# If you are looking at this as example code, Im0 is not necessarily the
# name of any image.
pdfimage = pd... | import pytest
import imghdr
from io import BytesIO
from PIL import Image
from pikepdf import _qpdf as qpdf
def test_jpeg(resources, outdir):
pdf = qpdf.Pdf.open(resources / 'congress.pdf')
# If you are looking at this as example code, Im0 is not necessarily the
# name of any image.
pdfimage = pdf.pag... | mpl-2.0 | Python |
505e8c7af30caf0d0051932c357826719612c837 | Document Pente controls | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai | pentai/gui/pente_help_screen.py | pentai/gui/pente_help_screen.py | import help_screen as hs_m
import pentai.base.logger as log
class PenteHelpScreen(hs_m.HelpScreen):
def __init__(self, *args, **kwargs):
self.heading = "Pente Game Screen Help"
super(PenteHelpScreen, self).__init__(*args, **kwargs)
def set_text(self):
sc = self.ids.scrollable_id
... | import help_screen as hs_m
import pentai.base.logger as log
class PenteHelpScreen(hs_m.HelpScreen):
def __init__(self, *args, **kwargs):
self.heading = "Pente Game Screen Help"
super(PenteHelpScreen, self).__init__(*args, **kwargs)
def set_text(self):
sc = self.ids.scrollable_id
... | mit | Python |
f6d019551cd5ae263f12cbe0ae402bb27b7df308 | Remove test saving used during debug | solidarium/correios,osantana/correios,olist/correios | tests/test_pdf_renderer.py | tests/test_pdf_renderer.py | # Copyright 2016 Osvaldo Santana Neto
#
# 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 ... | # Copyright 2016 Osvaldo Santana Neto
#
# 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 ... | apache-2.0 | Python |
b2d5587fa70d66111c65992ef01f3d659db97817 | remove test resource. Create test resources in tests. | pavlov99/jsonapi,pavlov99/jsonapi | tests/testapp/resources.py | tests/testapp/resources.py | from jsonapi.resource import Resource
from jsonapi.api import API
api = API()
@api.register
class AuthorResource(Resource):
class Meta:
model = 'testapp.Author'
@api.register
class PostWithPictureResource(Resource):
class Meta:
model = 'testapp.PostWithPicture'
fieldnames_include = ... | from jsonapi.resource import Resource
from jsonapi.api import API
api = API()
@api.register
class AuthorResource(Resource):
class Meta:
model = 'testapp.Author'
@api.register
class PostWithPictureResource(Resource):
class Meta:
model = 'testapp.PostWithPicture'
fieldnames_include = ... | mit | Python |
252cc726d01cb3c1765641daba1a5d93299dfa32 | Fix the broken demo. | ioeric/tensorboard,ioeric/tensorboard,ioeric/tensorboard,ioeric/tensorboard,ioeric/tensorboard,ioeric/tensorboard | tensorboard/plugins/profile/profile_demo_data.py | tensorboard/plugins/profile/profile_demo_data.py | # Copyright 2017 The TensorFlow Authors. 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 applica... | # Copyright 2017 The TensorFlow Authors. 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 applica... | apache-2.0 | Python |
f11c6b3137ef2d7fe40b1f030647ea83da50217b | update version to 0.67 | arcturusannamalai/open-tamil,Ezhil-Language-Foundation/open-tamil,Ezhil-Language-Foundation/open-tamil,arcturusannamalai/open-tamil,arcturusannamalai/open-tamil,Ezhil-Language-Foundation/open-tamil,Ezhil-Language-Foundation/open-tamil,Ezhil-Language-Foundation/open-tamil,arcturusannamalai/open-tamil,Ezhil-Language-Foun... | tests/ImportTester.py | tests/ImportTester.py | # -*- coding: utf-8 -*-
# (C) 2015-2017 Muthiah Annamalai
#
# This file is part of 'open-tamil' package tests
#
# setup the paths
from opentamiltests import *
class ImportTester(unittest.TestCase):
def test_import_tester(self):
import tamil; import ngram; import transliterate
def test_import_n... | # -*- coding: utf-8 -*-
# (C) 2015-2017 Muthiah Annamalai
#
# This file is part of 'open-tamil' package tests
#
# setup the paths
from opentamiltests import *
class ImportTester(unittest.TestCase):
def test_import_tester(self):
import tamil; import ngram; import transliterate
def test_import_n... | mit | Python |
1b19ef1ce2994569d00244c395cbf1e57006328d | Use a requests.Session to set defaults. | pagarme/pagarme-python | pagarme/resources/handler_request.py | pagarme/resources/handler_request.py | import requests
from pagarme import sdk
TEMPORARY_COMPANY = 'https://api.pagar.me/1/companies/temporary'
KEYS = {}
def headers():
_headers = {
'User-Agent': 'pagarme-python/{}'.format(sdk.VERSION),
'X-PagarMe-User-Agent': 'pagarme-python/{}'.format(sdk.VERSION)
}
return _headers
sessio... | import requests
from pagarme import sdk
TEMPORARY_COMPANY = 'https://api.pagar.me/1/companies/temporary'
KEYS = {}
def validate_response(pagarme_response):
if pagarme_response.status_code == 200:
return pagarme_response.json()
else:
return error(pagarme_response.json())
def create_temporar... | mit | Python |
f162b2c46bbb22d174523523e33a8f5d45571fd6 | backup factory | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | nodeconductor/backup/tests/factories.py | nodeconductor/backup/tests/factories.py | import factory
from nodeconductor.backup import models
from nodeconductor.cloud.tests.factories import FlavorFactory
class BackupScheduleFactory(factory.DjangoModelFactory):
class Meta(object):
model = models.BackupSchedule
name = factory.Sequence(lambda n: 'BackupSchedule#%s' % n)
backup_source... | import factory
from nodeconductor.backup import models
from nodeconductor.cloud.tests.factories import FlavorFactory
class BackupScheduleFactory(factory.DjangoModelFactory):
class Meta(object):
model = models.BackupSchedule
name = factory.Sequence(lambda n: 'BackupSchedule#%s' % n)
backup_source... | mit | Python |
a979f602df91e1fcecd0388d019a9c1d419e3edd | Add integration test forr optimal config | wq2012/SpectralCluster,wq2012/SpectralCluster | tests/configs_test.py | tests/configs_test.py | import unittest
import numpy as np
from spectralcluster import configs
from spectralcluster import constraint
from spectralcluster import utils
class Icassp2018Test(unittest.TestCase):
"""Tests for ICASSP 2018 configs."""
def test_1000by6_matrix(self):
matrix = np.array([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]] * 40... | import unittest
import numpy as np
from spectralcluster import configs
from spectralcluster import utils
class Icassp2018Test(unittest.TestCase):
"""Tests for ICASSP 2018 configs."""
def test_1000by6_matrix(self):
matrix = np.array([[1.0, 0.0, 0.0, 0.0, 0.0, 0.0]] * 400 +
[[0.0, 1.0, 0.... | apache-2.0 | Python |
64b49d75d36f67345f3607e7f1327a21272b5f03 | Implement cost tracking add-on base structure | opennode/nodeconductor,opennode/nodeconductor,opennode/nodeconductor | nodeconductor/cost_tracking/__init__.py | nodeconductor/cost_tracking/__init__.py | """
Cost tracking - add-on for NC plugins.
Add-on adds next functional to plugin:
- calculate and store price estimate for each resource, service, project, customer.
- register resource used items (ex: CPU, storage for VMs) prices and show their prices for resource cost calculation.
- get resource used items for ... | default_app_config = 'nodeconductor.cost_tracking.apps.CostTrackingConfig'
class PriceItemTypes(object):
FLAVOR = 'flavor'
STORAGE = 'storage'
LICENSE_APPLICATION = 'license-application'
LICENSE_OS = 'license-os'
SUPPORT = 'support'
NETWORK = 'network'
USAGE = 'usage'
USERS = 'users'
... | mit | Python |
881ec408b3555c7a7d80aeafaebedca332645e61 | Add utility function to L{sparked.stage}: positionInBox() | arjan/sparked,arjan/sparked,arjan/sparked | sparked/stage.py | sparked/stage.py | # Copyright (c) 2010 Arjan Scherpenisse
# See LICENSE for details.
"""
A grapihical window implemented using the
U{clutter<http://www.clutter-project.org/>} library, for interactive
displays.
F11 toggles fullscreen.
"""
import gtk
import clutter
from sparked import events
class Stage (clutter.Stage):
keys = ... | # Copyright (c) 2010 Arjan Scherpenisse
# See LICENSE for details.
"""
A grapihical window implemented using the
U{clutter<http://www.clutter-project.org/>} library, for interactive
displays.
F11 toggles fullscreen.
"""
import gtk
import clutter
from sparked import events
class Stage (clutter.Stage):
keys = ... | mit | Python |
9784595b56af5b6d6df6db037d938ea744af00ab | fix variable typo in tests | IanDCarroll/xox | tests/display_test.py | tests/display_test.py | import nose.tools
from source.display import *
def test_display_start_of_game():
display = Display()
test = display.show(display.start)
assert test == "Welcome"
def test_display_game_over_draw():
pass
def test_display_game_over_computer_wins():
pass
def test_display_game_over_human_wins():
p... | import nose.tools
from source.display import *
def test_display_start_of_game():
pass
def test_display_game_over_draw():
pass
def test_display_game_over_computer_wins():
pass
def test_display_game_over_human_wins():
pass
def test_display_current_board():
pass
def test_display_computers_last_mo... | mit | Python |
1a648d493ae14428fe724fc3bc302cd163d4f3ee | Fix constant.py | utgw/marisa-chan | constant.py | constant.py | from config import *
import tweepy
# Slack
slackURL = "https://slack.com/api/"
params = {'token': SLACK_TOKEN, 'channel': CHANNEL, 'text': '', 'username': USERNAME, 'icon_emoji': ICON_EMOJI}
# Twitter
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
ap... | from config import *
# Slack
slackURL = "https://slack.com/api/"
params = {'token': SLACK_TOKEN, 'channel': CHANNEL, 'text': '', 'username': USERNAME, 'icon_emoji': ICON_EMOJI}
# Twitter
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API... | mit | Python |
b01e31f4ff9ed6e40724fc7eff8c951c7b42cd1c | Remove program exit during subset import | pmoris/ebola-go,pmoris/ebola-go | go-enrichment-tool/genelist_importer.py | go-enrichment-tool/genelist_importer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
@author: Pieter Moris
'''
import os
def importBackground(path):
"""
Imports the background set of genes (uniprot AC).
Parameters
----------
path : str
The path to the file.
Returns
-------
set of str
A set of backgro... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
@author: Pieter Moris
'''
import os
def importBackground(path):
"""
Imports the background set of genes (uniprot AC).
Parameters
----------
path : str
The path to the file.
Returns
-------
set of str
A set of backgro... | mit | Python |
1e59fca57bbb50a96849092b096379d46e3e0071 | Refactor track_meta | Kaggle/learntools,Kaggle/learntools | notebooks/computer_vision/track_meta.py | notebooks/computer_vision/track_meta.py | track = dict(
author_username='ryanholbrook',
course_name='Computer Vision',
course_url='https://www.kaggle.com/ryanholbrook/computer-vision',
)
TOPICS = [
'The Convolutional Classifier',
'Convnet Architecture',
'Filter, Detect, Condense',
'Convolution and Pooling',
'Filters and Feature... | # See also examples/example_track/track_meta.py for a longer, commented example
track = dict(
author_username='ryanholbrook',
course_name='Computer Vision',
course_url='https://www.kaggle.com/ryanholbrook/computer-vision',
)
TOPICS = [
('The Convolutional Classifier', 1),
('Convnet Architecture', 2... | apache-2.0 | Python |
76e52fd32ce1616f92a1c3a3aab53bb3b7b9bbbf | Remove unused function | jakelever/kindred,jakelever/kindred | kindred/utils.py | kindred/utils.py |
import os
import zipfile
import hashlib
import requests
import logging
import traceback
def _calcSHA256(filename):
return hashlib.sha256(open(filename, 'rb').read()).hexdigest()
def _findDir(name, path):
if os.path.isdir(path):
for root, dirs, files in os.walk(path):
if name in dirs:
return os.path.abspat... |
import os
import zipfile
import hashlib
import requests
import logging
import traceback
def _calcSHA256(filename):
return hashlib.sha256(open(filename, 'rb').read()).hexdigest()
def _isDirEmpty(path):
files = os.listdir(path)
return files == []
def _findDir(name, path):
if os.path.isdir(path):
for root, dirs,... | mit | Python |
c8da962f22029d9ae84bedd884973fa2dbefa2c0 | Update Layer2.create_vault to return a Vault object | ddzialak/boto,SaranyaKarthikeyan/boto,revmischa/boto,TiVoMaker/boto,bleib1dj/boto,s0enke/boto,appneta/boto,khagler/boto,tpodowd/boto,lochiiconnectivity/boto,acourtney2015/boto,Asana/boto,weebygames/boto,Pretio/boto,disruptek/boto,dablak/boto,campenberger/boto,stevenbrichards/boto,podhmo/boto,Timus1712/boto,cyclecomputi... | boto/glacier/layer2.py | boto/glacier/layer2.py | # -*- coding: utf-8 -*-
# Copyright (c) 2012 Thomas Parslow http://almostobsolete.net/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation th... | # -*- coding: utf-8 -*-
# Copyright (c) 2012 Thomas Parslow http://almostobsolete.net/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation th... | mit | Python |
8eee2fa3b81cb28213807e5302667965df4eebc2 | Update 14UI.py | WeirdCoder/LilyPadOS,WeirdCoder/LilyPadOS,WeirdCoder/LilyPadOS,WeirdCoder/LilyPadOS | 14UI/14UI.py | 14UI/14UI.py | import lcm
import time
from lilylcm import L06Depth
from lilylcm import L07Humidity
from lilylcm import L08Tempurature
from lilylcm import L14LEDs
from lilylcm import L16ChargerCommand
from lilylcm import L19DockCommand
lc = lcm.LCM()
def my_handler(channel, data):
subDep = lc.subscribe("POD_Depth", my_handler)
sub... | import lcm
import time
from lilylcm import L06Depth
from lilylcm import L07Humidity
from lilylcm import L08Tempurature
from lilylcm import L10ChargerCOmplete
from lilylcm import L14LEDs
from lilylcm import L16ChargerCommand
from lilylcm import L19DockCommand
lc = lcm.LCM()
def my_handler(channel, data):
sub = lc.su... | mit | Python |
6874ff82ddf5e9d803a45676c45d83be65ad3b33 | Fix template and static paths | LINKIWI/linkr,LINKIWI/linkr,LINKIWI/linkr | core/app.py | core/app.py | import os
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
template_directory = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'../frontend/templates'
)
static_directory = '../frontend/static'
app = Flask(__name__, template_folder=template_direct... | import os
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
template_directory = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'frontend/templates'
)
static_directory = 'frontend/static'
app = Flask(__name__, template_folder=template_directory, s... | mit | Python |
9d97e0ceb96aa06da7fe8aa91c2402754632d89a | Replace eval with a proper importer. | opencorato/represent-boundaries,opencorato/represent-boundaries,opencorato/represent-boundaries,datamade/represent-boundaries,datamade/represent-boundaries,datamade/represent-boundaries | boundaries/__init__.py | boundaries/__init__.py | # coding: utf-8
from __future__ import unicode_literals
import logging
log = logging.getLogger(__name__)
import sys
import os
import re
from django.utils.translation import ugettext as _
registry = {}
_basepath = '.'
def register(slug, **kwargs):
"""
Adds a definition file to the list during the loadshapef... | # coding: utf-8
from __future__ import unicode_literals
import logging
log = logging.getLogger(__name__)
import os
import re
from django.utils.translation import ugettext as _
registry = {}
_basepath = '.'
def register(slug, **kwargs):
"""
Adds a definition file to the list during the loadshapefiles manage... | mit | Python |
a3b295b0c0317f85574fd3169c97d98422dc0adb | update .calc to use lxml, fixes #44 | TeamPeggle/ppp-helpdesk,Jeebeevee/DouweBot,andyeff/skybot,craisins/nascarbot,elitan/mybot,olslash/skybot,Jeebeevee/DouweBot_JJ15,cmarguel/skybot,ddwo/nhl-bot,craisins/wh2kbot,rmmh/skybot,parkrrr/skybot,isislab/botbot,Teino1978-Corp/Teino1978-Corp-skybot,df-5/skybot,callumhogsden/ausbot,jmgao/skybot,crisisking/skybot,So... | plugins/gcalc.py | plugins/gcalc.py | from util import hook, http
@hook.command
def calc(inp):
'''.calc <term> -- returns Google Calculator result'''
h = http.get_html('http://www.google.com/search', q=inp)
m = h.xpath('//h2[@class="r"]/text()')
if not m:
return "could not calculate " + inp
res = ' '.join(m[0].split())
... | import re
from util import hook, http
@hook.command
def calc(inp):
'''.calc <term> -- returns Google Calculator result'''
page = http.get('http://www.google.com/search', q=inp)
# ugh, scraping HTML with regexes
m = re.search(r'<h2 class=r style="font-size:138%"><b>(.*?)</b>', page)
if m is Non... | unlicense | Python |
c6dd8293cc7d5446d007f0ac9b7931852353ab5d | Add pygments and nbconvert style | tamasgal/km3pipe,tamasgal/km3pipe | km3pipe/style.py | km3pipe/style.py | # coding=utf-8
# Filename: style.py
# pylint: disable=locally-disabled
"""
The KM3Pipe style definitions.
"""
from __future__ import division, absolute_import, print_function
import os
import matplotlib.pyplot as plt
import km3pipe as kp
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the K... | # coding=utf-8
# Filename: style.py
# pylint: disable=locally-disabled
"""
The KM3Pipe style definitions.
"""
from __future__ import division, absolute_import, print_function
import os
import matplotlib.pyplot as plt
import km3pipe as kp
__author__ = "Tamas Gal"
__copyright__ = "Copyright 2016, Tamas Gal and the KM... | mit | Python |
5a21b677a18b4e3cb68c20328149ce9f2bb7412b | Add link to component | MartinHjelmare/home-assistant,mikaelboman/home-assistant,coteyr/home-assistant,betrisey/home-assistant,JshWright/home-assistant,pschmitt/home-assistant,devdelay/home-assistant,emilhetty/home-assistant,JshWright/home-assistant,toddeye/home-assistant,jamespcole/home-assistant,Smart-Torvy/torvy-home-assistant,DavidLP/home... | homeassistant/components/sensor/wink.py | homeassistant/components/sensor/wink.py | """
homeassistant.components.sensor.wink
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Wink sensors.
For more details about the wink component, please refer to the documentation
at https://home-assistant.io/components/wink.html
"""
import logging
from homeassistant.helpers.entity import Entity
from homeassistant.c... | """
homeassistant.components.sensor.wink
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Support for Wink sensors.
"""
import logging
from homeassistant.helpers.entity import Entity
from homeassistant.const import CONF_ACCESS_TOKEN, STATE_OPEN, STATE_CLOSED
REQUIREMENTS = ['https://github.com/balloob/python-wink/archive/'
... | mit | Python |
5a9dea03106718a55952a29a61249f5745a8dae0 | support flask-login v0.4.0 | inveniosoftware/invenio-accounts,inveniosoftware/invenio-accounts,inveniosoftware/invenio-accounts | invenio_accounts/__init__.py | invenio_accounts/__init__.py | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio user management and authentication.
Adminstration interface
-------------... | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio user management and authentication.
Adminstration interface
-------------... | mit | Python |
be9aa368fe454840797c253feb73d5dd88db8414 | update md5 function | juniwang/open-hackathon,msopentechcn/open-hackathon,msopentechcn/open-hackathon,juniwang/open-hackathon,msopentechcn/open-hackathon,juniwang/open-hackathon,juniwang/open-hackathon,msopentechcn/open-hackathon,juniwang/open-hackathon,juniwang/open-hackathon,msopentechcn/open-hackathon,msopentechcn/open-hackathon | open-hackathon-client/src/client/md5.py | open-hackathon-client/src/client/md5.py | # -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
import hashlib
import sys
sys.path.append("..")
from client import app
def encode(plaintext):
m = hashlib.md5()
origin = plaintext + app.config['SECRET_KEY']
m.update(origin.encode('utf8'))
retur... | # -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
import hashlib
import sys
sys.path.append("..")
from client import app
def encode(plaintext):
m = hashlib.md5()
origin = plaintext + app.config['SECRET_KEY']
m.update(origin.encode('utf8'))
retur... | mit | Python |
f2f975afe259120c0b648474b612fddf9ee02961 | change search view class | eliostvs/django-kb,eliostvs/django-kb | knowledge/views.py | knowledge/views.py | from __future__ import unicode_literals
from django.views.generic import TemplateView
from haystack.views import SearchView
from .article.views import (ArticleCreateView, ArticleDeleteView,
ArticleDetailView, ArticleListView,
ArticleUpdateView)
from .base.views... | from __future__ import unicode_literals
from django.views.generic import TemplateView
from haystack.views import SearchView
from .article.views import (ArticleCreateView, ArticleDeleteView,
ArticleDetailView, ArticleListView,
ArticleUpdateView)
from .base.views... | bsd-3-clause | Python |
f5fe10907d1ecffb89f62a56e8b7f8e34f4fcf2a | Make catch-all actually catch all | willmurnane/store | urls.py | urls.py | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^store/', include('store.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
(r'^ad... | from django.conf.urls.defaults import *
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Example:
# (r'^store/', include('store.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
(r'^ad... | bsd-3-clause | Python |
960d44a40f7db714c3b3596620e314a2800731af | handle blockquote using re | jeffjaehoyang/knowru_markdown | knowru_markdown.py | knowru_markdown.py | from markdown import markdown
import re
def markdown_to_html(user_given_text):
if user_given_text[0] == '>':
matchObj = re.match(r'> (.*)\("(.*)" \["(.*)" "(.*)"]\)', user_given_text)
html = '<blockquote>\n' + ' <p>' + matchObj.group(1) \
+ '</p>\n' + ' <footer>' + matchObj.gro... | from markdown import markdown
def markdown_to_html(user_given_text):
if user_given_text[0] == '>':
text_length = len(user_given_text)
p_content = ''
footer = ''
cite_content = ''
cite_title = ''
for x in range(2, text_length):
if user_given_te... | mit | Python |
882f6125d422f62794f6cc320ee60fc9f14a3e16 | Apply config for already opened files | SerkanSipahi/editorconfig-sublime,rivy/editorconfig-sublime,sindresorhus/editorconfig-sublime,gatero/editorconfig-sublime | EditorConfig.py | EditorConfig.py | import sublime_plugin
try:
import os, sys
# stupid python module system
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from .editorconfig import get_properties, EditorConfigError
except:
# Python 2
from editorconfig import get_properties, EditorConfigError
LINE_ENDINGS = {
'lf': 'unix',
'crlf':... | import sublime_plugin
try:
import os, sys
# stupid python module system
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
from .editorconfig import get_properties, EditorConfigError
except:
# Python 2
from editorconfig import get_properties, EditorConfigError
LINE_ENDINGS = {
'lf': 'unix',
'crlf':... | mit | Python |
cebd4d613cc95ef6e775581a6f77f4850e39020a | Improve error message on invalid conf key | executablebooks/mdformat | src/mdformat/_conf.py | src/mdformat/_conf.py | from __future__ import annotations
import functools
from pathlib import Path
from typing import Mapping
import tomli
DEFAULT_OPTS = {
"wrap": "keep",
"number": False,
"end_of_line": "lf",
}
class InvalidConfError(Exception):
"""Error raised given invalid TOML or a key that is not valid for
mdfo... | from __future__ import annotations
import functools
from pathlib import Path
from typing import Mapping
import tomli
DEFAULT_OPTS = {
"wrap": "keep",
"number": False,
"end_of_line": "lf",
}
class InvalidConfError(Exception):
"""Error raised given invalid TOML or a key that is not valid for
mdfo... | mit | Python |
1c15bab84ba9b2e0e4e1e4676f0c60c907d21e30 | remove running filter | coco-project/coco,coco-project/coco,coco-project/coco,coco-project/coco | ipynbsrv/web/views/common.py | ipynbsrv/web/views/common.py | from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.http.response import HttpResponse
from django.shortcuts import render
from ipynbsrv.core.auth import login_allowed
from... | from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.http.response import HttpResponse
from django.shortcuts import render
from ipynbsrv.core.auth import login_allowed
from... | bsd-3-clause | Python |
b3e9593480da8844451f092dfbbf45ccacd0801a | Fix test to account for divergent JSON encode error in Python 3.5 | valohai/minique | minique_tests/test_errors.py | minique_tests/test_errors.py | import time
import pytest
from minique.api import enqueue
from minique.enums import JobStatus
from minique.excs import AlreadyAcquired, DuplicateJob, NoSuchJob
from minique.models.queue import Queue
from minique.work.worker import Worker
from minique_tests.jobs import job_with_unjsonable_retval
def test_unjsonable_... | import time
import pytest
from minique.api import enqueue
from minique.enums import JobStatus
from minique.excs import AlreadyAcquired, DuplicateJob, NoSuchJob
from minique.models.queue import Queue
from minique.work.worker import Worker
from minique_tests.jobs import job_with_unjsonable_retval
def test_unjsonable_... | mit | Python |
6d74eed1b9b34a4803a77d05e9c19d940712f18b | Improve appearance of similarities in admin | FreeMusicNinja/api.freemusic.ninja | similarities/admin.py | similarities/admin.py | from django.contrib import admin
from .models import GeneralArtist, Similarity
class SimilarityModelAdmin(admin.ModelAdmin):
fields = ['other_artist', 'cc_artist', 'weight']
list_display = ['id', 'other_artist', 'cc_artist', 'weight']
readonly_fields = ['other_artist', 'cc_artist']
admin.site.register(... | from django.contrib import admin
from .models import GeneralArtist, Similarity
admin.site.register(GeneralArtist)
admin.site.register(Similarity)
| bsd-3-clause | Python |
d76e9c431d91ad95b7fa84b464c4e90ea7bb573b | add huber loss | BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH,BerlinUnited/NaoTH | Utils/py/BallDetection/RegressionNetwork/utility_functions/loss_zoo.py | Utils/py/BallDetection/RegressionNetwork/utility_functions/loss_zoo.py | import tensorflow as tf
def custom_loss(y_true, y_pred):
mse = tf.losses.mean_squared_error(y_true, y_pred)
return 100 * mse
def huber_loss(y_true, y_pred):
"""
for reqression tasks
"""
threshold = 1
error = y_true - y_pred
is_small_error = tf.abs(error) <= threshold
small_error... | import tensorflow as tf
def custom_loss(y_true, y_pred):
mse = tf.losses.mean_squared_error(y_true, y_pred)
return 100 * mse
| apache-2.0 | Python |
5163a2becef6196b39d16d4e2c7737c16beec404 | delete logging | uehara1414/lambda-mstdn-bot-sample,uehara1414/lambda-mstdn-bot-sample | lambda_function.py | lambda_function.py | import os
import io
import boto3
from botocore.exceptions import ClientError
from mastodon import Mastodon
s3 = boto3.resource(
's3',
aws_access_key_id=os.getenv('AWS_ACCESS_KEY'),
aws_secret_access_key=os.getenv('AWS_ACCESS_SECRET'),
)
HOST = 'https://mstdn.fun'
def get_mastodon_instance():
try:
... | import os
import io
import boto3
from botocore.exceptions import ClientError
from mastodon import Mastodon
s3 = boto3.resource(
's3',
aws_access_key_id=os.getenv('AWS_ACCESS_KEY'),
aws_secret_access_key=os.getenv('AWS_ACCESS_SECRET'),
)
HOST = 'https://mstdn.fun'
def get_mastodon_instance():
try:
... | mit | Python |
6c333cd5f3e8fe8b6cce3c3d651e1c4e4dcd98c0 | handle the multipart encoded request | SimonWaldherr/uploader,FineUploader/fine-uploader,SimonWaldherr/uploader,FineUploader/fine-uploader,SimonWaldherr/uploader,SimonWaldherr/uploader,SimonWaldherr/uploader,SimonWaldherr/uploader,SimonWaldherr/uploader,FineUploader/fine-uploader | server/python_django/file_uploader/__init__.py | server/python_django/file_uploader/__init__.py | """
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.conf import settings
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=None):
self.allowedExt... | """
@author: Ferdinand E. Silva
@email: ferdinandsilva@ferdinandsilva.com
@website: http://ferdinandsilva.com
"""
import os
from django.conf import settings
from django.utils import simplejson as json
class qqFileUploader(object):
def __init__(self, allowedExtensions=None, sizeLimit=None):
self.allowedEx... | mit | Python |
20151a50424bbb6c4edcab5f19b97e3d7fb838b9 | Change plugin type to profile_reader | Curahelper/Cura,fieldOfView/Cura,hmflash/Cura,ynotstartups/Wanhao,hmflash/Cura,senttech/Cura,Curahelper/Cura,ynotstartups/Wanhao,fieldOfView/Cura,totalretribution/Cura,totalretribution/Cura,senttech/Cura | plugins/GCodeReader/__init__.py | plugins/GCodeReader/__init__.py | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeReader
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "GCode Reader"),
"author"... | # Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the AGPLv3 or higher.
from . import GCodeReader
from UM.i18n import i18nCatalog
catalog = i18nCatalog("cura")
def getMetaData():
return {
"plugin": {
"name": catalog.i18nc("@label", "GCode Reader"),
"author"... | agpl-3.0 | Python |
8d3fbccf092937a0b9b2a2da1d7b0bab0f063f2c | print the teamdates | martbhell/wasthereannhlgamelastnight,martbhell/wasthereannhlgamelastnight,martbhell/wasthereannhlgamelastnight | parse_schedule/parse_nhl_schedule.py | parse_schedule/parse_nhl_schedule.py | #!/usr/bin/python
# This requires BS4 (findAll vs find_all)
from BeautifulSoup import BeautifulSoup
import urllib2
url= 'http://www.nhl.com/ice/schedulebyseason.htm'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
data = []
data1 = []
lines = []
# Format2 test: { "Wed Jun 8, 2015" : [ "Tampa Bay", "Ch... | #!/usr/bin/python
# This requires BS4 (findAll vs find_all)
from BeautifulSoup import BeautifulSoup
import urllib2
url= 'http://www.nhl.com/ice/schedulebyseason.htm'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
data = []
data1 = []
lines = []
# Format2 test: { "Wed Jun 8, 2015" : [ "Tampa Bay", "Ch... | mit | Python |
871d85487b90b6ddc179b078685eb8461b57e4a9 | Fix a small flake8 warning in test_checker.py | jparise/flake8-author | tests/test_checker.py | tests/test_checker.py | import ast
import unittest
from flake8.main.application import Application
from flake8_author import Checker
def make_linter(code, path='example.py', argv=None):
app = Application()
app.initialize(argv)
Checker.parse_options(app.options)
tree = ast.parse(code, path)
return Checker(tree, path)
d... | import ast
import unittest
from flake8.main.application import Application
from flake8_author import Checker
def make_linter(code, path='example.py', argv=None):
app = Application()
app.initialize(argv)
Checker.parse_options(app.options)
tree = ast.parse(code, path)
return Checker(tree, path)
d... | mit | Python |
3ce351b7b3d365c1b9170fe79ca7b57647b189ef | Fix permissions in api | frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq | frigg/api/views.py | frigg/api/views.py | from rest_framework import permissions, viewsets
from frigg.builds.filters import BuildPermissionFilter, ProjectPermissionFilter
from frigg.builds.models import Build, Project
from frigg.builds.serializers import BuildSerializer, PaginatedBuildSerializer, ProjectSerializer
class ProjectViewSet(viewsets.ModelViewSet)... | from rest_framework import viewsets
from frigg.builds.filters import BuildPermissionFilter, ProjectPermissionFilter
from frigg.builds.models import Build, Project
from frigg.builds.serializers import BuildSerializer, PaginatedBuildSerializer, ProjectSerializer
class ProjectViewSet(viewsets.ModelViewSet):
queryse... | mit | Python |
93ba4af6dbe2d5309800b17c540a828f6fde6a12 | fix float multipy overfloat by log sum | weixsong/algorithm,weixsong/algorithm,weixsong/algorithm | probability/birthday_paradox.py | probability/birthday_paradox.py | #!/usr/bin/env python
"""
Given a number of people, compute the probability of at least two people have the same birthday
"""
import math
class Solution(object):
def computeProb(self, n):
"""
:type n: int
:rtype: float
Idea: if n > 365, then definitely at least two people will ha... | #!/usr/bin/env python
"""
Given a number of people, compute the probability of at least two people have the same birthday
"""
class Solution(object):
def computeProb(self, n):
"""
:type n: int
:rtype: float
Idea: if n > 365, then definitely at least two people will has the same bi... | mit | Python |
babff08ce4a1ecb8b7885e80c6a4528bfaae6278 | add test case for incorrect number | katoken-0215/FikaNote,katoken-0215/FikaNote,gmkou/FikaNote,katoken-0215/FikaNote,sassy/FikaNote,sassy/FikaNote,sassy/FikaNote,gmkou/FikaNote,gmkou/FikaNote | tests/test_episode.py | tests/test_episode.py | import unittest
from django.test.client import Client
from django.db import models
from app.models import FikanoteDB
class EpisodeTest(unittest.TestCase):
def setUp(self):
# unittest requires to create Client everytime
self.client = Client()
self.episodes = FikanoteDB.objects.order_by('-dat... | import unittest
from django.test.client import Client
from django.db import models
from app.models import FikanoteDB
class EpisodeTest(unittest.TestCase):
def setUp(self):
# unittest requires to create Client everytime
self.client = Client()
def test_get_episode(self):
episodes = Fikan... | mit | Python |
b9eaa6d469fd47315efcd2d99990a74ae9da1285 | Add docstring to EfficiencyWarning | corburn/scikit-bio,anderspitman/scikit-bio,Achuth17/scikit-bio,Achuth17/scikit-bio,corburn/scikit-bio,xguse/scikit-bio,SamStudio8/scikit-bio,johnchase/scikit-bio,gregcaporaso/scikit-bio,jairideout/scikit-bio,jensreeder/scikit-bio,jdrudolph/scikit-bio,averagehat/scikit-bio,colinbrislawn/scikit-bio,anderspitman/scikit-bi... | skbio/core/warning.py | skbio/core/warning.py | """
Warnings (:mod:`skbio.core.warning`)
====================================
.. currentmodule:: skbio.core.warning
This module defines custom warning classes used throughout the core scikit-bio
codebase.
Warnings
--------
.. autosummary::
:toctree: generated/
EfficiencyWarning
"""
# ----------------------... | """
Warnings (:mod:`skbio.core.warning`)
====================================
.. currentmodule:: skbio.core.warning
This module defines custom warning classes used throughout the core scikit-bio
codebase.
Warnings
--------
.. autosummary::
:toctree: generated/
EfficiencyWarning
"""
# ----------------------... | bsd-3-clause | Python |
715098531f823c3b2932e6a03d2e4b113bd53ed9 | Revise grammar tests for atom | pdarragh/Viper | tests/test_grammar.py | tests/test_grammar.py | import viper.grammar as vg
import viper.lexer as vl
from viper.grammar.languages import (
SPPF,
ParseTreeEmpty as PTE, ParseTreeChar as PTC, ParseTreePair as PTP, ParseTreeRep as PTR
)
import pytest
@pytest.mark.parametrize('line,sppf', [
('foo',
SPPF(PTC(vl.Name('foo')))),
('42',
SPPF(PTC... | import viper.grammar as vg
import viper.grammar.languages as vgl
import viper.lexer as vl
import pytest
@pytest.mark.parametrize('line,sppf', [
('foo',
vgl.SPPF(vgl.ParseTreeChar(vl.Name('foo')))),
('2',
vgl.SPPF(vgl.ParseTreeChar(vl.Number('2')))),
('...',
vgl.SPPF(vgl.ParseTreeChar(vl.Op... | apache-2.0 | Python |
eca9ee90bf64b14c6a8eacdb4197825790ab7825 | Add tests for A2.4 and A2.5 | orbingol/NURBS-Python,orbingol/NURBS-Python | tests/test_helpers.py | tests/test_helpers.py | """
Tests for the NURBS-Python package
Released under The MIT License. See LICENSE file for details.
Copyright (c) 2018 Onur Rauf Bingol
Tests geomdl.helpers module.
"""
from geomdl import helpers
GEOMDL_DELTA = 10e-8
def test_basis_function_one():
degree = 2
knot_vector = [0, 0, 0, 1, 2, 3, 4, 4,... | mit | Python | |
99683d16551450686397f953668b7d6bf4167a5e | Add a length argument in TestMethods.interleave | mpkato/interleaving | tests/test_methods.py | tests/test_methods.py | import interleaving as il
import numpy as np
np.random.seed(0)
class TestMethods(object):
def assert_almost_equal(self, a, b, error_rate=0.1):
half_error_rate = error_rate / 2.0
lower_bound = (1.0 - half_error_rate) * a
upper_bound = (1.0 + half_error_rate) * a
assert lower_bound <... | import interleaving as il
import numpy as np
np.random.seed(0)
class TestMethods(object):
def assert_almost_equal(self, a, b, error_rate=0.1):
half_error_rate = error_rate / 2.0
lower_bound = (1.0 - half_error_rate) * a
upper_bound = (1.0 + half_error_rate) * a
assert lower_bound <... | mit | Python |
c3db9720f25e1af3b59ca7b1d22691dba09a0347 | test fixed (layer_sizes -> layers) | Quadrocube/rep,Quadrocube/rep | tests/test_nolearn.py | tests/test_nolearn.py | from __future__ import division, print_function, absolute_import
from ._test_classifier import check_classifier, check_regression
from rep.estimators import NolearnClassifier
from sklearn.ensemble import AdaBoostClassifier, BaggingClassifier
from rep.estimators.sklearn import SklearnClassifier
def test_nolearn_class... | from __future__ import division, print_function, absolute_import
from ._test_classifier import check_classifier, check_regression
from rep.estimators import NolearnClassifier
from sklearn.ensemble import AdaBoostClassifier, BaggingClassifier
from rep.estimators.sklearn import SklearnClassifier
def test_nolearn_class... | apache-2.0 | Python |
32dc7ddcbd9f655089d5b7297cbd065854439bb7 | Update status | Vgr255/logging | logger/__init__.py | logger/__init__.py | #!/usr/bin/env python3
"""Logging package for specific and general needs."""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3"
__status__ = "Mass Refactor [Unstable]"
__all__ = []
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
| #!/usr/bin/env python3
"""Logging package for specific and general needs."""
__author__ = "Emanuel 'Vgr' Barry"
__version__ = "0.2.3" # Version string not being updated during refactor
__status__ = "Mass Refactor"
__all__ = []
from . import loggers
from .loggers import *
__all__.extend(loggers.__all__)
| bsd-2-clause | Python |
01bcfe38aa07765927a227dca79d577b03621deb | fix tests | michaeltcoelho/pagarme.py | tests/test_payment.py | tests/test_payment.py | # coding:utf-8
import unittest
from pagarme.resources import Payment
class PaymentTest(unittest.TestCase):
@unittest.skip('')
def test_all(self):
payables = Payment.all()
self.assertGreater(len(payables), 0)
| # coding:utf-8
import unittest
from pagarme.resources import Payment
class PaymentTest(unittest.TestCase):
@unittest.skip('')
def test_all(self):
payables = Payment.all()
self.assertGreater(len(payables), 0) | mit | Python |
d6b4b43aa27d8b5c87f23f36ab2adffcbcbcb52f | fix test | Lee-W/pipreqs,intermezzo-fr/pipreqs,scalp42/pipreqs,extremewaysback/pipreqs,bndr/pipreqs,GadgetSteve/pipreqs,cychiang/pipreqs | tests/test_pipreqs.py | tests/test_pipreqs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pipreqs
----------------------------------
Tests for `pipreqs` module.
"""
import unittest, os
from pipreqs import pipreqs
class TestPipreqs(unittest.TestCase):
def setUp(self):
self.modules = ['flask', 'requests', 'sqlalchemy', 'docopt']
def t... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_pipreqs
----------------------------------
Tests for `pipreqs` module.
"""
import unittest, os
from pipreqs import pipreqs
class TestPipreqs(unittest.TestCase):
def setUp(self):
self.modules = ['flask', 'requests', 'sqlalchemy', 'docopt']
pa... | apache-2.0 | Python |
8c944af86b15f6694a594f375d883573aa8925ff | test for reverse player | abw333/dominoes | tests/test_players.py | tests/test_players.py | import copy
import dominoes
import unittest
class TestPlayers(unittest.TestCase):
def _test_player_interface(self, player):
g = dominoes.Game.new()
g_copy = copy.deepcopy(g)
player(g)
self.assertEqual(type(g.valid_moves), tuple)
self.assertEqual(len(g.valid_moves), len(g_... | import copy
import dominoes
import unittest
class TestPlayers(unittest.TestCase):
def _test_player_interface(self, player):
g = dominoes.Game.new()
g_copy = copy.deepcopy(g)
player(g)
self.assertEqual(type(g.valid_moves), tuple)
self.assertEqual(len(g.valid_moves), len(g_... | mit | Python |
61800be9a034b10bb35715adb314225d7b40b77c | Add http/https proxy management for dataset downloading | kuza55/keras,daviddiazvico/keras,kemaswill/keras,relh/keras,DeepGnosis/keras,keras-team/keras,dolaameng/keras,nebw/keras,keras-team/keras | keras/datasets/data_utils.py | keras/datasets/data_utils.py | from __future__ import absolute_import
from __future__ import print_function
import tarfile
import os
import sys
from six.moves.urllib.request import urlopen, build_opener, install_opener
from six.moves.urllib.error import URLError, HTTPError
from ..utils.generic_utils import Progbar
# Under Python 2, 'urlretrieve'... | from __future__ import absolute_import
from __future__ import print_function
import tarfile
import os
from six.moves.urllib.request import FancyURLopener
from ..utils.generic_utils import Progbar
class ParanoidURLopener(FancyURLopener):
def http_error_default(self, url, fp, errcode, errmsg, headers):
ra... | mit | Python |
5d5a036935873e6bdb598c366c668acea8dcaf85 | fix unicode errors | legoktm/legobot-old,legoktm/legobot-old | trunk/toolserver/WPlist.py | trunk/toolserver/WPlist.py | #!usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, re
__version__ = '$Id$'
sys.path.append(os.environ['HOME'] + '/pyenwiki')
import wikipedia, catlib, pagegenerators, query
def API(params):
return query.GetData(params, useAPI = True, encodeTitle = False)
def unicodify(text):
if not isinstance(text, unicode)... | #!usr/bin/python
# -*- coding: utf-8 -*-
import os, sys, re
__version__ = '$Id$'
sys.path.append(os.environ['HOME'] + '/pyenwiki')
import wikipedia, catlib, pagegenerators, query
def API(params):
return query.GetData(params, useAPI = True, encodeTitle = False)
def unicodify(text):
if not isinstance(text, unicode)... | mit | Python |
69d5a603419b927e6c7446d3fc1828c9541ad9e4 | Update test methods to better describe tests | ONSdigital/edcdi | tests/test_service.py | tests/test_service.py | from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
import requests
import base64
import unittest
import json
class TestPosieService(unittest.T... | from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
import requests
import base64
import unittest
import json
class TestPosieService(unittest.T... | mit | Python |
272bc2bdc49ac27884c29341d752eb241fa69700 | Clean up KILL output a little | Heufneutje/txircd,DesertBus/txircd,ElementalAlchemist/txircd | txircd/modules/cmd_kill.py | txircd/modules/cmd_kill.py | from twisted.words.protocols import irc
from txircd.modbase import Command
class KillCommand(Command):
def onUse(self, user, data):
target = data["targetuser"]
reason = "Killed by {}: {}".format(user.nickname, data["reason"])
target.sendMessage("KILL", ":{} {}".format(user.nickname, data["reason"]), prefix=user... | from twisted.words.protocols import irc
from txircd.modbase import Command
class KillCommand(Command):
def onUse(self, user, data):
target = data["targetuser"]
reason = "Killed by {}: {}".format(user.nickname, data["reason"])
target.sendMessage("KILL", ":{} {}".format(user.nickname, data["reason"]))
quit_to =... | bsd-3-clause | Python |
163a6c990fb79cceb8c0e5b9f4d72cb6892e0638 | Prepare configuration for xmr. | ajiwo/xiboside | xibo.py | xibo.py | import os
import json
class XiboConfig:
def __init__(self, path=None):
self.path = path
self.saveDir = None
self.url = None
self.serverKey = None
# datetime format (see strptime)
self.strTimeFmt = None
self.cmsTzOffset = None
self.res_file_ext = None... | import os
import json
class XiboConfig:
def __init__(self, path=None):
self.path = path
self.saveDir = None
self.url = None
self.serverKey = None
# datetime format (see strptime)
self.strTimeFmt = None
self.cmsTzOffset = None
self.res_file_ext = None... | agpl-3.0 | Python |
3373dc9cd1b6eef2ecd4e5498651bd23d1efbdb7 | Update dependency bazelbuild/bazel to latest version | google/copybara,google/copybara,google/copybara | third_party/bazel.bzl | third_party/bazel.bzl | # Copyright 2019 Google Inc.
#
# 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,... | # Copyright 2019 Google Inc.
#
# 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,... | apache-2.0 | Python |
c5631daf64d6f9f628276de0de1b6dab292e991b | Update media.py | SoumanRoy/udacity_1,SoumanRoy/udacity_1 | project/media.py | project/media.py | import webbrowser
class Movie():
""" This class stores movie related information along with ability to show a movie trailer. """
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url... | import webbrowser
class Movie():
def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube):
self.title = movie_title
self.storyline = movie_storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def show_trailer(self):
... | mit | Python |
fa0080b06b31e767f3207f2a0facd66e4e1602f9 | Update Bazel to latest version | google/copybara,google/copybara,google/copybara | third_party/bazel.bzl | third_party/bazel.bzl | # Copyright 2019 Google Inc.
#
# 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,... | # Copyright 2019 Google Inc.
#
# 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,... | apache-2.0 | Python |
94529f62757886d2291cf90596a179dc2d0b6642 | Make cute respect guild nicknames | HarkonenBade/yutu | yutu.py | yutu.py | import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.... | import discord
from discord.ext.commands import Bot
import json
client = Bot("~", game=discord.Game(name="~help"))
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.command()
async def highfive(ctx):
'''
Give Yutu a high-five
'''
await ctx.send('{0.... | mit | Python |
de1180fa94e06e749b3208f522f0750b532bd69a | Change the target that we build on the android bot from samples to runtime | dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dartino/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-lang/sdk,dartino/dart-sdk,dartino/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dart-lang/sdk,dart-archive/dart-sdk,dart-archive/dart-sdk,dartino/dart-sdk,da... | tools/bots/android.py | tools/bots/android.py | #!/usr/bin/python
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
Android buildbot steps.
"""
import os
import os.path
import re
import sys
import ... | #!/usr/bin/python
# Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
"""
Android buildbot steps.
"""
import os
import os.path
import re
import sys
import ... | bsd-3-clause | Python |
279f7a2f62f90d9e915388be599193f5f0c08902 | update extract audio | mcxiaoke/python-labs,mcxiaoke/python-labs,mcxiaoke/python-labs,mcxiaoke/python-labs,mcxiaoke/python-labs | labs/extract-audio-ffmpeg.py | labs/extract-audio-ffmpeg.py | # -*- coding: utf-8 -*-
# @Author: Miu
# @Date: 2017-06-27 21:41:37
# @Last Modified by: mcxiaoke
# @Last Modified time: 2017-06-27 22:24:32
from __future__ import print_function
import sys
import os
import codecs
import re
import string
import shutil
import subprocess
from os import path
def process(curdir, name... | # -*- coding: utf-8 -*-
# @Author: Miu
# @Date: 2017-06-27 21:41:37
# @Last Modified by: mcxiaoke
# @Last Modified time: 2017-06-27 22:24:32
from __future__ import print_function
import sys
import os
import codecs
import re
import string
import shutil
import subprocess
from os import path
def process(curdir, name... | apache-2.0 | Python |
e10be14e4ac91fdaeac8d74a99a5e44306aab795 | update req | globocom/GloboNetworkAPI-client-python | networkapiclient/__init__.py | networkapiclient/__init__.py | # -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... | # -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... | apache-2.0 | Python |
d5199a22a897bd7c91468ff66f7e6107cfda6a24 | Update TODO | martialblog/git-pullpush | pullpush/main.py | pullpush/main.py | #!/usr/bin/env python3
# TODO Retry-If-Fail implementation
# TODO Move Slack Config to seperate config file
from tempfile import TemporaryDirectory
from argparse import ArgumentParser
from slacker import Slacker
from pullpush import PullPush
from sys import exit
DESC = 'Pulls a git repository and pushes it somewhere... | #!/usr/bin/env python3
# TODO Retry-If-Fail implementation
from tempfile import TemporaryDirectory
from argparse import ArgumentParser
from slacker import Slacker
from pullpush import PullPush
from sys import exit
DESC = 'Pulls a git repository and pushes it somewhere'
HELP_PULL = 'The repo to pull from'
HELP_PUSH ... | mit | Python |
4235bbe016d7b9cce7dd8f2857a5abe0f0c63d04 | change name for test to remove duplication | neuropower/neuropower-core | neuropower/tests/test_bum.py | neuropower/tests/test_bum.py | from unittest import TestCase
from neuropower import BUM
import numpy as np
class TestBUM(TestCase):
def test_fpLL(self):
np.random.seed(seed=100)
testpeaks = np.vstack((np.random.uniform(0,1,10),np.random.uniform(0,0.2,10))).flatten()
x = np.sum(BUM.fpLL([0.5,0.5],testpeaks))
self.... | from unittest import TestCase
from neuropower import BUM
import numpy as np
class TestBUM(TestCase):
def test_fpLL(self):
np.random.seed(seed=100)
testpeaks = np.vstack((np.random.uniform(0,1,10),np.random.uniform(0,0.2,10))).flatten()
x = np.sum(BUM.fpLL([0.5,0.5],testpeaks))
self.... | mit | Python |
a3a55806ecb79541f066bfe5bce82bc9fca58481 | Make addresses unique | janLo/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,eXma/meet-and-eat-registration-system,janLo/meet-and-eat-registration-system | src/promo/__init__.py | src/promo/__init__.py | from contextlib import contextmanager
from email.mime.text import MIMEText
from email.utils import formatdate
from cfg import config, parse_end_date
import os
import re
from teammails import base_path, get_template, smtp_session
@contextmanager
def address_set(filename):
if not os.path.isfile(filename):
... | from contextlib import contextmanager
from email.mime.text import MIMEText
from email.utils import formatdate
from cfg import config, parse_end_date
import os
import re
from teammails import base_path, get_template, smtp_session
@contextmanager
def address_iterator(filename):
if not os.path.isfile(filename):
... | bsd-3-clause | Python |
1c39ab66626cb54b8bd65b094901ea004a352ad2 | Replace O(N^2) algorithm with a faster one. | cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,jupyter-widgets/ipywidgets,cornhundred/ipywidgets,cornhundred/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipy... | IPython/html/widgets/widget_container.py | IPython/html/widgets/widget_container.py | """ContainerWidget class.
Represents a container that can be used to group other widgets.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the ... | """ContainerWidget class.
Represents a container that can be used to group other widgets.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the ... | bsd-3-clause | Python |
b824f57916f91558c3541bc20d7a7a31464492d0 | use better method for translation in example | sheekap/exercism.io,MBGeoff/Exercism.io-mbgeoff,colinrubbert/exercism.io,mhelmetag/exercism.io,Tonkpils/exercism.io,kangkyu/exercism.io,nathanbwright/exercism.io,alexclarkofficial/exercism.io,mscoutermarsh/exercism_coveralls,exercistas/exercism.io,treiff/exercism.io,sheekap/exercism.io,RaptorRCX/exercism.io,tejasbubane... | assignments/python/rna-transcription/example.py | assignments/python/rna-transcription/example.py | from string import maketrans
class DNA(object):
rna_translation = maketrans('AGCT', 'AGCU')
def __init__(self, strand):
self.strand = strand
def to_rna(self):
return self.strand.translate(self.rna_translation)
| class DNA(object):
thymidine = 'T'
uracil = 'U'
def __init__(self, strand):
self.strand = strand
def to_rna(self):
return self.strand.replace(
self.thymidine,
self.uracil
)
| agpl-3.0 | Python |
928b173b6327533cb64d99be6c8ad0508740c5af | remove debugging code | rlowrance/re-avm | make_test_train.py | make_test_train.py | import numpy as np
import pandas as pd
import pdb
from pprint import pprint
import unittest
from Month import Month
def make_test_train(test_time_period, train_n_months_back, trade_month_column_name, samples):
'return dataframes for testing and training; see valavm.do_val.fit_and_run'
assert isinstance(test_... | import numpy as np
import pandas as pd
import pdb
from pprint import pprint
import unittest
from Month import Month
def make_test_train(test_time_period, train_n_months_back, trade_month_column_name, samples):
'return dataframes for testing and training; see valavm.do_val.fit_and_run'
assert isinstance(test_... | bsd-3-clause | Python |
5ee61c04a4e13293d8ef2ece02076898b7eb1b23 | add currencies and languages | dgulotta/puzzle-tools,dgulotta/puzzle-tools,dgulotta/puzzle-tools | puzzletools/enumerations_web.py | puzzletools/enumerations_web.py | from puzzletools.table_parser import parse_wikitable
from puzzletools.morse import dash_to_hyphen
from urllib.request import urlopen
from time import strptime
import unicodedata
def download_wikitable(url,tablenum=0):
return parse_wikitable(urlopen(url),tablenum)
def countries():
return download_wikitable('ht... | from puzzletools.table_parser import parse_wikitable
from puzzletools.morse import dash_to_hyphen
from urllib.request import urlopen
from time import strptime
import unicodedata
def download_wikitable(url,tablenum=0):
return parse_wikitable(urlopen(url),tablenum)
def countries():
return download_wikitable('ht... | mit | Python |
e09397c143ced7ea21fa9a660adb23d1808d8419 | Bump version to 0.0.2.dev0 | EUDAT-B2ACCESS/unity-api-python-client | unityapiclient/__init__.py | unityapiclient/__init__.py | __version__ = "0.0.2.dev0"
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(Nul... | __version__ = "0.0.1"
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHand... | apache-2.0 | Python |
d532cac15fa18dab5356d7e11c79a7cbfeb8bb9c | Move twisted import further down | pyfarm/pyfarm-agent,pyfarm/pyfarm-agent,guidow/pyfarm-agent,guidow/pyfarm-agent,guidow/pyfarm-agent,pyfarm/pyfarm-agent | pyfarm/agent/http/api/update.py | pyfarm/agent/http/api/update.py | # No shebang line, this module is meant to be imported
#
# Copyright 2014 Oliver Palmer
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# 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
#
... | # No shebang line, this module is meant to be imported
#
# Copyright 2014 Oliver Palmer
# Copyright 2014 Ambient Entertainment GmbH & Co. KG
#
# 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
#
... | apache-2.0 | Python |
7a3ae3c64354bbba16e8d21de25cc7fa48a79265 | add config file | Alafazam/simple_projects,Alafazam/simple_projects,Alafazam/simple_projects,Alafazam/simple_projects | python/parser.py | python/parser.py | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open(r'config.pcgf'))
username = config.get('creden... | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# driver = webdriver.PhantomJS()
driver = webdriver.Firefox()
driver.set_window_size(1120, 550)
driver.get("https://gma... | mit | Python |
756a87ffe09091bc55f88edc963bc03fc8fbfd6b | Fix incorrect python version | danielj7/pythonfutures,danielj7/pythonfutures | python2/setup.py | python2/setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='futures',
version='1.0',
description='Java-style futures implementation in Python 2.x',
author='Brian Quinlan',
author_email='brian@sweetapp.com',
url='http://code.google.com/p/pythonfutures',
download_url='http://p... | #!/usr/bin/env python3
from distutils.core import setup
setup(name='futures3',
version='1.0',
description='Java-style futures implementation in Python 3.x',
author='Brian Quinlan',
author_email='brian@sweetapp.com',
url='http://code.google.com/p/pythonfutures',
download_url='http:/... | bsd-2-clause | Python |
d45d149669a2ad4db486225d306007e80d91f3eb | update filters documentation | Pelagicore/qface,Gagi2k/qface | qface/filters.py | qface/filters.py | import json
import hashlib
def jsonify(symbol):
""" returns json format for symbol """
try:
# all symbols have a toJson method, try it
return json.dumps(symbol.toJson(), indent=' ')
except AttributeError:
pass
return json.dumps(symbol, indent=' ')
def upper_first(symbol):
... | import json
import hashlib
def jsonify(obj):
try:
# all symbols have a toJson method, try it
return json.dumps(obj.toJson(), indent=' ')
except AttributeError:
pass
return json.dumps(obj, indent=' ')
def upper_first(s):
s = str(s)
return s[0].upper() + s[1:]
def hash(... | mit | Python |
17f8615bbcbe1e694b573c359f109173d15af48b | update docstring for exceptions (#4475) | yuanming-hu/taichi,yuanming-hu/taichi,yuanming-hu/taichi,yuanming-hu/taichi | python/taichi/lang/exception.py | python/taichi/lang/exception.py | from taichi._lib import core
class TaichiCompilationError(Exception):
"""Base class for all compilation exceptions.
"""
pass
class TaichiSyntaxError(TaichiCompilationError, SyntaxError):
"""Thrown when a syntax error is found during compilation.
"""
pass
class TaichiNameError(TaichiCompila... | from taichi._lib import core
class TaichiCompilationError(Exception):
pass
class TaichiSyntaxError(TaichiCompilationError, SyntaxError):
pass
class TaichiNameError(TaichiCompilationError, NameError):
pass
class TaichiTypeError(TaichiCompilationError, TypeError):
pass
class TaichiRuntimeError(R... | apache-2.0 | Python |
d33f1317e4dde468e0d196b3824a9e47cd98e20e | Apply suggestions from code review | spyder-ide/qtpy | qtpy/QtCharts.py | qtpy/QtCharts.py | # -----------------------------------------------------------------------------
# Copyright © 2019- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtChart classes and... | # -----------------------------------------------------------------------------
# Copyright © 2019- The Spyder Development Team
#
# Licensed under the terms of the MIT License
# (see LICENSE.txt for details)
# -----------------------------------------------------------------------------
"""Provides QtChart classes and... | mit | Python |
d8516a5b1d5d97b64e0c2af51f1ffac6220280d6 | use intersphinx links on readthedocs.org for django | emory-libraries/eulxml,dannyroberts/eulxml | doc/conf.py | doc/conf.py | # eulcore documentation build configuration file
import eulxml
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
#templates_path = ['templates']
exclude_trees = ['build']
source_suffix = '.rst'
master_doc = 'index'
project = 'eulxml'
copyright = '2011, Emory University Libraries'
version = '%d.%d' % eul... | # eulcore documentation build configuration file
import eulxml
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
#templates_path = ['templates']
exclude_trees = ['build']
source_suffix = '.rst'
master_doc = 'index'
project = 'eulxml'
copyright = '2011, Emory University Libraries'
version = '%d.%d' % eul... | apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.