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
nsanthony/super-fortnight
wwk/py/rooms/room_directory/blank_room.py
Python
apache-2.0
289
0.010381
#! /Users/nsanthony/miniconda3/
bin/python import rooms.room_class as rc blank = rc.room() blank.name = 'blank room' blank.descript
= 'This is a blank room' blank.size = 'You cant see the edge' blank.occupied = 0 blank.people = 'There is no one in this room with you' blank.coord = [0,0,0]
metabrainz/picard
picard/ui/ui_options_tags_compatibility_id3.py
Python
gpl-2.0
7,654
0.002744
# -*- coding: utf-8 -*- # Automatically generated - don't edit. # Use `python setup.py build_ui` to update it. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TagsCompatibilityOptionsPage(object): def setupUi(self, TagsCompatibilityOptionsPage): TagsCompatibilityOptionsPage.setObjectName("TagsCompa...
with.addWidget(self.label_id3v23_join_with) self.id3v23_join_with = QtWidgets.QComboBox(self.tag_compatibility) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(1) sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.id3v23_join_with.sizePolicy().hasHeightForWidth()) self.id3v23_join_with.setSizePolicy(sizePolicy) self.id3v23_join_with.setEditable(True) self.id3v23_join_with.setObjectName("id3v23_join_with") self.id3v23_join_with.addItem("") self.id3v23_join...
MendeleievBros/Mendeleiev-Bros
mendeleiev_bros/escena_menu.py
Python
gpl-3.0
2,716
0.002578
# -*- coding: utf-8 -*- import pilas archi = open('datos.txt', 'r') nivel = archi.readline() pantalla = archi.readline() idioma = archi.readline() archi.close() if idioma == "ES": from modulos.ES import * else: from modulos.EN import * class EscenaMenu(pilas.escena.Base): "Es la escena de presentación d...
escena(escena_niveles.EscenaNiveles())
return False elif self.donde == "historia": self.sonido.detener() import escena_historia pilas.cambiar_escena(escena_historia.Historia()) elif self.donde == "ayuda": self.sonido.detener() import escena_ayud...
lurch/python-gpiozero
setup.py
Python
bsd-3-clause
3,407
0.015263
import os import sys from setuptools import setup, find_packages "A simple interface to GPIO devices with Raspberry Pi." if sys.version_info[0] == 2: if not sys.version_info >= (2, 7): raise ValueError('This package requires Python 2.7 or above') elif sys.version_info[0] == 3: if not sys.version_info ...
sys.version_info[:2] == (3, 2): # Particular versions are required for Python 3.2 compatibility __extra_requires__['doc'].extend([ 'Jinja2<2.7', 'MarkupSafe<0.16', ]) __extra_requires__['test'][1] = 'coverage<4.0dev' __entry_points__ = { 'gpiozero_pin_factories': [ 'PiG...
= gpiozero.pins.pigpiod:PiGPIOPin', 'RPiGPIOPin = gpiozero.pins.rpigpio:RPiGPIOPin', 'RPIOPin = gpiozero.pins.rpio:RPIOPin', 'NativePin = gpiozero.pins.native:NativePin', 'MockPin = gpiozero.pins.mock:MockPin', 'MockPWMPin = gpiozero.pins.mock:MockPWMPin', ], } def ...
enriquesanchezb/practica_utad_2016
venv/lib/python2.7/site-packages/coverage/backward.py
Python
apache-2.0
4,909
0
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt """Add things to old Pythons so I can pretend they are newer.""" # This file does lots of tricky stuff, so disable a bunch of pylint warnings. # pylint: disable=re...
`seq`.""" return iter(seq).next # Python 3.x is picky abo
ut bytes and strings, so provide methods to # get them right, and make them no-ops in 2.x if env.PY3: def to_bytes(s): """Convert string `s` to bytes.""" return s.encode('utf8') def binary_bytes(byte_values): """Produce a byte string with the ints from `byte_values`.""" return b...
chainer/chainercv
examples/ssd/train.py
Python
mit
6,895
0
import argparse import copy import numpy as np import chainer from chainer.datasets import ConcatenatedDataset from chainer.datasets import TransformDataset from chainer.optimizer_hooks import WeightDecay from chainer import serializers from chainer import training from chainer.training import extensions from chainer....
t triggers from chainercv.datasets import voc_bbox_label_names from chainercv.datasets import VOCBboxDataset from chainercv.extensions import DetectionVOCEvaluator from chainercv.links.model.ssd import GradientScaling from chainercv.links.model.ssd import multibox_loss from chainercv.links import SSD300 from chainercv...
el.ssd import random_distort from chainercv.links.model.ssd import resize_with_random_interpolation # https://docs.chainer.org/en/stable/tips.html#my-training-process-gets-stuck-when-using-multiprocessiterator import cv2 cv2.setNumThreads(0) class MultiboxTrainChain(chainer.Chain): def __init__(self, model, alp...
toenuff/treadmill
tests/idirwatcher_test.py
Python
apache-2.0
2,182
0
"""Unit test for directory watcher (inotify). """ import errno import os import shutil import tempfile import select import unittest # Disable W0611: Unused import import tests.treadmill_test_deps # pylint: disable=W0611 import mock from treadmill import idirwatch class DirWatcherTest(unittest.TestCase): """...
lambda x: created.append(x) or 'one' watcher.on_modified = lambda x: modified.append(x) or 'two' watcher.on_deleted = lambda x: deleted.append(x) or 'three' with open(test_file, 'w') as f: f.write('hello') with open(test_file, 'a') as f: f.write(' world!') ...
unlink(test_file) with open(test_file, 'w') as f: f.write('hello again') res = watcher.process_events(max_events=3) self.assertEqual([test_file], created) self.assertEqual([test_file], modified) self.assertEqual([test_file], deleted) self.assertEqual( ...
Diviyan-Kalainathan/dependency_criteria
lib/fsic/indtest.py
Python
mit
56,584
0.008607
""" Module containing many types of independence testing methods. """ __author__ = 'wittawat' from abc import ABCMeta, abstractmethod from data import PairedData #import matplotlib.pyplot as plt import numpy as np #from numba import jit import data as data import util as util import feature as fea #from fsic.util imp...
.mean(K, 0) mean_l = np.mean(L, 0) mkml = mean_k*mean_l rr = reg if np.isreal(reg) else 0 with util.NumpySeedContext(seed=seed): r = 0 while r < n_permute: # shuffle the order of X, Y while still keeping the original pairs ind = ...
Kt = Ks - mean_k Ktml = Kt*mean_l # shift Ls n-1 times for s in range(n-1): if r >= n_permute: break Ls = np.roll(Ls, 1, axis=0) # biased u = np.mean(Ks...
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/newrelic-2.46.0.37/newrelic/common/system_info.py
Python
agpl-3.0
10,108
0.001583
"""This module implements functions for querying properties of the operating system or for the specific process the code is running in. """ import os import sys import re import multiprocessing import subprocess try: from subprocess import check_output as _execute_program except ImportError: def _execute_pro...
will have the same value for all cores in a physical # processor. The 'cpu cores' field for each 'processor' section will # provide the total number of cores for that physical processor. # The 'cpu cores' field is duplicated, so only remember the last filename = filename or '/proc/cpuinfo' proces...
open(filename, 'r') as fp: processor_id = None cores = None for line in fp: try: key, value = line.split(':') key = key.lower().strip() value = value.strip() except ValueError: ...
neuropower/neuropower
neuropower/apps/main/views.py
Python
mit
439
0.029613
fro
m __future__ import unicode_literals import sys sys.path = sys.path[1:] from django.http import HttpResponseRedirect from django.shortcuts import render from django.conf import settings from scipy.stats import norm, t import pandas as pd import numpy as np import tempfile import uuid import os ### MAIN TEMPLATE PAGES ...
return render(request,"main/home.html",{})
araluce/NextMedia
NextMedia/forms.py
Python
gpl-3.0
1,632
0.037446
# -*- coding: UTF-8 -*- from django import forms from .models import * class LoginForm(forms.Form): User = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'User', 'class' : 'form-control'})) Passw
ord = forms.URLField(widget=forms.TextInput(attrs={'placeholder': 'Password', 'class' : 'form-control', 'type' : 'password'})) class RegForm(forms.ModelForm): class Meta: model = Usuario widgets = { 'User' : forms.TextInput(attrs={'placeholder': 'NickName', 'name': 'User', 'class' : 'form-control'}), 'Nombr...
llidos', 'class' : 'form-control'}), 'Email' : forms.TextInput(attrs={'placeholder': 'Email', 'class' : 'form-control'}), 'Password': forms.PasswordInput(attrs={'placeholder': 'Password', 'class' : 'form-control'}), 'Visa' : forms.TextInput(attrs={'placeholder': 'VISA', 'class' : 'form-control'}), 'Fecha' :...
chop-dbhi/arrc
learn/plotters.py
Python
mit
2,963
0.001687
__author__ = 'Aaron J. Masino' def plot_ROC(y_actual, y_scores, title='ROC'): fpr, tpr, _ = roc_curve(y_actual, y_scores) roc_auc = auc(fpr, tpr) # Plot ROC curve plt.figure() plt.plot(fpr, tpr, label='Area = {0:0.2f}'''.format(roc_auc)) plt.grid() plt.plot([0, 1], [0, 1], 'k--') plt.x...
curacy', score_label='Score'): """ Generate a simple plot of the test and traning learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validatio
n. title : string Title for the chart. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative t...
matee911/GrimReapersPie
setup.py
Python
apache-2.0
1,788
0.000559
#!/usr/bin/env python import re from codecs import open try: from setuptools import setup except ImportError: from distutils.core import setup def get_version(): version = '' with open('grimreaper.py', 'r') as fd: version
= re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) if not version: raise RuntimeError("Cannot find version's information") return version def get_long_description(): with open('README.rst', 'r', 'utf-8') as f: readme = f.r...
setup( name='GrimReapersPie', version=get_version(), description='Python client to the GrimReaper process killer.', long_description=get_long_description(), author='Mateusz Pawlik', author_email='matee+grimreaperspie@matee.net', url='https://github.com/matee911/GrimReapersPie', py_module...
barbossa/django-heroku-blog
heroku_blog/urls.py
Python
apache-2.0
1,004
0
"""heroku_blog URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function vie
ws 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatte
rns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from blog.views im...
cgimenop/Excel2Testlink
ExcelParser/lib/openpyxl/chart/tests/test_bubble_chart.py
Python
mit
952
0.003151
from __future__ import absolute_import # Copyright (c) 2010-2015 openpyxl import pytest from openpyxl.xml.functions import fromstring, tostring from openpyxl.tests.helper import compare_xml @pytest.fixture def BubbleChart(): from ..bubble_chart import BubbleChart return BubbleChart class TestBubbleChart: ...
assert diff is None, diff def test_from_xml(self, BubbleChart): src = """ <bubbleChart> <axId val="10" /> <axId val="20" /> </bubbleChart> """ node = fromstring(src) bubble_chart = BubbleChart.from_tree(n
ode) assert dict(bubble_chart) == {}
achilleas-k/gnome15
src/plugins/sysmon/sysmon.py
Python
gpl-3.0
18,178
0.014358
# Gnome15 - Suite of tools for the Logitech G series keyboards and headsets # Copyright (C) 2010 Brett Smith <tanktarta@blueyonder.co.uk> # # 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, e...
is None: self.selected_cpu = self.cpu_data[0] # Net self.selected_net = None _, self.net_list = self._get_net_stats() net_name = self.gconf_c
lient.get_string(self.gconf_
bsipocz/astropy
astropy/timeseries/periodograms/lombscargle/implementations/chi2_impl.py
Python
bsd-3-clause
2,966
0
import numpy as np from .mle import design_matrix def lombscargle_chi2(t, y, dy, frequency, normalization='standard', fit_mean=True, center_data=True, nterms=1): """Lomb-Scargle Periodogram This implements a chi-squared-based periodogram, which is relatively slow but useful for val...
----- power : array_like
Lomb-Scargle power associated with each frequency. Units of the result depend on the normalization. References ---------- .. [1] M. Zechmeister and M. Kurster, A&A 496, 577-584 (2009) .. [2] W. Press et al, Numerical Recipes in C (2002) .. [3] Scargle, J.D. 1982, ApJ 263:835-853 """...
Radagast-red/golem
golem/transactions/service.py
Python
gpl-3.0
1,673
0.001195
import logging from golem.resource.client import AsyncRequest, async_run from twisted.internet.task import LoopingCall log = logging.getLogger("golem") class Service(object): """ A prototype of Golem service -- an long running "thread" that performs some tasks in background and responds to request from ...
opingCall.running def start(self): if self.running: raise RuntimeError("service already started") deferred = self._loopin
gCall.start(self.__interval) deferred.addErrback(self._exceptionHandler) def stop(self): if not self.running: raise RuntimeError("service not started") self._loopingCall.stop() def _exceptionHandler(self, failure): log.exception("Service Error: " + failure.getTraceb...
qingfeng/mikoto
tests/test_utils.py
Python
bsd-3-clause
1,469
0.000682
# encoding: utf-8 from __future__ import absolute_import from unittest import TestCase from mikoto.markdown import render_markdown from mikoto.libs.text import get_mentions_from_text class TestUtils(TestCase): def test_mentioned_people_from_text(self): text1 = "@xingben OK" text2 = "OK @xingben"...
'] == get_mentions_from_tex
t(text3) assert ['xingben', 'qingfeng'] == get_mentions_from_text(text4) assert ['xingben', 'qingfeng'] == get_mentions_from_text(text5) assert ['xingben', 'qingfeng', 'zhangchi'] == get_mentions_from_text(text6) assert [] == get_mentions_from_text(text7) def test_render_markdown_si...
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/networkx/algorithms/tests/test_tournament.py
Python
gpl-3.0
4,558
0
# test_tournament.py - unit tests for the tournament module # # Copyright 2015 NetworkX developers. # # This file is part of NetworkX. # # NetworkX is distributed under a BSD license; see LICENSE.txt for more # information. """Unit tests for the :mod:`networkx.algorithms.tournament` module.""" from itertools import com...
import DiGraph from networkx.algorithms.tournament import is_reachable from networkx.algorithms.tournament import is_strongly_connected from networkx.algorithms.tournament import is_tournament from networkx.algorithms.tournament import random_tournament from networ
kx.algorithms.tournament import hamiltonian_path class TestIsTournament(object): """Unit tests for the :func:`networkx.tournament.is_tournament` function. """ def test_is_tournament(self): G = DiGraph() G.add_edges_from([(0, 1), (1, 2), (2, 3), (3, 0), (1, 3), (0, 2)]) assert...
scotwk/cloud-custodian
tests/test_ec2.py
Python
apache-2.0
39,894
0.000551
# Copyright 2015-2017 Capital One Services, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
art_tags) self.assertFalse('Containers' in end_tags) class TestVolumeFilter(BaseTest): def test_ec2_attached_ebs_filter(self): session_factory = self.replay_flight_data( 'test_ec2_attached_ebs_filter') policy = self.load_policy({ 'name': 'ec2-unencrypted-vol', ...
n_factory) resources = policy.run() self.assertEqual(len(resources), 1) # DISABLED / Re-record flight data on public account def test_ec2_attached_volume_skip_block(self): session_factory = self.replay_flight_data( 'test_ec2_attached_ebs_filter') policy = self.load_p...
bashkirtsevich/pyAnecdotesTelegramBot
bot/anecdotes_bot.py
Python
gpl-3.0
2,142
0.002999
#!/usr/bin/env python # -*- coding: utf-8 -*- from anecdotes import Anecdotes import telebot def main(token): base = Anecdotes() while True: try: bot = telebot.TeleBot(token, threaded=False) @bot.message_handler(commands=["start", "help"]) def handle_start_help(m...
удь, чтоб ты смеялся, сука, до усрачки бля! \xF0\x9F\x98\xA0" bot.send_message(message.chat.id, help_string) @bot.message_handler(commands=["stat"]) def handle_stat(message): users, queries = base.get_statistics() stat = u"Пользователей:\r\n" + st...
bot.send_message(message.chat.id, stat) @bot.message_handler(commands=base.categories) def handle_category(message): def extract_command(text): return text.split()[0].split('@')[0][1:] if text.startswith('/') else None base.write_messages...
boldfield/dvm
tests/test_add.py
Python
mit
591
0.003384
import unittest from nose.tools import assert_true, assert_equal from mock import patch, Mock, call from tests import tmp_repo_path class TestAdd(unittest.TestCase): def test_file_names_no_dot(self): from dvm import add link, filename = add.file_names('ba
shrc') assert_equal(link, '.bashrc
') assert_equal(filename, 'dot.bashrc.symlink') def test_file_names_dot(self): from dvm import add link, filename = add.file_names('.bashrc') assert_equal(link, '.bashrc') assert_equal(filename, 'dot.bashrc.symlink')
doctorzeb8/django-era
era/management/commands/flush.py
Python
mit
858
0
from itertools import chain import subprocess from django.conf import settings from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('--fix', dest='fixtures', default='') def db_action(self, action): ...
on, *args): return ' '.join(ch
ain(['python manage.py', action], args)) def handle(self, *args, **kw): subprocess.call( '; '.join([ self.db_action('dropdb'), self.db_action('createdb'), self.manage_action('migrate'), self.manage_action('loaddata', *chain( ...
lidakanari/NeuroM
neurom/view/view.py
Python
bsd-3-clause
14,676
0.002657
# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project # All rights reserved. # # This file is part of NeuroM <https://github.com/BlueBrain/NeuroM> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are ...
soma_outline=True, linewidth=_LINEWIDTH, color=None, alpha=_ALPHA): '''Generates a 2d figure of the soma. Args: ax(matplotlib axes): on what to plot soma(neurom.core.Soma): plotted soma plane(str): Any pair of 'xyz' diameter_scale(float):...
multiplied with segment diameters before plotting linewidth(float): all segments are plotted with this width, but only if diameter_scale=None color(str or None): Color of plotted values, None corresponds to default choice alpha(float): Transparency of plotted values ''' plane0, plane1 =...
traxtar3/OrbitCalc
OrbitCalc_v0.0.9/RV2COE.py
Python
gpl-3.0
7,416
0.020092
# Built by John W. Harms ## # Version 0.01 -- Initial Build ## # Version 0.02 -- Refactored to be added as module to different project ## # Version 0.08 -- Complete overhaul # -- Changed code using SGP4 calculations (https://pypi.python.org/pypi/sgp4/) # -- Added error messages & "undefined" o...
ind argument of perigee --------------- if typeorbit == 'ei':
argp = angle( nbar,ebar) if ebar[2] < 0.0: argp= twopi - argp else: argp= undefined # ------------ find true anomaly at epoch ------------- if typeorbit[0] == 'e': nu = angle( ebar,r) if rdotv < 0.0: n...
0todd0000/spm1d
spm1d/examples/stats1d_roi/ex_cca_Dorn2012.py
Python
gpl-3.0
541
0.036969
import numpy as np import matplotlib.pyplot as plt import spm1d #(0) Load dataset: dataset = spm1d.data.mv1d.cca.Dorn2012() Y,x = dataset.get_data() #A:slow, B:fast print( dataset ) #(0a) Create region of interes
t(ROI): roi = np.array([False]*Y.shape[1]) roi[20
:50] = True roi[60:90] = True #(1) Conduct test: alpha = 0.05 X2 = spm1d.stats.cca(Y, x, roi=roi) X2i = X2.inference(0.05) print( X2i ) #(2) Plot: plt.close('all') # X2.plot() X2i.plot() X2i.plot_p_values() plt.show()
gadeleon/toodledo_cli_client
toodle_sync.py
Python
mit
3,843
0.023679
''' Simple pull of account info ''' import requests import datetime import pickle import json import time import sys account_url = 'https://api.toodledo.com/3/account/get.php?access_token=' tasks_get_url = 'https://api.toodledo.com/3/tasks/get.php?access_token=' ''' Fields you can use to filter when you get tasks: ht...
te = arrange_date(task_dump[i]['completed']) print 'Completed Task : {}, Completed {}'.format(task_dump[i]['title'], comp_date) else: pass #test = display_tasks(
'tasks_queried.pkl', 4) def format_task(task): ''' Take a dictionary formatted task from display tasks and print it out to something human readable. ''' comp_date = arrange_date(task['completed']) print 'Completed Task : {}, Completed {}'.format(task['title'], comp_date) def get_completed_tasks(): query = query...
virtuald/exaile
plugins/daapserver/daapserverprefs.py
Python
gpl-2.0
644
0.01087
from xlgui.preferences import widgets from xl.nls import gettext as _ import os name = _('DAAP Server') basedir = os.path.d
irname(os.path.realpath(__file__)) ui = os.path.join(basedir, 'daapserver_prefs.ui') class PortPreference(widgets.SpinPreference): default = 3689 name = 'plugin/daapserver/port' class NamePreference(widgets.Preference): default = 'Exaile Share' name = 'plugin/daapserver/name' class Enable
dPreference(widgets.CheckPreference): default = True name = 'plugin/daapserver/enabled' class HostPreference(widgets.Preference): default = '0.0.0.0' name = 'plugin/daapserver/host'
oddeyeco/oe-agent2
checks_available/check_docker_stats.py
Python
apache-2.0
6,294
0.008897
import lib.record_rate import lib.commonclient import lib.getconfig import lib.puylogger import lib.pushdata import lib.basecheck import json baseurl = lib.getconfig.getparam('Docker', 'stats') detailed_mon = lib.getconfig.getparam('Docker', 'detailed') prettynames = lib.getconfig.getparam('Docker', 'prettynames') mem...
self.local_vars.append({'name': check_type + '_' + netcheck_rated + '_' + k, 'timestamp': self.timestamp, 'value': value, 'check_type': che
ck_type, 'chart_type': 'Rate','extra_tag':{'container': container_name}}) for netcheck_stack in netchecks_stack: value = data['networks'][k][netcheck_stack] self.local_vars.append({'name': check_type + '_' + netcheck_stack + '_' + k, 'times...
igorcoding/asynctnt-queue
asynctnt_queue/queue.py
Python
apache-2.0
2,395
0.000418
import asynctnt from .tube import Tube __all__ = ( 'Queue', ) class Queue: __slots__ = ( '_conn', '_tube_cls', '_tubes', '_namespace' ) def __init__(self, conn: asynctnt.Connection, tube_cls=Tube, namespace='queue'): """ ...
args = None if tube_name is not None: args = (tube_name,)
res = await self._conn.call('{}.statistics'.format(self._namespace), args) if self._conn.version < (1, 7): # pragma: nocover return res.body[0][0] return res.body[0]
infobloxopen/infoblox-netmri
infoblox_netmri/api/remote/models/vlan_member_remote.py
Python
apache-2.0
8,769
0.003649
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class VlanMemberRemote(RemoteModel): """ Device memberships in VLANs, along with their STP configurations. This includes switch members (BridgeMemberInd = 1) and devices attached to access ports (BridgeMemberInd =...
identifier for the collector NetMRI that collected this data record. | ``attribute type:`` number | ``DeviceID:`` The internal NetMRI identifier for the device associated with this VLAN membership. | ``attrib
ute type:`` number | ``InterfaceID:`` The internal NetMRI identifier for the switched virtual interface for this VLAN on this device. | ``attribute type:`` number | ``RootBridgeAddress:`` The spanning tree protocol root bridge address; this is the designated root with the STP priority portion removed. ...
carlthome/librosa
librosa/sequence.py
Python
isc
55,756
0.001489
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' Sequential modeling =================== Sequence alignment ------------------ .. autosummary:: :toctree: generated/ dtw rqa Viterbi decoding ---------------- .. autosummary:: :toctree: generated/ viterbi viterbi_discriminative viterbi_b...
ust be equal to len(step_sizes_sigma)') if C is None and (X is None or Y is None): raise ParameterError('If C is not supplied, both X and Y must be supplied') if C is not None and (X is not None or Y is not None): raise ParameterError('If C is supplied, both X and Y must not be supplied') ...
nces, unless already supplied. # C_local will keep track of whether the distance matrix was supplied # by the user (False) or constructed locally (True) C_local = False if C is None: C_local = True # take care of dimensions X = np.atleast_2d(X) Y = np.atleast_2d(Y) ...
ziad-saab/ramses
docs/source/conf.py
Python
apache-2.0
9,733
0.005959
# -*- coding: utf-8 -*- # # Nefertari documentation build configuration file, created by # sphinx-quickstart on Fri Mar 27 11:16:31 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # #...
ue, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_addit...
ndex is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using ...
sebi06/BioFormatsRead
ometiff_write.py
Python
bsd-2-clause
1,302
0.001536
import javabridge import bioformats as bf import numpy as np from matplotlib import pyplot as plt, cm javabridge.start_vm(class_path=bf.JARS, run_headless=True) NT = 10 NC = 2 NZ = 4 NX = 217 NY = 94 output_path = 'outome.tif' frames = [] for t in range(NT): for z in range(NZ): for c in range(NC): ...
.squeeze(frame)) print(frame.shape) bf.write_image(output_path, pixels=frame, pixel_type=bf.PT_UINT16, c=c, t=t, z=z, size_c=NC, size_t=NT, size_z=NZ) """ xml_metadata = bf.get_omexml_metadata(path=output_path) metadata = bf.OMEXML(xml_metadata) NXp = metadata.image().Pixels.SizeX NYp = meta...
tadata.image().Pixels.SizeC NTp = metadata.image().Pixels.SizeT print(NXp, NYp, NZp, NCp, NTp) assert(NXp == NX) assert(NYp == NY) assert(NZp == NZ) assert(NCp == NC) assert(NTp == NT) """ javabridge.kill_vm() fig = plt.figure(figsize=(10, 8), dpi=100) ax = fig.add_subplot(111) cax = ax.imshow(frames[0], interpola...
GoogleCloudPlatform/PerfKitBenchmarker
tests/scratch_disk_test.py
Python
apache-2.0
7,787
0.003596
# Copyright 2018 PerfKitBenchmarker 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 appli...
RRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for PerfKitBenchmarker' scratchdisks.""" i
mport abc import unittest from absl import flags from absl.testing import flagsaver import mock from perfkitbenchmarker import benchmark_spec from perfkitbenchmarker import context from perfkitbenchmarker import disk from perfkitbenchmarker import errors from perfkitbenchmarker import linux_virtual_machine from perfki...
mikeboers/siteconfig
siteconfig/__init__.py
Python
bsd-3-clause
208
0
from .configobj import Config config =
Config.from_environ() # Add the data and some of the API as attributes of the top-level package. globals().upda
te(config) get = config.get get_bool = config.get_bool
abusesa/abusehelper
abusehelper/core/mail/__init__.py
Python
mit
812
0
import idiokit class Handler(object): def __init__(self, log): self.log = log @idiokit.stream def handle(self, msg): handle_default = getattr(self, "handle_default", None) stack = [msg] while stack: part = stack.pop() content_type = part.get_conten...
).replace("/", "_") handler = getattr(self, "handle_" + suffix, handle_default) if handler is not None: skip_rest = yield handler(part) if skip_rest: idiokit.stop(True) continue if part.is_multipart(): ...
s = yield part.get_payload() stack.extend(reversed(parts)) idiokit.stop(False)
mdlerch/Nvim-R
R/synctex_evince_forward.py
Python
gpl-2.0
5,572
0.008435
# The code in this files is borrowed from Gedit Synctex plugin. # # Copyright (C) 2010 Jose Aliste # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public Licence as published by the Free Software # Foundation; either version 2 of the Licence, or (at your...
rned empty list") sys.stderr.flush() def SyncView(self, input_file, data): if self.s
tatus == CLOSED: if self.spawn: self._tmp_syncview = [input_file, data, 0]; self._handler = self._syncview_handler self._get_dbus_name(True) sys.stdout.write("call Evince_Again()") sys.stdout.flush() else: se...
nav/presence
presence/apps/presence/apps.py
Python
mit
836
0.003589
from __future__ import unicode_literals from django.apps import AppConfig from django.db.models import signals from django.contrib.auth import get_user_model def populate_users(sender, **kwargs): User = get_user_model() for i in range(10): username = "user_{}".format(i+1) email = "{}@example.c...
eate_user(username=username,
email=email, is_staff=True, password="demo1234") class PresenceConfig(AppConfig): name = 'apps.presence' def ready(self): signals.post_migrate.connect(populate_users, sender=self)
JustinSGray/pyCycle
example_cycles/N+3ref/benchmark_N3_SPD.py
Python
apache-2.0
6,750
0.008889
import numpy as np import unittest import os import openmdao.api as om from openmdao.utils.assert_utils import assert_near_equal import pycycle.api as pyc from N3_SPD import N3_SPD_model class N3MDPOptTestCase(unittest.TestCase): def benchmark_case1(self): prob = N3_SPD_model() ...
.OPR'], 49.03813765, tol)# assert_near_equal(prob['CRZ.balance.FAR'], 0.02528878, tol)# assert_near_equal(prob['CRZ.balance.fan_Nmech'], 2118.62554023, tol)# assert_near_equal(prob['CRZ.balance.lp_Nmech'], 6567.78766693, tol)# assert_near_equal(prob['CRZ.balance.hp_Nmech'], 20574.436...
.9756247, tol)# if __name__ == "__main__": unittest.main()
Guneet-Dhillon/mxnet
tests/python/unittest/test_loss.py
Python
apache-2.0
8,986
0.002893
# 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 u...
label = mx.random.uniform(-1, 1, shape=(N, 1)) data_iter = mx.io.NDArrayIter(data, label, batch_size=10, label_name='label') output = get_net(1) l = mx.symbol.Variable('label') Loss = gluon.loss.L2Loss() Loss(label, label) loss = Loss(output, l) loss = mx.sym.make_loss(loss) mod
= mx.mod.Module(loss, data_names=('data',), label_names=('label',)) mod.fit(data_iter, num_epoch=200, optimizer_params={'learning_rate': 1.}, eval_metric=mx.metric.Loss()) assert mod.score(data_iter, eval_metric=mx.metric.Loss())[0][1] < 0.05 def test_l1_loss(): mx.random.seed(1234) np.ran...
endlessm/chromium-browser
v8/tools/clusterfuzz/v8_fuzz_config.py
Python
bsd-3-clause
2,226
0.004043
# Copyright 2018 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import json import os import random THIS_DIR = os.path.dirname(os.path.abspath(__file__)) # List of configuration experiments for correctness fuzzing. # ...
for flag in flags.split():
extra_flags.append('--second-config-extra-flags=%s' % flag) # Calculate flags determining the experiment. acc = 0 threshold = self.rng.random() * 100 for prob, first_config, second_config, second_d8 in foozzie_experiments: acc += prob if acc > threshold: return [ '--first-...
leonardoo/to-do-list
todolist/settings.py
Python
mit
1,990
0
""" Django settings for todolist 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/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) i...
docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'es-co' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CS
S, JavaScript, Images) # https://docs.djangoproject.com/en/dev/howto/static-files/ STATIC_URL = '/static/'
andreaso/ansible
lib/ansible/modules/cloud/amazon/ec2_group.py
Python
gpl-3.0
22,124
0.002486
#!/usr/bin/python # -*- coding: utf-8 -*- # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # ...
- proto: tcp ports: - 8
0 - 443 - 8080-8099 cidr_ip: 0.0.0.0/0 # Rule sources list support was added in version 2.4. This allows to define multiple sources per source type as well as multiple source types per rule. - proto: tcp ports: - 6379 - 26379 group_name: ...
marcvinyals/cnfgen
profile.py
Python
gpl-3.0
744
0.013441
#!/usr/bin/env python """ Profile script for CNFgen package """ from __future__ import print_function import os import sys from contextlib import contextmanager @contextmanager def erase_stdout(): wi
th file(os.devnull,"w") as null: old_stdout = sys.stdout sys.stdout = null yield sys.stdout = old_stdout def cnf
gen_call(): from cnfformula import cnfgen cmd = ["cnfgen"] + sys.argv[1:] with erase_stdout(): cnfgen(cmd) if __name__ == '__main__': from cProfile import run as profile if len(sys.argv) <= 1: print("Usage: {} <cnfgen_args>".format(sys.argv[0]),file=sys.stderr) s...
zzz14/LOST-FOUND
userpage/jieba1/jieba/posseg/__init__.py
Python
gpl-3.0
9,036
0.000775
from __future__ import absolute_import, unicode_literals import os import re import sys from userpage.jieba1 import jieba import pickle from .._compat import * from .viterbi import viterbi PROB_START_P = "prob_start.p" PROB_TRANS_P = "prob_trans.p" PROB_EMIT_P = "prob_emit.p" CHAR_STATE_TAB_P = "char_state_tab.p" re_...
re_han_detail.split(sentence) for blk in blocks: if re_han_detail.match(blk): for word in self.__cut(blk): yield word else: tmp = re_skip_detail.split(blk) for x in tmp: if x: ...
yield pair(x, 'eng') else: yield pair(x, 'x') def __cut_DAG_NO_HMM(self, sentence): DAG = self.tokenizer.get_DAG(sentence) route = {} self.tokenizer.calc(sentence, DAG, route) x = 0 N = len(sentence) ...
trevor/mailman3
src/mailman/utilities/tests/test_templates.py
Python
gpl-3.0
11,539
0.00104
# Copyright (C) 2011-2014 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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 you...
e argument nexteq('/v/templates/site/it/foo.txt') # 2: Use the site's default language nexteq('/v/templates/site/fr/foo.txt') # 3: English nexteq('/v/templates/site/en/foo.txt') # 4: After all the site-admin override paths have been searched, the # Mailman in-tree...
mplates. nexteq('/m/templates/en/foo.txt') def test_no_optional_arguments_search_order(self): search_order = self._stripped_search_order('foo.txt') # For convenience. def nexteq(path): self.assertEqual(next(search_order), path) # 1: Use the site's default languag...
yajiedesign/mxnet
python/mxnet/__init__.py
Python
apache-2.0
3,631
0.001928
#!/usr/bin/env python # 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 # "L...
from . import name # use mx.sym as short for mx.symbol from . import symbol as sym # use mx.np_symbol as short for mx.symbol.numpy from .symbol.numpy import _symbol as np_symbol from . import symbol from . import symbol_doc from . import io from . import recordio from . import operator # use mx.rnd as short for mx.rand...
er from . import model from . import notebook from . import initializer # use mx.init as short for mx.initializer from . import initializer as init from . import visualization # use mx.viz as short for mx.visualization from . import visualization as viz from . import callback # from . import misc from . import lr_sched...
apyrgio/snf-ganeti
lib/watcher/state.py
Python
bsd-2-clause
6,797
0.005738
# # # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc. # 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, ...
logging.debug("Data didn't change, just touching status file") os.utime(filename, None) return # We need to make sure the file is locked before renaming it, otherwise # starting ganeti-watcher again at the same time will create a conflict. fd = utils.WriteFile(filename, ...
Close(self): """Unlock configuration file and close it. """ assert self.statefile # Files are automatically unlocked when closing them self.statefile.close() self.statefile = None def GetNodeBootID(self, name): """Returns the last boot ID of a node or None. """ ndata = self._d...
rcbops/opencenter
tests/test_ast.py
Python
apache-2.0
13,977
0.000072
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # OpenCenter(TM) is Copyright 2013 by Rackspace US, Inc. ############################################################################## # # OpenCenter is licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compli...
del_filter('nodes', 'facts.parent_id !< 999') self.app.logger.debug('result: %s' % result) self.assertEquals(len(result), 0) def test_less_than_equal(self): result = self._m
odel_filter('nodes', 'facts.parent_id <= %s' % self.container['id']) self.app.logger.debug('result: %s' % result) self.assertEquals(len(result), 2) result = self._model_filter('nodes', 'facts.parent_id < %s' % self.containe...
calum-chamberlain/EQcorrscan
eqcorrscan/tests/despike_test.py
Python
gpl-3.0
1,501
0
"""Test the despiking algorithms implimented in EQcorrscan.""" import unittest import os import numpy as np from obspy import Trace, read from eqcorrscan.utils.despike import median_filter, template_remove class DespikeTesting(unittest.TestCase): @classmethod def setUpClass(cls): cls.testing_path =...
on correlations.""" template = np.zeros(10)
template[2] = 1 template = Trace(template) template.stats.sampling_rate = 100 despiked = template_remove( tr=self.spiked.copy(), template=template, cc_thresh=0.9, windowlength=0.05, interp_len=0.05) self.assertNotEqual(despiked.data[100], 20) self.ass...
caiuspb/home-assistant
homeassistant/components/media_player/plex.py
Python
mit
10,331
0
""" homeassistant.components.media_player.plex ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides an interface to the Plex API. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/media_player.plex/ """ import os import json import logging from datetime impo...
ions, update_devices, update_sessions): self.plex_sessions = plex_sessions self.update_devices = update_devices self.update_sessions = update_sessions self.set_device(de
vice) def set_device(self, device): """ Sets the device property. """ self.device = device @property def unique_id(self): """ Returns the id of this plex client """ return "{}.{}".format( self.__class__, self.device.machineIdentifier or self.device.name) @p...
hatbot-team/hatbot_resources
preparation/lang_utils/morphology/replace_with_gap.py
Python
mit
2,900
0.002894
__author__ = 'shkiper' from . import morph def get_best_parse(word: str, part: str): possibilities = [x for x in morph.parse(word) if x.tag.POS == part] if len(possibilities) == 0: return None else: return max(possibilities, key=lambda x: (x.score, x.word)) WHO_PARSE = get_best_parse('кт...
"NPRO") HE_PARSE = get_best_parse('он', "NPRO") SHE_PARSE = get_best_parse('она', "NPRO") IT_PARSE = get_best_parse('оно', "NPRO") THEY_PARSE = get_best_parse('они', "NPRO") def replace_noun_with_question(word: str, default: str=None): """ Gets noun and returns a string with this case question for this noun....
уск*' >>> replace_noun_with_question('проводами') 'чем?' >>> replace_noun_with_question('проводницами') 'кем?' >>> replace_noun_with_question('железы') 'чего?' :param word: word for case question :param default: value, which returned if it's unable to get case question :return: case ...
gedakc/manuskript
manuskript/converters/abstractConverter.py
Python
gpl-3.0
525
0.001905
#!/usr/bin/env python # --!-- coding: utf8 --!-- class abstractConverter: """ A converter is used to convert (duh) between stuff. They provide access
to external libraries that may or may not be present. Now, things are a bit messy, since classes in `exporter` (and `importer` to a lesser extent) do the same. In a better world, classes from `exporter` and `importer` would use co
nverters to do their stuff. (TODO) """ name = "" @classmethod def isValid(cls): return False
prometheus/client_python
tests/test_graphite_bridge.py
Python
apache-2.0
3,054
0.000982
import socketserver as SocketServer import threading import unittest from prometheus_client import CollectorRegistry, Gauge from prometheus_client.bridge.graphite import GraphiteBridge def fake_timer(): return 1434898897.5 class TestGraphiteBridge(unittest.TestCase): def setUp(self): self.registry ...
) self.gb.push() self.t.join() self.assertEqual(b'labels;a=c;b=d 1.0 1434898897\n', self.data) def test_prefix(self): labels = Gauge('labels', 'help', ['a', 'b'], registry=self.registry) labels.labels('c', 'd').inc() self.gb.push(prefix='pre.fix') self.t.j...
bels.a.c.b.d 1.0 1434898897\n', self.data) def test_prefix_tags(self): self._use_tags() labels = Gauge('labels', 'help', ['a', 'b'], registry=self.registry) labels.labels('c', 'd').inc() self.gb.push(prefix='pre.fix') self.t.join() self.assertEqual(b'pre.fix.labels...
Bitcoin-ABC/bitcoin-abc
test/functional/wallet_importmulti.py
Python
mit
37,468
0.001762
#!/usr/bin/env python3 # Copyright (c) 2014-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the importmulti RPC. Test importmulti by generating keys on node0, importing the scriptPubKeys an...
"timestamp": "now", "pubkeys": [key.pubkey], "internal": True}, succes
s=True, warnings=["Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."]) test_address(self.nodes[1], key.p2pkh_addr, iswatchonly=True, ismine=False, ...
petejan/imos-toolbox
snapshot/snapshot.py
Python
gpl-3.0
1,834
0.014177
#!/usr/bin/python import os import sys import time import shutil import ziputil # snapshot.py # Exports the IMOS Toolbox from SVN and # # - Creates an archive of the source # - Runs Util/imosPackage.m to package the source # # These files are submitted back to the project as file downloads. # # python, svn (Sli...
)) shutil.copy('%s/imos-toolbox.zip' % exportDir, './%s' % stdArchive) try: submit(stdArchive) except: print('\n--Snapshot upload error. Check script, fix and then delete previous files before running new snapshot') print('\n--removing local git tree and archi
ves') shutil.rmtree('%s' % exportDir) os.remove(stdArchive)
pgk/genignore
genignore/helpers.py
Python
mit
616
0.008117
import sys from clint.textui import puts from clint.textui import colored from clint.textui import progress from clint.textui import columns TTY_COLUMN_SIZE = 80 isatty = lambda : sys.stdout.isatty() def print_colored(txt, color): if isatty(): puts(color(txt)) print_err
or = lambda txt: print_colored(txt, colored.red) print_notice = lambda txt: print_colored(txt, colored.yello
w) print_success = lambda txt: print_colored(txt, colored.green) def print_list(names, title=None): if title: print_notice('Available Templates:') puts(columns([", ".join(names), TTY_COLUMN_SIZE]))
mineo/picard
picard/formats/mutagenext/compatid3.py
Python
gpl-2.0
2,161
0.000463
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2006 Lukáš Lalinský # Copyright (C) 2005 Michael Urman # # 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...
own_frames["GRP1"] = GRP1 known_frames["TCMP"] = TCMP known_frames["TSO2"] = TSO2 known_frames["TSOC"] = TSOC known_frames["XDOR"] = XDOR known_frames["XSOP"] = XSOP class CompatID3(ID3): """ Additional features over mutagen.id3.ID3: * iTunes' TCMP frame * Allow some v2.4 frames also in v2.3 ""...
kwargs["known_frames"] = known_frames super().__init__(*args, **kwargs) def update_to_v23(self): # leave TSOP, TSOA and TSOT even though they are officially defined # only in ID3v2.4, because most applications use them also in ID3v2.3 frames = [] for key in ["TSOP...
googleapis/python-asset
google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py
Python
apache-2.0
1,176
0.00085
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
mport AssetServiceGrpcAsyncIOTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTran
sport]] _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport __all__ = ( "AssetServiceTransport", "AssetServiceGrpcTransport", "AssetServiceGrpcAsyncIOTransport", )
ivankokan/xbmc.plugin.video.nba
src/service.py
Python
gpl-3.0
3,711
0.003773
from tv import TV import xbmc, xbmcaddon import time, urllib, os, sys from urlparse import urlparse, parse_qs import vars # Add src/service in load paths my_addon = xbmcaddon.Addon(vars.__addon_id__) addon_dir = xbmc.translatePath(my_addon.getAddonInfo('path')).decode('utf-8') sys.path.append(os.path.join(addon_d...
while True: try: current_playing_url = self.player.getPlayingFile() self.readExpiresFromUrl(current_playing_url) utils.log("Playing url: %s - playing cache: %s" % (current_playing_url, self.shared_data.get("playing")), xbmc.LOGDEBUG) except: ...
checking the expiration if self.shared_data.get("playing.second_iteration") != "1": xbmc.sleep(2000) self.shared_data.set("playing.second_iteration", "1") continue timestamp = time.time() # Avoid refreshing too...
karllessard/tensorflow
tensorflow/python/training/session_manager_test.py
Python
apache-2.0
34,121
0.009173
# Copyright 2015 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...
eckpoint=True,
max_wait_secs=2) self.assertEqual( True, variables.is_variable_initialized( sess.graph.get_tensor_by_name("v:0")).eval(session=sess)) def _test_recovered_variable(self, checkpoint_dir=None, checkpoint_filenam...
dolaameng/keras
examples/mnist_swwae.py
Python
mit
6,417
0.001247
'''Trains a stacked what-where autoencoder built on residual blocks on the MNIST dataset. It exemplifies two influential methods that have been developed in the past few years. The first is the idea of properly "unpooling." During any max pool, the exact location (the "where") of the maximal value in a pooled re...
ion(mode=0, axis=1)(y) y = Activation('relu')(y) y = Convolution2D(nfeats, ksize, ksize, border_mode='same')(y) return merge([y0, y], mode='sum') def getwhere(x): ''' Calculate the "where" mask that contains switches indicating which index contained the max value when MaxPool2D was...
ice trick to keep everything high level.''' y_prepool, y_postpool = x return K.gradients(K.sum(y_postpool), y_prepool) # input image dimensions img_rows, img_cols = 28, 28 # the data, shuffled and split between train and test sets (X_train, _), (X_test, _) = mnist.load_data() X_train = X_train.resh...
PythonCharmers/python-future
src/future/moves/urllib/request.py
Python
mit
3,496
0
from __future__ import absolute_import from future.standard_library import suspend_hooks from future.utils import PY3 if PY3: from urllib.request import * # This aren't in __all__: from urllib.request import (getproxies, pathname2url, proxy_b...
import * # Rename: from urllib import toBytes # missing from __all__ on Py2.6 to_bytes = toBytes # from urllib import (pathname2url, # url2pathname, # getproxies, # urlretrieve, # ...
# proxy_bypass) # from urllib2 import ( # AbstractBasicAuthHandler, # AbstractDigestAuthHandler, # BaseHandler, # CacheFTPHandler, # FileHandler, # ...
mpgi/mpgi
editor/mpgi_editor/settings.py
Python
mit
3,319
0.001205
""" Django settings for mpgi_editor project. Generated by 'django-admin startproject' using Django 1.10.7. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ impor...
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE
': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValid...
PyPlanet/PyPlanet
pyplanet/core/events/manager.py
Python
gpl-3.0
6,932
0.028707
""" The events manager contains the class that manages custom and abstract callbacks into the system callbacks. Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals being created by other apps in a single place so it could be used over all apps. For exa...
urrent_namespace = None def register_signal(self,
signal, app=None, callback=False): """ Register a signal to be known in the signalling system. :param signal: Signal(s) :param app: App context/instance. :param callback: Will a callback handle the response (mostly raw callbacks). """ if isinstance(signal, list): for sig in signal: self.register_s...
mldbai/mldb
testing/MLDB-1242_sampled_dataset.py
Python
apache-2.0
6,502
0.004306
# ## # Francois Maillet, 11 janvier 2016 # This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved. # ## import unittest import random import datetime from mldb import mldb, ResponseException class SampledDatasetTest(unittest.TestCase): @classmethod def setUpClass(cls): # Create ...
et") self.assertEqual(len(rez.json()), 250) sampled_dataset_conf["params"]["fraction"] = 5
with self.assertRaises(ResponseException) as re: mldb.put("/v1/datasets/pwet", sampled_dataset_conf) self.assertEqual(re.exception.response.status_code, 400) sampled_dataset_conf["params"]["fraction"] = 0 with self.assertRaises(ResponseException) as re: mldb.put("/v...
meigrafd/Sample-Code
gpio_multifunction.py
Python
mit
3,122
0.01089
#!/usr/bin/python # -*- coding: utf-8 -*- # # http://www.forum-raspberrypi.de/Thread-python-taster-mit-mehreren-funktionen?pid=134513#pid134513 # # v0.1 by meigrafd # # https://github.com/SoCo/SoCo # import sys from time import sleep, time import RPi.GPIO as GPIO import signal from soco import SoCo #-------------------...
nt "special play" else: #normal play print "normal play" client.volume = 10 client.play() elif GPIO.input(Pause) == GPIO.HIGH: client.pause() elif GPIO.input(Lauter) == GPIO.HIGH: client.volume += 2 elif GPIO.input(Leiser) == GPI...
elif GPIO.input(Prev) == GPIO.HIGH: client.previous() else: print "ERROR! Unknown GPIO pin triggered: %s" % pin #------------------------------------------------------------------------ try: GPIO.add_event_detect(Play, GPIO.BOTH, callback=Interrupt_event, bouncetime=100) GPIO.add_event_de...
g-weatherill/hmtk
hmtk/seismicity/gcmt_utils.py
Python
agpl-3.0
5,792
0.008115
#!/usr/bin/env/python ''' Set of moment tensor utility functions ''' import numpy as np from math import fabs, log10, sqrt, acos, atan2, pi def tensor_components_to_use(mrr, mtt, mpp, mrt, mrp, mtp): ''' Converts components to Up, South, East definition USE = [[mrr, mrt, mrp], [mtt, mtt, mtp],...
.], [0., 1., 0.]]) def use_to_ned(tensor): ''' Converts a tensor in USE coordinate sytem to NED ''' return np.array(ROT_NED_USE.T * np.matrix(tensor) * ROT_NED_USE) def ned_to_use(tensor): ''' Converts a tensor in NED coordinate
sytem to USE ''' return np.array(ROT_NED_USE * np.matrix(tensor) * ROT_NED_USE.T) def tensor_to_6component(tensor, frame='USE'): ''' Returns a tensor to six component vector [Mrr, Mtt, Mpp, Mrt, Mrp, Mtp] ''' if 'NED' in frame: tensor = ned_to_use(tensor) return [tensor[0, 0], ten...
ecolell/pfamserver
tests/fixtures/uniprot.py
Python
agpl-3.0
304
0
from __fu
ture__ import unicode_literals import pytest from tests.factories import UniprotFactory @pytest.fixture def uniprot_egfr_human(): return UniprotFactory( uniprot_acc='P00533', uniprot_id='EGFR_HUMAN', description='Epidermal growth factor receptor EC=2.7.10.1'
)
kafana/ubik
lib/ubik/fab/jettypathhack.py
Python
gpl-3.0
1,655
0.00423
# Copyright 2012 Lee Verberne <lee@blarg.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 3 of the License, or # (at your option) any later version. # # This program is dis...
TY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org
/licenses/>. import ConfigParser import os, os.path from fabric.api import local, prompt, warn # Fabric 1.0 changed changed the scope of cd() to only affect remote calls. # This bit of kludgery maintains compatibility of this file with fabric 0.9, # but it is only possible because no remote calls are made in this fil...
open-geotechnical/ogt-ags-py
ogtgui/ags4_widgets.py
Python
gpl-2.0
27,425
0.008314
# -*- coding: utf-8 -*- """ @author: Peter Morgan <pete@daffodil.uk.com> """ from Qt import QtGui, QtCore, Qt, pyqtSignal from ogt import ags4 import app_globals as G from img import Ico import xwidgets from ags4_models import CG, AGS4_COLORS, HeadingsModel, AbbrevItemsModel class AGS4DataDictBrowser( QtGui.QWidg...
self.buttGroupFilter.addButton(rad, 3 if ridx == 2 else ridx) self.buttGroupFilter.button(0).setChecked(True) self.buttGroupFilter.buttonClicked.connect(self.on_filter_col) #self.comboSearchFor.
addItem("Code", CG.code) #self.comboSearchFor.addItem("Description", CG.description) #self.comboSearchFor.addItem("Code + Description", CG.search) #self.comboSearchFor.setMaximumWidth(150) # clear button self.buttClear = xwidgets.ClearButton(self, callback=self.on_clear_filter) ...
kmacinnis/sympy
bin/mailmap_update.py
Python
bsd-3-clause
3,001
0.002335
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A tool to help keep .mailmap and AUTHORS up-to-date. """ # TODO: # - Check doc/src/aboutus.rst # - Make it easier to update .mailmap or AUTHORS with the correct entries. from __future__ import print_function import os import sys from fabric.api import local, env from...
_skip =
["Kirill Smelkov <kirr@landau.phys.spbu.ru>"] predate_git = 0 exit1 = False print(blue(filldedent("""Read the text at the top of AUTHORS and the text at the top of .mailmap for information on how to fix the below errors. If someone is missing from AUTHORS, add them where they would have been if they were added aft...
cedricpradalier/vrep_ros_ws
src/rover_driver/nodes/rover_odom.py
Python
bsd-3-clause
4,100
0.014634
#!/usr/bin/env python import roslib; roslib.load_manifest('rover_driver') import rospy from std_msgs.msg import Float64 from sensor_msgs.msg import JointState from geometry_msgs.msg import Twist,Pose from math import atan2, hypot, pi, cos, sin import tf import message_filters import numpy from numpy.linalg import pinv ...
/%sDrive'%(self.name,k), rospy.Time(0), rospy.Duration(5.0)) ((x,y,z),rot) = self.listener.lookupTransform('/%s/ground'%(self.name), '/%s/%sDrive'%(self.name,k), rospy.Time(0)) self.radius[k] = z rospy.loginfo("Got transform for " + k) ...
n(): rate.sleep() if __name__ == '__main__': try: rd = RoverDriver("rover") rd.run() except rospy.ROSInterruptException: pass
astamp/PyXT
pyxt/tests/test_mda.py
Python
gpl-2.0
5,655
0.008665
import unittest from pyxt.mda import * from pyxt.chargen import CharacterGeneratorMock class MDATests(unittest.TestCase): def setUp(self): self.cg = CharacterGeneratorMock(width = 9, height = 14) self.mda = MonochromeDisplayAdapter(self.cg) # Hijack reset so it doesn't call into P...
lf.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_word_at_bottom_right(self): self.mda.mem_write_word(3998, 0x085A) # 'Z' with intensity.
self.assertEqual(self.mda.video_ram[3998], 0x5A) self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x5A, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_word_at_bottom_right_just_past(self): self.mda.mem_write_word(3999, 0xFF08)...
thaim/ansible
test/units/modules/network/check_point/test_cp_mgmt_service_icmp.py
Python
mit
3,878
0.001805
# Ansible module to manage CheckPoint Firewall (c) 2019 # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is dist...
r, connection_mock): mock_function = mocker.patch(function_path) mock_function.return_value = {'changed': True} result = self._run
_module(DELETE_PAYLOAD) assert result['changed'] def test_delete_idempotent(self, mocker, connection_mock): mock_function = mocker.patch(function_path) mock_function.return_value = {'changed': False} result = self._run_module(DELETE_PAYLOAD) assert not result['changed'] ...
chitwanix/Sagarmatha
files/usr/lib/sagarmatha-settings/bin/capi.py
Python
gpl-2.0
1,620
0.004938
# Copyright (C) 2007-2010 www.stani.be # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed...
_name(mod_id) if extension is None: print("Could not load %s module; is the sagarmatha-control-center package installed?" % mod_id) return None panel_type = extension.get_type() return GObject.new(panel_type) def lookup_c_module(self, mod_id): extension = sel...
t find %s module; is the sagarmatha-control-center package installed?" % mod_id) return False else: return True
andrei987/services
src/releng_clobberer/releng_clobberer/__init__.py
Python
mpl-2.0
1,316
0
# 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 http://mozilla.org/MPL/2.0/. from __future__ import absolute_imp
ort import click import json import os import releng_clobberer.cli import backend_common import backend_common.db DEBUG = bool(os.en
viron.get('DEBUG', __name__ == '__main__')) HERE = os.path.dirname(os.path.abspath(__file__)) APP_SETTINGS = os.path.abspath(os.path.join(HERE, '..', 'settings.py')) def init_app(app): return app.api.register( os.path.join(os.path.dirname(__file__), 'api.yml')) if DEBUG and not os.environ.get('DATABASE_...
jacksonwilliams/arsenalsuite
python/scripts/db_pruner.py
Python
gpl-2.0
794
0.036524
from blur.quickinit import * def tableSizeInMegs(tableName): q = Database.current().exec_('SELECT * FROM table_size_in_megs(?)',[QVariant(tableName)]) if q.next(): return q.value(0) return None def pruneTable(tableName, d
efaultSizeLimit, orderColumn, rowsPerIteration = 100): maxSize = Config.getInt('assburnerTableLimit' + tableName, defaultSizeLimit) tableNameLwr = str(tableName).lower() while tableSizeInMegs(tableNameLwr) > maxSize: q = Database.current().exec_('DELETE FROM %(name)s WHERE key%(name)
s IN (SELECT key%(name)s FROM %(name)s ORDER BY %(sort_col)s DESC LIMIT %(limit)i)' % {'name':tableNameLwr,'sort_col':orderColumn,'limit':rowsPerIteration} ) if q.numRowsAffected() < rowsPerIteration: break pruneTable('JobCommandHistory', 5000, 'keyjobcommandhistory')
walterdejong/synctool
contrib/attic/crc32.py
Python
gpl-2.0
463
0.041037
#! /usr/bin/env python # # CRC32 WJ103 # import zlib
def crc32(filename): '''calculate CRC-32 checksum of file''' f = open(filename, 'r') if not f: return '' crc = 0 while 1: buf = f.read(16384) if not buf: break crc = zlib.crc32(buf, crc) f.close() str_crc = '%x' % crc # print 'TD: CRC32 : %s' % str_crc return str_crc if __name__ == '__main__'...
1:]: print '%s %s' % (crc32(file), file) # EOB
martianstudio/stockanalysis
first_try.py
Python
apache-2.0
4,354
0.007809
import datetime import numpy as np import pandas as pd import sklearn from pandas.io.data import DataReader from sklearn.linear_model import LogisticRegression from sklearn.lda import LDA from sklearn.qda import QDA from sklearn.svm import SVC """ Feature X: T = Today's Price T - n = The n days before Today [T - 5,...
)] = tslag["Vol%s" % str(i+1)].pct_change()*100.0 # Create the "Direction" column (+1 or -1) indicating an up/down day # tsret["Direction"] = np.sign(tsret["Today"] - tsret["Lag5"]) #np.sign(tsret["Today"]) tsret = tsret[tsret.index >= start_date] return tsret def fit_model(name, model, X_train...
ification model (for our purposes this is LR, LDA and QDA) using the training data, then makes a prediction and subsequent "hit rate" for the test data.""" # Fit and predict the model on the training, and then test, data model.fit(X_train, y_train) pred[name] = model.predict(X_test) # Create a...
nicolewhite/py2neo
py2neo/legacy/__init__.py
Python
apache-2.0
826
0.001211
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2014, Nigel Small # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
e the License for the specific language governing permissions and # limitations under the License. from py2neo.legacy.batch import * from py2neo.legacy.core import * from py2neo.legacy.index import * __all__ = ["LegacyResource", "LegacyNode", "Index", "LegacyReadBatch", "Legac
yWriteBatch"]
thaim/ansible
lib/ansible/modules/network/aci/aci_static_binding_to_epg.py
Python
mit
14,726
0.002241
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2017, Bruno Calogero <brunocalogero@hotmail.com> # 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 ANSIBLE_METADATA = {'metadata_...
witch_port pod: 1 leafs: 101 interface: '1/7' state: absent dele
gate_to: localhost - name: Get specific Static Path binding for given EPG aci_static_binding_to_epg: host: apic username: admin password: SomeSecretPassword tenant: accessport-code-cert ap: accessport_code_app epg: accessport_epg1 interface_type: switch_port pod: 1 leafs: 101 ...
taimur97/Feeder
server/appengine/tasks.py
Python
gpl-2.0
4,156
0.002166
import webapp2 from google.appengine.api import taskqueue from util import (datetime_now, parse_timestamp, domain_from_url, datetuple_to_string) from cleaner import get_feeditem_model from models import (Feed
Model, FeedItemModel,
FeedModelKey, FeedItemKey) from storage import (get_feed, get_feedurls) import feedparser as fp # Don't remove embedded videos fp._HTMLSanitizer.acceptable_elements = \ set(list(fp._HTMLSanitizer.acceptable_elements) + ['object', 'embed', ...
CalPolyUROV/UROV2016
Last_Years_code/PythonServer/UI/pythonGenerator.py
Python
gpl-2.0
374
0.042781
import glob import os.path import sys from PyQt4 import uic UI_FILES = 'XML/*.ui' def compile_ui():
uifiles = glob.glob(UI_FILES) if len(uifiles) == 0: print 'none!' return with open('Generated/generatedGUI.py', 'w+b') as pyfile: for uifile in uifiles: uic.compileUi(uifile, pyfile) pyfile.close() if __name__ == '__m
ain__': compile_ui()
LukeC92/iris
lib/iris/tests/unit/fileformats/um/fast_load_structured_fields/test_FieldCollation.py
Python
lgpl-3.0
8,389
0
# (C) British Crown Copyright 2014 - 2017, Met Office # # This file is part of Iris. # # Iris 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 l...
result.keys()), keys) values, dims = result['blev'] self.assertArrayEqual(values, [1, 2]) self.assertEqual(dims, (0,)) def test_bhlev(self): collation = FieldColla
tion([_make_field(blev=0, bhlev=1), _make_field(blev=1, bhlev=2)]) result = collation.element_arrays_and_dims keys = set(['blev', 'brsvd1', 'brsvd2', 'brlev', 'bhrlev', 'lblev', 'bhlev']) self.assertEqual(set(result.keys()), keys) v...
abhyasi/euler_py
test/all_tests.py
Python
gpl-2.0
1,206
0.013267
import re import sys import glob import unittest def create_test_suite(testIds): # Grab a list of all test files in the directory test_file_strings = glob.glob('test/test_*.py') # Construct a list of test ids from argument filtered = [] if len(testIds) > 0: pattern = re.compile('(\d+)'...
section(set(available)))
# If specific problems have been specified as argument then invoke test for only those problems # map invocation may return empty string. filter them. module_strings = filter(lambda e: e is not None, map(lambda x: _filter(x, filtered), test_file_strings)) # Build the test s...
Kmayankkr/robocomp
tools/robocompdsl/templates/templateCPP/plugins/statemachine/functions/src/genericworker_cpp.py
Python
gpl-3.0
9,100
0.004835
from string import Template from templates.common.templatedict import TemplateDict STATEMACHINE_STATE_CREATION = """\ ${state_name}State = new ${state_type}(${child_mode}${parent}); """ STATEMACHINE_STATE_ADD = """\ ${statemachine_name}.addState(${state_name}State); """ VISUAL_STATEMACHINE_STATE_CREATION = """\ $...
s code_connects += connects code_set_initial_states += initials code_add_transitions = "" if statemachine['machine']['contents']['transitions'] is not None: code_add_transitions = self._statemachine_transition
s_creation(
nii-cloud/dodai-compute
nova/virt/dodai/ofc_utils.py
Python
apache-2.0
2,420
0.005785
from suds.client import Client from nova import exception from nova import db import logging logging.getLogger('suds').setLevel(logging.INFO) def update_for_run_instance(service_url, region_name, server_port1, server_port2, dpid1, dpid2): # check region name client = Client(service_url + "?wsdl") client...
dpid2, vlan_id): client = Client(service_url + "?wsdl")
client.service.clearServerPort(dpid1, server_port1) client.service.clearServerPort(dpid2, server_port2) client.service.save() dpid_datas = client.service.showSwitchDatapathId() for dpid_data in dpid_datas: ports = client.service.showPorts(dpid_data.dpid) for port in ports: ...
openstack/python-monascaclient
monascaclient/client.py
Python
apache-2.0
5,352
0
# (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP # Copyright 2017 Fujitsu LIMITED # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICE...
"""Handles all deprecations. Method goes through passed args and kwargs and handles all value
s that are invalid from POV of current client but: * has their counterparts * are candidates to be dropped """ kwargs.update(_handle_deprecated_args(args)) _handle_deprecated_kwargs(kwargs) def _handle_deprecated_kwargs(kwargs): depr_map = { 'tenant_name': ('project_name', lambd...
jason-neal/companion_simulations
simulators/bhm_script.py
Python
mit
5,758
0.002605
#!/usr/bin/env python """Run bhm analysis for HD211847.""" import argparse import sys import numpy as np import logging import simulators from joblib import Parallel, delayed from logutils import BraceMessage as __ from mingle.utilities.crires_utilities import barycorr_crires_spectrum from mingle.utilities.errors impo...
ue", help='Turn on Verbose.') return parser.parse_args(args) def main(star, obsnum, chip=None, suffix=None, error_off=False, disable_wav_scale=False, renormalize=Fals
e, norm_method="scalar", betasigma=False): """Best Host modelling main function.""" wav_scale = not disable_wav_scale star = star.upper() setup_bhm_dirs(star) # Define the broadcasted gamma grid gammas = np.arange(*simulators.sim_grid["gammas"]) # print("bhm gammas", gammas) ob...
plotly/python-api
packages/python/plotly/plotly/graph_objs/layout/scene/_domain.py
Python
mit
5,784
0.001902
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType import copy as _copy class Domain(_BaseLayoutHierarchyType): # class properties # -------------------- _parent_path_str = "layout.scene" _path_str = "layout.scene.domain" _valid_props = {"column", "row", "x", "y"...
elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError(
"""\ The first argument to the plotly.graph_objs.layout.scene.Domain constructor must be a dict or an instance of :class:`plotly.graph_objs.layout.scene.Domain`""" ) # Handle skip_invalid # ------------------- self._skip_invalid = kwargs.pop("skip_invalid", False) se...
msabramo/kallithea
kallithea/tests/models/test_notifications.py
Python
gpl-3.0
7,833
0.003575
from kallithea.tests import * from kallithea.model.db import User, Notification, UserNotification from kallithea.model.user import UserModel from kallithea.model.meta import Session from kallithea.model.notification import NotificationModel class TestNotifications(BaseTestCase): def __init__(self, methodName='...
[self.u1, self.u2] notific
ation = NotificationModel().create(created_by=self.u1, subject=u'subj', body=u'hi there', recipients=usrs) Session().commit() u1 = User.get(self.u1) u2 = User.get(self.u2) u3 = User.get(self.u3) ...
PennartLoettring/Poettrix
rootfs/usr/lib/python3.4/test/test_asyncio/__init__.py
Python
gpl-2.0
793
0
import os import sys import unittest from test.support import run_unittest, import_module # Skip tests if we don't have threading. import_module('threading') # Skip tests if we don't have concurrent.futures. import_module('concurrent.futures') def suite(): tests = unittest.TestSuite()
loader = unittest.TestLoader() for fn in os.listdir(os.path.dirname(__file__)): if fn.startswith("test") and fn.endswith(".py"): mod_name = 'test.test_asyncio.' + fn[:-3] try:
__import__(mod_name) except unittest.SkipTest: pass else: mod = sys.modules[mod_name] tests.addTests(loader.loadTestsFromModule(mod)) return tests def test_main(): run_unittest(suite())
shellphish/rex
rex/exploit/shellcodes/x86_leakaddress.py
Python
bsd-2-clause
876
0.001142
import claripy from ..shellcode import Shellcode class X86LeakAddress(Shellcode): os = ["cgc"] arches = ["X86"] name = "leakaddress" code = [b"\x31\xc0\x40\x40\x31\xdb\x43\xb9", b"\xba", b"\x31\xf6\xcd\x80"] def __init__(self, address, length):
""" :param addr: Address to leak. :param length: Amount of bytes to write from the leak. """ self.address = address self.length = length def raw(
self, arch=None): address, length = self.address, self.length if isinstance(self.address, int): address = claripy.BVV(address, 32) if isinstance(length, int): length = claripy.BVV(length, 32) bv_codes = [claripy.BVV(x) for x in self.code] return clarip...
mhbu50/erpnext
erpnext/hr/doctype/employee_transfer_property/test_employee_transfer_property.py
Python
gpl-3.0
167
0.005988
# Copyright (c) 2018, Frappe Technologies Pvt. Ltd. and Contri
butors # See license
.txt import unittest class TestEmployeeTransferProperty(unittest.TestCase): pass
diegocortassa/TACTIC
3rd_party/python3/site-packages/cheroot/test/test_dispatch.py
Python
epl-1.0
1,329
0
"""Tests for the HTTP server.""" # -*- coding: utf-8 -*- # vim: set fileencoding=utf-8 : from __future__ import absolute_import, division, print_function from cheroot.wsgi import PathInfoDispatcher def wsgi_invoke(app, environ): """Serve 1 requeset from a WSGI application.""" response = {} def start_re...
assert response == { 'status': '200 OK', 'headers': [ ('Content-Type', 'text/plain; charset=utf-8'), ], 'b
ody': b'Hello, world!', }
zooniverse/serengeti-analysis-scripts
validate-classifications-by-date-full-iteration.py
Python
apache-2.0
851
0.012926
#!/usr/bin/env python __author__ = 'alex' import pymongo import pickle print "Scanning classi
fications db..." # connect to the mongo server client = pymongo.MongoClient() db = client['serengeti3'] classification_collection = db["serengeti_classifications"] print "Collection contains %s documents." % db.command("collstats", "serengeti_classifications")["count"] # scan through *ALL* classifications and check w...
.find(no_cursor_timeout=True)): # .skip(skip).limit(limit) # skip tutorial classifications if "tutorial" in classification and classification["tutorial"]==True: continue if ii % 100000 == 0 or (ii > 10593400 and ii < 10593600): print "%s (id %s): created at %s" % (ii,classification["_id"],classification[...
tdent/pycbc
test/test_pnutils.py
Python
gpl-3.0
4,562
0.007234
# Copyright (C) 2012 Alex Nitz, Josh Willis # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the # Free Software Foundation; either version 3 of the License, or (at your # option) any later version. # # This program is distr...
Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ============================================================================= # # Preamble # # ============================================================================= # """ These are the unitte...
s import * from pycbc.scheme import * from utils import parse_args_cpu_only, simple_exit # We only need CPU tests parse_args_cpu_only("PN Utilities") class TestUtils(unittest.TestCase): def test_mass1_mass2_to_tau0_tau3(self): result = mass1_mass2_to_tau0_tau3(3.0,5.0,15.0) answer = (63.0390529880...