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 |
|---|---|---|---|---|---|---|---|---|
b53fcea70dd4babcffe1d9168c9d8d8ddac0ee59 | rename Telerivet to Telerivet (Android) | gmimano/commcaretest,dimagi/commcare-hq,dimagi/commcare-hq,gmimano/commcaretest,qedsoftware/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq,SEL-Columbia/commcare-hq,puttarajubr/commcare-hq,gmimano/commcaretest,qedsoftware/commcare-hq,qedsoftware/commcare-hq,... | corehq/apps/telerivet/models.py | corehq/apps/telerivet/models.py | import os
import pycurl
import StringIO
import json
from couchdbkit.ext.django.schema import *
from urllib import urlencode
from corehq.apps.sms.util import clean_phone_number
from corehq.apps.sms.mixin import SMSBackend
from corehq.apps.telerivet.forms import TelerivetBackendForm
MESSAGE_TYPE_SMS = "sms"
class Teler... | import os
import pycurl
import StringIO
import json
from couchdbkit.ext.django.schema import *
from urllib import urlencode
from corehq.apps.sms.util import clean_phone_number
from corehq.apps.sms.mixin import SMSBackend
from corehq.apps.telerivet.forms import TelerivetBackendForm
MESSAGE_TYPE_SMS = "sms"
class Teler... | bsd-3-clause | Python |
d86e3e98793173255f34cc0f9eb1894370f19147 | adjust key to match convention | UoA-eResearch/ckanext-googl,UoA-eResearch/ckanext-googl | ckanext/googl/plugin.py | ckanext/googl/plugin.py | import logging
import requests
import pylons.config as config
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckanext.external_id.interfaces import IExternalIDProvider
log = logging.getLogger(__name__)
class GooglPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)... | import logging
import requests
import pylons.config as config
import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
from ckanext.external_id.interfaces import IExternalIDProvider
log = logging.getLogger(__name__)
class GooglPlugin(plugins.SingletonPlugin):
plugins.implements(plugins.IConfigurer)... | agpl-3.0 | Python |
f13b445489774bfa19a3cd26f2324c1144c8f481 | Update word-search.py | jaredkoontz/leetcode,kamyu104/LeetCode,yiwen-luo/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,githubutilities... | Python/word-search.py | Python/word-search.py | # Time: O(m * n * l)
# Space: O(l)
#
# Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell,
# where "adjacent" cells are those horizontally or vertically neighboring.
# The same letter cell may not be used more than once.
#
# ... | # Time: O(m * n * 3^p)
# Space: O(m * n + p)
#
# Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell,
# where "adjacent" cells are those horizontally or vertically neighboring.
# The same letter cell may not be used more than o... | mit | Python |
4a8561c74440f34123475b0b62e8f2a663efa0ae | Bump version number to 1.0.0rc3 in preparation for upcoming release. | JaneliaSciComp/Neuroptikon,JaneliaSciComp/Neuroptikon | Source/__version__.py | Source/__version__.py | # Copyright (c) 2010 Howard Hughes Medical Institute.
# All rights reserved.
# Use is subject to Janelia Farm Research Campus Software Copyright 1.1 license terms.
# http://license.janelia.org/license/jfrc_copyright_1_1.html
version = "1.0.0rc3"
version_info = (1, 0, 0, "rc3")
JIRA_version_id = 10011
| # Copyright (c) 2010 Howard Hughes Medical Institute.
# All rights reserved.
# Use is subject to Janelia Farm Research Campus Software Copyright 1.1 license terms.
# http://license.janelia.org/license/jfrc_copyright_1_1.html
version = "1.0.0rc2a"
version_info = (1, 0, 0, "rc2a")
JIRA_version_id = 10011
| bsd-3-clause | Python |
9b86c2d5313e56033b0f601a8894a13a26f655ff | modify return values | haandol/algorithm_in_python | interview/amazon/gas.py | interview/amazon/gas.py | # https://www.interviewbit.com/problems/gas-station/
class Solution:
def canCompleteCircuit(self, gas, cost):
n = len(gas)
gas = gas*2
cost = cost*2
for start in xrange(n):
fuel = 0
for i in xrange(start, n+1):
fuel += gas[i]
... | # https://www.interviewbit.com/problems/gas-station/
class Solution:
def canCompleteCircuit(self, gas, cost):
n = len(gas)
gas = gas*2
cost = cost*2
for start in xrange(n):
fuel = 0
for i in xrange(start, n+1):
fuel += gas[i]
... | mit | Python |
0f487f0a061c10982513ffaf37b0a02855928049 | Fix import reports | Garrappachc/tf2director | actions.py | actions.py | from tf2server import Tf2Server
def start(servers):
"""
Start the server(s) with the config provided.
:param servers: list of servers to be started
"""
for s in servers:
if not isinstance(s, Tf2Server):
raise TypeError('Not an instance of Tf2Server')
s.start()
def st... | import reports
from tf2server import Tf2Server
def start(servers):
"""
Start the server(s) with the config provided.
:param servers: list of servers to be started
"""
for s in servers:
if not isinstance(s, Tf2Server):
raise TypeError('Not an instance of Tf2Server')
s.s... | mit | Python |
90f9b43109b94a765f018ab40fc616615765aff6 | Configure pdfcredentials extension. | modoboa/modoboa-demo,modoboa/modoboa-demo | modoboa_demo/modo_extension.py | modoboa_demo/modo_extension.py | """Demo extension."""
from django.utils.translation import ugettext_lazy
from modoboa.core.extensions import ModoExtension, exts_pool
from modoboa.lib.parameters import save_admin
from modoboa_admin.factories import DomainFactory, MailboxFactory
class Demo(ModoExtension):
"""The demo extension."""
name =... | """Demo extension."""
from django.utils.translation import ugettext_lazy
from modoboa.core.extensions import ModoExtension, exts_pool
from modoboa.lib.parameters import save_admin
from modoboa_admin.factories import DomainFactory, MailboxFactory
class Demo(ModoExtension):
"""The demo extension."""
name =... | mit | Python |
20a39ab7e1fd3218fba7a2b9e0e4f7aea0cb580a | Remove unused config schema & logger from totalconnect (#50604) | lukas-hetzenecker/home-assistant,rohitranjan1991/home-assistant,kennedyshead/home-assistant,toddeye/home-assistant,GenericStudent/home-assistant,sander76/home-assistant,kennedyshead/home-assistant,lukas-hetzenecker/home-assistant,jawilson/home-assistant,Danielhiversen/home-assistant,sander76/home-assistant,rohitranjan1... | homeassistant/components/totalconnect/__init__.py | homeassistant/components/totalconnect/__init__.py | """The totalconnect component."""
from total_connect_client import TotalConnectClient
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
import homeassi... | """The totalconnect component."""
import logging
from total_connect_client import TotalConnectClient
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions imp... | apache-2.0 | Python |
6cf47ba1a1b8057206fb37e0413015059dee95c2 | Fix syntax in sdb.get_or_set_hash examples | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/modules/sdb.py | salt/modules/sdb.py | """
Module for Manipulating Data via the Salt DB API
================================================
"""
import salt.utils.sdb
__func_alias__ = {
"set_": "set",
}
def get(uri, strict=False):
"""
Get a value from a db, using a uri in the form of ``sdb://<profile>/<key>``. If
the uri provided is not... | """
Module for Manipulating Data via the Salt DB API
================================================
"""
import salt.utils.sdb
__func_alias__ = {
"set_": "set",
}
def get(uri, strict=False):
"""
Get a value from a db, using a uri in the form of ``sdb://<profile>/<key>``. If
the uri provided is not... | apache-2.0 | Python |
2c6c8012a593e2abb2daa941e38da48e518eb02b | Update to the new tw.jquery.ui API | ralphbean/moksha,pombredanne/moksha,lmacken/moksha,mokshaproject/moksha,ralphbean/moksha,ralphbean/moksha,pombredanne/moksha,mokshaproject/moksha,pombredanne/moksha,lmacken/moksha,lmacken/moksha,mokshaproject/moksha,pombredanne/moksha,mokshaproject/moksha | moksha/widgets/misc/ptd/ptd.py | moksha/widgets/misc/ptd/ptd.py | # This file is part of Moksha.
# Copyright (C) 2008-2009 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later... | # This file is part of Moksha.
# Copyright (C) 2008-2009 Red Hat, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later... | apache-2.0 | Python |
dca2fa82efc337d096193a0f1082250f8db2acc6 | Fix loading yaml file warning in Python 3 | openstack/monasca-notification,stackforge/monasca-notification,openstack/monasca-notification | monasca_notification/config.py | monasca_notification/config.py | # Copyright 2017 FUJITSU LIMITED
#
# 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 writ... | # Copyright 2017 FUJITSU LIMITED
#
# 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 writ... | apache-2.0 | Python |
32cc8b63d7bbe5cfc83b82a058d1c5832980f290 | Add capabilities for privsep | noironetworks/neutron,openstack/neutron,mahak/neutron,mahak/neutron,openstack/neutron,openstack/neutron,mahak/neutron,noironetworks/neutron | neutron/privileged/__init__.py | neutron/privileged/__init__.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | apache-2.0 | Python |
2ceec594601a6564cf1dc78b90677f1987f9349d | Remove extra line | alphagov/notifications-utils | notifications_utils/version.py | notifications_utils/version.py | __version__ = '15.0.3'
| __version__ = '15.0.3'
| mit | Python |
3cced61b97a3b97a473e8335b1407a2901552d43 | Exclude authorities that have full elections | DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website,DemocracyClub/Website | democracy_club/apps/everyelection/views.py | democracy_club/apps/everyelection/views.py | import random
from django.db.models import Count
from django.shortcuts import get_object_or_404
from django.views.generic import RedirectView, UpdateView
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from .models import AuthorityElectio... | import random
from django.db.models import Count
from django.shortcuts import get_object_or_404
from django.views.generic import RedirectView, UpdateView
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from braces.views import LoginRequiredMixin
from .models import AuthorityElectio... | bsd-3-clause | Python |
e86da37512f30e4099610f16d2580d3e97f0b791 | Add reverse preprint to node_extras | baylee-d/osf.io,brianjgeiger/osf.io,HalcyonChimera/osf.io,binoculars/osf.io,cwisecarver/osf.io,icereval/osf.io,sloria/osf.io,CenterForOpenScience/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,hmoco/osf.io,chennan47/osf.io,caseyrollins/osf.io,felliott/osf.io,mfraezz/osf.io,crcresearch/osf.io,pattisdr/osf.io,cwiseca... | admin/nodes/templatetags/node_extras.py | admin/nodes/templatetags/node_extras.py | from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.filter
def reverse_node(value):
return reverse('nodes:node', kwargs={'guid': value})
@register.filter
def reverse_preprint(value):
return reverse('preprints:preprint', kwargs={'guid': value})
@r... | from django import template
from django.core.urlresolvers import reverse
register = template.Library()
@register.filter
def reverse_node(value):
return reverse('nodes:node', kwargs={'guid': value})
@register.filter
def reverse_user(user_id):
return reverse('users:user', kwargs={'guid': user_id})
| apache-2.0 | Python |
ccb5296c2104d90e5dfe236cd0482b9a47ecc50b | Update in smoothingpy | berkeley-stat159/project-delta | code/utils/smoothing.py | code/utils/smoothing.py |
# Import Gaussian filter from scipy module
import numpy as np
import itertools
from scipy.ndimage.filters import gaussian_filter
def smooth(input, sigma, slice):
'''
Return array of same shape as input.
The multidimensional filter is implemented as a sequence of one-dimensional
filters.
The intermediate arrays... | # Import numerical and plotting libraries
import numpy as np
import itertools
from scipy.ndimage.filters import gaussian_filter
def smooth(input, sigma, slice):
'''
Return array of same shape as input.
The multidimensional filter is implemented as a sequence of one-dimensional
filters.
The intermediate arrays ar... | bsd-3-clause | Python |
157197b330360ccfeaa0bbf54453702ee17d0106 | Change license to Apache 2 | sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia,sparkslabs/kamaelia | Code/Python/Kamaelia/Kamaelia/Device/__init__.py | Code/Python/Kamaelia/Kamaelia/Device/__init__.py | # -*- coding: utf-8 -*-
# Needed to allow import
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache Lice... | # Needed to allow import
#
# Copyright (C) 2006 British Broadcasting Corporation and Kamaelia Contributors(1)
# All Rights Reserved.
#
# You may only modify and redistribute this under the terms of any of the
# following licenses(2): Mozilla Public License, V1.1, GNU General
# Public License, V2.0, GNU Lesser Gener... | apache-2.0 | Python |
39e53bc4d06875312875a5f8e7a015b4dfd62c1a | Add import from vcs to show job in list | centrumholdings/cthulhubot | cthulhubot/jobs/__init__.py | cthulhubot/jobs/__init__.py | import logging
import pkg_resources
ENTRYPOINT = "chtulhubot.jobs"
from cthulhubot.jobs.job import Job
from cthulhubot.jobs.package import *
from cthulhubot.jobs.sleep import *
from cthulhubot.jobs.tests import *
from cthulhubot.jobs.vcs import *
log = logging.getLogger("cthulhubot.jobs")
ADDITIONAL_JOBS = {}
def ... | import logging
import pkg_resources
ENTRYPOINT = "chtulhubot.jobs"
from cthulhubot.jobs.job import Job
from cthulhubot.jobs.package import *
from cthulhubot.jobs.sleep import *
from cthulhubot.jobs.tests import *
log = logging.getLogger("cthulhubot.jobs")
ADDITIONAL_JOBS = {}
def get_core_jobs():
return dict([... | bsd-3-clause | Python |
3442da1529566e4b47d0c998fb9551094e027870 | use bisect.bisect_right function | googlefonts/fonttools,fonttools/fonttools | Lib/fontTools/unicodedata/__init__.py | Lib/fontTools/unicodedata/__init__.py | from __future__ import (
print_function, division, absolute_import, unicode_literals)
from fontTools.misc.py23 import *
from bisect import bisect_right
try:
# use unicodedata backport compatible with python2:
# https://github.com/mikekap/unicodedata2
from unicodedata2 import *
except ImportError:
... | from __future__ import (
print_function, division, absolute_import, unicode_literals)
from fontTools.misc.py23 import *
import functools
try:
# use unicodedata backport compatible with python2:
# https://github.com/mikekap/unicodedata2
from unicodedata2 import *
except ImportError:
# fall back to ... | mit | Python |
37a4e8d4a901628ac642942a96230b3758a6aa45 | Convert test_deriv to pytest | rparini/cxroots,rparini/cxroots | cxroots/tests/test_deriv.py | cxroots/tests/test_deriv.py | import pytest
import numpy as np
from scipy import cos, sin
from cxroots import Circle, Rectangle
from cxroots import CxDerivative
@pytest.mark.parametrize('C', [
pytest.param(Circle(0, 2), id='circle'),
pytest.param(Rectangle([-1.5,1.5],[-2,2]), id='rect'),
pytest.param(None, id='default')
])
def test_CxDerivativ... | import unittest
import numpy as np
from scipy import cos, sin
from cxroots import Circle, Rectangle
from cxroots import CxDerivative
class TestDerivative1(unittest.TestCase):
def setUp(self):
self.f = lambda z: z**10 - 2*z**5 + sin(z)*cos(z/2)
self.df = lambda z: 10*(z**9 - z**4) + cos(z)*cos(z/2) - 0.5*sin(z)*... | bsd-3-clause | Python |
a8c2b1490859393fb882c81312511148f0ea3cec | fix root group | rootpy/rootpy,rootpy/rootpy,ndawe/rootpy,kreczko/rootpy,ndawe/rootpy,rootpy/rootpy,kreczko/rootpy,kreczko/rootpy,ndawe/rootpy | rootpy/root2tables.py | rootpy/root2tables.py | """
This module handles conversion of ROOT's TFile and
contained TTrees into HDF5 format with PyTables
Also see scripts/root2hd5
"""
import sys
import os
import traceback
import numpy
import tables
import ROOT
from .progressbar import *
from .io import open as ropen, utils
from .tree import Tree
from .root2array impo... | """
This module handles conversion of ROOT's TFile and
contained TTrees into HDF5 format with PyTables
Also see scripts/root2hd5
"""
import sys
import os
import traceback
import numpy
import tables
import ROOT
from .progressbar import *
from .io import open as ropen, utils
from .tree import Tree
from .root2array impo... | bsd-3-clause | Python |
54c410541dee67c30a74283051b3bcf2a160ff6d | Debug strings | yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti,yeti-platform/yeti | Malcom/feeds/internal_dump_dataset.py | Malcom/feeds/internal_dump_dataset.py | import urllib2
import re
import md5
import os
import codecs
from bson.json_util import dumps, loads
from Malcom.feeds.feed import Feed
class ExportAll(Feed):
"""
This gets data from https://palevotracker.abuse.ch/?rssfeed
"""
def __init__(self, name):
super(ExportAll, self).__init__(name, run_every="1h")
se... | import urllib2
import re
import md5
import os
import codecs
from bson.json_util import dumps, loads
from Malcom.feeds.feed import Feed
class ExportAll(Feed):
"""
This gets data from https://palevotracker.abuse.ch/?rssfeed
"""
def __init__(self, name):
super(ExportAll, self).__init__(name, run_every="1h")
se... | apache-2.0 | Python |
03b45698206e2266c69aae3546030ad7a7010db8 | remove unused imports | ericdill/databroker,ericdill/databroker | databroker/headersource/shim.py | databroker/headersource/shim.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six # noqa
import logging
from ..core import format_time as _format_time
logger = logging.getLogger(__name__)
class HeaderSourceShim(object):
'''Shim class to turn a mds object into a HeaderSource... | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import warnings
import six # noqa
import logging
import doct as doc
import numpy as np
from ..core import format_time as _format_time
logger = logging.getLogger(__name__)
class HeaderSourceShim(object):
... | bsd-3-clause | Python |
16bd3a7018a5d957a0c2e06c603a6b524ce5d713 | Remove comments | xeBuz/CompanyDK,xeBuz/CompanyDK,xeBuz/CompanyDK,xeBuz/CompanyDK | api/models/company.py | api/models/company.py | from app import db
class CompanyModel(db.Model):
__tablename__ = 'co_company'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(125))
address = db.Column(db.String(125))
city = db.Column(db.String(125))
country = db.Column(db.String(125))
email = db.Column(db.String(... | from app import db
class CompanyModel(db.Model):
__tablename__ = 'co_company'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(125))
address = db.Column(db.String(125))
city = db.Column(db.String(125))
country = db.Column(db.String(125))
email = db.Column(db.String(... | mpl-2.0 | Python |
c9f762a3f421ec644bb62f72fbdf76068f515a5f | add xml file load option | dbcollection/dbcollection,farrajota/dbcollection | dbcollection/utils/file_load.py | dbcollection/utils/file_load.py | """
Data loading functions from files.
"""
import sys
import json
import scipy.io as scipy
import xmltodict
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
def open_read_file(fname, mode='r'):
"""Opens a file and returns the data.
Parameters
----------
fname : str
... | """
Data loading functions from files.
"""
import sys
import json
import scipy.io as scipy
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
def open_read_file(fname, mode='r'):
"""Opens a file and returns the data.
Parameters
----------
fname : str
File name ... | mit | Python |
1d09e197c02899bf33f4e30aef04e91cfe0dcbca | Change print statement to logger.debug | karenc/db-migrator | dbmigrator/commands/rollback.py | dbmigrator/commands/rollback.py | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
"""Rollback a migration."""
from .. import logger, utils
__all__ = ('cli_loader',)
@utils.with_cursor
... | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
"""Rollback a migration."""
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_... | agpl-3.0 | Python |
0bf756e418b4bc235426f440bcad80bd4c3ce78d | Add delays between autoload steps | brewbit/model-t,brewbit/model-t,brewbit/model-t | scripts/autoload.py | scripts/autoload.py | import os
import serial
import time
s = serial.Serial('/dev/ttyUSB0', 9600, timeout=0.5)
while True:
time.sleep(0.2)
# command arduino to wait for board connection
print "Waiting for board connection"
s.write('r')
time.sleep(0.2)
# wait for arduino to indicate board connected
if s.r... | import os
import serial
s = serial.Serial('/dev/ttyUSB0', 9600)
while True:
# command arduino to wait for board connection
print "Waiting for board connection"
s.write('r')
# wait for arduino to indicate board connected
if s.read(1) != '1':
continue
# command arduino to reset... | mit | Python |
46f2e5fb134a7b580d2443762125a7b72cf74c91 | add update and delete list item examples | vgrem/SharePointOnline-REST-Python-Client,vgrem/Office365-REST-Python-Client | examples/sharepoint/listitem_operations.py | examples/sharepoint/listitem_operations.py | from settings import settings
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
listTitle = "Tasks"
def read_list_items():
print("Read list items example...")
list_object = ctx.web.lists.get_by_title(listTitle)
i... | from settings import settings
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext
listTitle = "Tasks"
def read_list_items():
print("Read list items example...")
list_object = ctx.web.lists.get_by_title(listTitle)
i... | mit | Python |
34375256c9e7328dd305a6c6d6fc73ca973fffa8 | allow only_one decorator to define the key | areski/django-lets-go | common/only_one_task.py | common/only_one_task.py | #code from http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html
import redis
REDIS_CLIENT = redis.Redis()
def only_one(function=None, ikey="", timeout=None):
"""Enforce only one celery task at a time."""
def _dec(run_func):
"""Decorator."""
def _caller(*args, **kwargs):
... | #code from http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html
import redis
REDIS_CLIENT = redis.Redis()
def only_one(function=None, key="", timeout=None):
"""Enforce only one celery task at a time."""
def _dec(run_func):
"""Decorator."""
def _caller(*args, **kwargs):
... | mit | Python |
ca079d54017ac5266a74540011144201b697f421 | fix find_car.py script to use users existing ip | alanwells/donkey,wroscoe/donkey,alanwells/donkey,ricorx7/donkey,wroscoe/donkey,alanwells/donkey,wroscoe/donkey,ricorx7/donkey,ricorx7/donkey,wroscoe/donkey,ricorx7/donkey,kennethjiang/donkey,kennethjiang/donkey,kennethjiang/donkey | scripts/find_car.py | scripts/find_car.py | """
Convienience script to find your Raspberry Pi on a local network.
Usage:
find_car.py
"""
from docopt import docopt
import os
import socket
args = docopt(__doc__)
print('Looking up your computer IP address...')
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8",80))
ip = s.getsockna... | """
Convienience script to find your Raspberry Pi on a local network.
Usage:
find_car.py [--ip=<ip>]
Options:
--ip=<ip> Base ip address of your network [default: 192.168.1.0]
"""
from docopt import docopt
import os
import socket
args = docopt(__doc__)
ip = args['--ip']
print('Looking up your computer IP ... | mit | Python |
c500bfbc77540a76a7ebd3c5ffd66e64437ff9f3 | Update shortest-distance-from-all-buildings.py | kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,githubutilities/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,kamyu104/LeetCo... | Python/shortest-distance-from-all-buildings.py | Python/shortest-distance-from-all-buildings.py | # Time: O(k * m * n), k is the number of the buildings
# Space: O(m * n)
class Solution(object):
def shortestDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def bfs(grid, dists, cnts, x, y):
dist, m, n = 0, len(grid), len(grid[0])
... | # Time: O(k * m * n), k is the number of the buildings
# Space: O(m * n)
class Solution(object):
def shortestDistance(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
def bfs(grid, dists, cnts, x, y):
dist, m, n = 0, len(grid), len(grid[0])
... | mit | Python |
f4b49ed963c8eca7040eee82f91392847c826978 | Update jupyterhub_config.py | luisfdez/oauthenticator,luisfdez/oauthenticator | example/jupyterhub_config.py | example/jupyterhub_config.py | # Configuration file for Jupyter Hub
import os
c = get_config()
c.JupyterHub.log_level = 10
c.JupyterHub.authenticator_class = 'oauthenticator.openshift.OpenShiftOAuthenticator'
c.JupyterHub.spawner_class = 'kubespawner.KubeSpawner'
c.JupyterHub.ip = '0.0.0.0'
c.JupyterHub.hub_ip = '0.0.0.0'
c.JupyterHub.port = 80... | # Configuration file for Jupyter Hub
import os
c = get_config()
c.JupyterHub.log_level = 10
c.JupyterHub.authenticator_class = 'oauthenticator.openshift.OpenShiftOAuthenticator'
c.JupyterHub.spawner_class = 'kubespawner.KubeSpawner'
c.JupyterHub.ip = '0.0.0.0'
c.JupyterHub.hub_ip = '0.0.0.0'
c.JupyterHub.port = 90... | bsd-3-clause | Python |
0913f15b94bb49212f7d890298d6aa470c1d66c1 | add alias | hdm-dt-fb/rvt_model_services,hdm-dt-fb/rvt_model_services | rvt_journal_purger.py | rvt_journal_purger.py | """
Little helper to purge journal logs from /journals,
that are older than certain threshold.
"""
import os
import time
import colorful as col
def purge(journal_dir, threshold_age_days=60):
"""
deletes all files starting with 'journal' older than the threshold_age_days
:param journal_dir:
:param thre... | """
Little helper to purge journal logs from /journals,
that are older than certain threshold.
"""
import os
import time
import colorful
def purge(journal_dir, threshold_age_days=60):
"""
deletes all files starting with 'journal' older than the threshold_age_days
:param journal_dir:
:param threshold_a... | mit | Python |
67b569a5da64cd52682350d95fa02a64d83b7d16 | Update process_availability.py | site24x7/plugins,site24x7/plugins,site24x7/plugins | process_availability/process_availability.py | process_availability/process_availability.py | #!/usr/bin/python
import json
import subprocess
def get_process_details(process_name):
process_cmd = "ps -eo ruser,pid,args | grep -wiE '"+process_name+"' | grep -v grep | grep -v process_availability "
p = subprocess.Popen(process_cmd, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate(... | #!/usr/bin/python
import json
import subprocess
def get_process_details(process_name):
process_cmd = "ps -eo ruser,pid,args | grep -wiE '"+process_name+"' | grep -v grep"
p = subprocess.Popen(process_cmd, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
p_status = p.wait()
ou... | bsd-2-clause | Python |
1170bdd02aa929a7c9a1dccad91be1908bfa06d9 | bump version | amplifylitco/asiaq,amplifylitco/asiaq,amplifylitco/asiaq | disco_aws_automation/version.py | disco_aws_automation/version.py | """Place of record for the package version"""
__version__ = "1.0.89"
__rpm_version__ = "WILL_BE_SET_BY_RPM_BUILD"
__git_hash__ = "WILL_BE_SET_BY_EGG_BUILD"
| """Place of record for the package version"""
__version__ = "1.0.88"
__rpm_version__ = "WILL_BE_SET_BY_RPM_BUILD"
__git_hash__ = "WILL_BE_SET_BY_EGG_BUILD"
| bsd-2-clause | Python |
2562178d79c42753aaea99e9adf4243ca3ca9f57 | fix includes | buildtimetrend/python-lib | buildtimetrend/build.py | buildtimetrend/build.py | #!/usr/bin/env python
'''
vim: set expandtab sw=4 ts=4:
Gathers build related data.
Copyright (C) 2014 Dieter Adriaenssens <ruleant@users.sourceforge.net>
This file is part of buildtime-trend
<https://github.com/ruleant/buildtime-trend/>
This program is free software: you can redistribute it and/or modify
it under ... | #!/usr/bin/env python
'''
vim: set expandtab sw=4 ts=4:
Gathers build related data.
Copyright (C) 2014 Dieter Adriaenssens <ruleant@users.sourceforge.net>
This file is part of buildtime-trend
<https://github.com/ruleant/buildtime-trend/>
This program is free software: you can redistribute it and/or modify
it under ... | agpl-3.0 | Python |
cb1843af3008be46614c7a73658254167c32f95f | Bump version to 0.9.0 | wbtuomela/cartridge,traxxas/cartridge,jaywink/cartridge-reservable,wbtuomela/cartridge,dsanders11/cartridge,Kniyl/cartridge,Kniyl/cartridge,ryneeverett/cartridge,wyzex/cartridge,Parisson/cartridge,stephenmcd/cartridge,Parisson/cartridge,ryneeverett/cartridge,wyzex/cartridge,jaywink/cartridge-reservable,syaiful6/cartrid... | cartridge/__init__.py | cartridge/__init__.py |
__version__ = "0.9.0"
| from __future__ import unicode_literals
__version__ = "0.8.4"
| bsd-2-clause | Python |
5c8f74ce369c66b0902556fe644197a0190443f8 | remove a db query in login with code view | relekang/django-nopassword,mjumbewu/django-nopassword,smajda/django-nopassword,mjumbewu/django-nopassword,relekang/django-nopassword,smajda/django-nopassword | django_nopassword/views.py | django_nopassword/views.py | # -*- coding: utf-8 -*-
import json
from django.conf import settings
from django.contrib.auth.views import login as django_login
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth import login as auth_log... | # -*- coding: utf-8 -*-
import json
from django.conf import settings
from django.contrib.auth.views import login as django_login
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import redirect, render, get_object_or_404
from django.contrib.auth import login as auth_log... | mit | Python |
6f60f6257cbcd0328fcdb0873d88d55772731ba4 | Refactor to separate the function to clean the data | joaojunior/y_text_recommender_system | api/app.py | api/app.py | from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = m... | from flask import Flask
from flask import request
from flask import jsonify
from y_text_recommender_system.recommender import recommend
app = Flask(__name__)
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, payload=None):
Exception.__init__(self)
self.message = m... | mit | Python |
0dce975f09c997e6cd290a5d22f53342e8544f8e | Remove groups from admin | f3r3nc/connect,nlhkabu/connect,f3r3nc/connect,nlhkabu/connect,nlhkabu/connect,nlhkabu/connect,f3r3nc/connect,f3r3nc/connect | connect_config/admin.py | connect_config/admin.py | from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.sites.models import Site
from django.contrib.sites.admin import SiteAdmin
from .models import SiteConfig
class SiteConfigInline(admin.StackedInline):
model = SiteConfig
class CustomSiteAdmin(SiteAdmin):
inline... | from django.contrib import admin
from django.contrib.sites.models import Site
from django.contrib.sites.admin import SiteAdmin
from .models import SiteConfig
class SiteConfigInline(admin.StackedInline):
model = SiteConfig
class CustomSiteAdmin(SiteAdmin):
inlines = (SiteConfigInline,)
# Re-register SiteA... | bsd-3-clause | Python |
3aedd30f087a38a90bafc7b95159971780d0c8a8 | Add snark | blixt/py-starbound,6-lasers/py-starbound | sbon.py | sbon.py | """I call Starbound's binary serialization format SBON because it could've been
BSON, but isn't. :)
"""
import struct
def read_bytes(stream):
length = read_varlen_number(stream)
return stream.read(length)
def read_dynamic(stream):
type = ord(stream.read(1))
if type == 1:
return None
if t... | import struct
def read_bytes(stream):
length = read_varlen_number(stream)
return stream.read(length)
def read_dynamic(stream):
type = ord(stream.read(1))
if type == 1:
return None
if type == 4:
return read_varlen_number_signed(stream)
if type == 5:
return read_string(st... | mit | Python |
0765d3c94b84e8efc540bc0644518fd66e68fbf0 | Add localhost check. | rowhit/h2o-2,h2oai/h2o-2,calvingit21/h2o-2,elkingtonmcb/h2o-2,111t8e/h2o-2,eg-zhang/h2o-2,rowhit/h2o-2,111t8e/h2o-2,rowhit/h2o-2,calvingit21/h2o-2,elkingtonmcb/h2o-2,eg-zhang/h2o-2,calvingit21/h2o-2,vbelakov/h2o,100star/h2o,eg-zhang/h2o-2,vbelakov/h2o,elkingtonmcb/h2o-2,elkingtonmcb/h2o-2,h2oai/h2o,h2oai/h2o-2,eg-zhang... | py/testdir_single_jvm/test_with_a_browser.py | py/testdir_single_jvm/test_with_a_browser.py | # this lets me be lazy..starts the cloud up like I want from my json, and gives me a browser
# copies the jars for me, etc. Just hangs at the end for 10 minutes while I play with the browser
import unittest
import time,sys
sys.path.extend(['.','..','py'])
import h2o_cmd, h2o, h2o_hosts
import h2o_browse as h2b
class ... | # this lets me be lazy..starts the cloud up like I want from my json, and gives me a browser
# copies the jars for me, etc. Just hangs at the end for 10 minutes while I play with the browser
import unittest
import time,sys
sys.path.extend(['.','..','py'])
import h2o_cmd, h2o, h2o_hosts
import h2o_browse as h2b
class ... | apache-2.0 | Python |
d5112bf943035e774d00e7d05908a4093367a471 | Fix a syntax error | tebriel/dd-agent,AntoCard/powerdns-recursor_check,guruxu/dd-agent,tebriel/dd-agent,darron/dd-agent,tebriel/dd-agent,huhongbo/dd-agent,JohnLZeller/dd-agent,ess/dd-agent,eeroniemi/dd-agent,ess/dd-agent,relateiq/dd-agent,Shopify/dd-agent,truthbk/dd-agent,jamesandariese/dd-agent,jyogi/purvar-agent,darron/dd-agent,amalakar/... | checks/agent_metrics.py | checks/agent_metrics.py | import threading
from checks import Check
MAX_THREADS_COUNT = 50
MAX_COLLECTION_TIME = 30
MAX_EMIT_TIME = 5
MAX_CPU_PCT = 10
class CollectorMetrics(Check):
def __init__(self, logger):
Check.__init__(self, logger)
self.logger = logger
self.gauge('datadog.collector.collection.time')
... | import threading
from checks import Check
MAX_THREADS_COUNT = 50
MAX_COLLECTION_TIME = 30
MAX_EMIT_TIME = 5
MAX_CPU_PCT = 10
class CollectorMetrics(Check):
def __init__(self, logger):
Check.__init__(self, logger)
self.logger = logger
self.gauge('datadog.collector.collection.time')
... | bsd-3-clause | Python |
5d9162a6d739eea9a604d466f2848bdb6561ffaf | Add required imports | sjktje/sjkscan,sjktje/sjkscan | scan.py | scan.py | #!/usr/bin/env python
# encoding: utf-8
import os
import subprocess
from wand.image import Image
def run_cmd(args):
"""Run shell command."""
if isinstance(args, list):
args = ' '.join(args)
subprocess.run(args, stderr=subprocess.STDOUT, shell=True)
def scan(output_directory):
"""Run scan... | #!/usr/bin/env python
# encoding: utf-8
from wand.image import Image
def run_cmd(args):
"""Run shell command."""
if isinstance(args, list):
args = ' '.join(args)
subprocess.run(args, stderr=subprocess.STDOUT, shell=True)
def scan(output_directory):
"""Run scanimage in batch mode."""
c... | bsd-2-clause | Python |
0fef227916878b457df0041ac0efca24661388e9 | fix bug | xmaruto/mcord,cboling/xos,opencord/xos,zdw/xos,xmaruto/mcord,jermowery/xos,cboling/xos,wathsalav/xos,cboling/xos,zdw/xos,xmaruto/mcord,wathsalav/xos,open-cloud/xos,xmaruto/mcord,wathsalav/xos,jermowery/xos,jermowery/xos,opencord/xos,zdw/xos,zdw/xos,open-cloud/xos,jermowery/xos,opencord/xos,wathsalav/xos,cboling/xos,cbo... | planetstack/observer/steps/sync_roles.py | planetstack/observer/steps/sync_roles.py | import os
import base64
from django.db.models import F, Q
from planetstack.config import Config
from observer.openstacksyncstep import OpenStackSyncStep
from core.models.role import Role
from core.models.site import SiteRole
from core.models.slice import SliceRole
from core.models.deployment import DeploymentRole
clas... | import os
import base64
from django.db.models import F, Q
from planetstack.config import Config
from observer.openstacksyncstep import OpenStackSyncStep
from core.models.role import Role
from core.models.site import SiteRole
from core.models.slice import SliceRole
from core.models.deployment import DeploymentRole
clas... | apache-2.0 | Python |
2cc51dd426f53b699a544ef34984dc9efdfe03cc | Fix trailing slashes in URLconfs | lovehhf/xblock-sdk,lovehhf/XBlock,stvstnfrd/xblock-sdk,edx-solutions/XBlock,Lyla-Fischer/xblock-sdk,edx/xblock-sdk,lovehhf/xblock-sdk,Pilou81715/hackathon_edX,EDUlib/XBlock,cpennington/XBlock,nagyistoce/edx-XBlock,edx-solutions/XBlock,edx-solutions/xblock-sdk,edx/xblock-sdk,nagyistoce/edx-xblock-sdk,Pilou81715/hackatho... | debugger/urls.py | debugger/urls.py | from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('debugger.views',
url(r'^$', 'index', name='index'),
url(... | from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('debugger.views',
url(r'^$', 'index', name='index'),
url(... | apache-2.0 | Python |
7785d3129d089ce99aee340b3a72fd78d7e8f556 | Store your username in a file | NickGeek/WiN,NickGeek/WiN,NickGeek/WiN | send.py | send.py | import os
if os.path.exists("account.conf") is False:
sender = str(raw_input("Your Username: "))
accountFile = open('account.conf', 'w+')
accountFile.write(sender)
accountFile.close()
else:
accountFile = open('account.conf', 'r')
sender = accountFile.read()
accountFile.close()
target = str(raw_input("Target's ... | import os
sender = str(raw_input("Your Username: "))
target = str(raw_input("Target's Username: "))
message = str(raw_input("Message: "))
#Messages are encoded like so "senderProgramVx.x##target##sender##message"
#Example: "linuxV1.8##person87##NickGeek##Hey mate! What do you think of this WiN thing?"
formattedMessag... | mit | Python |
91d216d93b2070abe6a04686e4b3b030b252a48a | Make bundle reader more bulletproof | wcpr740/wcpr.org,wcpr740/wcpr.org,wcpr740/wcpr.org | flask_site/helpers/assets.py | flask_site/helpers/assets.py | import os
from webassets import filter
from flask_assets import Environment, Bundle
from flask_site.libraries.csscompressor_webassets import CSSCompressor
def register_filters():
# This compressor is better than the one built into webassets
filter.register_filter(CSSCompressor)
def compile_assets(app, bu... | import os
from webassets import filter
from flask_assets import Environment, Bundle
from flask_site.libraries.csscompressor_webassets import CSSCompressor
def register_filters():
# This compressor is better than the one built into webassets
filter.register_filter(CSSCompressor)
def compile_assets(app, bu... | apache-2.0 | Python |
3444468ec24ad53a7c713b6461be4c3ad7b4ba2c | fix recent games parser | bozhko-egor/dota2-discord-bot | dota2bot/recent_games_parser.py | dota2bot/recent_games_parser.py | from token_and_api_key import *
import pymongo
from parser import Parser
conn = pymongo.MongoClient()
db = conn['dota2-db']
def get_recent_matches(player_id):
p = 0
custom_args = {'players.account_id': player_id}
cursor = db['matches_all'].find(custom_args)
cursor.sort('start_time', -1)
hist = l... | from token_and_api_key import *
import pymongo
from parser import Parser
conn = pymongo.MongoClient()
db = conn['dota2-db']
def get_recent_matches(player_id):
p = 0
custom_args = {'players.account_id': player_id}
cursor = db['matches_all'].find(custom_args)
cursor.sort('start_time', -1)
hist = l... | mit | Python |
c9ee351df0afd96da8d3d9ade9934d4cbcd5122e | Update class_activation_map.py | philipperemy/tensorflow-class-activation-mapping | class_activation_map.py | class_activation_map.py | import matplotlib.pyplot as plt
import tensorflow as tf
from skimage.io import imsave
from utils import mkdir_p
def get_class_map(label, conv, im_width):
output_channels = int(conv.get_shape()[-1])
conv_resized = tf.image.resize_bilinear(conv, [im_width, im_width])
with tf.variable_scope('LeNet/GAP', reu... | import matplotlib.pyplot as plt
import tensorflow as tf
from skimage.io import imsave
from utils import mkdir_p
def get_class_map(label, conv, im_width):
output_channels = int(conv.get_shape()[-1])
conv_resized = tf.image.resize_bilinear(conv, [im_width, im_width])
with tf.variable_scope('LeNet/GAP', reu... | mit | Python |
eba2f3db3caa867e8b316f68bd808c3a6bc0c61c | Change LOG_LEVEL to INFO | MaxLikelihood/CODE | dataset/dataset/settings.py | dataset/dataset/settings.py | # Scrapy settings for dataset project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'dataset'
SPIDER_MODULES = ['dataset.spiders']
NEWSPIDER_MODULE = 'dataset.s... | # Scrapy settings for dataset project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'dataset'
SPIDER_MODULES = ['dataset.spiders']
NEWSPIDER_MODULE = 'dataset.s... | mit | Python |
9ac2be1bbfb7c28f7c29dd938bd276754271a0f0 | Update __init__.py | arteria/django-copywriting,arteria/django-copywriting | copywriting/__init__.py | copywriting/__init__.py | __version__ = "0.1.6"
| __version__ = "0.1.5"
| mit | Python |
3fd4b6b60415fd5cc79dc2aebc00b7791d2dcaa8 | Add a girder-client console script | kotfic/girder,jbeezley/girder,Kitware/girder,kotfic/girder,data-exp-lab/girder,RafaelPalomar/girder,RafaelPalomar/girder,Kitware/girder,kotfic/girder,data-exp-lab/girder,kotfic/girder,Xarthisius/girder,girder/girder,data-exp-lab/girder,jbeezley/girder,data-exp-lab/girder,adsorensen/girder,Xarthisius/girder,Kitware/gird... | clients/python/setup.py | clients/python/setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 ... | apache-2.0 | Python |
905f2d69a3720796e8ff7752b85d1bb5d6dab556 | change default value | RasaHQ/rasa_nlu,RasaHQ/rasa_nlu,RasaHQ/rasa_nlu | rasa/nlu/featurizers/featurzier.py | rasa/nlu/featurizers/featurzier.py | import numpy as np
from typing import Any, Text
from rasa.nlu.training_data import Message
from rasa.nlu.components import Component
from rasa.nlu.constants import (
MESSAGE_VECTOR_SPARSE_FEATURE_NAMES,
MESSAGE_VECTOR_DENSE_FEATURE_NAMES,
MESSAGE_TEXT_ATTRIBUTE,
)
class Featurizer(Component):
@static... | import numpy as np
from typing import Any, Text
from rasa.nlu.training_data import Message
from rasa.nlu.components import Component
from rasa.nlu.constants import (
MESSAGE_VECTOR_SPARSE_FEATURE_NAMES,
MESSAGE_TEXT_ATTRIBUTE,
)
class Featurizer(Component):
@staticmethod
def _combine_with_existing_de... | apache-2.0 | Python |
fed170afc901b8030946aa3574c046b539cb9361 | fix backup status bug - now successfully log one-file backup system | sparcs-kaist/heartbeat-server,sparcs-kaist/heartbeat-server,sparcs-kaist/heartbeat-server | apps/core/management/commands/backup.py | apps/core/management/commands/backup.py | from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import localtime
from apps.core.models import Server, BackupTarget, BackupLog
from croniter import croniter
from datetime import datetime
import pytz
import os
class Command(BaseCommand):
help = 'Updat... | from django.core.management.base import BaseCommand
from django.utils import timezone
from django.utils.timezone import localtime
from apps.core.models import Server, BackupTarget, BackupLog
from croniter import croniter
from datetime import datetime
import pytz
import os
class Command(BaseCommand):
help = 'Updat... | mit | Python |
f433efdbb2e1db4a2ec41cbb01dc0b42e0c217eb | make Engine instance callable | shmilee/gdpy3,shmilee/gdpy3,shmilee/gdpy3,shmilee/gdpy3 | gdpy3/plot/enginelib/base.py | gdpy3/plot/enginelib/base.py | # -*- coding: utf-8 -*-
# Copyright (c) 2017 shmilee
'''
Defines :class:`.Engine`
'''
import types
__all__ = ['Engine']
class Engine(object):
'''
engine class
Attributes
----------
name: str
figure_factory: function
Use FigureStructure to create a Figure instance
style_availab... | # -*- coding: utf-8 -*-
# Copyright (c) 2017 shmilee
'''
Defines :class:`.Engine`
'''
import types
__all__ = ['Engine']
class Engine(object):
'''
engine class
Attributes
----------
name: str
figure_factory: function
Use FigureStructure to create a Figure instance
style_availab... | mit | Python |
2ab8ef2764b438cc83a1af092330dba4c4a4d2f2 | change score type from Integer to Float | DevMine/devmine-core | devmine/app/models/score.py | devmine/app/models/score.py | from sqlalchemy import (
Column,
Integer,
ForeignKey,
String,
Float
)
from devmine.app.models import Base
class Score(Base):
"""Model of a score."""
__tablename__ = 'scores'
id = Column(Integer, primary_key=True)
ulogin = Column(String,
ForeignKey('users.logi... | from sqlalchemy import (
Column,
Integer,
ForeignKey,
String
)
from devmine.app.models import Base
class Score(Base):
"""Model of a score."""
__tablename__ = 'scores'
id = Column(Integer, primary_key=True)
ulogin = Column(String,
ForeignKey('users.login'),
... | bsd-3-clause | Python |
01bc6f808f0c184dd03550a3d639fd2b0bfe93c6 | include a status code in the response | thenetcircle/dino,thenetcircle/dino,thenetcircle/dino,thenetcircle/dino | dino/rest/resources/base.py | dino/rest/resources/base.py | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | #!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | apache-2.0 | Python |
58f96dd405586aa669598b23c09080bcb46c7edc | Add list args | JDevlieghere/dotfiles,Gres/dotfiles,Gres/dotfiles,JDevlieghere/dotfiles,JDevlieghere/dotfiles,Gres/dotfiles | scripts/llvm-cmake.py | scripts/llvm-cmake.py | #!/usr/bin/env python
import argparse
import subprocess
parser = argparse.ArgumentParser(
description=
"CMake configuration options are relatively verbose and remembering the "
"ones you don't use that often can be a real pain. This scripts attempts "
"to reduce some of the most commonly used options ... | #!/usr/bin/env python
import argparse
import subprocess
parser = argparse.ArgumentParser(
description=
"CMake configuration options are relatively verbose and remembering the "
"ones you don't use that often can be a real pain. This scripts attempts "
"to reduce some of the most commonly used options ... | mit | Python |
6a938d8755a8e887f07fa34ac910c2e4e8247756 | attach gdb again | HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak,HPI-SWA-Lab/RSqueak | rsqueakvm/plugins/v_m_debugging.py | rsqueakvm/plugins/v_m_debugging.py | import os
from rsqueakvm import error
from rsqueakvm.model.variable import W_BytesObject
from rsqueakvm.plugins.plugin import Plugin
from rsqueakvm.util.system import IS_WINDOWS
VMDebugging = Plugin()
VMDebugging.userdata['stop_ui'] = False
def stop_ui_process():
VMDebugging.userdata['stop_ui'] = True
# @VMDebu... | import os
from rsqueakvm import error
from rsqueakvm.model.variable import W_BytesObject
from rsqueakvm.plugins.plugin import Plugin
from rsqueakvm.util.system import IS_WINDOWS
VMDebugging = Plugin()
VMDebugging.userdata['stop_ui'] = False
def stop_ui_process():
VMDebugging.userdata['stop_ui'] = True
# @VMDebu... | bsd-3-clause | Python |
ba98b8088bd11c45b11b9eb04635a3aa1733bd86 | remove unnecessary import | CottageLabs/finance,CottageLabs/finance,CottageLabs/finance,CottageLabs/finance | service/database.py | service/database.py | from flask.ext.sqlalchemy import SQLAlchemy
from octopus.core import app
db = SQLAlchemy(app)
from service import models # initialise SQLAlchemy mappings with our models
__api_tables = db.metadata.tables.__reduce__()[1][0]
# remove all non-api tables from our temporary list
NON_FA_API_TABLE_NAMES = ['server_costs']
... | from flask.ext.sqlalchemy import SQLAlchemy
from octopus.core import app
from copy import deepcopy
db = SQLAlchemy(app)
from service import models # initialise SQLAlchemy mappings with our models
__api_tables = db.metadata.tables.__reduce__()[1][0]
# remove all non-api tables from our temporary list
NON_FA_API_TABLE... | apache-2.0 | Python |
5f5da50c674dbde7f186f40473ed2a2c0470b29f | Fix a few small problems | ilayn/scipy,surhudm/scipy,fredrikw/scipy,nvoron23/scipy,grlee77/scipy,pbrod/scipy,arokem/scipy,jsilter/scipy,mhogg/scipy,mortonjt/scipy,sauliusl/scipy,jjhelmus/scipy,woodscn/scipy,hainm/scipy,FRidh/scipy,pbrod/scipy,WillieMaddox/scipy,lukauskas/scipy,rgommers/scipy,ndchorley/scipy,maciejkula/scipy,aman-iitj/scipy,ndcho... | scipy/sandbox/exmplpackage/tests/test_foo.py | scipy/sandbox/exmplpackage/tests/test_foo.py | """Example SciPy test module, using nose features.
For information on nose, see:
http://somethingaboutorange.com/mrl/projects/nose
To run it in its simplest form::
nosetests test_foo.py
Labels will be implemented as one decorator per test. All pre-defined labels
are implemented in numpy.testing.decorators
Th... | """Example SciPy test module, using nose features.
For information on nose, see:
http://somethingaboutorange.com/mrl/projects/nose
To run it in its simplest form::
nosetests test_foo.py
Labels will be implemented as one decorator per test. All pre-defined labels
are implemented in numpy.testing.decorators
Th... | bsd-3-clause | Python |
fcdbfc3d119f67ffb44f2782a38386b969f9505f | update release branch format | NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs,NixOS/nixpkgs | pkgs/applications/virtualization/crosvm/update.py | pkgs/applications/virtualization/crosvm/update.py | #! /usr/bin/env nix-shell
#! nix-shell -p common-updater-scripts python3
#! nix-shell -i python
import csv
import json
import re
import shlex
import subprocess
from os.path import abspath, dirname, splitext
from urllib.request import urlopen
# CrOS version numbers look like this:
# [<chrome-major-version>.]<tip-build... | #! /usr/bin/env nix-shell
#! nix-shell -p common-updater-scripts python3
#! nix-shell -i python
import csv
import json
import re
import shlex
import subprocess
from os.path import abspath, dirname, splitext
from urllib.request import urlopen
# CrOS version numbers look like this:
# [<chrome-major-version>.]<tip-build... | mit | Python |
90b2457f6b2eeb7df93d80f1663e6d98e9816932 | allow other arguments to unanswered query | hguemar/website,hguemar/website,hguemar/website,hguemar/website,hguemar/website | scripts/unanswered.py | scripts/unanswered.py | #!/usr/bin/python
import urllib2
import json
import sys
# Magic
import sys # sys.setdefaultencoding is cancelled by site.py
reload(sys) # to re-enable sys.setdefaultencoding()
sys.setdefaultencoding('utf-8')
keyword = sys.argv[1] if len(sys.argv) >= 2 else 'rdo'
url = 'https://ask.openstack.org/en/api/v1/quest... | #!/usr/bin/python
import urllib2
import json
# Magic
import sys # sys.setdefaultencoding is cancelled by site.py
reload(sys) # to re-enable sys.setdefaultencoding()
sys.setdefaultencoding('utf-8')
url = 'https://ask.openstack.org/en/api/v1/questions/?scope=unanswered&query=rdo&sort=age-desc'
response = urllib2... | mit | Python |
7e577adc6ac8d9bd940ee6e0530916ddd4291849 | Correct dataset access. | ResidentMario/geoplot | geoplot/datasets/datasets.py | geoplot/datasets/datasets.py | """
User-facing utility module for downloading example datasets. Similar to the `geopandas.datasets` namespace.
"""
import geopandas as gpd
import fiona
from zipfile import ZipFile
from pkg_resources import resource_stream, resource_listdir
def load(dname):
"""
Retrieves a dataset by name.
Parameters
... | """
User-facing utility module for downloading example datasets. Similar to the `geopandas.datasets` namespace.
"""
import geopandas as gpd
import fiona
from zipfile import ZipFile
def load(dname):
"""
Retrieves a dataset by name.
Parameters
----------
dname : str
Name of the dataset to ... | mit | Python |
608a4a3227626588c93d77f3af21d5baea368caf | Bump version. | mishbahr/djangocms-gmaps,mishbahr/djangocms-gmaps,mishbahr/djangocms-gmaps | djangocms_gmaps/__init__.py | djangocms_gmaps/__init__.py | __version__ = '0.1.3.3' | __version__ = '0.1.3.2' | bsd-3-clause | Python |
ba241d309df4ff24d0a8096da6c999e474ea3c0f | Fix 'unexpected keyword argument' issue | locke105/gitoriouslib | gitoriouslib/cmd/__init__.py | gitoriouslib/cmd/__init__.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Mathew Odden <locke105@gmail.com>
#
# 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/licen... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Mathew Odden <locke105@gmail.com>
#
# 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/licen... | apache-2.0 | Python |
a519b3710ffe59e24f3f9c82d37f612c8abf1597 | test utils | proyectosdeley/proyectos_de_ley,proyectosdeley/proyectos_de_ley,proyectosdeley/proyectos_de_ley,proyectosdeley/proyectos_de_ley | proyectos_de_ley/seguimientos/tests/test_utils.py | proyectos_de_ley/seguimientos/tests/test_utils.py | from django.test import TestCase
from pdl.models import Proyecto, Seguimientos
from seguimientos import utils
class Object(object):
"""Dummy class for testing."""
pass
class TestSeguimientos(TestCase):
def setUp(self):
proyecto = Proyecto(**{
"numero_proyecto": "02764/2013-CR",
... | from django.test import TestCase
from pdl.models import Proyecto
from seguimientos import utils
class Object(object):
"""Dummy class for testing."""
pass
class SimpleTestSeguimientos(TestCase):
def test_get_proyecto_from_short_url(self):
short_url = "4zhube"
expected = {
"nu... | mit | Python |
42e4f42901872433f90dd84d5acf04fec76ab7f3 | Add better __repr__s for commands errors. | SunDwarf/curious | curious/commands/exc.py | curious/commands/exc.py | class CommandsError(Exception):
pass
class CheckFailureError(Exception):
def __init__(self, ctx, check):
self.ctx = ctx
self.check = check
def __repr__(self):
if isinstance(self.check, list):
return "The checks for `{.name}` failed.".format(self.ctx)
return "Th... | class CommandsError(Exception):
pass
class CheckFailureError(Exception):
def __init__(self, ctx, check):
self.ctx = ctx
self.check = check
def __repr__(self):
if isinstance(self.check, list):
return "The checks for {.name} failed.".format(self.ctx)
return "The ... | mit | Python |
440a9f7ec6c360db8ac5d929bb0d3c5511d2edc9 | Add question column to sqlite insert | andrewlrogers/srvy | srvy.py | srvy.py | from gpiozero import Button
from time import sleep
from datetime import datetime
import random
import sqlite3
from signal import pause
print('initializing variables')
like = Button(18)
okay = Button(14)
dislike = Button(15)
questions = ['Did you enjoy your visit today?', 'Would you reccomend us to a friend?', 'Were y... | from gpiozero import Button
from time import sleep
from datetime import datetime
import random
import sqlite3
from signal import pause
print('initializing variables')
like = Button(18)
okay = Button(14)
dislike = Button(15)
questions = ['Did you enjoy your visit today?', 'Would you reccomend us to a friend?', 'Were y... | mit | Python |
87da5b975b85780e07ae62b9b4e1565fe448ea55 | improve layout | sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana,sequana/sequana | sequana/report_fix.py | sequana/report_fix.py | import easydev
import os
from .report_main import BaseReport
# a utility from external reports package
from reports import HTMLTable
import pandas as pd
def _get_template_path(name):
# Is it a local directory ?
if os.path.exists(name):
return name
else:
template_path = easydev.get_... | import easydev
import os
from .report_main import BaseReport
# a utility from external reports package
from reports import HTMLTable
import pandas as pd
def _get_template_path(name):
# Is it a local directory ?
if os.path.exists(name):
return name
else:
template_path = easydev.get_... | bsd-3-clause | Python |
d7c960324ce680ed0b662ada3663a9f3d2b32a61 | Fix for uiautomator tests. | dushu1203/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,Chilledheart/chromium,M4sse/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chr... | build/android/pylib/uiautomator/test_runner.py | build/android/pylib/uiautomator/test_runner.py | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Class for running uiautomator tests on a single device."""
from pylib.instrumentation import test_runner as instr_test_runner
class TestRunner(inst... | # Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Class for running uiautomator tests on a single device."""
from pylib.instrumentation import test_runner as instr_test_runner
class TestRunner(inst... | bsd-3-clause | Python |
d8179c0006fb5b9983898e4cd93ffacfe3fdd54f | Support conversion format as extension, instead of mimetype | makinacorpus/Geotrek,Anaethelion/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,mabhub/Geotrek,GeotrekCE/Geotrek-admin,Anaethelion/Geotrek,johan--/Geotrek,camillemonchicourt/Geotrek,johan--/Geotrek,mabhub/Geotrek,Anaethelion/Geotrek,camillemonchicourt/Geotrek,GeotrekCE/Geotrek-admin,camillemo... | caminae/mapentity/templatetags/convert_tags.py | caminae/mapentity/templatetags/convert_tags.py | import urllib
from mimetypes import types_map
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def convert_url(request, sourceurl, format='pdf'):
if '/' not in format:
extension = '.' + format if not format.startswith('.') else format
... | import urllib
from django import template
from django.conf import settings
register = template.Library()
@register.simple_tag
def convert_url(request, sourceurl, format='pdf'):
fullurl = request.build_absolute_uri(sourceurl)
conversion_url = "%s?url=%s&to=%s" % (settings.CONVERSION_SERVER,
... | bsd-2-clause | Python |
0902f7caf513d558cce501c28a46ee83a604db05 | remove default key | LandRegistry/govuk-notify-flask,LandRegistry/govuk-notify-flask | govuk_notify_flask/config.py | govuk_notify_flask/config.py | import os
SECRET_KEY = os.getenv('SECRET_KEY', '13*#iT@1MT1!Satg')
NOTIFY_API_KEY = os.getenv('NOTIFY_API_KEY')
| import os
SECRET_KEY = os.getenv('SECRET_KEY', '13*#iT@1MT1!Satg')
NOTIFY_API_KEY = os.getenv('NOTIFY_API_KEY',
'test-92f7f929-38ba-4425-91a2-86e17dfb7d5a-8e4bb9ee-7c9e-4c8c-b84c-720b9c1b7a41')
| mit | Python |
1097b3fc78aa2d32b6316c2706e152c478c09e63 | Complete recur sol | bowen0701/algorithms_data_structures | lc0931_minimum_falling_path_sum.py | lc0931_minimum_falling_path_sum.py | """Leetcode 931. Minimum Falling Path Sum
Medium
URL: https://leetcode.com/problems/minimum-falling-path-sum/
Given a square array of integers A, we want the minimum sum of a falling
path through A.
A falling path starts at any element in the first row, and chooses one
element from each row. The next row's choice mu... | """Leetcode 931. Minimum Falling Path Sum
Medium
URL: https://leetcode.com/problems/minimum-falling-path-sum/
Given a square array of integers A, we want the minimum sum of a falling
path through A.
A falling path starts at any element in the first row, and chooses one
element from each row. The next row's choice m... | bsd-2-clause | Python |
5513d8a2ad6fe951bb5e2f471ebf162c4d334dfb | Update 3_Data_processing.py | Alumet/Astro-Fuel | Target-Selection/3_Data_processing.py | Target-Selection/3_Data_processing.py | '''
Author Yann HUET 2016
Astro Fuel project
Nasa Space Apps Challenge, 2016 Lyon france
Subject Asteroid Mining
The purpose of this script is to determine possible Asteroid targets to yeild for water
We used the http://www.asterank.com/ database along with the computed_dv
'''
... | '''
Astro Fuel project
Nasa Space Apps Challenge, 2016 Lyon france
Subject Asteroid Mining
The purpose of this script is to determine possible Asteroid targets to yeild for water
We used the http://www.asterank.com/ database along with the computed_dv
'''
import pandas as pd
import num... | mit | Python |
0ba871dabb96985fbcde1fc0c1b546b38c05b3a3 | test ... | ryanrhymes/scandex | test.py | test.py | #!/usr/bin/env python
import httplib
import os
import socket
import sys
class Uhttplib(httplib.HTTPConnection):
"""Subclass of Python library HTTPConnection that
uses a unix-domain socket.
"""
def __init__(self, path):
httplib.HTTPConnection.__init__(self, 'localhost')
self.path = p... | #!/usr/bin/env python
import httplib
import os
import socket
import sys
class Uhttplib(httplib.HTTPConnection):
"""Subclass of Python library HTTPConnection that
uses a unix-domain socket.
"""
def __init__(self, path):
httplib.HTTPConnection.__init__(self, 'localhost')
self.path = p... | mit | Python |
bd21897d3df95b73f1ba2c13cdf07c70a8b28186 | Fix SkImage on ChromeOS | google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbo... | slave/skia_slave_scripts/chromeos_install.py | slave/skia_slave_scripts/chromeos_install.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Install all executables, and any runtime resources that are needed by
*both* Test and Bench builders. """
from build_step ... | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Install all executables, and any runtime resources that are needed by
*both* Test and Bench builders. """
from build_step ... | bsd-3-clause | Python |
91a528877adbb0b7eaf0810bfde67d9dba721028 | test script | danielnyga/dnutils | test.py | test.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import colored
from pymongo import MongoClient
import dnlog
from dnlog import getlogger
from dnutils import out, stop, trace
from dnutils.console import bf, ProgressBar, StatusMsg
db = MongoClient()
dnlog.setup({
'default': dnlog.newlogger(dnlog.console),
... | '''
Created on May 22, 2017
@author: nyga
'''
from dnutils import out, stop, trace
from dnutils.console import get_terminal_size, ProgressBar, StatusMsg
from dnutils.tools import allnone, allnot
from colored import stylize
import colored
import time
import random
def print_globals():
out('here come the locals:'... | mit | Python |
e548ccea71d237630b8ecdff49a7d9c45cea455e | Add reset_seed() for a little more DRYness | foxscotch/foxrollbot | test.py | test.py | import random
from unittest import TestCase, main
from roll import Dice, Roll
def reset_seed():
random.seed(1, version=2)
class DiceTestCase(TestCase):
def setUp(self):
reset_seed()
def test_within_bounds_1d20(self):
dice = Dice(1, 20)
result = sum(dice.roll().results)
... | import random
from unittest import TestCase, main
from roll import Dice, Roll
class DiceTestCase(TestCase):
def setUp(self):
random.seed(1, version=2)
def test_within_bounds_1d20(self):
dice = Dice(1, 20)
result = sum(dice.roll().results)
self.assertGreaterEqual(result, 1)
... | mit | Python |
a22649069248059e5364d9a9c0488ededca44ecd | Move self.ip assignment into setUp. | frostynova/calico-docker,dalanlan/calico-docker,tomdee/calico-containers,Metaswitch/calico-docker,projectcalico/calico-docker,Symmetric/calico-docker,webwurst/calico-docker,quater/calico-containers,robbrockbank/calico-containers,Symmetric/calico-docker,TrimBiggs/calico-docker,fasaxc/calico-docker,caseydavenport/calico-... | calico_containers/tests/st/test_base.py | calico_containers/tests/st/test_base.py | from unittest import TestCase
from docker_host import DockerHost
import sh
from sh import docker
class TestBase(TestCase):
"""Base class for test-wide methods."""
def setUp(self):
"""
Clean up host containers before every test.
"""
containers = docker.ps("-qa").split()
... | from unittest import TestCase
from docker_host import DockerHost
import sh
from sh import docker
class TestBase(TestCase):
"""Base class for test-wide methods."""
def setUp(self):
"""
Clean up host containers before every test.
"""
containers = docker.ps("-qa").split()
... | apache-2.0 | Python |
ed833b69116b25beb1907173050471ad3bf9bfd7 | Remove import from non-longer existing dials.framework. | dials/dials,dials/dials,dials/dials,dials/dials,dials/dials | algorithms/scaling/model/scaling_model_ext.py | algorithms/scaling/model/scaling_model_ext.py | #!/usr/bin/env python
"""
Definitions of scaling model extensions.
"""
from __future__ import absolute_import, division
class ScalingModelIface(object):
'''
The interface definition for a scaling model.
'''
scope = "scaling"
name = 'scaling_model'
@classmethod
def factory(cls):
'''... | #!/usr/bin/env python
"""
Definitions of scaling model extensions.
"""
from __future__ import absolute_import, division
from dials.framework import interface
class ScalingModelIface(interface.Interface):
'''
The interface definition for a scaling model.
'''
scope = "scaling"
name = 'scaling_model'... | bsd-3-clause | Python |
3b76935a93377bb82f250cc64b28eaa415d52564 | Update load_country_dialcode.py | dedayoa/django-country-dialcode,dedayoa/django-country-dialcode | country_dialcode/management/commands/load_country_dialcode.py | country_dialcode/management/commands/load_country_dialcode.py | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.core.management import call_command
import inspect
import os
class Command(BaseCommand):
args = ' '
help = "Load Dial Code\n"
option_list = BaseCommand.option_list
def handle(self, *args, **options):
"""... | # -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.core.management import call_command
import inspect
import os
class Command(BaseCommand):
args = ' '
help = "Load Dial Code\n"
option_list = BaseCommand.option_list
def handle(self, *args, **options):
"""... | mit | Python |
88f606d418bac80c91fea58f3fce200e414d898a | update auto recipe to sort uploads | sebhtml/assembly,levinas/assembly,kbase/assembly,levinas/assembly,kbase/assembly,kbase/assembly,kbase/assembly,sebhtml/assembly,levinas/assembly,sebhtml/assembly | lib/assembly/recipes.py | lib/assembly/recipes.py | scaffolds = """
(begin
(define pp (bhammer (sga_preprocess READS)))
(define sp (spades pp))
(define id (idba pp))
(define gam (gam_ngs sp id))
(quast (upload (sspace pp gam)) (upload (get scaffolds sp)) (upload (get scaffolds id)))
)
"""
auto333 = """
(begin
(define pp (bhammer READS))
(define kval (get best_k ... | scaffolds = """
(begin
(define pp (bhammer (sga_preprocess READS)))
(define sp (spades pp))
(define id (idba pp))
(define gam (gam_ngs sp id))
(quast (upload (sspace pp gam)) (upload (get scaffolds sp)) (upload (get scaffolds id)))
)
"""
auto333 = """
(begin
(define pp (bhammer READS))
(define kval (get best_k ... | mit | Python |
ea6e5bf48ff0ea0cab54b2168e844097863c8b0a | Update local.py | 20tab/twentytab_project,20tab/twentytab_project,20tab/twentytab_project | project_name/settings/local.py | project_name/settings/local.py | from {{ project_name }}.settings.base import *
ALLOWED_HOSTS = ('localhost', '127.0.0.1')
DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = True
USE_DEBUG_TOOLBAR = True
INTERNAL_IPS = ('127.0.0.1', socket.gethostbyname(socket.gethostname()))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgre... | from {{ project_name }}.settings.base import *
ALLOWED_HOSTS = ('localhost', '127.0.0.1')
DEBUG = True
TEMPLATES[0]['OPTIONS']['debug'] = True
USE_DEBUG_TOOLBAR = True
INTERNAL_IPS = ('127.0.0.1', socket.gethostbyname(socket.gethostname()))
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgre... | mit | Python |
e853e0137e59314f5101c178c74fd626984c34ac | Change input from previous processing not from a file | studiawan/pygraphc | pygraphc/similarity/LogTextSimilarity.py | pygraphc/similarity/LogTextSimilarity.py | from pygraphc.preprocess.PreprocessLog import PreprocessLog
from pygraphc.similarity.StringSimilarity import StringSimilarity
from itertools import combinations
class LogTextSimilarity(object):
"""A class for calculating cosine similarity between a log pair. This class is intended for
non-graph based clust... | from pygraphc.preprocess.PreprocessLog import PreprocessLog
from pygraphc.similarity.StringSimilarity import StringSimilarity
from itertools import combinations
class LogTextSimilarity(object):
"""A class for calculating cosine similarity between a log pair. This class is intended for
non-graph based clust... | mit | Python |
48990e67794433553a34a0ea4616863cc6b4fcdd | remove typos | lmzintgraf/MultiMAuS | experiments/run_unimaus.py | experiments/run_unimaus.py | from simulator import parameters
from simulator.transactions_unimaus import UniMausTransactionModel
import time
from simulator.customer_unimaus import GenuineCustomer, FraudulentCustomer
from experiments import result_handling
def run_single():
start_time = time.time()
# initialise the model with some param... | from simulator import parameters
from simulator.transactions_unimaus import UniMausTransactionModel
import time
from simulator.customer_unimaus import GenuineCustomer, FraudulentCustomer
from experiments.results import result_handling
def run_single():
start_time = time.time()
# initialise the model with so... | mit | Python |
74b9473a3f779507797f00380699448091c967b9 | fix the name of the testing class | heprom/pymicro | pymicro/crystal/tests/test_Quaternion.py | pymicro/crystal/tests/test_Quaternion.py | import unittest
import numpy as np
from math import cos, sin
from pymicro.crystal.microstructure import Orientation
class QuaternionTests(unittest.TestCase):
def setUp(self):
print('testing the Quaternion class')
self.euler_deg = [343.580, 128.653, 290.986]
def test_Euler2Quaternion(self):
... | import unittest
import numpy as np
from math import cos, sin
from pymicro.crystal.microstructure import Orientation
class LatticeTests(unittest.TestCase):
def setUp(self):
print('testing the Quaternion class')
self.euler_deg = [343.580, 128.653, 290.986]
def test_Euler2Quaternion(self):
... | mit | Python |
9dbcf5bb1d49be1391987408e0b4a7fceafae503 | reset handlers when setting logger | jarodwilson/atomic-reactor,shaded-enmity/atomic-reactor,david-martin/atomic-reactor,vrutkovs/atomic-reactor,shaded-enmity/atomic-reactor,maxamillion/atomic-reactor,fr34k8/atomic-reactor,mmilata/atomic-reactor,david-martin/atomic-reactor,jpopelka/atomic-reactor,fatherlinux/atomic-reactor,DBuildService/atomic-reactor,DBu... | dock/__init__.py | dock/__init__.py | """
constants
"""
import logging
from dock.api import *
def set_logging(level=logging.DEBUG):
# create logger
logger = logging.getLogger('dock')
logger.handlers = []
logger.setLevel(level)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.D... | """
constants
"""
import logging
from dock.api import *
def set_logging(level=logging.DEBUG):
# create logger
logger = logging.getLogger('dock')
logger.setLevel(level)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create forma... | bsd-3-clause | Python |
e55de50d836c6a9e86b94fa6ad5393e61f0da9be | Add volume api | interhui/docker-api,PinaeCloud/docker-api | docker/volume.py | docker/volume.py | # coding=utf-8
from text import string_utils as str_utils
class Volume():
def __init__(self, session):
self.session = session
def list(self, filters = None):
params = {'filters': filters}
url = self.session._url('/volumes')
return self.session._result(self.session._ge... | # coding=utf-8
class Volumn():
def __init__(self):
pass | apache-2.0 | Python |
2fc2017483f4dd212c748f9fc39a6471421b873d | Test assignment of persistent attribute through dictionary interface | analytics-pros/universal-analytics-python | test.py | test.py | #!/usr/bin/python
###############################################################################
# Test and example kit for Universal Analytics for Python
# Copyright (c) 2013, Analytics Pros
#
# This project is free software, distributed under the BSD license.
# Analytics Pros offers consulting and integration serv... | #!/usr/bin/python
###############################################################################
# Test and example kit for Universal Analytics for Python
# Copyright (c) 2013, Analytics Pros
#
# This project is free software, distributed under the BSD license.
# Analytics Pros offers consulting and integration serv... | bsd-3-clause | Python |
a0acc951046f2e9e3958817bc3411eb58ca0d7f7 | Update an example | thombashi/pytablereader,thombashi/pytablereader,thombashi/pytablereader | examples/load_table_from_csv.py | examples/load_table_from_csv.py | #!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
import pytablereader
# prepare data ---
file_path = "sample_data.csv"
csv_text = "\n".join([
'"attr_a","attr_b","attr_c"',
'1,4,"a"',
'2,2.1,"bb"',
'3,120.9,"ccc"',
])
with open(file_path, "w") as f:
f.write(csv_text)
... | #!/usr/bin/env python
# encoding: utf-8
from __future__ import print_function
import pytablereader
# prepare data ---
file_path = "sample_data.csv"
csv_text = "\n".join([
'"attr_a","attr_b","attr_c"',
'1,4,"a"',
'2,2.1,"bb"',
'3,120.9,"ccc"',
])
with open(file_path, "w") as f:
f.write(csv_text)
... | mit | Python |
b745cccff78e7d8543f406a13c861520e419fdd7 | Add help option test | reubano/csv2ofx,reubano/csv2ofx | test.py | test.py | #!/usr/bin/env python
""" A script to test csv2ofx functionality """
import os
import sys
from hashlib import md5
from tempfile import NamedTemporaryFile
from sys import exit
from scripttest import TestFileEnvironment
def main():
try:
env = TestFileEnvironment('.scripttest')
dir = os.path.dirname(__file__)
... | #!/usr/bin/env python
""" A script to test csv2ofx functionality """
import os
import sys
from hashlib import md5
from tempfile import NamedTemporaryFile
from sys import exit
from scripttest import TestFileEnvironment
def main():
try:
env = TestFileEnvironment('.scripttest')
dir = os.path.dirname(__file__)
e... | mit | Python |
8c36cf669564ed391475b47f0459223fb2e75b10 | Write test for two gaussians. | gabraganca/instprofile | test.py | test.py | import numpy as np
from instprofile import peakdet
def test_one_gaussian():
"""
test the `peakdet` function with one gaussian.
"""
gaussian = lambda x: peak*np.exp(-(mean-x)**2/(2*stdev**2))
x_vector = np.arange(0, 100.5, 0.5)
peak = 1
stdev = 0.1
# the peakdet function does not obtai... | import numpy as np
from instprofile import peakdet
def test_one_gaussian():
"""
test the `peakdet` function with one gaussian.
"""
gaussian = lambda x: peak*np.exp(-(mean-x)**2/(2*stdev**2))
x_vector = np.arange(0, 100.5, 0.5)
peak = 1
stdev = 0.1
# the peakdet function does not obtai... | bsd-3-clause | Python |
b466938521ee0c4fbe06d958be7e91f45fdf022b | Add tests | codeforamerica/bongo | test.py | test.py | """
Unit tests for the Bongo API wrapper.
"""
import unittest
from mock import Mock, MagicMock
from bongo import Bongo
from bongo import bongo
def set_up_test(test):
"""A small function for setting up test cases."""
bongo.req = MagicMock()
bongo.json.loads = Mock()
test.get = bongo.req.get
class B... | bsd-3-clause | Python | |
039113c5843ddffb89b6fc7077a54713ce0e7da5 | Update center format in tests | numberoverzero/kmeans,numberoverzero/kmeans | test.py | test.py | from kmeans import kmeans
def test_single_point():
value = [0, 10, 20]
points = [
[value, 1]
]
k = 1
means = kmeans(points, k)
assert 1 == len(means)
assert value == means[0]
def test_single_point_with_guess():
value = [0, 10, 20]
guess = [(-20, 50, 100), 1]
points = ... | from kmeans import kmeans
def test_single_point():
value = [0, 10, 20]
points = [
[value, 1]
]
k = 1
means = kmeans(points, k)
assert 1 == len(means)
assert value == means[0]
def test_single_point_with_guess():
value = [0, 10, 20]
guess = [-20, 50, 100]
points = [
... | mit | Python |
d3cdc1d68868dd40d4ba4ee6a58f453531bcc167 | update to 2 second refresh | balrog95/MirrorV | test.py | test.py | #!/usr/bin/python
from tkinter import Tk, Frame, Label, BOTH
import time
class MirrorV(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("MirrorV")
self.makeFulls... | #!/usr/bin/python
from tkinter import Tk, Frame, Label, BOTH
import time
class MirrorV(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("MirrorV")
self.makeFulls... | mit | Python |
9dd5b7ece854c5f34b163f30679dbaa5c444ae1a | add "gobject list"-style output method | dashpay/sentinel,thelazier/sentinel,thelazier/sentinel,ivansib/sentinel,dashpay/sentinel,ivansib/sentinel | lib/queue_gov_object.py | lib/queue_gov_object.py | import os
import sys
sys.path.append( os.path.join( os.path.dirname(__file__), '..', 'lib' ) )
import models
# mixin for GovObj composed classes like proposal and superblock, etc.
class GovernanceClass(object):
def create_and_queue(self):
# ensure unique name in govobj table...
# ( we really need ... | import os
import sys
sys.path.append( os.path.join( os.path.dirname(__file__), '..', 'lib' ) )
import models
# mixin for GovObj composed classes like proposal and superblock, etc.
class GovernanceClass(object):
def create_and_queue(self):
# ensure unique name in govobj table...
# ( we really need ... | mit | Python |
093b920647d449168b95bef0e6cd8e4324c9cff8 | Implement CardXML.name and CardXML.description | Meerkov/fireplace,smallnamespace/fireplace,butozerca/fireplace,liujimj/fireplace,oftc-ftw/fireplace,liujimj/fireplace,beheh/fireplace,amw2104/fireplace,amw2104/fireplace,Ragowit/fireplace,Meerkov/fireplace,oftc-ftw/fireplace,NightKev/fireplace,butozerca/fireplace,jleclanche/fireplace,smallnamespace/fireplace,Ragowit/fi... | fireplace/cards/cardxml.py | fireplace/cards/cardxml.py | import os
from xml.etree import ElementTree
from fireplace.enums import GameTag, PlayReq
class CardXML(object):
def __init__(self, xml):
self.xml = xml
@property
def id(self):
return self.xml.attrib["CardID"]
@property
def entourage(self):
cards = self.xml.findall("EntourageCard")
return [tag.attrib["c... | import os
from xml.etree import ElementTree
from fireplace.enums import GameTag, PlayReq
class CardXML(object):
def __init__(self, xml):
self.xml = xml
@property
def id(self):
return self.xml.attrib["CardID"]
@property
def entourage(self):
cards = self.xml.findall("EntourageCard")
return [tag.attrib["c... | agpl-3.0 | Python |
7511fc239452277334da14dee806fb4f6dd50805 | Rename function | basepi/hubble,basepi/hubble | hubblestack/extmods/grains/configgrains.py | hubblestack/extmods/grains/configgrains.py | # -*- coding: utf-8 -*-
import salt.modules.config
salt.modules.config.__pillar__ = {}
salt.modules.config.__grains__ = {}
__salt__ = {'config.get': salt.modules.config.get}
def configgrains():
'''
Given a list of config values, create custom grains with custom names.
The list comes from config.
''... | # -*- coding: utf-8 -*-
import salt.modules.config
salt.modules.config.__pillar__ = {}
salt.modules.config.__grains__ = {}
__salt__ = {'config.get': salt.modules.config.get}
def splunkindex():
'''
Given a list of config values, create custom grains with custom names.
The list comes from config.
'''... | apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.