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 |
|---|---|---|---|---|---|---|---|---|
66cd4dafea774906b0b3ac3698267b70aac9295c | Update __init__.py | anuragpapineni/Hearthbreaker-evolved-agent,slaymaker1907/hearthbreaker,kingoflolz/hearthbreaker,noa/hearthbreaker,pieiscool/edited-hearthbreaker,anuragpapineni/Hearthbreaker-evolved-agent,Ragowit/hearthbreaker,slaymaker1907/hearthbreaker,pieiscool/edited-hearthbreaker,jirenz/CS229_Project,anuragpapineni/Hearthbreaker-e... | hsgame/cards/spells/__init__.py | hsgame/cards/spells/__init__.py | __author__ = 'Daniel'
from hsgame.cards.spells.druid import (
Innervate,
Moonfire,
Claw,
Naturalize,
Savagery,
MarkOfTheWild,
PowerOfTheWild,
WildGrowth,
Wrath,
HealingTouch,
MarkOfNature,
SavageRoar,
Bite,
SoulOfTheForest,
Swipe,
Nourish,
Starfall,
... | __author__ = 'Daniel'
from hsgame.cards.spells.druid import (
Innervate,
Moonfire,
Claw,
Naturalize,
Savagery,
MarkOfTheWild,
PowerOfTheWild,
WildGrowth,
Wrath,
HealingTouch,
MarkOfNature,
SavageRoar,
Bite,
SoulOfTheForest,
Swipe,
Nourish,
Starfall,
... | mit | Python |
113e5b8a524450c71e60d7003a1c3cf0c75226a2 | Bump version | mollie/mollie-api-python | mollie/api/version.py | mollie/api/version.py | # In this file the version of the package is defined.
# Don't change the syntax of the definition unless you know what you're doing, because this file is
# processed by python imports and by regular expressions. The version is defined as a string in the
# regular semantic versioning scheme (major,minor,patch).
VERSIO... | # In this file the version of the package is defined.
# Don't change the syntax of the definition unless you know what you're doing, because this file is
# processed by python imports and by regular expressions. The version is defined as a string in the
# regular semantic versioning scheme (major,minor,patch).
VERSIO... | bsd-2-clause | Python |
2fe4e433ff0b95b421a7106099b54d7e25189cc5 | Add an example how to parse object literals | rspivak/slimit,moses-palmer/slimit,slideclick/slimit,luiseduardohdbackup/slimit,cainiaocome/slimit | src/slimit/visitors/nodevisitor.py | src/slimit/visitors/nodevisitor.py | ###############################################################################
#
# Copyright (c) 2011 Ruslan Spivak
#
# 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, inc... | ###############################################################################
#
# Copyright (c) 2011 Ruslan Spivak
#
# 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, inc... | mit | Python |
95aa186535d392d95c4353a0e434a0d470ace886 | add isadmin | hackatbrown/2015.hackatbrown.org,hackatbrown/2015.hackatbrown.org,hackatbrown/2015.hackatbrown.org | hack-at-brown-2015/csv_export.py | hack-at-brown-2015/csv_export.py | import csv
import webapp2
from registration import Hacker, hacker_keys, personal_info_keys
from hacker_page import computeStatus
from config import onTeam
from config import isAdmin
def dict_from_hacker(hacker, include_keys):
d = {key: getattr(hacker, key, None) for key in include_keys}
d['status'] = computeSt... | import csv
import webapp2
from registration import Hacker, hacker_keys, personal_info_keys
from hacker_page import computeStatus
from config import onTeam
def dict_from_hacker(hacker, include_keys):
d = {key: getattr(hacker, key, None) for key in include_keys}
d['status'] = computeStatus(hacker)
return d
... | mit | Python |
cde853709f35c1d7c45f416bb9d4a874d82945b4 | Use our own proxy agent to avoid getting the full URI in the request path. | praekeltfoundation/certbot,praekeltfoundation/certbot | certbot/tests/test_server.py | certbot/tests/test_server.py | import json
import treq
from twisted.internet.defer import inlineCallbacks
from twisted.protocols.loopback import _LoopbackAddress
from twisted.trial.unittest import TestCase
from twisted.web.client import ProxyAgent, URI
from twisted.web.server import Site
from txfake import FakeServer
from uritools import uricompo... | import json
import treq
from twisted.internet.defer import inlineCallbacks
from twisted.protocols.loopback import _LoopbackAddress
from twisted.trial.unittest import TestCase
from twisted.web.client import ProxyAgent
from twisted.web.server import Site
from txfake import FakeServer
from uritools import uricompose
f... | mit | Python |
ed75c72a0129ffbf487881711171044510829852 | add find_between function, between two string | encorehu/nlp | nlp/extractors/base.py | nlp/extractors/base.py | import re
class BaseExtractor(object):
def _extract(self, html):
result =[]
return result
def find_between(self, text, s1, s2=None):
if not s1:
raise Exception('s1 is None!')
pos1 = text.find(s1)
if s2:
pos2 = text.find(s2)
... | import re
class BaseExtractor(object):
def _extract(self, html):
result =[]
return result
def extract(self, html):
return self._extract(html)
class BaseRegexExtractor(object):
regex = None
def _extract(self, html, regex=None):
result =[]
if re... | mit | Python |
90e4bd25b008cfaa7208bdcfc3997be77469a4c9 | add reduce=False to all calls of case/by_owner view, now that it has a reduce | dimagi/commcare-hq,puttarajubr/commcare-hq,gmimano/commcaretest,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,gmimano/commcaretest,qedsoftware/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,gmimano/commcaretest,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbi... | corehq/apps/cloudcare/api.py | corehq/apps/cloudcare/api.py | from corehq.apps.users.models import CouchUser
from casexml.apps.case.models import CommCareCase
from corehq.apps.app_manager.models import ApplicationBase, Application
def get_all_cases(domain, include_closed=False):
"""
Get all cases in a domain.
"""
cases = CommCareCase.view('hqcase/types_by_domain'... | from corehq.apps.users.models import CouchUser
from casexml.apps.case.models import CommCareCase
from corehq.apps.app_manager.models import ApplicationBase, Application
def get_all_cases(domain, include_closed=False):
"""
Get all cases in a domain.
"""
cases = CommCareCase.view('hqcase/types_by_domain'... | bsd-3-clause | Python |
e36477ca5d571bcd5449f661973f0d7321057c2f | enable manifest static files storage | liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin,liqd/a4-meinberlin | meinberlin/config/settings/production.py | meinberlin/config/settings/production.py | from .base import *
COMPRESS = True
COMPRESS_OFFLINE = True
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
DEBUG = False
try:
from .local import *
except ImportError:
pass
try:
from .polygons import *
except ImportError:
pass
try:
INSTALLED_APPS += tuple(A... | from .base import *
COMPRESS = True
COMPRESS_OFFLINE = True
DEBUG = False
try:
from .local import *
except ImportError:
pass
try:
from .polygons import *
except ImportError:
pass
try:
INSTALLED_APPS += tuple(ADDITIONAL_APPS)
except NameError:
pass
| agpl-3.0 | Python |
811d39b9a2a75f8f1eaa11270982afdc3fa285d3 | Fix wrong import (wanted rawxz url retrieving func, not qcow2 func) | fedora-infra/fedimg,fedora-infra/fedimg | fedimg/uploader.py | fedimg/uploader.py | #!/bin/env python
# -*- coding: utf8 -*-
import koji
import fedimg
from fedimg.services.ec2 import EC2Service
from fedimg.util import get_rawxz_url
def upload(builds):
""" Takes a list of one or more Koji build IDs (passed to it from
consumer.py) and sends the appropriate image files off to cloud
servi... | #!/bin/env python
# -*- coding: utf8 -*-
import koji
import fedimg
from fedimg.services.ec2 import EC2Service
from fedimg.util import get_qcow2_files
def upload(builds):
""" Takes a list of one or more Koji build IDs (passed to it from
consumer.py) and sends the appropriate image files off to cloud
ser... | agpl-3.0 | Python |
a766617424c54049a2392e22a066805e17a5c696 | Fix for boolean search query. | kmshi/miroguide,kmshi/miroguide,kmshi/miroguide | channelguide/guide/search.py | channelguide/guide/search.py | """search channels."""
from channelguide import util
from channelguide.guide.models import Channel, ItemSearchData
from sqlhelper import sql
from sqlhelper.sql import clause
class SearchScore(clause.Clause):
def __init__(self, table, terms):
query = ' '.join(terms)
self.text = ('(MATCH(#table#.impo... | """search channels."""
from channelguide import util
from channelguide.guide.models import Channel, ItemSearchData
from sqlhelper import sql
from sqlhelper.sql import clause
class SearchScore(clause.Clause):
def __init__(self, table, terms):
query = ' '.join(terms)
self.text = ('(MATCH(#table#.impo... | agpl-3.0 | Python |
7fc3952a23f0fb8d9056d1e05af7203a5e4a375c | test custom handling on Index class | macbre/index-digest,macbre/index-digest | indexdigest/test/formatters/test_yaml.py | indexdigest/test/formatters/test_yaml.py | import yaml
from unittest import TestCase
from indexdigest.schema import Index
from indexdigest.utils import LinterEntry
from indexdigest.formatters import format_yaml
from . import FormatterTestMixin
class TestPlainFormatter(TestCase, FormatterTestMixin):
def test_formatter(self):
out = format_yaml(se... | import yaml
from unittest import TestCase
from indexdigest.formatters import format_yaml
from . import FormatterTestMixin
class TestPlainFormatter(TestCase, FormatterTestMixin):
def test_formatter(self):
out = format_yaml(self.get_database_mock(), self.get_reports_mock())
print(out)
# ... | mit | Python |
e205447b61c8f0c7ce940cbf2b37f97032a592df | bump version | realms-team/solmanager,realms-team/basestation-fw,realms-team/solmanager,realms-team/solmanager,realms-team/solmanager | solmanager_version.py | solmanager_version.py | VERSION = (1, 2, 2, 0)
| VERSION = (1, 2, 1, 0)
| bsd-3-clause | Python |
69a3691e0f220949b3bcb9aa8dbfd20dc7b57d36 | Change imap-notify script | Gentux/imap-cli,Gentux/imap-cli | imap_cli/scripts/imap-notify.py | imap_cli/scripts/imap-notify.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Use IMAP CLI to gt a summary of IMAP account state."""
import logging
import os
import sys
import time
import docopt
import pynotify
import imap_cli
from imap_cli import config
app_name = os.path.splitext(os.path.basename(__file__))[0]
usage = """Usage: imap-cli... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Use IMAP CLI to gt a summary of IMAP account state."""
import logging
import os
import sys
import time
import docopt
import pynotify
import imap_cli
from imap_cli import config
app_name = os.path.splitext(os.path.basename(__file__))[0]
usage = """Usage: imap-cli... | mit | Python |
0bdb9322ea1c59650873f57686c7582382b70236 | change home to not conflict with prelogin url | qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq | corehq/apps/hqwebapp/urls.py | corehq/apps/hqwebapp/urls.py | from django.conf.urls import *
from corehq.apps.domain.views import PublicSMSRatesView
urlpatterns = patterns(
'corehq.apps.hqwebapp.views',
(r'^$', 'redirect_to_default'),
url(r'^homepage/$', 'redirect_to_default', name='homepage'),
url(r'^default_landing/$', 'landing_page', name='landing_page'),
... | from django.conf.urls import *
from corehq.apps.domain.views import PublicSMSRatesView
urlpatterns = patterns(
'corehq.apps.hqwebapp.views',
url(r'^homepage/$', 'redirect_to_default', name='homepage'),
url(r'^home/$', 'landing_page', name='landing_page'),
url(r'^crossdomain.xml$', 'yui_crossdomain', na... | bsd-3-clause | Python |
9fbe6657e638c8492a62ba23ead942a794fbdb8a | Change configure test to match current config. | kyle-long/pyshelf,kyle-long/pyshelf,not-nexus/shelf,not-nexus/shelf | tests/configure_test.py | tests/configure_test.py | import pyproctor
import pyshelf.configure as configure
import os
import yaml
import errno
import copy
class ConfigureTest(pyproctor.TestBase):
def setUp(self):
super(ConfigureTest, self).setUp()
self.path = os.path.dirname(os.path.realpath(__file__)) + "/data/config.yaml"
self.app = type("... | import pyproctor
import pyshelf.configure as configure
import os
import yaml
import errno
import copy
class ConfigureTest(pyproctor.TestBase):
def setUp(self):
super(ConfigureTest, self).setUp()
self.path = os.path.dirname(os.path.realpath(__file__)) + "/data/config.yaml"
self.app = type("... | mit | Python |
908100c967237c78e4fcc84a6a24dc6622c000b1 | Remove init print | oscar6echo/ezhc,oscar6echo/ezhc,oscar6echo/ezhc | ezhc/__init__.py | ezhc/__init__.py |
from ._config import load_js_libs
from ._highcharts import Highcharts
from ._highstock import Highstock
from . import sample
from . import build
from ._clock import Clock
__all__ = ['Highcharts',
'Highstock',
'sample',
'build',
'Clock',
]
load_js_libs()
|
from ._config import load_js_libs
from ._highcharts import Highcharts
from ._highstock import Highstock
from . import sample
from . import build
from ._clock import Clock
__all__ = ['Highcharts',
'Highstock',
'sample',
'build',
'Clock',
]
load_js_libs()
pri... | mit | Python |
8511f485b43e3d1a69b3a2d0b88e6a12ce3ad085 | Update jokes_eus.py | bennuttall/pyjokes,pyjokes/pyjokes | pyjokes/jokes_eus.py | pyjokes/jokes_eus.py | # -*- coding: utf-8 -*-
neutral = [
'Zer dira 8 Bocabits? BocaByte bat ',
'Zer esaten dio bit batek besteari? Busean ikusten gara!',
'Zer da terapeuta bat? - 1024 Gigapeuta',
]
adult = [
'',
]
jokes_eus = {
'neutral': neutral,
'adult': adult,
'all': neutral + adult,
}
| # -*- coding: utf-8 -*-
neutral = [
'Zer dira 8 Bocabits? BocaByte bat ',
'Zer esaten dio bit batek besteari? Busean ikusten gara!',
'Zer da terapeuta bat? - 1024 Gigapeuta',
'txiste bat geio',
'beste bat neutrala',
'eta beste bat',
# 'Abrese o elevador e hai un programador dentro. Pregunta... | bsd-3-clause | Python |
5252b5c4d9b78190bd4f3b8ac9299a64f87f4b3e | add page editing | anqxyr/pyscp,anqxyr/pyscp | wikidot.py | wikidot.py | #!/usr/bin/env python3
###############################################################################
# Module Imports
###############################################################################
import requests
###############################################################################
# Global connection s... | #!/usr/bin/env python3
###############################################################################
# Module Imports
###############################################################################
import requests
###############################################################################
# Global connection s... | mit | Python |
2dd8a13ff689d6101efd9ee13e8b202b4a1b665f | add test for expired method | byteweaver/django-coupons,byteweaver/django-coupons | coupons/tests/test_models.py | coupons/tests/test_models.py | from datetime import timedelta
import re
from django.utils import timezone
from django.test import TestCase
from coupons.models import Coupon
from coupons.settings import CODE_LENGTH, CODE_CHARS
class CouponTestCase(TestCase):
def test_generate_code(self):
self.assertIsNotNone(re.match("^[%s]{%d}" % (CO... | import re
from django.test import TestCase
from coupons.models import Coupon
from coupons.settings import CODE_LENGTH, CODE_CHARS
class CouponTestCase(TestCase):
def test_generate_code(self):
self.assertIsNotNone(re.match("^[%s]{%d}" % (CODE_CHARS, CODE_LENGTH,), Coupon.generate_code()))
def test_s... | bsd-3-clause | Python |
e23b146f613ed6e0090b0ef1f895ee1785e56f31 | Use block quotes for Markov-chain plugin | kvchen/keffbot-py,kvchen/keffbot | plugins/brian.py | plugins/brian.py | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... | """Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def gener... | mit | Python |
742036fb6be911d46b7f762901b4bde2b7ee7e0d | Add test that correct name files are used | treyhunner/names,treyhunner/names | test_names.py | test_names.py | #!/usr/bin/env python
from os.path import abspath, join, dirname
from unittest import TestCase, main
from collections import defaultdict
import names
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'test1': full_path('test/file1.txt'),
}
class patch_file:
def __init__(sel... | #!/usr/bin/env python
from os.path import abspath, join, dirname
from unittest import TestCase, main
from collections import defaultdict
import names
full_path = lambda filename: abspath(join(dirname(__file__), filename))
FILES = {
'test1': full_path('test/file1.txt'),
}
class patch_file:
def __init__(sel... | mit | Python |
5b10b83b486bc9f0dd81929e709e234a323c0f5e | Update version number and package info. | myDevicesIoT/Cayenne-Agent,myDevicesIoT/Cayenne-Agent | myDevices/__init__.py | myDevices/__init__.py | """
This package contains the Cayenne agent, which is a full featured client for the Cayenne IoT project builder: https://cayenne.mydevices.com. It sends system information as well as sensor and actuator data and responds to actuator messages initiated from the Cayenne dashboard and mobile apps.
"""
__version__ = '1.1.... | """
This package contains the Cayenne agent, which is a full featured client for the Cayenne IoT project builder: https://cayenne.mydevices.com.
"""
__version__ = '0.2.1'
| mit | Python |
535e8f4daef75b02d3ed7c223b46e00988307032 | add comments and rearranged tests for readability. removed redundant tests. | constanthatz/data-structures | test_queue.py | test_queue.py | from __future__ import unicode_literals
import pytest
from queue import Element
from queue import Queue
def test_element_init():
''' Test Element init. '''
m = Element(3)
assert m.val == 3
assert m.behind is None
def test_queue_init():
''' Test Queue init. '''
l = Queue()
assert l.front ... | from __future__ import unicode_literals
import pytest
from queue import Element
from queue import Queue
def test_element_init():
m = Element(3)
assert m.val == 3
assert m.behind is None
def test_queue_init():
l = Queue()
assert l.front is None
assert l.back is None
def test_queue_enqueue()... | mit | Python |
48ecde69f9ba1f4cdec2ee5e73f26114fb66e55e | use render for polls template | Lukyth/django-test,Lukyth/django-test | mysite/polls/views.py | mysite/polls/views.py | from django.shortcuts import render
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def detail(req... | from django.http import HttpResponse
from django.template import RequestContext, loader
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
'latest_question_l... | bsd-3-clause | Python |
00166e6e31582600439c1cdec1e20263306f475a | Stop cutting off +ud words | svkampen/James | plugins/urban.py | plugins/urban.py | """
Get definitions from urbandictionary
"""
from .util.decorators import command
import requests
import traceback
@command('urban', 'urbandictionary', 'ud')
def urban_lookup(bot, nick, target, chan, arg):
''' UrbanDictionary lookup. '''
if not arg:
return bot._msg(chan, "Usage: urban [phrase] [index?... | """
Get definitions from urbandictionary
"""
from .util.decorators import command
import requests
import traceback
@command('urban', 'urbandictionary', 'ud')
def urban_lookup(bot, nick, target, chan, arg):
''' UrbanDictionary lookup. '''
if not arg:
return bot._msg(chan, "Usage: urban [phrase] [index?... | mit | Python |
fe361d63e19951b036a180a79c8cff101a99ebee | remove mutable default argument | sattelite/OmNomNom,ekeih/OmNomNom,ekeih/OmNomNom | stats/tasks.py | stats/tasks.py | import influxdb
from backend.backend import app
from celery.utils.log import get_task_logger
from os import environ
logger = get_task_logger(__name__)
host = environ.get('OMNOMNOM_INFLUXDB_HOST')
database = environ.get('OMNOMNOM_INFLUXDB_DATABASE')
if host and database:
influxdb_client = influxdb.InfluxDBClien... | import influxdb
from backend.backend import app
from celery.utils.log import get_task_logger
from os import environ
logger = get_task_logger(__name__)
host = environ.get('OMNOMNOM_INFLUXDB_HOST')
database = environ.get('OMNOMNOM_INFLUXDB_DATABASE')
if host and database:
influxdb_client = influxdb.InfluxDBClien... | agpl-3.0 | Python |
1082946054c0298f51762b0548e840f4f3f8f0b6 | Add tests for signin page | bafana5/wKRApp,bafana5/wKRApp,bafana5/wKRApp | test_views.py | test_views.py | from wKRApp import app
import unittest
class FlaskTestCase(unittest.TestCase):
# Ensure that flask was set up correctly
def test_index(self):
tester = app.test_client(self)
response = tester.get('/', content_type='html/text')
self.assertEqual(response.status_code, 200)
# Ensure th... | from wKRApp import app
import unittest
class FlaskTestCase(unittest.TestCase):
# Ensure that flask was set up correctly
def test_index(self):
tester = app.test_client(self)
response = tester.get('/', content_type='html/text')
self.assertEqual(response.status_code, 200)
# Ensure that the login page loads cor... | mit | Python |
72046d8abbaca77ce61a4c780d5d0b9a2a193be4 | update rabobank mapping to reflect the current CSV files | reubano/csv2ofx,reubano/csv2ofx | csv2ofx/mappings/rabobank.py | csv2ofx/mappings/rabobank.py | # coding: utf-8
from __future__ import (
absolute_import, division, print_function, unicode_literals)
from operator import itemgetter
# example to convert:
# csv2ofx -m rabobank -E ISO-8859-1 CSV_O_20200630_014400.csv CSV_O_20200630_014400.ofx
def date_func(trxn):
tag = trxn['Datum']
tag = tag.split('-')
... | # coding: utf-8
from __future__ import (
absolute_import, division, print_function, unicode_literals)
from operator import itemgetter
def date_func(trxn):
tag = trxn['Datum']
# Chop up the ISO date and put it in ridiculous M/D/Y order
return '{}/{}/{}'.format(tag[1], tag[2], tag[0])
mapping = {
... | mit | Python |
e7b41c1e23bf30dc0f0bf3f989c5011a44fc4149 | complete divine_winner; now returns tuple of w/l tuples | BradleyMoore/RiskRoll | riskroll.py | riskroll.py | from app.RollDice import roll
def get_number_of_combatants():
"""Take no input and return tuple of ints."""
num_of_attackers = [1,2,3]
num_of_defenders = [1,2]
attackers = 0
defenders = 0
while attackers not in num_of_attackers:
attackers = int(raw_input('How many attackers? [1,2,3]\n... | from app.RollDice import roll
def get_number_of_combatants():
"""Take no input and return tuple of ints."""
num_of_attackers = [1,2,3]
num_of_defenders = [1,2]
attackers = 0
defenders = 0
while attackers not in num_of_attackers:
attackers = int(raw_input('How many attackers? [1,2,3]\n... | mit | Python |
9071b96c7fa253d44f055766c963c26ed197edd2 | Handle github ghost users | glasnt/octohat,LABHR/octohatrack | octohatrack_graphql.py | octohatrack_graphql.py | #!/usr/bin/env python
"""
Quick implementation of octhatrack with GraphQL
USAGE
./octohatrack_graphql.py user/repo
LIMITATIONS
Limitations in the github graphql api means that this will only return the:
- last 100 issues
- last 100 comments per issue
- last 100 pull requests
- last 100 co... | #!/usr/bin/env python
"""
Quick implementation of octhatrack with GraphQL
USAGE
./octohatrack_graphql.py user/repo
LIMITATIONS
Limitations in the github graphql api means that this will only return the:
- last 100 issues
- last 100 comments per issue
- last 100 pull requests
- last 100 co... | bsd-3-clause | Python |
21eb84b60a6324174163b062a444b08df15527ac | fix typo in __init__ | cmshobe/landlab,ManuSchmi88/landlab,landlab/landlab,cmshobe/landlab,Carralex/landlab,landlab/landlab,RondaStrauch/landlab,cmshobe/landlab,ManuSchmi88/landlab,RondaStrauch/landlab,csherwood-usgs/landlab,RondaStrauch/landlab,Carralex/landlab,amandersillinois/landlab,Carralex/landlab,ManuSchmi88/landlab,amandersillinois/l... | landlab/components/__init__.py | landlab/components/__init__.py | from .chi_index import ChiFinder
from .diffusion import LinearDiffuser
from .fire_generator import FireGenerator
from .detachment_ltd_erosion import DetachmentLtdErosion
from .flexure import Flexure
from .flow_routing import FlowRouter, DepressionFinderAndRouter
from .nonlinear_diffusion import PerronNLDiffuse
from .ov... | from .chi_index import ChiFinder
from .diffusion import LinearDiffuser
from .fire_generator import FireGenerator
from .detachment_ltd_erosion import DetachmentLtdErosion
from .flexure import Flexure
from .flow_routing import FlowRouter, DepressionFinderAndRouter
from .nonlinear_diffusion import PerronNLDiffuse
from .ov... | mit | Python |
a288e0c4a2cc5aba2cbc50f52889f082f764f790 | fix typo | gisce/primestg | spec/MessageS_spec.py | spec/MessageS_spec.py | from expects import expect, raise_error, be_a
from primestg.message import MessageS
from lxml.objectify import ObjectifiedElement
from lxml.etree import XMLSyntaxError
with description('MessageS'):
with it('raise an error if isn\'t provided an XML'):
def callback():
MessageS('foo bar')
... | from expects import expect, raise_error, be_a
from primestg.message import MessageS
from lxml.objectify import ObjectifiedElement
from lxml.etree import XMLSyntaxError
with description('MessageS'):
with it('raise an error if isn\'t provided an XML'):
def callback():
MessageS('foo bar')
... | agpl-3.0 | Python |
11a21f4ce70cbd99b9a1b369f0ca6cada9934450 | Move hash256 to separate function | DvA-leopold/CrAB,DvA-leopold/CrAB | storage/utils.py | storage/utils.py | import hashlib
def hash256(hash_data: bytes):
return hashlib.sha256(hashlib.sha256(hash_data).digest()).digest() | import hashlib
def hash256(hash_data):
return hashlib.sha256(hashlib.sha256(hash_data).digest()).digest() | mpl-2.0 | Python |
ff303bcca44cbeb1fa35b9de8fc3198a5e9de17c | add delete method | 2gis/stf-utils | stf-connect.py | stf-connect.py | from json import dumps, loads
import logging
import requests
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
API_URL = "http://stf.auto.ostack.test/api/v1"
OAUTH_TOKEN = "e1cb89b5108348dd9251b7848948084809dad3a2e1084d8ebc4bf6663381d56e"
devices_path = "/devices"
user_devices_path = "/user/d... | from json import dumps, loads
import logging
import requests
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
API_URL = "http://stf.auto.ostack.test/api/v1"
OAUTH_TOKEN = "e1cb89b5108348dd9251b7848948084809dad3a2e1084d8ebc4bf6663381d56e"
devices_path = "/devices"
user_devices_path = "/user/d... | mit | Python |
6d85cf76e1388d7778372e9e3ede673aed6132c8 | Fix bug preventing recurisive serialization. | scrapinghub/flatson | flatson/flatson.py | flatson/flatson.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
from collections import namedtuple
import json
class Field(namedtuple('Field', 'name getter schema')):
def is_simple_list(self):
simple_types = ('number', 'string')
return self.schema.get('type') == '... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function, absolute_import
from collections import namedtuple
import json
class Field(namedtuple('Field', 'name getter schema')):
def is_simple_list(self):
simple_types = ('number', 'string')
return self.schema.get('type') == '... | bsd-3-clause | Python |
5b0eda9dac7b542fecdc9db1c1d4f3440515fb10 | Add TODO in j2.py | google/j2cl,google/j2cl,google/j2cl,google/j2cl,google/j2cl | dev/j2.py | dev/j2.py | #!/usr/bin/python3
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | #!/usr/bin/python3
# Copyright 2021 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | apache-2.0 | Python |
8063150e9c1f99e91765a24931cbdb1d07e36b0f | Add contrib.handlers to installed apps and allow running a single test with runtests. | ewheeler/rapidsms-timelines,caktus/rapidsms-appointments,ewheeler/rapidsms-timelines,ewheeler/rapidsms-timelines,caktus/rapidsms-appointments | runtests.py | runtests.py | #!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
... | #!/usr/bin/env python
import sys
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
INSTALLED_APPS=(
... | bsd-3-clause | Python |
a5a336298db6120a73bbd30c5c5b06ad829110d7 | Correct import order on __init__ | elsonidoq/fito | fito/__init__.py | fito/__init__.py | from specs.base import PrimitiveField, SpecField, Spec
from operation_runner import OperationRunner
from operations.decorate import as_operation
from operations.operation import Operation
from data_store.dict_ds import DictDataStore
| from specs.base import PrimitiveField, SpecField, Spec
from operations.decorate import as_operation
from operations.operation import Operation
from operation_runner import OperationRunner
from data_store.dict_ds import DictDataStore
| mit | Python |
97a2618695658d2e32e1c7106662cfa5f8a2264f | update runtests | Tivix/django-spam | runtests.py | runtests.py | # This file mainly exists to allow python setup.py test to work.
import os
import sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
test_dir = os.path.join(os.path.dirname(__file__), 'tests')
sys.path.insert(0, test_dir)
import django
from django.test.utils import get_runner
from django.conf import set... | import os
import sys
import django
from django.conf import settings
from django.test.utils import get_runner
if __name__ == "__main__":
os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings'
django.setup()
TestRunner = get_runner(settings)
test_runner = TestRunner()
failures = test_runner.ru... | mit | Python |
52636e42163da5b6009991591d1bff9f58f3e706 | fix tests always "succeed" | rkhleics/wagtailmenus,rkhleics/wagtailmenus,ababic/wagtailmenus,ababic/wagtailmenus,ababic/wagtailmenus,rkhleics/wagtailmenus | runtests.py | runtests.py | #!/usr/bin/env python
import argparse
import os
import sys
import warnings
from django.core.management import execute_from_command_line
os.environ['DJANGO_SETTINGS_MODULE'] = 'wagtailmenus.settings.testing'
def make_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--deprecation',
... | #!/usr/bin/env python
import argparse
import os
import sys
import warnings
from django.core.management import execute_from_command_line
os.environ['DJANGO_SETTINGS_MODULE'] = 'wagtailmenus.settings.testing'
def make_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--deprecation',
... | mit | Python |
b4e77339665aa10ba7eda1d1c458e6f5e1626dd7 | fix gi version warnings | nkoep/dotfiles,nkoep/dotfiles,nkoep/dotfiles | python/.pystartup.py | python/.pystartup.py | import sys
import os
if sys.version_info.major == 2:
import numpy as np
import numpy.linalg as la
import numpy.random as rnd
else:
import gi
from importlib import import_module
modules = [("GObject", None), ("GLib", None) , ("Gio", None),
("Gtk", "3.0"), ("Gst", "1.0")]
glo... | import sys
import os
if sys.version_info.major == 2:
import numpy as np
import numpy.linalg as la
import numpy.random as rnd
else:
from importlib import import_module
globals_ = globals()
for module in "GObject GLib Gio Gtk Gst".split():
try:
globals_[module] = import_modul... | apache-2.0 | Python |
cb5b65f89d9d47abd1c131ea5248250318a492eb | add stddev to wrk | squeaky-pl/japronto,squeaky-pl/japronto,squeaky-pl/japronto,squeaky-pl/japronto,squeaky-pl/japronto | do_wrk.py | do_wrk.py | import argparse
import sys
import asyncio as aio
from asyncio.subprocess import PIPE, STDOUT
import statistics
import shlex
import uvloop
import cpu
import buggers
def run_wrk(loop, endpoint=None):
endpoint = endpoint or 'http://localhost:8080'
wrk_fut = aio.create_subprocess_exec(
'./wrk', '-t', '1... | import argparse
import sys
import asyncio as aio
from asyncio.subprocess import PIPE, STDOUT
import statistics
import shlex
import uvloop
import cpu
import buggers
def run_wrk(loop, endpoint=None):
endpoint = endpoint or 'http://localhost:8080'
wrk_fut = aio.create_subprocess_exec(
'./wrk', '-t', '1... | mit | Python |
80100a1e99d89e4246baa646b666cae1b567f09f | Update gift_exchange.py | brianboonstra/gift_exchange | gift_exchange.py | gift_exchange.py | import random
"""
This module randomly makes gift assignments among a group of
second cousins, ensuring no one is assigned a sibling or
first cousin.
The more unbalanced the family branches are, the higher the
likelihood the script will fail with
ValueError: sample larger than population
in which case runn... | import random
"""
This module randomly makes gift assignments among a group of
second cousins, ensuring no one is assigned a sibling or
first cousin.
The more unbalanced the family branches are, the higher the
likelihood the script will fail with
ValueError: sample larger than population
in which case runn... | bsd-3-clause | Python |
a736c029ab9b19932c18cd1917442606cef1b6fc | Update Atari Game testing script | sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet,sxjscience/mxnet | example/dqn/tests/test_atari_game.py | example/dqn/tests/test_atari_game.py | from ..games import AtariGame
import numpy
import time
import mxnet as mx
import mxnet.ndarray as nd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
replay_start_size = 1000
game = AtariGame(resize_mode='scale', replay_start_size=replay_start_size)
game.start()
start = time.time()
totoal_time_step = 1000000... | from ..games import AtariGame
import numpy
import time
import mxnet as mx
import mxnet.ndarray as nd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
replay_start_size = 1000
game = AtariGame(resize_mode='scale', replay_start_size=replay_start_size)
game.start()
start = time.time()
totoal_time_step = 10000
m... | apache-2.0 | Python |
4cef3788a19b9ad7059184a39accd2b551407de4 | Check bench mode==run with fixed block shape | opesci/devito,opesci/devito | tests/test_benchmark.py | tests/test_benchmark.py | from subprocess import check_call
def run_cmd(command, problem, so, shape, nbpml, *extra):
args = ["python", "../benchmarks/user/benchmark.py", command]
args.extend(["-P", str(problem)])
args.extend(["-so", str(so)])
args.extend(["-d"] + [str(i) for i in shape])
args.extend(["--nbpml", str(nbpml)]... | import os
from subprocess import check_call
import pytest
def run(command, problem, so, shape, nbpml, *extra):
args = ["python", "../benchmarks/user/benchmark.py", command]
args.extend(["-P", str(problem)])
args.extend(["-so", str(so)])
args.extend(["-d"] + [str(i) for i in shape])
args.extend(["... | mit | Python |
b31686ca7b201c953a4a7a35618a73a066db3b69 | Update runtests.py | caktus/django-email-bandit,caktus/django-email-bandit | runtests.py | runtests.py | #!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
},
MIDDLEWARE_CLASSE... | #!/usr/bin/env python
import sys
import django
from django.conf import settings
if not settings.configured:
settings.configure(
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'test.db',
}
},
MIDDLEWARE_CLASSE... | bsd-3-clause | Python |
9a14fec9a4bb931b41ab62988975e5688f16573d | Fix permalinks test which was breaking other tests. | lewiscollard/cms,jamesfoley/cms,danielsamuels/cms,lewiscollard/cms,dan-gamble/cms,dan-gamble/cms,lewiscollard/cms,danielsamuels/cms,dan-gamble/cms,jamesfoley/cms,danielsamuels/cms,jamesfoley/cms,jamesfoley/cms | cms/tests/test_permalinks.py | cms/tests/test_permalinks.py | from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import TestCase
from ..permalinks import expand, resolve, PermalinkError
class TestPermalinkModel(models.Model):
d... | from django.contrib.contenttypes.models import ContentType
from django.core import urlresolvers
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.test import TestCase
from ..permalinks import expand, resolve, PermalinkError
class TestPermalinkModel(models.Model):
d... | bsd-3-clause | Python |
24341ee3dabcbad751c849ef8007b669bdce5141 | Fix broken Mercenaries bountyxml test | HearthSim/python-hearthstone | tests/test_bountyxml.py | tests/test_bountyxml.py | from hearthstone import bountyxml
def test_bountyxml_load():
bounty_db, _ = bountyxml.load()
assert bounty_db
assert bounty_db[68].boss_name == "The Anointed Blades"
assert bounty_db[58].region_name == "The Barrens"
| from hearthstone import bountyxml
def test_bountyxml_load():
bounty_db, _ = bountyxml.load()
assert bounty_db
assert bounty_db[47].boss_name == "Cap'n Hogger"
assert bounty_db[58].region_name == "The Barrens"
| mit | Python |
32efe7a0365738f982030f7c5be3b702dbac87c8 | Add only_http_implementation and only_websocket_implementation methods | devicehive/devicehive-python | tests/test.py | tests/test.py | from devicehive import Handler
from devicehive import DeviceHive
import pytest
class TestHandler(Handler):
"""Test handler class."""
def handle_connect(self):
if not self.options['handle_connect'](self):
self.api.disconnect()
def handle_event(self, event):
pass
class Test(o... | from devicehive import Handler
from devicehive import DeviceHive
class TestHandler(Handler):
"""Test handler class."""
def handle_connect(self):
if not self.options['handle_connect'](self):
self.api.disconnect()
def handle_event(self, event):
pass
class Test(object):
""... | apache-2.0 | Python |
d1a43bb960d695ce74d38e9bd95218f655f057a0 | Remove manual indexing of args | oilshell/blog-code,oilshell/blog-code,oilshell/blog-code,oilshell/blog-code,oilshell/blog-code,oilshell/blog-code,oilshell/blog-code | forth-like/demo.py | forth-like/demo.py | #!/usr/bin/python
"""
demo.py -- Experimenting with expressing this forth-like pattern in Python.
It appears it can be done with varargs and splatting.
"""
import sys
import time
def retry(n, f, *args):
for i in range(n):
f(*args)
def hello_sleep(t):
print 'hello'
time.sleep(t)
def retry_demo():
ret... | #!/usr/bin/python
"""
demo.py -- Experimenting with expressing this forth-like pattern in Python.
It appears it can be done with varargs and splatting.
"""
import sys
import time
def retry(*args):
n = args[0]
f = args[1]
a = args[2:]
for i in range(n):
f(*a)
def hello_sleep(*args):
print 'hello'
... | apache-2.0 | Python |
9083a17ed8395bf29dd616e647d26ea7ef76229d | include the active (site) particles in the polymerization fraction | pdebuyl/cg_md_polymerization,pdebuyl/cg_md_polymerization | code/analyse_chain_lammps.py | code/analyse_chain_lammps.py | #!/usr/bin/env python
import sys
import os
import os.path
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('dirs', type=str, nargs='+',
help='directories containing simulation files')
parser.add_argument('--rate', type=float, default=0.1)
parser.add_argument('--sites', type=... | #!/usr/bin/env python
import sys
import os
import os.path
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('dirs', type=str, nargs='+',
help='directories containing simulation files')
parser.add_argument('--rate', type=float, default=0.1)
parser.add_argument('--sites', type=... | bsd-3-clause | Python |
e8d16d9df9a6c05551e4fbf14fc7c41aaf7323a9 | Remove sys import | thomasyu888/synapsePythonClient | synapseutils/describe_functions.py | synapseutils/describe_functions.py | from collections import defaultdict
import json
import os
import synapseclient
from synapseclient import table
def _open_entity_as_df(syn, entity: str):
"""
Gets a csv or tsv Synapse entity and returns it as a dataframe
:param syn: synapse object
:param entity: a synapse entity to be extracted and co... | from collections import defaultdict
import json
import os
import sys
import synapseclient
from synapseclient import table
def _open_entity_as_df(syn, entity: str):
"""
Gets a csv or tsv Synapse entity and returns it as a dataframe
:param syn: synapse object
:param entity: a synapse entity to be extra... | apache-2.0 | Python |
fdb67705d5990cd2da4be57c76cd0dbbb46a85a8 | Fix tests for urls | aaronn/django-rest-framework-passwordless,aaronn/django-rest-framework-passwordless | tests/urls.py | tests/urls.py | from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from drfpasswordless.settings import api_settings
from drfpasswordless.views import (ObtainEmailCallbackToken,
ObtainMobileCallbackToken,
ObtainAuthTokenFromCa... | from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from drfpasswordless.views import (ObtainEmailCallbackToken,
ObtainMobileCallbackToken,
ObtainAuthTokenFromCallbackToken,
... | mit | Python |
837c243b33822ca8c0312bf2d7038e367efbc0c7 | Fix for already removed hooks when reloading | sciyoshi/dotmod | dotmod.py | dotmod.py | import os
import imp
import sys
class DotImportHook:
def find_module(self, fullname, path=None):
print('FINDING', fullname, 'in', path)
bits = fullname.split('.')
if len(bits) <= 1:
return
for folder in sys.path:
if os.path.exists(os.path.join(folder, fullname)):
print('FOUND:', folder, fullname)... | import os
import imp
import sys
class DotImportHook:
def find_module(self, fullname, path=None):
print('FINDING', fullname, 'in', path)
bits = fullname.split('.')
if len(bits) <= 1:
return
for folder in sys.path:
if os.path.exists(os.path.join(folder, fullname)):
print('FOUND:', folder, fullname)... | mit | Python |
b5ac9f5cf13dc1eeeb124217031d060b2ec85a00 | support spaces in device identity (#58328) | thaim/ansible,thaim/ansible | lib/ansible/plugins/terminal/routeros.py | lib/ansible/plugins/terminal/routeros.py | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is d... | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible is d... | mit | Python |
0b15611eb0020bc2cdb4a4435756315b0bd97a21 | Fix errors with 2/3 FLO support | rtluckie/seria | seria/cli.py | seria/cli.py | # -*- coding: utf-8 -*-
import click
from .compat import StringIO, str, builtin_str
import seria
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--xml', 'out_fmt', flag_value='xml')
@click.option('--yaml', 'out_fmt', flag_value='yaml')
@c... | # -*- coding: utf-8 -*-
import click
from .compat import StringIO
import seria
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--xml', 'out_fmt', flag_value='xml')
@click.option('--yaml', 'out_fmt', flag_value='yaml')
@click.option('--jso... | mit | Python |
69c6017506c1412aaf80bd0915180c8121b5084e | Update vis.py | njchiang/task-fmri-utils,njchiang/task-fmri-utils,njchiang/task-fmri-utils | fmri_core/vis.py | fmri_core/vis.py | # TODO : populate after development is done
from nilearn import plotting as nplt
from .utils import unmask_img
from numpy import allclose
from scipy.spatial.distance import squareform
from scipy.stats import rankdata
from numpy import eye
from matplotlib.pyplot import colorbar, imshow
from sklearn.preprocessing import ... | # TODO : populate after development is done
from nilearn import plotting as nplt
from .utils import unmask_img
from numpy import allclose
from scipy.spatial.distance import squareform
from scipy.stats import rankdata
from numpy import eye
from matplotlib.pyplot import colorbar, imshow
from sklearn.preprocessing import ... | mit | Python |
b2d4bf11b293073c4410ca1be98f657a30c35762 | Improve time complexity of solution | rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank | python/triple-sum.py | python/triple-sum.py | def get_num_special_triplets(list_a, list_b, list_c):
a_index = 0
c_index = 0
num_special_triplets = 0
for b in list_b:
while a_index < len(list_a) and list_a[a_index] <= b:
a_index += 1
while c_index < len(list_c) and list_c[c_index] <= b:
c_index += 1
... |
# A special triplet is defined as: a <= b <= c for
# a in list_a, b in list_b, and c in list_c
def get_num_special_triplets(list_a, list_b, list_c):
# remove duplicates and sort lists
list_a = sorted(set(list_a))
list_b = sorted(set(list_b))
list_c = sorted(set(list_c))
num_special_triplets = 0
... | mit | Python |
7bb841d31833397f3a9c6ef8058d47c9881fb060 | test for NamedDict subclass repr infinite recursion | pcattori/maps | tests/test_nameddict.py | tests/test_nameddict.py | from maps import NamedDict
import unittest
class NamedDictTest(unittest.TestCase):
def test_create(self):
nd = NamedDict({'a': 1, 'b': 2})
self.assertIsInstance(nd, NamedDict)
self.assertTrue(hasattr(nd, 'a'))
self.assertTrue(hasattr(nd, 'b'))
nd = NamedDict(a=1, b=2)
... | from maps import NamedDict
import unittest
class NamedDictTest(unittest.TestCase):
def test_create(self):
nd = NamedDict({'a': 1, 'b': 2})
self.assertIsInstance(nd, NamedDict)
self.assertTrue(hasattr(nd, 'a'))
self.assertTrue(hasattr(nd, 'b'))
nd = NamedDict(a=1, b=2)
... | mit | Python |
95d01fbc7a92708721c60c420dde0bf751a3e1de | set min length for usedFor value | Leits/openprocurement.relocation.api | openprocurement/relocation/api/models.py | openprocurement/relocation/api/models.py | # -*- coding: utf-8 -*-
from uuid import uuid4
from zope.interface import implementer, Interface
from pyramid.security import Allow
from couchdb_schematics.document import SchematicsDocument
from schematics.types import StringType, BaseType, MD5Type
from schematics.types.compound import ModelType, DictType
from schema... | # -*- coding: utf-8 -*-
from uuid import uuid4
from zope.interface import implementer, Interface
from pyramid.security import Allow
from couchdb_schematics.document import SchematicsDocument
from schematics.types import StringType, BaseType, MD5Type
from schematics.types.compound import ModelType, DictType
from schema... | apache-2.0 | Python |
d2518ff13f00b8d8792ee94549d8a3db444668cc | Fix bugs and add functions in sirius-ramp-test.py | lnls-fac/scripts,lnls-fac/scripts | bin/sirius-ramp-test.py | bin/sirius-ramp-test.py | #!/usr/bin/env python-sirius
# -*- coding: utf-8 -*-
import math
import time
import sys
from epics import caput
import matplotlib.pyplot as plt
from siriuspy.magnet.util import generate_normalized_ramp
max_current = 10.0 # [A]
ref_current_3gev = max_current/1.05 # [A]
ramp = ref_current_3gev * generate_normalized_ra... | #!/usr/bin/env python-sirius
# -*- coding: utf-8 -*-
import math
import time
import sys
from epics import caput
import matplotlib.pyplot as plt
from siriuspy.magnet.util import generate_normalized_ramp
max_current = 10.0 # [A]
ref_current_3gev = max_current/1.05 # [A]
ramp = ref_current_3gev * generate_normalized_ra... | mit | Python |
35b4e36ef92ce10ce24359c1e6c007d94c889ef0 | fix lint | QISKit/qiskit-sdk-py,QISKit/qiskit-sdk-py,QISKit/qiskit-sdk-py | qiskit/exceptions.py | qiskit/exceptions.py | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... | apache-2.0 | Python |
8629f06e84ea8ca8c73b65ac16ac08405b6a9f10 | Use quoted-printable for mail format | sayoun/pyvac,sayoun/pyvac,doyousoft/pyvac,sayoun/pyvac,doyousoft/pyvac,doyousoft/pyvac | pyvac/helpers/mail.py | pyvac/helpers/mail.py | # Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
import email
import email.charset
from email.mime.text import MIMEText
from email.utils import formatdate
import logging
log = logging.getLogger(__name__)
# Init email module properties, we prefer quoted-printable en... | # Import smtplib for the actual sending function
import smtplib
# Import the email modules we'll need
from email.mime.text import MIMEText
from email.utils import formatdate
import logging
log = logging.getLogger(__name__)
class SmtpWrapper(object):
""" Simple smtp class wrapper"""
host = None
port = Non... | bsd-3-clause | Python |
3ea05581bba8247d35a19e87a8f0394e44c03c99 | Write bind_to_entity() | MarquisLP/gamehappy | entity.py | entity.py | """This module contains base classes for defining game objects as well
as their individual components and behaviours.
"""
from pygame.sprite import Sprite
class Entity(Sprite):
"""An object within the game.
It contains several Component objects that are used to define how it
is handled graphically and ph... | """This module contains base classes for defining game objects as well
as their individual components and behaviours.
"""
from pygame.sprite import Sprite
class Entity(Sprite):
"""An object within the game.
It contains several Component objects that are used to define how it
is handled graphically and ph... | unlicense | Python |
77089cab24e2675465997a850451710ccd246e7b | Update tests | TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine | tests/test_test_data.py | tests/test_test_data.py | import os
import pytest
from selenium import webdriver
BROWSER = os.environ.get('BROWSER', 'Firefox')
@pytest.fixture(scope="module")
def browser(request):
browser = getattr(webdriver, BROWSER)()
browser.implicitly_wait(3)
request.addfinalizer(lambda: browser.quit())
return browser
def test_1_match(... | import os
import pytest
from selenium import webdriver
BROWSER = os.environ.get('BROWSER', 'Firefox')
@pytest.fixture(scope="module")
def browser(request):
browser = getattr(webdriver, BROWSER)()
browser.implicitly_wait(3)
request.addfinalizer(lambda: browser.quit())
return browser
def test_1_match(... | agpl-3.0 | Python |
f2e0abafdf4db660fbe98a1a728711f2d906bbe4 | Add DEBUG mode | Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web,Grum-Hackdee/grum-web | grum/__init__.py | grum/__init__.py | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
if os.environ['DEBUG']:
app.config['DEBUG'] == True
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ["DATABASE_URL"]
db = SQLAlchemy(app)
from grum.api import api
app.register_blueprint(api, url_prefix='/api')
... | import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ["DATABASE_URL"]
db = SQLAlchemy(app)
from grum.api import api
app.register_blueprint(api, url_prefix='/api')
from grum import views, models | mit | Python |
30db66f793a480f4e85da6d6f8caf94dde0ed7b2 | Remove deprecated path to align_measures, add_implicit_acquires and pad. These functions are found in qiskit.pulse.reschedule rather than qiskit.pulse.utils (#3743) | QISKit/qiskit-sdk-py,QISKit/qiskit-sdk-py,QISKit/qiskit-sdk-py | qiskit/pulse/utils.py | qiskit/pulse/utils.py | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modif... | apache-2.0 | Python |
0409b20846259973ff0d3a7b3d3792c07a7199dd | Increase cache sizes | c-w/gutenberg-http,c-w/gutenberg-http | gutenberg_http/config.py | gutenberg_http/config.py | from os import getenv
METADATA_CACHE_SIZE = int(getenv('GUTENBERG_HTTP_METADATA_CACHE_SIZE', '1024'))
BODY_CACHE_SIZE = int(getenv('GUTENBERG_HTTP_BODY_CACHE_SIZE', '64'))
SEARCH_CACHE_SIZE = int(getenv('GUTENBERG_HTTP_SEARCH_CACHE_SIZE', '128'))
| from os import getenv
METADATA_CACHE_SIZE = int(getenv('GUTENBERG_HTTP_METADATA_CACHE_SIZE', '256'))
BODY_CACHE_SIZE = int(getenv('GUTENBERG_HTTP_BODY_CACHE_SIZE', '16'))
SEARCH_CACHE_SIZE = int(getenv('GUTENBERG_HTTP_SEARCH_CACHE_SIZE', '32'))
| apache-2.0 | Python |
abaaf1d4aa88a601705c00851ced815de31b228b | update get_maya_window | danbradham/mvp | mvp/utils.py | mvp/utils.py | from Qt import QtWidgets
import time
def get_maya_window(cache=[]):
'''Get Maya MainWindow as a QWidget.'''
if cache:
return cache[0]
for widget in QtWidgets.QApplication.instance().topLevelWidgets():
if widget.objectName() == 'MayaWindow':
cache.append(widget)
re... | from Qt import QtWidgets
import time
def get_maya_window(cache=[]):
'''Get Maya MainWindow as a QWidget.'''
if cache:
return cache[0]
for widget in QtWidgets.qApp.topLevelWidgets():
if widget.objectName() == 'MayaWindow':
cache.append(widget)
return widget
ra... | mit | Python |
f99d418a1b7a5d697ab760fd3f902865dea2f46f | bump version | thatch45/svt | svt/version.py | svt/version.py | version = '1.0.3'
| version = '1.0.2'
| apache-2.0 | Python |
1e6daf0c67cf7e22ed010171b9e39078d5fa3e96 | refactor database URI | gelnior/newebe,gelnior/newebe,gelnior/newebe,gelnior/newebe | settings.py | settings.py | # Global settings
try:
from newebe.local_settings import *
except:
TORNADO_PORT = 8000
COUCHDB_DB_NAME = "newebe"
DEBUG = False
TIMEZONE = "GMT"
# Couchdb configuration
COUCHDB_DB_URI = 'http://127.0.0.1:5984/%s' % COUCHDB_DB_NAME
COUCHDB_DATABASES = (
('newebe.news', COUCHDB_DB_URI),
(... | # Global settings
try:
from newebe.local_settings import *
except:
TORNADO_PORT = 8000
COUCHDB_DB_NAME = "newebe"
DEBUG = False
TIMEZONE = "GMT"
# Couchdb configuration
COUCHDB_DATABASES = (
('newebe.news', 'http://127.0.0.1:5984/%s' % COUCHDB_DB_NAME),
('newebe.core', 'http://127.0.0.1:59... | agpl-3.0 | Python |
37c79399a9714c161a722987cd94b1ab4bc6538c | change log path | FTwO-O/pyShadowsocks,FTwO-O/pyShadowsocks | settings.py | settings.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: booopooob@gmail.com
#
# Info:
#
#
import logging
import constants
from util.log import get_logger
PROTO_LOG = get_logger('protocol', logging.WARN)
CONFIG_LOG = get_logger('config', logging.INFO)
CONFIG_FILES = ['/etc/pyshadowsocks.ini', '~/.pyshadowsocks.ini'... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: booopooob@gmail.com
#
# Info:
#
#
import logging
import constants
from util.log import get_logger
PROTO_LOG = get_logger('protocol', logging.WARN)
CONFIG_LOG = get_logger('config', logging.INFO)
CONFIG_FILES = ['/etc/pyshadowsocks.ini', '~/.pyshadowsocks.ini'... | mit | Python |
3c849a866be475eebdc646ad47cad7860a4914ec | Update tests to run with right import. | Griatch/har2lilua | har2lilua/tests/tests.py | har2lilua/tests/tests.py | # -*- coding: utf-8 -*-
"""
har2lilua Tests
"""
from __future__ import unicode_literals
from io import open
import unittest
from har2lilua import har2lilua
def _read_testfiles():
with open("test.har", "r", encoding="utf-8") as fil:
harstring = fil.read()
with open("test.lua", "r", encoding="utf-8") as... | # -*- coding: utf-8 -*-
"""
har2lilua Tests
"""
from __future__ import unicode_literals
from io import open
import unittest
import har2lilua
def _read_testfiles():
with open("test.har", "r", encoding="utf-8") as fil:
harstring = fil.read()
with open("test.lua", "r", encoding="utf-8") as fil:
l... | bsd-2-clause | Python |
9d3e8fd54c392f44420d6ffbfa94a66358019b8d | Add mocking for memcache for Python3 tests | dstanek/keystone,jamielennox/keystone,dstanek/keystone,rajalokan/keystone,vivekdhayaal/keystone,idjaw/keystone,openstack/keystone,klmitch/keystone,ajayaa/keystone,cernops/keystone,takeshineshiro/keystone,vivekdhayaal/keystone,roopali8/keystone,klmitch/keystone,rajalokan/keystone,vivekdhayaal/keystone,jonnary/keystone,m... | keystone/tests/unit/__init__.py | keystone/tests/unit/__init__.py | # Copyright 2013 OpenStack Foundation
#
# 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 ... | # Copyright 2013 OpenStack Foundation
#
# 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 ... | apache-2.0 | Python |
5e27164cb821a75e07ae1bc658b9fbfd00dce6d2 | add Chile to McLocalizerSpider | iandees/all-the-places,iandees/all-the-places,iandees/all-the-places | locations/spiders/mcdonalds_localizer.py | locations/spiders/mcdonalds_localizer.py | # -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
class McLocalizer(scrapy.Spider):
name = "mclocalizer"
allowed_domains = [
"www.mcdonalds.com",
"www.mcdonalds.com.pr",
"www.mcdonalds.co.cr",
"www.mcdonalds.com.ar",
"ww... | # -*- coding: utf-8 -*-
import scrapy
import json
from locations.items import GeojsonPointItem
class McLocalizer(scrapy.Spider):
name = "mclocalizer"
allowed_domains = [
"www.mcdonalds.com",
"www.mcdonalds.com.pr",
"www.mcdonalds.co.cr",
"www.mcdonalds.com.ar",
"ww... | mit | Python |
d976da8addb62650320ee9d1ef31c332829aed6e | Implement streaming yml and table exports | notapresent/rbm2m,notapresent/rbm2m | rbm2m/views/public.py | rbm2m/views/public.py | # -*- coding: utf-8 -*-
import logging
from flask import (Blueprint, render_template, request, send_from_directory,
current_app, Response, stream_with_context)
from ..webapp import db
from ..action import exporter
bp = Blueprint('public', __name__)
logger = logging.getLogger(__name__)
@bp.route... | # -*- coding: utf-8 -*-
import logging
from flask import Blueprint, render_template, request, send_from_directory, current_app
from ..webapp import db
from ..action import exporter
bp = Blueprint('public', __name__)
logger = logging.getLogger(__name__)
@bp.route('/yml')
def yml():
"""
YML export endpo... | apache-2.0 | Python |
815980f95fc4e2e9fb327a7f89e664a4f1c991ea | Use TIME_SERIES_DAILY_ADJUSTED as it's available for non-premium API keys | whwright/stock-widget | get_stock_price.py | get_stock_price.py | #!/usr/bin/env python3
"""
usage: get_stock_price.py [SYMBOL]
Get stock information for a given symbol. Writes '[stock price] [percent change]'
to standard out.
"""
import argparse
import os
import requests
import sys
def main():
parser = argparse.ArgumentParser(description='Get current stock information for a... | #!/usr/bin/env python3
"""
usage: get_stock_price.py [SYMBOL]
Get stock information for a given symbol. Writes '[stock price] [percent change]'
to standard out.
"""
import argparse
import os
import requests
import sys
def main():
parser = argparse.ArgumentParser(description='Get current stock information for a... | mit | Python |
0f53a58d26051c76809c55819c623241ae3f160d | fix error | munisisazade/developer_portal,munisisazade/developer_portal,munisisazade/developer_portal | news/urls.py | news/urls.py | from django.conf.urls import url
from news.views import TestView, index,AboutView,GalleryView,ContactsView,PrivacyView,CategoryDetailView
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^index.aspx$', TestView.as_view(), name='main-index'),
url(r'^about-us.aspx$', AboutView.as_view(), name='about'),... | from django.conf.urls import url
from news.views import TestView, index,AboutView,GalleryView,ContactsView,PrivacyView,CategoryDetailView
urlpatterns = [
url(r'^$', index, name='index'),
url(r'^index.aspx$', TestView.as_view(), name='main-index'),
url(r'^about-us.aspx$', AboutView.as_view(), name='about'),... | mit | Python |
07f839c5b70458949d577f4e48e18293b0cb36bc | Add sample text | otknoy/ExTAT,otknoy/ExTAT | nlp/tfidf.py | nlp/tfidf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def term_frequency(terms):
tf = {}
for t in terms:
if not tf.has_key(t):
tf[t] = 0
tf[t] += 1
return tf
def document_frequency(texts):
from itertools import chain
all_terms = list(chain.from_iterable(texts)) # flatten
df... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def term_frequency(terms):
tf = {}
for t in terms:
if not tf.has_key(t):
tf[t] = 0
tf[t] += 1
return tf
def document_frequency(texts):
from itertools import chain
all_terms = list(chain.from_iterable(texts)) # flatten
df... | mit | Python |
74feef6094d884b0116fef895885aa47233801c1 | Fix GITDIR constant to use local gitdir if global doesn't exist | fenhl/gitdir | gitdir/__init__.py | gitdir/__init__.py | import os
import pathlib
GLOBAL_GITDIR = pathlib.Path('/opt/git')
LOCAL_GITDIR = pathlib.Path.home() / 'git'
if 'GITDIR' in is.environ:
GITDIR = pathlib.Path(os.environ['GITDIR'])
elif LOCAL_GITDIR.exists() and not GLOBAL_GITDIR.exists(): #TODO check permissions
GITDIR = LOCAL_GITDIR
else:
GITDIR = GLOBAL... | import os
import pathlib
GITDIR = pathlib.Path(os.environ.get('GITDIR', '/opt/git')) #TODO check permissions
| mit | Python |
e10826aafc5e2cc9f52aec0366030f8ce8f88c6b | Fix for hashdd | MISP/misp-modules,MISP/misp-modules,MISP/misp-modules | misp_modules/modules/expansion/hashdd.py | misp_modules/modules/expansion/hashdd.py | import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']}
moduleconfig = [... | import json
import requests
misperrors = {'error': 'Error'}
mispattributes = {'input': ['md5', 'sha1', 'sha256'], 'output': ['text']}
moduleinfo = {'version': '0.2', 'author': 'Alexandre Dulaunoy', 'description': 'An expansion module to check hashes against hashdd.com including NSLR dataset.', 'module-type': ['hover']... | agpl-3.0 | Python |
b3108723007e32fcb650a2ade8c697f12fd3f716 | fix mock_timing fixture name (typo) in timing.py | nicoddemus/pytest,nicoddemus/pytest,markshao/pytest,RonnyPfannschmidt/pytest,Akasurde/pytest,pytest-dev/pytest | src/_pytest/timing.py | src/_pytest/timing.py | """Indirection for time functions.
We intentionally grab some "time" functions internally to avoid tests mocking "time" to affect
pytest runtime information (issue #185).
Fixture "mock_timing" also interacts with this module for pytest's own tests.
"""
from time import perf_counter
from time import sleep
from time im... | """Indirection for time functions.
We intentionally grab some "time" functions internally to avoid tests mocking "time" to affect
pytest runtime information (issue #185).
Fixture "mock_timinig" also interacts with this module for pytest's own tests.
"""
from time import perf_counter
from time import sleep
from time i... | mit | Python |
4947ebf9460c2cf2ba8338de92601804dec2148a | Use the new reader classes in the template tag | mikedingjan/django-svg-icons,mikedingjan/django-svg-icons | src/svg_icons/templatetags/svg_icons.py | src/svg_icons/templatetags/svg_icons.py | import json
from importlib import import_module
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
reader_class = getattr(settings, 'SVG_ICONS_READER_CLASS', 'svg_icons.readers.icomoon.IcomoonReader')
try:
module, cls = reader_class.rspli... | import json
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
register = Library()
@register.inclusion_tag('svg_icons/icon.html')
def icon(name, **kwargs):
"""Render a SVG icon defined in a json file to our template.
..:json exampl... | apache-2.0 | Python |
6bac7e4bb23a8490446e5f28c6aba4dfcb48bb44 | Remove invalid dtype test (#20370) | pandas-dev/pandas,gfyoung/pandas,cython-testbed/pandas,kdebrab/pandas,jorisvandenbossche/pandas,rs2/pandas,amolkahat/pandas,pratapvardhan/pandas,cbertinato/pandas,datapythonista/pandas,pandas-dev/pandas,gfyoung/pandas,jorisvandenbossche/pandas,pandas-dev/pandas,rs2/pandas,datapythonista/pandas,gfyoung/pandas,cython-tes... | pandas/tests/extension/base/interface.py | pandas/tests/extension/base/interface.py | import numpy as np
import pandas as pd
from pandas.compat import StringIO
from pandas.core.dtypes.common import is_extension_array_dtype
from pandas.core.dtypes.dtypes import ExtensionDtype
from .base import BaseExtensionTests
class BaseInterfaceTests(BaseExtensionTests):
"""Tests that the basic interface is sa... | import numpy as np
import pandas as pd
from pandas.compat import StringIO
from pandas.core.dtypes.common import is_extension_array_dtype
from pandas.core.dtypes.dtypes import ExtensionDtype
from .base import BaseExtensionTests
class BaseInterfaceTests(BaseExtensionTests):
"""Tests that the basic interface is sa... | bsd-3-clause | Python |
24b7cdf680a88e3f0330905fb6ea4cb4bac629e7 | Bump version | markstory/lint-review,markstory/lint-review,markstory/lint-review | lintreview/__init__.py | lintreview/__init__.py | __version__ = '2.5.1'
| __version__ = '2.5.0'
| mit | Python |
f4a0a94cf32b90f93b01ec84f73110e965f7c325 | Clean up the drop test | nkhuyu/blaze,ContinuumIO/blaze,cpcloud/blaze,jcrist/blaze,alexmojaki/blaze,ChinaQuants/blaze,scls19fr/blaze,LiaoPan/blaze,mrocklin/blaze,cowlicks/blaze,xlhtc007/blaze,cowlicks/blaze,scls19fr/blaze,dwillmer/blaze,caseyclements/blaze,ContinuumIO/blaze,dwillmer/blaze,jdmcbr/blaze,ChinaQuants/blaze,jcrist/blaze,maxalbert/b... | blaze/tests/test_sql.py | blaze/tests/test_sql.py | import pytest
from sqlalchemy.exc import OperationalError
from cytoolz import first
from blaze.sql import drop, create_index
from blaze import compute, Table, SQL
@pytest.fixture
def sql():
data = [(1, 2), (10, 20), (100, 200)]
sql = SQL('sqlite:///:memory:', 'foo', schema='{x: int, y: int}')
sql.extend(d... | import pytest
from sqlalchemy.exc import OperationalError
from cytoolz import first
from blaze.sql import drop, create_index
from blaze import compute, Table, SQL
@pytest.fixture
def sql():
data = [(1, 2), (10, 20), (100, 200)]
sql = SQL('sqlite:///:memory:', 'foo', schema='{x: int, y: int}')
sql.extend(d... | bsd-3-clause | Python |
23be00014e1d9bd06db7ffa081b3499acd33b0de | fix namespace | radical-cybertools/aimes.emgr | src/aimes/__init__.py | src/aimes/__init__.py |
import pkg_resources
pkg_resources.declare_namespace (__name__)
| mit | Python | |
4dfeb3bd230b3c0e9920763085fd716b78c40845 | Bump version (0.2.0) | damianignacio/anima,damianignacio/anima,damianignacio/anima | src/anima/__init__.py | src/anima/__init__.py | # -*- coding: utf-8 -*-
__version__ = '0.2.0'
from django.apps import AppConfig
class Config(AppConfig):
label = 'anima'
verbose_name = 'Anima'
name = 'anima'
models_module = 'anima.models'
| # -*- coding: utf-8 -*-
__version__ = '0.1.0'
from django.apps import AppConfig
class Config(AppConfig):
label = 'anima'
verbose_name = 'Anima'
name = 'anima'
models_module = 'anima.models'
| mit | Python |
023e354500b08de3a0fb1564ee0bbf9d749e1b6c | test colors | adrn/globber,adrn/globber | globber/ngc5897.py | globber/ngc5897.py | from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Third-party
import astropy.coordinates as coord
import astropy.units as u
import numpy as np
cluster_c = coord.SkyCoord(ra=229.352*u.degree,
dec=-21.01*u.degree)
cluster_pad = {
'inner': 6*u... | from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Third-party
import astropy.coordinates as coord
import astropy.units as u
import numpy as np
cluster_c = coord.SkyCoord(ra=229.352*u.degree,
dec=-21.01*u.degree)
cluster_pad = {
'inner': 6*u... | mit | Python |
0472e83086330d5efba6e873f648c8a45c099581 | Update solution | xliiauo/leetcode,xiao0720/leetcode,xiao0720/leetcode,xliiauo/leetcode,xliiauo/leetcode | 1/Solution.py | 1/Solution.py | class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
try:
j = nums.index(target - nums[i])
except:
j = -1
... | class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
retur... | mit | Python |
e37320041141c371ac854f8f9d05636ed7da48f4 | add typehint to intialize function in plugin | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril | mythril/laser/ethereum/plugins/plugin.py | mythril/laser/ethereum/plugins/plugin.py | from mythril.laser.ethereum.svm import LaserEVM
class LaserPlugin:
""" Base class for laser plugins
Functionality in laser that the symbolic execution process does not need to depend on
can be implemented in the form of a laser plugin.
Laser plugins implement the function initialize(symbolic_vm) whi... | from mythril.laser.ethereum.svm import LaserEVM
class LaserPlugin:
""" Base class for laser plugins
Functionality in laser that the symbolic execution process does not need to depend on
can be implemented in the form of a laser plugin.
Laser plugins implement the function initialize(symbolic_vm) whi... | mit | Python |
f329815b1dff3f25f1bdbae8ad6316992f3e875a | Bump the gtk-sharp commit | BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,BansheeMediaPlayer/bockbuild,mono/bockbuild,mono/bockbuild | packages/gtk-sharp.py | packages/gtk-sharp.py | class GtkSharpPackage (Package):
def __init__ (self):
Package.__init__ (self, 'gtk-sharp', '2-12-branch')
self.commit = 'acbb04600d2dbdbe889117c07ee660818abd7070'
self.source_dir_name = 'mono-gtk-sharp-%s' % self.commit[:7]
self.configure = './bootstrap-2.12 --prefix="%{prefix}"'
self.sources = [
'http://... | class GtkSharpPackage (Package):
def __init__ (self):
Package.__init__ (self, 'gtk-sharp', '2-12-branch')
self.commit = 'b078aacaf263af84605812d778b62afbdf3e1b59'
self.source_dir_name = 'mono-gtk-sharp-%s' % self.commit[:7]
self.configure = './bootstrap-2.12 --prefix="%{prefix}"'
self.sources = [
'http://... | mit | Python |
d95a7806bab0c8f3e07d94f4ff8729adf462c058 | Clean up imports | martialblog/git-pullpush | pullpush/main.py | pullpush/main.py | #!/usr/bin/env python3
# TODO Slack Integration
# TODO Retry-If-Fail implementation
from tempfile import TemporaryDirectory
from argparse import ArgumentParser
from pullpush import PullPush
DESC = 'Pulls a git repository and pushes it somewhere'
HELP_PULL = 'The repo to pull from'
HELP_PUSH = 'The repo to push into... | #!/usr/bin/env python3
# TODO Deploy Key Integration
# TODO Slack Integration
# TODO Error/Expection Handling
# TODO Retry-If-Fail implementation
import tempfile
from argparse import ArgumentParser
from pullpush import PullPush
DESC = 'Pulls a git repository and pushes it somewhere'
def main():
argumentparse... | mit | Python |
2da9e552ae42930002b2477a03226b42ab5bf271 | fix merge | datamade/pupa,opencivicdata/pupa,mileswwatkins/pupa,mileswwatkins/pupa,opencivicdata/pupa,datamade/pupa | pupa/settings.py | pupa/settings.py | import os
import importlib
import sys
import dj_database_url
DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
SECRET_KEY = 'non-secret'
INSTALLED_APPS = ('opencivicdata.apps.BaseConfig', 'pupa',)
# scrape settings
ENABLE_KAFKA = os.environ.get('ENABLE_KAFKA', "False").lowe... | import os
import importlib
import sys
import dj_database_url
DATABASE_URL = os.environ.get('DATABASE_URL', 'postgis://pupa:pupa@localhost/opencivicdata')
SECRET_KEY = 'non-secret'
INSTALLED_APPS = ('opencivicdata.apps.BaseConfig', 'pupa',)
# scrape settings
ENABLE_KAFKA = os.environ.get('ENABLE_KAFKA', "False").lowe... | bsd-3-clause | Python |
1b557a1ce4e518f443a9ef9e76704a4410812bc5 | Bump version number | graphql-python/gql | gql/__version__.py | gql/__version__.py | __version__ = "3.0.0a2"
| __version__ = "3.0.0a1"
| mit | Python |
43c5fa0ce27993c8da73d5c0c5bff1897c3a0431 | Update svm_grid_search.py | JiJingYu/tensorflow-exercise | svm_grid_search/svm_grid_search.py | svm_grid_search/svm_grid_search.py | import pandas as pd
from sklearn import svm, datasets
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
iris = datasets.load_iris()
parameters = {'kernel':('linear', 'rbf'), 'C':[1, 2, 4], 'gamma':[0.125, 0.25, 0.5 ,1, 2, 4]}
svr = svm.SVC()
clf = GridSearchCV(svr, para... | apache-2.0 | Python | |
e4c0b6747bc875d12b07e3c14c3cba256d13ec0e | rearrange code for consistency | jarrodmillman/gradebook | gradebook/stats.py | gradebook/stats.py | #!/usr/bin/env python
import sys
from collections import OrderedDict, Counter
from numpy import array
import pandas as pd
from gradebook.utils import gb_home, get_grades
def main():
argv = sys.argv[1:]
print argv
narg = len(argv)
if narg == 0:
total = 0
assignments = get_grades(... | #!/usr/bin/env python
import sys
from collections import OrderedDict, Counter
from numpy import array
import pandas as pd
from gradebook.utils import gb_home, get_grades
def stem_and_leaf(x):
d = OrderedDict((((str(v)[:-1],' ')[v<10], Counter()) for v in sorted(x)))
for s in ((str(v),' '+str(v))[v<10] for v... | bsd-2-clause | Python |
bcc40b08c59ba8fcb8efc9044c2ea6e11ed9df12 | Add more "GET /users" tests | RBE-Avionik/skylines,Harry-R/skylines,RBE-Avionik/skylines,Turbo87/skylines,Harry-R/skylines,shadowoneau/skylines,shadowoneau/skylines,RBE-Avionik/skylines,Turbo87/skylines,skylines-project/skylines,Turbo87/skylines,RBE-Avionik/skylines,shadowoneau/skylines,Harry-R/skylines,Turbo87/skylines,shadowoneau/skylines,skyline... | tests/api/views/users/list_test.py | tests/api/views/users/list_test.py | from tests.data import add_fixtures, users, clubs
def test_list_users(db_session, client):
john = users.john()
add_fixtures(db_session, john)
res = client.get('/users/')
assert res.status_code == 200
assert res.json == {
u'users': [{
u'id': john.id,
u'name': u'John... | from tests.data import add_fixtures, users
def test_list_users(db_session, client):
john = users.john()
add_fixtures(db_session, john)
res = client.get('/users/')
assert res.status_code == 200
assert res.json == {
u'users': [{
u'id': john.id,
u'name': u'John Doe',
... | agpl-3.0 | Python |
ef7ed0b4bec10fe97c0f773604590d493cea983c | support signals vis in quick interface | amir-zeldes/rstWeb,amir-zeldes/rstWeb,amir-zeldes/rstWeb,amir-zeldes/rstWeb | get_structure.py | get_structure.py | #!/usr/bin/python3.5
# -*- coding: utf-8 -*-
from structure import build_canvas
from modules.rstweb_reader import read_rst
from modules.rstweb_sql import get_rst_rels
import io, sys, os
import cgi, cgitb
import codecs
from six import iteritems
def get_structure_main(**kwargs):
if "data" in kwargs:
rs3 =... | #!/usr/bin/python3.5
# -*- coding: utf-8 -*-
from structure import build_canvas
from modules.rstweb_reader import read_rst
from modules.rstweb_sql import get_rst_rels
import io, sys, os
import cgi, cgitb
import codecs
from six import iteritems
def get_structure_main(**kwargs):
if "data" in kwargs:
rs3 =... | mit | Python |
ef21f748806c0b8e75f101e6a4486aee3911681f | Remove vestige of gtk2 from Plot wrapper | pllim/ginga,pllim/ginga,naojsoft/ginga,pllim/ginga,naojsoft/ginga,ejeschke/ginga,naojsoft/ginga,ejeschke/ginga,ejeschke/ginga | ginga/gw/Plot.py | ginga/gw/Plot.py | # Figure out which widget set we are using and import those wrappers
from ginga import toolkit
tkname = toolkit.get_family()
if tkname == 'qt':
from ginga.qtw.Plot import * # noqa
elif tkname == 'gtk3':
from ginga.gtk3w.Plot import * # noqa
elif tkname == 'pg':
from ginga.web.pgw.Plot import * # noqa
... | # Figure out which widget set we are using and import those wrappers
from ginga import toolkit
tkname = toolkit.get_family()
if tkname == 'qt':
from ginga.qtw.Plot import * # noqa
elif tkname == 'gtk':
from ginga.gtkw.Plot import * # noqa
elif tkname == 'gtk3':
from ginga.gtk3w.Plot import * # noqa
e... | bsd-3-clause | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.