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
bitcoinknots/bitcoin
test/functional/feature_cltv.py
Python
mit
8,354
0.003831
#!/usr/bin/env python3 # Copyright (c) 2015-2020 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test BIP65 (CHECKLOCKTIMEVERIFY). Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) b...
e the following reasons: # 1) the stack is empty # 2) the top item on the stack is less than 0 # 3) the lock-time type (height vs. timestamp) of the top stack item and the # nLockTime field are not the same # 4) the top stack item is greater than the transaction's nLockTime field # 5) the nSe...
scheme = [ # | Script to prepend to scriptSig | nSequence | nLockTime | # +-------------------------------------------------+------------+--------------+ [[OP_CHECKLOCKTIMEVERIFY], None, None], [[OP_1NEGATE, OP_CHECKLOCKTIMEVERIF...
cenkbircanoglu/drf_authentication
drf_authentication/app_settings.py
Python
mit
2,084
0.00144
from __future__ import unicode_literals from django.conf import settings from drf_authentication.serializers.drf_auth_login_serializer \ import DrfAuthLoginSerializer from drf_authentication.serializers.drf_auth_logout_serializer \ import DrfAuthLogoutSerializer from drf_authentication.serializers.drf_auth_us...
= { 'LOGIN_SERIALIZER': DrfAuthLoginSerializer, 'LOGOUT_SERIALIZER': DrfAuthLogoutSerializer, 'USER_SERIALIZER': DrfAuthUserSerializer, 'AUTHENTICATION_BACKENDS': settings.AUTHENTICATION_BACKENDS } class APISettings(object): """ A settings object,
that allows API settings to be accessed as properties. For example: from rest_framework.settings import api_settings print(api_settings.DEFAULT_RENDERER_CLASSES) Any setting with string import paths will be automatically resolved and return the class, rather than the string literal. ""...
sashs/Ropper
sample.py
Python
bsd-3-clause
4,732
0.008664
#!/usr/bin/env python from ropper import RopperService # not all options need to be given options = {'color' : False, # if gadgets are printed, use colored output: default: False 'badbytes': '00', # bad bytes which should not be in addresses or ropchains; default: '' 'all' : False, #...
le to look for gadgets for a different architecture # It is useful for ARM if you want to look for ARM gadgets or Thumb gadgets # Or if you opened a raw file ls = 'test-binaries/ls-x86' rs.setArchitectureFor(name=ls, arch='x86') rs.setArchitectureFor(name=ls, arch='x86_64') rs.setArchitectureFor(name=ls, arch='ARM') rs...
s.setArchitectureFor(name=ls, arch='MIPS') rs.setArchitectureFor(name=ls, arch='MIPS64') rs.setArchitectureFor(name=ls, arch='PPC') rs.setArchitectureFor(name=ls, arch='PPC64') rs.setArchitectureFor(name=ls, arch='SPARC64') rs.setArchitectureFor(name=ls, arch='x86') ##### load gadgets ###### # load gadgets for all o...
alirizakeles/tendenci
tendenci/apps/base/templatetags/base_filters.py
Python
gpl-3.0
13,196
0.004471
import re import os import pytz from PIL import Image from dateutil.parser import parse from datetime import datetime from decimal import Decimal from django.template import Library from django.conf import settings from django.template.defaultfilters import stringfilter from django.utils import formats from django.uti...
'long': return date_long(value) if arg == 'short': return date_short(value) try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return '' date_long.is_safe = False...
plit(',')] return queryset.order_by(*args) @register.filter_function def str_to_date(string, args=None): """Takes a string and converts it to a datetime object""" date = parse(string) if date: return date return '' @register.filter_function def exif_to_date(s, fmt='%Y:%m:%d %H:%M:%S'): ...
levkar/odoo-addons
account_interests/__init__.py
Python
agpl-3.0
71
0.014085
# -*- c
oding: utf-8 -*- import interest import partner import compa
ny
fdroidtravis/fdroidserver
fdroidserver/__main__.py
Python
agpl-3.0
9,662
0.001346
#!/usr/bin/env python3 # # fdroidserver/__main__.py - part of the FDroid server tools # Copyright (C) 2020 Michael Pöhn <michael.poehn@fsfe.org> # Copyright (C) 2010-2015, Ciaran Gultnieks, ciaran@ciarang.com # Copyright (C) 2013-2014 Daniel Marti <mvdan@mvdan.cc> # # This program is free software: you can redistribute...
using update --nosign")), ("btlog", _("Update the binary transparency log for a URL")), ("signatures", _("Extract signatures from APKs")), ("nightly", _("Set up an app build for a nightly build repo")), ("mirror", _("Download complete mirrors of small repos")), ]) def print_help(available
_plugins=None): print(_("usage: ") + _("fdroid [<command>] [-h|--help|--version|<args>]")) print("") print(_("Valid commands are:")) for cmd, summary in COMMANDS.items(): print(" " + cmd + ' ' * (15 - len(cmd)) + summary) if available_plugins: print(_('commands from plugin modules:...
mflu/openvstorage_centos
ovs/extensions/generic/watcher.py
Python
apache-2.0
7,323
0.002868
#!/usr/bin/python2 # Copyright 2014 CloudFounders NV # # 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 o...
y) except Exception as message: _log(target, ' Error during persistent store test: {0}'.format(message), 2) key = 'ovs-watcher-{0}'.format(str(uuid.uuid4())) # Get another key time.sleep(1) tries += 1 if tries == max_tries...
es'.format(tries), 0) if target == 'volumedriver': # Arakoon, voldrv cluster _log(target, 'Testing arakoon (voldrv)...', 0) max_tries = 5 tries = 0 while tries < max_tries: try: from ovs.extensions.db.arakoon.Arakoo...
EngTurtle/skule_tutors2
course_manage/models.py
Python
mit
945
0.019048
from django.db import models # Create your models here. class Course(models.Model): year = models.SmallIntegerField(verbose_name = 'Course Year') course_code = models.CharField(verbose_
name = 'Course Code', max_length = 7, primary_key = True) name = models.CharField(verbose_name = 'Course Name', max_length = 50) description = models.TextField(blank = True) def save(self, *args, **kwargs): """ Make the course code always in upper case """ self.course_code = str(self.cours...
return self.course_code + ' | ' + self.name def __unicode__(self): return self.course_code # def get_absolute_url(self): # """ # returns the url of this course. # """ # return reverse('engsci_conga.views.courses_view', kwargs = {'cour...
achapkowski/ArcREST
src/arcrest/webmap/operationallayers.py
Python
apache-2.0
3,681
0.009508
from .._abstract.abstract import BaseOperationalLayer from ..common.general import _date_handler, _unicode_convert import json import uuid ######################################################################## class MapGraphicLayer(BaseOperationalLayer): """ Represents a graphic in the map. There are no...
"symbol":symbol.asDictionary}] } } self._storedFeatures[layerName] = template_ld return True, layerName #---------------------------------------------------------------------- def __look_up_geom(self, geomType): """ compares the geometry object...
Inputs: geomType - string - geometry object's type Returns: string JSON geometry type or None if not an allowed type """ if geomType.lower() == "point": return "esriGeometryPoint" elif geomType.lower() == "polyline": return "esriG...
tst-mswartz/earthenterprise
earth_enterprise/src/server/wsgi/search/plugin/poi_search_app.py
Python
apache-2.0
3,568
0.007848
#!/usr/bin/env python2.7 # # Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable l...
rror( "%s Status %s sent back to client.", e, status) _, _, tb = sy
s.exc_info() stack_trace = "".join(traceback.format_tb(tb)) self._poi.logger.debug("Stack trace:\n%s", stack_trace) response_body = "%s" % e response_headers.append(tuple(content_type.split(","))) start_response(status, response_headers) return [response_body] application = GePoiSearc...
citrix-openstack-build/swift
test/unit/container/test_server.py
Python
apache-2.0
75,820
0.000079
# Copyright (c) 2010-2012 OpenStack, 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 ...
lf.assert_(resp.status.startswith('204')) req = Request.blank( '/sda1/p/a/c', environ={'REQUEST_METHOD': 'HEAD'}) response = req.get_response(self.controller) self.assert_(response.status.startswith('204')) self.assertEquals(response.headers.get('x-container-read'), '.r:*') ...
sertEquals(response.headers.get('x-container-write'), 'account:user') # Ensure we can clear acls on POST req = Request.blank( '/sda1/p/a/c', environ={'REQUEST_METHOD': 'POST'}, headers={'X-Timestamp': '3', 'X-Container-Read': '', 'X-...
open-o/nfvo
lcm/lcm/ns/sfcs/create_sfc_worker.py
Python
apache-2.0
2,698
0.001483
# Copyright 2016 ZTE Corporation. # # 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 ...
import SfcInstance from lcm.ns.sfcs.utils import update_fp_status from lcm.pub.exceptions import NSL
CMException from lcm.pub.utils.jobutil import JobUtil logger = logging.getLogger(__name__) class CreateSfcWorker(Thread): def __init__(self, data): super(CreateSfcWorker, self).__init__() self.ns_inst_id = data["nsinstid"] self.ns_model_data = data["ns_model_data"] self.fp_id = da...
vincentbetro/NACA-SIM
imagescripts/plotfixEND1.py
Python
gpl-2.0
873
0.052692
#!/usr/bin/env python import os,sys import glob def mysystem(s): print(s) retval = os.system(s) return retval def main(): alphas = range(-8,9) orders = [1] machs = [0.55,0.65,0.75,0.85,0.95,1.05] #now, we need to recursively move everybody back for order in orders: f
or mach in machs: for alpha in alphas: result = '/home/vbetro/online_edu/images/order%d/mach%0.2f/alpha%+03d/naca0012_%d_%0.2f_%+03d_02.png'%(order,mach,alpha,order,mach,alpha); if not os.path.exists(result): mysystem('cp /home/vbetro/online_edu/images/order%d/...
r,mach,alpha,order,mach,alpha)); if __name__ == "__main__": main()
Hexxeh/libpebble
pebble/PblBuildCommand.py
Python
mit
10,418
0.008063
import logging import sh, os, subprocess import json import StringIO import traceback import sys import PblAnalytics from PblCommand import PblCommand from PblProjectCreator import requires_project_dir from LibPebblesCommand import (NoCompilerException, BuildErrorException, AppTooBigExc...
error occurred, we need to do some sleuthing to determine a # cause. This allows the caller to post more useful information to # analytics. We normally don't capture stdout and stderr using Poepn() # because you lose the nice color coding produced when the command # outputs to a termina...
if (retval): cmdArgs = cmdLine.spli
meteoswiss-mdr/monti-pytroll
scripts/demo_satpy_fog.py
Python
lgpl-3.0
13,803
0.012389
from __future__ import division from __future__ import print_function from PIL import Image from PIL import ImageFont from PIL import ImageDraw from PIL import ImageEnhance import nwcsaf import numpy as np from satpy import Scene, find_files_and_readers from datetime import datetime, timedelta from copy import deepc...
if not (sat in f): files_sat['seviri_l1b_hrit'].remove(f) continue if ("HRV" in f)
or ("VIS006" in f) or ("VIS008" in f) or ("IR_016" in f) or ("IR_039" in f): files_sat['seviri_l1b_hrit'].remove(f) continue if ("WV_062" in f) or ("WV_073" in f) or ("IR_097" in f) or ("IR_108" in f) or ("IR_134" in f): files_sat['seviri_l1b_hrit'].remove(f) co...
kshedstrom/pyroms
pyroms_toolbox/pyroms_toolbox/PCA.py
Python
bsd-3-clause
7,237
0.00608
import numpy as np from matplotlib.mlab import psd from scipy.signal import get_window class PCA(object): def __init__(self, dataset, algorithm='svd'): """ This class carries out Principal Component Analysis on dataset. Arguments: 'dataset' -- NumPy array containing the fie...
first dataset = center(dataset) or dataset = standardize(dataset) with the functions provided. """ self.dataset = dataset self.packedata, self.mask = self.pack(self.dataset) if algorithm == 'svd': self.packedEOFs, self.ECs, sel
f.L = self._pca_svd(self.packedata) elif algorithm == 'eig': self.packedEOFs, self.ECs, self.L = self._pca_eig(self.packedata) else: raise RuntimeError('Algorithm %s not known.'%algorithm) self.EOFs = self.unpack(self.packedEOFs, self.mask) def GetEOFs(self): ...
loechel/lmu.contenttypes.polls
src/lmu/contenttypes/polls/content/poll.py
Python
gpl-2.0
9,277
0.00097
# -*- coding: utf-8 -*- from AccessControl import Unauthorized from plone.dexterity.content import Item #from plone.dexterity.content import Container from plone import api from plone.i18n.normalizer import idnormalizer from plone.i18n.normalizer import urlnormalizer from z3c.form.interfaces import IValidator from z3...
oll: %s', member_id, request.getURL()) if api.user.is_anonymous() or member_id == 'Anonymous User': member_id = request.get('HTTP_EDUPERSONPRINCIPALNAME') if member_id: member_id = member_id.split('@')[0].strip() if not member_id and request: poll_uid ...
tility.anonymous_vote_id()) request.response[cookie] = vote_id request.response.setCookie(cookie, vote_id, path='/', expires=expires) member_id = 'Anonymous-%s' % vote...
joelagnel/lisa
libs/utils/env.py
Python
apache-2.0
37,818
0.002538
# SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2015, ARM Limited and contributors. # # 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 # # ...
eanup all previous content from the output folder :type wipe: bool :param force_new: Create a new TestEnv object even if there is one available for this session. By default, TestEnv only create
s one object per session, use this to override this behaviour. :type force_new: bool """ _initialized = False def __init__(self, target_conf=None, test_conf=None, wipe=True, force_new=False): super(TestEnv, self).__init__() if self._initialized a...
hmoco/osf.io
tests/test_subjects.py
Python
apache-2.0
7,079
0.003249
# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError from nose.tools import * # flake8: noqa (PEP8 asserts) from modularodm.exceptions import NoResultsFound, ValidationValueError from tests.base import OsfTestCase from osf_tests.factories import SubjectFactory, PreprintFactory, PreprintProviderF...
self.one_level_root.save() self.parent_subj_0 = SubjectFactory(parent=self.root_subject) self.parent_subj_1 = SubjectFactory(parent=self.root_subject) self.two_level_parent = SubjectFactory(parent=self.two_level_root) self.outside_parent = SubjectFactory(parent=self.outside_roo...
elf.parent_subj_1.save() self.outside_parent.save() self.two_level_parent.save() self.child_subj_00 = SubjectFactory(parent=self.parent_subj_0) self.child_subj_01 = SubjectFactory(parent=self.parent_subj_0) self.child_subj_10 = SubjectFactory(parent=self.parent_subj_1) s...
taranjeet/EvalAI
apps/challenges/migrations/0023_upload_unique_random_filename.py
Python
bsd-3-clause
767
0.002608
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-02-16 17:16 from __future__ import unicode_literals import base.utils from django.db import migrations, models class
Migration(migrations.Migration): dependencies = [ ('challenges', '0022_challengephase_dataset_split'), ] operations = [ migrations.AlterField( model_name='challenge', name='evaluation_script', field=models.FileField(default=False, upload_to=base.utils.Ra...
challengephase', name='test_annotation', field=models.FileField(upload_to=base.utils.RandomFileName('test_annotations')), ), ]
simonlindblad/quizilito
build/funktionell-programmering.py
Python
mit
295
0.030508
# Uppgift 4 [str(i) for i in range(4)] # Uppgift 5 from math import sqrt
# square root list(filter(lambda x: sqrt(x).is_integer(), range(1000, 1200))) # Uppgift 6 >>> def make_decrementor(n): ... return lambda x: n - x ... >>> f = make_decrementor(42) >>> f(0) 42 >>> f(1) 4
1 >>> f(-3)
antoinecarme/sklearn2sql_heroku
tests/classification/iris/ws_iris_RidgeClassifier_oracle_code_gen.py
Python
bsd-3-clause
135
0.014815
from sklea
rn2sql_heroku.tests.classification import generic as class_gen class_gen.test_model("RidgeClassifier" , "iris" ,
"oracle")
lisroach/PyRESTCONF
rest_calls/tests/unit/test_xml_mock.py
Python
apache-2.0
2,194
0.000456
import unittest import requests import mock from rest_calls.xmlRestClient import XMLRestCalls username = 'admin' password = 'admin' ip = '127.0.0.1' port = 80 endpoint = 'Cisco-IOS-XR-ip-static-cfg:router-static' sm_url = '{scheme}://{ip}:{port}{basePath}/'.format( scheme='http', ip=ip, port...
f/data' ) url = sm_url + endpoint contents = '{test: test}' class XMLRestCallsCase(unittest.TestCase): def setUp(self): self.classObject = XMLRestCalls( ip, port, username, password ) def test__init__(self): """Does const...
s.update({ 'Accept': ','.join([ 'application/yang.data+xml', 'application/yang.errors+xml', ]), 'Content-Type': 'application/yang.data+xml', }) self.assertEqual(self.classObject._session.headers, ses...
DecisionSystemsGroup/DSGos
airootfs/usr/share/DSGos-Installer/DSGos_Installer/pacman/pacman_conf.py
Python
mit
7,754
0.000903
#!/usr/bin/env python3 # # pacman_conf.py # # Based on pyalpm code Copyright (C) 2011 Rémy Oudompheng <remy@archlinux.org> # Copyright © 2013-2015 DSGos # # This file is part of DSGos_Installer. # # DSGos_Installer is free software; you can redistribute it and/or modify # it under the terms of the GNU General Pub...
erver, SigLevel, Usage options if key in ('Server', 'SigLevel', 'Usage') and equal == '=': yield (current_section, key, value) else: raise InvalidSyntax(f.name, 'invalid k
ey for repository configuration', line) continue if equal == '=': if key in LIST_OPTIONS: for val in value.split(): yield (current_section, key, val) elif key in SINGLE_OPTIONS: yield (current_section, key, value) ...
anhstudios/swganh
data/scripts/templates/object/draft_schematic/droid/component/shared_chassis_droid_r2.py
Python
mit
461
0.047722
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/droid/component/shared_chassis_droid_r2.iff" result.attrib...
MODIFICATIONS #### #### END MODIFICATIONS #### return result
spicerack/sage
examples/custom_prompt/custom_prompt.py
Python
gpl-3.0
1,863
0.00161
from sage import prompt, ansi, player class CustomPromptRenderer(prompt.PromptRenderer): """ Override prompt.PromptRenderer """ def colorize_vital(self, value): """ Give us green, yellow, and red colored numbers for vitals depending on our percentage. """ if value >= 66: ...
'balance': self.render_balance(),
'stats': self.render_stats() } fstr = "%-[{health}%-%]h [{mana}%-%]m {willpower}%-%%w {endurance}%-%e {balance}|{stats}%0-" return ansi.strfcolor(fstr).format(**data) # set prompt.renderer to the instance of your own Prompt prompt.renderer = CustomPromptRenderer()
markperdue/havocbot
src/havocbot/pluginmanager.py
Python
mit
8,630
0.003013
from havocbot.common import catch_exceptions from havocbot.plugin import HavocBotPlugin import imp import logging import os logger = logging.getLogger(__name__) class StatefulPlugin: def __init__(self, havocbot, name, path): self.path = path self.name = name self.handler = None se...
http://peak.telecommunity.com/DevCenter/PkgResources#resource-extraction import pkg_resources core_package = 'havocbot.core' resources_list = pkg_resources.resource_listdir(core_package, '') for f in resources_list: # Remove file extension name, ext = os.path.sp...
(f) if ext == '.py': # TODO - Optimize this. resource_filename is slow resource_filename = pkg_resources.resource_filename(core_package, f) plugin = load_plugin(havocbot, name, resource_filename) if plugin and isinstance(plugin.handler, Havoc...
anaoprea/iDibo
tests/iDibo_tests.py
Python
gpl-3.0
148
0.027027
from
nose.tools import * import iDibo def setup(): print "SETUP!" def teardown(): print "TEAR DOWN!" def test_
basic(): print "I RAN!"
equitania/myodoo-addons-v10
eq_project/models/__init__.py
Python
agpl-3.0
1,068
0
# -*- coding: utf-8 -*- ############################################################################## # # Odoo Addon, Open Source Management Solution # Copyright (C) 2014-now Equitania Software GmbH(<http://www.equitania.de>). # # This program is free software: you can redistribute it and/or modify # it un...
U Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of #
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ########################################...
tigerlinux/tigerlinux-extra-recipes
recipes/misc/python-learning/CORE/0031-module-packages-and-docs/package02/mymodule.py
Python
gpl-3.0
394
0.002538
#!/usr/bin/env python # # B
y Reynaldo R. Martinez P. # Sept 15, 2016 # TigerLinux AT Gmail DOT Com # Modules - Module file with a function - package version # # # Second function, sum all items in a list def sumallitems(inputlist): result = inputlist[0] for number in inputlist[1:]: res
ult = result + number return result # And, declare another variables variable2 = 23
DarthThanatos/citySimNG
citySimNGView/viewmodel/GameMenuViewModel.py
Python
apache-2.0
583
0.003431
from wx import wx from Converter import Converter class GameMenuViewModel(object): def __init__
(self, viewSetter): self.viewSetter = viewSetter def displayGameMenu(self): wx.CallAfter(self.viewSetter.setView, "GameMenu") def animateCurrentPrices(self, currentPricesJavaMap): wx.Call
After( self.viewSetter.getView("GameMenu").animateCurrentPrices, Converter(self.viewSetter.gateway).convertJavaMapToDict(currentPricesJavaMap) ) class Java: implements = ["py4jmediator.ViewModel$GameMenuViewModel"]
mattvonrocketstein/ymir
tests/test_service.py
Python
mit
1,173
0.000853
# -*- coding: utf-8 -*- """ """ import pytest import mock from peak.util.imports import lazyModule from ymir import api from ymir.data import BadProvisionInstruction import tests.common as test_common yservice = lazyModule('ymir.service') @test_common.mock_aws def test_load_skeleton_service(): service = api.lo...
AbstractService) return service def test_ssh_config_string_prop(): service = test_common.mock_service() #assert isinstance(service._ssh_config_string, basestring) def test_service_has_important_callables(): service = test_load_skeleton_service() for x in service._fabric_commands: assert ...
rovisioner(): with test_common.demo_service() as ctx: service = ctx.get_service() provisioner_name, provision_instruction = 'foobar', 'baz' with pytest.raises(BadProvisionInstruction): service._run_provisioner(provisioner_name, provision_instruction)
stuxcrystal/yuuno
yuuno_ipython/ipython/apps/feature.py
Python
lgpl-3.0
1,634
0.000612
# -*- encoding: utf-8 -*- # Yuuno - IPython + VapourSynth # Copyright (C) 2017,2018 StuxCrystal (Roland Netzsch <stuxcrystal@encode.moe>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation...
without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. from yuuno impor...
ine_magic, magics_class from IPython.display import display @magics_class class AppDrawer(Magics): def app_magic(self, app, line): local_ns = {'__app': app} return eval(f"__app({line})", self.shell.user_ns, local_ns) @line_magic def preview(self, line): from yuuno_ipython.ipython...
bacaldwell/ironic
ironic/tests/unit/common/test_driver_factory.py
Python
apache-2.0
7,434
0
# 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,...
interface='flat') node = obj_utils.create_test_node(self.context, driver='fake') with task_manager.acquire(self.context, node.id) as task: extension_mgr = factory._extension_manager self.assertIn('flat', extension_mgr) self.assertIn('noop', extension_mgr) ...
twork) def test_build_driver_for_task_default_is_flat(self): # flat and noop network interfaces are enabled in base test case factory = driver_factory.NetworkInterfaceFactory node = obj_utils.create_test_node(self.context, driver='fake') with task_manager.acquire(self.context, node....
taion/flask-jsonapiview
flask_resty/pagination.py
Python
mit
23,769
0.000252
import base64 from dataclasses import dataclass from typing import Any, List, Tuple, Union import flask import sqlalchemy as sa from marshmallow import ValidationError, fields from flask_resty.sorting import FieldOrderings, FieldSortingBase from flask_resty.view import ModelView from . import meta from .exceptions i...
_page`` property. Subclasses must implement :py:meth:`get_limit` to provide maximum number of returned items. """ def get_page(self, query, view) -> Li
st: limit = self.get_limit() if limit is not None: query = query.limit(limit + 1) items = query.all() if limit is not None and len(items) > limit: has_next_page = True items = items[:limit] else: has_next_page = False met...
torsade/mimk
cfg/all.py
Python
mit
127
0
# mimk target configration file # # Target:
all from .helloworld impo
rt helloworld, src_files targets = [ helloworld ]
elena/django
django/contrib/gis/db/backends/mysql/features.py
Python
bsd-3-clause
1,481
0.00135
from django.contrib.gis.db.backends.base.features import BaseSpatialFeatures from django.db.backends.mysql.features import ( DatabaseFeatures as MySQLDatabaseFeatures, ) from django.utils.functional import cached_property class DatabaseFeatures(BaseSpatialFeatures, MySQLDatabaseFeatures): has_spatialrefsys_ta...
upports_geometry_field_unique_
index(self): # Not supported in MySQL since https://dev.mysql.com/worklog/task/?id=11808 return self.connection.mysql_is_mariadb @cached_property def django_test_skips(self): skips = super().django_test_skips if ( not self.connection.mysql_is_mariadb and ...
bearstech/ansible
lib/ansible/modules/notification/irc.py
Python
gpl-3.0
9,058
0.003974
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Jan-Piet Mens <jpmens () gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.0', ...
" ] version_added: "2.0" # informational: requirements for nodes requirements: [ socket ] author: - '"Jan-Piet Mens (@jpmens)"' - '"Matt Martz (@sivel)"' ''' EXAMPLES = ''' - irc: server: irc.example.net channel: #t1 msg: Hello world - local_action: module: irc port: 6669 server: ...
r: irc.example.net channel: #t1 nick_to: - nick1 - nick2 msg: 'All finished at {{ ansible_date_time.iso8601 }}' color: red nick: ansibleIRC ''' # =========================================== # IRC module support methods. # import re import socket import ssl import time import traceback ...
mrquim/mrquimrepo
script.module.exodus/lib/resources/lib/sources/en/to_be_fixed/sitedown/icefilmsis.py
Python
gpl-2.0
5,058
0.008501
# -*- coding: utf-8 -*- ''' Exodus Add-on This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This progra...
host = client.
replaceHTMLCodes(host) host = host.encode('utf-8') sources.append({ 'source': host, 'quality': 'SD', 'language': 'en', 'url': url.replac...
alephu5/Soundbyte
environment/lib/python3.3/site-packages/pandas/computation/align.py
Python
gpl-3.0
7,849
0
"""Core eval alignment algorithms """ import warnings from functools import partial, wraps from pandas.compat import zip, range import numpy as np import pandas as pd from pandas import compat import pandas.core.common as com def _align_core_single_unary_op(term): if isinstance(term.value, np.ndarray): ...
axes[ax] = axes[ax].join(itm, how='outer') for i, ndim in compat.iteritems(ndims): for axis, items in zip(range(ndim), axes): ti = terms[i].value if hasattr(ti, 'reindex_axis'): transpose = isinstance(ti, pd.Series) and naxes > 1 rein
dexer = axes[naxes - 1] if transpose else items term_axis_size = len(ti.axes[axis]) reindexer_size = len(reindexer) ordm = np.log10(abs(reindexer_size - term_axis_size)) if ordm >= 1 and reindexer_size >= 10000: warnings.warn('Alignme...
zorroblue/scikit-learn
sklearn/utils/estimator_checks.py
Python
bsd-3-clause
71,139
0.000098
from __future__ import print_function import types import warnings import sys import traceback import pickle from copy import deepcopy import numpy as np from scipy import sparse from scipy.stats import rankdata import struct from sklearn.externals.six.moves import zip from sklearn.externals.joblib import hash, Memor...
ort assert_raises_regex from sklearn.utils.testing import assert_raise_message from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_not_equal from sklearn.utils.testing import assert_true from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_in from s...
n.utils.testing import assert_allclose_dense_sparse from sklearn.utils.testing import assert_warns_message from sklearn.utils.testing import META_ESTIMATORS from sklearn.utils.testing import set_random_state from sklearn.utils.testing import assert_greater from sklearn.utils.testing import assert_greater_equal from skl...
dropbox/changes
migrations/versions/51775a13339d_patch_hash_column.py
Python
apache-2.0
428
0.007009
"""patch hash column Revision ID: 51775a13339d Revises: 187eade64ef0 Create Date: 2016-06-17 13:46:10.921685 """ # revision identifiers, used by Alembic. revision = '5177
5a13339d' down_revision = '187eade64ef0' from alembic import op import sqlalchemy as sa def upgrade(): op.add_column('revision', sa.Column('patch_hash', sa.String(40), nullable=True
)) def downgrade(): op.drop_column('revision', 'patch_hash')
iAddz/allianceauth
groupmanagement/models.py
Python
gpl-2.0
4,177
0.004549
from __future__ import unicode_literals from django.utils.encoding import python_2_unicode_compatible from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import Group from django.db.models.signals import post_save from django.dispatch import receiver from eveonline....
but can still join with the correct link.") open = models.BooleanField(default=False, help_text="Group is open and users will be
automatically added upon request. <br>" "If the group is not open users will need their request manually approved.") public = models.BooleanField(default=False, help_text="Group is public. Any registered user is able to join this group, with...
PythonScientists/Shape
main/ext/__init__.py
Python
apache-2.0
431
0.021792
#-*-coding:utf-8-*- from flask_bcrypt import Bcrypt bcrypt = Bcrypt() from flask_bootstrap import Bootstrap bootstrap = Bootstrap() from flask_mail import Mail mail=Mail() from flask_login import LoginManage
r login_manager = LoginManager() login_
manager.login_view="auth.login_index" login_manager.session_protection="strong" login_manager.login_message="登录以获得更多功能" login_manager.login_message_category="info"
SouravJaiswal/saber
bots/bot3.py
Python
gpl-2.0
806
0.031017
#!/usr/bin/env python from Quantum import * import random class myBot(): """ rotate-cipher bot """ def __init__(self): self.name = "Rota
te Cipher Bot" # initialise any persistent data structures (if needed) def do_setup(self, game): self.delta = 26 - game.number_of_words self.turn = game.turn def do_turn(self, game): for i in range(1, random.randint(1, game.number_of_words)): r, c = random.randint
(0, game.number_of_words-1), random.randint(0, game.number_of_words-1) new_ch = self.rotate(game.map[r][c]) # print(r, c, new_ch, file=sys.stderr) game.edit(r, c, new_ch) def rotate(self, ch): return chr(ord('a') + (ord(ch) - ord('a') + self.delta) % 26) if __name__ == '__main__': try: ServerStack.laun...
cloud9ers/gurumate
environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py
Python
lgpl-3.0
6,316
0.003483
"""Windows-specific implementation of process utilities. This file is only meant to be imported by process.py, not by end-users. """ #----------------------------------------------------------------------------- # Copyright (C) 2010-2011 The IPython Development Team # # Distributed under the terms of the BSD Licen...
idUNCPath() as path: if path is not None: cmd = '"pushd %s &&"%s' % (path, cmd) os.system(cmd) """ def __enter__(self): self.path = os.getcwdu() self.is_unc_path = self.path.startswith(r"\\") if self.is_unc_path: # change to c drive (as...
NC addresses) os.chdir("C:") return self.path else: # We return None to signal that there was no change in the working # directory return None def __exit__(self, exc_type, exc_value, traceback): if self.is_unc_path: os.chdir(se...
Fendoe/open-hackathon-o
open-hackathon-client/src/client/views/route_user.py
Python
mit
1,510
0.005964
# -*- coding: utf-8 -*- """ Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd.  All rights reserved. The MIT License (MIT) 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, includi
ng without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copie...
ligo-cbc/pycbc
examples/waveform/add_waveform.py
Python
gpl-3.0
1,513
0.002644
def test_waveform(**args): import numpy from pycbc.types import TimeSeries flow = args['f_lower'] # Required parameter dt = args['delta_t'] # Required parameter fpeak = args['fpeak'] # A new parameter for my model t = numpy.arange(0, 10, dt) f = t/t.max() * (fpeak - flow) + flow a =...
model, select 'frequency' # instead of 'time' to this function call. pycbc.waveform.add_custom_waveform('test', test_waveform, 'time', force=True) # Let's plot what our new waveform looks like hp, hc = pycbc.waveform.get_td_waveform(approximant="test", f_lower=20, fpeak=50, ...
e_times, hp) pylab.xlabel('Time (s)') pylab.figure(1) hf = hp.to_frequencyseries() pylab.plot(hf.sample_frequencies, hf.real()) pylab.xlabel('Frequency (Hz)') pylab.xscale('log') pylab.xlim(20, 100) pylab.show()
infobloxopen/infoblox-netmri
infoblox_netmri/api/broker/v3_8_0/subnet_broker.py
Python
apache-2.0
68,120
0.002085
from ..broker import Broker class SubnetBroker(Broker): controller = "subnets" def show(self, **kwargs): """Shows the details for the specified subnet. **Inputs** | ``api version min:`` None | ``api version max:`` None | ``required:`` True ...
etLastIPNumeric, SubnetNetMaskDotte
d, SubnetNetMaskNumeric, SubnetCIDR, SubnetLocation, VlanID, VirtualNetworkID, RouteTimestamp, SubnetSdnInd. :type sort: Array of String | ``api version min:`` None | ``api version max:`` None | ``required:`` False | ``default:`` asc :param...
jiyfeng/DPLP
resources/bcreader.py
Python
mit
565
0.00885
## bcreader.py ## Author: Yangfeng Ji ## Date: 01-27-2015 ## Time-stamp: <yangfeng 01/30/2015 22:16:26> from cPickle import dump import gzip def reader(fname): bcvocab = {} with open(fname, 'r') as fin: for line in
fin: items = line.strip().split('\t') bcvocab[items[1]] = items[0] return bcvocab def savevocab(vocab, fname): with gzip.open(fname, 'w') as fout: dump(vocab, fout) print 'Done' if __name__ == '__main__': vocab = reader("./
bc-3200.txt") savevocab(vocab, "./bc3200.pickle.gz")
sajaldebnath/vrops-metric-collection
metric-collection.py
Python
mit
4,525
0.008177
# !/usr/bin python """ # # data-collect.py contain the python program to gather Metrics from vROps. Before you run this script # set-config.py should be run once to set the environment # Author Sajal Debnath <sdebnath@vmware.com> # """ # Importing the Modules import nagini import requests #import pprint import json ...
s.packages.urllib3.exceptions import InsecureRequestWarning # Function to get the absolute path from where the script is being run def get_script_path(): return os.path.dirname(os.path.realpath(sys.argv[0])) # Function to get the metric data def get_metric_data(
resourceknd,adapter,key,sampleno ): outdata = [] # It's going to store the final JSON data # Gettting a list of resources which matches the criteria or resourceKind and adapterKind for resource in vrops.get_resources(resourceKind=resourceknd, adapterKindKey=adapter)['resourceList']: allstat = {} # ...
rueckstiess/configparser
mconfcheck.py
Python
apache-2.0
9,553
0.011724
from pymongo import MongoClient, ASCENDING from bson.min_key import MinKey from bson.max_key import MaxKey from bson import ObjectId, Timestamp from chunk import Chunk from chunk_distribution import ChunkDistribution from config_parser import ConfigParser from copy import copy, deepcopy from dateutil import parser f...
import time from mtools.util.cmdlinetool import BaseCmdLineTool def all_equal(l): return all( it == l[0] for it in l ) def argmax(l): return max(enumerate(l), key=itemgetter(1))[0] class MConfCheckTool(BaseCmdLineTool): def __init__(self): """ Constructor: add description to argparser. """ ...
ription = 'Performs a health check on config servers and compares them for inconsistencies.' self.argparser.add_argument('config', action='store', nargs='*', metavar='URI', default=['mongodb://localhost:27017/config'], help='provide uri(s) to config server(s), default is mongodb://localhost:27017/config') ...
MicBrain/Scheme-Interpreter
scheme_primitives.py
Python
apache-2.0
27,263
0.004035
"""This module implements the primitives of the Scheme language.""" import math import operator import sys import numbers import re try: import turtle except: print("warning: could not import the turtle module.", file=sys.stderr) ############################# # Errors and Error Checking # ###################...
rmine whether some value is to be treated as meaning 'true'. As a result, any SchemeValue that Scheme considers to represent true also means true to Python. It is therefore unnecessary in Python to write things like 'if EXPRESSION is not scheme_false: ...'""" return True def print_...
rint' procedure.""" return str(self) # The following methods return SchemeValues. Those ending in 'p' (for # 'predicate') return scheme_false to mean 'false', and some other # SchemeValue (often scheme_true) to mean 'true'. def booleanp(self): return scheme_false def notp(self): ...
jm-/zeallect
zeallect/proxy.py
Python
apache-2.0
5,351
0.000934
import logging from sys import exc_info from socket import socket, AF_INET, SOCK_STREAM, SOCK_DGRAM, SHUT_RD, SOL_SOCKET, SO_REUSEADDR, error as socketError from traceback import format_exception from struct import Struct from .common import * from .models import * from .exceptions import * class ClientHost(): ...
remotedets) socketdict[newsock] = newservsock socketdict[newservsock] = newsock host = details[0]
if host not in self.hostmap: clienthost = ClientHost(host) else: clienthost = self.hostmap[host] clienthost.active += 1 self.hostmap[newsock] = clienthost self.hostmap[newservsock] = cli...
robcz/tangosnake
TangoServices.py
Python
apache-2.0
2,895
0.003109
#!/usr/bin/env python import boto3 import sys import json import logging from botocore.exceptions import ClientError from CoinCollection import ValueRecord logger = logging.getLogger("tango") logger.setLevel(logging.DEBUG) class Cache(): def stash(self, key, record): logger.debug("Stash request for: " + ...
was: " + rec)
return ValueRecord(key,'USD',0.0).fromJSON(rec) except (KeyError) as kerr: return None def expired(self, key): expired = True try: logger.debug("Expiration check for: " + key) expired = self.retrieve(key).expired() except (ValueEr...
unitedstates/congress-legislators
scripts/cspan.py
Python
cc0-1.0
760
0.006579
#!/usr/bin/env python # Update current cspan IDs using NYT Congress API. import json, urllib.request, urllib.parse, urllib.error from utils import load_data, save_data def run(): # load in current members y = load_data("legislators-cur
rent.yaml") for m in y: # retrieve C-SPAN id, if available, from ProPublica API # TODO: use utils.download here response = urllib.request.urlopen("https://projects.propublica.org/represent/api/v1/members/%s.json" % m['id']['bioguide']).read() j = json.loads(response.decode("utf8")) ...
['results'][0]['cspan_id'] if not cspan == '': m['id']['cspan'] = int(cspan) save_data(y, "legislators-current.yaml") if __name__ == '__main__': run()
JulyKikuAkita/PythonPrac
cs15211/AddOneRowToTree.py
Python
apache-2.0
3,694
0.009475
__source__ = 'https://leetcode.com/problems/add-one-row-to-tree/#/description' # Time: O(n) # Space: O(n) # # Description: 623. Add One Row to Tree # # Given the root of a binary tree, then value v and depth d, # you need to add a row of nodes with value v at the given depth d. The root node is at depth 1. # # The add...
gs Tree import unittest class Solution(object): pass # your function here class TestMethods(unittest.TestCase): def test_Local(self): self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() Java = ''' #Thought: https://leetcode.com/problems/add-one-row-to-tree/solution/ // 1. DFS:...
a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ #4ms 100% class Solution { public TreeNode addOneRow(TreeNode root, int v, int d) { if (d == 1) { TreeNode newRoot = new TreeNode(v); newRoot.left = root; ...
nkgilley/home-assistant
tests/components/group/test_init.py
Python
apache-2.0
19,157
0.001305
"""The tests for the Group components.""" # pylint: disable=protected-access from collections import OrderedDict import unittest import homeassistant.components.group as group from homeassistant.const import ( ATTR_ASSUMED_STATE, ATTR_FRIENDLY_NAME, ATTR_ICON, STATE_HOME, STATE_NOT_HOME, STATE_...
"" self.hass.states.set("light.Bowl", STATE_ON) self.hass.states.set("light.Ceiling", STATE_OFF)
test_group = group.Group.create_group( self.hass, "init_group", ["light.Bowl", "light.Ceiling"], False, mode=True ) # Turn one on self.hass.states.set("light.Ceiling", STATE_ON) self.hass.block_till_done() group_state = self.hass.states.get(test_group.entit...
scampion/pimpy
pimpy/image/__init__.py
Python
agpl-3.0
4,245
0.01437
#-*- coding:utf-8 -*- """ pimpy.image Image class object .. module:: image :synopsis: Tools for image description :platform: Unix, Mac, Windows .. moduleauthor:: Sebastien Campion <sebastien.campion@inria.fr> """ # pimpy # Copyright (C) 2010 Sebastien Campion <sebastien.campion@inria.fr> # # pimpy is free s...
reFactory.list() def save(self,outfile): u""" sa
ve frame in a file :param filename: file path :type: string """ self.log.debug("Save image to %s" % outfile) self.get_pil_object().save(outfile) def load(self,infile): u""" load frame from a file :param filename: file path :type: string ...
squidsoup/snapcraft
snapcraft/internal/lifecycle.py
Python
gpl-3.0
20,279
0
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright (C) 2015, 2016 Canonical Ltd # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in...
ng.getLogger(__name__) _TEMPLATE_YAML = """name: my-snap-name # you probably want to 'snapcraft register <name>' version: '0.1' # just for humans, typically '1.2+git' or '1.3.2' summary: Single-line elevator pitch for your amazing snap # 79 char long summary description: | This is my-snap's description. You have a ...
l the most important story about your snap. Keep it under 100 words though, we live in tweetspace and your description wants to look good in the snap store. grade: devel # must be 'stable' to release into candidate/stable channels confinement: devmode # use 'strict' once you have the right plugs and slots parts...
auto-mat/klub
apps/smmapdfs_edit/migrations/0002_auto_20191121_1640.py
Python
gpl-3.0
1,078
0.002783
# Generated by Django 2.2.7 on 2019-11-21 15:40 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('smmapdfs_edit', '0001_initial'), ] operations = [ migrations.AlterField( model_name='pdfsandwic...
etion.CASCADE, to='aklub.AdministrativeUnit'), ), migrations.AlterField( model_name='pdfsandwichfontconnector', name='administrative_unit', field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aklub.AdministrativeUnit'), ...
name='administrative_unit', field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='aklub.AdministrativeUnit'), ), ]
adalekin/xparse
xparse/factory.py
Python
gpl-3.0
6,048
0.008433
__author__ = 'adalekin' import re import requests import hashlib from PIL import Image, ImageOps from cStringIO import StringIO from xparse.parser import * from xparse.utils import get_in_dict, set_in_dict class URLExtractor(object): def __init__(self, regex, parser_class): self.regex = re.compile(rege...
proxies={'http': self.proxy} if self.proxy else None, ver
ify=False) orig_image = Image.open(StringIO(r.content)) orig_image, orig_buffer = self._convert_image(orig_image) self.storage.save(result["original"], orig_buffer) for thumb_id, thumb_params in self.IMAGE_THUMBS.iteritems(): if isinstance(thumb_params, dict): ...
ajessup/appstart
setup.py
Python
apache-2.0
2,381
0
# Copyright 2015 Google 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 required by applicable law or a...
tuptools.find_packages(exclude
='tests'), package_data={'appstart.devappserver_init': ['Dockerfile', 'das.sh'], 'appstart.pinger': ['Dockerfile'], 'appstart.sandbox': ['app.yaml']}, install_requires=['docker-py'], entry_points={ 'console_scripts': [ 'appstart=appstart.cli.start_scri...
zhuyue1314/simuvex
simuvex/procedures/libc___so___6/memcpy.py
Python
bsd-2-clause
1,566
0.006386
import simu
vex from simuvex.s_type import SimTypeTop, SimTypeLength import logging l =
logging.getLogger("simuvex.procedures.libc.memcpy") class memcpy(simuvex.SimProcedure): #pylint:disable=arguments-differ def run(self, dst_addr, src_addr, limit): # TODO: look into smarter types here self.argument_types = {0: self.ty_ptr(SimTypeTop()), 1: self.t...
Akitora/newsmail
newsmail_feed.py
Python
mit
1,279
0.021892
# -*- coding: utf-8 -*- import feedparser feedparser.PREFERRED_XML_PARSERS.remove('drv_libxml2') import os.path def feed(rssurl): d = feedparser.parse(rssurl) strings = [d.feed.title + "\n"] for entry in d['entries']: title = entry.title link = entry.link strings.append(title) ...
pen(rssurl.replace("/","_") + ".dat","r+",encoding = "UTF-8") strings2 = [d.feed.title + "\n"] main_subject = "" for row in f2: main_subject = row for entry in d['entries']: title = entry.title link = entry.link if (title == main_subject): break stri...
= open(rssurl.replace("/","_") + ".dat","w",encoding = "UTF-8") f.write(strings[1]) f.close() f2.close() #print(ret) return ret + "\n\n" if __name__ == '__main__': rssurl = 'http://www.dlsite.com/home/rss/=/channel/news_maniax' feed(rssurl)
ElchinValiyev/GameAI
Project_3/bayesian_imitation_learning/task3.py
Python
mit
2,142
0.006536
from __future__ import division import random import matplotlib.pyplot as plt from pylab import figure, axes, pie, titl
e, show from mpl_toolkits.mplot3d import Axes3D import csv import math import numpy as np import matplotlib.cm as cm c
lass Neuron: def __init__(self, x, y, z): self.x = x self.y = y self.z = z class SOM: list = [] def __init__(self, card): for i in range (0,card): self.list.append(Neuron(random.randint(0,1000), random.randint(0, 2000), random.randint(0, 100))) def calcul...
artPlusPlus/dijon
tests/test_sequence_compare.py
Python
mit
5,916
0
import dijon def test_compare_sequence_no_difference(): source_data = ['a', 'b', 'c'] target_data = ['a', 'b', 'c'] diff_graph = dijon.compare(source_data, target_data) diff_nodes = [n for n in diff_graph.iter_nodes(differences=True)] assert len(diff_nodes) == 0 def test_compare_sequence_append...
temModification) assert difference.full_path == ('root', (0, 1)) assert difference.source.full_path == ('root', (0, 1), 0) assert difference.source.data == 'a' assert difference.target.full_path == ('root', (0, 1), 1) assert difference.target.data == 'a' difference = diff_nodes[1] assert is...
(difference, dijon.SequenceItemModification) assert difference.full_path == ('root', (1, 2)) assert difference.source.full_path == ('root', (1, 2), 1) assert difference.source.data == 'b' assert difference.target.full_path == ('root', (1, 2), 2) assert difference.target.data == 'b' difference =...
kwantopia/shoppley-migrate
shoppley.com/shoppley/apps/buxfer/models.py
Python
mit
14,855
0.00754
from django.db import models from django.contrib.auth.models import User import time from sorl.thumbnail import ImageField, get_thumbnail # Create your models here. class Category(models.Model): name = models.CharField(max_length=128) related_categories = models.ManyToManyField('self') class Account(models.Model): ...
'timestamp': str(time.mktime(self.purchase_date.timetuple())) } if experiment == 2: detail['user'] = self.user.get_json(level=0) return detail def __unicode__(self): return str(self.memo) + " at " + str(self.purchase_date) class Receipt(mo...
l): txn = models.OneToOneField(Transaction) detail = models.TextField(blank=True) NOT_RATED = 0 POOR = 1 FAIR = 2 AVERAGE = 3 GOOD = 4 EXCELLENT = 5 RATING_CHOICES = ( (NOT_RATED, 'Not Rated'), (POOR, 'Poor'), (FAIR, 'Fair'), (AVERAGE, 'Average'), ...
woome/multidb
setup.py
Python
bsd-3-clause
1,052
0.000951
from setuptools import setup packages = ['multidb.' + p for p in ['replication', 'replication.management', 'replication.management.commands', 'feature', 'feature.management', 'feature.management.commands', 'backend', ]] + ['multidb'] setup( name='mul...
/woome/multidb/tarball/master", packages=packages, install_requires=['psycopg2', 'django'], platforms=['any'], #keywords=['asynchronous', 'queue', 'task queue'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU...
e (GPL)', 'Operating System :: POSIX', 'Programming Language :: Python', ], )
dashpay/dash
test/functional/feature_proxy.py
Python
mit
8,314
0.003849
#!/usr/bin/env python3 # Copyright (c) 2015-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test dashd with different proxy configuration. Test plan: - Start dashd's with different proxy configu...
odes[2], [self.serv2, self.serv2, self.serv2,
self.serv2], True) # Check that credentials as used for -proxyrandomize connections are unique credentials = set((x.username,x.password) for x in rv) assert_equal(len(credentials), len(rv)) if self.have_ipv6: # proxy on IPv6 localhost self.node_test(self.nodes[3]...
BoboTiG/python-mss
mss/factory.py
Python
mit
1,032
0
""" This is part of the MSS Python's module. Source: https://github.com/BoboTiG/python-mss """ import platform from typing import TYPE_CHECKING from .exception import ScreenShotError if TYPE_CHECKING: from typing import Any # noqa from .base import MSSBase # noqa def mss(**kwargs): # type: (Any) ->...
nce. It detects the platform we are running on
and chooses the most adapted mss_class to take screenshots. It then proxies its arguments to the class for instantiation. """ # pylint: disable=import-outside-toplevel os_ = platform.system().lower() if os_ == "darwin": from . import darwin return darw...
apehua/pilas
pilasengine/interprete/test_lanas.py
Python
lgpl-3.0
271
0
# -*- encoding: utf-8 -*- # # Inicia lanas para realizar una prueba
# rápida. import sys from PyQt4 import QtGui import lanas app = QtGui.QApplication(sys.argv) widget = lanas.WidgetLanas(scope={"lanas
": lanas}) widget.show() widget.raise_() sys.exit(app.exec_())
bmess/riak-python-client
riak/tests/test_search.py
Python
apache-2.0
7,512
0
# -*- coding: utf-8 -*- """ Copyright 2015 Basho Technologies, Inc. This file is provided to you 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 require...
rch_bucket). search_enabled())
bucket.enable_search() self.assertTrue(self.create_client(). bucket(self.search_bucket). search_enabled()) @unittest.skipIf(SKIP_SEARCH, 'SKIP_SEARCH is defined') def test_disable_search_commit_hook(self): bucket = self.client.bucket(self...
iradicek/clara
tests/test_matching.py
Python
gpl-3.0
2,125
0.005647
import pytest from utils import get_full_data_filename, parse_file from clara.interpreter import getlanginter from clara.matching import Matching from clara.parser import getlangparser ## Matching helper functions: def matching_helper(f1, f2, lang, ins=None, args=None, entryfnc="main", datadir=...
: """ Tests whether the C files `f1` and `f2` match with the inputs `ins`. `should_match` indicates whether the files should match. """ matching_test_helper(f1, f2, 'c', should_match, ins=ins) ## Python matching tests: def test_examples(): args=[[[4.5]], [[1.0,3.0,5.5]]] matching_test_hel...
ir="../examples", entryfnc="computeDeriv") matching_test_helper('c1.py', 'c3.py', 'py', False, args=args, datadir="../examples", entryfnc="computeDeriv") matching_test_helper('c2.py', 'c3.py', 'py', False, args=args, datadir="../examples", entryfnc="computeDeriv...
mcdeaton13/Tax-Calculator
conda.recipe/run_test.py
Python
mit
15
0
impor
t taxca
lc
wkschwartz/django
tests/auth_tests/test_models.py
Python
bsd-3-clause
21,579
0.00102
from unittest import mock from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.hashers import get_hasher from django.contrib.auth....
rmalize_email(r'Abc\@DEF@EXAMPLE.com') self.assertEqual(returned, r'Abc\@DEF@example.com') def test_create_user_email_domain_normalize(self): returned = UserManager.normalize
_email('normal@DOMAIN.COM') self.assertEqual(returned, 'normal@domain.com') def test_create_user_email_domain_normalize_with_whitespace(self): returned = UserManager.normalize_email(r'email\ with_whitespace@D.COM') self.assertEqual(returned, r'email\ with_whitespace@d.com') def test_em...
tombstone/models
official/benchmark/transformer_benchmark.py
Python
apache-2.0
29,410
0.00221
# Copyright 2019 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...
Keras benchmark and accuracy tests.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from absl import flags import tensorflow as tf from official.benchmark import benchmark_wrappers from official.benchmark import owner_utils from off...
er import transformer_main as transformer_main from official.utils.flags import core as flags_core TRANSFORMER_EN2DE_DATA_DIR_NAME = 'wmt32k-en2de-official' EN2DE_2014_BLEU_DATA_DIR_NAME = 'newstest2014' FLAGS = flags.FLAGS TMP_DIR = os.getenv('TMPDIR') class TransformerBenchmark(PerfZeroBenchmark): """Methods com...
lyusupov/SoftRF
software/firmware/source/libraries/arduino_midi_library/res/validator/midi.py
Python
gpl-3.0
4,067
0.00836
# -*- coding: utf-8 -*- import rtmidi import random # ------------------------------------------------------------------------------ class Midi: InvalidType = 0x00 # For notifying errors NoteOff = 0x80 # Note Off NoteOn = 0x90 # Note On AfterTouchPoly ...
-------------------------------------------------------------------------- def getAvailablePorts(self): return { 'input' : self.input.get_ports(), 'output': self.output.get_ports(), } def choosePorts(self): return { 'input' : self.choosePort(self.por...
('No MIDI ports available, bailing out.') return None if len(ports) == 1: return { 'id': 0, 'name': ports[0] } else: # Give a choice print('Multiple %s ports available, please make a choice:' % direction) ...
MauricioAcosta/Aprendiendo_Python
servidor/main.py
Python
gpl-3.0
182
0.016484
# -*- coding:
utf-8 -*- from flask import Flask; app = Flask(__name__) @app.route('/') def hello_wold(): return 'Hola, ingenieros :D' if __name__ == '__main__': a
pp.run()
TheAlgorithms/Python
data_structures/disjoint_set/disjoint_set.py
Python
mit
1,913
0
""" Disjoint set. Reference: https://en.wikipedia.org/wiki/Disjoint-set_data_structure """ class Node: def __init__(self, data: int) -> None: self.data = data self.rank: int self.parent: Node def make_set(x: Node) -> None: """ Make x as a set. """ ...
"" Return the parent of x """ if x != x.parent:
x.parent = find_set(x.parent) return x.parent def find_python_set(node: Node) -> set: """ Return a Python Standard Library set that contains i. """ sets = ({0, 1, 2}, {3, 4, 5}) for s in sets: if node.data in s: return s raise ValueError(f"{node.data} is no...
emlyn/python-osc
pythonosc/parsing/ntp.py
Python
unlicense
1,072
0.002799
"""Parsing and conversion of NTP dates contained in datagrams.""" import datetime import struct import time # 63 zero bits followed by a one in the least signifigant bit is a special # case meaning "immediately." IMMEDIATELY = struct.pack('>q', 1) # From NTP lib. _SYSTEM_EPOCH = datetime.date(*time.gmtime(0)[0:3]) ...
ef ntp_to_system_time(date): """Convert a NTP time to system time. System time is reprensented by seconds since the epoch in UTC. """ return date - _NTP_DELTA def system_time_to_ntp(date): """Convert a system time to a NTP time datagram. System time is reprensented by seconds since the epoch...
ve)) num_secs, fraction = str(ntp).split('.') return struct.pack('>I', int(num_secs)) + struct.pack('>I', int(fraction))
schukinp/python_training
model/contact.py
Python
apache-2.0
1,233
0.008921
from sys import maxsize class Contact: def __init__(self, firstname=None, lastname=None, homephone=None, nickname=None, mobilephone=None, workphone=None, email=None, email2=None, email3=None, fax=None, id=None, address=None, all_phones_from_home_page=None, all_emails_fro
m_home_page=None): self.firstname = firstname self.lastname = lastname self.address = address self.nickname = nickname self.homephone = homephone self.mobilephone = mobilephone self.workphone = workphone self
.fax = fax self.email = email self.email2 = email2 self.email3 = email3 self.id = id self.all_phones_from_home_page=all_phones_from_home_page self.all_emails_from_home_page=all_emails_from_home_page def __repr__(self): return "%s:%s:%s" % (self.id, self.last...
mattrenquist/fabric
test/test_operations.py
Python
gpl-2.0
57
0.017544
def
setUp(self): pass def test_stuff(self): pass
apache/libcloud
libcloud/compute/drivers/ktucloud.py
Python
apache-2.0
3,502
0.001142
# 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 use ...
on=None): args = {"templatefilter": "executable"} if location is not None: args["zoneid"] = location.id imgs = self._sync_request(command="listAvailableProductTypes", method="GET") images = [] for img in imgs["producttypes"]: images.append( ...
{ "hypervisor": "", "format": "", "os": img["templatedesc"], "templateid": img["templateid"], "zoneid": img["zoneid"], }, ) ) ...
flother/agate
agate/columns.py
Python
mit
3,731
0.000268
#!/usr/bin/env python """ This module contains the :class:`Column` class, which defines a "vertical" array of tabular data. Whereas :class:`.Row` instances are independent of their parent :class:`.Table`, columns depend on knowledge of both their position in the parent (column name, data type) as well as the rows that...
s) for this column. """ __slots__ = ['_index', '_name', '_data_type', '_rows', '_row_names'] def __init__(self, index, name, data_type, rows, row_names=None): self._index = index self._name = name self._data_type = data_type self._rows = rows self._keys = row_names ...
Return state values to be pickled. This is necessary on Python2.7 when using :code:`__slots__`. """ return { '_index': self._index, '_name': self._name, '_data_type': self._data_type, '_rows': self._rows, '_keys': self._keys ...
useanalias/qchess
setup.py
Python
mit
1,276
0
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='qchess', version='1.0.0.
dev1', description='A simple quantum chess client.', long_description=long_description, url='https://github.com/useanalias/qchess', author='Chandler', author_email='use.an.alias@gmail.com', license='MIT', classifiers=[ 'Development Status :: 1 - Planning', 'Intended Audience ...
:: OSI Approved :: MIT License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4...
takaakiaoki/PyFoam
PyFoam/Applications/AddCaseDataToDatabase.py
Python
gpl-2.0
2,898
0.007246
""" Application-class that implements pyFoamAddCaseDataToDatabase.py """ from optparse import OptionGroup from .PyFoamApplication import PyFoamApplication from PyFoam.Basics.RunDatabase import RunDatabase from os import path from PyFoam.ThirdParty.six.moves import cPickle as pickle from PyFoam.ThirdParty.six import ...
help="Tell about the data added") how.add_option("--skip-missing", action="store_true",
dest="skipMissing", default=False, help="Skip files that are missing or unreadable") def run(self): dest=self.parser.getArgs()[0] if path.exists(dest) and self.opts.create: self.error("database-file",dest,"exists already.") so...
KlubJagiellonski/pola-backend
pola/management/commands/update_from_kbpoz.py
Python
bsd-3-clause
362
0
from django.core.management.base import BaseCommand from pola.logic_workers import update_
from_kbpoz class Command(BaseCommand): help = 'Updates products according to KBPOZ database' def add_arguments(self, parser): parser.add_argument('db_filename') def ha
ndle(self, *args, **options): update_from_kbpoz(options["db_filename"])
lukecwik/incubator-beam
sdks/python/apache_beam/examples/snippets/transforms/aggregation/count.py
Python
apache-2.0
2,486
0.005008
# coding=utf-8 # # 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");...
ments) def count_per_key(test=None): # [START count_per_key] import apache_beam as beam with beam.Pipeline() as pipeline: total_elements_per_keys = ( pipeline | 'Create plants' >> beam.Create([ ('spring', '🍓'), ('spring', '🥕'), ('summer', '🥕'), ...
('summer', '🍅'), ('fall', '🍅'), ('summer', '🌽'), ]) | 'Count elements per key' >> beam.combiners.Count.PerKey() | beam.Map(print)) # [END count_per_key] if test: test(total_elements_per_keys) def count_per_element(test=None): # [START count_per_ele...
alliemacleay/MachineLearning_CS6140
utils/plots.py
Python
mit
641
0.0078
__author__ = 'Allison MacLeay' import matplotlib.pyplot as plt def points(array): plt_range = get_axes(array) print plt_range #plt.scatter(array, 'ro') plt.scatter(array[0], array[1]) #plt.axis(plt_range) plt.show() def get_axes(array): x_max = max(array[0]) x_min = min(array[0]) ...
n, y_max] def fit_v_point(array): """ array[0] = x array[1] = y
array[2] = linear fit""" plt.scatter(array[0], array[1], color='red') plt.scatter(array[0], array[2], color='blue') plt.show()
bitmovin/bitmovin-python
bitmovin/resources/models/encodings/inputstreams/__init__.py
Python
unlicense
459
0.006536
from .inges
t_input_stream import IngestInputStream from .concatenation_input_stream_configuration import ConcatenationInputStreamConfiguration from .concatenation_input_stream import ConcatenationInputStream from .time_based_trimming_input_stream import TimeBasedTrimmingInputStream from .time_code_track_trimming_input_stream impo...
ingInputStream
ktbs/ktbs
lib/ktbs/plugins/profiler.py
Python
lgpl-3.0
2,998
0.001668
# This file is part of KTBS <http://liris.cnrs.fr/sbt-dev/ktbs> # Copyright (C) 2011-2012 Pierre-Antoine Champin <pchampin@liris.cnrs.fr> / # Universite de Lyon <http://www.universite-lyon.fr> # # KTBS is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General ...
all the code is actually ran in the profiler (rather than differed by a generator). """ from c
Profile import runctx as run_in_profiler from datetime import datetime from os.path import join from tempfile import gettempdir from webob import Request import logging LOG = logging.getLogger(__name__) from rdfrest.http_server import \ register_middleware, unregister_middleware, MyResponse, TOP class ProfilerMi...
Mariam118/UYR
uyr/__init__.py
Python
gpl-2.0
42
0
__author__ = 'binary' __vers
ion__ = "1.0"
ZenQ3/Data-Structures
algorithms/string/checkSam.py
Python
mit
363
0.00551
#!/usr/bin/env python # -*- coding: utf-8 -*- class Same: def checkSam(self, stringA, stringB):
# write code here setA = sorted(stringA) setB = sorted(stringB) if setA == setB: return True return False if __name__ == '__main__': s = Same() print s.checkSam("This is nowcoder","is This nowcod
er")
stephenbez/memizr
spacedRepetition/flashcards/views.py
Python
agpl-3.0
7,218
0.016209
from django import forms from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import login, authenticate from django.core.urlresolvers import reverse from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts impo...
tion" : card.question, "2_answer" : card.answer} dict_card_list.append(d) result = json.dumps(dict_card_list, sort_keys=True, indent=4) response = HttpResponse(result, mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=cards.json' return response @login_required def...
e=RequestContext(request)) @login_required def upload(request): if request.method == 'POST': file = request.FILES['file'] num_cards_imported = handle_uploaded_file(file, request.user.username) return edit(request, num_cards_imported) else: return import_cards(request) def handl...
streeter/django-ticketing
runtests.py
Python
mit
1,704
0.005869
#!/usr/bin/env python import sys from os.path import dirname, abspath, join from django.conf import settings if not settings.configured: settings.configure( DATABASES={ 'default': { 'NAME': 'ticketing_test', 'ENGINE': 'django.db.backends.sqlite3', } ...
INSTALLED_APPS=[ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.sessions', 'django.contrib.sites', # Included to fix Disqus' test Django which solves IntegrityMessage case 'django.contrib.contenttype
s', 'ticketing', ], ROOT_URLCONF='', DEBUG=False, TICKETING_TESTING=True, ) def runtests(*test_args): if 'south' in settings.INSTALLED_APPS: from south.management.commands import patch_for_test_db_setup patch_for_test_db_setup() if not test_...
murawaki/lexwave
cossim.py
Python
bsd-2-clause
1,265
0.005534
# -*- coding: utf-8 -*- import sys from sklearn.decomposition import PCA import numpy as np from parse_tree import Node def create_leaf2vect(root, k): leaf2vect = {} stack = [root] size = -1 while len(stack) > 0: node = stack.pop(0) vect = np.array(map(lambda x: int(x), node.annotati
on['&' + k][2:-1]), dtype=np.int32) # vect = map(lambda x: int(x), node.annotation['&Ainu_UCLD_GRRW_SDollo'][2:-1]) # vect = map(lambda x: int(x), node.annotation['&japanese'][2:-1]) size = len(vect) if hasattr(node, "left"): stack.append(node.left) stack.append(n...
f2vect = create_leaf2vect(root, sys.argv[2]) vect1 = leaf2vect[sys.argv[3]] leaf2sim = {} for k, vect2 in leaf2vect.iteritems(): leaf2sim[k] = (vect1 * vect2).sum() / np.sqrt((vect1 * vect1).sum() * (vect2 * vect2).sum()) sorted_leaves = sorted(leaf2sim.keys(), key=lambda x: leaf2sim[x], reverse...
AmandaMoen/AmandaMoen
students/MichelleRascati/funct.py
Python
gpl-2.0
1,535
0
import codecs def funct(f_name): """Remove leading and trailing whitespace from file.""" f_read = codecs.open(f_name, 'r') f_lines = f_read.readlines() out_lines = map(str.strip, f_lines) f_read.close() while True: o_write = raw_input("Create new file (c) or overwrite existing (o): ")...
ormat(f_name) def funct_comp(f_name): """Remove leading and trailing whitespace from file w/ comprehension.""" f_read = codecs.open(f_name, 'r') f_lines = f_read.readlines() print f_lines # out_lines = map(str.strip, f_lines) out_lines = [line.str
ip() for line in f_lines] print out_lines f_read.close() while True: o_write = raw_input("Create new file (c) or overwrite existing (o): ") if o_write.lower() == 'o': # f_name stays the same break elif o_write.lower() == 'c': f_name = raw_input("...
samuelcolvin/pydantic
docs/examples/models_custom_root_field_parse_obj.py
Python
mit
478
0
from typing import List, Dict from pydantic import BaseModel, ValidationError class Pets(BaseModel): __root
__: List[str] print(Pets.parse_obj(['dog', 'cat'])) print(Pets.parse_obj({'__root__': ['dog', 'cat']})) # not recommended class PetsByName(BaseModel): __root__: Dict[str, str] print(PetsByName.parse_obj({'Otis': 'dog', 'Milo': 'cat'})) try: PetsByName.parse_obj({'__root__': {'Otis': 'dog', 'Milo': 'cat'}...
: print(e)
RuthAngus/turnip
turnip/gyro.py
Python
mit
892
0
# Age-rotation rela
tions. from teff_bv import teff2b
v class gyro_age(object): def __init__(self, p, teff=None, feh=None, logg=None, bv=None): self.p = p self.bv = bv if not self.bv: self.bv = teff2bv(teff, logg, feh) self.teff = teff self.feh = feh self.logg = logg def barnes07(self, version="barne...