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 |
|---|---|---|---|---|---|---|---|---|
opennode/nodeconductor-assembly-waldur | src/waldur_slurm/tests/fixtures.py | Python | mit | 591 | 0 | from django.utils.functional import cached_property
from waldur_core.structure. | tests.fixtures import ProjectFixture
from . import factories
class SlurmFixture(ProjectFixture):
@cached_property
def settings(self):
return factories.SlurmSe | rviceSettingsFactory(customer=self.customer)
@cached_property
def allocation(self):
return factories.AllocationFactory(
service_settings=self.settings, project=self.project,
)
@cached_property
def association(self):
return factories.AssociationFactory(allocation=sel... |
curiousdannii/parchment-proxy | mirror.py | Python | bsd-3-clause | 1,540 | 0.021429 | # Parchment-proxy - A proxy for fetching web data for Parchment
# Copyright 2008-2012 The Parchment-proxy contributors (see CONTRIBUTORS)
# Released under a BSD-like licence, see LICENCE
# mirror.py: File download/retrieval functions
# Will eventually form a mirror of the IF Archive
import logging
from google.appeng... | # raise ProxyError('url does not contain a story file')
# All good... | cache it and return (don't cache big files for now)
if len(data) <= MAX_FILE_SIZE:
if not memcache.add(url, data, 3600):
logging.error('Memcache set failed for url ' + url)
return data
|
apache/aurora | src/main/python/apache/aurora/client/cli/cron.py | Python | apache-2.0 | 5,179 | 0.009847 | #
# 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 ... | ig.raw().has_cron_schedule():
raise context.CommandError(
EXIT_COMMAND_FAILURE,
"Non-cron jobs may only be created with \"aurora job create\" command | ")
resp = api.schedule_cron(config)
context.log_response_and_raise(resp,
err_msg=("Error scheduling cron job %s:" % context.options.jobspec))
context.print_out("Cron job scheduled, status can be viewed at %s"
% get_job_page(api, context.options.jobspec))
return EXIT_OK
class Desched... |
chrisspen/burlap | burlap/system.py | Python | mit | 7,377 | 0.000542 | """
System settings
===============
"""
from __future__ import print_function
from fabric.api import hide, run, settings
from burlap.files import file # pylint: disable=redefined-builtin
from burlap.utils import read_lines, run_as_root
from burlap.constants import *
is_file = file.is_file
class UnsupportedFamily(Ex... | bit Intel/AMD system")
"""
with settings(hide('running', 'stdout')):
arch = run('uname -m')
return arch
def cpus():
"""
Get the number of CPU cores.
Example::
from burlap.system import cpus
nb_workers = | 2 * cpus() + 1
"""
with settings(hide('running', 'stdout')):
res = run('python -c "import multiprocessing; '
'print(multiprocessing.cpu_count())"')
return int(res)
def using_systemd():
"""
Return True if using systemd
Example::
from burlap.system impor... |
ctrlaltdel/neutrinator | vendor/openstack/tests/functional/cloud/test_volume_backup.py | Python | gpl-3.0 | 3,281 | 0 | # 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 t... | escription'])
self.user_cloud.delete_volume_backup(backup['id'], wait=True)
self.assertIsNone(self.user_cloud.get_volume_backup(backup['id']))
def test_list_volume_backups(self):
vol1 = self.user_cloud.create_volume(
display_name=self.getUniqueString(), size=1)
self.add... | # We create 2 volumes to create 2 backups. We could have created 2
# backups from the same volume but taking 2 successive backups seems
# to be race-condition prone. And I didn't want to use an ugly sleep()
# here.
vol2 = self.user_cloud.create_volume(
display_name=se... |
beeftornado/sentry | src/sentry/web/frontend/pipeline_advancer.py | Python | bsd-3-clause | 1,944 | 0.002058 | from __future__ import absolute_import, print_function
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.utils.translation import ugettext_lazy as _
from sentry.identity.pipeline import IdentityProviderPipeline
from sentry.integrations.pipeline import IntegrationPipeline
fro... | ineAdvancerView")
def handle(self, request, provider_id):
pipeline = None
for pipeline_cls in PIPELINE_CLASSES:
pipeline = pipeline_cls.get_for_request(request=request)
if pipeline:
break
if (
provider_id in FORWARD_INSTALL_FOR
... | and pipeline is None
):
installation_id = request.GET.get("installation_id")
return self.redirect(
reverse("integration-installation", args=[provider_id, installation_id])
)
if pipeline is None or not pipeline.is_valid():
messages.a... |
diegomvh/pyqt | widgets/locator/__init__.py | Python | mit | 87 | 0.011494 | #!/usr/bin/en | v pytho | n
from .base import LocatorWidget
from .command import OpenCommand |
david-caro/chrooter | chrooter/cmd.py | Python | gpl-3.0 | 2,048 | 0 | #!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
import logging
from stevedore import extension
def load_providers():
logging.debug('Loading distro provider extensions')
mgr = extension.ExtensionManager(
namespace='chrooter.provider',
)
distros =... | return distros
def get_parser(providers):
parser = ArgumentParser()
subparsers = parser.add_subparsers(
title='distro',
description='Distribution to create the chroot for',
dest='distro',
)
for provider_name, provider in providers.items():
subparser = subparsers.add_pa... | ser(provider_name)
provider.populate_parser(subparser)
if not providers:
raise Exception('Unable to load any distro providers')
return parser
def main():
logging.basicConfig(level=logging.INFO)
providers = load_providers()
parser = get_parser(providers)
parser.add_argument(
... |
rasros/CloudTranscoderLTH2 | readlog.py | Python | apache-2.0 | 723 | 0.034578 | #!/usr/bin/env python
import os
import sys
import etcd
import subprocess
import signal
import time
if len(sys.argv) < 2:
print("Please provide a server argument")
sys.exit(1)
def siginthandler(signum, stackframe):
sys.exit(-1)
signal.signal(signal.SIGINT, siginthandler)
logpat | h="/log"
if len(sys.argv) > 2:
logpath=sys.argv[2]
while True:
try:
idx = 0
time.sleep(1)
p = 2379
print("Connect to {}:{}".format(sys.argv[1], p))
keyval = etcd.Client(host=sys | .argv[1], port=p)
while keyval:
res = keyval.watch(logpath, index=idx, recursive=True)
for e in res.leaves:
if e.key == logpath:
idx = 0
break
print(e.value)
idx = e.createdIndex+1
except Exception as e:
print(e)
|
fdr/heroku-wal-e | wal_e/pipeline.py | Python | bsd-3-clause | 4,389 | 0.001823 | """ Primitives to manage and construct pipelines for compression/encryption. """
from gevent import sleep
from wal_e.exception import UserCritical
from wal_e.piper import popen_sp, NonBlockPipeFileWrap, PIPE
PV_BIN = 'pv'
GPG_BIN = 'gpg'
LZOP_BIN = 'lzop'
# BUFSIZE_HT: Buffer Size, High Throughput
#
# This is set co... | self.commands = commands
@property
def stdin(self):
return NonBlockPipeFileWrap(self.commands[0].stdin)
@property
def stdout(self):
return NonBlockPipeFileWrap(self.commands[-1].stdout)
def finish(self):
[command.finish() for command in self.commands]
class Pipel... | n and stdout are *blocking* because you
want them to be if you're piping them to another command.
(If you need a gevent-compatible stdin/out, wrap it in NonBlockPipeFileWrap.)
"""
def __init__(self, stdin=PIPE, stdout=PIPE):
pass
def start(self, command, stdin, stdout):
sel... |
thiagolcmelo/segregation | segregation/muraki/migrations/0001_initial.py | Python | mit | 3,708 | 0.007012 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Alloy',
fields=[
('id', models.AutoField(verbos... | e=b"Valence's hydrostatic deformation potential")),
('b', models.CharField(max_length=200, verbose_name=b'Deformation potential for tetragonal distorion')),
('c11', models.CharField(max_length=200, verbose_name=b'Elastic constant')),
('c12', models.CharField(max_length=20... | ('mhh', models.CharField(max_length=200, null=True, verbose_name=b'Heavy-hole effective mass')),
('mlh', models.CharField(max_length=200, null=True, verbose_name=b'Light-hole effective mass')),
('eg2', models.CharField(max_length=200, verbose_name=b'Gap energy at 2 K')),
... |
decodio/l10n_hr | l10n_hr_fiskal/fiskalizacija.py | Python | agpl-3.0 | 13,888 | 0.001513 | # -*- coding: utf-8 -*-
# Odoo, Open Source Management Solution
# Copyright (C) 2016 Decodio
# Copyright (C) 2012- Daj Mi 5 Davor Bojkić bole@dajmi5.com
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api, _
from openerp.exceptions import Warning as UserError
import ... | ):
fiskal_prostor_id = odoo_id
elif msg_type in ('racun', 'racun_ponovo', 'Rac | un'):
invoice_id = odoo_id
elif msg_type in ('mp_racun', 'mp_racun_ponovo', 'MP Racun'):
pos_order_id = odoo_id
stop_time = self._fiskal_time_formated()
t_obrada = stop_time['time_stamp'] - start_time['time_stamp']
time_obr='%s.%s s'%(t_obrada.seconds, t_obrada.m... |
jeremycline/pulp | nodes/extensions/admin/pulp_node/extensions/admin/commands.py | Python | gpl-2.0 | 20,361 | 0.002014 | import os
from gettext import gettext as _
from pulp.bindings.exceptions import NotFoundException
from pulp.client.arg_utils import convert_boolean_arguments
from pulp.client.extensions.decorator import priority
from pulp.client.extensions.extensions import PulpCliCommand, PulpCliOption
from pulp.client.commands.poll... | notes = con | sumer['notes']
if not notes.get(constants.NODE_NOTE_KEY):
continue
consumer[self.STRATEGY_FIELD] = \
notes.get(constants.STRATEGY_NOTE_KEY, constants.DEFAULT_STRATEGY)
nodes.append(consumer)
return nodes
def format_bindings(self, consumer)... |
AtsushiSakai/googleearthplot | googleearthplot/__init__.py | Python | mit | 74 | 0 | from googleearthplot import g | oogleearthplot
__all__ = ["googleearthplot"]
| |
wangtai/py_gif_processor | test.py | Python | apache-2.0 | 761 | 0.003942 | #!/usr/bin/env python
# -*- coding: utf-8 | -*-
# Last modified: Wang Tai (i@wangtai.me)
"""
"""
__revision__ = '0.1'
from unittest import TestCase
class simpleTest(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def testExample(self):
from gif_thumb import create_thumb
import os
for root, dirs... | t'):
for file_name in files:
path = os.path.join(root, file_name)
thumbnail_path = os.path.join(root, file_name + '.jpg')
create_thumb(path, thumbnail_path)
self.assertEqual(1, 1)
def testOther(self):
self.assertNotEqual(0, 1)
if '__main_... |
cmpgamer/Sprint1 | .~c9_invoke_HdX4pf.py | Python | mit | 5,328 | 0.01295 | import sys
reload(sys)
sys.setdefaultencoding("UTF8")
import os
import uuid
from flask import *
from flask.ext.socketio import SocketIO, emit
from flask_socketio import join_room, leave_room
import psycopg2
import psycopg2.extras
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
m... | archTerm = '%{0}%'.format(searchItem)
cur.execute(mosearchQuery, (searchTerm,));
cur.execute(movieSearchQuery, (searchTerm,));
results = cur.fetchall();
#print(results)
# for i in range(len(results)):
# resultsDict = {'text' : results[i]['content'], 'name' : results[i]['u... | searchResults', queryResults)
cur.close()
db.close()
# @app.route('/chat')
# def chat():
# if 'username' in session:
# return render_template('chat.html') # chat.html
# else:
# return render_template('index.html')
#TODO make new search functions displaying queries
@app.route('/'... |
keflavich/pyradex | pyradex/version.py | Python | bsd-3-clause | 25 | 0 | __version__ = "0.4 | .2dev" | |
osgcc/ryzom | nel/tools/build_gamedata/generators/simple_max_exporter_template/3_install.py | Python | agpl-3.0 | 1,874 | 0.00587 | #!/usr/bin/python
#
# \file 3_install.py
# \brief Install %PreGenProcessName%
# \date %PreGenDateTimeStamp%
# \author Jan Boon (Kaetemi)
# Python port of game data build pipeline.
# Install %PreGenProces | sName%
#
# NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
# Copyright (C) 2010 Winch Gate Property Limited
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version ... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import time, sys, os, shutil, subprocess, distuti... |
alekseysidorov/exonum | test-suite/exonum-py-tests/suite/crypto_advanced_client.py | Python | apache-2.0 | 3,816 | 0.002358 | """Module provides an interface to simplify interaction with cryptocurrency-advanced service."""
import random
from exonum_client import ModuleManager, ExonumClient, MessageGenerator
class ExonumCryptoAdvancedClient:
"""Class provides an interface to simplify interaction with cryptocurrency-advanced service."""
... | s_module.Hash(data=hash_address.value))
transfer_tx = self.msg_generator.create_message(transfer)
transfer_tx.sign(from_wallet)
return self.client.public_api.send_transaction(transfer_tx)
def gen_seed():
"""Method to generate seed"""
return random.getrandbits(64) | |
WSU-RoboticsClub/Tutorials | xbox_controller/xboxdrv/quadcopter_controller_example.py | Python | mit | 734 | 0.021798 | from xboxdrv_parser import Controller
from time import sleep
import os
def main ():
# Get input from the two analog sticks as yaw, throttle, roll, and pitch. Ta | ke the (0 - 255) input value and
# map it to a (-1 - 1) range.
controller = Co | ntroller (["X1", "Y1", "X2", "Y2", "L2", "R2", "X", "/\\", "[]"], ["yaw", "throttle", "roll", "pitch", "descend", "ascend", "takeover", "takeoff", "land"], (0, 255), (-1, 1))
#controller = Controller (["X1", "Y1", "X2", "Y2"])
while True:
control_packet = controller.get_values ()
os.system("clear")
f... |
shamilbi/loxodo | setup.py | Python | gpl-2.0 | 2,574 | 0.019814 | #!/usr/bin/env python
"""
py2app/py2exe build script for Loxodo.
Usage (Mac OS X):
python setup.py py2app
Usage (Windows):
python setup.py py2exe
"""
import sys
import re
from setuptools import setup
version_regex = r'__version__ = ["\']([^"\']*)["\']'
with open('loxodo/__init__.py', 'r') as f:
text = f... | packages = ['loxodo', 'wx'],
site_packages = True,
resources = ['resources', 'locale', 'LICENSE.txt', 'README.txt']
)
)
)
elif sys.platform == 'win32':
import py2exe
import os
# create list of needed data | files
dataFiles = []
for subdir in ('resources', 'locale'):
for root, dirs, files in os.walk(subdir):
if not files:
next
files = []
for filename in files:
files.append(os.path.join(root, filename))
if not files:
... |
Jorge-Rodriguez/ansible | lib/ansible/modules/cloud/google/gcp_spanner_database_facts.py | Python | gpl-3.0 | 4,857 | 0.004324 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
... | : name-of-resource` to a gcp_spanner_instance
task and then set this instance field to "{{ name-of-resource }}"'
required: true
extends_documentation_fragment: gcp
'''
EXAMPLES = ''' |
- name: a database facts
gcp_spanner_database_facts:
instance: "{{ instance }}"
project: test_project
auth_kind: serviceaccount
service_account_file: "/tmp/auth.pem"
'''
RETURN = '''
items:
description: List of items
returned: always
type: complex
contains:
name:
descripti... |
sherpaman/MolToolPy | bin/calc_transfer_info_traj_fluct.py | Python | gpl-2.0 | 2,175 | 0.037701 | #!/usr/bin/env python
import ts
import matplotlib.pyplot as plt
import numpy as np
import mdtraj as md
from argparse import ArgumentParser
parser = ArgumentParser( description = 'Calculate Mutual Information')
#
# INPUT FILES
#
parser.add_argument("-f","--traj",dest="traj",action="store",type=str,default=None,help="In... | .add_argument("-o","--out",dest="out",action="store",type=str,default=None,required=True,help="Output File Name",metavar="DAT FILE")
#
# VAR ARGUMENTS
#
parser.add_argument("-s","-- | stride",dest="stride",action="store",type=int,default=1,help="time", metavar="INTEGER")
#parser.add_argument("-d","--ndim",dest="ndim",action="store",type=int,default=1,help="nuber of dimensions", metavar="INTEGER")
parser.add_argument("-n","--nbins",dest="nbins",action="store",type=int ,default=10,help="number of bins... |
Bolt64/my_code | euler/non_bouncy_numbers.py | Python | mit | 1,200 | 0 | #!/usr/bin/env python3
from math import factorial
def memoize(func):
cache = {}
def inner(n, m):
if not (n, m) in cache:
cache[(n, m)] = func(n, m)
return cache[(n, m)]
return inner
@memoize
def choose(n, m):
if not (0 <= m <= n):
return 0
else:
ret... | tone_numbers(num_digits, max_choices):
count = 0
for num_choices in range(1, max_choices+1):
count += choose(max_choices, num_choices) *\
compute_positive_partitions(num_digits, num_choices)
return count
def compute_ascending_numbers(num_digits):
return proto_compute_monotone_... | e_non_bouncy(digit_threshold):
count = 0
for num_digits in range(1, digit_threshold + 1):
count += compute_ascending_numbers(num_digits)
count += compute_descending_numbers(num_digits)
return count - (9 * digit_threshold)
|
fs714/concurrency-example | protobuf_example/addressbook/addressbook.py | Python | apache-2.0 | 1,357 | 0 | from google.protobuf.timestamp_pb2 import Timestamp
from protobuf_example.addressbook.pb_addressbook import addressbook_pb2
if __name__ == '__main__':
ts = Timestamp()
ts.GetCurrentTime()
person1 = addressbook_pb2.Person()
person1.id = 1
person1.name = "Mikasa"
person | 1.email = "mikasa@gmail.com"
person1.last_updated.MergeFrom(ts)
phone11 = person1.phones.add()
phone11.number = "021-12345678"
phone11.type = addressbook_pb2.Person.HOME
phone12 = person1.phones.add()
phone12.number = "138888 | 88888"
phone12.type = addressbook_pb2.Person.MOBILE
person2 = addressbook_pb2.Person()
person2.id = 2
person2.name = "Historia"
person2.email = "historia@example.com"
person2.last_updated.MergeFrom(ts)
phone21 = person2.phones.add()
phone21.number = "021-88888888"
phone21.type = ad... |
GovCERT-CZ/dionaea | modules/python/scripts/smb/include/asn1/ber.py | Python | gpl-2.0 | 15,167 | 0.012989 | #*************************************************************************
#* Dionaea
#* - catches bugs -
#*
#*
#*
#* Copyright (C) 2010 Markus Koetter
#*
#* This program is free software; you can redistribute it and/or
#* modify it under the terms of the GNU Gen... | er')
logger.setLevel(logging.DEBUG)
BER_CLASS_UNI = 0
BER_CLASS_APP = 1
BER_CLASS_CON = 2
BER_CLASS_PRI = 3
BER_CLASS_ANY = 99
##################
## BER encoding ##
##################
#####[ BER tools ]#####
class BER_Exception(Exception):
pass
class BER_Enc | oding_Error(ASN1_Encoding_Error):
def __init__(self, msg, encoded=None, remaining=None):
Exception.__init__(self, msg)
self.remaining = remaining
self.encoded = encoded
def __str__(self):
s = Exception.__str__(self)
if isinstance(self.encoded, BERcodec_Object):
... |
tectronics/freeermind | src/gui/dialog.py | Python | gpl-3.0 | 3,910 | 0.006905 | """
This file is part of Freeermind.
Freeermind 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.
... | be useful,
but WITHOUT 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 Freeermind. If not, see <h... | ight Jasm Sison 2009
"""
from java.lang import System as sys_
from org.eclipse.swt.events import *
from org.eclipse.swt.graphics import *
from org.eclipse.swt.layout import *
from org.eclipse.swt.widgets import *
from org.eclipse.swt.custom import *
from org.eclipse.swt import SWT
# TODO
# - fix event handling of Te... |
vincentchevrier/dataquick | dataquick/plugins/visualizations/psd.py | Python | mit | 8,840 | 0.001244 | """Module for the Visualization of particle size distributions
Log plot"""
import os
import pyqtgraph as pg
from dataquick.qt import colors, uchars
from dataquick.qt import plotlist
from dataquick.qt.visualizations import base, register_visualizations
from dataquick.plugins.structures import psd
from dataquick.plugi... | (item),
y=item.plotDataItem.yData
)
def recalculateYValues(self):
for item in self.listView_datasets.iterItems(): # type: DQFItem
if item.isChecked():
item.plotDataItem.setData(
x=item.plotDataItem.xData,
... | """
Parameters
----------
df : structures.PSD
Returns
-------
xVals : np.ndarray
the data to be used for x-axis plotting
"""
return df.diameter.values
def yData(self, df):
"""
Parameters
----------
df ... |
tensorflow/graphics | tensorflow_graphics/geometry/deformation_energy/as_conformal_as_possible.py | Python | apache-2.0 | 9,050 | 0.002652 | # Copyright 2020 The TensorFlow Authors
#
# 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 i... | port absolute_import
from __future__ import division
from __future__ import print_function
from typing import Optional
import tensorflow as tf
from tensorflow_graphics.geometry.transformation import quaternion
from tensorflow_graphics.math import vector
from tensorflow_graphics.util import export_api
from tensorflow... | orflow_graphics.util import type_alias
def energy(vertices_rest_pose: type_alias.TensorLike,
vertices_deformed_pose: type_alias.TensorLike,
quaternions: type_alias.TensorLike,
edges: type_alias.TensorLike,
vertex_weight: Optional[type_alias.TensorLike] = None,
ed... |
olegvg/me-advert | me-advert/rotabanner/application.py | Python | gpl-3.0 | 2,183 | 0.004581 | # -*- coding: utf-8 -*-
__author__ = 'ogaidukov'
import os.path
import argparse
import tornado.ioloop
import tornado.httpserver
import tornado.web
from commonlib import configparser, logmaker
from rotabanner.lib import route
import redis
import pygeoip
config = None
logger = None
args = None
redisdb = None
geoip = N... |
args = arg_parser.parse_args()
config = configparser.parse_config(args.config)
# TODO make use of standard Tornado logging streams 'tornado.access', 'tornado.application' and 'tornado.general'
logger = logmaker.logger_from_config(config)
redis_config = configparser.config_section_obj(config, 're... | geoip = pygeoip.GeoIP('../me-advert/rotabanner/data/GeoIPCity.dat', pygeoip.MEMORY_CACHE)
import handlers # Important! Initialize url handler classes by importing
def run_application():
init_application()
listen_port = int(args.listen_port)
listen_addr = args.listen_addr
template_path=os.path... |
EmuKit/emukit | tests/emukit/test_functions/test_hennig1d.py | Python | apache-2.0 | 425 | 0 | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import num | py as np
from emukit.test_functions.quadrature import hennig1D
def test_hennig1D_return_shape():
"""
Test output dimension is 2d
"""
hennig1d_func, _ = hennig1D()
x = np.zeros((2, 1))
result | = hennig1d_func.f(x)
assert result.ndim == 2
assert result.shape == (2, 1)
|
batermj/algorithm-challenger | code-analysis/programming_anguage/python/source_codes/Python3.5.9/Python-3.5.9/Lib/xml/sax/expatreader.py | Python | apache-2.0 | 15,704 | 0.001337 | """
SAX driver for the pyexpat C module. This driver works with
pyexpat.__version__ == '2.22'.
"""
version = "0.20"
from xml.sax._exceptions import *
from xml.sax.handler import feature_validation, feature_namespaces
from xml.sax.handler import feature_namespace_prefixes
from xml.sax.handler import feature_external_... | available in Java", None)
del sys
try:
from xml.parsers import expat
except ImportError:
raise SA | XReaderNotAvailable("expat not supported", None)
else:
if not hasattr(expat, "ParserCreate"):
raise SAXReaderNotAvailable("expat not supported", None)
from xml.sax import xmlreader, saxutils, handler
AttributesImpl = xmlreader.AttributesImpl
AttributesNSImpl = xmlreader.AttributesNSImpl
# If we're using a... |
volkhin/ycmd | ycmd/tests/python/get_completions_test.py | Python | gpl-3.0 | 5,570 | 0.028736 | # coding: utf-8
#
# Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd 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... | _parameter', '[ID]' ),
),
'errors': empty(),
} )
},
} )
@SharedYcmd
def GetCompletions_Unicode_InLine_test( app ):
RunTest( app, {
'description': 'return completions for strings with multi-byte chars',
'request' | : {
'filetype' : 'python',
'filepath' : PathToTestFile( 'unicode.py' ),
'line_num' : 7,
'column_num': 14
},
'expect': {
'response': requests.codes.ok,
'data': has_entries( {
'completions': contains(
CompletionEntryMatcher( 'center', 'function: builtins.st... |
tylerlaberge/Jasper | jasper/utility.py | Python | mit | 341 | 0.002933 | """
The utility module.
"""
import traceback
def extract_traceback(exception):
"""
Utility functio | n for extracting the traceback from an exception.
:param exception: The exception to | extract the traceback from.
:return: The extracted traceback.
"""
return ''.join(traceback.format_tb(exception.__traceback__))
|
homeworkprod/byceps | tests/integration/blueprints/monitoring/healthcheck/test_healthcheck.py | Python | bsd-3-clause | 1,360 | 0 | """
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from unittest.mock import patch
import pytest
# Test against an admin app because that doesn't require setup of brand
# party. After all, both admin and party apps should react the same.
def test_healthcheck_... | lthcheck.views._is_rdbms_ok')
def test_healthcheck_fail(is_rdbms_ok_mock, client):
expected_media_type = 'application/health+json'
is_rdbms_ok_mock.return_value = False
response = client.get('/health')
assert response.status_code == 503
assert response.content_type == expected_media_type
asse... | 'status': 'ok',
'details': {
'rdbms': [{'status': 'fail'}],
},
}
@pytest.fixture(scope='module')
def client(make_client, admin_app):
return make_client(admin_app)
|
MihaZelnik/meepleAPI | meeple/apps/api/serializers/publisher.py | Python | bsd-3-clause | 435 | 0.002299 | from apps.a | pi.serializers import base
from apps.api.models import Publisher
class PublisherListSerializer(base.BaseP | ropertiesListSerializer):
resource = 'publisher'
class Meta(object):
model = Publisher
fields = base.LIST_FIELDS
class PublisherSerializer(base.BasePropertiesDetailSerializer):
resource = 'publisher'
class Meta(object):
model = Publisher
fields = base.DETAIL_FIELDS |
oemof/oemof_examples | oemof_examples/oemof.solph/v0.4.x/storage_investment/v1_invest_optimize_all_technologies.py | Python | gpl-3.0 | 6,671 | 0 | # -*- coding: utf-8 -*-
"""
General description
-------------------
This example shows how to perform a capacity optimization for
an energy system with storage. The following energy system is modeled:
input/output bgas bel
| | | |
| ... | ###############################################################
logging.info("Optimise the energy system")
# initialise the operational model
om = solph.Model(energysystem)
# if tee_switch is true solver messages will be displayed
logging.info("Solve the optimization problem")
om.solve(solver="cbc", solve_kwargs={"t... | ##
# Check and plot the results
##########################################################################
# check if the new result object is working for custom components
results = solph.processing.results(om)
custom_storage = solph.views.node(results, "storage")
electricity_bus = solph.views.node(results, "electri... |
zibraproject/zika-pipeline | scripts/minion.py | Python | mit | 4,070 | 0.020885 | #Written by Nick Loman (@pathogenomenick)
import os
import sys
from Bio import SeqIO
from clint.textui import colored, puts, indent
def get_nanopolish_header(ref):
recs = list(SeqIO.parse(open(ref), "fasta"))
if len (recs) != 1:
print >>sys.stderr, "FASTA has more than one sequence"
raise SystemExit
return "... | ample, args.sample, args.sample))
cmds.append("align_trim.py %s %s --report %s.alignreport.txt < %s.sorted.bam 2> %s.alignreport.er | samt | ools view -bS - | samtools sort -T %s - -o %s.primertrimmed.sorted.bam" % (normalise_string, bed, args.sample, args.sample, args.sample, args.sample, args.sample))
cmds.append("samtools index %s.trimmed.sorted.bam" % (args.sample))
cmds.append("samtools index %s.primertrimmed.sorted.bam" % (args.sample))
#covplot.R... |
ntpwilliam/totravel | first2.py | Python | gpl-3.0 | 264 | 0.049242 | #!/user/bin/python
# -*- coding: UTF-8 -*--
import time;
import calendar;
ticks = time.time();
cal = calendar.month(2016,1);
#print 'Right now ' , ticks;
#print 'date ' , cal;
tt = 3
if tt< 3 :
print('three')
elif tt == 5 :
prin | t(' | ffff')
|
openSUSE/yabsc | yabsclib/results.py | Python | gpl-2.0 | 36,764 | 0.005658 | #
# results.py - Result widget for Yabsc
#
# Copyright (C) 2008 James Oakley <jfunk@opensuse.org>
# 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 2
# of the License, or (at your... | ut WITHOUT 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, write to the Free Software
# Foundation, ... | on, MA 02111-1307, USA.
import os
from PyQt4 import QtGui, QtCore
#
# Data model
#
class ResultModel(QtCore.QAbstractItemModel):
"""ResultModel()
Model for package results
"""
def __init__(self):
QtCore.QAbstractItemModel.__init__(self)
self.results = []
self.targets = [... |
datenschuft/SMA-EM | features/pvdata.py | Python | gpl-2.0 | 3,769 | 0.000531 | """
Get inverter pv values via modbus
2018-12-28 Tommi2Day
2020-09-22 Tommi2Day fixes empty data exeptions
2021-01-02 sellth added support for multiple inverters
Configuration:
pip3 install pymodbus
[FEATURE-pvdata]
# How frequently to send updates over (defaults to 20 sec)
min_u... | S32', 'FIX0', 'Power L1', 'W'],
['30779', 'S32', 'FIX0', 'Power L2', 'W'],
['30781', 'S32', 'FIX0', 'Power L3', 'W'],
['30953', 'S32', 'FIX1', u | 'device temperature', u'\xb0C'],
['30517', 'U64', 'FIX3', 'daily yield', 'kWh'],
['30513', 'U64', 'FIX3', 'total yield', 'kWh'],
['30521', 'U64', 'FIX0', 'operation time', 's'],
['30525', 'U64', 'FIX0', 'feed-in time', 's'],
['30975', 'S32', 'FIX2', 'intermediate voltage', 'V'],
... |
jbutler42/pynet_class | pyclass/week2/SNMP/exercise4.py | Python | apache-2.0 | 1,452 | 0.006887 | #!/usr/bin/env python
'''
4. SNMP Basics
a. Create an 'SNMP' directory in your home directory.
$ mkdir SNMP
$ cd SNMP
b. Verify that you can import the snmp_helper library. This is a small library that I created to simplify aspects of PySNMP.
$ python
Python 2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4... | "[%s]:\t----\t%s" % (k, v | ))
print()
print()
if __name__ == "__main__":
main()
|
Gab0/gekkoJaponicus | japonicus/japonicus.py | Python | mit | 5,398 | 0.000926 | #!/bin/python
from . import halt, Settings, interface
from time import sleep
import random
from threading import Thread
from .evolution_generations import Generations
import datetime
import os
import waitress
import promoterz
from version import VERSION
def launchWebEvolutionaryInfo():
print("WEBSERVER MOD... | nMethod": None,
"TargetParameters": None
}
japonicusOptions["GenerationMethod"] =\
'chromosome' if options.chromosome_mode else 'oldschool'
if options.skeleton:
EvaluationMode = 'indicator'
AllIndicators = Settings.get... | lIndicators[K]) != dict:
TargetParameters[K] = AllIndicators[K]
elif AllIndicators[K]['active']:
TargetParameters[K] = AllIndicators[K]
TargetParameters[K]['active'] = (0, 1)
japonicusOptions["TargetParameters"]... |
moskupols/habiter | habiter/settings.py | Python | mit | 1,683 | 0 | """
This is the file to store all user-definable magic constants.
Of course, all these values are supposed to be got from some
decent config file, something like ~/.habiter. Somewhen I'll
do that. Nevertheless, current file could be the source of
the default s | ettings.
"""
try:
from .secret import USER_ID, API_KEY
except ImportError:
USER_ID = 'c31fdbc0-15c5-44a8-8ef9-c8c8842b0266'
API_KEY = '085e09c3-9a28-4828-a9e5-8dfb953f2dea'
# the screen is divided in this proportion
TASK_LIST_HEIGHT_WEIGHT = 4
DEFERRED_LIST_HEIGHT_WEIGHT = 1
# task values are real numbe | rs, and are rounded for showing in task list
VALUE_ROUND = 3
# these are used to define colors for task value half-intervals.
# each half-interval is left-inclusive, right-exclusive.
VALUE_COLOR_BOUNDS = (
-10, -5, -0.9, 1, 5, 10,
)
# see http://urwid.org/manual/displayattributes.html
# for info on palette syntax... |
Kaezon/allianceauth | allianceauth/corputils/migrations/0003_granular_permissions.py | Python | gpl-2.0 | 908 | 0.001101 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-22 23:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('corputils', '0002_migrate_permissions'),
]
operations = [
migrations.AlterModelOpti... | name='corpstats',
options={'permissions': (('corp_apis', 'Can view API keys of members of their corporation.'), ('alliance_apis', 'Can view API keys of members of their alliance.'), ('blue_apis', 'Can view API keys of members of blue | corporations.'), ('view_corp_corpstats', 'Can view corp stats of their corporation.'), ('view_alliance_corpstats', 'Can view corp stats of members of their alliance.'), ('view_blue_corpstats', 'Can view corp stats of blue corporations.')), 'verbose_name': 'corp stats', 'verbose_name_plural': 'corp stats'},
),
... |
nxnfufunezn/qtile | libqtile/group.py | Python | mit | 15,212 | 0.000329 | # Copyright (c) 2012-2014 Tycho Andersen
# Copyright (c) 2013 xarvh
# Copyright (c) 2013 roger
# Copyright (c) 2013 Tao Sauvage
# Copyright (c) 2014 ramnes
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2014 dequis
# Copyright (c) 2015 Dario Giovannetti
# Copyright (c) 2015 Alexander Lozovskoy
#
# Permission is hereby g... | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS | IN THE
# SOFTWARE.
import contextlib
import xcffib
import xcffib.xproto
from . import command
from . import hook
from . import window
from . import utils
class _Group(command.CommandObject):
"""
A group is a container for a bunch of windows, analogous to workspaces
in other window managers. Each... |
mathcamp/steward_palantir | steward_palantir/tasks.py | Python | mit | 7,289 | 0.000274 | """ Palantir tasks """
import itertools
from datetime import datetime
import copy
from collections import defaultdict
from steward_salt.tasks import salt_match, salt, salt_key
from steward_tasks.tasks import pub
from .models import CheckDisabled, MinionDisabled, CheckResult, Alert
from steward_tasks import celery, St... | t)\
.filter(CheckResult.check.notin_(check_names))\
.delete(synchronize_session=False)
task.db.query(Alert)\
.filter(Alert.check.notin_(check_names))\
.delete(synchronize_session=False)
minion_list = salt_key('list_keys')['minions']
minions = set( | minion_list)
old_minions = set(itertools.chain.from_iterable(
task.db.query(CheckResult.minion)
.group_by(CheckResult.minion).all()))
removed = old_minions - minions
added = minions - old_minions
if removed:
task.db.query(MinionDisabled).filter(MinionDisabled.name.in_(removed))\
... |
berkmancenter/mediacloud | apps/webapp-api/tests/python/auth/reset_password/test_send_password_reset_token.py | Python | agpl-3.0 | 1,341 | 0.002983 | from mediawords.db import connect_to_db
from webapp.auth.register import add_user
from | webapp.auth.reset_password import send_password_reset_token
from webapp.auth | .user import NewUser
from webapp.test.dummy_emails import TestDoNotSendEmails
class TestResetPassword(TestDoNotSendEmails):
def test_send_password_reset_token(self):
db = connect_to_db()
email = 'test@user.login'
password = 'userlogin123'
password_reset_link = 'http://password-re... |
matthappens/taskqueue | taskqueue/venv_tq/lib/python2.7/site-packages/boto/ec2/blockdevicemapping.py | Python | mit | 5,727 | 0.000524 | # Copyright (c) 2009-2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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 the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditio | ns:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR ... |
streema/deployer | deployer/envs.py | Python | mit | 337 | 0.005935 | from os import environ
from fabric.api import env, task
@task
def production():
env.user = 'deploy'
env.environment = 'production'
env.hosts = environ.get('PRODUCTION_SERVERS').split(',')
@task
def staging():
env.user = 'deplo | y'
env.environment = 'staging'
env.hosts = e | nviron.get('STAGING_SERVERS').split(',')
|
CaHudson94/data-structures | src/Completed/test_hash.py | Python | mit | 4,487 | 0 | """Test suite for hash tables."""
from hash_table import HashTable, naive_hash
from os import path
import pytest
from faker import Faker
dictionary = path.realpath(__file__).replace('test_hash.py',
'american-english')
with open(dictionary, 'r') as dictionary:
dictiona... | ckets[sack_bucket].search(sacks_hash)._list)
def test_key_not_in_hash_table(dict_hash_table_500_buckets):
"""Test that the given key is not in the table."""
with py | test.raises(KeyError):
dict_hash_table_500_buckets.get('gobledygook')
def test_naive_hash_get_five(dict_hash_table_253_buckets):
"""Test get on naive hash with minimal buckets."""
ht = dict_hash_table_253_buckets
assert ht.get('wombat') == 'wombat'
def test_naive_has_set_three(hash_table_with_le... |
samuel/squawk | squawk/__init__.py | Python | bsd-3-clause | 195 | 0 |
from squawk.aggregates import *
from s | quawk.parsers import *
from squawk.query | import *
from squawk.version import *
__author__ = "Samuel Stauffer <samuel@descolada.com>"
__version__ = VERSION
|
CaymanUnterborn/burnman | examples/example_fit_data.py | Python | gpl-2.0 | 6,646 | 0.011285 | # This file is part of BurnMan - a thermoelastic and thermodynamic toolkit for the Earth and Planetary Sciences
# Copyright (C) 2012 - 2015 by the BurnMan team, released under the GNU
# GPL v2 or later.
"""
example_fit_data
----------------
This example demonstrates BurnMan's functionality to fit various mineral ph... | pressures, temperat | ures)[0]
print('')
# Fit to the third order Birch-Murnaghan EoS
mg_perovskite_test.set_method("bm3")
fitted_eos = best_fit()
print('3rd order fit:')
burnman.tools.pretty_print_values(fitted_eos.popt, fitted_eos.pcov, fitted_eos.fit_params)
model_vs_3rd_order_correct = mg_perovskite_te... |
Cesarmerjan/Pystatistic | Bartletts_test.py | Python | mit | 2,271 | 0.006605 | import numpy as np
from scipy import stats
def Bartlett (matrix):
n = np.array([len(i) for i in matrix])
k = len(matrix)
N = n.sum()
Si2 = np.var(matrix, axis=1, ddof=1)
Sp2 = (np.array([(n[i]-1) * Si2[i] for i in range(k)]).sum() / (N - k))
term_1 = (N-k)*np.log(Sp2)
| term_2 = np.array([(n[i]-1)*np.log(Si2[i]) for i in range(k)]).sum()
term_3 = 1/(3*(k-1))
term_4 = np.array([1/(n[i]-1) for i in range(k)]).sum()
term_5 = (1/(N-k))
statistic = (term_1-term_2)/(1+(term_3*(term_4-term_5)))
degrees_ | of_freedom = k-1
significance_level = 0.05
critical_value = stats.chi2.isf(significance_level, degrees_of_freedom)
return (statistic, degrees_of_freedom, significance_level, critical_value)
tt = np.array([[1.006, 0.996, 0.998, 1.000, 0.992, 0.993, 1.002, 0.999, 0.994, 1.000],
[0.998, 1.0... |
kapilt/cloud-custodian | tests/test_iamgen.py | Python | apache-2.0 | 3,515 | 0.000853 | # Copyright 2020 Amazon.com, Inc. or its affiliates. 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... | g permissions and
# limitations under the License.
from .common import BaseTest, load_data
from c7n.config import Config, Bag
from c7n import manager
import fnmatch
class TestIamGen(BaseTest):
def check_permissions(self, perm_db, perm_set, path) | :
invalid = []
for p in perm_set:
if ':' not in p:
invalid.append(p)
continue
s, a = p.split(':', 1)
if s not in perm_db:
invalid.append(p)
continue
if '*' in a:
if not fnmatch... |
pierrecnalb/White-Renamer | whiterenamer/model/__init__.py | Python | gpl-2.0 | 846 | 0.001182 | #!/usr/bin/python3
# Copyright (C) 2015-2016 Pierre Blanc
#
# This file is part of WhiteRenamer.
#
# WhiteRenamer 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.
#
# WhiteRenamer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public Lic... | more details.
#
# You should have received a copy of the GNU General Public License
# along with WhiteRenamer. If not, see <http://www.gnu.org/licenses/>.
from . import action_manager
from .file_system import FileDescriptor, Controller, FileSystemTreeNode, FileSystem
|
soarpenguin/python-scripts | net.py | Python | gpl-3.0 | 954 | 0.016771 | #!/usr/bin/env Python
import time
import sys
if len(sys.argv) > 1:
INTERFACE = sys.argv[1]
else:
INTERFACE = 'eth1'
STATS = []
print 'Interface:',INTERFACE
def rx():
ifstat = open('/proc/net/dev').readlines()
for interface in ifstat:
#print '----', interface, '-----'
if INTERFACE in ... | )
RX_O = rxstat_o[0]
TX = float(STATS[1])
TX_O = rxstat_o[1]
RX_RATE = round((RX - R | X_O)/1024/1024,3)
TX_RATE = round((TX - TX_O)/1024/1024,3)
print RX_RATE ,'MB ',TX_RATE ,'MB'
|
18F/quotable | app_config.py | Python | mit | 1,915 | 0.002089 | #!/usr/bin/env python
"""
Project-wide application configuration.
DO NOT STORE SECRETS, PASSWORDS, ETC. IN THIS FILE.
They will be exposed to users. Use environment var | iables instead.
See get_secrets() below for a fast way to access them.
"""
import os
"""
NAMES
"""
# Project name used for display
PROJECT_NAME = 'quotable'
# Project name in urls
# Use dashes, not underscores!
PROJECT_SLUG = 'quotable'
# The name of the repository conta | ining the source
REPOSITORY_NAME = 'quotable'
REPOSITORY_URL = 'git@github.com:nprapps/%s.git' % REPOSITORY_NAME
REPOSITORY_ALT_URL = None # 'git@bitbucket.org:nprapps/%s.git' % REPOSITORY_NAME'
# The name to be used in paths on the server
PROJECT_FILENAME = 'quotable'
"""
DEPLOYMENT
"""
FILE_SERVER = 'tools.apps.npr... |
lukecwik/incubator-beam | sdks/python/apache_beam/runners/portability/spark_java_job_server_test.py | Python | apache-2.0 | 2,695 | 0.001855 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | 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 implied.
# See the License for t... | # pytype: skip-file
import logging
import unittest
from apache_beam.options import pipeline_options
from apache_beam.runners.portability.spark_runner import SparkRunner
class SparkTestPipelineOptions(pipeline_options.PipelineOptions):
def view_as(self, cls):
# Ensure only SparkRunnerOptions and JobServerOptio... |
christoffkok/auxi.0 | src/modelling/process/materials/core.py | Python | lgpl-3.0 | 3,403 | 0 | #!/usr/bin/env python3
"""
This module provides a material class that can do thermochemical calculations.
"""
from auxi.core.objects import NamedObject
from auxi.tools.materialphysicalproperties.core import StateOfMatter
__version__ = '0.3.2'
__license__ = 'LGPL v3'
__copyright__ = 'Copyright 2016, Ex Mente Technolo... | *state)
def rho(self, **state):
"""
Calculate the rho value given the material state.
:param **state: material state
:returns: | float
"""
raise NotImplementedError()
if __name__ == '__main__':
import unittest
from core_test import *
unittest.main()
|
mynameisfiber/pymicha | pymicha/utils/__init__.py | Python | mit | 88 | 0 | from .senda | ble import sendable
from .timer import timer, Timer
from .chunk impo | rt chunk
|
Mirantis/tempest | tempest/services/database/json/versions_client.py | Python | apache-2.0 | 1,231 | 0 | # Copyright 2014 OpenStack Foundation
# 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 requ... | the specific language governing permissions and limitations
# under the License.
import urll | ib
from tempest.common import rest_client
from tempest import config
CONF = config.CONF
class DatabaseVersionsClientJSON(rest_client.RestClient):
def __init__(self, auth_provider):
super(DatabaseVersionsClientJSON, self).__init__(auth_provider)
self.skip_path()
self.service = CONF.datab... |
boss2608-cmis/boss2608-cmis-cs2 | simple.py | Python | cc0-1.0 | 624 | 0.033654 | import math
def area(a, b, c | ):
A1 = ((4*math.pi)*a**2)
A2 = ((4*math.pi)*b**2)
A3 = ((4*math.pi)*c**2)
Avg = (A1+A2+A3)/3
return Avg
def output(a, b ,c , d, e):
return """
Hello there, {}!
equation: ((4*math.pi)*{}**2)((4*math.pi)*{}**2)((4*math.pi)*{}**2)
Calculating average area of three spheres...
the answer is: {}
""".format(a, b | , c, d, e)
def main():
Name = raw_input("Name: ")
Area1 = raw_input("Area of 1st sphere: ")
Area2 = raw_input("Area of 2nd sphere: ")
Area3 = raw_input("Area of 3rd sphere: ")
e = area(int(Area1), int(Area2), int(Area3))
print output(Name, Area1, Area2, Area3, e)
main()
|
barrowkwan/Python_Class_2014 | Ian/hw2.py | Python | gpl-2.0 | 527 | 0.018975 | #!/usr/bin/env python
#Name: Ian Wong
#Date: 1/3/16
#Assignment: Counting Vowels
string = input("What is your string?")
string = string.lower()
count1= string.count('a')
coun | t2 = string.count('e')
count3 = string.count('i')
count4 = string.count('o')
count5 = string.count('u')
print ("There are %i a in the text." % (count1))
print ("There are %i e in the text." % (count2))
print ("There are %i i in the text." % (count3))
print ("There are %i | o in the text." % (count4))
print ("There are %i u in the text." % (count5))
|
torbjoernk/easybuild-framework | easybuild/tools/module_naming_scheme/categorized_hmns.py | Python | gpl-2.0 | 4,235 | 0.000708 | ##
# Copyright (c) 2015 Forschungszentrum Juelich GmbH, Germany
#
# All rights reserved.
#
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notic... | Geimer (Juelich Supercomputing Centre)
"""
import os
from easybuild.tools.module_naming_scheme.hierarchical_mns import HierarchicalMNS
from easybuild.tools.config import build_option
class CategorizedHMNS(HierarchicalMNS):
"""
Class implementing an extended hierarchical module naming scheme using the
'm... | S = ['name', 'version', 'versionsuffix', 'toolchain', 'moduleclass']
def det_module_subdir(self, ec):
"""
Determine module subdirectory, relative to the top of the module path.
This determines the separation between module names exposed to users,
and what's part of the $MODULEPATH. ... |
miur/miur | tui/urwid_tui.py | Python | gpl-3.0 | 1,631 | 0.001226 | #
# SPDX-FileCopyrightText: 2020 Dmytro Kolomoiets <amerlyq@gmail.com> and contributors.
#
# SPDX-License-Identifier: GPL-3.0-only
#
import pickle
import urwid
import zmq
from ..ifc import *
def tui_client(src_uri, dst_uri, log_uri):
set_current_thread_name()
_log = getLogger()
ctx = zmq.Context.instan... |
dst_sock = ctx.socket(zmq.PUSH)
dst_sock.connect(dst_uri)
src_sock = ctx.socket(zmq.SUB)
src_sock.connect(src_uri)
src_sock.setsockopt_string(zmq.SUBSCRIBE, '*') # custom broadcast
src_sock.setsockopt_string(zmq.SUBSCRIBE, 'ui')
try:
## BET: python-urwid
# [Urwid] key cap... |
# http://lists.excess.org/pipermail/urwid/2011-July/001080.html
body = urwid.Text("<Press ',' to exit>")
view = urwid.Filler(body, 'top')
def unhandled_input(key):
if key in ('esc', ','):
raise urwid.ExitMainLoop()
dst_sock.send_multipart([b'key'... |
adamrvfisher/TechnicalAnalysisLibrary | BigDownScanFilter.py | Python | apache-2.0 | 1,265 | 0.008696 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 28 23:29:44 2017
@author: AmatVictoriaCuramIII
"""
#Get modules
from SAge import SAge
from SAverageReturn import SAverageReturn
from SCoeffVar import SCoeffVar
from STrend import STrend
from SGapDown import SGapDown
from DayOverAverageRollingVolume import DayOverAverageRo... | )
df1 = df.set_index('Symbol')
symbols = df.Symbol.values
port = (symbols)
port1 = []
print(symbols)
for s in port:
try:
q = data.DataReader(s, 'yahoo', start='1/1/1950', end='01/01/2050')
if su | m(SAdjustedClose(q)) > 5 and SAge(q) > 750 and sum(SGapDown(q)
) > .01 and sum(SAverageRollingVolume(q)
) > 500000 and sum(DayOverAverageRollingVolume(q)
) > 2 and sum(SAverageReturn(q)) < -.01 and sum(STrend(q)) < -0.01:
print(s, STrend(q), DayOverAverageRollingVolume(q), SAge(q))
... |
skftn/pika | tests/unit/callback_tests.py | Python | mpl-2.0 | 16,337 | 0 | # -*- coding: utf8 -*-
"""
Tests for pika.callback
"""
import logging
try:
import mock
except ImportError:
from unittest import mock
try:
import unittest2 as unittest
except ImportError:
import unittest
from pika import amqp_object
from pika import callback
from pika import frame
from pika import spe... | None)
self.assertEqual(self.obj.pending(self.PREFIX_CLASS, self.KEY), 1)
def test_pending_two(self):
self.obj.add(self.PREFIX, self.KEY, | None)
self.obj.add(self.PREFIX, self.KEY, lambda x: True)
self.assertEqual(self.obj.pending(self.PREFIX_CLASS, self.KEY), 2)
def test_process_callback_false(self):
self.obj._stack = dict()
self.assertFalse(self.obj.process('FAIL', 'False', 'Empty',
... |
foone/7gen | bin/bmp2vxp.py | Python | gpl-2.0 | 5,629 | 0.047255 | #!/usr/env python
# Change this stuff:
name='Arka Texture'
author='Travis Wells'
origauth='Travis Wells'
shortname='arkatexture' # out file will be shortname with a 'vxp' extension
image='sleep2.bmp'
uniqueid=0 # Set to 0 if you don't have one.
dither=True # Set to False if you are doing sprites, True for photos
#Don... | 'code')
import zipfile
import py | game
from tmap import TMAP
import lib3dmm
from urllib import urlopen
from struct import pack
from simpleMBMP import MBMP
from idgenerator import GenerateID
from error import SaveError
from time import time
version='0.6'
def CreateVXPExpansionFromBMP(name,author,origauth,outfile,shortname,image,uniqueid,progress,dither=... |
fboender/miniorganizer | src/lib/kiwi/ui/listdialog.py | Python | gpl-3.0 | 14,071 | 0.000355 | #
# Copyright (C) 2007-2008 by Async Open Source
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This progr... | :
self.list. | update(item)
# Public API
def add_item(self, item):
"""Appends an item to the list
@param item: item to append
"""
self.list.append(item)
def add_items(self, items):
"""Appends a list of items to the list
@param items: items to add
@type items: a se... |
jeedom/plugin-blea | resources/blead/devices/meyerdom2analog.py | Python | gpl-2.0 | 725 | 0.042759 | import time
import logging
import globals
class Meyerdom2Analog():
def __init__(self):
self.name = 'meyerdom2analog'
self.ignoreRepeat = False
def isvalid(self,name,manuf='',data='',mac=''):
if 'meyerdom 2 contacteurs analog' in name.lower() or name.lower()==self.name:
ret | urn True
def parse(sel | f,data,mac,name,manuf):
action={}
action['present'] = 1
try:
action['analog1'] = int(bytearray.fromhex(manuf[8:16]).decode())
action['analog2'] = int(bytearray.fromhex( manuf[16:24]).decode())
action['voltage'] = float(bytearray.fromhex(manuf[24:]).decode())
except Exception as e:
logging.error(str(... |
mindw/shapely | tests/test_predicates.py | Python | bsd-3-clause | 2,506 | 0.001596 | """Test GEOS predicates
"""
from . import unittest
from shapely.geometry import Point, Polygon
from shapely.geos import TopologicalError, PredicateError
import pytest
class PredicatesTestCase(unittest.TestCase):
def test_binary_predicates(self):
point = Point(0.0, 0.0)
self.assertTrue(point.disj... | point.touches(Point(-1.0, -1.0)))
self.assertFalse(point.crosses(Point(-1.0, -1.0)))
self.assertFalse(point.within(Point(-1.0, -1.0)))
self.assertFalse(point.contains(Point(-1.0, | -1.0)))
self.assertFalse(point.equals(Point(-1.0, -1.0)))
self.assertFalse(point.touches(Point(-1.0, -1.0)))
self.assertTrue(point.equals(Point(0.0, 0.0)))
self.assertTrue(point.covers(Point(0.0, 0.0)))
self.assertFalse(point.covers(Point(-1.0, -1.0)))
def test_unary_predic... |
NullScope/BorderlessStone | tests/setupenv_windows.py | Python | lgpl-3.0 | 4,510 | 0.002217 | #-----------------------------------------------------------------------------
# Copyright (c) 2013, PyInstaller Development Team.
#
# Distributed under the terms of the GNU General Public License with exception
# for distributing bootloader.
#
# The full license is in the file COPYING.txt, distributed with this softwa... | asy_ | install
# Expand PYTHONPATH with PyInstaller package to support running without
# installation -- only if not running in a virtualenv.
if not hasattr(sys, 'real_prefix'):
pyi_home = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
sys.path.insert(0, pyi_home)
from PyInstaller.compat import is_... |
EBII/account-invoicing | sale_timesheet_invoice_description/tests/test_sale_timesheet_description.py | Python | agpl-3.0 | 6,239 | 0 | # -*- coding: utf-8 -*-
# © 2016 Carlos Dauden <carlos.dauden@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp.addons.sale.tests.test_sale_common import TestSale
import datetime
class TestSaleTimesheetDescription(TestSale):
def test_sale_timesheet_description_1111(self... | # let's log some timesheets
# self.env['account.analytic.line'].create({
# 'name': 'Test description 1234567890',
# 'account_id': sale_order.project_id.id,
# 'unit_amount': 11.5,
# 'user_id': self.manager.id,
# 'is_timesheet': True,
# })
... | description=True
# ).action_invoice_create()
# invoice = inv_obj.browse(invoice_id)
#
# description = invoice.invoice_line_ids[0].name
# date = datetime.date.today()
# self.assertIn('Support Contract (on timesheet)\n'+
# '- 11.5 Hour(s) - Test description 1234567890 -... |
BackupTheBerlios/honeyspy-svn | junk/sshsimpleserver.py | Python | gpl-2.0 | 4,759 | 0.005463 | #!/usr/bin/env python
from twisted.cred import portal, checkers
from twisted.conch import error, avatar
from twisted.conch.checkers import SSHPublicKeyDatabase
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.internet import reactor, protocol, defer
from twisted.python import log
... | 4fxjHf9imyRJbixtQhlH9lfNjUIx+4LmrJH5QNRsFporcHDKOTwTTYLh5KmRpslkYHRivcJSkbh/C+BR3utDS555mV'
privateKey = """-----BEGIN RSA PRIVATE KEY-----
MIIByAIBAAJhAK8ycfDmDpyZs3+LXwRLy4vA1T6yd/3PZNiPwM+uH8Yx3/YpskSW
4sbUIZR/ZXzY1CMfuC5qyR+UDUbBaaK3Bwyjk8E02C4eSpkabJZGB0Yr3CUpG4fw
vgUd7rQ0ueeZlQIBIwJgbh+1VZfr7WftK5lu7MHtqE1S1vPWZ... | Td0E8hU8AcP0FVP+8
PQm/g/aXf2QQkQT+omdHVEJrAjEAy0pL0EBH6EVS98evDCBtQw22OZT52qXlAwZ2
gyTriKFVoqjeEjt3SZKKqXHSApP/AjBLpF99zcJJZRq2abgYlf9lv1chkrWqDHUu
DZttmYJeEfiFBBavVYIF1dOlZT0G8jMCMBc7sOSZodFnAiryP+Qg9otSBjJ3bQML
pSTqy7c3a2AScC/YyOwkDaICHnnD3XyjMwIxALRzl0tQEKMXs6hH8ToUdlLROCrP
EhQ0wahUTCk1gKA4uPD6TMTChavbh4K63OvbKg==
-... |
bopen/mariobros | tests/test_mariofile.py | Python | apache-2.0 | 6,933 | 0.001731 | # -*- coding: utf-8 -*-
# python 2 support via python-future
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import dict
import os
import pytest
from mariobros import mariofile
SIMPLE_MARIOFILE = """[section_one]
text one
[section_two]
text two
"""
COMPLEX_MARIOFIL... | 'section_include_1': {
'action_template': '',
'sources_repls': '',
'target_pattern': '',
'variable_include1': '3',
}
}
h = mario_folder.join('test_parse_config.ini')
| h.write(TEST_PARSE_CONFIG)
parsed_mariofile_include = mariofile.parse_config(MARIOFILE_AND_INCLUDE.splitlines(True),
cwd=os.path.join(
str(mario_folder.dirname), 'tmpdir'
... |
F5Networks/f5-ansible-modules | ansible_collections/f5networks/f5_modules/plugins/modules/bigip_profile_http2.py | Python | mit | 20,741 | 0.001543 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: bigip_profile_http2
sho... | 'concurrentStreamsPerConnection': 'streams',
'connectionIdleTimeout': 'idle_timeout',
'defaultsFrom': 'parent',
'enforceTlsRequirements': 'enforce_tls_requirements',
'frameSize': 'frame_size',
'headerTableSize': 'header_table_size',
'insertHeader': 'insert_header',
... | ',
}
api_attributes = [
'activationModes',
'concurrentStreamsPerConnection',
'connectionIdleTimeout',
'description',
'defaultsFrom',
'enforceTlsRequirements',
'frameSize',
'headerTableSize',
'insertHeader',
'insertHeaderName',
... |
jsvennevid/adventofcode | 2015/03/puzzle2.py | Python | mit | 440 | 0.05 | x = [0,0]
y = [0,0]
houses = {}
i = 0
with open('day3.txt') as f:
while True:
address = ':'.join([s | tr(x[i]),str(y[i])])
presents = 0
if houses.has_key(address):
presents = houses[address]
houses[address] = presents + 1
c = f.read(1)
if not c:
break
if c == '^':
y[i] = y[i] - 1
if c == 'v':
y[i] = y[i] + 1
if c == '>':
x[i] = x[i] + 1
if c == '<':
x[i | ] = x[i] - 1
i = (i + 1) & 1
print len(houses)
|
starze/openhab2 | openhab2/scripts/nilan_connectiontest.py | Python | mit | 1,939 | 0.020113 | #!/usr/bin/env python
import minimalmodbus |
import serial
__author__ = "Nick Ma"
class Nilan( minimalmodbus.Instrument ):
"""Instrument class for nilan heat pump.
communication via RS485
"""
HOLDINGREG_OFFSET = 10000
def __init__(self, portname, slaveaddress=30):
minimalmodbus.Instrument.__init__(self, portname, slaveaddre... | s as high as 898.5 ms
self.mode = minimalmodbus.MODE_RTU
def is_manual_loop1(self):
"""Return True if loop1 is in manual mode."""
return self.read_register(273, 1) > 0
def get_t11Top(self):
"""Return the setpoint (SP) target for loop1."""
return ... |
vshymanskyy/Espruino | boards/STM32F429IDISCOVERY.py | Python | mpl-2.0 | 5,336 | 0.036169 | #!/bin/false
# This file is part of Espruino, a JavaScript interpreter for Microcontrollers
#
# Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk>
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at h... | 2f429idiscovery.bin',
};
chip = {
'part' : "ST | M32F429ZIT6",
'family' : "STM32F4",
'package' : "LQFP144",
'ram' : 128,#256,
'flash' : 512, #2048,
'speed' : 168,
'usart' : 6,
'spi' : 3,
'i2c' : 3,
'adc' : 3,
'dac' : 2,
};
# left-right, or top-bottom order
board = {
'left' : [ ], # fixme
'left2' : [ ],
'right2' : [ ],
'right' : [ ],
};
dev... |
SpheMakh/Stimela | stimela/cargo/cab/tigger_restore/src/run.py | Python | gpl-2.0 | 1,455 | 0.001375 | import os
import sys
import subprocess
import glob
import yaml
import shlex
import shutil
CONFIG = os.environ["CONFIG"]
INPUT = os.environ["INPUT"]
OUTPUT = os.environ["OUTPUT"]
MSDIR = os.environ["MSDIR"]
with open(CONFIG, "r") as _std:
cab = yaml.safe_load(_std)
junk = cab["junk"]
args = []
for param in cab['... | continue
if name in ' | restoring-beam scale'.split() and hasattr(value, '__iter__'):
value = ','.join(value)
if value is True:
value = ""
if name == 'f':
args.append('-f')
continue
# Positional arguments
if name == 'input-image':
inim = value
continue
elif nam... |
ypwalter/evennia | evennia/utils/batchprocessors.py | Python | bsd-3-clause | 15,282 | 0.001898 | """
This module contains the core methods for the Batch-command- and
Batch-code-processors respectively. In short, these are two different
ways to build a game world using a normal text-editor without having
to do so 'on the fly' in-game. They also serve as an automatic backup
so you can quickly recreate a world also a... | nother file at this point.
#IMPORT examples.batch
@drop box
# Done, the box is in the warehouse! (this last comment is not necessary to
# close the @drop command since i | t's the end of the file)
```
-------------------------
An example batch file is `contrib/examples/batch_example.ev`.
==========================================================================
Batch-code processor file syntax
The Batch-code processor accepts full python modules (e.g. `batch.py`)
that looks identi... |
jmp0xf/django-user-sessions | tests/urls.py | Python | mit | 504 | 0 | from django.conf.urls import patterns, url, include
from django.contrib import | admin
from django.http import HttpResponse
admin.autodiscover()
def empty(request):
return HttpResponse('')
def modify_session(request):
request.session['FOO'] = 'BAR'
return HttpResponse('')
urlpatterns = patterns(
'',
url(r'^$', empty),
url(r'^modify_session/$', modify_session),
u... | ,
)
|
urisimchoni/samba | python/samba/kcc/graph.py | Python | gpl-3.0 | 27,975 | 0.000214 | # Graph functions used by KCC intersite
#
# Copyright (C) Dave Craft 2011
# Copyright (C) Andrew Bartlett 2015
#
# Andrew Bartlett's alleged work performed by his underlings Douglas
# Bagnall and Garming Sam.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Genera... | e last. The
first byte covers Sunday 12am - 2am (per spec).
Here we pack two elements of the NTDS Connection schedule slots
into one element of the replTimes list.
If no schedule appears in NTDS Connection then a default of 0x11
is set in each replTimes slot as per behaviour noted in a Windows
... | of each hour.
"""
# note, NTDSConnection schedule == None means "once an hour"
# repl_info == None means "always"
if schedule is None or schedule.dataArray[0] is None:
return [0x11] * 84
times = []
data = schedule.dataArray[0].slots
for i in range(84):
times.append((data[i ... |
eryueniaobp/contest | encoder/VectorEncoder.py | Python | apache-2.0 | 1,662 | 0.010896 | #encoding=utf-8
#一大类特征
from scipy import sparse
import re
class VectorEncoder(object):
def __init__(self):
self.n_size = 0
self.idmap = {}
def fit(self, X):
for row in X:
units = re.split("\\s+", row)
for unit in units:
if unit == '-1': unit = 'nul... | a = (1,2)
| buf = sorted(buf, key=lambda x : x[0] )
for ind, val in buf:
indices.append(ind)
data.append(val)
indptr.append(len(data))
return sparse.csr_matrix((data, indices, indptr),shape=(n_row,n_col), dtype=float)
if __name__ == '__main__':
data = [... |
Murillo/Hackerrank-Algorithms | Algorithms/Implementation/repeated-string.py | Python | mit | 597 | 0.011725 | # Repeated String
# Developer: Murillo Grubler
# https://www.hackerrank.com/challenges/repeated-string/problem
# Time Complexity = O(n)
import m | ath
def repeated_string(text, total):
if len(text) == 1 and text == 'a':
return total
if text.find('a')!=-1:
add_value = len([text[i] for i in range(len(text)) if text[i] == 'a'])
excess = text[:total % len(text)]
return add_value * (total // len(text)) + len([excess[i] for i ... | i] == 'a'])
return 0
s = input().strip()
n = int(input().strip())
print (repeated_string(s, n)) |
pureqml/qmlcore | platform/android/dist/build.py | Python | mit | 1,685 | 0.02908 | #!/usr/bin/env python
from __future__ import print_function
import argparse
import os
def build(app, title, release):
os.system('rm -rf %s' %app)
res = os.system('cordova create %s com.%s.app %s' %(app, app, title))
if res != 0:
print("Failed to create android app")
return
os.system('rsync -a ./ %s/www --ex... | )
res = os.system('cordova --version')
if res == 0:
build(args.app, args. | title, args.release)
else:
print('Install "cordova" first: https://cordova.apache.org/docs/en/latest/guide/cli/')
|
mbirru/midonet-charms | midonet-repository/hooks/services.py | Python | apache-2.0 | 1,540 | 0.000649 | #
# Copyright (c) 2015 Midokura SARL, 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 ... | rom charmhelpers.core.services.base import ServiceManager
from charmhelpers.core.services import helpers
import actions
def manage():
manager = ServiceManager([
{
'service': 'midonet-repository',
'ports': [], # ports to after start
'provided_data | ': [
# context managers for provided relations
# e.g.: helpers.HttpRelation()
],
'required_data': [
# data (contexts) required to start the service
# e.g.: helpers.RequiredConfig('domain', 'auth_key'),
# helper... |
kernsuite-debian/lofar | RTCP/Cobalt/CoInterface/test/tRingCoordinates.py | Python | gpl-3.0 | 6,214 | 0.024139 | #!/usr/bin/env python3
import sys
from math import sqrt, cos, pi
import subprocess
import itertools
class RingCoordinates:
"""
Original RingCoordinates implementation (+ Vlad's fix). Taken from parset.py in
RTCP\Run\src\LOFAR\parset
"""
def __init__(self, numrings, width, center, dirtype):
... | rtype != "J2000" and self.dirtype != "B1950":
return offset
# warp coordinates closer to the NCP
cos_dec = cos(self.center[1] + offset[1])
epsilon = 0.0001
if cos_dec > epsilon:
return (offset[0]/cos_dec, offset[1])
else:
return offset
d... | width / sqrt(3)
def len_width(self):
"""
_
/ \
\_/
|...|
"""
return 2 * self.len_edge()
def len_height(self):
"""
_ _
/ \ :
\_/ _
"""
return self.width
def delta_width(self):
... |
hamtamtots/website | matt_site/blog/models/article.py | Python | mit | 622 | 0.022581 | from django.db import models
from .tag import Tag
from .articlebody import ArticleBody
class Article(models | .Model):
id = models.AutoField(primary_key = True)
key = models.CharField(max_length = 1000)
title = models.CharField(max_length = 1000)
description = models.CharField(max_length = 1000)
tags = models.ManyToManyField(Tag, related_name='articles')
created = models.DateTimeField(auto_now_add = Tr... | icleBody)
def __str__(self):
return self.title |
USGSDenverPychron/pychron | pychron/pipeline/tasks/panes.py | Python | apache-2.0 | 28,668 | 0.000942 | # ===============================================================================
# Copyright 2015 Jake Ross
#
# 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... | pter import TabularAdapter
from traitsui.tree_node import TreeNode
from uncertainties import nominal_value, std_dev
from pychron.core.configurable_tabular_adapter import ConfigurableMixin
from pychron.core.helpers.color_generators import colornames
from pychron.core.helpers.formatting import floatfmt
from pychron.core... | or
from pychron.core.ui.table_configurer import TableConfigurer
from pychron.core.ui.tabular_editor import myTabularEditor
from pychron.envisage.browser.view import PaneBrowserView
from pychron.envisage.icon_button_editor import icon_button_editor
from pychron.pipeline.engine import Pipeline, PipelineGroup, NodeGroup
f... |
OGKevin/ComBunqWebApp | apiwrapper/endpoints/certificate_pinned.py | Python | mit | 856 | 0 | from apiwrapper.endpoints.endpoint import Endpoint
from apiwrapper.endpoints.user import User
class CertificatePinned(Endpoint):
__endpoint_user_pinned_certificates = "certificate-pinned"
@classmethod
def _get_base_endpoint(cls, user_id, certificate_id=None):
endpoint = User._get_base_endpoint(u... | self._get_base_endpoint(user_id)
return self._make_get_request(en | dpoint)
def get_pinned_certificate_by_id(self, user_id, certificate_id):
endpoint = self._get_base_endpoint(user_id, certificate_id)
return self._make_get_request(endpoint)
|
rapidpro/ureport-web-participation | webparticipation/apps/profile_page/views.py | Python | agpl-3.0 | 2,099 | 0.002859 | from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_http_methods, require_GET
from webparticipation.apps.ureporter.models import Ureporter
from webparticipation.apps.latest_poll.decor... | eporter.user.email,
'date_joined': ureporter.user.date_joined,
'subscribed': ureporter.subscribed,
| 'confirm_changes': confirm_changes})
@login_required
@require_http_methods(['GET', 'POST'])
def deactivate_account(request):
ureporter = Ureporter.objects.get(user__username=request.user)
if request.method == 'GET':
return render(
request,
'deactivate.html',
... |
chubbymaggie/miasm | miasm2/jitter/jitload.py | Python | gpl-2.0 | 15,894 | 0.000692 |
import logging
from functools import wraps
from collections import Sequence, namedtuple, Iterator
from miasm2.jitter.csts import *
from miasm2.core.utils import *
from miasm2.core.bin_stream import bin_stream_vm
from miasm2.core.interval import interval
from miasm2.jitter.emulatedsymbexec import EmulatedSymbExec
from... | ck to the key @name, iff the @callback isn't already
assigned to it"""
if callback not in self.callbacks.get(name, []):
self.callbacks[name] = self.callbacks.get(name, []) + [callback]
def set_callback(self, name, *args):
"Set the list of callback for key 'name'"
self.ca... | sociated to key 'name'"
return self.callbacks.get(name, [])
def remove_callback(self, callback):
"""Remove the callback from the list.
Return the list of empty keys (removed)"""
to_check = set()
for key, cb_list in self.callbacks.items():
try:
cb... |
anguoyang/SMQTK | OLD_ROOT/WebUI/login.py | Python | bsd-3-clause | 3,379 | 0.006807 | """
LICENCE
-------
Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to
KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
"""
import flask
from functools import wraps
from flask import Blueprint, redirect, render_temp... | success")
return f(*args, **kwargs)
flask.f | lash("Access restricted only to login group \"" + role + "\" group :(", "error")
return flask.redirect(url_for("home"))
return decorated_function
return decorator
@mod.route('/login', methods=["get"])
def login():
return render_template("login.html", next=flask.request.args.get("next","... |
MrYsLab/python_banyan | examples/echo_cmdline_client.py | Python | agpl-3.0 | 7,036 | 0.000995 | #!/usr/bin/env python3
"""
echo_cmdline_client.py
Copyright (c) 2018-2019 Alan Yorinks All right reserved.
Python Banyan is free software; you can redistribute it and/or
modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
Version 3 as published by the Free Software Foundation; either
or (at your ... | This must match that of the
banyan_base backplane.
:param number_of_messages: number of message to tra | nsmit
:param process_name: Component identifier
:param loop_time: receive loop sleep time
"""
# initialize the parent
super(EchoCmdClient, self).__init__(back_plane_ip_address=kwargs['back_plane_ip_address'],
subscriber_port=kwargs['s... |
census-instrumentation/opencensus-python | opencensus/common/utils/__init__.py | Python | apache-2.0 | 3,607 | 0 | # Copyright 2018, OpenCensus Authors
#
# 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.apac | he.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 | implied.
# See the License for the specific language governing permissions and
# limitations under the License.
try:
from weakref import WeakMethod
except ImportError:
from opencensus.common.backports import WeakMethod
import calendar
import datetime
import weakref
UTF8 = 'utf-8'
# Max length is 128 bytes f... |
Catofes/musicbox | NEMbox/ui.py | Python | mit | 23,861 | 0.000085 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: omi
# @Date: 2014-08-24 21:51:57
# @Last Modified by: omi
# @Last Modified time: 2015-08-02 20:57:35
'''
网易云音乐 Ui
'''
import hashlib
import re
import curses
import terminalsize
from api import NetEase
from scrollstring import scrollstring, truelen
from stora... | self.update_space()
self.lyric = ''
self.now_lyric = ''
self.tlyric = ''
self.storage = Storage()
self.config = Config()
self.newversion = False
def notify(self, summary, song, album, artist):
if summary != 'disable':
body = '%s\nin %s by %s' ... | name,
artist,
album_name,
quality,
start,
pause=False):
curses.noecho()
# refresh top 2 line
self.screen.move(1, 1)
self.screen.clrtoeol()
self.screen.move(2, 1)
... |
kervinck/gigatron-rom | Core/ROMv2.asm.py | Python | bsd-2-clause | 106,391 | 0.023188 | #!/usr/bin/env python3
#-----------------------------------------------------------------------
#
# Core video, sound and interpreter loop for Gigatron TTL microcomputer
# - 6.25 MHz clock
# - Rendering 160x120 pixels at 6.25MHz with flexible videoline programming
# - Must stay above 31 kHz horizontal sync --> 200 ... | ClearRect
# CopyMemory Nx1 8 s,t,n
# CopyString Nx1 8 s,t
# SetMemory Nx1 8 s,n
# Sprites by scan line 4 reset method? ("videoG"=graphics)
# XXX MODE command (or other interface) to set speed from BASIC
# XXX vPulse widt... | oftware function
# XXX Music sequencer (combined with LED sequencer, but retire soundTimer???)
# XXX Adjustable return for LUP trampolines (in case SYS functions need it)
# XXX Loader: make noise when data comes in
# XXX vCPU: Multiplication (mulShift8?)
# XXX vCPU: Interrupts / Task switching (e.g for clock, LED ... |
mattdangerw/inkscape | share/extensions/test/simplestyle.test.py | Python | gpl-2.0 | 2,041 | 0.016659 | #!/usr/bin/env python
import unittest, sys
sys.path.append('..') # this line allows to import the extension code
from simplestyle import parseColor, parseStyle
class ParseColorTest(unittest.TestCase):
"""Test for single transformations"""
def test_namedcolor(self):
"Parse 'red'"
col = parseC... | %,0%,1%)')
self.failUnlessEqual((127,0,2),col)
def test_rgbcolorpercentdecimal(self):
"Parse 'rgb(66.667%,0%,6.667%)'"
col = parseColor('rgb(66.667%,0%,6.667%)')
self.failUnlessEqual((170, 0, 17),col)
# TODO: This test appears to be broken. parseColor can
# ... | '),col)
def test_spaceinstyle(self):
"Parse 'stop-color: rgb(0,0,0)'"
col = parseStyle('stop-color: rgb(0,0,0)')
self.failUnlessEqual({'stop-color': 'rgb(0,0,0)'},col)
#def test_unknowncolor(self):
# "Parse 'unknown'"
# col = parseColor('unknown')
# self.failUnless... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.