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 |
|---|---|---|---|---|---|---|---|---|
nivbend/bdd_bot | bddbot/test/constants.py | Python | mit | 367 | 0 | "" | "Constant definitions for testing purposes."""
from bddbot.config import TEST_COMMAND
BANK_PATH_1 = "banks/first.bank"
BANK_PATH_2 = "banks/second.bank"
FEATURE_PATH_1 = BANK_PATH_1.replace("bank", "feature")
FEATURE_PATH_2 = BANK_PATH_2.replace("bank", "feature")
(HOST, PORT) = ("bank_server", 0xBDD)
CLIENT = "clien... | ]
|
atombrella/django-rest-framework | tests/test_model_serializer.py | Python | bsd-2-clause | 43,267 | 0.00141 | """
The `ModelSerializer` and `HyperlinkedModelSerializer` classes are essentially
shortcuts for automatically creating serializers based on a given model class.
These tests deal with ensuring that we correctly map the model fields onto
an appropriate set of serializer fields for each case.
"""
from __future__ import ... | non_model_field = serializers.CharField()
class Meta:
| model = OneFieldModel
fields = ('char_field', 'non_model_field')
serializer = TestSerializer(data={
'char_field': 'foo',
'non_model_field': 'bar',
})
serializer.is_valid()
with self.assertRaises(TypeError) as excinfo:
serializer.save... |
google/cyanobyte | test/sampleData/circuitpython/BH1750FVI.py | Python | apache-2.0 | 4,207 | 0.001426 | # Copyright (C) 2020 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # 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.
#
# Auto-generated file for BH1750FVI v0.1.0.
# Generated from peripherals/BH1750FVI.yaml using Cyanobyte Codegen v0.1.0
"""
Class for BH1750FVI
"""
from adafruit_bus_device.i2c_device import I2CDevice
I2C_ADDRESS_35 = 35
I2C_ADDRESS_92 = 92
class BH1750FVI:
"""
Rohm Light Sensor
... |
hizni/vod-systems | vod_systems/vod/urls.py | Python | mit | 6,067 | 0.008076 | from django.conf import settings
from django.conf.urls import url
from django.conf.urls.static import static
from vod import user_views
from vod.alias_id_views import AliasIdListView, AliasIdCreateView, AliasIdUpdateView, AliasIdRetireView
from vod.datatype_views import DataTypeListView, DataTypeCreateView, DataTypeUp... | .validate_username, name='validate_username'),
url(r'^ajax/cleansing-profile-detail/$', helper_views.dataCleansingTemplateFields_asJSON, name='ajax-cleansing-profile-detail'),
url(r'^ajax/models/$', helper_views.modelsInApp, name='app-models'),
]
if settings.DEBUG:
urlpattern | s += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
zestrada/nova-cs498cc | nova/virt/hyperv/snapshotops.py | Python | apache-2.0 | 4,875 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 Cloudbase Solutions Srl
# 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.ap... | src_vhd_path, dest_vhd_path)
i | mage_vhd_path = None
if not src_base_disk_path:
image_vhd_path = dest_vhd_path
else:
basename = os.path.basename(src_base_disk_path)
dest_base_disk_path = os.path.join(export_dir, basename)
LOG.debug(_('Copying base disk %(src_vhd_p... |
DailyActie/Surrogate-Model | 01-codes/OpenMDAO-Framework-dev/openmdao.util/src/openmdao/util/wrkpool.py | Python | mit | 3,630 | 0 | import Queue
import atexit
import logging
import threading
import traceback
class WorkerPool(object):
""" Pool of worker threads; grows as necessary. """
_lock = threading.Lock()
_pool = None # Singleton.
def __init__(self):
self._idle = [] # Queues of idle workers.
self._workers =... | e].is_alive():
logging.debug('WorkerPool: worker join timed-out.')
try:
self._idle.remove(queue)
except ValueError:
pass # Never released due to some other issue...
self._idle = []
self._workers = {}
... | rgs, **kwargs, reply_queue)``
Work replies are of the form:
``(queue, retval, exc, traceback)``
one_shot: bool
If True, the worker will self-release after processing one request.
"""
return WorkerPool.get_instance()._get(one_shot)
def _get(self, one_shot):
... |
jaeilepp/eggie | eggie.py | Python | bsd-2-clause | 1,903 | 0.017867 | #!/usr/bin/env python
#Copyright (c) <2015>, <Jaakko Leppakangas>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#1. Redistributions of source code must retain the above copyright notice, this
#... | ION) HOWEVER CAUSED AND
#ON ANY THEORY OF | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#The views and conclusions contained in the software and documentation are those
#of the authors and should not be inte... |
google-research/google-research | direction_net/dataset.py | Python | apache-2.0 | 15,616 | 0.005635 | # coding=utf-8
# Copyright 2022 The Google Research 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | 1])], -1)
# Convert camera coordinates to world coordinates.
p_world = tf.squeeze(
tf.matmul(pose_c2w[tf.newaxis, tf.newaxis, :],
tf.expand_dims(p_camera_homogeneous, -1)), -1)
return p_world
def overlap_mask(depth1,
pose1_c2w,
depth2,
po... | intrinsics):
"""Compute the overlap masks of two views using triangulation.
The masks have the same shape of the input images. A pixel value is true if it
can be seen by both cameras.
Args:
depth1: [HEIGHT, WIDTH, 1] the depth map of the first view.
pose1_c2w: [3, 4] camera pose matrix (camera to wor... |
openstack/octavia | octavia/certificates/common/local.py | Python | apache-2.0 | 3,779 | 0 | # Copyright (c) 2014 Rackspace US, 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 req... | n import cert
TLS_CERT_DEFAULT = os.environ.get(
'OS_OCTAVIA_TLS_CA_CERT', '/etc/ssl/certs/ssl-cert-snak | eoil.pem'
)
TLS_KEY_DEFAULT = os.environ.get(
'OS_OCTAVIA_TLS_CA_KEY', '/etc/ssl/private/ssl-cert-snakeoil.key'
)
TLS_PKP_DEFAULT = os.environ.get('OS_OCTAVIA_CA_KEY_PASS')
TLS_PASS_AMPS_DEFAULT = os.environ.get('TLS_PASS_AMPS_DEFAULT',
'insecure-key-do-not-use-this-key')
TLS... |
sonjagruen/elephant | elephant/signal_processing.py | Python | bsd-3-clause | 9,104 | 0.00022 | '''
Basic processing procedures for analog signals (e.g., performing a z-score of a signal, or filtering a signal).
:copyright: Copyright 2014-2015 by the Elephant team, see AUTHORS.txt.
:license: Modified BSD, see LICENSE.txt for details.
'''
from __future__ import division, print_function
import numpy as np
import ... | d. When given as Quantity array or NumPy
ndarray, the sampling frequency should be given through the keyword
argument `fs`.
highpass_freq, lowpass_freq : Quantity or float
| High-pass and low-pass cut-off frequencies, respectively. When given as
float, the given value is taken as frequency in Hz.
Filter type is determined depending on values of these arguments:
* highpass_freq only (lowpass_freq = None): highpass filter
* lowpass_freq only (... |
KKfo/captcha_solver | experiment.py | Python | gpl-3.0 | 7,350 | 0.011837 | import requests
from PIL import Image, ImageEnhance, ImageChops, ImageFilter
from io import BytesIO, StringIO
import time
import sys, os
import codecs
url = 'http://d1222391-23d7-46de-abef-73cbb63c1862.levels.pathwar.net'
imgurl = url + '/captcha.php'
headers = { 'Host' : 'd1222391-23d7-46de-abef-73cbb63c1862.levels.... | ="":
key = line[0]
if key not in imgs:
imgs[key] = []
imgs[key].append(Image.open(StringIO.StringIO(line[2:-1].decode("hex"))))
line = datfile.readline()
datfile.close()
# calculate difference with dataset for each boundbox
word = ""
for bound in bounds:
... | ize)[0]*(img.crop(bound).size)[1]*1.0
for key in imgs:
for pattern in imgs[key]:
diff = ImageChops.difference(img.crop(bound), pattern.resize(img.crop(bound).size, Image.NEAREST))
pixels = list(diff.getdata())
samePixCnt = sum(i==0 for i in pixels)
... |
paradiseOffice/Bash_and_Cplus-plus | CPP/full_examples/pyqt/chap03/item.py | Python | gpl-2.0 | 3,660 | 0.005738 | #!/usr/bin/env python3
# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.
# This program or module 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
# version 3 of the Lic... | h
def setDepth(self, depth):
self.__depth = depth
def area(self):
raise NotImplemented
def volume(self):
raise NotImplemented
if __name__ == "__main__":
items = []
items.append(Painting("Cecil Collins", "The Poet", 1941))
items.append(Painting("Cecil Colli | ns", "The Sleeping Fool", 1943))
items.append(Painting("Edvard Munch", "The Scream", 1893))
items.append(Painting("Edvard Munch", "The Sick Child", 1896))
items.append(Painting("Edvard Munch", "The Dance of Life", 1900))
items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917,
... |
stormi/tsunami | src/primaires/salle/masques/coordonnees2d/__init__.py | Python | bsd-3-clause | 3,189 | 0.0044 | # -*-coding:Utf-8 -*
# Copyright (c) 2012 LE GOFF Vincent
# 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 notice, this
# l... | S "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYR | IGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
... |
datastreaming/mflow_nodes | tests/helpers.py | Python | gpl-3.0 | 1,389 | 0.0036 | import json
from mflow_nodes.processors.base import BaseProcessor
from mflow_nodes.stream_node import get_processor_function, get_receiver_function
from mflow_nodes.node_manager import NodeManager
def setup_file_writing_receiver(connect_address, output_filename):
"""
Setup a node that writis the message head... | tput_filename, 'r') as input_file:
test_data = json.load(input_file)
test_data.append(message.get_header())
with open(output_filename, 'w') as output:
output.write(json.dumps(test_data, indent=4))
processor = BaseProcessor()
processor.process_message = process_message
... | odeManager(processor_function=get_processor_function(processor=processor,
connection_address=connect_address),
receiver_function=get_receiver_function(connection_address=connect_address),
processor... |
cvubrugier/rtslib-fb | rtslib/alua.py | Python | apache-2.0 | 15,637 | 0.001151 | '''
Implements the RTS ALUA Target Port Group class.
This file is part of RTSLib.
Copyright (c) 2016 by 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/lice... | pport_active_nonoptimized" % self.path
try:
fwrite(path, str(int(enabled)))
except IOError as e:
raise RTSLibError("Cannot set alua_support_active_nonoptimized: %s" % e)
def _get_alua_support_active_optimized(self):
self._check_self()
path = "%s/alua_support_... | rt_active_optimized" % self.path
try:
fwrite(path, str(int(enabled)))
except IOError as e:
raise RTSLibError("Cannot set alua_support_active_optimized: %s" % e)
def _get_alua_support_offline(self):
self._check_self()
path = "%s/alua_support_offline" % self.pa... |
classam/threepanel | threepanel/dashboard/management/commands/clear_cache.py | Python | agpl-3.0 | 258 | 0.007752 | from django.core.ma | nagement.base import BaseCommand, CommandError
from django.core.cache import cache
class Command(BaseCommand):
help = 'Clears the cache'
def ha | ndle(self, *args, **options):
print("Clearing cache!")
cache.clear()
|
SocialCognitiveSystems/PRIMO | primo2/tests/Inference_test.py | Python | lgpl-3.0 | 13,455 | 0.012337 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of PRIMO2 -- Probabilistic Inference Modules.
# Copyright (C) 2013-2017 Social Cognitive Systems Group,
# Faculty of Technology, Bielefeld University
#
# This program is free software: you can redistribute it and/or modify
# it ... | prinkler", "winter", "rain", "wet_grass"],
["slippery_road", "sprinkler", "wet_grass", "winte | r", "rain"],
["slippery_road", "sprinkler", "wet_grass", "rain", "winter"],
["slippery_road", "sprinkler", "rain", "winter", "wet_grass"],
["slippery_road", "sprinkler", "rain", "wet_grass", "winter"],
["slip... |
FAB4D/humanitas | data_collection/ts/climate/get_climate_data.py | Python | bsd-3-clause | 3,498 | 0.006861 | #---------------------------------
#Joseph Boyd - joseph.boyd@epfl.ch
#---------------------------------
from bs4 import BeautifulSoup
from urllib2 import urlopen
import csv
BASE_URL = 'http://www.tutiempo.net'
PAGE_1 = '/en/Climate/India/IN.html'
PAGE_2 = '/en/Climate/India/IN_2.html'
headings = ['Location', 'Year',... | html = urlopen(BASE_URL + month.a['href']).read()
soup = BeautifulSoup(html, 'lxml')
climate_table = soup.find('table', 'TablaClima')
if climate_table is None:
continue
climate_rows = clim... | indAll('tr')
for row in climate_rows[1:-2]:
data = row.findAll('td')
print_line = [title, year, month_name]
for datum in data:
a = ','.join(datum.findAll(text=True))
... |
benoitsteiner/tensorflow-xsmm | tensorflow/python/ops/linalg/linear_operator_full_matrix.py | Python | apache-2.0 | 6,537 | 0.001836 | # Copyright 2016 The TensorFlow Authors. 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 applica... | x, name="matrix")
dtype = matrix.dtype
if dtype not in allowed_dtypes:
raise TypeError(
"Argument matrix must have dtype in %s. Found: %s"
% (allowed_dtypes, dtype))
if matrix.get_shape().ndims is not None and matrix.get_shape().ndims < 2:
raise ValueError(
"Argu... | % matrix)
def _shape(self):
return self._matrix.get_shape()
def _shape_tensor(self):
return array_ops.shape(self._matrix)
def _matmul(self, x, adjoint=False, adjoint_arg=False):
return linear_operator_util.matmul_with_broadcast(
self._matrix, x, adjoint_a=adjoint, adjoint_b=adjoint_ar... |
saullocastro/pyNastran | pyNastran/op2/dev/op2.py | Python | lgpl-3.0 | 118,219 | 0.000068 | # -*- coding: utf-8 -*-
"""
Some Python tools for reading select data from Nastran .op2 files.
Converted from the Yeti version.
Can read files in big or little endian format.
@author: Tim Widrick
"""
from __future__ import print_function
import sys
import struct
import itertools as it
import warnings
from six import... | n and lit | tle-endian, respectively.
_intstr : string
Either `endian` + 'i4' or `endian` + 'i8'.
_ibytes : integer
Either 4 or 8 (corresponds to `intstr`)
_int32str : string
`endian` + 'i4'.
_label : string
The op2 header label or, if none, None.
... |
JohanComparat/nbody-npt-functions | bin/bin_SMHMr/MD10-pie-plot.py | Python | cc0-1.0 | 5,119 | 0.034186 | import time
t0 = time.time()
import os
import numpy as n
import sys
import glob
import cPickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as p
from scipy.interpolate import interp1d
L_box = 1000./0.6777
tracer_names = n.array(['S8_ELG', 'S8_BG1', 'S8_BG2', 'S5_GAL', 'S8_QSO', 'S6_AGN', 'S5_B... | cer loop
#path_2_tracer_file = tracer_files[0]
for path_2_tracer_file in tr | acer_files:
print path_2_tracer_file
spl_bn = os.path.basename(path_2_tracer_file)[:-5].split('_')
tracer_name = spl_bn[-2]+'_'+spl_bn[-1]
ids = fits.open(path_2_tracer_file)[1].data['line_number']
x_i = positions['x'][ids]/0.6777 - x_observer + x_shift
y_i = positions['y'][ids]/0.6777 - y_obse... |
sissaschool/xmlschema | xmlschema/namespaces.py | Python | mit | 10,509 | 0.001713 | #
# Copyright (c), 2016-2020, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author Davide Brunato <brunato@... | rong format: %r" % qname)
except TypeError:
raise XMLSchemaTypeError("the argument 'qname' must be a string-like object")
for prefix, uri in sorted(self._namespaces.items(), reverse=True):
if uri == namespace:
return '%s:%s' % (prefix, local_part) if prefix else ... | tr]]] = None) -> str:
"""
Converts a QName in prefixed format or a local name to the extended QName format.
Local names are converted only if a default namespace is included in the instance.
If a *name_table* is provided a local name is mapped to the default namespace
only if not... |
1uk/3tsqd | classes/Player.py | Python | mit | 198 | 0.010101 | import pygame
from pyga | me import event
class Player:
def __init__(self, p_id) | :
self.points = None
self.p_id = p_id
def turn(self, nr):
return pygame.event.get()
|
alexkolar/home-assistant | homeassistant/components/ifttt.py | Python | mit | 1,789 | 0 | """
homeassistant.components.ifttt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This component enable you to trigger Maker IFTTT recipes.
Check https://ifttt.com/maker for details.
Configuration:
To use Maker IFTTT you will need to add something like the following to your
config/configuration.yaml.
ifttt:
key: xxxxx-x-xxxxxxxxxx... | UE3: value3,
}
hass.services.call(DOMAIN, SERVICE_TRIGGER, data)
def setup(hass, config):
""" Setup the ifttt service component """
if not validate_config(config, {DOMAIN: ['key']}, _LOGGER):
return False
key = config[DOMAIN]['key']
def trigger_service(call):
""" Handle iftt... | s. """
event = call.data.get(ATTR_EVENT)
value1 = call.data.get(ATTR_VALUE1)
value2 = call.data.get(ATTR_VALUE2)
value3 = call.data.get(ATTR_VALUE3)
if event is None:
return
try:
import pyfttt as pyfttt
pyfttt.send_event(key, event, va... |
wenxichen/tensorflow_yolo2 | src/imagenet/imagenet_train_darknet.py | Python | mit | 4,911 | 0.001833 | """Train ILSVRC2017 Data using homemade scripts."""
import cv2
import os
import math
import tensorflow as tf
from multiprocessing import Process, Queue
import os
import sys
FILE_DIR = os.path.dirname(__file__)
sys.path.append(FILE_DIR + '/../')
import config as cfg
from img_dataset.ilsvrc2017_cls_multithread import ... | batch_size=64)
# set up child process for getting validation data
queue_in = Queue()
queue_out = Queue()
val_data_process = Process(target=get_validat | ion_process,
args=(val_imdb, queue_in, queue_out))
val_data_process.start()
queue_in.put(True) # start getting the first batch
CKPTS_DIR = cfg.get_ckpts_dir('darknet19', imdb.name)
TENSORBOARD_TRAIN_DIR, TENSORBOARD_VAL_DIR = cfg.get_output_tb_dir(
'darknet19', imdb.name)
input_data =... |
cournape/talkbox | scikits/talkbox/linpred/__init__.py | Python | mit | 156 | 0.019231 | __all__ = []
from common import *
im | port common
__all__ += common.__all__
| from levinson_lpc import *
import levinson_lpc
__all__ += levinson_lpc.__all__
|
EnTeQuAk/pytest-django-casperjs | conftest.py | Python | bsd-3-clause | 1,003 | 0 | import os
import os.path
def pytest_configure(config):
test_db = os.environ.get('DB', 'sqlite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'pytest_django_casperjs.tests.settings' # noqa
from django.conf import settings
if test_db == 'postgresql':
settings.DATABASES['default'].update({
... | tings.DATABASES['default'].update({
'ENGINE': 'django.db.backends.mysql',
'USER': 'root',
'NAME': 'pytest_django_casperjs_test',
})
elif test_db == 'sqlite':
settings.DATABASES['default'].update({
'ENGINE': 'djang | o.db.backends.sqlite3',
'NAME': ':memory:',
})
else:
raise RuntimeError('Unsupported database configuration %s' % test_db)
|
nan86150/ImageFusion | src/main/fusion_dwb.py | Python | mit | 2,018 | 0.002973 | #!/usr/bin/env python
# encoding: utf-8
from ImageFusion import ImageFusion
from PIL import Image
import numpy as np
import pylab as plt
import pywt
class FusionDWB(ImageFusion):
""" Image Fusion based wavelet """
def __init__(self, imageNames = None, zt=2, ap=2, mp=0):
self._imageNames = imageNames... | pywt.waverec2(coeffsFusion, 'db1')
return self._fusionImage
def plot(self):
plt.figure(0)
plt.gray()
plt.subplot(131)
plt.imshow(self._images[0])
plt.subplot(132)
plt.imshow(self._images[1])
plt.subplo | t(133)
plt.imshow(self._fusionImage)
plt.show()
if __name__ == '__main__':
IMAGEPATH = "../../images/multifocus/"
imLists = [IMAGEPATH+"a01_1.tif",IMAGEPATH+"a01_2.tif"]
fu = FusionDWB(imLists)
fu.fusion()
fu.plot()
|
abarnert/pyinterval | test/test_basic.py | Python | bsd-3-clause | 13,302 | 0.005488 | # Copyright (c) 2008, Stefano Taschini <taschini@ieee.org>
# All rights reserved.
# See LICENSE for details.
import unittest
from interval import interval, fpu
class FpuTestCase(unittest.TestCase):
def test_third(self):
"Nearest rounding of 1/3 is downwards."
self.assertEqual(1/3.0, fpu.down(lam... | interval(0, [1, [2, 3]]))
self.assertRaises(interval.ComponentError, lambda: interval['a', 1])
def test_canonical_constructor(self):
| self.assertEqual(interval([1, 3], [4, 6], [2, 5], 9), ((1, 6), (9, 9)))
self.assertEqual(interval[2 ** (52 + 1) - 1], interval[9007199254740991.0])
self.assertEqual(interval[2 ** (52 + 1) + 1], interval[4503599627370496 * 2.0, 4503599627370497 * 2.0])
self.assertEqual(interval[-2 ** (52 + 1... |
111pontes/ydk-py | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_clns_isis_datatypes.py | Python | apache-2.0 | 1,675 | 0.014328 | """ Cisco_IOS_XR_clns_isis_datatypes
This module contains a collection of generally useful
derived YANG data types.
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.
"""
import re
import collections
from enum import Enum
from ydk.types import Empt | y, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk.errors import YPYError, YPYModelError
class IsisAddressFamilyEnum(Enum):
"""
IsisAddressFamilyEnum
Isis address family
.. data:: ipv4 = 0
IPv4
.. data:: ipv6 = 1
IPv6
"""
| ipv4 = 0
ipv6 = 1
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_clns_isis_datatypes as meta
return meta._meta_table['IsisAddressFamilyEnum']
class IsisInternalLevelEnum(Enum):
"""
IsisInternalLevelEnum
Isis internal level
.. d... |
ThreatConnect-Inc/tcex | tcex/api/tc/v2/notifications/notifications.py | Python | apache-2.0 | 3,187 | 0.000628 | """TcEx Notification Module"""
# standard library
import json
import logging
from typing import TYPE_CHECKING
# first-party
from tcex.exit.error_codes import handle_error
if TYPE_CHECKING:
# third-pa | rty
from requests import Session
# get tcex logger
logger = logging.getLogger('tcex')
class Notifications:
"""TcEx Notification Class"""
def __init__(self, session_tc: 'Session'):
"""Initialize the Class properties.
Args:
session_tc: An configured instance of request.Session... | self._recipients = None
self._priority = 'Low'
self.log = logger
def recipients(self, notification_type, recipients, priority='Low'):
"""Set vars for the passed in data. Used for one or more recipient notification.
.. code-block:: javascript
{
"notifica... |
MDAnalysis/mdanalysis | package/MDAnalysis/__init__.py | Python | gpl-2.0 | 7,425 | 0.002559 | # -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under t... | sses are declared.
_READERS = {}
_READER_HINTS = {}
_SINGLEFRAME_WRITERS = {}
_MULTIFRAME_WRITERS = {}
_PARSERS = {}
_PARSER_HINTS = {}
_SELECTION_WRITERS = {}
_CONVERTERS = {}
# Registry of TopologyAttributes
_TOPOLOGY_ATTRS = {} # {attrname: cls}
_TOPOLOGY_TRANSPLA | NTS = {} # {name: [attrname, method, transplant class]}
_TOPOLOGY_ATTRNAMES = {} # {lower case name w/o _ : name}
# custom exceptions and warnings
from .exceptions import (
SelectionError, NoDataError, ApplicationError, SelectionWarning,
MissingDataWarning, ConversionWarning, FileFormatWarning,
StreamW... |
dnxbjyj/python-basic | gui/wxpython/wxPython-demo-4.0.1/samples/dataview/CustomRenderer.py | Python | mit | 5,439 | 0.005516 | import sys
import wx
import wx.dataview as dv
#import os; print('PID:'+str(os.getpid())); raw_input("Press enter...")
#----------------------------------------------------------------------
class MyCustomRenderer(dv.DataVi | ewCustomRenderer):
def __init__(self, log, *args, **kw):
dv.DataViewCustomRenderer.__init__(self, *args, **kw)
self.log = log
self.value = None
def SetValue(self, value):
#self.log.write('MyCustomRenderer.SetValue: %s\n' % value)
self.value = v | alue
return True
def GetValue(self):
#self.log.write('MyCustomRenderer.GetValue\n')
return self.value
def GetSize(self):
# Return the size needed to display the value. The renderer
# has a helper function we can use for measuring text that is
# aware of any cus... |
westernx/sgfs | sgfs/actions/create_structure.py | Python | bsd-3-clause | 1,165 | 0.009442 | from sgfs import SGFS
from sgactions.utils import notify, progress, alert
def run_create(**kwargs):
_run(False, **kwargs)
def run_preview(**kwargs):
_run(True, **kwargs)
def _run(dry_run, entity_type, selected_ids, **kwargs):
title='Preview Folders' if dry_run else 'Creating Folders'
verb | = 'previewing' if dry_run else 'creating'
progress(message=('Previewing' if dry_run else 'Creating') + ' folders for %s %ss; please wait...' % (len(selected_ids), entity_type))
sgfs = SGFS()
entities = sgfs.session.merge([dict(type=entity_type, id=id_) for id_ in selected_ids])
heirarchy = sgfs.... | ion.fetch_core(heirarchy)
command_log = sgfs.create_structure(entities, dry_run=dry_run)
if command_log:
details = '\n'.join(command_log)
if dry_run:
alert(title='Folder Preview', message=details)
else:
notify(
message='Created folders fo... |
boweeb/nhweb | config/settings/common.py | Python | bsd-3-clause | 9,076 | 0.001102 | # -*- coding: utf-8 -*-
"""
Django settings for nhweb project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from __future__ import absolute_import, unicode_liter... | are.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
# MIGRATIONS CONFIGURATION
# -------------------------------------------------------------------------... | See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = env.bool("DJANGO_DEBUG", False)
# FIXTURE CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS
FIXTURE_DIRS = (
str(A... |
gregbillock/Spectrum-Access-System | src/prop/model.py | Python | apache-2.0 | 6,985 | 0.013314 | # Copyright 2017 SAS Project Authors. 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... | 2, f, 0.5)
J = ehata_loss - itm_loss
pri | nt 'Got ehata=%f itm=%f J=%f' % (ehata_loss, itm_loss, J)
if J < 0.0:
J = 0.0
return self.ITM_AdjustedPropagationLoss(lat1, lng1, h1, lat2, lng2, h2, f, 0.5) + J
def LandClassification(self, lat, lng):
code = self.nlcdIndx.NlcdCode(lat, lng)
return self.nlcdIndx.NlcdLandCategory(code)
... |
pytest-dev/pytest-bdd | tests/feature/test_outline.py | Python | mit | 5,878 | 0.00051 | """Scenario Outline tests."""
import textwrap
from pytest_bdd.utils import collect_dumped_objects
from tests.utils import assert_outcomes
STEPS = """\
from pytest_bdd import parsers, given, when, then
from pytest_bdd.utils import dump_obj
@given(parsers.parse("there are {start:d} cucumbers"), target_fixture="cucumb... | int)
dump_obj(start)
return {"start": start}
@when(parsers.parse("I eat {eat:g} cucumbers"))
def eat_cucumbers(cucumbers, eat):
assert isinstance(eat, float)
dump_obj(eat)
cucumbers["eat"] = eat
@then(parsers.parse("I should have {left} cucumbers"))
def should_have_left_cucumbers(cucumbers, left... | ert isinstance(left, str)
dump_obj(left)
assert cucumbers["start"] - cucumbers["eat"] == int(left)
"""
def test_outlined(testdir):
testdir.makefile(
".feature",
outline=textwrap.dedent(
"""\
Feature: Outline
Scenario Outline: Outlined given, when, t... |
benpicco/mate-deskbar-applet | deskbar/handlers/calculator.py | Python | gpl-2.0 | 8,080 | 0.017946 | #
# calculator.py : A calculator module for the deskbar applet.
#
# Copyright (C) 2008 by Johannes Buchner
# Copyright (C) 2007 by Michael Hofmann
# Copyright (C) 2006 by Callum McKenzie
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License... | ("{", "("), ("]", ")"), ("}", ")")):
scrubbedquery = scrubbedquery.replace (c1, c2)
answer = eval (scrubbedquery, restricted_dictionary)
# Try and avoid echoing back simple numbers. Note that this
# doesn't work well for floating point, e.g. '3.' behaves badly.
... | s check because the eval can return function objects
# when we are halfway through typing the expression.
if isinstance (answer, (float, int, long, str)):
return answer
else:
return None
except Exception, e:
LOGGER.debug (str(e))
... |
OddBloke/moore | matches/migrations/0001_initial.py | Python | agpl-3.0 | 12,520 | 0.006709 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Card'
db.create_table('matches_card', (
('id', self.gf('django.db.models.field... | 'Role'
db.create_table('matches_role', (
('description', self.gf('django.db.models.fields.CharField')(max_length=255, primary_ke | y=True)),
))
db.send_create_signal('matches', ['Role'])
# Adding model 'Participation'
db.create_table('matches_participation', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('event', self.gf('django.db.models.fields.related.ForeignKey... |
lesserwhirls/scipy-cwt | scipy/sparse/construct.py | Python | bsd-3-clause | 12,885 | 0.006054 | """Functions to construct sparse matrices
"""
__docformat__ = "restructuredtext en"
__all__ = [ 'spdiags', 'eye', 'identity', 'kron', 'kronsum',
'hstack', 'vstack', 'bmat', 'rand']
from warnings import warn
import numpy as np
from sputils import upcast
from csr import csr_matrix
from csc import csc_m... | e=(m,n)).asformat(format | )
def identity(n, dtype='d', format=None):
"""Identity matrix in sparse format
Returns an identity matrix with shape (n,n) using a given
sparse format and dtype.
Parameters
----------
n : integer
Shape of the identity matrix.
dtype :
Data type of the matrix
format : st... |
12019/pyscard | smartcard/wx/APDUHexValidator.py | Python | lgpl-2.1 | 2,088 | 0 | # -*- coding: iso-8859-15 -*-
"""
A wxValidator that matches APDU in hexadecimal such as:
A4 A0 00 00 02
A4A0000002
__author__ = "http://www.gemalto.com"
Copyright 2001-20 | 10 gemalto
Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com
This file is part of pyscard.
pyscard 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.1 of the License, or
(at your option) any later version.
pyscard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even th... |
openstack/ironic-inspector | ironic_inspector/plugins/local_link_connection.py | Python | apache-2.0 | 6,493 | 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 the... | alid
will be saved into the local link connection info port id and switch id
fields on the Ironic port that represents that NIC.
"""
def _get_local_link_patch(self, tlv_type, tlv_value, port, node_info):
try:
data = bytearray(binascii.unhexlify(tlv_value))
except TypeError:
... | LOG.warning("TLV value for TLV type %d not in correct"
"format, ensure TLV value is in "
"hexidecimal format when sent to "
"inspector", tlv_type, node_info=node_info)
return
item = value = None
if tlv_type == t... |
miquelcampos/GEAR_mc | gear/xsi/curve.py | Python | lgpl-3.0 | 14,878 | 0.004772 | '''
This file is part of GEAR_mc.
GEAR_mc is a fork of Jeremie Passerin's GEAR project.
GEAR 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 3 of the License, or
(at your option) any later version.
This program 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 Lesser General Public... |
sim1234/Odtwarzacz | prog.py | Python | gpl-3.0 | 4,653 | 0.012261 | ## Copyright (c) 2012 Szymon Zmilczak
##
##
## This file is part of Odtwarzacz.
##
## Odtwarzacz is free software; you c | an redistribute it and/or modi | fy
## 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 option) any later version.
##
## Odtwarzacz is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the im... |
google/smbios-validation-tool | dmiparse/dmiparse_test.py | Python | apache-2.0 | 3,929 | 0.002036 | # Lint as: python3
"""Unit tests for dmiparse."""
import os
import dmiparse
from google3.pyglib import resources
from google3.testing.pybase import googletest
TEST_PATH = 'google3/third_party/py/dmiparse/test_data'
class DmiParserTest(googletest.TestCase):
def setUp(self):
super(DmiParserTest, self).setUp(... |
self.assertEqual([
'WLYDCRB.86B.WR.64.2019.19.3.03.1837', '0. 0. 0', '4:2.1.21', 'N/A',
'FRU: Ver 1.21', 'N/A', 'N/A'
], oem_specific_record.props[ | 'Strings'].items)
def testDmiParseReturnsValidGroups(self):
_, groups = dmiparse.DmiParser(self.data_file).parse()
self.assertIn(2, groups)
self.assertEqual(['0x0002'], groups[2])
self.assertIn(14, groups)
self.assertEqual(['0x0125', '0x0126'], groups[14])
if __name__ == '__main__':
googlete... |
wcmckee/brobeurdotcom | cache/.mako.tmp/index.tmpl.py | Python | mit | 5,371 | 0.003351 | # -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1440369075.543512
_enable_loop = True
_template_filename = u'themes/monospace/templates/index.tmpl'
_template_uri = u'index.tmpl'
_source_... | 24, "97": 24, "98": 26, "99": 28, "100": 28, "101": 28, "102" | : 29, "103": 29, "104": 30, "105": 30, "111": 105}, "uri": "index.tmpl", "filename": "themes/monospace/templates/index.tmpl"}
__M_END_METADATA
"""
|
beraldoleal/entendaobrasil | scripts/import.py | Python | gpl-2.0 | 642 | 0.007788 | #!/usr/bin/env python
from api.camara.orgaos import *
from api.camara.deputados import *
from core.models import *
import django
django.setup()
## Orgaos Webservice
orgaos = OrgaosCamara()
orgaos.importar_tipos_orgaos()
orgaos.importar_orgaos()
orga | os.importar_cargos()
## Deputados Webservice
deputados = DeputadosCamara()
deputados.importar_partidos()
deputados.importar_deputados()
#deputados.importar_detalhes_deputados()
# Google Images download
#for parlamentar in Parlamentar.objects.all():
# parlamentar.download_photos()
# Wikipedia data
#for parlamenta... | in Parlamentar.objects.all():
# parlamentar.get_wikipedia_data()
|
staslev/beam | sdks/python/apache_beam/io/gcp/internal/clients/storage/storage_v1_messages.py | Python | apache-2.0 | 78,320 | 0.004941 | #
# 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... | sages.Variant.INT32)
action = _messages.MessageField('ActionValue', 1)
condition = _messages.MessageField('ConditionValue', 2)
rule = _messages.MessageField('RuleValueListEntry', 1, repeated=True)
class LoggingValue(_messages.Message):
"""The bucket's logging configuration, which defines the | destination
bucket and optional name prefix for the current bucket's logs.
Fields:
logBucket: The destination bucket where the current bucket's logs should
be placed.
logObjectPrefix: A prefix for log object names.
"""
logBucket = _messages.StringField(1)
logObjectPrefix = _me... |
Osmose/kitsune | kitsune/search/api.py | Python | bsd-3-clause | 4,930 | 0.00142 | from django.conf import settings
from rest_framework import serializers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from kitsune.products.models import Product
from kitsune.questions.models import Question, QuestionMappingType
from kitsune.questions.api import QuestionS... | xes(es_utils.read_index('default')))
data = serializer.validated_data
return Response({
| 'questions': _question_suggestions(
searcher, data['q'], data['locale'], data['product'], data['max_questions']),
'documents': _document_suggestions(
searcher, data['q'], data['locale'], data['product'], data['max_documents']),
})
def _question_suggestions(searcher, text, locale... |
nkoech/csacompendium | csacompendium/csa_practice/api/practicelevel/practicelevelviews.py | Python | mit | 2,046 | 0.002444 | from csacompendium.csa_practice.models import PracticeLevel
from csacompendium.utils.pagination import APILimitOffsetPagination
from csacompendium.utils.permissions import IsOwnerOrReadOnly
from csacompendium.utils.viewsutils import DetailViewUpdateDelete, CreateAPIViewHook
from rest_framework.filters import DjangoFilt... | ):
"""
Updates a record.
"""
queryset = PracticeLevel.objects.all()
serializer_class = practice_level_serializer['PracticeLevelDetailSerializer']
permission_classes = [IsAuthenticated, IsAdminUser]
lookup_field = 'slug'
return {
| 'PracticeLevelListAPIView': PracticeLevelListAPIView,
'PracticeLevelDetailAPIView': PracticeLevelDetailAPIView,
'PracticeLevelCreateAPIView': PracticeLevelCreateAPIView
}
|
toonn/capselai | clustering/augmented_dendrogram.py | Python | bsd-2-clause | 540 | 0.007407 | from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as p | lt
def augmented_dendrogram(*args, **kwargs):
ddata = dendrogram(*args, **kwargs)
if not kwargs.get('no_plot', False):
for i, d in zip(ddata['icoord'], ddata['dcoord']):
x = 0.5 * sum(i[1:3])
y = d[1]
#plt.plot(x, y, 'ro')
plt.annotate("%.3g" % y, (x, y... | xt=(0, -8),
textcoords='offset points',
va='top', ha='center')
return ddata
|
EvilDako/PyTraining | fixture/session.py | Python | gpl-2.0 | 1,421 | 0.003519 | __author__ = 'dako'
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, username, password):
wd = self.app.wd
self.app.open_home_page()
wd.find_element_by_name("user").click()
wd.find_element_by_name("user").clear()
wd.find_element_by_... | ss_selector('input[type="submit"]').click()
def logout(self):
wd = self.app.wd
wd.find_element_by_link_text("Logout").click()
def is_logged_in(sel | f):
wd = self.app.wd
return len(wd.find_elements_by_link_text("Logout")) > 0
def is_logged_in_as(self, username):
wd = self.app.wd
return self.get_logged_user() == username
def get_logged_user(self):
wd = self.app.wd
return wd.find_element_by_xpath("//div/div[1]... |
ADEQUATeDQ/portalmonitor | odpw/core/model.py | Python | gpl-3.0 | 12,953 | 0.012738 | from sqlalchemy import Column, String, Integer, ForeignKey, SmallInteger, TIMESTAMP, BigInteger, ForeignKeyConstraint, \
Boolean, func, select, Float, distinct
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import backref
from sqlalchemy.orm i... | = tmp+"licensedist"
tab_isodist= tmp+"lice | nsedist"
tab_datasets=tmp+'datasets'
tab_datasetsquality=tmp+'datasetsquality'
tab_datasetsdata=tmp+'datasetsdata'
tab_resources=tmp+'metaresources'
tab_resourcesinfo=tmp+'resourcesinfo'
tab_resourcescrawllog=tmp+'resourcescrawllog'
tab_organisations=tmp+'organisations'
tab_organisationssnapshot=tmp+'organisationsn... |
EmreAtes/spack | var/spack/repos/builtin/packages/stc/package.py | Python | lgpl-2.1 | 1,737 | 0.000576 | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | ):
"""STC: The Swift-Turbine Compiler"""
homepage = 'http://swift-lang.org/Swift-T'
url = 'http://swift-lang.github.io/swift-t-downloads/stc-0.7.3.tar.gz'
version('0.7.3', '6bf769f406f6c33d1c134521373718d3')
depends_on('java')
depends_on('ant')
depends_on('turbine')
depends_on('z... | configure_args(self):
args = ['--with-turbine=' + self.spec['turbine'].prefix]
return args
|
babble/babble | include/jython/Lib/test/test_trace.py | Python | apache-2.0 | 21,728 | 0.005339 | # Testing the line trace facility.
from test import test_support
import unittest
import sys
import difflib
# A very basic example. If this fails, we're in deep trouble.
def basic():
return 1
basic.events = [(0, 'call'),
(1, 'line'),
(1, 'return')]
# Many of the tests below are t... | No code
# exists for it, so the line numbers skip directly from "del x"
# to "x = 1".
def arigo_example():
x = 1
del x
while 0:
pass
x = 1
arigo_example.events = [(0, 'call'),
(1, 'line'),
(2, 'line'),
(5, 'line'),
... | ne instruction get traced:
def one_instr_line():
x = 1
del x
x = 1
one_instr_line.events = [(0, 'call'),
(1, 'line'),
(2, 'line'),
(3, 'line'),
(3, 'return')]
def no_pop_tops(): # 0
x = 1 ... |
wieden-kennedy/autoscalebot | autoscalebot/tests.py | Python | bsd-3-clause | 21,789 | 0.001056 | from copy import copy
import datetime
import time
import urllib2
from nose.tools import assert_equals
from nose.plugins.skip import SkipTest
from autoscalebot import TOO_LOW, JUST_RIGHT, TOO_HIGH
from autoscalebot.conf import AutoscaleSettings
from autoscalebot.models import HerokuAutoscaler
class TestSettings(Autosc... | y(TOO_LOW)
self.test_scaler.add_to_history(TOO_LOW)
self.test_scaler.add_to_history(TOO_LOW)
self.test_scaler.add_to_hi | story(TOO_LOW)
self.test_scaler.add_to_history(TOO_LOW)
assert_equals(self.test_scaler.needs_scale_down, True)
def test_scale_up(self):
assert_equals(self.test_scaler.num_dynos, 1)
self.test_scaler.scale_up()
assert_equals(self.test_scaler.num_dynos, 2)
def test_scale_u... |
vgamula/sp | server/accounts/forms.py | Python | mit | 1,763 | 0 | import trafaret as t
from server.c | ore.passwords import generate_password, check_password
from server.core.forms import TrafaretForm, TrafaretErro | r
class RegistrationForm(TrafaretForm):
fields = t.Dict({
t.Key('email'): t.Email(),
t.Key('password'): t.String(max_length=255),
t.Key('confirm'): t.String(max_length=255),
t.Key('accept_tos'): t.StrBool(),
})
async def extra_validation(self):
errors = {}
... |
robwarm/gpaw-symm | gpaw/__init__.py | Python | gpl-3.0 | 10,531 | 0.001045 | # Copyright (C) 2003 CAMP
# Please see the accompanying LICENSE file for further information.
"""Main gpaw module."""
import os
import sys
try:
from distutils.util import get_platform
except ImportError:
modulepath = os.environ.get('GPAW_GET_PLATFORM')
if modulepath is None:
errmsg = ('Error: Cou... | assert len(parsize_domain) == 3
elif arg.startswith('--state-parallelization='):
parsize_bands = int | (arg.split('=')[1])
elif arg.startswith('--sl_default='):
# --sl_default=nprow,npcol,mb,cpus_per_node
# use 'd' for the default of one or more of the parameters
# --sl_default=default to use all default values
sl_args = [n for n in arg.split('=')[1].split(',')]
if len(sl_args... |
xkollar/spacewalk | backend/server/rhnServer/search_notify.py | Python | gpl-2.0 | 1,394 | 0.001435 | #
# Copyright (c) 2008--2015 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a c... | censes/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2 | . No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
# Sends notification to search-server that it should update server index
#
import xmlrpclib
from spacewalk.common.rhnLog import log_error
class SearchNotify:
def __init__(self, ho... |
AnyWi/py-ubnt-airviewer | airviewer.py | Python | bsd-2-clause | 11,342 | 0.0082 | #
# Copyright (c) 2016, AnyWi Technologies BV
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditi... | 0000,2407000000\n") # 5 MHz
#writeline("REQUEST RANGE: 2402000000,2412000000\n") # 10 MHz
#writeline("REQUEST RANGE: 2402000000,2417000000\n") # 15 MHz
#writeline("REQUEST RANGE: 2402000000,2422000000\n") # 20 Mhz
#writeline("REQUEST RANGE: 2402000000,2477000000\n") # (ch 1-11 - US allocation)
#wri... | (ch 1-13 - UK allocation)
#writeline("REQUEST RANGE: 2402000000,2497000000\n") # (ch 1-14)
writeline("REQUEST RANGE: 5150000000,5250000000\n") # 5.150-5.250 (U-NII Lower Band)
#writeline("REQUEST RANGE: 5250000000,5350000000\n") # 5.250-5.350 (U-NII Middle Band)
#writeline("REQUEST RANGE: 5470000000,57... |
youfou/wxpy | wxpy/ext/xiaoi.py | Python | mit | 3,546 | 0.000897 | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_wi... | enhance_connection(self.session)
def _make_signature(self):
"""
生成请求签名
"""
# 40位随机字符
# nonce = "".join([str(randint(0, 9)) for _ in range(40)])
nonce = "4103657107305326101203516108016101205331"
sha1 = "{0}:{1}:{2}".format(self.key, self.realm, self.secr... | a2 = "{0}:{1}".format(self.http_method, self.uri).encode("utf-8")
sha2 = hashlib.sha1(sha2).hexdigest()
signature = "{0}:{1}:{2}".format(sha1, nonce, sha2).encode("utf-8")
signature = hashlib.sha1(signature).hexdigest()
ret = collections.namedtuple("signature_return", "signature nonce"... |
Richert/BrainNetworks | BasalGanglia/stn_gpe_str_opt.py | Python | apache-2.0 | 14,060 | 0.004481 | import os
import warnings
import numpy as np
from pyrates.utility.genetic_algorithm import CGSGeneticAlgorithm
from pandas import DataFrame, read_hdf
from copy import deepcopy
class CustomGOA(CGSGeneticAlgorithm):
def eval_fitness(self, target: list, **kwargs):
# define simulation conditions
wor... | ')
# calculate fitness
for gene_id in param_grid.index:
self.pop.at[gene_id, 'fitness'] = 1.0 / results_tmp.at[gene_id, 'fitness']
self.pop.at[gene_id, 'results'] = [results_tmp.at[gene_id, v] | for v in result_vars]
# set fitness of invalid parametrizations
#for gene_id in invalid_params.index:
# self.pop.at[gene_id, 'fitness'] = 0.0
# self.pop.at[gene_id, 'results'] = [0. for _ in result_vars]
def fitness(y, t):
y = np.asarray(y).flatten()
t = np.asarray(t).fl... |
Asana/python-asana | asana/resources/gen/webhooks.py | Python | mit | 7,089 | 0.00227 | # coding=utf-8
class _Webhooks:
def __init__(self, client=None):
self.client = client
def create_webhook(self, params=None, **options):
"""Establish a webhook
:param Object params: Parameters for the request
:param **options
- opt_fields {list[str]}: Defines fields... | ther times requests retur | n more information than you may need. This option allows you to list the exact set of fields that the API should be sure to return for the objects. The field names should be provided as paths, described below. The id of included objects will always be returned, regardless of the field options.
- opt_pretty ... |
GbalsaC/bitnamiP | venv/src/codejail/codejail/tests/test_safe_exec.py | Python | agpl-3.0 | 4,712 | 0 | """Test safe_exec.py"""
from cStringIO import StringIO
import os.path
import textwrap
import unittest
import zipfile
from nose.plugins.skip import SkipTest
from codejail import safe_exec
class SafeExecTests(unittest.TestCase):
"""The tests for `safe_exec`, to be mixed into specific test classes."""
# Safe... | st__ = True
def setUp(self):
# If safe_exec is actually an alias to not_safe_exec, then there's no
# point running | these tests.
if safe_exec.UNSAFE: # pragma: no cover
raise SkipTest
def safe_exec(self, *args, **kwargs):
safe_exec.not_safe_exec(*args, **kwargs)
|
GearsAD/semisorted_arnerve | arnerve_bot/arnerve_bot/LCMRover.py | Python | mit | 2,720 | 0.009926 | '''
Created on Dec 3, 2014
@author: gearsad
'''
import sys
from roverpylot import rover
from bot_update_t import bot_update_t
from bot_control_command_t import bot_control_command_t
import lcm
# Try to start OpenCV for video
try:
import cv
except:
cv = None
class LCMRover(rover.Rover):
'''
A rover ... | eadVelright)
print "Setting the treads to {0}, {1}".format(controlParams.botTreadVelLeft, controlParams.botTreadVelright)
if self.__lightsOn != controlPa | rams.isLightsOn:
if controlParams.isLightsOn != 0:
self.turnLightsOn()
else:
self.turnLightsOff()
self.__lightsOn = controlParams.isLightsOn
if self.__infraredOn != controlParams.isInfraredOn:
if controlParams.isInfraredOn != 0:
... |
tpmccauley/invenio-previewer-ispy | tests/__init__.py | Python | gpl-2.0 | 871 | 0.001148 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio-Previewer-ISPY
# Copyright (C) 2014 CERN
#
# Invenio-Previewer-ISPY 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, o... | long with Invenio-Previewer-ISPY; if not, write to the Free Softw | are Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Invenio-Previewer-ISPY testsuite."""
|
jgeewax/gcloud-python | error_reporting/google/cloud/error_reporting/client.py | Python | apache-2.0 | 10,193 | 0 | # Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | },
'message': '{0}'.format(message)
}
if self.version:
paylo | ad['serviceContext']['version'] = self.version
if report_location or http_context or user:
payload['context'] = {}
if report_location:
payload['context']['reportLocation'] = report_location
if http_context:
http_context_dict = http_context.__dict__
... |
yonglong009/pycharmNoteBook | lean_python3/dive_into_p3/tanslate.py | Python | gpl-3.0 | 1,160 | 0.025862 | #!/usr/bin/env python3
import urllib
| import codecs
from bs4 import BeautifulSoup
from sys import argv
import re,time
class Translate:
def start(self):
self._get_html_sourse()
s | elf._get_content("enc")
self._remove_tag()
self.print_result()
def _get_html_sourse(self):
word=argv[1] if len(argv)>1 else ''
url="http://dict.baidu.com/s?wd=%s&tn=dict" % word
self.htmlsourse=urllib.unicode(urllib.urlopen(url).read(),"gb2312","ignore").encode("utf-8","ign... |
rajalokan/keystone | keystone/tests/unit/test_cli.py | Python | apache-2.0 | 57,490 | 0.00007 | # Copyright 2014 IBM Corp.
#
# 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, s... | "methods": ["password"],
"password": {
"user": {
"name": bootstrap.username,
"password": bootstrap.password,
"domain": {
"id": CONF.identity.default_domain_id
| }
}
}
}
}
auth_response = v3_token_controller.authenticate_for_token(
self.make_request(), v3_password_data)
token = auth_response.headers['X-Subject-Token']
self._do_test_bootstrap(bootstrap)
# build validation reques... |
Tocknicsu/nctuoj_contest | backend/handler/index.py | Python | apache-2.0 | 195 | 0.010256 | import tornado
im | port tornado.gen
from req import Service
from req import ApiRequestHandler
class Index(ApiRequestHandler):
@tornado.gen.coroutine
def get(self):
self.rend | er()
|
forScie/FrankenCipher | franken.py | Python | gpl-3.0 | 13,770 | 0.030719 | #!/usr/bin/python
# FRANKEN CIPHER
# WRITTEN FOR ACADEMIC PURPOSES
#
# AUTHORED BY: Dan C and james@forscience.xyz
#
# THIS SCRIPT IS WRITTEN TO DEMONSTRATE A UNIQUE ENCRYPTION ALGORITHM THAT IS INSPIRED BY A NUMBER
# OF EXISTING ALGORITHMS.
# THE SCRIPT IS WRITTEN ENTIRELY FOR ACADEMIC PURPOSES. NO WARRANTY OR GUARAN... | ocess. takes a pigp | en string and converts it back to clear text
# first creates a list of each 3 values from the inputted string (each element has 3 chars)
# then compares those elements to the pigpen dictionary to create the decrypted string
def pigpenBackward():
global decrypted_message
# convert encrypted message (int array) back t... |
rolapp/plugin.video.zattooboxExt.beta | resources/zattooDB.py | Python | bsd-2-clause | 26,019 | 0.016529 | # coding=utf-8
#
# copyright (C) 2017 Steffen Rolapp (github@rolapp.de)
#
# based on ZattooBoxExtended by Daniel Griner (griner.ch@gmail.com) license under GPL
#
# This file is part of ZattooHiQ
#
# zattooHiQ is free software: you can redistribute it and/or modify
# it under the terms of the GNU... | dation, either version 3 of the Licens | e, or
# (at your option) any later version.
#
# zattooHiQ 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 License for more details.
#
# You s... |
muk-it/muk_dms | muk_dms_access/models/access_groups.py | Python | lgpl-3.0 | 1,927 | 0.008303 | ###################################################################################
#
# Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Documents Access
# (see https://mukit.at).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Le... |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with | this program. If not, see <http://www.gnu.org/licenses/>.
#
###################################################################################
from odoo import models, fields, api
class AccessGroups(models.Model):
_inherit = 'muk_security.access_groups'
#-------------------------------------------... |
jorgecasals/VoiceTrainingTool | Repositories/Cache.py | Python | gpl-3.0 | 420 | 0.004762 | class RepositoryCache:
def __init__(self):
self.data_dict = {}
def add_data(self, keys, data):
self.data_dict[keys, data]
def clear(self):
self.data_dict = {}
def is_data_cac | hed(self, keys):
result = self.data_dict.has_key(keys)
return result
def get_data(self, keys):
result = self.data_dict[keys]
return result
Cache | = RepositoryCache()
|
jeffhsu3/genda | tests/exon_utils_tests.py | Python | bsd-3-clause | 1,802 | 0.021643 |
"""Testing for overlap intervals
"""
import unittest
from genda.transcripts.exon_utils import calcOverlap, collideIntervals, \
collapseIntervals
class TestOverlapFunctions(unittest.TestCase):
def setUp(self):
# Simple Overlap
self.simple = [(1,10), (6,15)]
# One interval enclosed ... | rlap(self):
# Make sure overlaps are calculated correctly
self.assertEqual(calcOverlap(self.simple), 4)
self.assertEqual(calcOverlap(self.enclosed), 40)
self.assertEqual(calcOverlap(self.partial),400)
def test_collideIntervals(self):
self.assertEqual(collideIntervals(self.si... | e[0], self.simple[1]),
[(1,15)])
self.assertEqual(collideIntervals(self.enclosed[0], self.enclosed[1]),
[(100,200)])
self.assertEqual(collideIntervals(self.no[0], self.no[1]),self.no)
def test_collapseIntervals(self):
self.assertEqual(collapseIntervals(self.s... |
WeirdCoder/LilyPadOS | 04Dan/RandomStuff/listener.py | Python | mit | 403 | 0.012407 | import lcm
from lilylcm import 03Citrus
def my_handler(channel, data):
msg = 03Citrus.decode(data)
print("Received message on channel /"%s/"" % channel)
print(" value = %s" % str(msg.value))
print("")
lc = lcm.LCM()
subscriptio | n = lc.subscribe("03Citrus", my_handler)
try:
while True:
lc.handle()
except Key | boardInterrupt:
pass
lc.unsubscribe(subscription)
|
markuz/scripts | copyemail.py | Python | gpl-2.0 | 4,573 | 0.014433 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- encoding: utf-8 -*-
#
# This file is part of my scripts project
#
# Copyright (c) 2013 Marco Antonio Islas Cruz
#
# This script 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 So... | el mensaje %s/%s"%(d,subject)
newhost.append(d, None, None, msg.as_string())
#Conectar al | host anterior
print "Connecting to %s:%d"%(OLDHOST, OLDPORT)
oldhost = imaplib.IMAP4(OLDHOST, OLDPORT)
print "Auth: %s,%s"%(options.email, options.oldpassword)
oldhost.login(options.email, options.oldpassword)
#Conectar al nuevo host
newhost = imaplib.IMAP4(NEWHOST, NEWPORT)
newhost.login(options.newemail, options.ne... |
OCA/purchase-workflow | purchase_propagate_qty/tests/__init__.py | Python | agpl-3.0 | 107 | 0 | # License AGPL-3 | .0 or later (http://www.gnu.org/licenses/agpl.html).
|
from . import test_purchase_delivery
|
jojanper/draalcore | draalcore/models/admin.py | Python | mit | 302 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Register models to admin view."""
# System | imports
from django.contrib import admin
from django.contrib.admin.models import LogEntry
# Project imports
from draalcore.models.admin_log import LogEnt | ryAdmin
admin.site.register(LogEntry, LogEntryAdmin)
|
ParalelniPolis/polis-heroku | paralelnipolis/settings.py | Python | lgpl-3.0 | 3,240 | 0.000309 | """
Django settings for paralelnipolis project.
Generated by 'django-admin startproject' using Django 1.8.3.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Bui... | True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
# 'south',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttype | s',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.... |
luisza/academica | matricula/contrib/bills/signals.py | Python | gpl-3.0 | 2,438 | 0.002871 | # -*- coding: UTF-8 -*-
from django.db.models.signals import post_save
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.dispatch import receiver
from matricula.models import Enroll
from .models import Bill
from django.utils.translation import ugettext_lazy as _
from... | go.utils.encoding import smart_text
from django.conf import settings
@receiver(post_save, sender= | Enroll)
def create_bill(sender, **kwargs):
instance = kwargs['instance']
if not instance.bill_created and instance.enroll_finished\
and instance.group.cost > 0:
instance.bill_created = True
Bill.objects.create(short_description=_("Enroll in %s") % (instance.group),
... |
kalyan02/dayone | do/private_config-sample.py | Python | gpl-2.0 | 296 | 0.023649 | # rename this file to private_config.py
# dropbox api creden | tials
DROPBOX_APP_ID=''
DROPBOX_API_SECRET=''
# django app sercret for salting and | hashing cookies
SECRET_KEY = ''
# automatic admin configuration
AUTO_ADMINS = (
('admin_username','admin_password','admin_password@yoursite.com'),
) |
hamonikr-root/system-config-printer-gnome | cupshelpers/cupshelpers.py | Python | gpl-2.0 | 29,800 | 0.007282 | ## system-config-printer
## Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Red Hat, Inc.
## Authors:
## Florian Festi <ffesti@redhat.com>
## Tim Waugh <twaugh@redhat.com>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as ... | t key.startswith ('requesting-user-name-')):
self.other_attributes[key] = value
self.job_sheet_start, self.job_sheet_end = attrs.get(
'job-sheets-default', ('none', 'none'))
self.job_sheets_supported = attrs.get('job-sheets-supported', ['none'])
self.error_po... | ne')
self.error_policy_supported = attrs.get(
'printer-error-policy-supported', ['none'])
self.op_policy = attrs.get('printer-op-policy', "") or "default"
self.op_policy_supported = attrs.get(
'printer-op-policy-supported', ["default"])
self.default_allow = True
... |
bearops/ebzl | ebzl/lib/config.py | Python | bsd-3-clause | 3,082 | 0 | """Helper module for parsing AWS ini config files."""
import os
try:
import configparser
except ImportError:
import ConfigParser as configparser
AWS_CLI_CREDENTIALS_PATH = "~/.aws/credentials"
AWS_CLI_CONFIG_PATH = "~/.aws/config"
DEFAULT_PROFILE_NAME = os.getenv("AWS_DEFAULT_PROFILE", "default")
class N... | file=None):
"""Returns AWS credentials.
Reads ~/.aws/credentials if the profile name is given or tries
to get them from environment otherwise. Returns a (key, secret)
tuple.
:type profile: basestring
:rtype: tuple
"""
if profile is None:
key, secret = _get_credentials_from_env... | key is not None and secret is not None:
return key, secret
raise NoConfigFoundException("AWS credentials not found.")
config = _get_config_parser(path=AWS_CLI_CREDENTIALS_PATH)
key = config.get(profile, "aws_access_key_id")
secret = config.get(profile, "aws_secret_access_key")
re... |
andredias/nikola | nikola/data/themes/base/messages/messages_bg.py | Python | mit | 2,386 | 0 | # -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"%d min remaining to read": "%d минути до прочитане",
"(active)": "(активно)",
"Also available in:": "Достъпно също на:",
"Archive": "Архив",
"Authors": "Автори",
"Categories": "Категории",
"Comments": "Коментари"... | year | }": "Публикации от {day} {month} {year}",
"Posts for {month} {year}": "Публикации за {month} {year}",
"Previous post": "Предишна публикация",
"Previous": "",
"Publication date": "Дата на публикуване",
"RSS feed": "RSS поток",
"Read in English": "Прочетете на български",
"Read more": "Чети на... |
mensler/ansible | lib/ansible/module_utils/facts.py | Python | gpl-3.0 | 171,136 | 0.004494 | # (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
#
# 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 lat... | th' : '/usr/local/sbin/pkg', 'name' : 'pkgng' },
{ 'path' : '/usr/bin/swupd', 'name' : 'swupd' },
{ 'path' : '/usr/sbin/sorcery', 'name' : 'sorcery' },
]
def __init__(self, module, load_on_init=True, cached_facts=None):
self.module = mo | dule
if not cached_facts:
self.facts = {}
else:
self.facts = cached_facts
### TODO: Eventually, these should all get moved to populate(). But
# some of the values are currently being used by other subclasses (for
# instance, os_family and distribution). ... |
praekelt/vumi-go | go/router/templatetags/router_tags.py | Python | bsd-3-clause | 319 | 0 | from django import template
from go.base.utils import get_router_view_definition
register = template.Library()
@register.simple_tag
def router_screen(router, view_name='show'):
view_def = get_router_view_definition(router.rout | er_type, router)
return view_def.get_view_url(view_name, router_ | key=router.key)
|
robinwyss/raspberry-scripts | main.py | Python | mit | 390 | 0 | # | !/usr/bin/env python
import camera
import resize
import ftpupload
import time
# wait 10s to not interfer with the timelaps script
time.sleep(10)
print("taking a picture")
imagePath = camera.capture()
print("captured %s" % imagePath)
smallImagePath = resize.resizeImg(imagePath)
print("resized image")
print("uploading.... | |
acm-uiuc/DJ-Roomba | dj_roomba/adrive.py | Python | gpl-2.0 | 906 | 0.005519 | """audio driver subsystem"""
from os.path import exists
from os import environ
from subprocess import check_call
from functools import partial
from .drive import Driver
import click
DRIVE_QUEUE = 'a.drive'
CTL_PATH | = '{}/.config/pianobar/ctl'.format(environ['HOME'])
COMMANDS = {'p', 'n', '^', '(', ')'}
def callback(ctl:'file_t', cmd:str) -> "IO ()":
"""writes command to ctl pipe"""
if cmd not in COMMANDS:
return
ctl.write(cmd)
ctl.flush()
@click.command()
@click.option('--ctl_path', default=CTL_PATH)
@... | on('--queue', default=DRIVE_QUEUE)
def main(ctl_path:str, queue:str) -> "IO ()":
"""daemon for a.drive queue consumption"""
if not exists(ctl_path):
with open('/dev/null', 'w') as null:
check_call(['pianoctl'], stdout=null)
with open(ctl_path, 'w') as ctl:
Driver(callback=partia... |
jandecaluwe/myhdl-examples | crusty_UK101/UK101AddressDecode/bench.py | Python | mit | 691 | 0.013025 | from myhdl import *
from UK101AddressDecode import UK101AddressDecode
def bench():
AL = Signal(intbv(0)[16:])
MonitorRom = Signal(bool(0))
ACIA = Signal(bool(0))
KeyBoardPort = Signal(bool(0))
VideoMem = Signal(bool(0))
BasicRom = Signal(bool(0))
Ram = Signal(bool(0))
dut = UK101Addr... | deoMem,
BasicRom,
Ram)
@instance
def stimulus():
for i in range(0, 2**16):
AL.next = i
yield delay(10)
raise StopSimulation()
return dut, st | imulus
sim = Simulation(traceSignals(bench))
sim.run()
|
glad-web-developer/zab_sno | src/sno_galleries/models.py | Python | apache-2.0 | 1,164 | 0.00184 | from django.db import models
from django.utils.html import format_html
from sorl.thumbnail import get_thumbnail
from sorl.thumbnail.fields import ImageField
from sno.models import Sno
class SnoGalleries(models.Model):
class Meta:
verbose_name = 'Фотография в галереи СНО'
verbose_name_plural = 'Фот... | ('Название фото', max_length=255, blank=True, null=True)
photo = ImageField(verbose_name='Фото', max_length=255)
description = models.TextField('Описание', blank=True, null=True)
sno = models.ForeignKey(Sno, verbose_name='СНО', on_delete=models.CASCADE)
date_created = models.DateField('Дата', auto_now_a... | |
Inspq/ansible | lib/ansible/modules/system/debconf.py | Python | gpl-3.0 | 5,880 | 0.006633 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Ansible module to configure .deb packages.
(c) 2014, Brian Coca <briancoca+ansible@gmail.com>
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 Softwa... | etsel = module.get_bin_path('debconf-set-selections', True)
cmd = [setsel]
if unseen:
cmd.append('-u')
if vtype == 'boolean':
if value == 'True':
value = 'true'
elif value == 'False':
value = 'false'
data = ' '.join([pkg, question, vtype, value])
ret... | name = dict(required=True, aliases=['pkg'], type='str'),
question = dict(required=False, aliases=['setting', 'selection'], type='str'),
vtype = dict(required=False, type='str', choices=['string', 'password', 'boolean', 'select', 'multiselect', 'note', 'error', 'title', 'text', 'seen'])... |
oemof/examples | oemof_examples/tespy/solar_collector/solar_collector.py | Python | gpl-3.0 | 2,858 | 0.0007 | # -*- coding: utf-8 -*-
from tespy.networks import network
from tespy.components import sink, source, solar_collector
from tespy.connections import connection
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
# %% network
fluid_list = ['H2O']
nw = net... | T=np.nan)
gridnum = 10
T_amb = np.linspace(-10, 30, gridnum, dtype=float)
E_glob = np.linspace(100, | 1000, gridnum, dtype=float)
df = pd.DataFrame(columns=T_amb)
for E in E_glob:
eta = []
coll.set_attr(E=E)
for T in T_amb:
coll.set_attr(Tamb=T)
nw.solve(mode=mode, design_path='design')
eta += [coll.Q.val / (coll.E.val * coll.A.val)]
# cut out efficiencies smaller than zer... |
brennie/reviewboard | reviewboard/webapi/tests/test_user.py | Python | mit | 14,393 | 0 | from __future__ import unicode_literals
from django.contrib.auth.models import Permission, User
from django.utils import six
from djblets.avatars.services.gravatar import GravatarService
from djblets.testing.decorators import add_fixtures
from djblets.webapi.testing.decorators import webapi_test_template
from kgb impo... | e GET <URL>/?include-inactive=true API includes inactive
users
"""
dopey = User.objects.get(username='dopey')
dopey.is_active = False
dopey.save()
rsp = self.api_get(get_user_list_url(), {'include-inactive': 'true'},
expected_mimetype=user_list... |
self.assertEqual(set(User.objects.filter(pk__in=user_pks)),
set(User.objects.all()))
def test_get_with_q(self):
"""Testing the GET users/?q= API"""
rsp = self.api_get(get_user_list_url(), {'q': 'gru'},
expected_mimetype=user_list_mimetype... |
CodeForAfrica/grano | grano/logic/entities.py | Python | mit | 6,574 | 0 | import logging
import colander
from grano.core import db, celery
from grano.model import Entity
from grano.logic import properties as properties_logic
from grano.logic.references import ProjectRef, AccountRef
from grano.logic.references import SchemaRef, EntityRef
from grano.plugins import notify_plugins
log = loggi... | es) and canonical is not None:
if alias_name not in known_names:
data = {
'value': alias_name,
'active': False,
'name': 'name',
'source_url': source_url
}
properties_logic.save(canonical, data)
_entit... | , canonical_name)
for alias in aliases:
if canonical is None:
# Rename an alias to its new, canonical name.
data = {
'value': canonical_name,
'active': True,
'name': 'name',
'source_url': source_url
}
... |
Ecotrust/forestplanner | lot/landmapper/settings.py | Python | bsd-3-clause | 33,100 | 0.004683 | import os
from datetime import date
TODAY_DATE = date.today().strftime("%D")
LANDMAPPER_DIR = os.path.dirname(os.path.abspath(__file__))
###########################################
## Keys ###
###########################################
MAPBOX_TOKEN = 'set_in_landmapper_local_settings... | ON': {'source': 'USGS', 'attribution': 'USGS The National Map: Orthoimagery. Data refreshed October, 2020.'}
# Can get updated attribution at https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer?f=pjson ['copyrightText']
},
'ESRI_Satellite': {
| 'URL': 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/export',
'LAYERS': '0',
'TECHNOLOGY': 'arcgis_mapserver',
'ATTRIBUTION': {'source': 'ESRI', 'attribution': 'Source: Esri, DigitalGlobe, GeoEye, Earthstar Geographics, CNES/Airbus DS, USDA, USGS, AeroGRID, IGN,... |
KaranToor/MA450 | google-cloud-sdk/lib/surface/functions/call.py | Python | apache-2.0 | 2,127 | 0.002351 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, V | ersion 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 implied.
# See the License for the specific lang... |
DemocracyClub/yournextrepresentative | ynr/apps/elections/uk/tests/test_custom_merge.py | Python | agpl-3.0 | 5,408 | 0 | from django_webtest import WebTest
from candidates.views.people import MERGE_FORM_ID, SUGGESTION_FORM_ID
import people.tests.factories
from candidates.tests import factories
from candidates.tests.auth import TestUserMixin
from candidates.tests.uk_examples import UK2015ExamplesMixin
from people.models import Person
fro... | ):
self.assertTrue(Person.objects.filter(pk=10000).exists())
primary_membership = factories.MembershipFactory.create(
person=self.primary_person,
post=self.camberwell_post,
party=self.labour_party,
ballot=self.camberwell_post_ballot_earlier,
el... | post=self.local_post,
party=self.labour_party,
ballot=self.local_election.ballot_set.get(post=self.local_post),
)
factories.MembershipFactory.create(
person=self.secondary_person,
post=self.camberwell_post,
party=self.labour_party,
... |
fukun07/neural-image-captioning | codes/pycoco/rouge/rouge.py | Python | mit | 3,659 | 0.008746 | #!/usr/bin/env python
#
# File Name : rouge.py
#
# Description : Computes ROUGE-L metric as described by Lin and Hovey (2004)
#
# Creation Date : 2015-01-07 06:03
# Author : Ramakrishna Vedantam <vrama91@vt.edu>
import numpy as np
import pdb
def my_lcs(string, sub):
"""
Calculates longest common subsequence ... | def calc_score(self, candidate, refs):
"""
Compute ROUGE-L score given one candidate and references for an image
:param candidate: str : candidate sentence to be evaluated
:param refs: list of str : COCO reference sentences | for the particular image to be evaluated
:returns score: int (ROUGE-L score for the candidate evaluated against references)
"""
assert(len(candidate)==1)
assert(len(refs)>0)
prec = []
rec = []
# split into tokens
token_c = candidate[0].split(" ... |
baigk/compass-core | compass/db/api/installer.py | Python | apache-2.0 | 1,791 | 0 | # Copyright 2014 Huawei Technologies Co. Ltd
#
# 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 ... | sions and
# limitations under the License.
"""Adapter database operations."""
im | port logging
import os
from compass.db.api import database
from compass.db.api import utils
from compass.db import exception
from compass.db import models
from compass.utils import setting_wrapper as setting
from compass.utils import util
def _add_installers(session, model, configs, exception_when_existing=True):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.