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
trondhindenes/ansible
contrib/inventory/foreman.py
Python
gpl-3.0
17,060
0.000997
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # # Copyright (C) 2016 Guido Günther <[email protected]>, # Daniel Lobato Garcia <[email protected]> # # This script is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # t...
, ConfigParser.NoSectionError): self.rich_params = False try: self.host_filters = config.get('foreman', 'host_filters') except (ConfigParser.No
OptionError, ConfigParser.NoSectionError): self.host_filters = None # Cache related try: cache_path = os.path.expanduser(config.get('cache', 'path')) except (ConfigParser.NoOptionError, ConfigParser.NoSectionError): cache_path = '.' (script, ext) = os...
yuyuyu101/VirtualBox-NetBSD
src/libs/xpcom18a4/python/test/pyxpcom_test_tools.py
Python
gpl-2.0
4,286
0.008166
# test tools for the pyxpcom bindings from xpcom import _xpcom import unittest # export a "getmemusage()" function that returns a useful "bytes used" count # for the current process. Growth in this when doing the same thing over and # over implies a leak. try: import win32api import win32pdh import win32...
n leak tests. class TestLoader(unittest.TestLoader): def loadTestsFromTestCase(self, testCaseClass): """Ret
urn a suite of all tests cases contained in testCaseClass""" leak_tests = [] for name in self.getTestCaseNames(testCaseClass): real_test = testCaseClass(name) leak_test = self._getTestWrapper(real_test) leak_tests.append(leak_test) return self.suiteClass(leak_...
Stracksapp/stracks_api
stracks_api/middleware.py
Python
bsd-2-clause
2,170
0.005069
try: from django.conf import settings STRACKS_CONNECTOR = settings.STRACKS_CONNECTOR except (ImportError, AttributeError): STRACKS_CONNECTOR = None STRACKS_API = None from stracks_api.api import API from stracks_api import client import django.http STRACKS_API = None if STRACKS_CONNECTOR: STRACK...
st, store it in local thread storage useragent = request.META.get('HTTP_USER_AGENT', 'unknown') ip = request.META.get('REMOTE_ADDR', '<none>') path = request.get_full_path() sess =
request.session.get('stracks-session') if sess is None: sess = STRACKS_API.session() request.session['stracks-session'] = sess request = sess.request(ip, useragent, path) client.set_request(request) def process_response(self, request, response): if not STRA...
dmlc/tvm
tests/python/relay/op/annotation/test_annotation.py
Python
apache-2.0
2,947
0.001357
# 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...
ain_body assert not call.attrs.constrain_result def test_on_device_via_device(): x = relay.Var("x") call = relay.annotation.on_device(x, tvm.device("cpu")) assert call.attrs.virtual_device.device_type_int == 1 # ie kDLCPU def test_on_device_invalid_device(): x = relay.Var("x") pytest.raises...
ue) assert call.attrs.virtual_device.device_type_int == 2 # ie kDLCUDA assert call.attrs.constrain_body assert call.attrs.constrain_result def test_on_device_free(): x = relay.Var("x") call = relay.annotation.on_device(x, "cuda", constrain_result=False, constrain_body=False) assert call.attrs...
interop-dev/django-netjsongraph
tests/settings.py
Python
mit
3,592
0.001949
import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DEBUG = True ALLOWED_HOSTS = [] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'django_netjsongraph.db', } } SECRET_KEY = 'fn)t*+$)ugeyip6-#txyy$5wf2ervc0d2n#h)qb)y5@ly$t*@w' INSTALLED_APPS = [ ...
join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'djang...
, }, ] # See http://docs.djangoproject.com/en/dev/topics/logging for # more details on how to customize your logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse',}, 'require_de...
maartenbreddels/vaex
tests/getattr_test.py
Python
mit
3,825
0.005229
from common import * def test_column_subset(ds_local): ds = ds_local dss = ds[['x', 'y']] assert dss.get_column_names() == ['x', 'y'] np.array(dss) # test if all columns can be put in arrays def test_column_subset_virtual(ds_local): ds = ds_local ds['r'] = ds.x + ds.y dss = ds[['r']] ...
d a virtual column assert ds[['x']].values[:,0].tolist() ==
ds.x.values.tolist() def test_non_existing_column(df_local): df = df_local with pytest.raises(NameError, match='.*Did you.*'): df['x_'] def test_alias(df_local): df = df_local df2 = df[['123456']] assert '123456' in df2
atvcaptain/enigma2
lib/python/Components/Renderer/AnalogClockLCD.py
Python
gpl-2.0
3,341
0.034122
from __future__ import absolute_import # original code is from openmips gb Team: [OMaClockLcd] Renderer # # Thx to arn354 # import math from Components.Renderer.Renderer import Renderer from skin import parseColor from enigma import eCanvas, eSize, gRGB, eRect from Components.VariableText import VariableText from Comp...
y, self.linewidth, self.linewidth), self.fColor) error = (error + deltay) if (error > 0): y = (y + ystep)
error = (error - deltax) def changed(self, what): opt = (self.source.text).split(',') try: sopt = int(opt[0]) if len(opt) < 2: opt.append('') except Exception as e: return if (what[0] == self.CHANGED_CLEAR): pass elif self.instance: self.instance.show() if (self.forend != sopt): ...
DemocracyClub/yournextrepresentative
ynr/apps/uk_results/migrations/0023_auto_20160505_1636.py
Python
agpl-3.0
322
0
from django.db import migrations class Migration(migrations.Mig
ration): dependencies = [("uk_results", "0022_postresult_confirmed_resultset")] operations = [ migrations.AlterModelOptions( name="candidateresult", options={"ordering":
("-num_ballots_reported",)}, ) ]
somethingnew2-0/distadmin
distadmin/users/migrations/0002_set_site_domain_and_name.py
Python
mit
4,351
0.007125
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import DataMigration from django.conf import settings from django.db import models class Migration(DataMigration): def forwards(self, orm): """Set site domain and name.""" Site = orm['sites.Site'] site = Site.ob...
'Meta': {'ordering': "(u'domain',)", 'object_name': 'Site', 'db_table': "u'django_site'"}, 'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.Ch...
Field', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.M...
xinghai-sun/models
ssd/config/pascal_voc_conf.py
Python
apache-2.0
2,573
0
from easydict import EasyDict as edict import numpy as np __C = edict() cfg = __C __C.TRAIN = edict() __C.IMG_WIDTH = 300 __C.IMG_HEIGHT = 300 __C.IMG_CHANNEL = 3 __C.CLASS_NUM = 21 __C.BACKGROUND_ID = 0 # training settings __C.TRAIN.LEARNING_RATE = 0.001 / 4 __C.TRAIN.MOMENTUM = 0.9 __C.TRAIN.BATCH_SIZE = 32 __C.T...
om fc7 __C
.NET.FC7 = edict() __C.NET.FC7.PB = edict() __C.NET.FC7.PB.MIN_SIZE = [60] __C.NET.FC7.PB.MAX_SIZE = [114] __C.NET.FC7.PB.ASPECT_RATIO = [2., 3.] __C.NET.FC7.PB.VARIANCE = [0.1, 0.1, 0.2, 0.2] # configuration for priorbox_layer from conv6_2 __C.NET.CONV6 = edict() __C.NET.CONV6.PB = edict() __C.NET.CONV6.PB.MIN_SIZE =...
Nic30/hwtLib
hwtLib/examples/errors/errors_test.py
Python
mit
2,037
0
import unittest from hwt.synthesizer.exceptions import TypeConversionErr from hwt.synthesizer.rtlLevel.signalUtils.exceptions import \ SignalDriverErr from hwt.synthesizer.utils import to_rtl_str
from hwtLib.examples.errors.accessingSubunitInternalIntf import \ AccessingSubunitInternalIntf from hwtLib.examples.errors.inconsistentIntfDirection import \ InconsistentIntfDirection f
rom hwtLib.examples.errors.invalidTypeConnetion import InvalidTypeConnetion from hwtLib.examples.errors.multipleDriversOfChildNet import \ MultipleDriversOfChildNet, MultipleDriversOfChildNet2 from hwtLib.examples.errors.unusedSubunit import UnusedSubunit, UnusedSubunit2 class ErrorsTC(unittest.TestCase): def...
simark/simulavr
regress/test_opcodes/test_BLD.py
Python
gpl-2.0
2,630
0.018251
#! /usr/bin/env python ############################################################################### # # simulavr - A simulator for the Atmel AVR family of microcontrollers. # Copyright (C) 2001, 2002 Theodore A. Roth # # This program is free software; you can redistribute it and/or modify # it under the terms of th...
, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # ############################################################################### # # $Id: test_BLD.py,v 1.1 2004/07/31 00:59:11 rivetwa Exp $ # """Test the BLD opcode. """ import base_test from registers
import Reg, SREG class BLD_TestFail(base_test.TestFail): pass class base_BLD(base_test.opcode_test): """Generic test case for testing BLD opcode. Bit load from the T flag in SREG to bin in register. opcode is '1111 100d dddd 0bbb' where d is register and b is the register bit. Only registers PC and Rd should b...
malcolmpl/fleetpanel
FleetPanel.py
Python
mit
83,136
0.015276
#!/usr/bin/python # vim:sw=4:softtabstop=4:expandtab:set fileencoding=ISO8859-2 # # FleetPanel.py, part of the FleetPanel # # Copyright (c) 2008-2009 Pawe³ 'Reef' Polewicz # All rights reserved. # # This software is licensed as described in the file LICENSE, which # you should have received as part of this distribution...
if not cacheObject.has(corpname) or cacheObject.expired(corpname): newdata, expirationTime = getMemberData(charid, userid, apikey, corpname) cacheObject.set(corpname, newdata, expirationTime) return newdata else: return cacheObject.get(corpname) def getMemberData(charid, userid,...
'userid': userid, 'apikey': apikey, } ) headers = { "Content-type": "application/x-www-form-urlencoded" } conn = httplib.HTTPConnection("api.eve-online.com") conn.request("POST", "/corp/MemberTracking.csv.aspx", params, headers) response = conn.getresponse() rawdata = respons...
stallmanifold/cs229-machine-learning-stanford-fall-2016
src/homework2/q3/svm_train.py
Python
apache-2.0
3,651
0.006574
import numpy as np import pandas as pd def train(df_train, tau, max_iters): Xtrain = df_train.iloc[:, 1:].as_matrix() ytrain = df_train.iloc[:, 0].as_matrix() classifier = SVM(Xtrain, ytrain, tau, max_iters) return classifier class SVM: def __init__(self, X, y, tau, max_iters): """ ...
um_tr
ain_docs) average_alpha = np.zeros(num_train_docs) t = 0 for _ in range(max_iters * num_train_docs): t += 1 idx = np.random.randint(num_train_docs) # margin = ytrain[idx] * Ktrain.T[:, idx] * alpha margin = ytrain[idx] * Ktrain[idx, :].dot(alpha) ...
adityaduggal/erpnext
erpnext/config/desktop.py
Python
gpl-3.0
11,448
0.047182
# coding=utf-8 from __future__ import unicode_literals from frappe import _ def get_data(): return [ { "module_name": "Item", "_doctype": "Item", "color": "#f39c12", "icon": "octicon octicon-package", "type": "link", "link": "List/Item" }, { "module_name": "Customer", "_doctype": "Custo...
nk": "List/Project" }, { "module_name": "Is
sue", "color": "#2c3e50", "icon": "octicon octicon-issue-opened", "_doctype": "Issue", "type": "link", "link": "List/Issue" }, { "module_name": "Lead", "icon": "octicon octicon-broadcast", "type": "module", "_doctype": "Lead", "type": "link", "link": "List/Lead" }, { "module_...
thethythy/Mnemopwd
mnemopwd/server/util/__init__.py
Python
bsd-2-clause
1,500
0.002667
# -*- coding: utf-8 -*- # Copyright (c) 2015, Thierry Lemeunier <thierry at lemeunier dot net> # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # a
re permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following...
HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR AN...
chirpradio/chirpradio-machine
chirp/common/mp3_frame.py
Python
apache-2.0
8,719
0.000803
""" Convert a stream into a sequence of MPEG audio frames. """ from chirp.common import id3_header from chirp.common import mp3_header # The size of the chunks of data we read from file_obj. The largest # possible MP3 frame is 1045 bytes; this value should be larger than # that. Keeping the value low helps perfor...
15\x2f\xc0\x8f\xa5\x22\xd1\x79\x95" "\x75\x50\xcf\xbe\xda\xd8\xcd\x70\x00\xd0\x12\xc0\x21\x41\xc4\xa2" "\x40\xf1\x9c\x10\x9c\x12\xd8\x2a\x94\xcc\xa4\x09\x6c\xe9\x7a\x98" "\xe6\x15\x06\x5e\x96\xcf\x2b\xd6\xb6\xbb\x16\x68\xd4\
xa5\xa2\xdc" "\x4f\x31\x02\xf4\x91\x50\x49\x4f\x58\xc2\xf3\xa6\x49\x0a\xb0\x3f" "\x1e\x2f\xdd\x7a\xca\x3d\xc3\x03\x54\x1b\x6a\xa9\x0a\x97\x74\x49" "\x24\xb1\xa2\x2b\x8e\x09\x08\x15\x81\xb1\xc4\x02\x82\x44\xa1\x30" "\x10\xc4\x21\xe5\x92\xb9\xfa\x49\xa0\x9a\xec\xf5\xbc\x51\x62\xe3" "\xd3\x60\x55\xac\x...
pglotov/django-rest-framework-gis
setup.py
Python
mit
2,039
0.000981
import sys import os from setuptools import setup, find_packages from rest_framework_gis import get_version def get_install_requires(): """ parse requirements.txt, ignore links, exclude comments """ requirements = [] for line in open('requirements.txt').readlines(): # skip to next iteratio...
'rest-framework', 'gis', 'geojson'], packages=find_packages(exclude=['tests', 'tests.*']), install_requires=get_install_r
equires(), classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Topic :: Internet :: WWW/HTTP', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Framework :: Djang...
Linguistics-DTU/DTU_8th_Sem_Project
code/bunch-of-taggers.py
Python
gpl-3.0
10,340
0.017505
# -*- coding: utf-8 -*- """ Created on Sun Apr 24 08:43:26 2016 @author: user """ #import nltk # eo_words = nltk.corpus.udhr.word_tokenizer('Esperanto-UTF8') # eo_words = nltk.corpus.udhr.raw('Esperanto-UTF8') # eo_words #print(eo_words) ###################################### """ English English...
ltk.corpus.udhr.words('German_Deutsch-Latin1')) ###################################### """ French French_Francais-Latin1 """ import nltk nltk.pos_tag(nltk.corpus.udhr.words('French_Francais-Latin1')) ###################################### """ Russian Russian-UTF8 Russian_Russky-C...
################ """ Farsi Farsi_Persian-UTF8 Farsi_Persian-v2-UTF8 """ ## something is wrong as most words are just NNP !!!! import nltk nltk.pos_tag(nltk.corpus.udhr.words('Farsi_Persian-UTF8')) ###################################### """ Finnish Finnish_Suomi-Latin1 """ import nlt...
dkarchmer/django-aws-template
server/apps/main/tests.py
Python
mit
4,010
0.002743
#import unittest import json from django.contrib.auth import get_user_model from django.core import mail from django.test import Client, TestCase from rest_framework import status from rest_framework.reverse import reverse from rest_framework.test import APIClient, APIRequestFactory from .models import * user_model...
sp = self.client.post('/api/v1/message', {'name':'M1', 'email':'[email protected]', 'phone':'(650)555-1234', 'message':'This is a test'}, format='json') self.assertEqual(resp.status_code, status.HT...
same user'}, format='json') self.assertEqual(resp.status_code, status.HTTP_201_CREATED) resp = self.client.post('/api/v1/message', {'name':'M2', 'email':'[email protected]', 'message':'This is a test'}, forma...
tbabej/astropy
astropy/extern/configobj/configobj.py
Python
bsd-3-clause
88,262
0.001496
# configobj.py # A config file reader/writer that supports nested sections in config files. # Copyright (C) 2005-2014: # (name) : (email) # Michael Foord: fuzzyman AT voidspace DOT org DOT uk # Nicola Larosa: nico AT tekNico DOT net # Rob Dennis: rdennis AT gmail DOT com # Eli Courtwright: eli AT courtwright DOT org #...
OM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE from ...extern import six from ...extern.six.moves import range, zip, map # from __future__ import __version__ # imported lazily to avoid startup performance hit if it isn't used compiler = None # A dictionary mapping BOM to # the encoding to decode with, and what to set the # en...
_16'), BOM_UTF16_LE: ('utf16_le', 'utf_16'), BOM_UTF16: ('utf_16', 'utf_16'), } # All legal variants of the BOM codecs. # TODO: the list of aliases is not meant to be exhaustive, is there a # better way ? BOM_LIST = { 'utf_16': 'utf_16', 'u16': 'utf_16', 'utf16': 'utf_16', 'utf-16': 'utf_1...
tellybug/dynamic-dynamodb
dynamic_dynamodb/statistics/gsi.py
Python
apache-2.0
6,518
0
# -*- coding: utf-8 -*- """ This module returns stats about the DynamoDB table """ import math from datetime import datetime, timedelta from boto.exception import JSONResponseError, BotoServerError from retrying import retry from dynamic_dynamodb.aws import dynamodb from dynamic_dynamodb.log_handler import LOGGER as ...
umed_read_units) / float(dynamodb.get_provisioned_gsi_read_units( table_name, gsi_name)) * 100)) except JSONResponseError: raise logger.info('{0} - GSI: {1} - Consumed read units: {2:d}%'.format( t
able_name, gsi_name, consumed_read_units_percent)) return consumed_read_units_percent def get_throttled_read_event_count( table_name, gsi_name, lookback_window_start=15): """ Returns the number of throttled read events during a given time frame :type table_name: str :param table_name: Name of...
kkirstein/proglang-playground
Python/benchmark/tests/test_benchmark.py
Python
mit
90
0
from be
nchmark import __version__ def test_version(): assert __version__ == '0.1.0
'
ShyamSS-95/Bolt
example_problems/nonrelativistic_boltzmann/linear_modes/linear_modes_euler/1D/entropy_mode/run_cases.py
Python
gpl-3.0
1,686
0.002966
import arrayfire as af import numpy as np from bolt.lib.physical_system import physical_system from bolt.l
ib.nonlinear.nonlinear_solver import nonlinear_solver from bolt.lib.linear.linear_solver import linear_solver import input_files.domain as domain import input_f
iles.boundary_conditions as boundary_conditions import input_files.params as params import input_files.initialize as initialize import bolt.src.nonrelativistic_boltzmann.advection_terms as advection_terms import bolt.src.nonrelativistic_boltzmann.collision_operator as collision_operator import bolt.src.nonrelativistic...
Kaggle/docker-python
tests/test_lightgbm.py
Python
apache-2.0
2,382
0.002939
import unittest import lightgbm as lgb import pandas as pd from common import gpu_test class TestLightgbm(unittest.TestCase): # Based on the "simple_example" from their documentation: # https://github.com/Microsoft/LightGBM/blob/master/examples/python-guide/simple_example.py def test_cpu(self): l...
d=1, valid_sets=lgb_eval, early_stopping_roun
ds=1) self.assertEqual(1, gbm.best_iteration) def load_datasets(self): df_train = pd.read_csv('/input/tests/data/lgb_train.csv', header=None, sep='\t') df_test = pd.read_csv('/input/tests/data/lgb_test.csv', header=None, sep='\t') y_train = df_train[0] y_test =...
zestrada/nova-cs498cc
nova/api/openstack/compute/contrib/multiple_create.py
Python
apache-2.0
1,025
0
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/
LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # L
icense for the specific language governing permissions and limitations # under the License from nova.api.openstack import extensions class Multiple_create(extensions.ExtensionDescriptor): """Allow multiple create in the Create Server v1.1 API.""" name = "MultipleCreate" alias = "os-multiple-create" ...
yashchandak/GNN
Sample_Run/level2/Eval_MLP.py
Python
mit
9,173
0.013845
from __future__ import print_function import tensorflow as tf import numpy as np import time, sys from Eval_Data import Data from Eval_Config import Config import Eval_Calculate_Performance as perf import Eval_utils as utils class Network: def __init__(self, cfg): self.cfg = cfg def loss(self, y_p...
ep = optimizer.minimize(loss) return train_step class Model: def __init__(self, config): self.config = config self.data = Data(config) self.add_placeholders() self.net = Network(self.config) self.y_pred = self.net.prediction(self.x, self.keep_prob) ...
self.optimizer= self.config.optimizer self.loss = self.net.loss(self.y_pred, self.y) self.train = self.net.train(self.loss, self.optimizer) self.saver = tf.train.Saver() self.init = tf.global_variables_initializer() def add_placeholders(self): self.x = tf.place...
machaharu/odenos
apps/mininet_examples/single_network_control/start_mininet.py
Python
apache-2.0
1,901
0.000526
#!/usr/bin/env python # -*- coding:utf-8 -*- # Copyright 2015 NEC Corporation. # # # # Licensed under the Apache License, Version 2.0 (the "License"); # # you may not use this file except in comp...
applicable law or agreed to in writing, software # # distributed under the License is distributed on an "AS IS" BASIS, # # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # # limitations under the License. ...
art_of13_switches(controller, switches): for s in switches: s.start([controller]) s.sendCmd('ovs-vsctl set bridge %s protocols=OpenFlow13' % s) if '__main__' == __name__: net = Mininet(controller=RemoteController, autoStaticArp=True, switch=OVSSwitch) c1 = net.addController('c1', ip='127....
eirki/script.service.koalahbonordic
tests/test_library.py
Python
mit
9,102
0.003516
#! /usr/bin/env python2 # -*- coding: utf-8 -*- from __future__ import (unicode_literals, absolute_import, division) import unittest import os from os.path import isfile import shutil from lib import constants as const from lib import utils from lib import library from tests import mock_constants from tests import mo...
ath) class AddShow(unittest.TestCase): def test_add_show_S01E01_htm(self)
: """Was show (True Detective) added, with S01E01 htm created?""" path = check_episode(name="True Detective", ext="htm", season=1, episode=1) self.assertTrue(isfile(path), msg="File not created:\n%s" % path) def test_add_show_S01E01_nfo(self): """Was show (True Detective) added, wit...
Vauxoo/account-financial-tools
partner_report_open_invoices/models/__init__.py
Python
agpl-3.0
174
0
# -*- coding: utf-8 -*- # Copyrig
ht 2016 Serpent Consulting Services Pvt. Ltd # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). from . import res_
company
gaufung/PythonStandardLibrary
Network/Selector/selector_echo_server.py
Python
mit
1,269
0.00788
import selector import socket mysel = selector.DefaultSelec
tor() keep_running = True def read(connection, mask): ''' callback for read events ''' global keep_running client_address = connection.getpeername() print('read({})'.format(client_address)) data
= connection.recv(1024) if data: print (' received {!r}'.format(data)) connection.sendall(data) else: print (' closing') mysel.unregister(conneciton) connection.close() keep_running = False def accept(sock, mask): ''' callback for new connection ...
danirus/django-comments-xtd
example/custom/mycomments/forms.py
Python
bsd-2-clause
659
0.001517
from django import forms from django.utils.translation import gettext_lazy as _ from django_comments_xtd.forms import XtdCommentFor
m from django_comments_xtd.models import TmpXtdComment class MyCommentForm(XtdCommentForm): title = forms.CharField(max_length=256,
widget=forms.TextInput( attrs={'placeholder': _('title'), 'class': 'form-control'})) def get_comment_create_data(self, site_id=None): data = super(MyCommentForm, self).get_comment_create_data() data.update({'ti...
goldhand/django-nupages
docs/conf.py
Python
bsd-3-clause
8,131
0.007625
# -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 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 file. # # ...
ages for django.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true,
do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
CI-WATER/gsshapy
gsshapy/base/__init__.py
Python
bsd-3-clause
379
0
""" ***
***************************************************************************** * Name: Base Classes * Author: Nathan Swain * Created On: July 31, 2014 * Copyright: (c) Brigham Young University 2014 * License: BSD 2-Clause ******************************************************************************** """ from .rast im...
port *
lakshmi-kannan/st2
st2common/st2common/util/templating.py
Python
apache-2.0
3,501
0.001143
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th...
Lookup(prefix=prefix, scope=SYSTEM_SCOPE) } rendered = render_template(value=value, context=context)
return rendered def render_template_with_system_and_user_context(value, user, context=None, prefix=None): """ Render provided template with a default system context and user context for the provided user. :param value: Template string. :type value: ``str`` :param user: Name (PK) of the user for ...
scrapinghub/scrapinghub-buildpack-scrapy
vendor/sh_scrapy/sh_scrapy/log.py
Python
mit
5,397
0.001297
import sys, os, logging, warnings from twisted.python import log as txlog from scrapy import log, __version__, optional_features from scrapy.utils.python import unicode_to_str from sh_scrapy.hsref import hsref # keep a global reference to stderr as it is redirected on log initialization _stderr = sys.stderr def _lo...
logging.Handler.handleError(self, record) finally: sys.stderr = cur class HubstorageLogObserver(object): """Twisted log observer with Scrapy
specifics that writes to HubStorage""" def __init__(self, loghdlr): self._hs_loghdlr = loghdlr def emit(self, ev): logitem = self._get_log_item(ev) if logitem: _logfn(**logitem) def _get_log_item(self, ev): """Get HubStorage log item for the given Twisted even...
gkc1000/pyscf
examples/grad/06-tddft_gradients.py
Python
apache-2.0
948
0.018987
#!/usr/bin/env python # # Author: Qiming Sun <[email protected]> # ''' TDDFT analytical nuclear gradients. ''' from pyscf import gto, scf, dft, tddft mol = gto.M( atom = [ ['O' , 0. , 0. , 0], ['H' , 0. , -0.757 , 0.587], ['H' , 0. , 0.757 , 0.587]], basis = 'ccpvdz') mf = sc...
int.libxc = dft.xcfun postmf = tddft.TDDFT(mf).run() # PySCF-1.6.1 and newer supports the .Gradients method to create a gra
d # object after grad module was imported. It is equivalent to call the # .nuc_grad_method method. from pyscf import grad g = postmf.Gradients() g.kernel(state=1) #mf = scf.UHF(mol).x2c().run() #postmf = tddft.TDHF(mf).run() #g = postmf.nuc_grad_method() #g.kernel()
migglu/life
src/life.py
Python
gpl-2.0
2,013
0.035271
from cell import Cell from twodarray import TwoDArray from time import sleep from configparser import config import random class Life(object): def __init__(self, height, width): self.area = TwoDArray(width, height) self.buffer_area = TwoDArray(width, height) self.rows = height self.cols = width for x in ra...
ndexError, e: pass return neighbours def evolve(self): Life.copy_cells(self.area, self.buffer_area) for cell_num_x in range(self.area.width): for cell_num_y in range(self.area.height): neighbours = self.get_alive_neighbours(self.area, cell_num_x, cell_num_y) curr_cell = self.buffer_area.get(...
eighbours > 3 ) ): curr_cell.flip_state() Life.copy_cells(self.buffer_area, self.area) def randomize(self): for cell in self.area: if random.random() < float(config.random_alive_chance): cell.set_alive() else: cell.set_dead() def play_forever(self): while 1: print print self self....
JacobCallahan/rizza
rizza/helpers/prune.py
Python
gpl-3.0
2,971
0
# -*- encoding: utf-8 -*- """A utility that tries saved genetic tests and removes those failing""" import asyncio import yaml from pathlib import Path from logzero import logger from rizza import entity_tester from rizza import genetic_tester def genetic_prune(conf, entity='All'): """Check all saved genetic_teste...
logger.debug('{} failed.'.format(test)) to_remove.append(test) else: logger.debug('{} passed.'.format(test)) for test in to_remove: logger.warning('Removing {} from {}'.format(test, test_file)) del ...
ile)) yaml.dump(tests, test_file.open('w+'), default_flow_style=False) logger.info('Done pruning {}'.format(entity)) if test_file.exists() and test_file.stat().st_size < 10: logger.warning('Deleting empty file {}'.format(test_file)) test_file.unlink() async def ...
dwrpayne/zulip
zerver/management/commands/deactivate_realm.py
Python
apache-2.0
789
0.001267
from __future__ import absolute_import from __future__ import print_function from django.core.management.base import BaseCommand import sys from zerver.lib.actions import do_deactivate_realm from zerver.models import get_realm class Command(BaseCommand):
help = """Script to deactivate a realm.""" def add_arguments(self, parser): parser.add_argument('domain', metavar='<domain>', type=str, help='domain of realm to deactivate') def handle(self, *args, **options): realm = get_realm(options["domain"]) if rea...
"],)) sys.exit(1) print("Deactivating", options["domain"]) do_deactivate_realm(realm) print("Done!")
FederatedAI/FATE
examples/pipeline/hetero_logistic_regression/pipeline-hetero-lr-normal.py
Python
apache-2.0
2,733
0.001829
# # Copyright 2019 The FATE 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...
nstance(config, str): config = load_job_config(config) lr_param = { "name": "hetero_lr_0", "penalty": "L2", "optimizer": "rmsprop", "tol": 0.0001, "alpha": 0.01, "max_iter": 30, "early_stop": "diff", "batch_size": 320, "learning_rate":...
e": 5000, "random_seed": None }, "cv_param": { "n_splits": 5, "shuffle": False, "random_seed": 103, "need_cv": False }, "callback_param": { "callbacks": ["ModelCheckpoint"], "save_freq": "epoch" }...
tranlyvu/autonomous-vehicle-projects
Traffic Sign Classifier/src/second_attempt.py
Python
apache-2.0
8,997
0.018784
import pickle import pandas as pd import numpy as np import random import cv2 import glob import tensorflow as tf from tensorflow.contrib.layers import flatten from tensorflow.contrib.layers import flatten from sklearn.utils import shuffle def grayscale(input_image): output = [] for i in range(l...
qual(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1)) accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) saver = tf.train.Saver() train_loss_history = [] valid_loss_history = [] #Start running tensor flow with tf.Session() as sess: sess.run(tf.global_variables_in...
izer()) num_examples = len(X_train_final) print("Training...") for i in range(EPOCHS): X_train, y_train = shuffle(X_train_final, y_train_original) for offset in range(0, num_examples, BATC
nomad-vino/SPSE-1
Module 5/x5_7.py
Python
gpl-3.0
1,696
0.014741
#!/usr/bin/python print " __ " print " |__|____ ___ __ " print " | \__ \\\\ \/ / " print " | |/ __ \\\\ / " print " /\__| (____ /\_/ " print " \______| \/ " p...
p = aslr = "NO" module = imm.getModule(key) module_baseAddress = module.getBaseAddress() pe_offset = struct.unpack('<L',imm.readMemory(module_baseAddress + 0x3c,4))[0] pebase = module_baseAddress + pe_offset flags = struct.unpack('<H',imm.readMemory(pebase + 0x5e,2))[0] ...
_DLLCHARACTERISTICS_NX_COMPAT != 0) : dep = "YES" if (flags & IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE != 0) : aslr = "YES" imm.log("---- %s ----" %key) imm.log("DEP: %s ASLR: %s" %(dep, aslr)) imm.log("--------------") return "[+] Executed Successfully"
abdhaleegit/avocado-misc-tests
toolchain/gdb.py
Python
gpl-2.0
3,103
0
#!/usr/bin/env python # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
xpected failures[1-9]", line): self.log.info(line) self.fail("Few gdb tests have fail
ed")
Vicyorus/BattleTank
src/Bullet.py
Python
gpl-3.0
5,190
0.010405
import pygame from Explosion import Explosion class Bullet(object): PLAYER, ENEMY = 1, 0 def __init__(self, manager, parent, init_pos, direction, speed=3): self.manager = manager self.parent = parent self.image = pygame.image.load("res/tanks/bullet.png") self.expl...
: self.rect.x = 632 self.explode() if self.rect.y < 0: self.rect.y = 0 self.explode() if self.rect.y > 568: self.
rect.y = 568 self.explode() crashed = False # Check if we crashed with another block for block in blocks: # We can't crash with ourselves... can we? if block == self: pass # If...
googleapis/python-resource-manager
google/cloud/resourcemanager_v3/services/tag_keys/pagers.py
Python
apache-2.0
5,731
0.001396
# -*- 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...
ong with the request as metadata. """ self._method = method self._request = tag_keys.ListTagKeysRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async...
se]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterator[tag_key...
vmg/hg-stable
mercurial/localrepo.py
Python
gpl-2.0
96,365
0.000903
# localrepo.py - read/write repository class for mercurial # # Copyright 2005-2007 Matt Mackall <[email protected]> # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from node import hex, nullid, short from i18n import _ import peer, c...
ts = set() self.sharedpath = self.path try: vfs = scmutil.vfs(self.vfs.read("sharedpath").rstrip('\n'), realpath=True) s = vfs.base if not vfs.exists(): raise error.RepoError( _('.hg/sharedpath points ...
except IOError, inst: if inst.errno != errno.ENOENT: raise self.store = store.store(requirements, self.sharedpath, scmutil.vfs) self.spath = self.store.path self.svfs = self.store.vfs self.sopener = self.svf
Pointedstick/ReplicatorG
skein_engines/skeinforge-44/fabmetheus_utilities/geometry/manipulation_paths/bevel.py
Python
gpl-2.0
2,387
0.028069
""" Add material to support overhang or remove material at the overhang angle. """ from __future__ import absolute_import #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module. import __init__ from fabmetheus_utili...
05 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' globalExecutionOrder = 20 def getBevelPath( begin, center, close, end, radius ): "Get bevel path." beginComplex = begin.dropAxis() centerComplex = center.dropAxis() endComplex = end.dropAxis() beginComplexSegmentLengt...
Complex - endComplex ) minimumRadius = lineation.getMinimumRadius( beginComplexSegmentLength, endComplexSegmentLength, radius ) if minimumRadius <= close: return [ center ] beginBevel = center + minimumRadius / beginComplexSegmentLength * ( begin - center ) endBevel = center + minimumRadius / endComplexSegmentLen...
rangertaha/salt-manager
salt-manager/webapp/apps/fabric/fabhistory/urls.py
Python
mit
1,051
0.010466
#!/usr/bin/env python """ """ from __future__ import unicode_literals from django.conf.urls import patterns, url from views import * urlpatterns = patterns('', url(r'^index/$', FabricIndex.as_view(), name='fabric_index'), # Users url(r'^access/$', FabricAccessList.as_view(), name='
fabric_access'), url(r'^access/create/$', FabricAccessCreate.as_view(), name='fabric_access_creat
e'), url(r'^access/(?P<pk>\d+)/$', FabricAccessDetail.as_view(), name='fabric_access_details'), url(r'^access/delete/(?P<pk>\d+)/$', FabricAccessDelete.as_view(), name='fabric_access_delete'), url(r'^access/update/(?P<pk>\d+)/$', FabricAccessUpdate.as_view(), name='fabric_access_update'), url(r'^histor...
dadavidson/Python_Lab
Python Examples/functions-inmodule.py
Python
mit
144
0.020833
import math # Imports the math module everything = dir(math) # Sets everything to a list of things f
rom math print everything # Prints
'em all!
arizvisa/syringe
lib/ndk/pstypes.py
Python
bsd-2-clause
57,087
0.002575
import ptypes, pecoff from ptypes import * from . import error, ldrtypes, rtltypes, umtypes, ketypes, Ntddk, heaptypes, sdkddkver from .datatypes import * class PEB_FREE_BLOCK(pstruct.type): pass class PPEB_FREE_BLOCK(P(PEB_FREE_BLOCK)): pass PEB_FREE_BLOCK._fields_ = [(PPEB_FREE_BLOCK, 'Next'), (ULONG, 'Size')] cla...
(PVOID, 'fnINOUTLPMEASUREITEMSTRUCT'), (PVOID, 'fnINLPWINDOWPOS'), (PVOID, 'fnINOUTLPPOINT5'), (PVOID, 'fnINOUTLPSCROLLINFO'), (PVOID, 'fnINOUTLPRECT'), (PVOID, 'fnINOUTNCCALCSIZE'), (PVOID, 'fnINOUTLPPOINT5_'), (PVOID, 'fnINPAINTCLIPBRD'), (PVOID,...
HANGE'), (PVOID, 'fnPOWERBROADCAST'), (PVOID, 'fnINLPUAHDRAWMENU'), (PVOID, 'fnOPTOUTLPDWORDOPTOUTLPDWORD'), (PVOID, 'fnOPTOUTLPDWORDOPTOUTLPDWORD_'), (PVOID, 'fnOUTDWORDINDWORD'), (PVOID, 'fnOUTLPRECT'), (PVOID, 'fnOUTSTRING'), (PVOID, 'fnPOPTINLPUINT3'),...
drolando/SoftDev
tests/fife_test/tests/MultiPathfinderTest.py
Python
lgpl-2.1
7,856
0.032332
#!/usr/bin/env python # -*- coding: utf-8 -*- # #################################################################### # Copyright (C) 2005-2013 by the FIFE team # http://www.fifengine.net # This file is part of FIFE. # # FIFE is free software; you can redistribute it and/or # modify it under the terms of the GNU ...
st._engine self._test = test fife.InstanceActionListener.__init__(self) def onInstanceActionFinished(self, instance, action): instance.move('walk', self._test.createRandomTarget(), 4.0) def onInstanceActionCancelled(self, instance, action): pass def onInstanceActionFr
ame(self, instance, action, frame): pass class MultiPathfinderTest(test.Test): def create(self, engine, application): self._application = application self._engine = engine self._running = False self._loader = fife.MapLoader(self._engine.getModel(), self._engine.getVFS(), self._engine....
saltastro/timDIMM
weather.py
Python
bsd-3-clause
3,654
0.000547
#!/usr/bin/env python import sys import html5lib import urllib2 from numpy import median, array from xml_icd import parseICD from html5lib import treebuilders def salt(): wx = {} try: tcs = parseICD("http://icd.salt/xml/salt-tcs-icd.xml") time = t
cs['tcs xml time info'] bms = tcs['bms external conditions'] temps = bms['Te
mperatures'] wx["Temp"] = median(array(temps.values())) wx["Temp 2m"] = temps["2m"] wx["Temp 30m"] = temps["30m"] # get time wx["SAST"] = time["SAST"].split()[1] wx["Date"] = time["SAST"].split()[0] # set up other values of interest wx["Air Pressure"] =...
dreamibor/Algorithms-and-Data-Structures-Using-Python
practice/implementation/two_pointers/sort_colors.py
Python
gpl-3.0
2,266
0.008392
""" Two pointers - Sort Colours / Dutch National Flag Problem (medium) Description: Given an array containing 0s, 1s and 2s, sort the array in-place. You should treat numbers of the array as objects, hence, we can’t count 0s, 1s, and 2s to recreate the array. The flag of the Netherlands consists of three colors: red...
: [2, 0, 2, 1, 1, 0] Output: [0, 0, 1, 1, 2, 2] Notes: 1. We shall modify the array in-place. Time Complexity - O(N) - N is the total number of elements in the given array. Space Complexity - O(1) - Constant space complexity. LeetCode link: https://leetcode-cn.com/problems/sort-colors/ """ def sort_colours(nums:l...
Initially, we set two pointers called `low` and `high` which are pointing at the first element and the last element in the array. While iterating, we will move all 0s before low and all 2s after high, so in the end, all 1s will be between low and high. Since the high pointer is moving from right ...
FlexBE/generic_flexbe_states
flexbe_utility_states/src/flexbe_utility_states/publish_twist_state.py
Python
bsd-3-clause
850
0.025882
#!/usr/bin/env python from flexbe_core import EventState, Logger import rospy from flexbe_core.proxy import ProxyPublisher from geometry_msgs.msg import Twist """Created on June. 21, 2017 @author: Alireza Hosseini """ class PublishTwistState(EventState): """ Publishes a velocity command from userdata. -- t
opic string Topic to which the velocity command will be published. ># twist Twist Velocity command to be published. <= done Velcoity command has been published. """ def __init__(self, topic): """Cons
tructor""" super(PublishTwistState, self).__init__(outcomes=['done'], input_keys=['twist']) self._topic = topic self._pub = ProxyPublisher({self._topic: Twist}) def execute(self, userdata): return 'done' def on_enter(self, userdata): self._pub.publish(self._topic, userdata.twist)
winkidney/wei-dev
setup.py
Python
gpl-2.0
329
0
from
setuptools import setup, find_packages setup( name="wei-dev", version="0.2.0", packages=find_packages(), description="DevTool for weichat development and testing, "
"GUI and CLI tool and testing util-library included.", install_requires=( "cmdtree", "requests", ), )
patrickleweryharris/anagram-solver
anagram_solver/__main__.py
Python
mit
145
0
# -*-
coding: utf-8 -*- """anagram_solver.__main__: executed when directory is called as script.""" from .anagram_solv
er import main main()
yarocoder/radwatch-analysis
Isotopic_Abudance.py
Python
mit
25,349
0.000039
"""Isotopic Abundances for each isotope""" class Natural_Isotope(object): def __init__(self, symbol, mass_number, mass, isotopic_abundance, cross_section): self.symbol = symbol self.mass_number = mass_number self.mass = mass self.isotopic_abundance = .01 * isotopic...
8885, 2.365, 0.411198) Manganese_55 = Natural_Isotope("Mn", 55, 54.93805, 100, 13.2784) Iron_54 = Natural_Isotope("Fe", 54, 53.939615, 5.845, 2.25
193) Iron_56 = Natural_Isotope("Fe", 56, 55.934942, 91.754, 2.58936) Iron_57 = Natural_Isotope("Fe", 57, 56.935399, 2.119, 2.42654) Iron_58 = Natural_Isotope("Fe", 58, 57.93328, 0.282, 1.14965) Cobalt_59 = Natural_Isotope("Co", 59, 58.9332, 100, 37.1837) Nickel_58 = Natural_Isotope("Ni", 58, 57.935348, 68.0769, 4.22661...
jpacg/su-binary
jni/selinux/gui/mappingsPage.py
Python
gpl-2.0
1,873
0.009076
## mappingsPage.py - show selinux mappings ## Copyright (C) 2006 Red Hat, Inc. ## This program is free software; you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation; either version 2 of the License, or ## (at your option) any lat...
port __builtin__ __builtin__.__dict__['_'] = unicode class loginsPage: def __init__(self, xml): self.xml = xml self.view = xml.get_widget("mappingsView") self.store = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING) self.s
tore.set_sort_column_id(0, gtk.SORT_ASCENDING) self.view.set_model(self.store) self.login = loginRecords() dict = self.login.get_all(0) for k in sorted(dict.keys()): print("%-25s %-25s %-25s" % (k, dict[k][0], translate(dict[k][1])))
mbinette91/ConstructionLCA
webapp.py
Python
gpl-2.0
7,974
0.038375
import os import threading import urlparse import time from SimpleHTTPServer import SimpleHTTPRequestHandler from ModelBuilder import ModelBuilder import pickle import sqlite3 import json db = None; def GetUniqueProjectId(): global db filename = "../temp.db" if not db: db = {'last_project_id': 0} if os.path.is...
.cursor() c.execute('SELECT guid,p.name,description,class_name,m.name,m.thickness,m.layer_name FROM products p LEFT JOIN materials m ON p.id=m.product_id WHERE project_id=?', (query['id'][0],)) data = [] for row in c.fetchall(): data.append({ 'guid': row[0], 'name': row[1], 'descrip...
d_header("Content-type", "text/html") self.end_headers() self.wfile.write(json.dumps(data, encoding='latin1')) return; elif query['get'][0] == 'properties': conn = sqlite3.connect('../database.db3') conn.text_factory = str c = conn.cursor() c.execute('SELECT ps.id, ps.name FROM products p JOIN pr...
BedivereZero/LeeCode
algorithms/0005-longest-palindromic-substring.py
Python
gpl-3.0
627
0.001595
class Solution: def longestPalindrome(self, s: str) -> str:
f = [[None for _ in range(len(s))]for _ in range(len(s))] a, b = 0, 0 for length in range(len(s)): for head in range(len(s)): tail = head + length if tail < len(s): if length < 2: f[head][tail] = s[head] == s...
d][tail] = f[head + 1][tail - 1] and s[head] == s[tail] if f[head][tail] and b - a < length: a, b = head, tail return s[a:b + 1]
tianyang-li/de-novo-metatranscriptome-analysis--the-uniform-model
analysis/single_align_analysis_0.py
Python
gpl-3.0
8,259
0.005933
#!/usr/bin/env python # Copyright (C) 2012 Tianyang Li # [email protected] # # 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 lat...
(read_start < len(self.reads) and cur_nuc == self.reads[read_start].low):
cur_cov += 1 read_start += 1 while (read_end < len(self.reads) and cur_nuc == self.reads[read_end].high + 1): cur_cov -= 1 read_end += 1 nuc_cov.append(cur_cov) return nuc_cov class SingleChrom(Chr...
rvianello/rdkit
rdkit/Chem/Pharm2D/LazyGenerator.py
Python
bsd-3-clause
4,307
0.01068
# # Copyright (C) 2003-2006 greg Landrum and Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # """ lazy generator of 2D pharm...
r bit in
bits: v = sig[bit] t2 = time.time() print('\tthat took %4.2f seconds' % (t2 - t1))
yolanother/ubuntumobidev_ubiquity
ubiquity/frontend/kde_components/testing/partman.py
Python
gpl-3.0
10,910
0
# -*- coding: utf-8 -*- import os import sys from PyQt4 import QtGui from ubiquity.frontend.kde_components.PartMan import PartMan if __name__ == "__main__": app = QtGui.QApplication(sys.argv) app.setStyle("Oxygen") PartMan._uidir = '../../../../gui/qt' styleFile = os.path.join(PartMan._uidir, "s...
62882559', ]
def tree_device(dev, part_id=None): prefix = '60partition_tree__________/var/lib/partman/devices/=dev=' if part_id is None: return prefix + dev + '//' else: return prefix + dev + '//' + part_id disk_cache = { '/var/lib/partman/devices/=dev=sda//': { ...
econne01/flask_blog
app/app.py
Python
mit
1,579
0.002533
""" Configuration for Flask app """ import os import urllib from flask import (Flask, abort, flash, Response) from playhouse.flask_utils import FlaskDB ADMIN_PASSWORD = 'secret' APP_DIR = os.path.dirname(os.path.realpath(__file__)) DATABASE = 'sqliteext:///%s' % os.path.join(APP_DIR, 'blog.db') DEBUG = False SECRET_...
', 'drafts', views.drafts, methods=['GET']) app.add_url_rule('/<slug>', 'detail', views.detail, methods=['GET']) app.add_url_rule('/<slug>/edit', 'edit', views.edit, methods=['GET', 'POST']) @app.template_filter('clean_querystring') def clean_querystring(request_args, *keys_to_remove, **new_values): querystring =...
one) querystring.update(new_values) return urllib.urlencode(querystring) @app.errorhandler(404) def not_found(exc): return Response('<h3>404 Error: Page Not found</h3>'), 404
cuckoo5/soap
Soap_know/oauth/base_mixin.py
Python
gpl-3.0
196
0.005102
# c
oding=utf-8 from tornado import httpclient from tornado.auth import OAuth2Mixin class BaseMixin(OAuth2Mixin): def get_auth_http_c
lient(self): return httpclient.AsyncHTTPClient()
Maximilian-Reuter/SickRage-1
lib/fake_useragent/fake.py
Python
gpl-3.0
1,434
0
from __future__ import absolute_import, unicode_literals import random from threading import Lock from fake_useragent import settings from fake_useragent.utils import load, load_cached, update class UserAgent(object): lock = Lock() # mutable cross-instance threading.Lock def __init__(self, cache=True): ...
S.items(): attr = attr.replace(value, replacement) attr = attr.lower() if attr == 'random': attr = self.data['randomiz
e'][ str(random.randint(0, len(self.data['randomize']) - 1)) ] else: if attr in settings.SHORTCUTS: attr = settings.SHORTCUTS[attr] try: return self.data['browsers'][attr][ random.randint( 0, len(sel...
kohnle-lernmodule/palama
exe/webui/block.py
Python
gpl-2.0
12,877
0.007067
# =========================================================================== # eXe # Copyright 2004-2006, University of Auckland # # 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 versio...
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write
to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # =========================================================================== """ Block is the base class for the classes which are responsible for rendering and processing Idevices in XHTML """ import sys from exe.webui ...
antoinecarme/pyaf
tests/artificial/transf_Fisher/trend_MovingAverage/cycle_5/ar_/test_artificial_128_Fisher_MovingAverage_5__100.py
Python
bsd-3-clause
266
0.086466
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_le
ngth = 5, transform = "Fisher", sigma
= 0.0, exog_count = 100, ar_order = 0);
bobwalker99/Pydev
plugins/com.python.pydev.refactoring/tests/pysrcrefactoring/reflib/renamemodule6/scene_tree.py
Python
epl-1.0
25
0.04
class
SceneTree:
pass
opendatakosovo/kosovolunteer
ve/views/delete_event.py
Python
gpl-2.0
558
0.003584
from flask import Flask from flask.views import View from flask import Response, request import urllib2 from ve import utils class DeleteEvent(View): def dispatch_request(self): api_base_url = utils.get_
api_url() url = '%s/delete/event'%(api_base_url) data = request.data print data r = urllib2.Request(url, data=data, headers={"Content-Type": "application/json"}) res = urllib2.urlopen(r) resp = Response( response=data, mimetype='application/json')...
nerandell/vyked
vyked/utils/decorators.py
Python
mit
356
0
import warnings from functools import wraps def deprecated(func): """ Generates a deprecation warning """ @wraps(func) def wrapper(*args, **kwargs): msg = "'{}' is deprecated".format(func.__name__) warnings.warn(msg, category=Depre
cationWarning, stacklevel=2) return func(*args, **kwargs) return wrappe
r
atyndall/cits4211
tools/tree_generator.py
Python
mit
14,570
0.02464
# tree_generator was written with Python 2.7.4. # The pickle files it produces should not be read with a version of # Python less than 2.7.4, as they are not forwards compatible. from piece_definitions import PIECES import numpy as np import sys import collections import itertools import argparse import multiprocessing...
for _, r in options: for h in
range(HEIGHT): for w in range(WIDTH): try: i += 1 op = DAction(BOARD, n, r, h, w) possibilities.append(op) except PieceNotFitError: pass print i lp = len(possibilities) print "There are %d possible orientations and positions for the give...
federicotdn/piter
src/util.py
Python
gpl-3.0
625
0.056
import unicodedata import curses class BufferError(Exception): def __init__(self, msg): self._msg = msg def __str__(sel
f): return repr(self._msg) def interpret_arrowkey(key): directions = { curses.KEY_UP : (0, -1), curses.KEY_DOWN : (0, 1), curses.KEY_RIGHT : (1, 0), curses.KEY_LEFT : (-1, 0) } if key not in directions: return None
return directions[key] def is_printable(t): if not isinstance(t, str): return False non_printables = ['Cc', 'Cn'] printables_extra = ['\n', '\t'] return unicodedata.category(t) not in non_printables or \ t in printables_extra
schelleg/PYNQ
pynq/lib/rpi/rpi.py
Python
bsd-3-clause
5,799
0.001207
# Copyright (c) 2016, Xilinx, 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, # this list of con...
ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import os from pynq.lib import PynqMicroblaze from pynq.lib.pynqmicroblaze import add_bsp from ...
T from . import MAILBOX_PY2IOP_CMD_OFFSET from . import BIN_LOCATION from . import BSP_LOCATION __author__ = "Yun Rock Qu" __copyright__ = "Copyright 2016, Xilinx" __email__ = "[email protected]" class Rpi(PynqMicroblaze): """This class controls the Raspberry Pi Microblaze instances in the system. This class...
Kamik423/uni_plan
plan/plan/lib64/python3.4/base64.py
Python
apache-2.0
20,167
0.002231
#! /usr/bin/python3.4 """Base16, Base32, Base64 (RFC 3548), Base85 and Ascii85 data encodings""" # Modified 04-Oct-1995 by Jack Jansen to use binascii module # Modified 30-Dec-2003 by Barry Warsaw to add full RFC 3548 support # Modified 22-May-2007 by Guido van Rossum to use bytes everywhere import re import struct ...
('Non-base64 digit found') return binascii.a2b_base64(s) def standard_b64encode(s): """Encode a byte string using the standard Base64 alphabet. s is the byte string to encode. The encoded byte string is returned. """ return b64encode(s) def standard_b64decode(s): """Decode a byte string enc...
nput is incorrectly padded or if there are non-alphabet characters present in the input. """ return b64decode(s) _urlsafe_encode_translation = bytes.maketrans(b'+/', b'-_') _urlsafe_decode_translation = bytes.maketrans(b'-_', b'+/') def urlsafe_b64encode(s): """Encode a byte string using a url-sa...
TimelyToga/wtf_is
wtf_proj/wtf_proj/views.py
Python
mit
3,001
0.000666
from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from bs4 import BeautifulSoup as bs import requests import json WIKI_PAGE_BASE = "https://en.wikipedia.org/wiki/" WIKI_API_BASE = "https://en.wikipedia.org/w/api.php?format=json&action=query" WIKI_EXTRACT = WIKI_API_BASE...
return HttpResponseRedirect("/is/" + parameter) def scrape_site_fs(term): rdata = requests.get(WIKI_PAGE_BASE + term) soup = bs(rdata.content) page_content = soup.find("div", {"id": "mw-content-text"}) if page_content: return page_content.findAll("p")[:5] return None def api_fs(term...
HttpResponseRedirect("/search_results/?term=" + term) # Get the pages from the results pages = json_data["query"]["pages"] page_keys = pages.keys() if int(page_keys[0]) == -1: return None first_page = pages[page_keys[0]] if not first_page: # If no first page, perform search ...
jainanisha90/WeVoteServer
import_export_ctcl/models.py
Python
mit
730
0.00411
# im
port_export_ctcl/models.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- from django.db import m
odels import wevote_functions.admin logger = wevote_functions.admin.get_logger(__name__) class CandidateSelection(models.Model): """ Contest Office to Candidate mapping is stored in this table. """ batch_set_id = models.PositiveIntegerField(verbose_name="batch set id", default=0, null=True, blank=Tr...
mpharrigan/msmbuilder
MSMBuilder/metrics/rmsd.py
Python
gpl-2.0
5,554
0.002341
from __future__ import print_function, absolute_import, division from mdtraj.utils.six.moves import xrange import warnings import numpy as np from collections import namedtuple import mdtraj as md from .baseclasses import AbstractDistanceMetric class RMSD(AbstractDistanceMetric): """ Compute distance b
etween frames using the Room Mean Square Deviation over a specifiable set of atoms using the Theobald QCP algorithm References ---------- .. [1] Theobald, D. L. Acta. Crystallogr., Sect. A 2005, 61, 478-480. """ def __init__(self, atomindices=None, omp_parallel=True): """Initalize an ...
ray_like, optional List of the indices of the atoms that you want to use for the RMSD calculation. For example, if your trajectory contains the coordinates of all the atoms, but you only want to compute the RMSD on the C-alpha atoms, then you can supply a reduced set of a...
vsco/grpc
src/python/grpcio/grpc_core_dependencies.py
Python
bsd-3-clause
33,262
0.000241
# Copyright 2015, 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: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the f...
/pollset_windows.c', 'src/core/lib/iomgr/resolve_address_posix.c', 'src/core/lib/iomgr/resolve_address_uv.c', 'src/core/lib/iomgr/resolve_address_windows.c', 'src/core/lib/i
omgr/resource_quota.c', 'src/core/lib/iomgr/sockaddr_utils.c', 'src/core/lib/iomgr/socket_factory_posix.c', 'src/core/lib/iomgr/socket_mutator.c', 'src/core/lib/iomgr/socket_utils_common_posix.c', 'src/core/lib/iomgr/socket_utils_linux.c', 'src/core/lib/iomgr/socket_utils_posix.c', 'src/core/lib/iomgr/soc...
terencezl/pydass_vasp
pydass_vasp/electronic_structure/dos.py
Python
mit
12,658
0.002844
import re import numpy as np import pandas as pd import matplotlib.pyplot as plt from .helpers import determine_tag_value, figs_assert, initiate_figs, plot_helper_settings from ..xml_utils import parse def get_tdos(filepath='DOSCAR', ISPIN=None, Ef=None, plot=False, xlim=None, ylim_upper=None, on_figs=None): """
Get the total density of states, with consideration of spin-polarization. Accepts file type 'DOSCAR', or 'vasprun.xml'. Parameters ----------
filepath: string filepath, default to 'DOSCAR' For DOSCAR-type file, can be any string containing 'DOSCAR'. For vasprun.xml-type file, can be any string ending with '.xml'. ISPIN: int user specified ISPIN If not given, for DOSCAR-type file, infer from 'OUTCAR'/'INCAR'. ...
Chilledheart/chromium
tools/telemetry/third_party/modulegraph/modulegraph_tests/testpkg-relimport/pkg/relative.py
Python
bsd-3-clause
57
0
from
__future__ import absolute_import fr
om . import mod
ldotlopez/appkit
tests/config.py
Python
gpl-2.0
2,801
0
# -*- coding: utf-8 -*- # Copyright (C) 2015 Luis López <[email protected]> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any late...
o'), 1) b = config.Record() b.set('foo', 1) b.set('bar', 'x') self.assertEqual(a, b) def test_setget(self):
s = config.Record() s.set('foo', 1) s.set('bar', 'x') s.set('x.y', []) self.assertEqual(s.get('foo'), 1) self.assertEqual(s.get('bar'), 'x') self.assertEqual(s.get('x.y'), []) def test_nonexistent_key(self): s = config.Record() with self.ass...
pomarec/core
arkos/system/services.py
Python
gpl-3.0
12,907
0.00031
""" Classes and functions for management of system-level services. arkOS Core (c) 2016 CitizenWeb Written by Jacob Cook Licensed under GPLv3, see LICENSE.md """ import configparser import os import time from dbus.exceptions import DBusException from arkos import conns, signals from arkos.utilities import shell cl...
self.enable() signals.emit("services", "post_add", self) def start(self): """Start service.""" signals.emit("services", "pre_start", self) if self.stype == "supervisor": supervisor_ping() try: conns.Supervisor.startProcess(self.name) ...
raise ActionError( "svc", "The service failed to start. Please check " "`sudo arkosctl svc status {0}`".format(self.name)) else: # Send the start command to systemd try: path = conns.SystemD.LoadUnit(self.sfname) ...
stackforge/solum
solum/objects/sqlalchemy/image.py
Python
apache-2.0
5,222
0
# Copyright 2014 - Rackspace Hosting # # 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 ...
ls as sql cfg.CONF.import_opt('operator_project_id', 'solum.api.handlers.language_pack_handler', group='api') operator_id = cfg.CONF.api.opera
tor_project_id LOG = logging.getLogger(__name__) class Image(sql.Base, abstract.Image): """Represent a image in sqlalchemy.""" __tablename__ = 'image' __resource__ = 'images' __table_args__ = sql.table_args() id = sa.Column(sa.Integer, primary_key=True, autoincrement=True) uuid = sa.Column(...
knights-lab/shi7
shi7/shi7_learning.py
Python
agpl-3.0
15,977
0.006009
#!/usr/bin/env python from __future__ import print_function, division import multiprocessing import os import csv import datetime import logging from datetime import datetime import argparse import shutil import math from glob import glob import gzip from shi7 import __version__ from shi7.shi7 import TRUE_FALSE_DICT, ...
_inf = csv.reader(inf, delimiter="\t") x2f = 0 sum = 0 cnt = 0 for row in csv_inf: row = [int(r) for r in row] cnt = cnt + row[1] sum = sum + row[0] * row[1] x2f = x2f + row[
0] * row[0] * row[1] mean = sum/cnt std = math.sqrt((x2f - sum*sum/cnt)/(cnt-1)) cv = std/mean total_cv = total_cv + cv total_mean = total_mean + mean total_files = len(hist_files) return total_cv/total_files, total_mean/total_files def trimmer_learn...
pybuilder/pybuilder
src/main/python/pybuilder/_vendor/virtualenv/config/ini.py
Python
apache-2.0
2,807
0.001425
from __future__ import absolute_import, unicode_literals import logging import os from ...platformdirs import user_config_dir from ..info import PY3 from ..util import ConfigParser from ..util.path import Path from ..util.six import ensure_str from .convert import convert class IniConfig(object): VIRTUALENV_C...
ption: result = None self._cache[cache_key] = result return result def __bool__(self): return bool(self
.has_config_file) and bool(self.has_virtualenv_section) @property def epilog(self): msg = "{}config file {} {} (change{} via env var {})" return msg.format( "\n", self.config_file, self.STATE[self.has_config_file], "d" if self.is_env_var else "", ...
fmuzf/python_hk_glazer
hk_glazer/test/test.py
Python
mit
1,705
0.022287
from nose.tools import with_setup import os import hk_glazer as js2deg import subprocess import json class TestClass: @classmethod def setup_class(cls): cls.here = os.path.dirname(__file__) cls.data = cls.here + '/data' def test_1(self): '''Test 1: Check that json_to_degree works when imported'...
os.
remove("test2.txt") pass def test_3(self): '''Test 3: Command line execution when outfile already exists''' cmd = os.path.abspath(self.here + '/../../bin/hk_glazer') subprocess.check_call([cmd, "js2degree", self.data + "/json_test_in.json", "-o=test3.txt", "-s"]) try: subprocess.check_cal...
edickie/ciftify
tests/test_ciftify_recon_all.py
Python
mit
15,712
0.005474
#!/usr/bin/env python3 import unittest import logging import importlib import copy import os from docopt import docopt from unittest.mock import patch import pytest import ciftify.utils logging.disable(logging.CRITICAL) ciftify_recon_all = importlib.import_module('ciftify.bin.ciftify_recon_all') class ConvertFreesu...
self.work_dir = '/somepath/hcp' class Subject(object): def __init__(self): id = 'some_id' settings = S
ettings() mesh_settings = {'meshname' : 'some_mesh'} ciftify_recon_all.copy_atlas_roi_from_template(settings, mesh_settings) assert mock_link.call_count == 0 class DilateAndMaskMetric(unittest.TestCase): @patch('ciftify.bin.ciftify_recon_all.run') def test_does_nothing_when_dscalars_m...
okfde/odm-datenerfassung
utils/extractFileName.py
Python
mit
660
0.010606
import unicodecsv as csv import sys csvoutfile = open(s
ys.argv[3], 'wb') citywriter = csv.writer(csvoutfile, delimiter=',') with open(sys.argv[1], 'rb') as csvfile: cityreader = csv.reader(csvfile, delimiter=',') #Skip headings headings = next(cityreader, None)
#Write headings citywriter.writerow(headings) for inrow in cityreader: url = inrow[1] tcolumn = int(sys.argv[2]) filename = inrow[1].split('/')[-1] if (len(inrow) - 1) < tcolumn: inrow.append(filename) else: inrow[tcolumn] = filename city...
wulczer/flvlib
lib/flvlib/scripts/cut_flv.py
Python
mit
7,154
0
import sys import logging from optparse import OptionParser from flvlib import __versionstr__ from flvlib.constants import TAG_TYPE_AUDIO, TAG_TYPE_VIDEO, TAG_TYPE_SCRIPT from flvlib.constants import FRAME_TYPE_KEYFRAME from flvlib.constants import H264_PACKET_TYPE_SEQUENCE_HEADER from flvlib.constants import H264_PA...
d_time) def main(): try: outcome = cut_files() except KeyboardInterrupt: # give the right exit status, 128 + signal number # signal.SIGINT = 2 sys.exit(128 + 2) except EnvironmentError, (errno, strerror): try: print >> sys.stderr, strerror except...
sys.exit(2) if outcome: sys.exit(0) else: sys.exit(1) if __name__ == '__main__': main()
pwyliu/packagecloud-poll
packagecloudpoll/poll.py
Python
mit
4,074
0.003191
"""packagecloud-poll Packagecloud-poll repeatedly polls the packagecloud API, looking for a specific package filename to appear. It is intended to be used in continuous integration/continuous deployment scenarios where we want to block until we are sure a package has been indexed and is avaiable before continuing. Al...
t, --poll_interval, --page_interval and --log-level. Increased productivity gains high favour from the machine god. Usage: packagecloud-poll --user user --repo repo_name --type type --distro distro --distro_version distro_version --arch arch --pkg_name pkg_name --filename filename [--timeout timeout] [--poll_inte...
val] [--page_interval interval] [--log-level log_level] packagecloud-poll --help packagecloud-poll --version Options: --user <user> Packagecloud user. --repo <repo_name> Packagecloud repository. --type <type> Package type. (i.e. rpm or deb) ...
eusoubrasileiro/fatiando
setup.py
Python
bsd-3-clause
3,101
0
""" Build extension modules, package and install Fatiando. """ import sys import os from distutils.core import setup from distutils.extension import Extension import numpy import versioneer versioneer.VCS = 'git' versioneer.versionfile_source = 'fatiando/_version.py' versioneer.versionfile_build = 'fatiando/_version.p...
Extension('.'.join(e), [os.path.join(*e) + ext], libraries=libs, include_dirs=[numpy.get_include()], **extra_args))
if USE_CYTHON: sys.argv.remove('--cython') from Cython.Build import cythonize extensions = cythonize(extensions) if __name__ == '__main__': setup(name=NAME, fullname=FULLNAME, description=DESCRIPTION, long_description=LONG_DESCRIPTION, version=VERSION, ...
UMD-AMAV/TerpCopter
terpcopter_libraries/mavlink/share/pyshared/pymavlink/mavextra.py
Python
gpl-3.0
4,562
0.00811
#!/usr/bin/env python ''' useful extra functions for use by mavlink clients Copyright Andrew Tridgell 2011 Released under GNU GPL version 3 or later ''' from math import * def kmh(mps): '''convert m/s to Km/h''' return mps*3.6 def altitude(press_abs, ground_press=955.0, ground_temp=30): '''calculate ba...
eturn dv def delta_angle(var, key): '''calculate slope of an angle''' global last_delta dv = 0 if key in last_delta: dv = var - last_delta[key] last_delta[key] = var if dv > 180: dv -= 360 if dv < -180: dv += 360 return dv def roll_estimate(RAW_IMU,smooth=0.7): ...
AW_IMU.xacc,'rx',smooth) ry = lowpass(RAW_IMU.yacc,'ry',smooth) rz = lowpass(RAW_IMU.zacc,'rz',smooth) return degrees(-asin(ry/sqrt(rx**2+ry**2+rz**2))) def pitch_estimate(RAW_IMU, smooth=0.7): '''estimate pitch from accelerometer''' rx = lowpass(RAW_IMU.xacc,'rx',smooth) ry = lowpass(RAW_IMU.y...
rembish/mls
setup.py
Python
bsd-2-clause
1,212
0
#!/usr/bin/env python from os.path import dirname, abspath, join from setuptools import setup here = abspath(dirname(__file__)) readme = open(join(here, "README.rst")) setup( name="mls", version="1.2.2", py_modules=["mls"], url="https://github.com/rembish/mls", license="BSD", author="Aleksey R...
nes()), test_suite="tests", install_requires=["six"], classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: BSD License", "Programming Language :: Python :: 2", "Programmin
g Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: Impl...
andras-tim/tchart
tests/test_decorators_paper.py
Python
gpl-3.0
1,537
0.000651
# -*- coding: UTF-8 -*- # pylint: disable=misplaced-comparison-constant,redefined-outer-name,no-self-use import pytest from tchart.decorators import PaperDecorator @pytest.mark.parametrize('lines,expected_lines', ( ( [ u'0', ], [ u' .---. ', u' ...
', ], [ u' .---. ', u' / . \\ ', u' |\\_/| |', u' | | /|', u' .-------------------------\' |', u' / .-. orange kako banana |', ...
u'| |\\_. | mango |', u'|\\| | /| pulp / ', u'| |-------------------\' ', u'\\ | ', u' \\ / ', u' `---\' ', ], ), )) def te...
ucsd-ccbb/Oncolist
src/restLayer/app/SearchDrugsTab.py
Python
mit
15,395
0.006236
__author__ = 'aarongary' from app import PubMed from app import elastic_search_uri from collections import Counter from elasticsearch import Elasticsearch es = Elasticsearch([elastic_search_uri],send_get_body_as='POST',timeout=300) #============================ #============================ # DRUG SEARCH #=====...
else: hitMin = hit['_sco
re'] geneNeighborhoodArray = []; scoreRankCutoff = 0.039 node_list_name_and_weight = [] for geneNodeHit in hit["_source"]["node_list"]: geneNeighborhoodArray.append(geneNodeHit['name']) x = [set(geneNeighborhoodArray), set(queryTermArray)] y = set.interse...
pdehaye/theming-edx-platform
lms/djangoapps/bulk_email/tasks.py
Python
agpl-3.0
10,209
0.003624
""" This module contains celery task functions for handling the sending of bulk email to a course. """ import math import re import time from smtplib import SMTPServerDisconnected, SMTPDataError, SMTPConnectError from django.conf import settings from django.contrib.auth.models im
port User, Group from django.core.mail import EmailMultiAlternatives, get_connection from django.http import Http404 from celery import task, current_task from celery.utils.log import get_task_logger from django.core.urlresolvers import reverse from statsd import statsd from bulk_email.models import ( CourseEmail,...
ND_TO_MYSELF, SEND_TO_STAFF, SEND_TO_ALL, ) from courseware.access import _course_staff_group_name, _course_instructor_group_name from courseware.courses import get_course_by_id, course_image_url log = get_task_logger(__name__) @task(default_retry_delay=10, max_retries=5) # pylint: disable=E1102 def delegate_email_...
Fantomas42/django-blog-zinnia
zinnia/admin/category.py
Python
bsd-3-clause
1,209
0
"""CategoryAdmin for Zinnia""" from django.contrib import admin from django.urls import NoReverseMatch from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ from zinnia.admin.forms import CategoryAdminForm class CategoryAdmin(admin.ModelAdmin): """ Admin for Categor...
t', 'description', 'slug') list_display = ('title', 'slug', 'get_tree_path', 'description') sortable_by = ('title', 'slug') prepopulated_fields = {'slug': ('title', )} search_fields = ('title', 'description') list_filter = ('parent',) def __init__(self, model, admin_site): self.form.adm...
): """ Return the category's tree path in HTML. """ try: return format_html( '<a href="{}" target="blank">/{}/</a>', category.get_absolute_url(), category.tree_path) except NoReverseMatch: return '/%s/' % category.tree_path ...
sacharya/nova
nova/weights.py
Python
apache-2.0
4,485
0.000223
# Copyright (c) 2011-2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Un...
xval = weight weights.append(weight) return weights class BaseWeightHandler(loadables.BaseLoader): object_class = WeighedObject def get_weighed_objects(self, weigher_classes, obj_list, weighing_properties
): """Return a sorted (descending), normalized list of WeighedObjects.""" if not obj_list: return [] weighed_objs = [self.object_class(obj, 0.0) for obj in obj_list] for weigher_cls in weigher_classes: weigher = weigher_cls() weights = weigher.weigh_...