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 |
|---|---|---|---|---|---|---|---|---|
724f967ae980291ae467297e4d28bffde57b8384 | Fix a Kombu error that I made in Hey, too | BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo,BowdoinOrient/bongo | bongo/apps/celery/celery.py | bongo/apps/celery/celery.py | from __future__ import absolute_import
from datetime import timedelta
from celery import Celery, task
from django.conf import settings
from celery.schedules import crontab
import os
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bongo.settings.dev')
... | from __future__ import absolute_import
from datetime import timedelta
from celery import Celery, task
from django.conf import settings
from celery.schedules import crontab
import os
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bongo.settings.dev')
... | mit | Python |
c109a75cd5b5159e82a1ffc6c26a0daca5c2d400 | remove old code | freifunk-darmstadt/tools | filter_contact.py | filter_contact.py | #!/bin/env python
import sys
import json
import datetime
from bson import json_util
from functools import reduce
dt = datetime.datetime
argv = sys.argv
KEY_MAPPING = {
'node_id': 'node_id',
'contact': 'owner.contact',
'hostname': 'hostname'
}
def get_recursive(path, p_dict):
return reduce(dict.__ge... | #!/bin/env python
import sys
import json
import datetime
from bson import json_util
from hashlib import md5 as hash_func
FILTER_FIELDS = ['node_id', 'owner', 'hostname']
dt = datetime.datetime
def stable_hash(entry):
return hash_func(entry.encode('ascii')).hexdigest()
# TODO create dict class with versioning... | agpl-3.0 | Python |
d5e844aa302461d3828bb687bef4118ee76cd653 | fix bug | zaycev/mokujin | findmetaphors2.py | findmetaphors2.py | #!/usr/bin/env python
# coding: utf-8
# Copyright (C) USC Information Sciences Institute
# Author: Vladimir M. Zaytsev <zaytsev@usc.edu>
# URL: <http://nlg.isi.edu/>
# For more information, see README.md
# For license information, see LICENSE
import sys
import logging
import argparse
import cPickle as pickle
from it... | #!/usr/bin/env python
# coding: utf-8
# Copyright (C) USC Information Sciences Institute
# Author: Vladimir M. Zaytsev <zaytsev@usc.edu>
# URL: <http://nlg.isi.edu/>
# For more information, see README.md
# For license information, see LICENSE
import sys
import logging
import argparse
import cPickle as pickle
from it... | apache-2.0 | Python |
2156c9a62c12539d1eabaa47ad9d307ce1fbd81b | save png | joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven,idaholab/raven,idaholab/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven | tests/framework/executeRAVENworkflow/executeRavenFromPython.py | tests/framework/executeRAVENworkflow/executeRavenFromPython.py | # Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 t... | # Copyright 2017 Battelle Energy Alliance, LLC
#
# 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 t... | apache-2.0 | Python |
c03f3df9ed7337dd89087521ef70f693151442f2 | Update popular 25 extensions list | littlstar/chromium.src,M4sse/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,jaruba/chr... | tools/perf/profile_creators/many_extensions_profile_creator.py | tools/perf/profile_creators/many_extensions_profile_creator.py | # Copyright 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.
from telemetry.page import extensions_profile_creator
class ManyExtensionsProfileCreator(
extensions_profile_creator.ExtensionsProfileCreator):
"""Ins... | # Copyright 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.
from telemetry.page import extensions_profile_creator
class ManyExtensionsProfileCreator(
extensions_profile_creator.ExtensionsProfileCreator):
"""Ins... | bsd-3-clause | Python |
9897febed8f48835a12de127dc48bc039c15caa4 | update check_installation script | aepyornis/nyc-db,aepyornis/nyc-db | scripts/check_installation.py | scripts/check_installation.py |
"""
USE: python3 check_installation.py --user USER --password PASS --host HOST --database DATABASE
"""
import argparse
import psycopg2
parser = argparse.ArgumentParser(description='Checks row count of tables in NYCDB')
parser.add_argument("-U", "--user", help="Postgres user. default: postgres", default="postgres")
pa... |
"""
USE: python3 check_installation.py --user USER --password PASS --host HOST -- database DATABASE
"""
import argparse
import psycopg2
parser = argparse.ArgumentParser(description='clean and parse department of buildings jobs. Writes cleaned csv to stdout unless option --psql is invoked.')
parser.add_argument("-U", ... | agpl-3.0 | Python |
dfdac5764236ce9301e7997443b6de4a7a4b4473 | Add outfile option to conversion script | gaberosser/geo-network | scripts/convert_gml_to_csv.py | scripts/convert_gml_to_csv.py | import sys
import os
sys.path.append(os.path.abspath(os.path.curdir))
from converter import gml_to_node_edge_list
if __name__ == '__main__':
in_file = sys.argv[1]
outfile = sys.argv[2] if len(sys.argv) > 2 else None
res = gml_to_node_edge_list(in_file, outfile=outfile, routing=True)
| import sys
import os
sys.path.append(os.path.abspath(os.path.curdir))
from converter import gml_to_node_edge_list
if __name__ == '__main__':
in_file = sys.argv[1]
res = gml_to_node_edge_list(in_file, routing=True)
| mit | Python |
d7ba48ea8a03e8c721591ccffc277c5d14f7c695 | fix build | tjcsl/director,tjcsl/director,tjcsl/director,tjcsl/director | web3/apps/sites/migrations/0021_auto_20170821_1123.py | web3/apps/sites/migrations/0021_auto_20170821_1123.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-21 15:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
def forwards_func(apps, schema_editor):
SiteHost = apps.get_model("sites", "SiteHost")
Site = apps.get_model("sites", "Sit... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-21 15:23
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
def forwards_func(apps, schema_editor):
SiteHost = apps.get_model("sites", "SiteHost")
Site = apps.get_model("sites", "Sit... | mit | Python |
1fef8dbb26aec9b0f3f174e09789461714e55ac5 | Convert to use the base class and update for new plugin path. | mk23/snmpy,mk23/snmpy | snmpy/disk_utilization.py | snmpy/disk_utilization.py | import os
import time
import snmpy
import subprocess
import logging as log
class disk_utilization(snmpy.plugin):
def __init__(self, conf, script=False):
snmpy.plugin.__init__(self, conf, script)
def key(self, idx):
return 'string', self.data[idx - 1]
def val(self, idx):
ts = time.... | import os, time, subprocess
import logging as log
class disk_utilization:
def __init__(self, conf):
os.environ['LC_TIME'] = 'POSIX'
self.devs = ['dev%s-%s' % tuple(line.split()[0:2]) for line in open('/proc/diskstats')]
def len(self):
return len(self.devs)
def key(self, idx):
... | mit | Python |
74410fac2cf741da608478feebc1c2f844d9fdf3 | Fix lint errors | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | lib/node_modules/@stdlib/math/base/special/cosm1/benchmark/python/benchmark.scipy.py | lib/node_modules/@stdlib/math/base/special/cosm1/benchmark/python/benchmark.scipy.py | #!/usr/bin/env python
"""Benchmark scipy.special.cosm1."""
from __future__ import print_function
import timeit
NAME = "cosm1"
REPEATS = 3
ITERATIONS = 1000000
def print_version():
"""Print the TAP version."""
print("TAP version 13")
def print_summary(total, passing):
"""Print the benchmark summary.
... | #!/usr/bin/env python
"""Benchmark scipy.special.cosm1."""
import timeit
name = "cosm1"
repeats = 3
iterations = 1000000
def print_version():
"""Print the TAP version."""
print("TAP version 13")
def print_summary(total, passing):
"""Print the benchmark summary.
# Arguments
* `total`: total ... | apache-2.0 | Python |
acf51a2776eb24794de07d6bbb27ad31b8f68a6c | Include users_signout in list of views not filtered by profilemiddleware. | mozilla/betafarm,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/betafarm,mozilla/betafarm,mozilla/mozilla-ignite,mozilla/betafarm | apps/innovate/middleware.py | apps/innovate/middleware.py | from django.contrib import messages
from django.core.urlresolvers import reverse, resolve
from django.http import HttpResponseRedirect
from tower import ugettext as _
class ProfileMiddleware(object):
def process_request(self, request):
try:
path = u'/%s' % ('/'.join(request.path.split('/')[2:... | from django.contrib import messages
from django.core.urlresolvers import reverse, resolve
from django.http import HttpResponseRedirect
from tower import ugettext as _
class ProfileMiddleware(object):
def process_request(self, request):
try:
path = u'/%s' % ('/'.join(request.path.split('/')[2:... | bsd-3-clause | Python |
2f34d442157f86af4fd75c48ea2cf568fbef34f6 | Rearrange imports in previous migration. | wakermahmud/sync-engine,nylas/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,EthanBlackburn/sync-engine,rmasters/inbox,jobscore/sync-engine,closeio/nylas,Eagles2F/sync-engine,ErinCall/sync-engine,Eagles2F/sync-engine,wakermahmud/sync-engine,closeio/nylas,Eagles2F/sync-engine,wakermahmud/sync-engine... | migrations/versions/223041bb858b_message_contact_association.py | migrations/versions/223041bb858b_message_contact_association.py | """message contact association
Revision ID: 223041bb858b
Revises: 2c9f3a06de09
Create Date: 2014-04-28 23:52:05.449401
"""
# revision identifiers, used by Alembic.
revision = '223041bb858b'
down_revision = '2c9f3a06de09'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'... | """message contact association
Revision ID: 223041bb858b
Revises: 2c9f3a06de09
Create Date: 2014-04-28 23:52:05.449401
"""
# revision identifiers, used by Alembic.
revision = '223041bb858b'
down_revision = '2c9f3a06de09'
# Yes, this is a terrible hack. But tools/rerank_contacts.py already contains a
# script to pro... | agpl-3.0 | Python |
47eac4ef8acca10023f2f43dd3fea0e0abbc1202 | Add Admin page for OrganizationMember. | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | apps/organizations/admin.py | apps/organizations/admin.py | from django.contrib import admin
from apps.organizations.models import (
Organization, OrganizationAddress, OrganizationMember
)
class OrganizationAddressAdmin(admin.StackedInline):
model = OrganizationAddress
extra = 1
class OrganizationAdmin(admin.ModelAdmin):
inlines = (OrganizationAddressAdmin,... | from apps.organizations.models import Organization, OrganizationAddress
from django.contrib import admin
class OrganizationAddressAdmin(admin.StackedInline):
model = OrganizationAddress
extra = 1
class OrganizationAdmin(admin.ModelAdmin):
inlines = (OrganizationAddressAdmin,)
admin.site.register(Organ... | bsd-3-clause | Python |
48e04ae85c563ab6af03773535ebeed748d33572 | Implement dumph to generate input for cbor.me | fritz0705/flynn | flynn/__init__.py | flynn/__init__.py | # coding: utf-8
import flynn.decoder
import flynn.encoder
def dump(obj, fp):
return flynn.encoder.encode(fp, obj)
def dumps(obj):
return flynn.encoder.encode_str(obj)
def dumph(obj):
return "".join(hex(n)[2:].rjust(2, "0") for n in dumps(obj))
def load(s):
return flynn.decoder.decode(s)
def loads(s):
return ... | # coding: utf-8
import flynn.decoder
import flynn.encoder
def dump(obj, fp):
return flynn.encoder.encode(fp, obj)
def dumps(obj):
return flynn.encoder.encode_str(obj)
def load(s):
return flynn.decoder.decode(s)
def loads(s):
return flynn.decoder.decode(s)
| mit | Python |
ad2d223b0a19a607ea8e1d53711e89ac2d8efa10 | Update class011_fighter.py | GrognardsFromHell/TemplePlus,GrognardsFromHell/TemplePlus,GrognardsFromHell/TemplePlus,GrognardsFromHell/TemplePlus,GrognardsFromHell/TemplePlus | tpdatasrc/tpgamefiles/rules/char_class/class011_fighter.py | tpdatasrc/tpgamefiles/rules/char_class/class011_fighter.py | from toee import *
import char_class_utils
import char_editor
###################################################
def GetConditionName(): # used by API
return "Fighter"
def GetCategory():
return "Core 3.5 Ed Classes"
def GetClassDefinitionFlags():
return CDF_BaseClass | CDF_CoreClass
def GetClassHelpTopic():
re... | from toee import *
import char_class_utils
import char_editor
###################################################
def GetConditionName(): # used by API
return "Fighter"
def GetCategory():
return "Core 3.5 Ed Classes"
def GetClassDefinitionFlags():
return CDF_BaseClass | CDF_CoreClass
def GetClassHelpTopic():
re... | mit | Python |
a77d0f2cdb1ece1d9982c91efb6c204c9521fb4d | fix Cron to properly handle multiple exclusive jobs | eXcomm/gratipay.com,mccolgst/www.gittip.com,studio666/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,studio666/gratipay.com,gratipay/gratipay.com,mccolgst/www.gittip.com,studio666/gratipay.com,eXcomm/gratipay.com,eXcomm/gratipay.com,eXcomm... | gratipay/cron.py | gratipay/cron.py | import threading
from time import sleep
import traceback
from aspen import log_dammit
class Cron(object):
def __init__(self, website):
self.website = website
self.conn = None
self.has_lock = False
self.exclusive_jobs = []
def __call__(self, period, func, exclusive=False):
... | import threading
import time
import traceback
from aspen import log_dammit
class Cron(object):
def __init__(self, website):
self.website = website
self.conn = website.db.get_connection().__enter__()
def __call__(self, period, func, exclusive=False):
def f():
if period <=... | mit | Python |
f8bc6e5c652862b8d088d3a31ae143b57d6291af | support for handling errors and warnings(#36) | lzwme/SublimeLinter-contrib-stylelint,lzwme/SublimeLinter-contrib-stylelint | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provide... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by @kungfusheep
# Copyright (c) 2016 @kungfusheep
#
# License: MIT
#
"""This module exports the Stylelint plugin class."""
import os
from SublimeLinter.lint import Linter, util
class Stylelint(Linter):
"""Provide... | mit | Python |
33e10f3943fbd0c6bd22758d24b8263f12fe15a2 | add - implementation for DeployLogDefault::log. | linearregression/git-deploy | git_deploy/deploylog/deploylog.py | git_deploy/deploylog/deploylog.py | """
Handles logging related functionality for deployments
"""
__date__ = '2014-01-14'
__license__ = 'GPL v2.0 (or later)'
from git_deploy.utils import ssh_command_target
from git_deploy.config import log
class DeployLogError(Exception):
""" Basic exception class for DeployDriver types """
def __init__(self,... | """
Handles logging related functionality for deployments
"""
__date__ = '2014-01-14'
__license__ = 'GPL v2.0 (or later)'
class DeployLogError(Exception):
""" Basic exception class for DeployDriver types """
def __init__(self, message="DeployDriver error.", exit_code=1):
Exception.__init__(self, mess... | bsd-3-clause | Python |
a603871616c0f90d695d078c917578d8c3b94941 | add html5 syntax | SublimeLinter/SublimeLinter-phpmd | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpmd plugin class."""
from SublimeLinter.lint import Linter
class Phpmd(Linter):
"""Provides an interface to phpmd."... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Dmitry Tsoy
# Copyright (c) 2013 Dmitry Tsoy
#
# License: MIT
#
"""This module exports the Phpmd plugin class."""
from SublimeLinter.lint import Linter
class Phpmd(Linter):
"""Provides an interface to phpmd."... | mit | Python |
7d8e5c1b06a9d3beaac7709ba7090e95ba89f610 | Exclude .svn directories from catalog generation diff command. Add svn:ignore properties for generated catalog files. | wolffcm/voltdb,kumarrus/voltdb,migue/voltdb,creative-quant/voltdb,ingted/voltdb,VoltDB/voltdb,paulmartel/voltdb,simonzhangsm/voltdb,kobronson/cs-voltdb,VoltDB/voltdb,ingted/voltdb,flybird119/voltdb,migue/voltdb,migue/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,ingted/voltdb,kumarrus/voltdb,simonzhangsm/voltdb,zuow... | src/catgen/install.py | src/catgen/install.py | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2010 VoltDB L.L.C.
#
# VoltDB 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) a... | #!/usr/bin/env python
# This file is part of VoltDB.
# Copyright (C) 2008-2010 VoltDB L.L.C.
#
# VoltDB 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) a... | agpl-3.0 | Python |
61a33f4c4ddece92e1ce8dc98055e1abbd7ebab7 | Disable line numbering of code blocks | calvinleenyc/zulip,susansls/zulip,Juanvulcano/zulip,proliming/zulip,bluesea/zulip,shaunstanislaus/zulip,zulip/zulip,shaunstanislaus/zulip,themass/zulip,shrikrishnaholla/zulip,cosmicAsymmetry/zulip,Batterfii/zulip,ashwinirudrappa/zulip,hackerkid/zulip,krtkmj/zulip,tommyip/zulip,glovebx/zulip,Juanvulcano/zulip,punchagan/... | zephyr/lib/bugdown/__init__.py | zephyr/lib/bugdown/__init__.py | import re
import markdown
from zephyr.lib.avatar import gravatar_hash
from zephyr.lib.bugdown import codehilite
class Gravatar(markdown.inlinepatterns.Pattern):
def handleMatch(self, match):
# NB: the first match of our regex is match.group(2) due to
# markdown internal matches
img = mark... | import re
import markdown
from zephyr.lib.avatar import gravatar_hash
from zephyr.lib.bugdown import codehilite
class Gravatar(markdown.inlinepatterns.Pattern):
def handleMatch(self, match):
# NB: the first match of our regex is match.group(2) due to
# markdown internal matches
img = mark... | apache-2.0 | Python |
e1e7152ae23ce5f4e8219254581e3a3c13960149 | Fix a pydocstyle warning in .travis.yml | SublimeLinter/SublimeLinter-luacheck | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
syn... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Copyright (c) 2014 CorvisaCloud, LLC
#
# License: MIT
#
"""This module exports the Luacheck plugin class."""
from SublimeLinter.lint import Linter
class Luacheck(Linter):
"""Provides an interface to luacheck."""
sy... | mit | Python |
7adc3bb80b9fbc3638200cf272da9f5f4d5ac031 | Remove ,,, | sirreal/SublimeLinter-contrib-govet | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon Surrell
# Copyright (c) 2014 Jon Surrell
#
# License: MIT
#
"""This module exports the Govet plugin class."""
from SublimeLinter.lint import Linter, util
class Govet(Linter):
"""Provides an interface to g... | #
# linter.py
# Linter for SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Jon Surrell,,,
# Copyright (c) 2014 Jon Surrell,,,
#
# License: MIT
#
"""This module exports the Govet plugin class."""
from SublimeLinter.lint import Linter, util
class Govet(Linter):
"""Provides an interfac... | mit | Python |
b6bebcf941228900fe683b2ef45462690f1ddfd5 | Mark tfdv.LiftStatsGenerator and tfdv.NonStreamingPartitionedStatsGenerator for removal from public APIs. | tensorflow/tfx,tensorflow/tfx | tfx/components/statistics_gen/component_test.py | tfx/components/statistics_gen/component_test.py | # Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | # Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | apache-2.0 | Python |
7f5a5786db946b88d9149fadd26a83101b3069e0 | Fix AlertPluginUserData | Razvy000/cabot_alert_plivo | cabot_alert_plivo/models.py | cabot_alert_plivo/models.py | from os import environ as env
from django.conf import settings
from django.template import Context, Template
from cabot.cabotapp.alert import AlertPlugin, AlertPluginUserData
import requests
import logging
import plivo
# get the environment variables (see cabot/conf/development.env)
auth_id = env.get('PLIVO_AUTH_I... | from os import environ as env
from django.conf import settings
from django.template import Context, Template
from cabot.cabotapp.alert import AlertPlugin
import requests
import logging
import plivo
# get the environment variables (see cabot/conf/development.env)
auth_id = env.get('PLIVO_AUTH_ID')
auth_token = env.... | mit | Python |
130b6d47e95c2e538cd5842f6f2f2a88fd9bf9dd | Rename `CMSApp` to Forms — make it consistent to Django verbose app name. | mishbahr/djangocms-forms,mishbahr/djangocms-forms,mishbahr/djangocms-forms | djangocms_forms/cms_app.py | djangocms_forms/cms_app.py | from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
class DjangoCMSFormsApphook(CMSApp):
name = _('Forms')
urls = ['djangocms_forms.urls']
apphook_pool.register(DjangoCMSFormsApphook)
| from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
class DjangoCMSFormsApphook(CMSApp):
name = _('Django CMS Forms')
urls = ['djangocms_forms.urls']
apphook_pool.register(DjangoCMSFormsApp... | bsd-3-clause | Python |
0aa5540cef1e3137147cd379eaffc98208b78595 | Make copying labels less verbose when things are fine.: | edx/repo-tools,edx/repo-tools | copy-labels.py | copy-labels.py | #!/usr/bin/env python
"""Copy tags from one repo to others."""
from __future__ import print_function
import json
import requests
import yaml
from helpers import paginated_get
LABELS_URL = "https://api.github.com/repos/{owner_repo}/labels"
def get_labels(owner_repo):
url = LABELS_URL.format(owner_repo=owner_r... | #!/usr/bin/env python
"""Copy tags from one repo to others."""
from __future__ import print_function
import json
import requests
import yaml
from helpers import paginated_get
LABELS_URL = "https://api.github.com/repos/{owner_repo}/labels"
def get_labels(owner_repo):
url = LABELS_URL.format(owner_repo=owner_r... | apache-2.0 | Python |
0b0d6a4b051786d93cb72448aef25d26db145746 | add support to py2 | szu-stu/ezFund,szu-stu/ezFund,szu-stu/ezFund | fund/check_per.py | fund/check_per.py | #coding:utf-8
from django.shortcuts import get_object_or_404, render
from .models import Fund
from django.contrib.auth.models import User, Group
def detial_cp_decorator(function):
def wrapped_check(request, fund_id, *args, **kwargs):
now_user = request.user
fund = get_object_or_404(Fund, pk=fund_id... | from django.shortcuts import get_object_or_404, render
from .models import Fund
from django.contrib.auth.models import User, Group
def detial_cp_decorator(function):
def wrapped_check(request, fund_id, *args, **kwargs):
now_user = request.user
fund = get_object_or_404(Fund, pk=fund_id)
try:... | apache-2.0 | Python |
110c362e3e8436700707c2306d115b3b2476a79d | Add initial account balance for users. | stephenmcd/gamblor,stephenmcd/gamblor | core/models.py | core/models.py |
from os import makedirs
from os.path import join, exists
from urllib import urlretrieve
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from social_auth.signals import socialau... |
from os import makedirs
from os.path import join, exists
from urllib import urlretrieve
from django.conf import settings
from social_auth.signals import socialauth_registered
def create_profile(sender, user, response, details, **kwargs):
try:
# twitter
photo_url = response["profile_image_url"]
... | bsd-2-clause | Python |
37ec67f868ec803423cd76af28f8116c326ebedd | Update examples.py | explosion/spaCy,explosion/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,honnibal/spaCy,honnibal/spaCy,explosion/spaCy,explosion/spaCy | spacy/lang/tn/examples.py | spacy/lang/tn/examples.py | """
Example sentences to test spaCy and its language models.
>>> from spacy.lang.tn.examples import sentences
>>> docs = nlp.pipe(sentences)
"""
sentences = [
"Apple e nyaka go reka JSE ka tlhwatlhwa ta R1 billion",
"Johannesburg ke toropo e kgolo mo Afrika Borwa.",
"O ko kae?",
"ke mang pr... | # coding: utf8
from __future__ import unicode_literals
"""
Example sentences to test spaCy and its language models.
>>> from spacy.lang.en.examples import sentences
>>> docs = nlp.pipe(sentences)
"""
sentences = [
"Apple e nyaka go reka JSE ka tlhwatlhwa ta R1 billion",
"Johannesburg ke toropo ... | mit | Python |
972ada0697ce787de130001caa0fd2b5850ba34f | allow to override widget IDs | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | core/widget.py | core/widget.py | import core.input
import core.decorators
import util.store
import util.format
class Widget(util.store.Store, core.input.Object):
def __init__(self, full_text='', name=None, module=None):
super(Widget, self).__init__()
self.__full_text = full_text
self.module = module
self.name = na... | import core.input
import core.decorators
import util.store
import util.format
class Widget(util.store.Store, core.input.Object):
def __init__(self, full_text='', name=None, module=None):
super(Widget, self).__init__()
self.__full_text = full_text
self.module = module
self.name = na... | mit | Python |
927c702bdba7f12713738f9a62ac1f2d706d8034 | update doc | yuyu2172/chainercv,pfnet/chainercv,chainer/chainercv,yuyu2172/chainercv,chainer/chainercv | chainercv/links/detection_link.py | chainercv/links/detection_link.py | import chainer
class DetectionLink(chainer.Link):
"""A chainer.Link for object detection.
This is an abstract class for object detection links.
All object detectors should inherit this class.
"""
def predict(self, img):
"""Detect objects in an image.
This method detects objects ... | import chainer
class DetectionLink(chainer.Link):
"""A chainer.Link for object detection.
This is an abstract class for object detection links.
All object detectors should inherit this class.
"""
def predict(self, img):
"""Detect objects in an image.
This method detects objects ... | mit | Python |
08b59dd51bb5a43045c0fabf5b77537f8939b8ba | Change ALLOWED_HOSTS to meras.lt | sirex/nuomones,sirex/manopozicija.lt,sirex/manopozicija.lt,sirex/nuomones,sirex/manopozicija.lt | seimas/settings/production.py | seimas/settings/production.py | # pylint: disable=wildcard-import,unused-wildcard-import
from seimas.settings.base import * # noqa
DEBUG = False
ALLOWED_HOSTS = ['manopozicija.lt', 'meras.lt', 'localhost']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'manopozicija',
'USER': 'm... | # pylint: disable=wildcard-import,unused-wildcard-import
from seimas.settings.base import * # noqa
DEBUG = False
ALLOWED_HOSTS = ['manoseimas.lpylab.lt', 'localhost']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'manopozicija',
'USER': 'manopozi... | agpl-3.0 | Python |
325979c5822a277095ad3e0ec645c6bc03963972 | document iterator filters papers by keyword frequency | andrew-lockwood/lab-project | corpus/document_iterator.py | corpus/document_iterator.py | # Simple iterator that goes over every full text article in the database
# Uses the same parsing as the unlabled sentence iterator
import sqlite3
import re
from context import settings
conn = sqlite3.connect(settings.db)
curr = conn.cursor()
class Documents:
def __init__(self):
q = (" SELECT articleID... | # Simple iterator that goes over every full text article in the database
# Uses the same parsing as the unlabled sentence iterator
import sqlite3
import re
from context import settings
conn = sqlite3.connect(settings.db)
curr = conn.cursor()
class Documents:
def __init__(self):
q = """ SELECT articleID... | mit | Python |
b3c64a9fbe41360754d841b301c44f4fdea83b50 | add binary_classification_metrics | madjelan/CostSensitiveClassification,albahnsen/CostSensitiveClassification | costcla/metrics/__init__.py | costcla/metrics/__init__.py | from .costs import *
import numpy as np
from sklearn.utils import column_or_1d
from sklearn.metrics import roc_auc_score
def binary_classification_metrics(y_true, y_pred, y_prob):
#TODO: update description
"""classification_metrics.
This function cal...
Parameters
----------
y_true : array-l... | from .costs import *
| bsd-3-clause | Python |
6f05ab2dbcb4d4765c662fcc56d2d93c89a54413 | Remove unused logic from search form | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | csunplugged/search/forms.py | csunplugged/search/forms.py | """Module for custom search form."""
from django import forms
from haystack.forms import ModelSearchForm
from topics.models import (
Lesson,
CurriculumIntegration,
CurriculumArea,
)
class CustomSearchForm(ModelSearchForm):
"""Class for custom search form."""
curriculum_areas = forms.ModelMultiple... | """Module for custom search form."""
from django import forms
from haystack.forms import ModelSearchForm
from topics.models import (
Lesson,
CurriculumIntegration,
CurriculumArea,
)
class CustomSearchForm(ModelSearchForm):
"""Class for custom search form."""
curriculum_areas = forms.ModelMultiple... | mit | Python |
b416addd53a2b779f9ee5a311217bdf3a82ce9b5 | Update mintapi.py | reubano/csv2ofx,reubano/csv2ofx | csv2ofx/mappings/mintapi.py | csv2ofx/mappings/mintapi.py | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=invalid-name
"""
csv2ofx.mappings.mintapi
~~~~~~~~~~~~~~~~~~~~~~~~
Provides a mapping for transactions obtained via the mintapi python script
"""
from __future__ import absolute_import
from operator import itemgetter
mapping = {
'is_split': Fal... | # -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
# pylint: disable=invalid-name
"""
csv2ofx.mappings.mintapi
~~~~~~~~~~~~~~~~~~~~~~~~
Provides a mapping for transactions obtained via the mintapi python script
"""
from __future__ import absolute_import
from operator import itemgetter
mapping = {
'is_split': Fal... | mit | Python |
641b39069cebe5c767c043d593b58a66cce9d182 | add extra test for compss_delete_object | mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs,mF2C/COMPSs | tests/sources/basic/41-deleteApi_python/src/modules/testDeleteObject.py | tests/sources/basic/41-deleteApi_python/src/modules/testDeleteObject.py | '''@author: srodrig1
PyCOMPSs Delete Object test
=========================
This file represents PyCOMPSs Testbench.
Checks the delete object functionality.
'''
import unittest
from pycompss.api.api import compss_wait_on, compss_delete_object
from tasks import increment_object
class testDeleteObject(unittest.T... | '''@author: srodrig1
PyCOMPSs Delete Object test
=========================
This file represents PyCOMPSs Testbench.
Checks the delete object functionality.
'''
import unittest
from pycompss.api.api import compss_wait_on, compss_delete_object
from tasks import increment_object
class testDeleteObject(unittest.T... | apache-2.0 | Python |
6be57a38751e42c9544e29168db05cba611acbb1 | Add trial period days option to initial plans. | aibon/django-stripe-payments,grue/django-stripe-payments,jawed123/django-stripe-payments,grue/django-stripe-payments,wahuneke/django-stripe-payments,boxysean/django-stripe-payments,jamespacileo/django-stripe-payments,boxysean/django-stripe-payments,pinax/django-stripe-payments,ZeevG/django-stripe-payments,jawed123/djan... | payments/management/commands/init_plans.py | payments/management/commands/init_plans.py | import decimal
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in set... | import decimal
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in set... | mit | Python |
e5c3237220a7f5bc211dfe9bb537bfc2a3ad9f2a | Add mask_to_mirrored_value test for mask keyword | astropy/photutils,larrybradley/photutils | photutils/segmentation/tests/test_utils.py | photutils/segmentation/tests/test_utils.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the _utils module.
"""
import numpy as np
from numpy.testing import assert_allclose
from .._utils import mask_to_mirrored_value
def testmask_to_mirrored_value():
center = (2.0, 2.0)
data = np.arange(25).reshape(5, 5)
mask = np... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Tests for the _utils module.
"""
import numpy as np
from numpy.testing import assert_allclose
from .._utils import mask_to_mirrored_value
def testmask_to_mirrored_value():
center = (2.0, 2.0)
data = np.arange(25).reshape(5, 5)
mask = np... | bsd-3-clause | Python |
89e118d1a024a4556030372d6afb52ade5489152 | Bump version to 0.9.2 | RealDolos/volaupload | volaupload/_version.py | volaupload/_version.py | """
Version information for volaupload
"""
__version__ = "0.9.2"
| """
Version information for volaupload
"""
__version__ = "0.9.1"
| mit | Python |
918896d4b25956d29edd195d96190849a013255f | Handle undeferred results. | ox-it/humfrey,ox-it/humfrey,ox-it/humfrey | humfrey/results/views/standard.py | humfrey/results/views/standard.py | from __future__ import absolute_import
import types
from django.http import HttpResponse
from django_conneg.decorators import renderer
from django_conneg.views import ContentNegotiatedView
from humfrey import streaming
from humfrey.streaming.base import StreamingParser
def get_renderer_test(serializer_class):
... | from __future__ import absolute_import
from django.http import HttpResponse
from django_conneg.decorators import renderer
from django_conneg.views import ContentNegotiatedView
from humfrey import streaming
from humfrey.streaming.base import StreamingParser
def get_renderer_test(serializer_class):
def test(self,... | bsd-3-clause | Python |
5e911e2f90b41b6d6e482f0ed3ebde3b6e5cc758 | Add data write test | nestauk/innovation_networks | tests/test_data_gathering/test_github.py | tests/test_data_gathering/test_github.py | import json
import os
import pytest
import responses
import sys
from datetime import datetime, timedelta
from innovation_networks.data_gathering.github import get_data
def test_make_url():
"""GitHub Archive URL creation works"""
day = 6
year = 1987
month = 11
hour = 8
url = get_data.make_url(... | import os
import pytest
import sys
from datetime import datetime, timedelta
from innovation_networks.data_gathering.github import get_data
def test_make_url():
"""GitHub Archive URL creation works"""
day = 6
year = 1987
month = 11
hour = 8
url = get_data.make_url(year=year,
... | apache-2.0 | Python |
18f0176a3981c82a4aac88940503d9446aee06cc | make it more complex | fishtown-analytics/hologram | tests/test_multi_optional_definitions.py | tests/test_multi_optional_definitions.py | import pytest
from dataclasses import dataclass, field
from typing import Union, NewType, Optional
from hologram import JsonSchemaMixin, ValidationError
from hologram.helpers import StrEnum
class MySelector(StrEnum):
A = "a"
B = "b"
C = "c"
@dataclass
class RestrictAB(JsonSchemaMixin):
foo: MySele... | import pytest
from dataclasses import dataclass, field
from typing import Union, NewType
from hologram import JsonSchemaMixin, ValidationError
from hologram.helpers import StrEnum
class MySelector(StrEnum):
A = "a"
B = "b"
C = "c"
@dataclass
class RestrictAB(JsonSchemaMixin):
foo: MySelector = fie... | mit | Python |
f41c92759aad09309b8f5c33e1aac384a29da46d | use fake apikey | scrapinghub/exporters | tests/test_writers_reducer_hubstorage.py | tests/test_writers_reducer_hubstorage.py | import unittest
import vcr
from exporters.records.base_record import BaseRecord
from exporters.writers.hs_reduce_writer import HubstorageReduceWriter
DASH_URL = 'https://dash.scrapinghub.com'
class HubstorageReduceWriterTest(unittest.TestCase):
@vcr.use_cassette('tests/fixtures/vcr_cassettes/reducer_hubstorag... | import os
import unittest
import vcr
from exporters.records.base_record import BaseRecord
from exporters.writers.hs_reduce_writer import HubstorageReduceWriter
DASH_URL = 'https://dash.scrapinghub.com'
class HubstorageReduceWriterTest(unittest.TestCase):
@vcr.use_cassette('tests/fixtures/vcr_cassettes/reducer... | bsd-3-clause | Python |
a3e6197c16fd6a105147c38486f278f84f9e16a3 | Fix warnings parser to ignore files with no path info. | KiemVM/Mozilla--dxr,kleintom/dxr,gartung/dxr,jonasfj/dxr,pelmers/dxr,pombredanne/dxr,kleintom/dxr,pelmers/dxr,jbradberry/dxr,jonasfj/dxr,pelmers/dxr,bozzmob/dxr,jay-z007/dxr,pelmers/dxr,bozzmob/dxr,pombredanne/dxr,nrc/dxr,jbradberry/dxr,srenatus/dxr,jbradberry/dxr,jay-z007/dxr,erikrose/dxr,srenatus/dxr,nrc/dxr,gartung/... | xref-scripts/warning-parser.py | xref-scripts/warning-parser.py | #!/usr/bin/env python
"""
Modified from http://hg.mozilla.org/users/bsmedberg_mozilla.com/static-analysis-buildbot/file/19e7a98a8dc4/warning-parser.py
Assumes filenames in warnings use abs/real paths, see:
https://bugzilla.mozilla.org/show_bug.cgi?id=579203
Reads a build log on stdin. Parse warning messages (from GC... | #!/usr/bin/env python
"""
Modified from http://hg.mozilla.org/users/bsmedberg_mozilla.com/static-analysis-buildbot/file/19e7a98a8dc4/warning-parser.py
Assumes filenames in warnings use abs/real paths, see:
https://bugzilla.mozilla.org/show_bug.cgi?id=579203
Reads a build log on stdin. Parse warning messages (from GC... | mit | Python |
ebb3b4f1d5e89ae32fcb6200f9b074dd1f3c2364 | Remove unused import. | arokem/pyAFQ,yeatmanlab/pyAFQ,arokem/pyAFQ,yeatmanlab/pyAFQ | AFQ/tests/test_dki.py | AFQ/tests/test_dki.py | import numpy.testing as npt
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from AFQ import dki
def test_fit_dki_inputs():
data_files = ["String in a list"]
bval_files = "just a string"
bvec_files = "just another string"
npt.assert_raises(ValueError, dki.fit_dki, data_files, bval_files,
... | import tempfile
import numpy.testing as npt
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from AFQ import dki
def test_fit_dki_inputs():
data_files = ["String in a list"]
bval_files = "just a string"
bvec_files = "just another string"
npt.assert_raises(ValueError, dki.fit_dki, data_files, ... | bsd-2-clause | Python |
2768f7ac50a7b91d984f0f872b647e647d768e93 | Add failing (on Py 2) test for passwd_check with unicode arguments | ipython/ipython,ipython/ipython | IPython/lib/tests/test_security.py | IPython/lib/tests/test_security.py | # coding: utf-8
from IPython.lib import passwd
from IPython.lib.security import passwd_check, salt_len
import nose.tools as nt
def test_passwd_structure():
p = passwd('passphrase')
algorithm, salt, hashed = p.split(':')
nt.assert_equal(algorithm, 'sha1')
nt.assert_equal(len(salt), salt_len)
nt.asse... | from IPython.lib import passwd
from IPython.lib.security import passwd_check, salt_len
import nose.tools as nt
def test_passwd_structure():
p = passwd('passphrase')
algorithm, salt, hashed = p.split(':')
nt.assert_equal(algorithm, 'sha1')
nt.assert_equal(len(salt), salt_len)
nt.assert_equal(len(has... | bsd-3-clause | Python |
9aedd914cf73dc5d5ce504c6b0e6ef3474b44c8c | fix args | N4NU/mn-darts,N4NU/mn-darts | darts/views.py | darts/views.py | """Flask Login Example and instagram fallowing find"""
from flask import Flask, url_for, render_template, request, redirect, session
from flask_sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from darts import app
import commands
app.config.update(
DEBUG=True,
SQLALCHEMY_DATABASE_URI='sqlite:... | """Flask Login Example and instagram fallowing find"""
from flask import Flask, url_for, render_template, request, redirect, session
from flask_sqlalchemy import SQLAlchemy
from flask.ext.bcrypt import Bcrypt
from darts import app
import commands
app.config.update(
DEBUG=True,
SQLALCHEMY_DATABASE_URI='sqlite:... | mit | Python |
fc97b9ce0ccf08a2c6b7c0859d98ba476d5094ee | Fix ModelValidator driver for searching across pipelines | tensorflow/tfx,tensorflow/tfx | tfx/components/model_validator/driver.py | tfx/components/model_validator/driver.py | # Lint as: python2, python3
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | # Lint as: python2, python3
# Copyright 2019 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | apache-2.0 | Python |
0efa6f23ef8e6f5044b7867f842885c1911a08a7 | fix a few obvious bugs in the test code | JohnDoee/deluge-client | deluge_client/tests.py | deluge_client/tests.py | import os
import sys
import pytest
from .client import DelugeRPCClient, RemoteException
if sys.version_info > (3,):
long = int
def client_factory(**kw):
"""Create a disconnected client for test purposes."""
if sys.platform.startswith('win'):
auth_path = os.path.join(os.getenv('APPDATA'), 'delu... | import os
import sys
import pytest
from .client import DelugeRPCClient, RemoteException
if sys.version_info > (3,):
long = int
def client_factory():
"""Create a disconnected client for test purposes."""
if sys.platform.startswith('win'):
auth_path = os.path.join(os.getenv('APPDATA'), 'deluge',... | mit | Python |
fd2753667b185e66d68fe9601dce6036a768419d | Add test for ordering Page search by title | wagtail/wagtail,thenewguy/wagtail,gasman/wagtail,zerolab/wagtail,mixxorz/wagtail,FlipperPA/wagtail,gasman/wagtail,rsalmaso/wagtail,zerolab/wagtail,mikedingjan/wagtail,nimasmi/wagtail,torchbox/wagtail,takeflight/wagtail,mixxorz/wagtail,timorieber/wagtail,thenewguy/wagtail,mikedingjan/wagtail,timorieber/wagtail,takefligh... | wagtail/wagtailsearch/tests/test_page_search.py | wagtail/wagtailsearch/tests/test_page_search.py | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.test import TestCase
from wagtail.wagtailcore.models import Page
from wagtail.wagtailsearch.backends import get_search_backend
class PageSearchTests(object):
# A TestCase with this class mixed in will be dynami... | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.test import TestCase
from wagtail.wagtailcore.models import Page
from wagtail.wagtailsearch.backends import get_search_backend
class PageSearchTests(object):
# A TestCase with this class mixed in will be dynami... | bsd-3-clause | Python |
9e7b07ed1dfaa35104deb7bbc9c9c87c3e02739a | make check_service() optional | fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver,fausecteam/ctf-gameserver | checker/checker/abstract.py | checker/checker/abstract.py | #!/usr/bin/python3
from abc import ABCMeta, abstractmethod
import logging
class AbstractChecker(metaclass=ABCMeta):
"""Base class for custom checker scripts
Individual checkers should import `BaseChecker` which does the
right thing in terms of backend depending on whether you test
locally or the che... | #!/usr/bin/python3
from abc import ABCMeta, abstractmethod
import logging
class AbstractChecker(metaclass=ABCMeta):
"""Base class for custom checker scripts
Individual checkers should import `BaseChecker` which does the
right thing in terms of backend depending on whether you test
locally or the che... | isc | Python |
e3defaaa60bc4f9747276309c5f6e5e4348fb6b5 | Add /debug command | joshfriend/atlas,joshfriend/atlas | atlas/api/webhooks/slash.py | atlas/api/webhooks/slash.py | #!/usr/bin/env python
import json
from flask import jsonify, Response, request
from flask.views import MethodView
from webargs.flaskparser import use_args
from atlas.api import api_v1_blueprint as bp, log
from atlas.api.webhooks import slash_cmd_args
from atlas.api.webhooks.jira_mention import jira_command
class S... | #!/usr/bin/env python
from flask import jsonify, Response
from flask.views import MethodView
from webargs.flaskparser import use_args
from atlas.api import api_v1_blueprint as bp, log
from atlas.api.webhooks import slash_cmd_args
from atlas.api.webhooks.jira_mention import jira_command
class SlashCommand(MethodView... | mit | Python |
46b63173d8b4e305650765981a152ff23169aaa2 | Support multiline variables. | madrisan/saltstack-sdb-passwd | json.py | json.py | '''
SDB module for JSON
Like all sdb modules, the JSON module requires a configuration profile
to be configured in either the minion or, as in our implementation,
in the master configuration file (/etc/salt/master.d/passwords.conf).
This profile requires very little:
.. code-block:: yaml
pwd:
dr... | '''
SDB module for JSON
Like all sdb modules, the JSON module requires a configuration profile
to be configured in either the minion or, as in our implementation,
in the master configuration file (/etc/salt/master.d/passwords.conf).
This profile requires very little:
.. code-block:: yaml
pwd:
dr... | apache-2.0 | Python |
2aec7b9c03948104974b4e47e873c41f26820ab3 | Add comments to sbratio and remove unused variables | savvytruffle/cauldron,savvytruffle/cauldron | rvs/sbratio.py | rvs/sbratio.py | '''This program is a translation of Keivan Stassun's IDL code to compute Temp ratios
with surface brightnesses for Spectroscopic Eclipsing Binaries. To run this program,
execute it with the following input arguments:
python sbratio.py 0 6237 0.3920984216 0 '''
## More instructive: python sbratio.py teff1 sbratio
## ... | '''This program is a translation of Keivan Stassun's IDL code to compute Temp ratios
with surface brightnesses for Spectroscopic Eclipsing Binaries. To run this program,
execute it with the following input arguments:
python sbratio.py 0 6237 0.3920984216 0 '''
import numpy as np
from scipy.interpolate import interp1... | mit | Python |
090180470c031967f11870b7a101e1f619a17072 | Add support for reading snapshots for program audit reader | VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,selahssea/ggrc-core | src/ggrc_basic_permissions/roles/ProgramAuditReader.py | src/ggrc_basic_permissions/roles/ProgramAuditReader.py | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "AuditImplied"
description = """
A user with the ProgramReader role for a private program will also have this
role in the audit context for any audit created for that program.
"""
permissions =... | # Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
scope = "AuditImplied"
description = """
A user with the ProgramReader role for a private program will also have this
role in the audit context for any audit created for that program.
"""
permissions =... | apache-2.0 | Python |
7618cedbc057b2359f5bc9a1b2479c8287b2d64d | Add setitem and contains to DataStore | DesertBot/DesertBot | desertbot/datastore.py | desertbot/datastore.py | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
self.save()
return
with open... | import json
import os
class DataStore(object):
def __init__(self, storagePath="desertbot_data.json"):
self.storagePath = storagePath
self.data = {}
self.load()
def load(self):
if not os.path.exists(self.storagePath):
self.save()
return
with open... | mit | Python |
9c10e991b1ca6eff0dc3b508217982a02f4943b7 | Fix get_distro for FreeBSD. | rjschwei/WALinuxAgent,rjschwei/WALinuxAgent,Azure/WALinuxAgent,andyliuliming/WALinuxAgent,hglkrijger/WALinuxAgent,andyliuliming/WALinuxAgent,hglkrijger/WALinuxAgent,Azure/WALinuxAgent | azurelinuxagent/metadata.py | azurelinuxagent/metadata.py | # Microsoft Azure Linux Agent
#
# Copyright 2014 Microsoft Corporation
#
# 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 b... | # Microsoft Azure Linux Agent
#
# Copyright 2014 Microsoft Corporation
#
# 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 b... | apache-2.0 | Python |
372e8081e0df0ec74113708b15909bd086aa977b | Update watchdog.py | Python-IoT/Smart-IoT-Planting-System,Python-IoT/Smart-IoT-Planting-System | device/src/watchdog.py | device/src/watchdog.py | #Detect device status, if errors, reboot by watchdog.
#Send on-line message to gateway while bootup, if gateway receive plenty of
#on-line messages in a short time from the same device, an alarm occurs.
| #Detect device status, if errors, reboot by watchdog.
#Send on-line message to gateway while bootup, if gateway receive plenty of
#on-line messages in a short time from the same device, an alarm occurs.
1
2
3
4
5
6
| mit | Python |
5492bc6f7aadc51fc6fb042766225950b0e529c7 | Gère les requêtes de moteur de recherche vides. | dezede/dezede,dezede/dezede,dezede/dezede,dezede/dezede | dezede/views.py | dezede/views.py | # coding: utf-8
from __future__ import unicode_literals
import json
from django.http import HttpResponse
from django.utils.encoding import smart_text
from django.views.generic import ListView, TemplateView
from haystack.query import SearchQuerySet
from haystack.views import SearchView
from .models import Diapositive
... | # coding: utf-8
from __future__ import unicode_literals
import json
from django.http import HttpResponse
from django.utils.encoding import smart_text
from django.views.generic import ListView, TemplateView
from haystack.query import SearchQuerySet
from haystack.views import SearchView
from .models import Diapositive
... | bsd-3-clause | Python |
c77b9df949ea51b7e2cd36ff1486e296d097f20c | Update Keras.py | paperrune/Neural-Networks,paperrune/Neural-Networks | History/Momentum/Keras.py | History/Momentum/Keras.py | import keras
from keras.datasets import mnist
from keras.initializers import RandomUniform
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import SGD
batch_size = 128
epochs = 30
learning_rate = 0.1
momentum = 0.9
num_classes = 10
(x_train, y_train), (x_test, y_te... | import keras
from keras.datasets import mnist
from keras.initializers import RandomUniform
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import SGD
batch_size = 128
epochs = 30
learning_rate = 0.5
momentum = 0.9
num_classes = 10
(x_train, y_train), (x_test, y_te... | mit | Python |
a95b0c06b818fac088bdc87376dadddb5d3b5ac2 | Update fb_post_clipboard.py | umangahuja1/Python | Automation/fb_post_clipboard.py | Automation/fb_post_clipboard.py | '''
This script is created to post status on fb from your clipboard via terminal
'''
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdri... | '''
This script list created to post status on fb from your clipboard via terminal
'''
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webd... | apache-2.0 | Python |
a2a55e52c4012b4260596416ac23c626b174351b | print explicit errors in the console | liuhewei/gotools-sublime | gotools_oracle.py | gotools_oracle.py | import sublime
import sublime_plugin
import os
import golangconfig
from .gotools_util import Buffers
from .gotools_util import GoBuffers
from .gotools_util import Logger
from .gotools_util import ToolRunner
class GotoolsOracleCommand(sublime_plugin.TextCommand):
def is_enabled(self):
return GoBuffers.is_go_sour... | import sublime
import sublime_plugin
import os
import golangconfig
from .gotools_util import Buffers
from .gotools_util import GoBuffers
from .gotools_util import Logger
from .gotools_util import ToolRunner
class GotoolsOracleCommand(sublime_plugin.TextCommand):
def is_enabled(self):
return GoBuffers.is_go_sour... | mit | Python |
f642f75e8e40a2f0c1c44dea540300a024ebd69b | Speed up test - removed redundant cycle, generate only one tree. | 111t8e/h2o-2,vbelakov/h2o,111t8e/h2o-2,100star/h2o,rowhit/h2o-2,vbelakov/h2o,111t8e/h2o-2,h2oai/h2o,calvingit21/h2o-2,h2oai/h2o,elkingtonmcb/h2o-2,eg-zhang/h2o-2,111t8e/h2o-2,h2oai/h2o,111t8e/h2o-2,eg-zhang/h2o-2,h2oai/h2o-2,calvingit21/h2o-2,h2oai/h2o-2,h2oai/h2o,eg-zhang/h2o-2,vbelakov/h2o,vbelakov/h2o,eg-zhang/h2o-2... | py/testdir_hosts/test_rf_311M_rows_fvec.py | py/testdir_hosts/test_rf_311M_rows_fvec.py | import unittest, sys, time
sys.path.extend(['.','..','py'])
import h2o_cmd, h2o, h2o_hosts, h2o_browse as h2b, h2o_import as h2i
# Uses your username specific json: pytest_config-<username>.json
# copy pytest_config-simple.json and modify to your needs.
class Basic(unittest.TestCase):
def tearDown(self):
h... | import unittest, sys, time
sys.path.extend(['.','..','py'])
import h2o_cmd, h2o, h2o_hosts, h2o_browse as h2b, h2o_import as h2i
# Uses your username specific json: pytest_config-<username>.json
# copy pytest_config-simple.json and modify to your needs.
class Basic(unittest.TestCase):
def tearDown(self):
h... | apache-2.0 | Python |
711e58fcbfffdf0a6d04c2b9306807745fd10176 | Make community screen | samukasmk/pythonbrasil_mobile,akshayaurora/PyDelhiMobile,shivan1b/pydelhi_mobile,pydelhi/pydelhi_mobile | pydelhiconf/uix/screens/screencommunity.py | pydelhiconf/uix/screens/screencommunity.py | from kivy.uix.screenmanager import Screen
from kivy.uix.gridlayout import GridLayout
from kivy.factory import Factory
from kivy.lang import Builder
from functools import partial
class ScreenCommunity(Screen):
Builder.load_string('''
<ScreenCommunity>
name: 'ScreenCommunity'
ScrollView
ScrollGrid
... | from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
class ScreenCommunity(Screen):
Builder.load_string('''
<ScreenCommunity>
name: 'ScreenCommunity'
''') | agpl-3.0 | Python |
6a7bd021adca6fc8924478455c20035e08429110 | Replace doctests with unittest | irwinlove/django-disqus,aptivate/django-disqus,arthurk/django-disqus,irwinlove/django-disqus,aptivate/django-disqus,arthurk/django-disqus | disqus/tests.py | disqus/tests.py | import unittest
from django.conf import settings
from django.core.management.base import CommandError
from unittest import TestCase
from disqus.api import DisqusClient
class DisqusTest(TestCase):
def test_client_init(self):
"""
First, we test if the DisqusClient class can be initialized
a... | from django.conf import settings
from django.core.management.base import CommandError
from disqus.api import DisqusClient
__test__ = {'API_TESTS': """
First, we test if the DisqusClient class can be initialized
and parameters that were passed are set correctly.
>>> c = DisqusClient(foo='bar', bar='foo')
>>> c.foo
'... | bsd-3-clause | Python |
a7e627e60b67f74e1799a272436d58e2eb925e82 | Move all SQL commands to one set of files | worldcomputerxchange/inventory-control,codeforsanjose/inventory-control | inventory_control/database/components.py | inventory_control/database/components.py | """
So this is where all the SQL commands for the Component Stuff exists
"""
CREATE_SQL = """
CREATE TABLE components (
id INT PRIMARY KEY AUTO_INCREMENT,
sku TEXT,
type INT,
status INT
);
CREATE TABLE component_type (
id INT PRIMARY KEY AUTO_INCREMENT,
type TEXT
);
"""
SELECT_ALL_COMPONENTS ... | mit | Python | |
a0732c380c542961e617ef8b4733a5dfce4bb6f9 | change parameter name | AlienVault-Engineering/service-manager | src/main/python/service_manager/service_initializer/creators/bamboo_build_creator.py | src/main/python/service_manager/service_initializer/creators/bamboo_build_creator.py | import json
import os
from service_manager.util.services import invoke_process
class BambooBuildCreator(object):
def __init__(self, template_dir,dry_run):
self.dry_run = dry_run
self.template_dir = template_dir
bamboo_config = os.path.join(os.path.abspath(template_dir),"build-config.json... | import json
import os
from service_manager.util.services import invoke_process
class BambooBuildCreator(object):
def __init__(self, template_dir,dry_run):
self.dry_run = dry_run
self.template_dir = template_dir
bamboo_config = os.path.join(os.path.abspath(template_dir),"build-config.json... | apache-2.0 | Python |
31cfd168a8e92f18e8a0d357c6151b936da67994 | Use the -Deleted suffix | dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | corehq/apps/locations/management/commands/delete_locations.py | corehq/apps/locations/management/commands/delete_locations.py | from django.core.management.base import BaseCommand
from dimagi.utils.couch.database import iter_docs
from dimagi.utils.couch.undo import DELETED_SUFFIX
from corehq.apps.domain.models import Domain
from corehq.apps.locations.models import Location
from .check_loc_types import locs_by_domain
class Command(BaseCommand)... | from django.core.management.base import BaseCommand
from dimagi.utils.couch.database import iter_docs
from corehq.apps.domain.models import Domain
from corehq.apps.locations.models import Location
from .check_loc_types import locs_by_domain
class Command(BaseCommand):
args = "<domain>"
help = ("Change the doc... | bsd-3-clause | Python |
94207f9a5000a286ee23d8de176423fa9d76bb2a | Connect document route | nh0815/PySearch,nh0815/PySearch | search/urls.py | search/urls.py | __author__ = 'Nick'
from django.conf.urls import url
from search import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^query/$', views.query, name='query'),
url(r'^document/$', views.doc, name='document')
] | __author__ = 'Nick'
from django.conf.urls import url
from search import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^query/$', views.query, name='query')
] | mit | Python |
33b33a53a4a308ae6c9779db83ee143f347d416b | add example of synchronous query API | kmaehashi/sensorbee-python | example/general_example.py | example/general_example.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import sensorbee.api
class GeneralExample(object):
def main(self):
api = sensorbee.api.SensorBeeAPI()
print(api.runtime_status())
print(api.create_topology('bee... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import sensorbee.api
class GeneralExample(object):
def main(self):
api = sensorbee.api.SensorBeeAPI()
print(api.runtime_status())
print(api.create_topology('bee... | mit | Python |
b181c35d62ba1970e2d1e637b277c709ab7b9124 | Fix asynchronous batch requests | bcb/jsonrpcserver | jsonrpcserver/async_dispatcher.py | jsonrpcserver/async_dispatcher.py | """Asynchronous dispatch"""
import asyncio
from .dispatcher import Requests
from .async_request import AsyncRequest
from .response import BatchResponse, NotificationResponse
class AsyncRequests(Requests): #pylint:disable=too-few-public-methods
"""Asynchronous requests"""
def __init__(self, requests):
... | """Asynchronous dispatch"""
from .dispatcher import Requests
from .async_request import AsyncRequest
from .response import BatchResponse, NotificationResponse
class AsyncRequests(Requests): #pylint:disable=too-few-public-methods
"""Asynchronous requests"""
def __init__(self, requests):
super(AsyncReq... | mit | Python |
8a32334f5cf3bc39784a841f21edeb5837c9045e | Fix minus sign in pressure | hombit/house | house/weather.py | house/weather.py | import requests
from functools import reduce
from numbers import Real
from typing import Optional, SupportsInt, SupportsFloat, Tuple, Union
from urllib.parse import urljoin
from .secrets import weather_underground_api_key
from .tools import ApiBasic
_base_url = 'https://api.wunderground.com/api/'
class Weather(ApiB... | import requests
from functools import reduce
from numbers import Real
from typing import Optional, SupportsInt, SupportsFloat, Tuple, Union
from urllib.parse import urljoin
from .secrets import weather_underground_api_key
from .tools import ApiBasic
_base_url = 'https://api.wunderground.com/api/'
class Weather(ApiB... | mit | Python |
0f23769760e3b44a784d57e36527c08563e361d7 | change indents from tabs to spaces? | berkeley-stat159/project-alpha,reychil/project-alpha-1 | code/utils/tests/test_bh.py | code/utils/tests/test_bh.py | """ Tests for bh_procedure in benjamini_hochberg module
Run at the project directory with:
nosetests code/utils/tests/test_bh.py
"""
# Loading modules.
import numpy as np
import itertools
import scipy.ndimage
from scipy.ndimage.filters import gaussian_filter
import matplotlib.pyplot as plt
import nibabel as nib
i... | """ Tests for bh_procedure in benjamini_hochberg module
Run at the project directory with:
nosetests code/utils/tests/test_bh.py
"""
# Loading modules.
import numpy as np
import itertools
import scipy.ndimage
from scipy.ndimage.filters import gaussian_filter
import matplotlib.pyplot as plt
import nibabel as nib
i... | bsd-3-clause | Python |
066a544c68225450edce0c9b40dee37d22a22d52 | Bump version # for final release | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | Lib/distutils/__init__.py | Lib/distutils/__init__.py | """distutils
The main package for the Python Module Distribtion Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
__revision__ = "$Id$"
__version__ = "1.0.2"
| """distutils
The main package for the Python Module Distribtion Utilities. Normally
used from a setup script as
from distutils.core import setup
setup (...)
"""
__revision__ = "$Id$"
__version__ = "1.0.2pre"
| mit | Python |
f78eb698de6402144710692f6feb023f7e52b8e3 | Update doc strings | Kellel/ProxyMiddleware,Kellel/ProxyMiddleware | ProxyMiddleware/ProxyMiddleware.py | ProxyMiddleware/ProxyMiddleware.py | #!/usr/bin/env python
#
# Kellen Fox
# https://github.com/Kellel/ProxyMiddleware
#
from bottle import redirect, HTTPError, abort
class ReverseProxied(object):
"""
Reverse Proxied
---------------
Wrap a wsgi application such that the script name and path info are gleaned from the Nginx Reverse Proxy... | #!/usr/bin/env python
#
# Reverse Proxy Middleware. This snippit of code sets the script_name environment variable to what is set in nginx
# It then strips the common bits from the PATH_INFO variable
from bottle import redirect, HTTPError, abort
class ReverseProxied(object):
def __init__(self, wrap_app):
... | bsd-3-clause | Python |
c05a83bd4f815e24389a3ebddbf2da7126cd84e1 | Add CoAP server and webserver in test nodes | bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr | examples/6lbr/test/coojagen/examples/config_preset_1dag_10nodes_llsec.py | examples/6lbr/test/coojagen/examples/config_preset_1dag_10nodes_llsec.py | """
Load a preset topology: preset-2dags-20nodes, which is 2 totally disjoint DODAGs with 10 nodes in each.
The first 2 nodes in the generated array are the ones meant to be use as slip-radio, so we assign them as such
"""
outputfolder = 'coojagen/output'
template = 'coojagen/templates/cooja-template-udgm.csc'
radio_m... | """
Load a preset topology: preset-2dags-20nodes, which is 2 totally disjoint DODAGs with 10 nodes in each.
The first 2 nodes in the generated array are the ones meant to be use as slip-radio, so we assign them as such
"""
outputfolder = 'coojagen/output'
template = 'coojagen/templates/cooja-template-udgm.csc'
radio_m... | bsd-3-clause | Python |
9fbfbc5f71e78046d22db409f59e4c7febce1b88 | fix tests | CanonicalLtd/subiquity,CanonicalLtd/subiquity | subiquity/ui/views/filesystem/tests/test_filesystem.py | subiquity/ui/views/filesystem/tests/test_filesystem.py | import unittest
from unittest import mock
import urwid
from subiquitycore.testing import view_helpers
from subiquity.controllers.filesystem import FilesystemController
from subiquity.models.filesystem import (
Bootloader,
Disk,
FilesystemModel,
)
from subiquity.models.tests.test_filesystem import (
... | import unittest
from unittest import mock
import urwid
from subiquitycore.testing import view_helpers
from subiquity.controllers.filesystem import FilesystemController
from subiquity.models.filesystem import (
Bootloader,
Disk,
FilesystemModel,
)
from subiquity.models.tests.test_filesystem import (
... | agpl-3.0 | Python |
45fe5a48cf71c24afe59b4714a739610cd217396 | Update unique-word-abbreviation.py | kamyu104/LeetCode,yiwen-luo/LeetCode,yiwen-luo/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,githubutilities/LeetCode,githubutilities/LeetCode,tudennis/LeetCo... | Python/unique-word-abbreviation.py | Python/unique-word-abbreviation.py | # Time: O(n) for constructor, n is number of words in the dictionary.
# O(1) for lookup
# Space: O(k), k is number of unique words.
from sets import Set
class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str... | # Time: O(n) for constructor, n is number of words in the dictionary.
# O(1) for lookup
# Space: O(k), k is number of unique words.
from sets import Set
class ValidWordAbbr(object):
def __init__(self, dictionary):
"""
initialize your data structure here.
:type dictionary: List[str... | mit | Python |
d4bf194dc925f464a7e4f87aa1d99970b8eb44e7 | Update an example test | seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase | examples/test_docs_site.py | examples/test_docs_site.py | from seleniumbase import BaseCase
class DocsSiteTests(BaseCase):
def test_docs(self):
self.open("https://seleniumbase.io/")
self.delete_all_cookies()
self.assert_exact_text("SeleniumBase", "h1")
self.click('a[href="help_docs/features_list/"]')
self.assert_exact_tex... | from seleniumbase import BaseCase
class DocsSiteTests(BaseCase):
def test_docs(self):
self.open("https://seleniumbase.io/")
self.delete_all_cookies()
self.assert_exact_text("SeleniumBase ReadMe", "h1")
self.click('a[href="help_docs/features_list/"]')
self.assert_ex... | mit | Python |
1124941bbfbb633b91057082851729626ef68fdb | Add comment re expand_to_sematic_unit function | johyphenel/sublime-expand-region,aronwoost/sublime-expand-region,johyphenel/sublime-expand-region | expand_to_semantic_unit.py | expand_to_semantic_unit.py | import re
try:
import utils
except:
from . import utils
# This function definitely sucks and needs a serious rework. Finding semantic
# units is not that easy. Maybe a parser is needed?
def expand_to_semantic_unit(string, startIndex, endIndex):
symbols = "([{)]}"
breakSymbols = ",;=&|\n"
lookBackBreakSymbol... | import re
try:
import utils
except:
from . import utils
def expand_to_semantic_unit(string, startIndex, endIndex):
symbols = "([{)]}"
breakSymbols = ",;=&|\n"
lookBackBreakSymbols = breakSymbols + "([{"
lookForwardBreakSymbols = breakSymbols + ")]}"
symbolsRe = re.compile(r'(['+re.escape(symbols)+re.esc... | mit | Python |
e13ae9717dbb836f0057173b09a75d59d453c61c | fix typo | shadow3x3x3/renew-skyline-path-query | skyline_path/strcture/edge.py | skyline_path/strcture/edge.py | class Edge:
"""
Record Edge data
"""
def __init__(self, id, src, dst, attrs):
self.id = id
self.src = src
self.dst = dst
self.distance = attrs[0] # Distance value on first position by default.
self.attrs = attrs
def connect_nodes(self):
return (self.s... | class Edge:
"""
Record Edge data
"""
def __init__(self, id, src, dst, attrs):
self.id = id
self.src = src
self.dst = dst
self.distance = attrs[0] # Distane value on first position by default.
self.attrs = attrs
def connect_nodes(self):
return (self.sr... | mit | Python |
105f8f796af559c62d084948c59e2ed0b030896a | Update google_面经.py | UmassJin/Leetcode | Experience/May/google_面经.py | Experience/May/google_面经.py | '''
http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=135449&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26sortid%3D311
1. 两个链表 求最大的公共后缀
'''
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
def find_max_postfix(head1, head2):
if not head1 or not he... | http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=135449&extra=page%3D1%26filter%3Dsortid%26sortid%3D311%26sortid%3D311
两个链表 求最大的公共后缀
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
def find_max_postfix(head1, head2):
if not head1 or not head2: return... | mit | Python |
978fb0bf5c4e2022c33531a4e71a93d6344fef3c | clean up | awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat | onadata/apps/fsforms/viewsets/XformsViewset.py | onadata/apps/fsforms/viewsets/XformsViewset.py | from django.db.models import Q
from rest_framework import viewsets
from onadata.apps.fsforms.serializers.XformSerializer import XFormListSerializer
from onadata.apps.logger.models import XForm
class XFormViewSet(viewsets.ReadOnlyModelViewSet):
"""
A simple ViewSet for viewing xforms.
"""
queryset = X... | from django.db.models import Q
from rest_framework import viewsets
from onadata.apps.fsforms.serializers.XformSerializer import XFormListSerializer
from onadata.apps.logger.models import XForm
class XFormViewSet(viewsets.ReadOnlyModelViewSet):
"""
A simple ViewSet for viewing xforms.
"""
queryset = X... | bsd-2-clause | Python |
1475ae4f18094e047d0b110fe6526f044defa058 | Disable the warning about .env files not being present. | OpenCanada/website,OpenCanada/website,OpenCanada/website,OpenCanada/website | manage.py | manage.py | #!/usr/bin/env python
import os
import sys
import warnings
import dotenv
with warnings.catch_warnings():
warnings.simplefilter("ignore")
dotenv.read_dotenv()
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opencanada.settings")
from django.core.management import execute_f... | #!/usr/bin/env python
import os
import sys
import dotenv
dotenv.read_dotenv()
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "opencanada.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| mit | Python |
bfa56f36419ab18536cb53fcf5c0be3cd0b3183b | add doc string to run main run method | CloudBrewery/docrane | docrane/main.py | docrane/main.py | import gevent
import logging
import os
import sys
from argparse import ArgumentParser
from docrane import util
from docrane.container import Container
from docrane.watcher import ContainerWatcher, ImagesWatcher
LOG = logging.getLogger("docrane")
def run(base_key_dir):
"""
Sets up all etcd watchers to boot... | import gevent
import logging
import os
import sys
from argparse import ArgumentParser
from docrane import util
from docrane.container import Container
from docrane.watcher import ContainerWatcher, ImagesWatcher
LOG = logging.getLogger("docrane")
def run(base_key_dir):
# Main agent loop
containers = util.g... | mit | Python |
5506b9728f36e9489d51a0e96420386b411c42f6 | support packet reporting (#6) | epiphyte/freeradius,epiphyte/freeradius,epiphyte/freeradius | mods-config/python/utils/report.py | mods-config/python/utils/report.py | #!/usr/bin/python
"""reports for processing."""
import argparse
import sqlite3
OUT_PACKETS = 'Acct-Output-Packets'
IN_PACKETS = 'Acct-Input-Packets'
def _packets(cursor):
"""print information about packet thru-put."""
cursor.execute("select line, key, val from data where key = '{0}' or key = '{1}'".format(O... | #!/usr/bin/python
"""reports for processing."""
import argparse
def _packets(database):
"""print information about packet thru-put."""
print database
# available reports
available = {}
available["packets"] = _packets
def main():
"""main entry."""
parser = argparse.ArgumentParser()
parser.add_... | mit | Python |
a050fba578289e03b78dd601729d91ee49a20325 | Choose the edge annotator based on the underlying arch | axt/bingraphvis | bingraphvis/angr/factory.py | bingraphvis/angr/factory.py | from ..base import *
from . import *
from .x86 import *
from .arm import *
class AngrVisFactory(object):
def __init__(self):
pass
def default_cfg_pipeline(self, project, asminst=False, vexinst=False, remove_path_terminator=True, color_edges=True, comments=True):
vis = Vis()
vis.set_sou... | from ..base import *
from . import *
from .x86 import *
class AngrVisFactory(object):
def __init__(self):
pass
def default_cfg_pipeline(self, project, asminst=False, vexinst=False, remove_path_terminator=True, color_edges=True, comments=True):
vis = Vis()
vis.set_source(AngrCFGSource()... | bsd-2-clause | Python |
c66f32b0e6610744d074693beb443e91242970fb | Revert "Make download filenames congruent with augur "DENV" serotypes." | nextstrain/fauna,nextstrain/fauna,blab/nextstrain-db,blab/nextstrain-db | vdb/dengue_download.py | vdb/dengue_download.py | import os,datetime
from download import download
from download import get_parser
import rethinkdb as r
import time
import re
class dengue_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
def add_selections_command(self, command, selections=[], **kwargs): # Command is... | import os,datetime
from download import download
from download import get_parser
import rethinkdb as r
import time
import re
class dengue_download(download):
def __init__(self, **kwargs):
download.__init__(self, **kwargs)
def add_selections_command(self, command, selections=[], **kwargs): # Command is... | agpl-3.0 | Python |
f2e9c55a2c4a21fb588803c10fac21d1b833d276 | Fix tests (II) | Rademade/taiga-back,bdang2012/taiga-back-casting,crr0004/taiga-back,joshisa/taiga-back,dayatz/taiga-back,gauravjns/taiga-back,crr0004/taiga-back,frt-arch/taiga-back,bdang2012/taiga-back-casting,rajiteh/taiga-back,forging2012/taiga-back,crr0004/taiga-back,dycodedev/taiga-back,obimod/taiga-back,forging2012/taiga-back,ast... | tests/integration/test_project_references_sequences.py | tests/integration/test_project_references_sequences.py | import pytest
from django.core import management
from django.conf import settings
from .. import factories
@pytest.fixture
def seq():
from taiga.projects.references import sequences as seq
return seq
@pytest.fixture
def refmodels():
from taiga.projects.references import models
return models
@pytes... | import pytest
from django.core import management
from django.conf import settings
from .. import factories
@pytest.fixture
def seq():
from taiga.projects.references import sequences as seq
return seq
@pytest.fixture
def refmodels():
from taiga.projects.references import models
return models
@pytes... | agpl-3.0 | Python |
6a4fd7454e0715ecd34302b0fefe8e96e2163334 | fix bug on customer match mobile uploader | google/megalista,google/megalista | megalist_dataflow/uploaders/google_ads_customer_match/mobile_uploader.py | megalist_dataflow/uploaders/google_ads_customer_match/mobile_uploader.py | # Copyright 2020 Google LLC
#
# 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 agreed to in writing, ... | # Copyright 2020 Google LLC
#
# 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 agreed to in writing, ... | apache-2.0 | Python |
e98e34b72806c649ee029d86af2f01a4986133d4 | Update Osc.py | MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab,MyRobotLab/pyrobotlab | service/Osc.py | service/Osc.py | # start the service
osc = Runtime.start("osc","Osc")
# connect - which is not 'really' connecting - but
# specifying the host/port of where we'll be sending
# the messages to
osc.connect("localhost", 12000)
# now start sending messages
# the format is
# sendMsg(topic, arg1, arg2, arg3, ...)
osc.sendMsg("/... | # start the service
osc = Runtime.start("osc","Osc")
# connect - which is not 'really' connecting - but
# specifying the host/port of where we'll be sending
# the messages to
osc.connect("localhost", 12000)
# now start sending messages
# the format is
# sendMsg(topic, arg1, arg2, arg3, ...)
osc.sendMsg("/... | apache-2.0 | Python |
746df5cff523361145a74d9d429dc541a7b99910 | Update climbing-stairs.py | kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,jaredkoontz/leetcode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,jaredkoontz/leetcode,jaredkoontz/leetcode,kamyu104/LeetCode,yi... | Python/climbing-stairs.py | Python/climbing-stairs.py | # Time: O(n)
# Space: O(1)
#
# You are climbing a stair case. It takes n steps to reach to the top.
#
# Each time you can either climb 1 or 2 steps.
# In how many distinct ways can you climb to the top?
class Solution:
"""
:type n: int
:rtype: int
"""
def climbStairs(self, n):
prev, cur... | # Time: O(n)
# Space: O(1)
#
# You are climbing a stair case. It takes n steps to reach to the top.
#
# Each time you can either climb 1 or 2 steps.
# In how many distinct ways can you climb to the top?
class Solution:
"""
:type n: int
:rtype: int
"""
def climbStairs(self, n):
prev, cur... | mit | Python |
fba7c7119fa8c7ccea8659fdf1bb1c8fc8e9735b | Fix test function name | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps | tests/unit/services/ticketing/test_is_ticket_code_wellformed.py | tests/unit/services/ticketing/test_is_ticket_code_wellformed.py | """
:Copyright: 2006-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from byceps.services.ticketing import ticket_code_service
@pytest.mark.parametrize(
'code, expected',
[
('ZWXL' , False), # denied: too short
('zwxln' , False), # denied... | """
:Copyright: 2006-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
import pytest
from byceps.services.ticketing import ticket_code_service
@pytest.mark.parametrize(
'code, expected',
[
('ZWXL' , False), # denied: too short
('zwxln' , False), # denied... | bsd-3-clause | Python |
70c959597ace6ee820166e0716792e8d72f967e7 | change around where status code goes in the debug output | GooeeIOT/python-evrythng | src/evrythng/utils.py | src/evrythng/utils.py | import os
import requests
try:
# Python 3.x
from urllib.parse import urlencode
except:
# Python 2.x
from urlparse import urlparse
def request(request_type, resource_url, data=None, api_key=None, files=None,
base_url='https://api.evrythng.com', accept=False, debug=None,
query_pa... | import os
import requests
try:
# Python 3.x
from urllib.parse import urlencode
except:
# Python 2.x
from urlparse import urlparse
def request(request_type, resource_url, data=None, api_key=None, files=None,
base_url='https://api.evrythng.com', accept=False, debug=None,
query_pa... | mit | Python |
bb2c3c90dd351cb08a26587a3a04e7cd5faacee3 | Fix email delivery | pirati-cz/helios-server,stanley89/helios-server,pirati-cz/helios-server,stanley89/helios-server,stanley89/helios-server,pirati-cz/helios-server,pirati-cz/helios-server,stanley89/helios-server,stanley89/helios-server,pirati-cz/helios-server | helios_auth/auth_systems/pirateid.py | helios_auth/auth_systems/pirateid.py | """
Yahoo Authentication
"""
from django.http import *
from django.core.mail import send_mail
from django.conf import settings
import sys, os, cgi, urllib, urllib2, re
from xml.etree import ElementTree
from openid import view_helpers
import json
import urllib2
import logging
# some parameters to indicate that sta... | """
Yahoo Authentication
"""
from django.http import *
from django.core.mail import send_mail
from django.conf import settings
import sys, os, cgi, urllib, urllib2, re
from xml.etree import ElementTree
from openid import view_helpers
import json
import urllib2
import logging
# some parameters to indicate that sta... | apache-2.0 | Python |
64f059658894462f81ad51ae9b4f9e38348324e8 | Make leaderboard not break on AnonymousUser | sleepers-anonymous/zscore,sleepers-anonymous/zscore,sleepers-anonymous/zscore,sleepers-anonymous/zscore | sleep/views.py | sleep/views.py | from django.template import RequestContext
from django.template.loader import render_to_string
from django.http import *
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from sleep.models import Sleep, Sleeper
import datetime
def home(request):
return render(request, ... | from django.template import RequestContext
from django.template.loader import render_to_string
from django.http import *
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from sleep.models import Sleep, Sleeper
import datetime
def home(request):
return render(request, ... | mit | Python |
d2461563a109e81bc9059e60125b7bd060f0b249 | Allow dots in usernames. | django-de/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django/djangosnippets.org,django/djangosnippets.org,django-de/djangosnippets.org,django-de/djangosnippets.org | djangosnippets/urls.py | djangosnippets/urls.py | from django.conf.urls import url, patterns, include
from django.contrib import admin
from django.shortcuts import render
from cab.views import snippets
admin.autodiscover()
urlpatterns = patterns('',
url(r'^captcha/', include('captcha.urls')),
url(r'^accounts/', include('cab.urls.accounts')),
url(r'^manag... | from django.conf.urls import url, patterns, include
from django.contrib import admin
from django.shortcuts import render
admin.autodiscover()
urlpatterns = patterns('',
url(r'^captcha/', include('captcha.urls')),
url(r'^accounts/', include('cab.urls.accounts')),
url(r'^manage/', include(admin.site.urls)),... | bsd-3-clause | Python |
b3bde3bf3eecaf20c7fb8ed2bcf34992a5158965 | Allow passing in a path to a fabfile. | coderanger/fabric-rundeck | fabric_rundeck/__main__.py | fabric_rundeck/__main__.py | #
# Author:: Noah Kantrowitz <noah@coderanger.net>
#
# Copyright 2014, Noah Kantrowitz
#
# 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
#
# Unles... | #
# Author:: Noah Kantrowitz <noah@coderanger.net>
#
# Copyright 2014, Noah Kantrowitz
#
# 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
#
# Unles... | apache-2.0 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.