repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
qedsoftware/commcare-hq | corehq/blobs/tests/test_util.py | Python | bsd-3-clause | 904 | 0 | from __future__ import unicode_literals
from tempfile import NamedTemporaryFile
from unittest import TestCase
import corehq.blobs.util as mod
class TestClosingContextProxy(TestCase):
def test_proxy_is_iterable(self):
with NamedTemporaryFile() as tmp:
tmp.write("line 1\nline 2\n")
... | self.assertEqual(list(proxy), ["line 1\n", "line 2\n"])
class TestRandomUrlId(TestCase):
sample_size = 100
def setUp(self):
self.ids = [mod.random_url_id(8) for x in xrange(self.sample_size)]
def test_random_id_length(self):
self.assertGreater(min(len(id) for id in self.ids), 0, self... | self.assertEqual(max(len(id) for id in self.ids), 11, self.ids)
def test_random_id_randomness(self):
self.assertEqual(len(set(self.ids)), self.sample_size, self.ids)
|
xmnlab/pyxmn | db/conn.py | Python | gpl-3.0 | 1,460 | 0.000685 | # -*- coding: utf-8 -*-
"""
Connection module
"""
from pyxmn.utils import support
# from psycopg2.pool import SimpleConnectionPool
import psycopg2.extras # load the psycopg extras module
class Pool():
"""
Connection Pool
"""
settings = None
connection = None
pool = None
@staticmethod
... | statement, arg=()):
"""
"""
if Pool.settings.DEBUG:
try:
support.log(statement % arg)
except:
| pass
cursor.execute(statement, arg)
|
JazzyServices/jazzy | examples/DbC_methods_with_both_pre_and_post.py | Python | mit | 1,944 | 0.015947 | # coding:ascii
""" Example usage of DbC (design by contract)
In this example we show you how to use pre- and post-condition checkers
decorating the same function.
"""
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import DbC
DbC.ASSERTION_LEVEL = DbC.ASSERTION_ALL
# in this example we bring `pre` an... | val = args[-1]
# simple check of the number of items in the return
assert 2 * len(rval) == len(args) - 1
# check | units
units_out = [i%10 for i in rval]
units_in = [i for i in args[1:-1:2]]
assert units_out == units_in
# check tens
tens_out = [i//10 for i in rval]
tens_in = [i for i in args[0:-1:2]]
assert tens_out == tens_in
# It doesn't matter which order you include the decorators
@pre(check_pre)... |
ai-ku/langvis | jython-2.1/Lib/dbexts.py | Python | mit | 20,664 | 0.031165 | # $Id: dbexts.py,v 1.5 2002/01/07 04:59:50 bzimmer Exp $
"""
This script provides platform independence by wrapping Python
Database API 2.0 compatible drivers to allow seamless database
usage across implementations.
In order to use the C version, you need mxODBC and mxDateTime.
In order to use the Java version, you n... | f rollback(self):
""" rollback the cursor """
self.db.rollback()
def display(self):
""" using the formatter, display the results """
if self.formatter and self.verbose > 0:
res = self.results
if res:
print >> self.out, ""
for a in self.formatter(res, map(lambda x: x[0], self.headers)):
prin... | .begin()
try:
if bindings:
cur.execute(sql, params, bindings, maxrows=maxrows)
elif params:
cur.execute(sql, pa |
purism/pdak | tests/dbtest_cruft.py | Python | gpl-2.0 | 2,916 | 0.021605 | #!/usr/bin/env python
from db_test import DBDakTestCase
from daklib.dbconn import *
from daklib.cruft import *
import unittest
class CruftTestCase(DBDakTestCase):
"""
This class checks various functions of cruft-report.
"""
def setUp(self):
super(CruftTestCase, self).setUp()
self.in... | cation = self.loc['main'], filesize = 0, md5sum = '')
self.source['sl_3.03-17'] = DBSource(source = 'sl', version = '3.03-17', \
maintainer = self.maintainer['maintainer'], \
changedby = self.maintainer['uploader'], \
poolfile = self.file['sl_3 | .03-17.dsc'], install_date = self.install_date)
self.source['sl_3.03-17'].suites.append(self.suite['squeeze'])
list = newer_version('squeeze', 'sid', self.session)
self.assertEqual([('sl', '3.03-16', '3.03-17')], list)
def test_multiple_source(self):
'tests functions related to repo... |
mktumbi/MMPBSA-OutPut-File-Parser | MMPBSA-Outfile-Parser.py | Python | gpl-3.0 | 1,521 | 0.017751 | #!/usr/bin/python
import argparse
__author__ = 'Tumbi Mohammed Khaled'
parser = argparse.ArgumentParser(description='This is the script is to extract energy values from MMPBSA.DAT file.')
parser.add_argument('-j', '--jobname', help='Enter your job name and it will appear as first coloumn in the result file', required... | otal Electrostatic energy contribution.
EGB = all[85].split()[1] #Will extract Total GB Electrostatics Solvation parameters .
ESURF = all[86].split()[1]
GBTOT = all[92].split()[4]
EPB = all[147].split()[1]
ECAVITY = all[148].split()[1]
PBTOT = all[154].split()[4]
print args.jobname, "\t", VDWAALS, "\t", EEL... | rite(EEL)
fout.write('\t')
fout.write(EGB)
fout.write('\t')
fout.write(ESURF)
fout.write('\t')
fout.write(GBTOT)
fout.write('\t')
fout.write(EPB)
fout.write('\t')
fout.write(ECAVITY)
fout.write('\t')
fout.write(PBTOT)
fout.write('\n')
fout.close()
fin.close()
|
qateam123/eq | tests/integration/star_wars/test_radio_boxes.py | Python | mit | 1,487 | 0.002017 | from tests.integration.star_wars import | star_wars_test_urls, BLOCK_2_DEFAULT_ANSWERS
from tests.integration.star_wars.star_wars_tests import StarWarsTestCase
class TestEmptyRadioBoxes(StarWarsTestCase):
def test_radio_boxes_mandatory_empty(self):
self.login()
first_page = self.start_questionnaire_and_navigate_routing()
# We ... | survey without a mandatory radio box
# We fill in our answers missing one required field
form_data = BLOCK_2_DEFAULT_ANSWERS.copy()
del form_data['a5dc09e8-36f2-4bf4-97be-c9e6ca8cbe0d']
# We submit the form
resp = self.submit_page(first_page, form_data)
# We stay on t... |
Zundrium/djangocms-gamegroup | matches/models.py | Python | mit | 967 | 0.018614 | from django.db import models
from cms.models import CMSPlugin
from community.models import Clan, Member | , Game
from django.utils.translation import ugettext as _
class Match(models.Model):
datetime = models.DateTimeField(_("Date"))
game = models.ForeignKey(Game, verbose_name=_("Game"))
clanA = models.ForeignKey(Clan, related_name="clanA_set")
clanB = models.For | eignKey(Clan, related_name="clanB_set")
winner = models.ForeignKey(Clan, null=True, blank=True)
def __unicode__(self):
return "%s vs %s" % (self.clanA, self.clanB)
class MemberScore(models.Model):
match = models.ForeignKey(Match, verbose_name=_("Match"))
player = models.ForeignKey(Member, verbose_name=_("Player"... |
coocol/WeWater | waterproj/settings.py | Python | cc0-1.0 | 1,901 | 0 | # -*- coding: utf-8 -*-
"""
Django 配置 for waterproj project.
"""
import os
import wewater
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z(d^c!%f2yip&*qzj)bqcq*9lc=ch78 | (=5n3$79be6xs7om_$i'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
... | ib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking... |
nkgilley/home-assistant | tests/components/switch/common.py | Python | apache-2.0 | 1,177 | 0.001699 | """Collection of helper methods.
All containing methods are legacy helpers that should not be used by new
components. Instead call the service directly.
"""
from homeassistant.components.switch import DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
ENTITY_MATCH_ALL,
SERVICE_TURN_OFF,
SERVICE_T... | LL):
"""Turn all or specified switch on."""
data = {ATTR_ENTITY_ID: entity_id} if entity_id else None
await hass.services.async_call(DOMAIN, SERVICE_TURN_ON, data, bl | ocking=True)
@bind_hass
def turn_off(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified switch off."""
hass.add_job(async_turn_off, hass, entity_id)
async def async_turn_off(hass, entity_id=ENTITY_MATCH_ALL):
"""Turn all or specified switch off."""
data = {ATTR_ENTITY_ID: entity_id} if enti... |
caioserra/apiAdwords | examples/adspygoogle/dfp/v201306/approve_orders.py | Python | apache-2.0 | 2,329 | 0.003435 | #!/usr/bin/python
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This code example approves all eligible draft and pending orders. To
determine which orders exist, run get_all_orders.py."""
__author__ = 'api.shamjeff@gmail.com... | rt datetime
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..'))
# Import appropriate classes from the client library.
from adspygoogle import DfpClient
from adspygoogle.dfp import DfpUtils
# Initialize client object.
client = DfpClient(path=os.path.join('..', '..', '..', '..'))
# Initializ... |
Azure/azure-sql-database-samples | django/django-mssql/DjangoWebProject1/settings.py | Python | mit | 5,410 | 0.000555 | """
Django settings for DjangoWebProject1 project.
"""
from os import path
PROJECT_ROOT = path.dirname(path.abspath(path.dirname(__file__)))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = (
'localhost',
)
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'def... | Middleware',
)
ROOT_URLCONF = 'DjangoWebProject1.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'DjangoWebProject1.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/hom | e/html/django_templates" or
# "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
... |
mohamedhagag/community-addons | product_unique_serial/tests/test_for_unicity.py | Python | agpl-3.0 | 22,996 | 0 | # coding: utf-8
###############################################################################
# Module Writen to OpenERP, Open Source Management Solution
#
# Copyright (c) 2010 Vauxoo - http://www.vauxoo.com/
# All Rights Reserved.
# info Vauxoo (info@vauxoo.com)
##########################################... | 'lot_unique_ok': True}),
"Cannot write produ | ct %s" % (product.name))
stock_move_datas = [{
'product_id': product.id,
'qty': 1.0
}]
# Creating the pickings
picking_data_1 = {
'name': 'Test Picking IN 1',
}
picking_data_2 = {
'name': 'Test Picking IN 2',
}
... |
rpavlik/jhbuild-vrjuggler | jhbuild/utils/unpack.py | Python | gpl-2.0 | 5,855 | 0.002391 | # jhbuild - a build script for GNOME 1.x and 2.x
# Copyright (C) 2007 Alberto Ruiz <aruiz@gnome.org>
#
# unpack.py: helper functions for unpacking compressed packages
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the ... | .path.splitext(localfile)[-1]
if ext == '.lzma' and has_command('lzcat') and has_command('tar'):
buildscript.execute('lzcat -d "%s" | tar xf -' % localfile,
cwd=target_directory)
elif ext == '.xz' and has_command('xzcat') and has_command('tar'):
| buildscript.execute('xzcat -d "%s" | tar xf -' % localfile,
cwd=target_directory)
elif ext == '.bz2' and has_command('bunzip2') and has_command('tar'):
buildscript.execute('bunzip2 -dc "%s" | tar xf -' % localfile,
cwd=target_directory)
elif ext in ('.gz', '.tgz')... |
shykes/cloudlets | cloudlets.py | Python | apache-2.0 | 10,876 | 0.00377 |
import os
import re
import sys
import shutil
import tarfile
import subprocess
from tempfile import mkdtemp, mktemp
import js
import metashelf
import vm2vm.raw
import jsonschema
import simplejson as json
from ejs import EJSTemplate
import mercurial.hg, mercurial.ui, mercurial.error, mercurial.dispatch
class DictSchem... | ile:
include += map(re.compile, self.manifest.get("volatile", []))
if persistent: |
include += [re.compile("^{0}($|/)".format(p)) for p in self.manifest.get("persistent", [])]
return self.get_files(include=include, exclude=exclude)
def get_cloudletdir(self):
""" Return the path of the directory containing the image's metadata. """
return os.path.join(self.... |
arcward/martapy | setup.py | Python | mit | 599 | 0.001669 | from setuptools import setup
import os
import martapy
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name="martapy",
version=martapy.__version__,
author=martapy. | __author__,
author_email="git@edward.sh",
description="Wrapper for MARTA realtime rail/bus APIs",
long_description=read('README.rst'),
keywords="MARTA API rail train Atlanta Georgia GA ATL itsmarta",
url="https://github.com/arcward/fbparser",
license="MIT",
packages=['martapy'],
in | stall_requires=['requests'],
include_package_data=True
)
|
GNS3/gns3-server | gns3server/compute/iou/utils/iou_export.py | Python | gpl-3.0 | 7,003 | 0.000428 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# To use python v2.7 change the first line to:
#!/usr/bin/env python
# Copyright (C) 2015 Bernhard Ehlers
#
# This program 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 F... | if bitPos > numBufBits:
break
| if symbol >= head:
raise ValueError('invalid data')
if blockMode and symbol == 256:
numBufBits = bitPos = 0
numBits = LZC_NUM_BITS_MIN
head = 257
needPrev = 0
continue
# convert symbol to string
stack = []
cu... |
pbardea/scribbler | finalPrj/notUsed/makex.py | Python | mit | 606 | 0.008251 | def makex():
threesixty(.5, -.5, 0.835)
wait(.2)
forward(1, 0.806)
wait(.1)
backward(1, 0.403)
wait(.1)
threesix | ty(1, -1, 0.835)
wait(.1)
forward(1, 0.403)
wait(.1)
backward(1, 0.806)
wait(.2)
threesixty(.5, -.5, 0.835)
wait(.2)
forward(1, .57)
wait(.2)
threesixty(1, -1, 1.6478)
stop()
#########################################################... | and where we want the bot to finish
# add a ccw or cw in function?
|
Eloston/ungoogled-chromium | devutils/check_patch_files.py | Python | bsd-3-clause | 4,385 | 0.001824 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# Copyright (c) 2019 The ungoogled-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.
"""Run sanity checking algorithms over ungoogled-chromium's patch files
It checks the following... | are not are logged to stdout.
Returns True if warnings occured, False otherwise.
"""
warnings = False
for patch_path in _read_series_file(patches_dir, series_path, join_dir=True):
if patch_path.exists():
with patch_path.open(encoding=ENCODING) as file_obj:
try:
... | parse patch: %s', patch_path)
warnings = True
continue
else:
get_logger().warning('Patch not found: %s', patch_path)
warnings = True
return warnings
def check_unused_patches(patches_dir, series_path=Path('series')):
"""
Checks if the... |
akvo/akvo-rsr | akvo/rest/serializers/indicator_period_disaggregation.py | Python | agpl-3.0 | 3,125 | 0.00256 | # -*- coding: utf-8 -*-
# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
from rest_framework import serializers... | ue.name.pk, 'name': obj.dimension_value.n | ame.name}
def get_dimension_value(self, obj):
return {'id': obj.dimension_value.pk, 'value': obj.dimension_value.value}
class Meta:
model = IndicatorPeriodDisaggregation
fields = (
'id',
'dimension_name',
'dimension_value',
'value',
... |
birryree/servo | python/servo/bootstrap_commands.py | Python | mpl-2.0 | 16,812 | 0.002736 | # Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
#... | (chunk)
if not dumb:
print()
except urllib2.HTTPError, e:
print("Download failed (%d): %s - %s" % (e.code, e.reason, src))
if e.code == 403:
print("No Rust compiler binary available for this platform. "
"Please see https://github.com/servo/servo/#pr... | ailing URL was: %s" % (e.reason, src))
sys.exit(1)
except socket_error, e:
print("Looks like there's a connectivity issue, check your Internet connection. %s" % (e))
sys.exit(1)
except KeyboardInterrupt:
writer.flush()
raise
def download_file(desc, src, dst):
tmp_pa... |
agiacomolli/odfpy | contrib/tracplugins/0.10/odfpreview/__init__.py | Python | apache-2.0 | 34 | 0 | from | odfpreview impor | t OdfPreview
|
knipknap/SpiffWorkflow | tests/SpiffWorkflow/serializer/dictTest.py | Python | lgpl-3.0 | 2,803 | 0.002141 | # -*- coding: utf-8 -*-
from __future__ import print_function, absolute_import, division
from builtins import str
import sys
import unittest
import re
import os
dirname = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(dirname, '..', '..', '..'))
import uuid
from SpiffWorkflow.serializer.dict import Dictiona... | =False,
exclude_items=None):
exclude_items = exclude_items if exclude_items is not None else []
if exclude_dynamic:
if 'last_state_change' not in exclude_items:
exclude_items.append('last_state_change')
if 'last_task' not in exclude_items:... | exclude_items.append('last_task')
if uuid.UUID not in exclude_items:
exclude_items.append(uuid.UUID)
if type(item1) in exclude_items:
return
if isinstance(item1, dict):
self.assertIsInstance(item2, dict)
for key, value in l... |
major/monitorstack | monitorstack/cli.py | Python | apache-2.0 | 3,975 | 0 | #!/usr/bin/env python
# Copyright 2017, Major Hayden <major@mhtx.net>
#
# 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... | '))
output_formatter = getattr(
importlib.import_module(module_name),
method_name
)
# Force the output formatter into a list
if not isinstance(results, list): # pragma: no cover
results = [results]
exit_code = 0
for result in results:
output_formatter(result)
... | pdir = os.path.normpath(
os.path.join(
os.path.abspath(
sys.argv[0]
),
os.pardir,
os.pardir
)
)
sys.path.insert(0, topdir)
cli()
|
Heipiao/weibo | retry.py | Python | mit | 1,243 | 0.018504 | import math
import time
# Retry decorator with exponential backoff
def retry(tries, delay=1, backoff=2):
"""Retries a function or method until it returns True.
delay sets the initial delay, and backoff sets how much the delay should
lengthen after each failure. backoff must be greater than 1, or else it
isn'... | r than 1")
tries = math.floor(tries)
if tries < 0:
raise ValueError("tries must be 0 or greater")
if delay <= 0:
raise ValueError("delay must be greater than 0")
def deco_retry(f):
def f_retry(*args, **kwargs):
| mtries, mdelay = tries, delay # make mutable
rv = f(*args, **kwargs) # first attempt
while mtries > 0:
if rv == True or type(rv) == str: # Done on success ..
return rv
mtries -= 1 # consume an attempt
time.sleep(mdelay) # wait...
mdelay *= backoff # make fu... |
pculture/mirocommunity | localtv/templatetags/video_list.py | Python | agpl-3.0 | 3,388 | 0.000295 | from django import template
from localtv.search.utils import NormalizedVideoList
from localtv.search.views import SortFilterMixin
register = template.Library()
class BaseVideoListNode(SortFilterMixin, template.Node):
"""
Base helper class (abstract) for handling the get_video_list_* template
tags. Bas... | one) + 2
if len(bits) != argument_count:
raise template.TemplateSyntaxError(
"%r tag requires %i arguments" % (tag_name, argument_count))
item = None
if argument | _count == 3:
item = parser.compile_filter(bits[0])
bits = bits[1:]
if bits[0] != 'as':
raise template.TemplateSyntaxError(
"%s argument in %r tag must be 'as'" % (
"Third" if argument_count == 3 else "Second", tag_name))
ret... |
justincely/cos_monitoring | tests/conftest.py | Python | bsd-3-clause | 1,819 | 0.002749 | import os
import pytest
from glob import glob
HERE = os.path.dirname(os.path.abspath(__file__))
TEST_CONFIG = os.path.join(HERE, 'cosmoconfig_test.yaml')
# Check to make sure that the test config file is being used. If not, don't run the tests
if os.environ['MONITOR_CONFIG'] != TEST_CONFIG:
raise TypeError('Tes... | onfiguration file')
if os.environ['COSMO_SMS_DB'] != os.path.join(HERE, 'test.db'):
raise TypeError('Test should only be executed with a test database')
@pytest.fixture(scope='session', autouse=True)
def db_cleanup():
yield # The tests don't actually need this test "value"
# Cleanup
if os.path.ex | ists('test.db'):
os.remove('test.db') # Delete test database file after the completion of all tests
# Remove temporary shared memory file if it exists
if os.path.exists('test.db-shm'):
os.remove('test.db-shm')
# Remove temporary write-ahead log file if it exists
if os.path.exists('te... |
Diacamma2/asso | diacamma/member/printmodel/TaxReceipt_0001.py | Python | gpl-3.0 | 4,411 | 0.002494 | # -*- coding: utf-8 -*-
'''
Printmodel django module for invoice
@author: Laurent GAY
@organization: sd-libre.fr
@contact: info@sd-libre.fr
@copyright: 2016 sd-libre.fr
@license: This file is part of Lucterios.
Lucterios is free software: you can redistribute it and/or modify
it under the terms of the GNU General Pub... | ns-serif" font_weight="" font_size="9">
%(text recipient)s : {[b]}***#total***{[/b]}{[br/]}
{[br/]}
%(Date payoff)s : {[b]}#date_payoff{[/b]}{[br/]}
%( | Mode payoff)s : {[b]}#mode_payoff{[/b]}{[br/]}
</text>
<text height="15.0" width="60.0" top="60.0" left="130.0" padding="1.0" spacing="0.0" border_color="black" border_style="" border_width="0.2" text_align="right" line_height="10" font_family="sans-serif" font_weight="" font_size="9">
#date{[br/]}
%(signature)s
</text... |
Vaysman/ntlmaps | ntlmaps/config_affairs.py | Python | gpl-2.0 | 5,763 | 0.007635 | # This file is part of 'NTLM Authorization Proxy Server'
# Copyright 2001 Dmitry A. Rozmanov <dima@xenon.spb.ru>
#
# NTLM APS 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 2 of the Licens... | conf['GENERAL']['MAX_CONNECTION_BACKLOG'] = int(conf['GENERAL']['MAX_CONNECTION_BACKLOG'])
except ValueError:
|
if conf['GENERAL']['MAX_CONNECTION_BACKLOG'] == 'SOMAXCONN':
conf['GENERAL']['MAX_CONNECTION_BACKLOG'] = socket.SOMAXCONN
else:
print "ERROR: There is a problem with 'MAX_CONNECTION_BACKLOG' in the config (neither a number nor 'SOMAXCONN'?)"
sys.exit(1)
conf... |
clarkyzl/flink | flink-python/pyflink/table/tests/test_udtf.py | Python | apache-2.0 | 5,986 | 0.003174 | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... | ou may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distribute | d on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
import unittest
from pyflink.table ... |
KL-WLCR/incubator-airflow | tests/test_logging_config.py | Python | apache-2.0 | 7,599 | 0.001053 | # -*- coding: utf-8 -*-
#
# 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
... | ame | )s:%%(lineno)d}} %%(levelname)s - %%(message)s'
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'airflow.task',
'stream': 'ext://sys.stdout'
}
},
'loggers': {
'airflow': {
'handlers': ['file.h... |
okdana/mp3civ | mp3sum/logging.py | Python | mit | 3,911 | 0.072871 | # -*- coding: utf-8 -*-
"""
Log/output handling.
"""
from __future__ import print_function
import sys
import colors
CRITICAL = 50
ERROR = 40
WARNING = 30
INFO = 20
DEBUG = 10
_levels = [
CRITICAL,
ERROR,
WARNING,
INFO,
DEBUG,
]
_levels_to_names = {
CRITICAL: 'CRITICAL',
ERROR: 'ERROR',... | evel):
self.level = self.normalise_level(level)
return self
def normalise_level(self, level):
if str(level) == level:
if level not in _names_to_levels:
raise ValueError('Unknown level %s' % level)
level = _name_to_levels[level]
i | f level > _levels[0]:
level = _levels[0]
if level < _levels[-1]:
level = _levels[-1]
if level not in _levels:
raise ValueError('Unknown level %i' % level)
return level
def puts(
self,
message,
level = None,
fg = None,
bg = None,
style = None,
pref... |
shenxudeu/deuNN | deuNet/layers/batch_normalization.py | Python | mit | 4,407 | 0.009984 | import theano
import theano.tensor as T
from .. import activations, initializations
from .. utils.theano_utils import shared_zeros
from .. layers.core import Layer
import pdb
class BatchNormalization(Layer):
"""
Batch Normalization:
Published by S. Ioffee and C. Szegedy from Google.Solve the gradient
... | N2D, self).__init__()
self.alpha = alpha
self.k = k
self.beta = beta
self.n = n
def get_output(self, train):
X = self.get_input(train)
b, ch, r, c = X.shape
half_n = self.n // 2
input_sqr = T.sqr(X)
extra_channels = T.alloc(0., b, ch + 2 * hal... | in range(self.n):
scale += self.alpha * input_sqr[:, i:i+ch, : , :]
scale = scale ** self.beta
return X/ scale
def get_config(self):
return {"name": self.__class__.__name__,
"alpha": self.alpha,
"k": self.k,
"beta": self.beta,
... |
NitorCreations/aws-utils | opt/nitor/library/ec2_ami_find.py | Python | apache-2.0 | 9,762 | 0.006556 | #!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distribut... | description:
- A hypervisor type type to match (e.g. xen).
default: null
required: false
is_public:
description:
- Whether or not the image(s) are public.
choices: ['yes', 'no']
default: null
required: false
name:
description:
- An AMI name to | match.
default: null
required: false
platform:
description:
- Platform type to match.
default: null
required: false
sort:
description:
- Optional attribute which with to sort the results.
- If specifying 'tag', the 'tag_name' parameter is required.
choices: ['name', 'd... |
tiregram/Boufix | snackix/migrations/0001_initial.py | Python | agpl-3.0 | 2,164 | 0.002311 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-02-06 16:27
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... | ls.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Product',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_... | 'description', models.CharField(max_length=200)),
('price', models.IntegerField()),
('hide', models.BooleanField(default=False)),
('image', models.ImageField(upload_to='static')),
],
),
migrations.AddField(
model_name='logs',
... |
CCS-Lab/hBayesDM | Python/tests/test_bandit2arm_delta.py | Python | gpl-3.0 | 228 | 0 | import pytest
from hbayesdm.models import bandit2arm_delta
def test_bandit2arm_delta() | :
_ = bandit2arm_delta(
data="example", niter=10, nwarmup=5, nchain=1, ncore=1)
if __name__ == '__main__':
| pytest.main()
|
kenshay/ImageScript | ProgramData/SystemFiles/Python/Lib/site-packages/scipy/special/_precompute/gammainc_asy.py | Python | gpl-3.0 | 2,599 | 0.001539 | """
Precompute coefficients of Temme's asymptotic expansion for gammainc.
This takes a | bout 8 hours to run on a 2.3 GHz Macbook Pro with 4GB ram.
Sources:
[1] NIST, "Digital Library of Mathematical Functions",
http://dlmf.nist.gov/
"""
from __future__ import division, print_function, absolute_import
import os
from scipy.special._precompute.utils import lagrange_inversion
try:
import | mpmath as mp
except ImportError:
pass
def compute_a(n):
"""a_k from DLMF 5.11.6"""
a = [mp.sqrt(2)/2]
for k in range(1, n):
ak = a[-1]/k
for j in range(1, len(a)):
ak -= a[j]*a[-j]/(j + 1)
ak /= a[0]*(1 + mp.mpf(1)/(k + 1))
a.append(ak)
return a
def co... |
kennedyshead/home-assistant | homeassistant/components/fan/device_trigger.py | Python | apache-2.0 | 1,252 | 0.001597 | """Provides device automations for Fan."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.automation import AutomationActionType
from homeassistant.components.device_automation import toggle_entity
from homeassistant.const import CONF_DOMAIN
from homeassistant.core import CA... | K_TYPE, HomeAssistant
from homeassistant.helpers.typing import ConfigType
from . import DOMAIN
TRIG | GER_SCHEMA = toggle_entity.TRIGGER_SCHEMA.extend(
{vol.Required(CONF_DOMAIN): DOMAIN}
)
async def async_get_triggers(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device triggers for Fan devices."""
return await toggle_entity.async_get_triggers(hass, device_id, DOMAIN)
async def async_get_... |
jrrpanix/master | examples/python/math/matplotlibExample2.py | Python | gpl-3.0 | 5,018 | 0.02232 | import os
import numpy as np
import scipy
import matplotlib as mp
import matplotlib.pyplot as plt
def plot_colors() :
return ['g green',
'r red',
'c cyan',
'm magenta',
'y yellow',
'k black',
'w white']
def plot_markers() :
return ['s square marker',
... | 0.05),
)
plt.ylim(-2,2)
t=plt.text(0.5, 1.1, r'cos($2\pi$)')
#print(dir(t))
t.set_fontsize(20)
t.set_color('purple')
plt.show()
def plot7() :
y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))
... |
plt.yscale('linear')
plt.title('linear')
plt.grid(True)
# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)
# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.05)
plt.title('symlog'... |
dark-lbp/isf | icssploit/modules/creds/http_basic_bruteforce.py | Python | bsd-2-clause | 3,678 | 0.002719 | import threading
import itertools
from icssploit import (
exploits,
wordlists,
print_status,
print_error,
print_success,
print_table,
http_request,
multi,
threads,
validators,
)
from icssploit.exceptions import StopThreadPoolExecutor
class Exploit(exploits.Exploit):
"""
... | pas | sword = password.encode('utf-8').strip()
response = http_request(method="GET", url=url, auth=(user, password))
if response is not None and response.status_code != 401:
print_success("Target: {}:{} {}: Authentication Succeed - Username: '{}' Password: '{}'".format(self.target, self.port, na... |
SummerLW/Perf-Insight-Report | catapult_build/html_checks_unittest.py | Python | bsd-3-clause | 2,443 | 0.00614 | # Copyright 2015 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.
import unittest
from catapult_build import html_checks
class MockAffectedFile(object):
def __init__(self, path, lines):
self.path | = path
self.lines = lines
def NewContents(self):
return (l for l in self.lines)
def LocalPath(self):
return self.path
class MockInputApi(object):
def __init__(self, affected_files):
self.affected_files = affected_files
def AffectedFiles(self, file_filter=None, **_):
if file_filter:
... | return filter(file_filter, self.affected_files)
return self.affected_files
class MockOutputApi(object):
def PresubmitError(self, error_text):
return error_text
class HtmlChecksTest(unittest.TestCase):
def testRunChecksShowsErrorForWrongDoctype(self):
f = MockAffectedFile('foo/x.html', ['<!DOCTYP... |
chrislit/abydos | tests/phonetic/test_phonetic_soundex.py | Python | gpl-3.0 | 6,370 | 0 | # Copyright 2014-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | ')
self.assertEqual(pa_special.encode('Ashcroft'), 'A226')
self. | assertEqual(pa_special.encode('Asicroft'), 'A226')
self.assertEqual(pa_special.encode('AsWcroft'), 'A226')
self.assertEqual(pa_special.encode('Rupert'), 'R163')
self.assertEqual(pa_special.encode('Rubin'), 'R150')
def test_soundex_census(self):
"""Test abydos.phonetic.Soundex(Census... |
kennedyshead/home-assistant | homeassistant/components/cloud/tts.py | Python | apache-2.0 | 2,957 | 0.000338 | """Support for the cloud for text to speech service."""
from hass_nabucasa import Cloud
from hass_nabucasa.voice import MAP_VOICE, VoiceError
import voluptuous as vol
from homeassistant.components.tts import CONF_LANG, PLATFORM_SCHEMA, Provider
from .const import DOMAIN
CONF_GENDER = "gender"
SUPPORT_LANGUAGES = l... | raise vol.Invalid("Unsupported language and gender specified.")
return value
PLATFORM_SCHEMA = vol.All(
PLATFORM_SCHEMA.extend(
{
vol.Optional(CONF_LANG): str,
vol.Optional(CONF_GENDER): str,
}
),
validate_lang,
)
async def async_get_engine(hass, config,... | nfo=None):
"""Set up Cloud speech component."""
cloud: Cloud = hass.data[DOMAIN]
if discovery_info is not None:
language = None
gender = None
else:
language = config[CONF_LANG]
gender = config[CONF_GENDER]
return CloudProvider(cloud, language, gender)
class CloudP... |
beni55/pokeapi | pokemon/models.py | Python | bsd-3-clause | 11,645 | 0.000086 | from __future__ import unicode_literals
from django.db import models
from imagekit.models.fields import ProcessedImageField
from imagekit.processors import ResizeToFill
from .utils import unique_filename
class DateTimeModel(models.Model):
class Meta:
abstract = True
modified = models.DateTimeField... | to=e.to.name.capitalize(),
resource_uri='/api/v1/pokemon/' + str(e.to.pkdx_id) + '/',
| method=e.method,
)
if e.level > 0:
d['level'] = e.level
if e.detail:
d['detail'] = e.detail
lst.append(d)
return lst
return []
evolutions = property(fget=get_evolution_details)
... |
akvo/akvo-rsr | akvo/rsr/models/__init__.py | Python | agpl-3.0 | 29,900 | 0.006254 | # -*- coding: utf-8 -*-
# Akvo RSR is covered by the GNU Affero General Public License.
# See more details in the license.txt file located at the root folder of the Akvo RSR module.
# For additional details on the GNU license please see < http://www.gnu.org/licenses/agpl.html >.
import logging
from django.db.models.... | 'OrganisationTotalBudgetLine',
'OrganisationTotalExpenditure',
'ProjectLocation',
'ProjectUpdateLocation',
'PartnerSite',
'Partnership',
'PeriodActualValue',
'PeriodDisaggregation',
'IndicatorPeriodDisaggregation',
'PlannedDisbursement',
'PolicyMark | er',
'Project',
'ProjectCondition',
'ProjectContact',
'ProjectCustomField',
'ProjectDocument',
'ProjectDocumentCategory',
'ProjectEditorValidation',
'ProjectEditorValidationSet',
'ProjectHierarchy',
'ProjectRole',
'ProjectUpdate',
'ProjectUpdatePhoto',
'PublishingStat... |
Shirui816/UmbrellaIntegrate.py | ubint.py | Python | mit | 9,737 | 0.00113 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: shirui <shirui816@gmail.com>
import re
import warnings
import argparse
from scipy.constants import Boltzmann as KB
from scipy.constants import Avogadro as NA
import numpy as np
import pandas as pd
from argparse import RawTextHelpFormatter
from scipy.integrate impo... | window_data - x0 + xi_range[0] # move data to -P/2, P/2
xi_mean_w = circmean(window_data, high=period / 2, low=-period / 2)
window_data = pbc(window_data - xi_mean_w, period)
# unwrap data
# move the MEAN of the distribution to 0, only for relatively
# symmetric distributions. I... | , distances further than
# half period is permitted. However, I don't think this case is physical...
xi_var_w = np.mean(window_data ** 2)
delta_xis = pbc(xis - xi_mean_w, period)
delta_xis_ref = pbc(xis - xi_center_w, period)
else:
xi_mean_w = window_data.mean()
xi_va... |
derNarr/synchronicity | experiment/generate_sessionfiles.py | Python | mit | 3,446 | 0.002322 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from __future__ import division
import random
import os
import math
import pickle
import stimulus
WIN_SIZE = (1280, 1024)
FPS = 60
N_RANDOM_TRIALS = 25
def create_random_items():
"""
Creates pickle files with lists of random positions for RandomWalk and
R... | ses_file.write("\n")
ses_file.write("\n")
if vpnr % 2 == 0:
ses_file.write("run_movie(movie1audio, 'Jetzt folgt ein Video mit Ton.\\n\\nWeiter mit Leertaste')\n"
+ "run_movie(movie2noaudio, 'Jetzt folgt ein Video OHNE Ton.\\n\\nWei... | + "run_movie(movie2audio, 'Jetzt folgt ein Video mit Ton.\\n\\nWeiter mit Leertaste')\n")
|
vickenty/ookoobah | ookoobah/data.py | Python | mit | 199 | 0.01005 | """Data loaders.
Add functions here to load specific types of resources.
"""
from __futu | re__ import division
import os
from pyglet import resource
resource.path = [ 'data' | ]
resource.reindex()
|
f0rki/cb-multios | original-challenges/AIS-Lite/poller/for-release/machine.py | Python | mit | 5,236 | 0.02903 | #!/usr/bin/env python
#
# Copyright (C) 2014 Narf Industries <info@narfindustries.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# t... | rmat(s_p2))
eng = m5.get_engl_str()
# print "read '{0}'".format(eng)
self.read(length=len(eng), expect=eng)
def | type_five_bad(self):
'''
Send a malformed type 5 message.
'''
m5 = ais.MsgType5()
s5 = ais.Sentence(m5)
[s_p1, s_p2] = s5.get_sentences()
eng = self.INVALID_SENTENCE
if self.chance(self.FAIL_CHANCE): # invaild part 1
# bad checksum
if self.chance(self.FAIL_CHANCE):
cs = s_p1[-2:]
cs = int... |
mathLab/RBniCS | rbnics/backends/online/numpy/wrapping/function_load.py | Python | lgpl-3.0 | 485 | 0 | # Copyright (C) 2015-2022 by the RBniCS a | uthors
#
# This file is part of RBniCS.
#
# SPDX-License-Identifier: LGPL-3.0-or-later
from rbnics.utils.io import NumpyIO
def function_load(fun, directory, filename, suffix=None):
if suffix is not None:
filename = filename + "." + str(suffix)
file_exists = NumpyIO.exists_file(directory, filename)
... | vector()[:] = vec
return file_exists
|
Cube777/dotgit | dotgit/plugins/plain.py | Python | gpl-2.0 | 1,536 | 0 | import os
import shutil
import filecmp
from dotgit.plugin import Plugin
class PlainPlugin(Plugin):
def __init__(self, *args, **kwargs):
self.hard = kwargs.pop('hard', False)
super().__init__(*args, **kwargs)
def setup_data(self):
pass
# copies file from outside the repo to the r... | not in hard mode, creates a symlink in dest (outside the repo) that
# points to source (inside the repo)
# if in hard mode, copies the file from the repo to the dest.
def remove(self, source, dest):
if self.hard:
shutil.copy2(source, dest)
else:
os.s | ymlink(source, dest)
# if not in hard mode, checks if symlink points to file in repo
# if in hard mode, a bit-by-bit comparison is made to compare the files
def samefile(self, repo_file, ext_file):
if self.hard:
if os.path.islink(ext_file):
return False
if no... |
jelly/calibre | src/calibre/ebooks/conversion/plugins/lrf_output.py | Python | gpl-3.0 | 7,750 | 0.006194 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import sys, os
from calibre.customize.conversion import OutputFormatPlugin
from cal... | efstream=imageStream,
blockwidth=width, blockheight=height, xsize=width,
ysize=height, x1=width, y1=height))
| book.append(_page)
book.renderLrf(open(opts.output, 'wb'))
def flatten_toc(self):
from calibre.ebooks.oeb.base import TOC
nroot = TOC()
for x in self.oeb.toc.iterdescendants():
nroot.add(x.title, x.href)
self.oeb.toc = nroot
def convert(self, oeb, ou... |
NaraJeamfry/CodeathonURV2016_Raspi | PublicServer/faculty/migrations/0001_initial.py | Python | mit | 1,021 | 0.003918 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-13 18:52
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
| class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODE | L),
('supervision', '0001_initial'),
('bookings', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Professor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... |
Princeton-CDH/derrida-django | ci/testsettings.py | Python | apache-2.0 | 1,100 | 0 | # This file is exec'd from settings.py, so it has access to and can
# modify all the variables in settings.py.
# If this file is changed in development, the development server will
# have to be manually restarted because changes will not be noticed
# immediately.
DEBUG = False
ALLOWED_HOSTS = ["*"]
# disable compress... | ': '3306',
},
}
# must be defined for initial setup
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'derrida.common.solr_backend.RangeSolrEngine',
'URL': 'http://127.0.0.1:8983/solr/derrida',
'ADMIN_URL': 'http://127.0.0.1:8983/solr/admin/cores',
}
}
# for unit tests, that swap te... | added as a travis build step
|
erudit/zenon | tests/functional/apps/public/journal/test_views.py | Python | gpl-3.0 | 135,649 | 0.003 | from bs4 import BeautifulSoup
from collections import OrderedDict
from lxml import etree as et
import datetime as dt
import io
import os
import pikepdf
import unittest.mock
import subprocess
import itertools
from hashlib import md5
from unittest.mock import PropertyMock
from django.contrib.auth.models import Anonymou... | ')
# Run
response = self.client.get(url)
displayed_journals = set(response.context['journals'])
assert displayed_journals == set(journals[:5])
assert journals[5] not in displayed_journals
def test_can_sort_journals_by_name(self):
# Setup
collection = Collecti... | n, name='ABC journal')
journal_2 = JournalFactory.create_with_issue(collection=collection, name='ACD journal')
journal_3 = JournalFactory.create_with_issue(collection=collection, name='DEF journal')
journal_4 = JournalFactory.create_with_issue(collection=collection, name='GHI journal')
j... |
testmana2/test | E5Gui/E5LineEditButton.py | Python | gpl-3.0 | 2,885 | 0.005199 | # -*- coding: utf-8 -*-
# Copyright (c) 2010 - 2015 Detlev Offenbach <detlev@die-offenbachs.de>
#
"""
Module implementing a button class to be used with E5LineEdit.
"""
from __future__ import unicode_literals
from PyQt5.QtCore import Qt, QPoint, QPointF
from PyQt5.QtGui import QPainter, QPainterPath
from PyQt5.QtWi... | method to get a reference to the menu.
@return reference to the associated menu (QMenu)
"""
return self.__menu
def setIcon(self, icon):
"""
Public method to set the button icon.
@param icon icon to be set (QIcon)
"""
if icon.isN... | = None
else:
self.__image = icon.pixmap(16, 16).toImage()
super(E5LineEditButton, self).setIcon(icon)
def __clicked(self):
"""
Private slot to handle a button click.
"""
if self.__menu:
pos = self.mapToGlobal(QPoint(0, self.height()))
... |
guillermooo/dart-sublime-bundle-releases | sublime_plugin_lib/__init__.py | Python | bsd-3-clause | 4,790 | 0.001253 | # Copyright (c) 2014, Guill | ermo López-Anglada. Please see the AUTHORS file for details.
# All rights reserved. Use of this source code is g | overned by a BSD-style
# license that can be found in the LICENSE file.)
from logging.handlers import RotatingFileHandler
from os import path
import logging
import logging.config
import logging.handlers
import os
import sys
class LogDir(object):
'''
Locates the log dir for plugin logs.
'''
@staticm... |
tommy-u/chaco | examples/demo/canvas/mp_viewport_pan_tool.py | Python | bsd-3-clause | 1,535 | 0.001954 |
from traits.api import Int, Tuple
from enable.tools.api import ViewportPanTool
class MPViewportPanTool(ViewportPanTool):
cur_bid = Int(-1)
_last_blob_pos = Tuple
def normal_blob_down(self, event) | :
if self.cur_bid == -1 and self.is_draggable(event.x, event.y):
self.cur_bid = event.bid
self.drag_start(event)
def dragging_blob_up(self, event):
if event.bid == self.cur_bid:
self.cur_bid = -1
self.drag_end(event)
| def dragging_blob_move(self, event):
if event.bid == self.cur_bid:
self._last_blob_pos = (event.x, event.y)
self.dragging(event)
def drag_start(self, event):
if self.component:
self.original_padding = self.component.padding
if hasattr(event, "bid"... |
jacobdein/nacoustik | nacoustik/plot/__init__.py | Python | mit | 19 | 0.052632 | f | rom .plot import | * |
ctownsen357/Dockerfiles | apache-drill/tst_turbo.py | Python | mit | 408 | 0.007353 | from turbodbc import connect, make_ | options, Megabytes
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
options = make_options(read_buffer_size=Megabytes(20),
autocommit=True)
conn = connect(dsn='drill', turbodbc_options=options)
sql = "select * from dfs.`/test.csv`"
cursor = con | n.cursor()
cursor.execute(sql)
table = cursor.fetchallarrow()
data = table.to_pandas()
print(data)
|
QualiSystems/AWS-Shell | package/cloudshell/cp/aws/domain/services/waiters/subnet.py | Python | isc | 1,404 | 0.000712 | import time
from cloudshell.cp.aws.common import retry_helper
class SubnetWaiter(object):
PENDING = 'pending'
AVAILABLE = 'available'
INSTANCE_STATES = [PENDING,
AVAILABLE]
def __init__(self, delay=10, timeout=10):
"""
:param delay: the time in seconds between ... | self.timeout = timeout * 60
def wait(self, subnet, state, load=False):
"""
Will sync wait for the change of state of the subnet
| :param subnet:
:param state:
:param load:
:return:
"""
if not subnet:
raise ValueError('Instance cannot be null')
if state not in self.INSTANCE_STATES:
raise ValueError('Unsupported instance state')
retry_helper.do_with_retry(lambda: ... |
nikhs/slack-analytics | slackwrapper.py | Python | mit | 10,543 | 0.054539 | import urllib
import requests
class Config(object):
""" Config object for Slack """
API_PATHS = { "auth.test" : "auth.test",
"oauth.access" : "oauth.access",
# CHANNELS
"channels.archive" : "channels.archive",
"channels.create" : "channels.create",
"channels.history" : "channels... | chive"],
"groups:history" : ["groups.history"],
"groups:read" : ["groups.info","groups.list"],
"im:write" : ["im.close", "im.mark", "im.open"],
"im:history" : ["im | .history"],
"im:read" : ["im.list"],
"mpim:write" : ["mpim.close", "mpim.mark", "mpim.open"],
"mpim:history" : ["mpim.history"],
"mpim:read" : ["mpim.list"],
"pins:write" : ["pins.add","pins.remove"],
"pins:read" : ["pins.list"],
"reactions:write" : ["reactions.add","r... |
SlamJam/asq | asq/selectors.py | Python | mit | 4,595 | 0.000871 | '''Selector functions and selector function factories.'''
import operator
from asq._portability import is_callable
from asq._types import is_string
from asq.initiators import query
__author__ = 'Robert Smallshire'
k_ = operator.itemgetter
'''Create a selector function which indexes into the element by key.... | ssed to the
called method.
Returns:
A unary selector function which calls the named method with any
optional positional or named arguments and which returns the
result of the method call.
'''
k_ = operator.itemgetter
'''Create a selector function which indexes into the element by key.
... | __getitem__() method. If multiple items
are specified a tuple of looked-up values will be returned.
Args:
key: The key which the generated selector will use to index into
elements.
*args: Optional additional arguments which will be used as additional keys
for lookup. If supplied then ... |
nacl-webkit/native_client | src/trusted/validator_arm/generate_decoder.py | Python | bsd-3-clause | 7,502 | 0.006265 | #!/usr/bin/python
#
# Copyright 2012 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
#
"""Decoder Generator script.
Usage: generate-decoder.py <table-file> <o | utput-cc-file> <decoder-name> \
<options>
Options include:
--add_rule_patterns=bool - If bool='True', rule patterns are added (default).
If =bool is omitted, 'True' is assumped. Legal values for bool is
'True' and 'False'.
--table_remov | e=name - Remove table 'name' from decoder. May be repeated.
--auto-actual=name - Install automatically generated actuals into the
decoder table with the given name. May be repeated.
--auto-actual-sep=name - Use as separator to split up automatically
generated actual classes.
--auto-baseline-sep=na... |
arxiv-vanity/arxiv-vanity | arxiv_vanity/papers/templatetags/papers.py | Python | apache-2.0 | 1,851 | 0.00108 | from django import template
import randomcolor
register = template.Library()
CATEGORY_NAMES = {
'cs.AI': 'Artificial Intelligence',
'cs.CL': 'Computation and Language',
'cs.CC': 'Computational Complexity',
'cs.CE': 'Computational Engineering',
'cs.CG': 'Computational Geometry',
'cs.GT': 'Game ... | cs.DS': 'Data Structures and Algorithms',
'cs.DB': 'Databases',
'cs.DL': 'Digital Libraries',
'cs.DM': 'Discrete Mathematics',
'cs.DC': 'Distributed Computing',
'cs.ET': 'Emerging Technologies',
'cs.FL': 'Formal Languages',
'cs.GL': 'General Literature',
'cs.GR': 'Graphics',
'cs.AR':... | Interaction',
'cs.IR': 'Information Retrieval',
'cs.IT': 'Information Theory',
'cs.LG': 'Learning',
'cs.LO': 'Logic',
'cs.MS': 'Mathematical Software',
'cs.MA': 'Multiagent Systems',
'cs.MM': 'Multimedia',
'cs.NI': 'Networking and Internet',
'cs.NE': 'Neural and Evolutionary Computi... |
roscopecoltran/scraper | shared/docker/templates/deepdetect/demo/imgsearch/imgsearch.py | Python | mit | 3,645 | 0.018656 | import os, sys, argparse
from os import listdir
from os.path import isfile, join
from os import walk
from dd_client import DD
from annoy import AnnoyIndex
import shelve
import cv2
parser = argparse.ArgumentParser()
parser.add_argument("--index",help="repository of images to be indexed")
parser.add_argument("--index-ba... | x(layer_size,metric) # prepare index
t.add_item(c,p['vals'])
s[str(c)] = p['uri']
c = c + 1
#if c >= 10000:
# break
print 'building index...\n'
print 'layer_size=',layer_size
t.build(ntrees)
t.save('index.ann')
s.close()
if args.search:
s =... | _predict(sname,data,parameters_input,parameters_mllib,parameters_output)
near = u.get_nns_by_vector(classif['body']['predictions'][0]['vals'],args.search_size,include_distances=True)
print near
near_names = []
for n in near[0]:
near_names.append(s[str(n)])
print near_names
cv2.imshow('qu... |
Enlik/entropy | rigo/rigo_app.py | Python | gpl-2.0 | 38,116 | 0.0016 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright (C) 2012 Fabio Erculiani
Authors:
Fabio Erculiani
This program 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; version 3.
This program is distributed in... | igo_app
self._service = rigo_service
def onDeleteWindow(self, window, event):
# if UI is locked, do not allow to close Rigo
if self._app.is_ui_locked() or \
self._service.local_activity() != LocalActivityStates.READY:
rc = self._app._show_... | ure?")))
if rc == Gtk.ResponseType.NO:
return True
while True:
try:
entropy.tools.kill_threads()
Gtk.main_quit((window, event))
except KeyboardInterrupt:
continue
... |
nave91/dbt | dbt/node_types.py | Python | apache-2.0 | 686 | 0 |
class NodeType(object):
Base = 'base'
Model = 'model'
Analysis = 'analysis'
Test = 'te | st'
Archive = 'archive'
Macro = 'macro'
Operation = 'operation'
Seed = 'seed'
Documentation = 'documentation'
@classmethod
def executable(cls):
return [
cls.Model,
cls.Test,
cls.Archive,
| cls.Analysis,
cls.Operation,
cls.Seed,
cls.Documentation,
]
@classmethod
def refable(cls):
return [
cls.Model,
cls.Seed,
]
class RunHookType:
Start = 'on-run-start'
End = 'on-run-end'
Both = [Start, End... |
rsbrisci/Math455RandomWalkProject | Python Solution v1.0/SimulateP2PNetwork.py | Python | mit | 9,332 | 0.004393 | # Author:
# Ross Sbriscia, April 2016
import random
import sys
import traceback
import os
import math
import argparse
import time
import random_connected_graph
# Parses Arguments
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description='Simulat... | Ratio = | math.ceil(numberOfTrails * 2 / 100)
# sys.stdout.write("[%s]" % (" " * 50))
# sys.stdout.flush()
# sys.stdout.write("\b" * (50 + 1)) # return to start of line, after '['
# Run the expirement
outputCSV = open(outfileName, 'w')
sys.stdout.write("\033[92m0\033[0m")
for currentTrial in range(numberOfTrails):
network ... |
askdaddy/PerfKitBenchmarker | perfkitbenchmarker/packages/ycsb.py | Python | apache-2.0 | 27,030 | 0.006548 | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | stage only. Comma-separated list')
flags.DEFINE_list('ycsb_load_parameters', [],
'Passed to YCSB during the load stage. Comma-separated list '
'of "key=value" pairs.')
flags.DEFINE_list('ycsb_run_parameters', [],
'Passed to YCSB during the load stage. Comma-separate... | FINE_list('ycsb_threads_per_client', ['32'], 'Number of threads per '
'loader during the benchmark run. Specify a list to vary the '
'number of clients.')
flags.DEFINE_integer('ycsb_preload_threads', 1, 'Number of threads per '
'loader during the initial data pop... |
djw8605/htcondor | src/condor_contrib/mgmt/qmf/test/jobcontrol.py | Python | apache-2.0 | 1,434 | 0.01325 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2009-2011 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | oker or scheduler"
exit(1)
result = schedulers[0]._invoke(cmdarg,[jobid,"test"],[None])
if result.status:
print "error invoking: ", cmdarg
print result.text
session.delBroker(broker)
exit(1)
session.delBroker | (broker)
|
MicroPyramid/Django-CRM | opportunity/swagger_params.py | Python | mit | 2,381 | 0.00252 | from drf_yasg import openapi
organization_params_in_header = openapi.Parameter(
"org", openapi.IN_HEADER, required=True, type=openapi.TYPE_INTEGER
)
organization_params = [
organization_params_in_header,
]
opportunity_list_get_params = [
organization_params_in_header,
openapi.Parameter("name", openap... | enapi.Parameter("currency", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter("stage", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter("lead_source", openapi.IN_QUERY, type=openapi.TYPE_STRING),
| openapi.Parameter("probability", openapi.IN_QUERY, type=openapi.TYPE_INTEGER),
openapi.Parameter("teams", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter("assigned_to", openapi.IN_QUERY, type=openapi.TYPE_STRING),
openapi.Parameter("contacts", openapi.IN_QUERY, type=openapi.TYPE_STRING),
... |
SheffieldML/GPy | GPy/kern/src/prod.py | Python | bsd-3-clause | 8,449 | 0.013848 | # Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from .kern import CombinationKernel
from paramz.caching import Cache_this
import itertools
from functools import reduce
def numpy_invalid_op_as_exception(func):
"""
A decorator ... | art)
_newkerns.append(part.copy())
else:
| _newkerns.append(kern.copy())
super(Prod, self).__init__(_newkerns, name)
def to_dict(self):
"""
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary contain... |
BNBLORD/bookingsynclord | bookingsynclord/entities/Attachment.py | Python | gpl-3.0 | 334 | 0.002994 | from Entity import Entity
class Attachment(Entity):
ENTITY_TYPE = "attachments"
"""Represent an Inbox Attachment element.
Documentation : http://developers.bookingsync.com/reference/endpoints/inbox_attachments/
"""
def __init__(self, id=None):
return super(Attachment, self).__ini | t__("attachments", | id)
|
theirc/ServiceInfo | services/migrations/0008_auto_20150702_1445.py | Python | bsd-3-clause | 776 | 0.001289 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations | .Migration):
dependencies = [
('services', '0007_load_geo'),
]
operations = [
migrations.AlterField(
model_name='feedback',
name='staff_satisfaction',
field=models.SmallInteg | erField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(5)], help_text='How would you rate your satisfaction with the staff of the organization that provided services to you, (from 1 to 5, where 5 is the highest rating possible)?', blank=True, null=True, default=None),
... |
jfsantos/neon | conftest.py | Python | apache-2.0 | 3,983 | 0.00226 | # ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# | Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance | with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or i... |
nash-x/hws | cinder/api/extensions.py | Python | apache-2.0 | 13,552 | 0 | # Copyright 2011 OpenStack Foundation
# Copyright 2011 Justin Santa Barbara
# 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/l... | a base nsmap
nsmap = ext_nsmap.copy()
# Add the namespace for the extension
nsmap[cls.alias] = cls.namespace
return nsmap
@cla | ssmethod
def xmlname(cls, name):
"""Synthesize element and attribute names."""
return '{%s}%s' % (cls.namespace, name)
def make_ext(elem):
elem.set('name')
elem.set('namespace')
elem.set('alias')
elem.set('updated')
desc = xmlutil.SubTemplateElement(elem, 'description')
d... |
ARM-software/trappy | tests/test_duplicates.py | Python | apache-2.0 | 4,015 | 0.00523 | # Copyright 2015-2017 ARM 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 w... | 0.018624: sched_load_avg_sg: cpus=00000002 load=1 utilization=4
rcuos/2-22 [001] 6550.018625: sched_load_avg_sg: cpus=00000002 load=2 utilization=5
rcuos/2-22 [001] 6550.018626: sched_load_avg_sg: cpus=00000002 load=3 utilization=6
rcuos/2-22 [001] 6550.018627: sched_ | load_avg_sg: cpus=00000002 load=1 utilization=7
rcuos/2-22 [001] 6550.018628: sched_load_avg_sg: cpus=00000004 load=2 utilization=8\n""")
fout.close()
trace1 = trappy.FTrace(name="first")
l = trappy.LinePlot(
trace1,
trappy.sched.SchedLoadAvgSchedGroup,
... |
manateelazycat/deepin-software-center | src/searchView.py | Python | gpl-3.0 | 9,264 | 0.006261 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2011 Deepin, Inc.
# 2011 Wang Yong
#
# Author: Wang Yong <lazycat.manatee@gma | il.com>
# Maintainer: Wang Yong <lazycat.manatee@gmail.com>
#
# This program 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
# any later version.
#
# This program is distr... | T ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from appItem... |
bhrutledge/debugged-django | debugged/admin/__init__.py | Python | mit | 529 | 0.007561 | from django.contrib import admin
from django.contrib.contenttypes import generic
class LinkedStackedInline(admin.StackedInline):
template = 'admin/edit_inline/stacked_linked.html'
clas | s LinkedTabularInline(admin.TabularInline):
template = 'admin/edit_inline/tabular_linked.html'
class GenericLinkedStackedInline(generic.GenericStackedInline):
template = 'admin/edit_inline/stacked_linked.ht | ml'
class GenericLinkedTabularInline(generic.GenericTabularInline):
template = 'admin/edit_inline/tabular_linked.html'
|
eroicaleo/LearningPython | ch20/ScrambledSequence.py | Python | mit | 768 | 0.010417 | #!/usr/bin/python3.3
L, S = [1, 2, 3], 'spam'
for i in range(len(S)):
S = S[1:] + S[:1]
print(S)
# simple function
def scramble(seq):
res = []
for i in range(len(seq)):
res.append(seq[i:] + seq[:i])
r | eturn res
print(scramble('spam'))
print(scramble(L))
# generator function
def scramble(seq):
for i in range(len(seq)):
yield seq[i:] + seq[:i]
for x in scramble('spam'):
print(x)
for x in scramble(L):
print(x)
print(list(scramble('spam')))
print(list(scramble(L)))
# generator expression
... | ] for i in range(len(seq)))
print(list(F('spam')))
print(list(F(L)))
for x in F(L):
print(x, end=' ')
print()
|
twneale/vertica-python | vertica_python/tests/basic_tests.py | Python | mit | 12,619 | 0.005864 | import unittest
import logging
import tempfile
from .test_commons import conn_info
import vertica_python
from vertica_python import errors
logger = logging.getLogger('vertica')
def init_table(cur):
# clean old table
cur.execute('DROP TABLE IF EXISTS vertica_python_unit_test;')
# create test table
... | cute("SELECT a, b from vertica_python_unit_test WHERE a = 1")
r | es = cur.fetchall()
assert 1 == len(res)
def test_iterator(self):
with vertica_python.connect(**conn_info) as conn:
cur = conn.cursor()
init_table(cur)
cur.execute(""" INSERT INTO vertica_python_unit_test (a, b) VALUES (1, 'aa') """)
cur... |
kamyu104/LeetCode | Python/employee-free-time.py | Python | mit | 2,095 | 0.002387 | # Time: O(m * logn), m is the number of schedule, n is the number of employees, m >= n
# Space: O(n)
# We are given a list schedule of employees, which represents the working time for each employee.
# Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
# Return the list of ... | apq
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
class Solution(object):
def employeeFreeTime(self, schedule):
"""
:type s | chedule: List[List[Interval]]
:rtype: List[Interval]
"""
result = []
min_heap = [(emp[0].start, eid, 0) for eid, emp in enumerate(schedule)]
heapq.heapify(min_heap)
last_end = -1
while min_heap:
t, eid, i = heapq.heappop(min_heap)
if 0 <= l... |
python-cmd2/cmd2 | examples/read_input.py | Python | mit | 4,590 | 0.002397 | #!/usr/bin/env python
# coding=utf-8
"""
A simple example demonstrating the various ways to call cmd2.Cmd.read_input() for input history and tab completion
"""
from typing import (
List,
)
import cmd2
EXAMPLE_COMMANDS = "Example Commands"
class ReadInputApp(cmd2.Cmd):
def __init__(self, *args, **kwargs) -> ... | EOFError:
pass
@cmd2.with_category(EXAMPLE_COMMANDS)
def do_custom_choices(self, _) -> None:
"""Call read_input to use custom history and choices"""
self.poutput("Tab completing with static choices list and using custom history")
try:
input_str = self.read_input... | history=self.custom_history,
completion_mode=cmd2.CompletionMode.CUSTOM,
choices=['choice_1', 'choice_2', 'choice_3'],
)
except EOFError:
pass
else:
self.custom_history.append(input_str)
# noinspection PyMethodMayBeS... |
lud4ik/txAWS | txaws/server/tests/fixtures/importerror/amodule.py | Python | mit | 131 | 0 | from txaws.ser | ver.method import Method
from tx | aws.server.tests.fixtures import method
@method
class TestMethod(Method):
pass
|
flz/portbuild-ng | bin/qmanager-agent.py | Python | bsd-2-clause | 3,560 | 0.009551 | #! /usr/bin/env python
import signal
import pickle
import platform
import socket
import time
from pika import BasicProperties
import portbuild.qthreads as qthreads
import portbuild.torrent as torrent
import portbuild.util as util
ready = []
class AgentProducer(qthreads.QueueProducerThread):
def __init__(self):
... | queue,
mandatory=True,
immediate=True,
body=pickle.dumps(message),
properties=props)
def notif | y_return(self, method, header, body):
"""Notification was returned. Head node isn't listening anymore."""
# This actually is only triggered when the exchange doesn't exists,
# not when the queue doesn't exist.
print "Message returned!"
class AgentConsumer(qthreads.QueueConsumerThread):
def __init__(... |
JonnyWong16/plexpy | lib/dns/resolver.py | Python | gpl-3.0 | 57,421 | 0.000192 | # Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
# Copyright (C) 2003-2017 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permis... | s.name.Name`` to a
``dns.message.Message``.
"""
return self.kwargs['responses']
def response(self, qname):
"""The response for query *qname*.
Returns a ``dns.message.Message``.
"""
return self.kwargs['responses'][qnam | e]
class YXDOMAIN(dns.exception.DNSException):
"""The DNS query name is too long after DNAME substitution."""
# The definition of the Timeout exception has moved from here to the
# dns.exception module. We keep dns.resolver.Timeout defined for
# backwards compatibility.
Timeout = dns.exception.Timeout
class ... |
DStauffman/dstauffman2 | setup.py | Python | lgpl-3.0 | 1,638 | 0.005495 | r"""
Packaging setup file for Pypi and installation via pip.
Notes
-----
#. Written by David C. Stauffer in January 2019.
"""
#%% Import
import os
from setuptools import setup
#%% Support functions - readme
def readme():
r"""Opens the README.rst file for additional descriptions."""
filename = os.path.join(... | or('Unable to load version information.')
#%% Setup
setup(
name='dstauffman2',
version=get_version(),
description='Vaguely useful Python utilities, plus a playground for games and miscelllaneous code.',
long_description=readme(),
keywords='dstauffman dstauffman2 games playground spyder configuratio... | ',
author='David C. Stauffer',
author_email='dstauffman@yahoo.com',
license='LGPLv3',
packages=['dstauffman2'],
package_data={'dstauffman2': ['py.typed']},
install_requires=[
'h5py',
'matplotlib',
'numpy',
'pandas',
'PyQt5',
'pytest',
'scip... |
jfitz/hours-reporter | parse_datetime.py | Python | mit | 2,257 | 0.008418 |
"""
Simple robust time and date parsing.
Note: Follows the Australian standard, dd/mm/yyyy.
Americans should replace '%d %m %Y' with '%m %d %Y' and '%d %m %y' with '%m %d %y' below.
Routines will either
- return a date or time
- return None if the string is empty
- throw ... | rmats_with_year = ['%m %d %Y', '%Y %m %d', '%d %B %Y', '%B %d %Y',
'%d %b %Y', '%b %d %Y',
'%m %d %y', '%y %m %d', '%d %B %y', '%B %d %y',
'%d %b %y', '%b %d %y']
date_formats_without_year = ['... | ):
string = string.strip()
if not string: return None
for format in time_formats:
try:
result = time.strptime(string, format)
return datetime.time(result.tm_hour, result.tm_min)
except ValueError:
pass
raise ValueError()
def par... |
colab/colab-superarchives-plugin | src/colab_superarchives/__init__.py | Python | gpl-3.0 | 70 | 0 |
default_app_co | nfig = 'colab_superarch | ives.apps.SuperArchivesConfig'
|
evandromr/stingray | stingray/simulator/base.py | Python | mit | 2,875 | 0 | from __future__ import division, print_function
import numpy as np
import numpy.random as ra
import scipy.interpolate as sci
from ..utils import assign_value_if_none
def simulate_times(lc, use_spline=False, bin_time=None):
"""
Assign (simulate) photon arrival times to event list, using the
acceptance-reje... | nts_predict / n_bin
if use_spline:
max_bin = np.long(np.max([4, 1000000 / events_per_bin_predict]))
else:
max_bin = np.long(np.max([4, 5000000 / events_per_bin_predict]))
ev_list = np.zeros(n_events_predict)
nev = 0
while bin_start < n_bin:
t0 = times[bin_start]
... | start + max_bin, n_bin + 1])
lc_filt = counts[bin_start:bin_stop]
t_filt = times[bin_start:bin_stop]
length = t_filt[-1] - t_filt[0]
n_bin_filt = len(lc_filt)
n_to_simulate = n_bin_filt * np.max(lc_filt)
safety_factor = 10
if n_to_simulate > 10000:
... |
hackaugusto/raiden | raiden/tests/utils/smartcontracts.py | Python | mit | 4,965 | 0.001611 | import os
from typing import List, Tuple
from raiden.network.blockchain_service import BlockChainService
from raiden.network.pathfinding import get_random_service
from raiden.network.proxies.service_registry import ServiceRegistry
from raiden.network.rpc.client import JSONRPCClient
from raiden.network.rpc.smartcontrac... | ntract_proxy(
contract_interface=contract_abi, contract_address=token_address
)
def deploy_tokens_and_fund_accounts(
token_amount: int,
number_of_tokens: int,
deploy_service: BlockChainService,
participants: typing.List[typing.Address],
contract_manager: ContractManager,
) -> typing.Li... | n_amount` minted and
distributed among `blockchain_services`. Optionally the instances will be registered with
the raiden registry.
Args:
token_amount (int): number of units that will be created per token
number_of_tokens (int): number of token instances that will be created
deploy_... |
doconix/django-mako-plus | django_mako_plus/http.py | Python | apache-2.0 | 2,608 | 0.005368 | from django.http import HttpResponse
# this redirect key is (hopefully) unique but generic so it doesn't signpost the use of DMP/Django.
# not prefixing with X- because that's now deprecated.
REDIRECT_HEADER_KEY = 'Redirect-Location'
###############################################################################
###... | edirect_to=None, *args, **kwargs):
# set up the code
if redirect_to:
script = 'window.location.assign("{}");'.format(redirect_to.split('#')[0])
| else:
script = 'window.location.assign(window.location.href.split("#")[0])'
# do we need to add the <script> tag? (that's the default)
if kwargs.pop('include_script_tag', True):
script = '<script>{}</script>'.format(script)
# call the super
super().__init_... |
fzimmermann89/pyload | module/plugins/hoster/MegavideoCom.py | Python | gpl-3.0 | 596 | 0.011745 | # -*- coding: utf-8 -*-
from module.plugins.internal.DeadHoster import DeadHoster, create_getInfo
class MegavideoCom(D | eadHoster):
__name__ = "MegavideoCom"
__type__ = "hoster"
__version__ = "0.23"
__status__ = "stable"
__pattern__ = r'http://(?:www\.)?megavideo\.com/\?.*&?(d|v)=\w+'
__config__ = [] #@TODO: Remove in 0.4.10
__description__ = """Megavideo.com hoster plugin"""
__license__ = ... | aay.de")]
getInfo = create_getInfo(MegavideoCom)
|
googkit/googkit | test/commands/test_update_deps.py | Python | mit | 4,284 | 0.001401 | import unittest
import os
import subprocess
from test.stub_conf | ig import StubConfig, StubConfigOnStubProject
from test.stub_environment import StubEnvironment
from test.stub_stdout import StubStdout
from googkit.commands.update_deps im | port UpdateDepsCommand
from googkit.compat.unittest import mock
class TestUpdateDepsCommand(unittest.TestCase):
def setUp(self):
self.env = StubEnvironment()
self.cmd = UpdateDepsCommand(self.env)
self.cmd.config = StubConfig()
def test_needs_project_config(self):
self.assertT... |
stuti-rastogi/leetcodesolutions | 215_kthLargestElement.py | Python | apache-2.0 | 228 | 0.004386 | c | lass Solution:
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
return sorted(nums)[-k]
# return heapq.nlargest(k, | nums)[k-1] |
fusor/fusor_ovirt | bin/ovirt_create_vm_from_template.py | Python | gpl-2.0 | 3,526 | 0.001985 | #! /usr/bin/env python
import logging
import sys
from optparse import OptionParser
try:
from ovirtsdk.api import API
from ovirtsdk.xml import params
except:
print "Please re-run after you have installed 'ovirt-engine-sdk-python'"
print "Example: easy_install ovirt-engine-sdk-python"
sys.exit()
D... | _option('--vm_template_name', default=None,
help='VM template name to create VM from')
parser.add_option('--cluster_name', default=None,
help='Cluster name to create VM in')
parser.add_opt | ion('--vm_name', default=None, help='VM name to be created')
(opts, args) = parser.parse_args()
for optname in ["api_host", "api_pass", "api_user",
"vm_template_name", "cluster_name", "vm_name"]:
optvalue = getattr(opts, optname)
if not optvalue:
parser.print_he... |
kaedroho/wagtail | wagtail/tests/search/migrations/0001_initial.py | Python | bsd-3-clause | 3,247 | 0.00308 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-10-18 12:59
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
import wagtail.search.index
class Migration(migrations.Migration):
initial = True
dependencies = [
('taggit', '0002_auto_20150616_... | models.ManyToManyField(related_name='books', to='searchtests.Author'),
),
migrations.AddField(
model_name='book',
name='tags',
field=taggit.managers.TaggableManager(help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name... | ngo.db.models.deletion.CASCADE, related_name='characters', to='searchtests.Novel'),
),
]
|
acrsilva/animated-zZz-machine | pruebas/matplotlib_pie.py | Python | lgpl-3.0 | 4,541 | 0.003744 | prueba = 5
if(prueba==2):
"""
Demo of a basic pie chart plus a few additional features.
In addition to the basic pie chart, this demo shows a few optional features:
* slice labels
* auto-labeling the percentage
* offsetting a slice with "explode"
* drop-shadow
* c... | pie is drawn as a circle.
ax.set_aspect('equal')
plt.show()
elif(prueba == 2):
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'mediumpurple', 'lightskyblue', 'lightcoral']
explode = (0, 0, 0, 0) # proportion with which to offset each wedge
... | array of colours
autopct='%1.1f%%', # print the values inside the wedges
shadow=True, # enable shadow
startangle=70 # starting angle
)
plt.axis('equal')
plt.show()
elif(prueba==3):
# Data to plot
labels = ['Python', 'C... |
ilmir-k/website-addons | website_sales_team/__init__.py | Python | lgpl-3.0 | 90 | 0 | # -*- coding: utf-8 -*-
fro | m . import website_sales_team_models
from . import control | lers
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.