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
amilcarsj/analytic
analytic/al_strategies.py
Python
gpl-3.0
12,074
0.004307
import math import numpy as np from collections import defaultdict from analytic import trajectory_manager import scipy.sparse as ss from sklearn.naive_bayes import MultinomialNB, GaussianNB, BernoulliNB from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier from sklearn.linear_model import LogisticReg...
"""Overide method BaseStrategy.chooseNext **Parameters** * pool (*int*) - range of numbers within length of pool * X - None or pool.toarray() * model - None * k (*int*) - 1 or step size * current_train_indices - None or array of tr
ained indices * current_train_y - None or train_indices specific to y_pool **Returns** * [candidates[i] for i in dis[:k]] """ if not self.sub_pool: rand_indices = self.randgen.permutation(len(pool)) array_pool = np.array(list(pool)) candida...
vzer/ToughRADIUS
toughradius/console/control/control.py
Python
agpl-3.0
905
0.003315
#!/usr/bin/env python # coding:utf-8 import sys, os from twisted.internet import reactor from bottle import Bottle from bottle import request from bottle import response from bottle import redirect from bottle import static_file from bottle import abort from hashlib import md5 from urlparse import urljoin from toughrad...
static_path = os.path.join(os.path.split(os.path.split(__file__)[0])[0], 'static') return static_file(path, root=static_path) @app.get('/', apply=auth_ctl) def control_index(render): return render("index") @app.route('/dashboard', apply=auth_ct
l) def index(render): return render("index", **locals())
sdgdsffdsfff/jumpserver
apps/perms/api/user_permission/common.py
Python
gpl-2.0
3,904
0.000512
# -*- coding: utf-8 -*- # import uuid from django.shortcuts import get_object_or_404 from rest_framework.views import APIView, Response from rest_framework.generics import ( ListAPIView, get_object_or_404, RetrieveAPIView ) from common.permissions import IsOrgAdminOrAppUser, IsOrgAdmin from common.utils import ge...
inOrAppUser,) serializer_class = serializers.AssetSystemUserSerializer only_fields = serializers.AssetSystemUserSerializer.Meta.only_fields def get_queryset(self): asset_id = self.kwargs.get('asset_id') asset = get_object_or_404(Asset, id=asset_id)
system_users_with_actions = self.util.get_asset_system_users_with_actions(asset) system_users = [] for system_user, actions in system_users_with_actions.items(): system_user.actions = actions system_users.append(system_user) system_users.sort(key=lambda x: x.priority...
algorhythms/LeetCode
658 Find K Closest Elements.py
Python
mit
2,116
0.007089
#!/usr/bin/python3 """ Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred. Example 1: Input: [1,2,3,4,5], k=4, x=3 Output: [1,2,3,4] Example 2: Input: [1,2,3,4,5], k...
lo = mid + 1 else: hi = mid return A[lo:lo+k] def
findClosestElements2(self, A: List[int], k: int, x: int) -> List[int]: """ input sorted arrya two pointers """ n = len(A) idx = bisect_left(A, x) ret = deque() i = idx - 1 j = idx while k: if 0 <= i < n and 0 <= j < n: ...
eschava/broadlink-mqtt
test.py
Python
mit
1,269
0.002364
# noinspection PyMethodMayBeStatic class TestDevice: def __init__(self,
cf): self.type = cf.get('device_test_type', 'test') self.host = ('test', 80) self.mac = [1, 2, 3, 4, 5, 6] def auth(self): pass # RM2/RM4 def check_temperature(self): return 23.5 # RM4 def check_humidity(self): return 56 def enter_learning(sel...
payload = bytearray(5) payload[0] = 0xAA payload[1] = 0xBB payload[2] = 0xCC payload[3] = 0xDD payload[4] = 0xEE return payload def send_data(self, data): pass def check_sensors(self): return {'temperature': 23.5, 'humidity': 36, 'light': 'dim',...
osbjmg/evt
bin/evt.py
Python
mit
14,898
0.009666
#!/usr/bin/python # -* coding: UTF-8 -*- #import iso8602 #import iso-8601 import pprint import cgi import cgitb import json from slackclient import SlackClient import datetime import pytz import re import os #### ToDo #### # Assume wallClockTime is not None scenario time is not negative, go to the next day # Convert a...
: timeValid = False # convert time # present time in a nifty manner, left/right eve time, your time, difference, colors # see elephants formatting, color t
z_city, tz, offset, now, name = getUserTimezone(user) response_type = 'in_channel' if timeValid is True : hours=int(hours) minutes=int(minutes) reqdEveTime = now.replace(hour=hours, minute=minutes) difference = int((reqdEveTime - now).total_seconds()) ...
shuxin/androguard
androguard/decompiler/dad/decompile.py
Python
apache-2.0
18,369
0.001633
from __future__ import print_function import sys from builtins import input from builtins import map # This file is part of Androguard. # # Copyright (c) 2012 Geoffroy Gueguen <geoffroy.gueguen@gmail.com> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this...
e[start] = ThisParam(start, self.cls_name) self.lparams.append(start) start += 1 num_param = 0 for ptype in self.params_type: param = start + num_param self.lparams.append(param)
self.var_to_name[param] = Param(param, ptype) num_param += util.get_type_size(ptype) if not __debug__: from androguard.core import bytecode bytecode.method2png('/tmp/dad/graphs/%s#%s.png' % \ (self.cls_name.split('/')[-1][:-1...
code-for-india/sahana_shelter_worldbank
private/templates/India/config.py
Python
mit
167,905
0.007278
# -*- coding: utf-8 -*- try: # Python 2.7 from collections import OrderedDict except: # Python 2.6 from gluon.contrib.simplejson.ordered_dict import OrderedDict from datetime import timedelta from gluon import current, Field, URL from gluon.html import * from gluon.storage import Storage from gluon.v...
anisation_roles = { # 1: T("Host National Society"), # 2: T("Partner"), # 3: T("Donor"), # #4: T("Customer"), # T("Beneficiary")? # #5: T("Supplier"), # 9: T("Partner National Society"), #} # ----------------------------------------------------------------------------- # Notifications # Template for ...
sub
irvingprog/pilas
pilas/test/test_interface.py
Python
lgpl-3.0
736
0.002717
import pilas def test_todos_los_objetos_de_interfaz_se_pueden_crear(): pilas.iniciar() deslizador = pilas.interfaz.Deslizador() assert deslizador assert deslizador.progreso == 0 boton = pilas.interfaz.Boton() assert boton
ingreso = pilas.interfaz.IngresoDeTexto() assert ingreso try: pilas.interfaz.ListaSeleccion() except TypeError: assert True # Se espera esta excepcion, porque un argumento es obligatorio lista = pilas.interfaz.ListaSeleccion([('uno')]) assert lista try: pilas.i...
la") assert selector
dnjohnstone/hyperspy
hyperspy/tests/component/test_gaussian2d.py
Python
gpl-3.0
2,985
0
# -*- coding: utf-8 -*- # Copyright 2007-2020 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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...
= np.radians(20) g.rotation_angle.value = angle assert_allclose(g.rotation_angle_wrapped, angle) angle = np.radians(380) g.rotation_angle.value = angle assert_allclose(g.rotation_angle_wrapped, math.fmod(angle, 2 * np.pi)) g = Gaussian2D(add_rotation=True) g.sigma_x.value = 0.5 g.sigma...
1 angle = np.radians(20) g.rotation_angle.value = angle assert_allclose(g.rotation_angle_wrapped, angle) assert_allclose(g.rotation_major_axis, angle) g = Gaussian2D(add_rotation=True) g.sigma_x.value = 0.1 g.sigma_y.value = 0.5 assert g.ellipticity == 5.0 assert g.rotation_angle.va...
bqbn/addons-server
src/olympia/lib/tests/test_cache.py
Python
bsd-3-clause
1,418
0.001445
# -*- coding: utf-8 -*- from django.utils import translation from django.core.cache import cache from olympia.lib.cache import memoize, memoize_key, make_key def test_make_key(): with translation.override('en-US'): assert make_key('é@øel') == 'é@øel:en-us' with translation.override('de'): as...
'en-US'): assert make_key('é@øel', normalize=True) == '2798e65bbe384320c9da7930e93e63fb' assert ( make_key('é@øel', with_locale=
False, normalize=True) == 'a83feada27737072d4ec741640368f07' ) with translation.override('fr'): assert make_key('é@øel', normalize=True) == 'bc5208e905c8dfcc521e4196e16cfa1a' def test_memoize_key(): assert memoize_key('foo', ['a', 'b'], {'c': 'e'}) == ( 'memoize:foo:9666a2a48c17dc...
etos/django
tests/model_fields/test_floatfield.py
Python
bsd-3-clause
1,149
0
from django.db import transaction from django.test import TestCase from .models import FloatModel class TestFloatField(TestCase): def test_float_validates_object(self): instance = FloatModel(size=2.5) # Try setting float field to unsaved object instance.size = instance with trans...
nce instance.size = instance msg = ( 'Tried to update field model_fields.FloatModel.size with a model ' 'instance, %r. Use a value ' 'compatible with FloatField.' ) % instance with transaction.atomic(): with self.assertRaisesMessage(TypeErr...
atModel.objects.get(pk=instance.id) obj.size = obj with self.assertRaises(TypeError): obj.save()
r0k3/arctic
tests/unit/date/test_util.py
Python
lgpl-2.1
3,570
0.003641
import pytest import pytz from datetime import datetime as dt from arctic.date import datetime_to_ms, ms_to_datetime, mktz, to_pandas_closed_closed, DateRange, OPEN_OPEN, CLOSED_CLOSED from arctic.date._mktz import DEFAULT_TIME_ZONE_NAME from arctic.date._util import to_dt @pytest.mark.parametrize('pdt', [ ...
to_dt(dt(1970, 1, 1, tzinfo=mktz('UTC')), mktz('Europe/London')) == dt(1970, 1, 1, tzinfo=mktz('UTC')) def test_daterange_raises(): with pytest.raises(ValueError): assert(DateRange(dt(2013, 1, 1), dt(2000, 1, 1))) def test_daterange_eq(): dr = DateRange(dt(2013, 1, 1)) assert((dr == None) == Fal...
(dr2 < dr) == False)
magnusgasslander/sqlalchemy-bigquery
sqlalchemy_bigquery/gcp/authorize/authorize.py
Python
mit
3,503
0.003426
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
authorize(self, scope = 'https://www.googleapis.com/auth/bigquery', key_path = None): """ Returns an authorized HTTP object to be used to build a Google cloud service hook connection. """ kwargs = {} if not key_path: logging.info('Getting connection using `g...
auth` user, since no key file ' 'is defined for hook.') credentials = GoogleCredentials.get_application_default() else: if not scope: raise Exception('Scope should be defined when using a key file.') scopes = [s.strip() for s in scope....
Jidgdoi/PacmanPy
src/GhostAI.py
Python
gpl-2.0
5,502
0.035474
# -*- coding:utf-8 -*- # Cyril Fournier # 19/01/2016 import random import threading import Queue import time import UtilsAndGlobal as UAG # ============================== # === Class Ghost === # ============================== class Ghost(): """ Object representing a ghost. """ def __init__(self, ID, sta...
UAG.MovementUp self.countdownFear = 0.0 def __repr__(self): return "%s%s\033[0m: %s" %(self.color, self.ID, "Alive" if self.state == 1 else "Afraid" if self.state == 2
else "Dead") def setNewDirection(self, direction): """ Set new direction for the ghost. """ self.mvt = direction def booh(self): """ Change ghost's state to GhostAfraid and make him turn back. """ if self.state == UAG.GhostAlive: self.state = UAG.GhostAfraid # Turn back if self.mvt == UAG.M...
CuBoulder/atlas
atlas/instance_operations.py
Python
mit
24,722
0.003276
""" atlas.instance_operations ~~~~ Commands that run on servers to deploy instances. Instance methods: Create - Local - All symlinks are in place, DB exists, NFS mount is attached Update - Local and Update code or configuration; Delete - Local - Remove instance symlinks, delete settings fil...
for symlink if not os.path.islink(site_files_dir): # Check if directory is empty and remove it if it is if not os.listdir(site_files_dir):
os.rmdir(site_files_dir) else: # Remove symlink os.remove(site_files_dir) os.symlink(nfs_src, site_files_dir) # Create setttings file switch_settings_files(instance) # Create symlinks for current in instance root, 'sid' and 'path' (if needed) ...
torehc/carontepass-v2
web/carontepass/access/migrations/0002_user.py
Python
gpl-3.0
962
0.002079
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('access', '0001_initial'), ] operations = [ migrations.CreateModel(
name='User', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.Cha
rField(max_length=60)), ('last_name', models.CharField(max_length=120)), ('rol', models.CharField(default=b'USER', max_length=4, choices=[(b'USER', b'User'), (b'ADMI', b'Administrator')])), ('phone', models.CharField(max_length=18)), ('address', models.Cha...
google/jax-cfd
jax_cfd/spectral/time_stepping.py
Python
apache-2.0
8,747
0.009049
# Copyright 2021 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 agreed to in writing, ...
disable=line-too-long return low_storage_runge_kutta_crank_nicolson( alphas=[0, 0.1496590219993, 0.3704009573644, 0.6222557631345, 0.9582821306748, 1], betas=[0, -0.4178904745, -1.192151694643, -1.697784692471, -1.514183444257], gammas=[0.
1496590219993, 0.3792103129999, 0.8229550293869, 0.6994504559488, 0.1530572479681], equation=equation, time_step=time_step, ) @dataclasses.dataclass class ImExButcherTableau: """Butcher Tableau for implicit-explicit Runge-Kutta methods.""" a_ex: Sequence[Sequence[float]] a_im: Sequence[Sequence[fl...
whitepyro/debian_server_setup
sickbeard/scene_numbering.py
Python
gpl-3.0
25,288
0.003282
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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,...
Returns a tuple, (season, episode, absolute_number) with the TVDB and TVRAGE numbering for (sceneAbsoluteNumber) (this works like the reverse of get_absolute_numbering) """ if indexer_id is None or sceneAbsoluteNumber is None:
return sceneAbsoluteNumber indexer_id = int(indexer_id) indexer = int(indexer) myDB = db.DBConnection() if scene_season is None: rows = myDB.select( "SELECT absolute_number FROM scene_numbering WHERE indexer = ? and indexer_id = ? and scene_absolute_number = ?", ...
Comunitea/CMNT_00098_2017_JIM_addons
shipping_container/models/shipping_container.py
Python
agpl-3.0
3,735
0.002678
# -*- coding: utf-8 -*- # © 2016 Comunitea - Kiko Sanchez <kiko@comunitea.com> # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0. from odoo import api, fields, models, _ import odoo.addons.decimal_precision as dp class ShippingContainerType(models.Model): _name = "shipping.container.type" name = fi...
g.container" @api.one def _get_moves(self): self.move_ids_count = len(self.move_ids) @api.one def _get_partners(self): self.partner_ids = self.picking_ids.partner_id @api.multi def _available_volume(self):
for container in self: volume = container.shipping_container_type_id.volume weight = 0.00 for move in container.move_ids: volume -= move.product_id.volume * move.product_uom_qty weight += move.product_id.weight * move.product_uom_qty c...
google/tink
python/tink/_keyset_reader.py
Python
apache-2.0
2,497
0.009211
# Copyright 2019 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 agreed to in writing, ...
) def read_encrypted(self) -> tink_pb2.EncryptedKeyset: if not self._serialized_keyset: raise core.TinkError('No keyset found') try: return tink_pb2.EncryptedKeyset.FromString(self._serial
ized_keyset) except message.DecodeError as e: raise core.TinkError(e)
ahu-odoo/odoo
openerp/models.py
Python
agpl-3.0
274,326
0.003879
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
. import SUPERUSER_ID from . import api from . import tools from .api import Environment from .exceptions import except_orm, AccessError, MissingError from .osv i
mport fields from .osv.query import Query from .tools import lazy_property from .tools.config import config from .tools.misc import CountingStream, DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT from .tools.safe_eval import safe_eval as eval from .tools.translate import _ _logger = logging.getLogger(__name...
khufkens/daymetpy
setup.py
Python
agpl-3.0
955
0.024084
from distutils.core import setup setup( name = 'daymetpy', packages = ['daymetpy'], version = '1.0.0', license = 'AGPL-3', description = 'A library for accessing Daymet surface weather data', author = 'Koen Hufkens', author_email = 'koen.hufkens@gmail.com', url = 'https://github.com/khufkens/daymetpy', ...
se v3', # Python versions supported 'Programming Language ::
Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5' ], )
samsu/neutron
tests/unit/ml2/drivers/mechanism_bulkless.py
Python
apache-2.0
872
0
# Copyright (c) 2014 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in complia
nce 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 dist
ributed 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. from neutron.plugins.ml2 import driver_api as api class BulklessMechanismDriver(api.MechanismDriver):...
SXBK/kaggle
zillow/xgb.py
Python
gpl-3.0
2,782
0.00683
# This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load in import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O...
train_columns] del df_test; gc.collect() for c in x_test.dtypes[x_test.dtypes == object].index.values: x_test[c] = (x_test[c] == True) x_test = x_test.values.astype(np.float32, copy=False) print("Start prediction ...") d_test = xgb.DMatrix(x_test) p_test = clf.predict(d_test) del x
_test; gc.collect() print("Start write result ...") sub = pd.read_csv('data/sample_submission.csv') for c in sub.columns[sub.columns != 'ParcelId']: sub[c] = p_test sub.to_csv('out/xgb.csv', index=False, float_format='%.4f')
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/newrelic-2.46.0.37/newrelic/common/encoding_utils.py
Python
agpl-3.0
9,031
0.001218
"""This module implements assorted utility functions for encoding/decoding of data. """ import types import base64 import json import zlib from hashlib import md5 from ..packages import six # Functions for encoding/decoding JSON. These wrappers are used in order # to hide the differences between Python 2 and Python...
the wrappers to supply # defaults. def json_encode(obj, **kwargs): _kwargs = {} # This wrapper function needs to deal with a few issues. # # The first is that when a byte string is provided, we need to # ensure that it is interpreted as being Latin-1. This is necessary # as by default JSON wil...
# invalid UTF-8 byte string is provided, a failure will occur when # encoding the value. # # The json.dumps() function in Python 2 had an encoding argument # which needs to be used to dictate what encoding a byte string # should be interpreted as being. We need to supply this and set it # to L...
cinek810/refractiveindex.info
plot.py
Python
gpl-2.0
2,040
0.042857
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import yaml from parse import * import sys import cmath import numpy as np from getData import * def NtoEps(matVec): matVec=np.array(matVec) lamb=matVec[:,0] n=matVec[:,1] k=matVec[:,2] N=n[:]+1j*k[:] eps=N[:]*N[:] matEps=[...
,label=r'Imag($\varepsilon_{Ag}$)') #plt.plot(lambdasTiO2*1e3,[ (x*x).real for x in tio2],'g-',label=r'Real($\varepsilon_{TiO_{2}}$)') plt.legend() plt.title(r"Współczynnik przenikalnośći elektryczne
j ($\varepsilon$)"); plt.ylabel('') plt.xlabel('wavelength [nm]') plt.xlim([380,750]) #plt.ylim([-1.5,1.5]) plt.savefig("../phd/images/agtio2eps.png") ######## #GaAs do rozdzialu o THz plt.show()
wazo-pbx/xivo-auth
wazo_auth/__init__.py
Python
gpl-3.0
310
0
# Copyright 2015-2020 The Wazo Authors (see the AUTHORS file) # SPDX-License-Identifier: GPL-3.0-or-later from wazo_auth.interfaces import ( BaseAuthenticationBackend,
BaseMetadata, DEFA
ULT_XIVO_UUID, ) __all__ = [ 'BaseAuthenticationBackend', 'BaseMetadata', 'DEFAULT_XIVO_UUID', ]
superdesk/Live-Blog
plugins/livedesk-sync/livedesk/core/impl/icon_content.py
Python
agpl-3.0
3,125
0.0032
''' Created on August 19, 2013 @package: livedesk-sync @copyright: 2013 Sourcefabric o.p.s. @license: http://www.gnu.org/licenses/gpl-3.0.txt @author: Martin Saturka Content for icons of collaborators of chained blogs. ''' import socket import logging from urllib.request import urlopen from ally.api.model import Con...
r-Agent' : 'Magic Browser'}) self._response = urlopen(req) except (HTTPError, socket.error) as e: log.error('Can not read icon im
age data %s' % e) raise InputError(Ref(_('Can not open icon URL'),)) if not self._response: log.error('Can not read icon image data %s' % e) raise InputError(Ref(_('Can not open icon URL'),)) if str(self._response.status) != '200': ...
yupswing/yaps
lib/sound_engine.py
Python
mit
1,288
0.000776
# # YetAnotherPythonSnake 0.94 # Author: Simone Cingano (simonecingano@gmail.com) # Web: http://simonecingano.it # Licence: MIT # import pygame import os # YASP common imports import data if pygame.mixer: pygame.mixer.init() class dummysound: def play(self): pass class SoundPlayer: def __init__(...
def play(self, sound): self.sounds[sound].play() def load(self, key, filename): self.sounds[key] = self.load_sound(filename) def load_sou
nd(self, filename): if not pygame.mixer: return dummysound() filepath = data.filepath("sfx", filename) if filepath: sound = pygame.mixer.Sound(filepath) return sound else: return dummysound() EXTENSION = os.name == 'nt' and '.mp3' or '.og...
Azure/azure-sdk-for-python
sdk/appservice/azure-mgmt-web/azure/mgmt/web/v2021_03_01/aio/operations/_recommendations_operations.py
Python
mit
48,433
0.004852
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
for a
subscription. Description for Reset all recommendation opt-out settings for a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpR...
impulse-cloud/web-ping
run-web-ping.py
Python
mit
364
0.005495
impo
rt requests import time import traceback import sys print "Web Ping running..." print "All connection exceptions will be output to stdout." while True: time.sleep(5) try: r = requests.get('http://web/') except: print "Exception in request:"
print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60
nocarryr/django-ingress-agent-info
ingress_agent_info/locations/models.py
Python
gpl-2.0
5,462
0.006225
import urllib, urllib2 import json from django.contrib.gis.db import models from django.contrib.gis import geos class Country(models.Model): name = models.CharField(max_length=30, unique=True) short_name = models.CharField(max_length=10, unique=True) objects = models.GeoManager() def __unicode____(...
urllib.quote_plus(address) show_debug = kwargs.get('show_debug', False) LOG = kwargs.get('log_fn') if LOG is N
one: def LOG(*args): if not show_debug: return print '\t'.join([str(arg) for arg in args]) conf = {} for key in GEOCODING_CONF_DEFAULTS.keys(): try: conf_item = GeoCodingConf.objects.get(name=key) except GeoCodingConf.DoesNotExist: ...
p1c2u/openapi-core
tests/integration/contrib/django/test_django_project.py
Python
bsd-3-clause
10,712
0
import os import sys from base64 import b64encode from json import dumps from unittest import mock import pytest class BaseTestDjangoProject: api_key = "12345" @property def api_key_encoded(self): api_key_bytes = self.api_key.encode("utf8") api_key_bytes_enc = b64encode(api_key_bytes) ...
assert expected_data in response.content def test_get_unauthorized(self, client): headers = { "HTTP_HOST": "petstore.swagger.io", }
response = client.get("/v1/pets/12", **headers) expected_data = { "errors": [ { "class": ( "<class 'openapi_core.validation.exceptions." "InvalidSecurity'>" ),
khughitt/ete
ete_dev/orthoxml/__init__.py
Python
gpl-3.0
25
0.04
from _ortho
xml
import *
vincentltz/MobileR
Scraper/myUtility.py
Python
apache-2.0
2,217
0.032927
''' Copyright 2015 Kendall Bailey Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in w...
): print "Error: " + pattern print "length = " + str(len(sys.argv)) sys.exit(2) def OverwriteFile(filename, data): try: with open(filename, 'w') as outfile: outfile.write(data) outfile.close() except UnicodeEncodeErr
or as e: print "Unicode Encode Error: Couldn't write --" + data + "-- to file" sys.exit(2) def AppendToFile(filename, data): try: with open(filename, 'a') as outfile: outfile.write(data) outfile.close() except UnicodeEncodeError as e: print "Unicode Encode Error: Couldn't write --" + data + "-- to fi...
bgris/ODL_bgris
odl/test/largescale/tomo/analytic_slow_test.py
Python
gpl-3.0
7,939
0.000756
# Copyright 2014-2016 The ODL development group # # This file is part of ODL. # # ODL 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. #...
skip_if_no_astra_cuda('par2d astra_cuda uniform'), skip_if_no_astra_cuda('cone2d astra_cuda uniform'), skip_if_no_astra_cuda('par3d astra_cuda uniform'), skip_if_no_astra_cuda('cone3d astra_cuda uniform'),
skip_if_no_astra_cuda('helical astra_cuda uniform'), skip_if_no_scikit('par2d scikit uniform')] projector_ids = ['geom={}, impl={}, angles={}' ''.format(*p.args[1].split()) for p in projectors] # bug in pytest (ignores pytestmark) forces us to do this this largescale = " or not ...
alex/readthedocs.org
readthedocs/core/admin.py
Python
mit
356
0.005618
"""Djang
o admin interface for core models. """ from django.contrib import admin from core.models import UserProfile class UserProfileAdmin(admin.ModelAdmin): list_display = ('user', 'whitelisted', 'homepage') search_fields = ('user__username', 'homepage') list_edita
ble = ('whitelisted',) admin.site.register(UserProfile, UserProfileAdmin)
ryanbressler/numpy2go
numpy2go.py
Python
bsd-2-clause
496
0.004032
import numpy as np import ctypes import numpy.ctypeslib as npct # For more information see: # https://scipy-lectures.github.io/advanced/interfacing_with_c/interfacing_with_c.html#id5 numpy2go = npct.load_library
("numpy2go", ".") array_1d_double = npct.ndpointer(dtype=np.double, ndim=1, flags='CONTIGUOUS') numpy2go.Test.restype = None numpy2go.Test.argtypes = [array_1d_double, ctypes.c_int] data = np.array([0.0, 1.0, 2.0]) print("Python says", data) numpy2go.Te
st(data, len(data))
smartbgp/yarib
yarib/db/mongodb.py
Python
apache-2.0
4,903
0.001224
# Copyright 2015 Cisco Systems, 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 requi...
ns(read_preference=pymongo.ReadPreference.NEAREST) else: LOG.error('unknow read preference setting') pass # for write concern if self.w > -1: coll.write_concern['w'] = self.w coll...
name] = coll return self._MONGO_COLLS[self.collection_name] def remove_collection(self): self._DB[self.db_name].drop_collection(self.collection_name)
ketan-analytics/learnpython
Safaribookonline-Python/courseware-btb/solutions/py3/patterns/properties_extra.py
Python
gpl-2.0
2,255
0.000887
''' Ohm's law is a simple equation describing electr
ical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create...
this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want ...
UnderXirox/Python-3_Des-fichiers-complementaires
test_asyncio_35.py
Python
gpl-3.0
1,476
0.009498
#!/usr/bin/p
ython3.4 from itertools import permutations import asyncio from time import time class BoardTester: def __init__(self, n): self.data = permutations(range(n)) async def __aiter__(self): return self async d
ef __anext__(self): return await next(self.data) async def nqueens_async_coroutine(n): async for board in BoardTester(n): if n == len(set(board[i]+i for i in columns)) \ == len(set(board[i]-i for i in columns)): pass # print(board) # await (board for board in permutatio...
nttks/edx-platform
cms/djangoapps/course_creators/tests/test_admin.py
Python
agpl-3.0
7,332
0.004501
""" Tests course_creators.admin.py. """ from django.test import TestCase from django.contrib.auth.models import User from django.contrib.admin.sites import AdminSite from django.http import HttpRequest import mock from course_creators.admin import CourseCreatorAdmin from course_creators.models import CourseCreator fr...
urse_creator_denied.txt' else: template = 'emails/course_creator_revoked.txt' email_user.assert_called_with(
mock_render_to_string('emails/course_creator_subject.txt', context), mock_render_to_string(template, context), self.studio_request_email ) with mock.patch.dict('django.conf.settings.FEATURES', self.enable_creator_group_patch): # User is initially unrequ...
RandolphVI/CNN-Text-Classification
SANN/train_sann.py
Python
apache-2.0
11,145
0.004217
# -*- coding:utf-8 -*- __author__ = 'Randolph' import os import sys import time import logging sys.path.append('../') logging.getLogger('tensorflow').disabled = True import numpy as np import tensorflow as tf from tensorboard.plugins import projector from text_sann import TextSANN from utils import checkmate as cm f...
ad_seqs'], data['onehot_labels']) def train_sann(): """Training RNN model.""" # Print parameters used for the model dh.tab_printer(args, logger) # Load word2vec model word2idx, embedding_matrix = dh.load_word2vec_matrix(args.word2vec_file) # Load sentences, labels, and training parameters ...
ding data...") logger.info("Data processing...") train_data = dh.load_data_and_labels(args, args.train_file, word2idx) val_data = dh.load_data_and_labels(args, args.validation_file, word2idx) # Build a graph and sann object with tf.Graph().as_default(): session_conf = tf.ConfigProto( ...
crwilcox/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/networkresourceprovider.py
Python
apache-2.0
866,693
0.007992
# # Copyright (c) Microsoft and contributors. 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 a...
OperationResponse, self).__init__(**kwargs) self._azure_async_operation = kwargs.get('azure_async_operation') @property def azure_async_operation(self): """ Users can perform a Get on Azure-AsyncOperation to get t
he status of their update(PUT/PATCH/DELETE) operations """ return self._azure_async_operation @azure_async_operation.setter def azure_async_operation(self, value): self._azure_async_operation = value class LoadBalancerGetResponse(AzureOperationResponse): """ Resp...
rafaelthca/OmniDB
OmniDB/omnidb-server.py
Python
mit
12,308
0.011618
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import platform import random import string #Parameters import optparse import configparser import OmniDB.custom_settings OmniDB.custom_settings.DEV_MODE = False OmniDB.custom_settings.DESKTOP_MODE = False parser = optparse.OptionParser(version=OmniD...
pps import django.contrib.admin.apps import django.contrib.au
th.apps import django.contrib.contenttypes.apps import django.contrib.sessions.apps import django.contrib.messages.apps import OmniDB_app.urls import django.contrib.messages.middleware import django.contrib.auth.middleware import django.contrib.sessions.middleware import django.contrib.sessions.serializers import djang...
FreshXOpenSource/wallaby-base
wallaby/pf/peer/pref.py
Python
bsd-2-clause
2,613
0.003444
# Copyright (c) by it's authors. # Some rights reserved. See LICENSE, AUTHORS. from peer import * from documentCache import DocumentCache from viewer import Viewer class Pref(Peer): Load = Pillow.In Add = Pillow.In NoDocument = Pillow.Out SheetNotFound = Pillow.Out Ready = Pillow.OutState ...
ut.Ready, False) def __init__(self, room, controller, configDocId, path): Peer.__init__(self,
room) self._configDoc = None self._path = path self._configRev = None self._docRev = None self._document = None self._controller = controller self._configDocId = configDocId self._catch(Pref.In.Add, self._add) self._catch(Viewer.In.Document, s...
petterreinholdtsen/creepy
creepy/models/ProjectWizardPluginListModel.py
Python
gpl-3.0
2,179
0.005507
#!/usr/bin/python # -*- coding: utf-8 -*- from PyQt4.QtCore impo
rt QVariant, QAbstractListModel, Qt from PyQt4.Qt import QPixmap, QFileSystemModel, QIcon from utilities import GeneralUtilities import os class ProjectWizardPluginListModel(QAbstractListModel): def __init__(self, plugins, parent=None): super(ProjectWizardPluginListModel, self).__init__(parent) se...
ef rowCount(self, index): return len(self.plugins) def data(self, index, role): plugin = self.plugins[index.row()][0] if index.isValid(): if role == Qt.DisplayRole: return QVariant(plugin.name) if role == Qt.DecorationRole: for dir...
skorokithakis/nxt-python
nxt/server.py
Python
gpl-3.0
9,781
0.007054
# nxt.server module -- LEGO Mindstorms NXT socket interface module # Copyright (C) 2009 Marcus Wanner # # 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 ...
ouch_sample'): try: port = string.split(c
md, ':')[1] port = _process_port(port) retmsg = str(TouchSensor(brick, port).get_sample()) retcode = 0 except: retcode = 1 retmsg = str(sys.exc_info()[1]) elif cmd.startswith('get_sound_sample'): try: port = string.sp...
banderlog/greed
greed/colors.py
Python
mit
370
0.018919
class Color: ''' print() wrappers for console colors ''' d
ef red(*args, **kwargs): print("\033[91m{}\033
[0m".format(" ".join(map(str,args))), **kwargs) def green(*args, **kwargs): print("\033[92m{}\033[0m".format(" ".join(map(str,args))), **kwargs) def yellow(*args, **kwargs): print("\033[93m{}\033[0m".format(" ".join(map(str,args))), **kwargs)
billryan/github-rss
github/gh.py
Python
mit
5,484
0.000547
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import getpass import requests import ConfigParser BASE_DIR = os.path.dirname(__file__) class Auth: """GitHub API Auth""" def __init__(self): self.auth_url = 'https://api.github.com' auth_conf = os.path.join(BASE_DIR, 'auth.co...
po_info['author']) return fg def add_entry(self, fg, co
mmit_info): fe = fg.add_entry() fe.title(commit_info['message']) fe.link(href=commit_info['html_url']) id_prefix = 'tag:github.com,2008:Grit::Commit/' entry_id = id_prefix + commit_info['sha'] fe.id(entry_id) fe.author(commit_info['author']) fe.published(c...
ekopylova/burrito-fillings
bfillings/usearch.py
Python
bsd-3-clause
101,582
0.000975
#!/usr/bin/env python #----------------------------------------------------------------------------- # Copyright (c) 2013--, biocore development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. #-------------------------...
# turn the parameter off so subsequent runs are not # affected by parameter settings from previous runs self.Parameters[v].off() if v in data: # turn the parameter on if specified by the user
self.Parameters[v].on(data[v]) return '' def _get_result_paths(self, data): """ Set the result paths """ result = {} result['Output'] = ResultPath( Path=self.Parameters['--output'].Value, IsWritten=self.Parameters['--output'].isOn()) resul...
chemelnucfin/tensorflow
tensorflow/python/summary/writer/writer.py
Python
apache-2.0
17,167
0.004078
# 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...
bal_step: Number. Optional global step value to record with the summary. """ event = event_pb2.Event(session_log=session_log) self._add_event(event, global_step) def _add_graph_def(self, graph_def, global_step=None): graph_bytes = graph_def.SerializeToString() event = eve
nt_pb2.Event(graph_def=graph_bytes) self._add_event(event, global_step) def add_graph(self, graph, global_step=None, graph_def=None): """Adds a `Graph` to the event file. The graph described by the protocol buffer will be displayed by TensorBoard. Most users pass a graph in the constructor instead. ...
antechrestos/cf-python-client
integration/v2/test_service_instances.py
Python
apache-2.0
1,263
0.003959
import logging import unittest from config_test import build_client_from_configuration _logger = logging.getLogger(__name__) class TestServiceInstances(unittest.TestCase): def test_create_update_delete(self): client = build_client_from_configuration() result = client.v2.service_instances.create(...
client.v2.service_instances.update(result["metadata"]["guid"], client.update_parameters) else: _logger.warning("update test skipped") client.v2.service_instances.remove(result["metadata"]["guid"]) def test_get(self): client = build_client_from_configuration() cpt = 0 ...
instance in client.v2.service_instances.list(): if cpt == 0: self.assertIsNotNone(client.v2.service_instances.get_first(space_guid=instance["entity"]["space_guid"])) self.assertIsNotNone(client.v2.service_instances.get(instance["metadata"]["guid"])) self.asser...
ovaskevich/PyLaTeX
pylatex/base_classes/latex_object.py
Python
mit
5,960
0
# -*- coding: utf-8 -*- """ This module implements the base LaTeX object. .. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ from ordered_set import OrderedSet from ..utils import dumps_list from abc import abstractmethod, ABCMeta from reprlib import recursive_repr from in...
"""Determine wheter or not to escape content of this class. This defaults to `True` for most classes. """ if self._escape is not None: return self._escape if s
elf._default_escape is not None: return self._default_escape return True #: Start a new paragraph before this environment. begin_paragraph = False #: Start a new paragraph after this environment. end_paragraph = False #: Same as enabling `begin_paragraph` and `end_paragraph`, ...
terbolous/cloudstack-python-client
setup.py
Python
mit
1,975
0.015696
#!/usr/bin/python # Copyright (c) 2011 Jason Hancock <jsnbyh@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
OR OTHER DEALINGS # IN THE SOFTWARE. import os try: from setuptools import setup except ImportError: from distutils.core import setup def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name ...
cription = "CloudStack API Client", long_description = (read('README.md') + '\r\n' + read('HISTORY.rst') + '\r\n' + read('AUTHORS') ), author = "Erik Weber", author_email = "terbolous@gmail.com", url =...
eduNEXT/edunext-platform
common/lib/capa/capa/tests/test_responsetypes.py
Python
agpl-3.0
119,649
0.001847
# -*- coding: utf-8 -*- """ Tests of responsetypes """ import io import json import os import textwrap import unittest import zipfile from datetime import datetime import pytest import calc import mock import pyparsing import random2 as random import requests import six from pytz import UTC from six import text_type...
correctness('1_2_1') == expected_correctness, msg def assert_answer_form
at(self, problem): answers = problem.get_question_answers() assert answers['1_2_1'] is not None # pylint: disable=missing-function-docstring def assert_multiple_grade(self, problem, correct_answers, incorrect_answers): for input_str in correct_answers: result = problem.grade...
hzlf/openbroadcast
website/shop/shop_simplevariations/urls.py
Python
gpl-3.0
697
0.005739
#-*- coding: utf-8 -*- from django.conf.urls.defaults import patterns, url from shop_simplev
ariations.views import SimplevariationCartDetails urlpatterns = patterns('', url(r'^delete/$', SimplevariationCartDetails.as_view(action='delete'), name='cart_delete'), url('^item/$', SimplevariationCartDetails.as_view(action='post'), name='cart_item_add' ), url(r'^$', ...
id>[0-9A-Za-z-_.//]+)$', SimplevariationCartDetails.as_view(), name='cart_item' ), )
kmadathil/sanskrit_parser
sanskrit_parser/rest_api/api_v1.py
Python
mit
4,459
0.002018
from flask import Blueprint import flask_restx from flask_restx import Resource from flask import request # import subprocess # from os import path # from flask import redirect from sanskrit_parser.base.sanskrit_base import SanskritObject, SLP1 from sanskrit_parser.parser.sandhi_analyzer import LexicalSandhiAnalyzer f...
sentence """ strict
_p = True if request.args.get("strict") == "false": strict_p = False vobj = SanskritObject(v, strict_io=strict_p, replace_ending_visarga=None) parser = Parser(input_encoding="SLP1", output_encoding="Devanagari", replace_ending_visarga='...
google-research/kubric
test/test_cameras.py
Python
apache-2.0
1,140
0.007024
# Copyright 2022 The Kubric 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 applicable law or agreed to in w...
cam = cameras.OrthographicCamera(orthographic_scale=7) assert cam.orthographic_scale == 7 def test_perspective_camera_constructor(): cam = cameras.PerspectiveCamera(focal_leng
th=22, sensor_width=33) assert cam.focal_length == 22 assert cam.sensor_width == 33 def test_perspective_camera_field_of_view(): cam = cameras.PerspectiveCamera(focal_length=28, sensor_width=36) assert cam.field_of_view == pytest.approx(1.1427, abs=1e-4) # ca 65.5°
cloudbase/cloudbase-init-ci
argus/recipes/base.py
Python
apache-2.0
2,745
0
# Copyright 2015 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.apache.org/licenses/LICENSE-2.0 # # Unless r...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Contains base recipes functionality. A recipe is a class which knows how to provision an instance, by installing and configuring it with w...
""" import abc from argus import config as argus_config from argus import log as argus_log LOG = argus_log.LOG CONFIG = argus_config.CONFIG RETRY_COUNT = 15 RETRY_DELAY = 10 __all__ = ( 'BaseRecipe', ) class BaseRecipe(object): """Base class for a recipe. A recipe is a way in which an instance can...
jdemon519/cfme_tests
cfme/storage/object_store.py
Python
gpl-2.0
1,961
0.00153
# -*- coding: utf-8 -*- from functools import partial from navmazing import NavigateToSibling, NavigateToAttribute from cfme.common import SummaryMixin, Taggable from cfme.fixtures import pytest_selenium as sel from cfme.web_ui import toolbar as tb from cfme.web_ui import Quadicon, match_location, mixins from utils.ap...
ble, SummaryMixin, Navigatable): """ Automate Model page of Cloud Object Stores Args: name: Name of Object Store """ def __init__(self, name=None, appliance=None): Navigatable.__init__(self, appliance=appliance) self.name = name self.quad_name = 'object_store' def ...
navigate_to(self, 'Details') mixins.add_tag(tag, **kwargs) def untag(self, tag): """Removes the selected tag off the system""" navigate_to(self, 'Details') mixins.remove_tag(tag) @navigator.register(ObjectStore, 'All') class All(CFMENavigateStep): prerequisite = Navigate...
datamade/large-lots
tests/lots_client/test_ppf.py
Python
mit
2,817
0.00142
import datetime import uuid import pytest from lots_admin.models import Application from lots_client.views import advance_if_ppf_and_eds_submitted @pytest.mark.django_db @pytest.mark.parametrize('eds_received,ppf_received', [ (False, False), (True, False), (False, True), (True, True) ]) def test_adv...
ddress_street='456 Feather Lane') rv = client.post( '/principal-profile-form/{}/'.format(app.tracking_id), data
=data, ) assert rv.status_code == 200 assert 'Success!' in str(rv.content) app.refresh_from_db() assert app.ppf_received == True principal_profiles = app.principalprofile_set.all() assert len(principal_profiles) == 2 primary_ppf = principal_profiles.first() if ppf_type == 'organ...
lilleswing/deepchem
deepchem/dock/pose_generation.py
Python
mit
13,071
0.005967
""" Generates protein-ligand docked poses. """ import platform import logging import os import tempfile import tarfile import numpy as np from subprocess import call from subprocess import check_output from typing import List, Optional, Tuple, Union from deepchem.dock.binding_pocket import BindingPocketFinder from dee...
lt None) If specified, `self.pocket_finder` must be set. Will only generate poses for t
he first `num_pockets` returned by `self.pocket_finder`. out_dir: str, optional If specified, write generated poses to this directory. generate_score: bool, optional (default False) If `True`, the pose generator will return scores for complexes. This is used typically when invoking exter...
jcfr/mystic
examples_UQ/TEST_surrogate_cut.py
Python
bsd-3-clause
9,913
0.023303
#!/usr/bin/env python # # Author: Mike McKerns (mmckerns @caltech and @uqfoundation) # Copyright (c) 2009-2015 California Institute of Technology. # License: 3-clause BSD. The full license text is available at: # - http://trac.mystic.cacr.caltech.edu/project/mystic/browser/mystic/LICENSE DEBUG = False ##############...
UG: failure,success = sample(model,lb[0],ub[0]) pof = float(failure) / float(failure + success) print "Exact PoF: %s" % pof for i in range(len(lb)): print
"\n" print " lower bounds: %s" % lb[i] print " upper bounds: %s" % ub[i] for solved in params0[0]: print "solved: %s" % solved print "subdiameters (squared): %s" % subdiams0[0] print "diameter (squared): %s" % diam0[0] print " probability mass: %s" % probmass0[0] expectation = expe...
2ndy/RaspIM
usr/lib/python2.6/distutils/util.py
Python
gpl-2.0
21,928
0.001779
"""distutils.util Miscellaneous utility functions -- anything that doesn't fit into one of the other *util.py modules. """ __revision__ = "$Id$" import sys, os, string, re from distutils.errors import DistutilsPlatformError from distutils.dep_util import newer from distutils.spawn import spawn from distutils import ...
archs = tuple(sorted(set(archs))) if len(archs) == 1: machine = archs[0] elif archs == ('i386', 'ppc'):
machine = 'fat' elif archs == ('i386', 'x86_64'): machine = 'intel' elif archs == ('i386', 'ppc', 'x86_64'): machine = 'fat3' elif archs == ('ppc64', 'x86_64'): machine = 'fat64' ...
ares/robottelo
tests/foreman/cli/test_domain.py
Python
gpl-3.0
11,616
0
# -*- encoding: utf-8 -*- """Test class for Domain CLI :Requirement: Domain :CaseAutomation: Automated :CaseLevel: Acceptance :CaseComponent: CLI :TestType: Functional :CaseImportance: High :Upstream: No """ from fauxfactory import gen_string from robottelo.cli.base import CLIReturnCodeError from robottelo.cli....
in import Domain from robottelo.cli.factory import CLIFactoryError from robottelo.cli.factory import make_domain, make_location, make_org from robottelo.datafactory import ( filtered_datapoint, invalid_id_list, valid_data_list ) from robottelo.decorat
ors import ( run_only_on, tier1, tier2, bz_bug_is_open, ) from robottelo.test import CLITestCase @filtered_datapoint def valid_create_params(): """Returns a list of valid domain create parameters""" return [ {u'name': u'white spaces {0}'.format(gen_string(str_type='utf8')), u'...
codegooglecom/sphivedb
client/python/testcli.py
Python
gpl-2.0
1,157
0.076923
import sphivedbcli import time import sys def printResultSet( rs ): print "row.count %d" % ( rs.getRowCount() ) columnCount = rs.getColumnCount() hdrs = "" for i in range( columnCount ): hdrs = hdrs + ( "\t%s(%s)" % ( rs.getName( i ), rs.getType( i ) ) ) print hdrs for i in range( rs.getRowCount() ): r...
sys.exit( -1 ) configFile = sys.argv[1] cli = sphivedbcli.SPHiveDBClient() cli.init( configFile ) try: resp = cli.execute( 0, "foobar", "addrbook", \ [ "insert into addrbook ( addr ) values ( \"
%d\" )" % ( time.time() ), \ "select * from addrbook" ] ) if 0 == resp.getErrorCode(): rsCount = resp.getResultCount() for i in range( rsCount ): rs = resp.getResultSet( i ) printResultSet( rs ) else: print "%d: %s" % ( resp.getErrdataCode(), resp.getErrdataMsg() ) except Exception, e: pri...
js0701/chromium-crosswalk
tools/telemetry/telemetry/internal/actions/load_media.py
Python
bsd-3-clause
1,508
0.005305
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.core import exceptions from telemetry.internal.actions import media_action from telemetry.internal.actions import page_action class LoadMedi...
def WillRunAction(self, tab): """Load the JS code prior to running the action.""" super(LoadMediaAction, self).WillRunAction(tab) self.LoadJS(tab, 'load_media.js') def RunAction(self, ta
b): try: tab.ExecuteJavaScript('window.__loadMediaAndAwait("%s", "%s");' % (self._selector, self._event_to_await)) if self._timeout_in_seconds > 0: self.WaitForEvent(tab, self._selector, self._event_to_await, self._timeout_in_seconds) exc...
myangeline/pygame
flightgame/game.py
Python
apache-2.0
5,800
0.00141
# _*_ coding:utf-8 _*_ import random from parser_xml import doxml __author__ = 'Administrator' import pygame def item_to_int(array=[]): arr = [] for a in array: arr.append(int(a)) return arr pygame.init() keys = [False, False, False, False] screen = pygame.display.set_mode((450, 650), 0, 32) ...
plane = pygame.image.load('resources/plane.png').convert_alpha() pos = doxml('resources/
plane.xml') # hero_1 hero_1_p = pos['hero_1'] hero_1_p = item_to_int(hero_1_p) hero_1 = plane.subsurface(pygame.Rect((hero_1_p[2], hero_1_p[3]), (hero_1_p[0], hero_1_p[1]))) hero_1_pos = [200, 580] # bullet_1 蓝色 bullet_1_p = item_to_int(pos['bullet_1']) bullet_1 = plane.subsurface(pygame.Rect((bullet_1_p[2], bullet_1...
tlake/http-server
test_functests_gevent_server.py
Python
mit
5,433
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals import gevent_server import socket import pytest import time from multiprocessing import Process addr = ("127.0.0.1", 8000) _CRLF = b'\r\n' # yield fixtures are demons # We used to have a yield fixture here and in the server.py tests # which would sta...
ince we # only ever started one server throughout the entire testing process. # Once we created the gevent server, there were within the test suite # two different server creation fixtures, both scoped to module. We # falsely believed that each of these fixtures would terminate at the # end of the module. In practice, ...
re testing session, regardless # of defined scope. # The solution, seen below, is to use just a regular fixture with # a process-terminating finalizer. The scope behaves properly, # and autouse also still works. @pytest.fixture(scope='module', autouse=True) def gevent_server_setup(request): process = Process(tar...
nschloe/maelstrom
test/test_poisson_order.py
Python
mit
4,993
0.000401
# -*- coding: utf-8 -*- # from __future__ import print_function import warnings import numpy import pytest import sympy from dolfin import ( MPI, Constant, Diri
chletBC, Expression, FunctionSpace, UnitSquareMesh, errornorm, pi, triangle, ) import helpers import matplotlib.pyplot as plt from maelstrom import heat
MAX_DEGREE = 5 def problem_sinsin(): """cosine example. """ def mesh_generator(n): return UnitSquareMesh(n, n, "left/right") x = sympy.DeferredVector("x") # Choose the solution such that the boundary conditions are fulfilled # exactly. Also, multiply with x**2 to make sure that the ...
alexbredo/site-packages3
handler/elasticsearch.py
Python
bsd-2-clause
6,002
0.033156
# Copyright (c) 2014 Alexander Bredo # 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 conditions ...
#elif isinstance(dictionary[key], int) and isinstance(dictionary[key], float): # dictionary[key] = dictionary[key] return dictionary except Exception as e: log.error(e) de
f deleteIndex(self): r = self.http.request('DELETE', 'http://%s:%i/%s/' % (self.host, self.port, self.index)) if int(r.status/100) == 2: log.info("Elasticsearch-Index '%s' was removed." % self.index) return True else: log.warning("Elasticsearch-Index '%s' does not exist." % self.index) return False # ...
arvinddoraiswamy/blahblah
stockfighter/test.py
Python
mit
539
0.011132
import requests import os import sys proxies = { "http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080", } #Adding directory to the path where Python searches for modules cmd_folder = os.path.dirname
('/home/arvind/Documents/Me/My_Projects/challenges/stockfighter/modules/') sys.path.insert(0, cmd_folder) #Importing API module import api if __name__ == "__main__": requests.packages.urllib3.disable_warnings() r1= api.orderbook().json()[u'asks'] print r1
r1= api.orderbook().json()[u'bids'] print r1
sot/mica
mica/web/admin.py
Python
bsd-3-clause
127
0
# Licensed under a 3-
clause BSD style license - see LICENSE.rst from django.cont
rib import admin # Register your models here.
nathan-hoad/aesop
aesop/utils.py
Python
bsd-3-clause
4,678
0.001069
import asyncio import os from urllib.parse import urlparse import aiohttp def damerau_levenshtein(first_string, second_string): """Returns the Damerau-Levenshtein edit distance between two strings.""" previous = None prev_a = None current = [i for i, x in enumerate(second_string, 1)] + [0] for ...
useful when trying to download metadata for new series. """ # FIXME: make this connection map configurable. connection_map =
{ 'www.omdbapi.com': 20, } current_requests = {} limits = {} CONN_POOL = aiohttp.TCPConnector() count = 0 @classmethod def get_pool(cls, key): if key not in cls.limits: limit = cls.connection_map.get(key, 50) cls.limits[key] = asyncio.BoundedSemapho...
muttiopenbts/nazar
create_netblocks.py
Python
gpl-2.0
2,145
0.000466
# -*- coding: utf-8 -*- """ Created on Sun Nov 1 12:36:04 2015 @author: Mutti argument 1 country argument 2 city argument 3 location of maxmind csv files """ from netaddr import * import sys import os import re BASE_PATH = '/opt/masscan/targets/' def grep(search_string, filename, options=''): ''' Call OS...
print len(cidr_blocks) # Attempt to merge overlaping netblocks cidr_merge(merged_cidr_blocks) print len(merged_cidr_blocks) merged_cidr_blocks = [cidr.__str__() for cidr in merged_cidr_blocks] new_filename = country+"-"+city+".txt" write_city_netblock_to_file( '\n'.join(merged_cidr_bl...
'__main__': main()
olexiim/edx-platform
cms/djangoapps/contentstore/views/videos.py
Python
agpl-3.0
12,554
0.001434
""" Views related to the video upload feature """ from boto import s3 import csv from uuid import uuid4 from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import HttpResponse, HttpResponseNotFound from django.utils.translation import ugettext as _ from django.vi...
en user has access to it, and it is properly configured for video uploads """ course_key = CourseKey.from_string(course_key_string) # For now, assume all studio users that have access to the course can upload videos. # In the future, we plan to add a new org-level role for video uploaders. cour...
d course and course.video_pipeline_configured ): return course else: return None def _get_videos(course): """ Retrieves the list of videos from VAL corresponding to the videos listed in the asset metadata store. """ edx_videos_ids = [ v.asset...
MIRAvzw/qt-brisa
doc/docSource/conf.py
Python
lgpl-3.0
6,284
0.006684
# -*- coding: utf-8 -*- # # BRisa UPnP documentation build configuration file, created by # sphinx-quickstart on Mon May 4 11:21:11 2009. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pick...
will be prepended to all description # unit titles (such as .. function::). add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False show_authors = True # The name of the Pygments (syntax highlighting) style to use. ...
----------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> ...
pbanaszkiewicz/amy
amy/reports/tests/test_instructor_issues.py
Python
mit
1,579
0
from django.urls import reve
rse from workshops.models import Event, Role, Tag, Task from workshops.tests.base import TestBase
class TestInstructorIssues(TestBase): """Tests for the `instructor_issues` view.""" def setUp(self): super().setUp() self._setUpUsersAndLogin() TTT, _ = Tag.objects.get_or_create(name="TTT") stalled = Tag.objects.get(name="stalled") learner, _ = Role.objects.get_or_cre...
x0rnn/minqlx-plugins
midair_only.py
Python
gpl-3.0
9,927
0.004835
# midair_only.py, this plugin changes the gameplay into a rockets-only mode where only midair shots kill. # If you just want a midair ranking system, use midair.py instead. # This plugin also keeps score of top X midair rocket kills per map in terms of distance. # On evey midair kill that counts (minheight and mindista...
KILLER']['STEAM_ID'] v_id = data['VICTIM']['STEAM_ID'] distance = math.sqrt((v_X - k_X) ** 2 + (v_Y - k_Y) ** 2 + (v_Z - k_Z) ** 2)
height = abs(data['KILLER']['POSITION']['Z'] - data['VICTIM']['POSITION']['Z']) killer_name = data['KILLER']['NAME'] victim_name = data['VICTIM']['NAME'] players = self.players() map_name = self.game.map.lower() minheight = 100 #min ...
suutari/shoop
shuup_workbench/__main__.py
Python
agpl-3.0
998
0.001002
#!/usr/bin/env python # This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is
licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import logging import os import sys import warnings from shuup.utils.deprecation import RemovedInFutureShuupWarning if __name__ == "__main__": if not sys.warnoptions: # Route warnings through python lo...
ureWarnings(True) # RemovedInFutureShuupWarning is a subclass of PendingDeprecationWarning which # is hidden by default, hence we force the "default" behavior warnings.simplefilter("default", RemovedInFutureShuupWarning) sys.path.insert(0, os.path.realpath(os.path.dirname(__file__) + "/.."))...
jamesblunt/glances
glances/plugins/glances_diskio.py
Python
lgpl-3.0
5,679
0.000704
# -*- coding: utf-8 -*- # # This file is part of Glances. # # Copyright (C) 2014 Nicolargo <nicolas@nicolargo.com> # # Glances 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 Lic...
(self.curse_add_line(msg)) # Disk list (sorted by name) for i in sorted(self.stats, key=lambda diskio: diskio['disk_name']): # Do not display hidden interfaces if self.is_hide(i['disk_name']):
continue # New line ret.append(self.curse_new_line()) if len(i['disk_name']) > 9: # Cut disk name if it is too long disk_name = '_' + i['disk_name'][-8:] else: disk_name = i['disk_name'] msg = '{0:9}'.format(dis...
mas90/pygopherd
pygopherd/protocols/http.py
Python
gpl-2.0
12,731
0.003692
# pygopherd -- Gopher-based protocol server in Python # module: serve up gopherspace via http # $Id: http.py,v 1.21 2002/04/26 15:18:10 jgoerzen Exp $ # Copyright (C) 2002 John Goerzen # <jgoerzen@complete.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GN...
)] = splitline[1] self.requesthandler.pygopherd_http_slurped = self.httpheaders def handle(self): self.canhandlerequest() # To get self.requestparts self.iconmapping = eval(self.config.get("protocols.http.HTTPProtocol", "iconmapping"))...
slurp() splitted = self.requestparts[1].split('?') self.selector = splitted[0] self.selector = urllib.unquote(self.selector) self.selector = self.slashnormalize(self.selector) self.formvals = {} if len(splitted) >= 2: self.formvals = cgi.parse_qs(splitted[1])...
julien6387/supvisors
supvisors/test/scripts/check_starting_strategy.py
Python
apache-2.0
14,658
0.001364
#!/usr/bin/python # -*- coding: utf-8 -*- # ====================================================================== # Copyright 2017 Julien LE CLEACH # # 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 Lice...
self.assertEqual(f'ABNORMAL_TERMINATION: my_movies:converter_{idx:02d}', exc.exception.faultString) # wait for event FATAL event = self._get_next_process_event() assert {'group': 'my_movies', 'name': f'converter_{idx:02d}', 'state': 200}.items() < event.items() # refresh the node l...
available defined in the program section of the rules file. """ print('### Testing CONFIG starting strategy') # initial state is cliche81=10% cliche82=15% cliche83=9% cliche85=0% assert list(self.loading.values()) == [10, 15, 9, 0] self.strategy = StartingStrategies.CONFIG ...
evenmarbles/mlpy
mlpy/auxiliary/datastructs.py
Python
mit
10,818
0.000277
""" .. module:: mlpy.auxiliary.datastructs :platform: Unix, Windows :synopsis: Provides data structure implementations. .. moduleauthor:: Astrid Jackson <ajackson@eecs.ucf.edu> """ from __future__ import division, print_function, absolute_import import heapq import numpy as np from abc import ABCMeta, abstra
ctmethod class Array(object): """The managed array class. The managed array class pre-allocates memory to
the given size automatically resizing as needed. Parameters ---------- size : int The size of the array. Examples -------- >>> a = Array(5) >>> a[0] = 3 >>> a[1] = 6 Retrieving an elements: >>> a[0] 3 >>> a[2] 0 Finding the length of the array: ...
Pixdigit/Saufbot
logger.py
Python
mit
1,904
0.003155
# -*- coding: utf-8 -*- from __future__ import unicode_literals import time import string import json import config import helper import busses def log_message(msg): #log format: time type message time_str = str(time.time()) line = time_str[:time_str.find(".")] line = line.rjust(10, str(" ")) li...
msg_type == "command": appendix = msg.text[1:] elif msg_type == "location": location_data = msg.location.to_dict() ap
pendix = str(location_data["latitude"]) + "°, " + str(location_data["longitude"]) + "°" elif msg_type == "contact": appendix = str(msg.contact.user_id) + " " + msg.contact.first_name + " " + msg.contact.last_name elif msg_type == "new_user": appendix = str(msg.new_chat_member.id) + " " + str(msg...
AISpace2/AISpace2
aipython/cspSLSPlot.py
Python
gpl-3.0
12,720
0.001101
# cspSLS.py - Stochastic Local Search for Solving CSPs # AIFCA Python3 code Version 0.7.1 Documentation at http://aipython.org # Artificial Intelligence: Foundations of Computational Agents # http://artint.info # Copyright David L Poole and Alan K Mackworth 2017. # This work is licensed under a Creative Commons # Attr...
var_differential[v] = var_differential.get(v, 0) + 1 else: self.display(3, "Still inconsistent", varcon) self.variable_pq.update_each_priority(var_differential) self.display(2, "Conflicts:", self.conflicts) ...
, "in", self.number_of_steps, "steps") return self.number_of_steps self.display(1, "No solution in", self.number_of_steps, "steps", len(self.conflicts), "conflicts remain") return None def create_pq(self): """Create the variable to number-of-conflicts priority queue. ...
caktus/rapidsms-reports
reports/tests/base.py
Python
bsd-3-clause
1,259
0
from __future__ import unicode_literals import datetime import random from django.conf import settings from rapidsms.tests.harness import RapidTest from healthcare.api import client class ReportTestBase(RapidTest): def setUp(self): # Before doing anything else, we must clear out the dummy backend ...
nd._patients = {} registry.backend._patient_ids = {} registry.backend._providers = {} def create_patient(self, **kwargs): defaults = { 'name': self.random_string(25), 'birth_date': datetime.date.today() - datetime.timedelta(365), 'sex': ra...
def create_provider(self, **kwargs): defaults = { 'name': self.random_string(25), } defaults.update(kwargs) return client.providers.create(**defaults)
mrakitin/sirepo
tests/template/model_units_test.py
Python
apache-2.0
1,624
0.001847
# -*- coding: utf-8 -*- u"""Test sirepo.cooki
e :copyright: Copy
right (c) 2019 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function import pytest def test_model_units(): from sirepo.template.template_common import ModelUnits import re def _xpas(value, is_nat...
Tong-Chen/scikit-learn
sklearn/linear_model/tests/test_sgd.py
Python
bsd-3-clause
30,538
0.000295
import pickle import unittest import numpy as np import scipy.sparse as sp from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_almost_equal from sklearn.utils.testing import assert_greater from sklearn.utils.testing ...
om sklearn.linear_model import SGDClassifier, SGDRegressor from sklearn.preprocessing import LabelEncoder, scale class SparseSGDClassifier(SGDClassifier): def fit(self, X, y, *args, **kw): X = sp.csr_matrix(X) return SGDClassifier.fit(self, X, y, *args, **kw) def partial_fit(self, X, y, *arg...
tion(self, X, *args, **kw): X = sp.csr_matrix(X) return SGDClassifier.decision_function(self, X, *args, **kw) def predict_proba(self, X, *args, **kw): X = sp.csr_matrix(X) return SGDClassifier.predict_proba(self, X, *args, **kw) def predict_log_proba(self, X, *args, **kw): ...
pmquang/python-anyconfig
anyconfig/schema.py
Python
mit
4,139
0
# # Copyright (C) 2015 Satoru SATOH <ssato redhat.com> # License: MIT # """anyconfig.schema module. .. versionadded:: 0.0.11 Added new API :function:`gen_schema` to generate schema object .. versionadded:: 0.0.10 Added new API :function:`validate` to validate config with JSON schema """ from __future__ import a...
= jsonschema.FormatChecker() # :raises: NameError try: jsonschema.validate(obj, schema, format_checker=format_checker) return (True, '') except (jsonschema.ValidationError, jsonschema.SchemaError, Exception) as exc: if safe: return (Fa...
is not available") return (True, '') def array_to_schema_node(arr, typemap=None): """ Generate a node represents JSON schema object with type annotation added for given object node. :param arr: Array of dict or MergeableDict objects :param typemap: Type to JSON schema type mappings :re...
DigitalCampus/django-nurhi-oppia
docs/conf.py
Python
gpl-3.0
8,476
0.007433
# -*- coding: utf-8 -*- # # OppiaMobile-Server documentation build configuration file, created by # sphinx-quickstart on Tue Jun 25 16:03:07 2013. # # 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 fi...
mentation". #html_title = None # A shorter title for the navigation bar. Default is the s
ame as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixe...
amiv-eth/amivapi
amivapi/tests/test_cascade_delete.py
Python
agpl-3.0
1,659
0
# -*- coding: utf-8 -*- # # license: AGPLv3, see LICENSE for details. In addition we strongly encourage # you to buy us beer if we meet and you like the software. """Test for cascading deletes""" from bson import ObjectI
d from amivapi.tests.utils import WebTestNoAuth class CascadingDeleteTest(WebTestNoAuth): def test_delete_cascades(self): """Test that deletion of an object deletes referencing objects, when
cascading is enabled""" self.load_fixture({ 'users': [ { '_id': 'deadbeefdeadbeefdeadbeef', 'nethz': 'user1' }, { '_id': 'deadbeefdeadbeefdeadbee3', 'nethz': 'use...
ehuelsmann/openipam
openIPAM/openipam/web/admin/system/system.py
Python
gpl-3.0
1,167
0.042845
import che
rrypy from openipam.web.basepage import BasePage from openipam.web.admin.admin import Admin from openipam.web.resource.submenu import submenu class AdminSystem(Admin): '''The admin system settings class. This includes a
ll pages that are /admin/sys/*''' #----------------------------------------------------------------- # PUBLISHED FUNCTIONS #----------------------------------------------------------------- #----------------------------------------------------------------- #----------------------------------------------...
genialis/resolwe-bio
resolwe_bio/processes/support_processors/bam_conversion.py
Python
apache-2.0
4,807
0.00104
"""Converting BAM to BEDPE and normalized BigWig files.""" import os from resolwe.process import ( Cmd, DataField, FileField, FloatField, Process, SchedulingClass, StringField, ) class BamToBedpe(Process): """Takes in a BAM file and calculates a normalization factor in BEDPE format. ...
sename(path) assert basename.endswith(".bam") name = basename[:-4] out_file = f"{name}.SInorm.bigwig" out_index = f"{name}.bai" with open(inputs.bedpe.output.bedpe.path) as f: spike_count = f.readlines() spike_count = len(spike_count) scale_factor...
path, "--scaleFactor", scale_factor, "--outFileName", out_file, "--numberOfProcessors", self.requirements.resources.cores, "--outFileFormat", "bigwig", ] (Cmd["samtools"]["index"][path][out_index])() ...
diydrones/ardupilot
Tools/scripts/uploader.py
Python
gpl-3.0
45,137
0.002725
#!/usr/bin/env python ############################################################################ # # Copyright (c) 2012-2017 PX4 Development Team. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are me...
y-id/usb-3D*', '/dev/serial/by-id/usb-APM*', '/dev/serial/by-id/usb-Radio*', '/dev/serial/by-id/usb-*_3DR_*', '/dev/serial/by-id/usb-Hex_Technology_Limited*',
'/dev/serial/by-id/usb-Hex_ProfiCNC*', '/dev/serial/by-id/usb-Holybro*', '/dev/serial/by-id/usb-mRo*', '/dev/serial/by-id/usb-modalFC*', '/dev/serial/by-id/usb-*-BL_*', '/dev/serial/by-id/usb-*_BL_*', '/dev/tty.usb...
camsas/qjump-nsdi15-plotting
figure11/plot_throughput_factor_experiment.py
Python
bsd-3-clause
8,217
0.008762
#!/usr/bin/python # -*- coding: utf-8 -*- # Simple script which takes a file with one packet latency (expressed as a # signed integer) per line and plots a trivial histogram. # Copyright (c) 2015, Malte Schwarzkopf # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modifica...
ntile(x, 50),
scoreatpercentile(x, box_top), scoreatpercentile(x, box_bottom), get_whisk(x, whisker_top), get_whisk(x, whisker_bottom), scoreatpercentile(x, 100)) bp.draw_on(ax, index) def worst_case_approx(setup...
jasonwee/asus-rt-n14uhp-mrtg
src/lesson_the_internet/uuid_uuid1.py
Python
apache-2.0
641
0
import uuid u = uuid.uuid1() p
rint(u) print(type(u)) print('bytes :', repr(u.bytes)) print('hex :', u.h
ex) print('int :', u.int) print('urn :', u.urn) print('variant :', u.variant) print('version :', u.version) print('fields :', u.fields) print(' time_low : ', u.time_low) print(' time_mid : ', u.time_mid) print(' time_hi_version : ', u.time_hi_version) print(' clock_seq_hi_variant:...
opennetworkinglab/spring-open-cli
sdncon/rest/models.py
Python
epl-1.0
944
0.001059
# # Copyright (c) 2013 Big Switch Networks, Inc. # # Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html # # Unless required by applicable l...
software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, eithe
r express or # implied. See the License for the specific language governing # permissions and limitations under the License. # from django.db import models from django.contrib.auth.models import User # Create your models here. class UserData(models.Model): user = models.ForeignKey(User, null=True) name = mode...