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
lv10/bestbuyapi
bestbuyapi/api/bulk.py
Python
mit
3,123
0.000961
import json import zipfile from io import BytesIO from ..constants import BULK_API from ..api.base import BestBuyCore from ..utils.exceptions import BestBuyBulkAPIError class BestBuyBulkAPI(BestBuyCore): def _api_name(self): return BULK_API def archive(self, name, file_format): """BestBuy ge...
- productsDigital (Currently empty or deprecated) :file_format (str)
: File format in which the archive is to be downloaded. - xml - json BestBuy product subsets bulk docs: - https://developer.bestbuy.com/documentation/bulkDownload-api """ payload = {"query": f"subsets/{subset}.{file_format}.zip", "params": {}} ...
thopiekar/Uranium
UM/Math/Ray.py
Python
lgpl-3.0
767
0.006519
# Copyright
(c) 2015 Ultimaker B.V. # Uranium is released under the terms of the LGPLv3 or higher. from UM.Math.Vector import Vector class Ray: def __init__(self, origin = Vector(), direction = Vector()): self._origin = origin self._direction = direction self._inverse_direction = 1.0 / direction ...
return self._inverse_direction def getPointAlongRay(self, distance): return self._origin + (self._direction * distance) def __repr__(self): return "Ray(origin = {0}, direction = {1})".format(self._origin, self._direction)
mozilla/BanHammer
BanHammer/blacklist/views/zlb.py
Python
bsd-3-clause
9,627
0.006232
from django.shortcuts import render_to_response from django.template import RequestContext from django.core.exceptions import ObjectDoesNotExist from django.views.decorators.cache import never_cache from django.http import HttpResponse, HttpResponseRedirect from session_csrf import anonymous_csrf from ..models import ...
=password, comment=comment, ) zlb.save() return HttpResponseRedirect('/zlbs') else: form = ZLBForm() return render_to_response( 'zlb/new.html', {'form': form}, context_instance = RequestContext(request) ...
zlb.name = form.cleaned_data['name'] zlb.hostname = form.cleaned_data['hostname'] zlb.datacenter = form.cleaned_data['datacenter'] zlb.doc_url = form.cleaned_data['doc_url'] zlb.comment = form.cleaned_data['comment'] zlb.login = form.cleaned_data['login'] ...
igor-toga/local-snat
neutron/plugins/ml2/drivers/linuxbridge/agent/linuxbridge_neutron_agent.py
Python
apache-2.0
41,399
0.000121
#!/usr/bin/env python # Copyright 2012 Cisco Systems, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2...
ace name prefix we use: # * the physical_interface, if len(physical_interface) + # len(vlan_postifx) <= 15 for backward compatibility reasons # Example: physical_interface = eth0 # prefix = eth0.1 # prefix = eth0.1111 # # * otherwise a un...
al_interface to help debugging # Example: physical_interface = long_interface # prefix = longHASHED.1 # prefix = longHASHED.1111 # # Remark: For some physical_interface values, the used prefix can be # both, the physical_interface itself or a hash,...
plivo/plivo-python
tests/xml/test_recordElement.py
Python
mit
1,989
0.003017
from unittest import TestCase from plivo import plivoxml from tests import PlivoXmlTestCase class RecordElementTest(TestCase, PlivoXmlTestCase): def test_set_methods(self): expected_response = '<Response><Record action="https://foo.example.com" callbackMethod="GET" ' \ 'callbac...
alse finishOnKey = '#' transcriptionType = 'hybrid' transcriptionUrl = 'https://foo.example.com' transcriptionMethod = 'GET' callbackUrl = 'https://foo.e
xample.com' callbackMethod = 'GET' element = plivoxml.ResponseElement() response = element.add( plivoxml.RecordElement().set_action(action).set_method(method) .set_file_format(fileFormat).set_redirect(redirect).set_timeout( timeout).set_max_length(maxLeng...
julianwang/cinder
cinder/db/sqlalchemy/migrate_repo/versions/004_volume_type_to_uuid.py
Python
apache-2.0
5,948
0
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
raise def downgrade(migrate_engine): """Convert volume_type from UUID back to int.""" meta = MetaData() meta.bind = migrate_engine volumes = Table('volumes', meta, autoload=True) volume_types = Table('volume_types', meta, autoload=True) extra_specs = Table('volume_type_extra_specs', meta, a...
volumes.c.volume_type_id, volume_types.c.id, extra_specs.c.volume_type_id] for column in fkey_remove_list: fkeys = list(column.foreign_keys) if fkeys: fkey_name = fkeys[0].constraint.name fkey = ForeignKeyConstraint(columns=[co...
ivaxer/tipsip
tipsip/tests/test_header.py
Python
isc
2,901
0.002413
from twisted.trial import unittest from tipsip.header import Headers from tipsip.header import Header, AddressHeader, ViaHeader class HeadersTest(unittest.TestCase): def test_construct(self): aq = self.assertEqual at = self.assertTrue h = Headers({'Subject': 'lunch'}, f='John', to='abacab...
aq(v.display_name, 'The Operator') aq
(v.params, {'tag': '287447'}) v = AddressHeader.parse('sip:echo@example.com') aq(str(v.uri), 'sip:echo@example.com') class ViaHeaderTest(unittest.TestCase): def test_construct(self): aq = self.assertEqual v = ViaHeader(transport='UDP', host='192.168.0.1', port='5060', params={'rece...
singhj/locality-sensitive-hashing
utils/levenshtein.py
Python
mit
745
0.016107
# Reference: http://hetland.org/coding/python/levenshtein.py def levenshtein(a,b): "Calculates the Levenshtein distance between a and b." n, m = len(a), len(b) if n > m
: # Make sure n <= m, to use O(min(n,m)) space a,b = b,a n,m = m,n current = range(n+1) for i in range(1,m+1): previous, current = current, [i]+[0]*n for j in range(1,n+1): add, delete = previous[j]+1, current[j-1]+1 change = previous[j-1]...
current[j] = min(add, delete, change) return current[n] if __name__=="__main__": from sys import argv print levenshtein(argv[1],argv[2])
matthieu-meaux/DLLM
examples/broken_wing/test_broken_wing.py
Python
gpl-2.0
1,720
0.005814
# -*-mode: python; py-indent-offset: 4; tab-width: 8; coding: iso-8859-1 -*- # DLLM (non-linear Differentiated Lifting Line Model, open source software) # # Copyright (C) 2013-2015 Airbus Group SAS # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Pub...
peratingCondition('cond1', atmospheric_model='ISA') OC.set_Mach(0.8) OC.set_AoA(3.0) OC.set_altitude(10000.) OC.set_T0_deg(15.) OC.set_P0(101325.) OC.set_humidity(0.) OC.compute_atmosphere() wing_param=Wing_Broken('broken_wing',n_sect=20) wing_param.import_BC_from_file('input_parameters.par') wing_param.build_linear_a...
param.update() wing_param.plot() DLLM = DLLMSolver('test', wing_param, OC, verbose=1) DLLM.run_direct() DLLM.run_post() DLLM.run_adjoint()
ASCIT/donut-python
donut/constants.py
Python
mit
2,372
0.000422
"""Sto
re various constants here""" from enum import Enum # Maximum file upload size (in bytes). MAX_CONTENT_LENGTH = 1 * 10
24 * 1024 * 1024 # Authentication/account creation constants PWD_HASH_ALGORITHM = 'pbkdf2_sha256' SALT_SIZE = 24 MIN_USERNAME_LENGTH = 2 MAX_USERNAME_LENGTH = 32 MIN_PASSWORD_LENGTH = 8 MAX_PASSWORD_LENGTH = 1024 HASH_ROUNDS = 100000 PWD_RESET_KEY_LENGTH = 32 # Length of time before recovery key expires, in minutes. P...
brousch/saythis2
tts_engines/osx_say.py
Python
mit
888
0.003378
import os import re import subprocess from utils import whereis_exe class osx_voice(): def __init__(self, voice_line): mess = voice_line.split(' ') cleaned = [ part for part in mess if len(part)>0 ] self.name = cleaned[0] self.locality = cleaned[1] self.desc = cleaned[2]....
: osx_voices = [] if whereis_exe("say"): voices_raw = os.popen("say -v ?").read() voice_lines = voices_raw.split('\n') for line in voice_lines: try: osx_voices.append(osx_voice(line)) except IndexError: pass return osx_v
oices def speak(text, voice, rate): if whereis_exe("say"): subprocess.call(["say", text, "-v", voice, "-r", rate])
NlGG/experiments
Experimental Games on Networks/otree_code/network/models.py
Python
mit
3,635
0.009134
# -*- coding: utf-8 -*- # <standard imports> from __future__ import division import random import otree.models import otree.constants from otree.db import models from otree import widgets from otree.common import Currency as c, currency_range, safe_json from otree.constants import BaseConstants from otree...
network_type_group = ['Blue network', 'Red network', 'Brown network'] network_type = random.choice(network_type_group) return network_type def network(self): network_type = str(self.network_tp) if network_type == 'Blue network': network = {'A':['B'], '...
B', 'D', 'E'], 'D':['C', 'E'], 'E':['B', 'C', 'D']} elif network_type == 'Red network': network = {'A':['B'], 'B':['A', 'C'], 'C':['B', 'D', 'E'], 'D':['C', 'E'], 'E':['C', 'D']} else: network = {'A':['B'], 'B':['A', 'C', 'E'], 'C':['B', 'D'], 'D':['C', 'E'], 'E':['B', 'D']} ...
UnrememberMe/pants
testprojects/src/python/interpreter_selection/python_3_selection_testing/test_py2.py
Python
apache-2.0
554
0.012635
# coding=utf-8 # Copyright 2017 Pants project contributors (see CONTRIBUTORS
.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import sys from interpreter_selection.python_3_selection_testing.main_py2 import main def tes...
executable) # Note that ascii exists as a built-in in Python 3 and # does not exist in Python 2 ret = main() assert ret == None
xtao/code
vilya/views/api/repos/__init__.py
Python
bsd-3-clause
4,261
0
# -*- coding: utf-8 -*- import json from vilya.libs import api_errors from vilya.models.project import CodeDoubanProject from vilya.views.api.utils import RestAPIUI, api_require_login, jsonize from vilya.views.api.repos.product import ProductUI from vilya.views.api.repos.summary import SummaryUI from vilya.views.api....
guages = request.get_form_var('languages', '[]') try: languages = json.loads(languages) except ValueError: raise api_errors.NotJSONError self.repo.language = language self.repo.languages = languages return {} else: ...
return ForksUI(self.repo) @property def pulls(self): return PullsUI(self.repo) @property def product(self): return ProductUI(self.repo) @property def summary(self): return SummaryUI(self.repo) @property def intern_banned(self): return InternUI(...
paluh/django-tz
django_tz/middleware.py
Python
bsd-2-clause
1,766
0.002831
import datetime import pytz from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.translation import trans_real from . import global_tz from .forms import TimeZoneForm from .utils import guess_tz_from_lang def get_tz_from_request(request): if hasattr(request, 's
ession'): session_name = getattr(settings, 'TIMEZONE_SESSION_NAME', 'django_timezone') tz = request.session.get(session_name, None) if tz and isinstance(tz, datetime.tzinfo): return tz cookie_name = getattr(settings, 'TIMEZONE_COOKIE_NAME', 'TIMEZONE') form = TimeZoneForm({'...
iddleware(object): """ This middleware guesses timezone from language and sets it in current thread global cache. """ def get_tz(self, request): raise NotImplementedError() def process_request(self, request): tz = self.get_tz(request) if tz: global_tz.activat...
titusjan/astviewer
astviewer/misc.py
Python
mit
6,180
0.004854
""" Miscellaneous routines and constants. """ import logging, sys, traceback import os.path import astviewer.qtpy import astviewer.qtpy._version as qtpy_version from astviewer.version import DEBUGGING, PROGRAM_NAME, PROGRAM_VERSION, PYTHON_VERSION from astviewer.qtpy import QtCore, QtWidgets logger=logging.getLogger(...
is used. :type logger: logging.Logger or a string :param level: log level. String or int as described in the logging module documentation. Default: 'debug'. :type level: string or int :param item_prefix: String that will be prefixed to each line. Default: two spaces. ...
') if msg : logger.log(level_nr, "Logging dictionary: {}".format(msg)) if not dictionary: logger.log(level_nr,"{}<empty dictionary>".format(item_prefix)) return max_key_len = max([len(k) for k in dictionary.keys()]) for key, value in sorted(dictionary.items()): logger...
LINKIWI/modern-paste
app/uri/main.py
Python
mit
62
0
from base_uri im
port URI class HomeURI(URI): pa
th = '/'
acsone/server-tools
base_name_search_improved/__init__.py
Python
agpl-3.0
99
0
# -*- coding: utf-8 -*- from .ho
oks import post_init_hook from .
import models from . import tests
spectralDNS/shenfun
demo/laguerre_dirichlet_poisson1D.py
Python
bsd-2-clause
1,587
0.00252
r""" Solve Poisson equation in 1D with homogeneous Dirichlet bcs on the domain [0, inf) \nabla^2 u = f, The equation to solve for a Laguerre basis is (\nabla u, \nabla v) = -(f, v) """ import os import sys from sympy import symbols, sin, exp, lambdify import numpy as np from shenfun import inner, grad, Tes...
are with analytical solution ua = Array(SD, buffer=ue) print("Error=%2.16e" %(np.linalg.norm(uj-ua))) print("Error=%2.16e" %(np.sqrt(dx(uj-ua)**2))) assert np.allclose(uj, ua, atol=1e-5) point = np.array([0.1, 0.2]) p = SD.eval(point, f_hat) assert np.all
close(p, lambdify(x, ue)(point), atol=1e-5) if 'pytest' not in os.environ: import matplotlib.pyplot as plt xx = np.linspace(0, 16, 100) plt.plot(xx, lambdify(x, ue)(xx), 'r', xx, uh.eval(xx), 'bo', markersize=2) plt.show()
vitan/blaze
blaze/data/core.py
Python
bsd-3-clause
6,508
0.000154
from __future__ import absolute_import, division, print_function from itertools import chain from dynd import nd import datashape from datashape.internal_utils import IndexCallable from datashape import discover from functools import partial from ..dispatch import dispatch from blaze.expr import Projection, Field from...
end_chunks((nd.array(chunk, type=dtype_of(chunk)) for chunk in chunks)) def _extend_chunks(self, chunks): self.extend((row for chunk in chunks for row in nd.as_py(chunk, tuple=True))) def chunks(self, **kwargs): def dshape(chunk): ...
ype=dshape(chunk)) def _chunks(self, blen=100): return partition_all(blen, iter(self)) def as_dynd(self): return self.dynd[:] def as_py(self): if isdimension(self.dshape[0]): return tuple(self) else: return tuple(nd.as_py(self.as_dynd(), tuple=True)...
tensorflow/adanet
adanet/core/evaluator.py
Python
apache-2.0
4,624
0.00519
"""An AdaNet evaluator implementation in Tensorflow using a single graph. Copyright 2018 The AdaNet 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 https://www.ap...
ss, ensemble_metrics): """Evaluates the given AdaNet objectives on the data from `input_fn`. The candidates are fed the same batches of feature
s and labels as provided by `input_fn`, and their losses are computed and summed over `steps` batches. Args: sess: `Session` instance with most recent variable values loaded. ensemble_metrics: A list dictionaries of `tf.metrics` for each candidate ensemble. Returns: List of e...
KredekPth/Kurs_django
rental/models.py
Python
mit
564
0.031915
from django.db import models from django.contrib.auth.models import User from datetime import datetime from django.utils.timezone import now from shelf.models import BookItem # Create your models here. class Rental(models.Model): who = models.ForeignKey(User) what = models.ForeignKey(BookItem) when = models...
default = datetime.now) returned = models.DateTimeField(null = True, blank = True) def __str__(
self): return"{User},{Book},{rent},{ret}".format(User = self.who,Book = self.what,rent=self.when,ret = self.returned)
pik/pypayd
pypayd/config.py
Python
mit
1,595
0.013166
#Defaults - overridable via. pypayd.conf or command-line arguments DEFAULT_KEYPATH = '0/0/1' DEFAULT_TICKER = 'dummy' DEFAULT_CURRENCY = 'USD' DEFAULT_WALLET_FILE = 'wallet.txt' DEFAULT_WALLET_PASSWORD = "foobar" DEFAULT_MNEMONIC_TYPE = "electrumseed" DB = None DEFAULT_DB = "pypayd.db" DEFAULT_TESTNET_DB = "pypayd_tes...
3001' #'https://test-insight.bitpay.com' #None LOCAL_BLOCKCHAIN = False BLOCKCHAIN_SERVICE = 'insight' #generate a new address for every order if gen_new == True GEN_NEW = False #delay between requests to the blockchain service for new transactions POLLING_DELAY = 30 #maximum time a leaf (address) is used t
o process orders before a new one is generated MAX_LEAF_LIFE = 604800 #maximum number of transactions per address before a new one is generated MAX_LEAF_TX = 9999 #maximum amount of time an order received for generated amount will be considered valid ORDER_LIFE = 86400 #time from last order creation, after which an adr...
rupak0577/ginga
ginga/tests/test_colors.py
Python
bsd-3-clause
4,797
0.0271
# # Unit Tests for the colors.py functions # # Rajul Srivastava (rajul09@gmail.com) # import unittest import logging import numpy as np import ginga.colors class TestError(Exception): pass class TestColors(unittest.TestCase): def setUp(self): self.logger = logging.getLogger("TestColors") self.color_list_...
olor_white") # Tests for the add_color() and remove_color() function def test_add_and_remove_color_len(self): ginga.colors.add_color("test_color_white", (0.0, 0.0, 0.0)) expected = self.color_list_length + 1 actual = len(ginga.colors.color_dict) assert expected == actual expected = len(ginga.colors.co...
d == actual ginga.colors.remove_color("test_color_white") expected = self.color_list_length actual = len(ginga.colors.color_dict) assert expected == actual expected = len(ginga.colors.color_dict) actual = len(ginga.colors.color_list) assert expected == actual def test_add_and_remove_color_rbg(self):...
mlperf/training_results_v0.7
Google/benchmarks/resnet/implementations/resnet-cloud-TF2.0-tpu-v3-32/resnet_imagenet_main.py
Python
apache-2.0
12,959
0.007408
# Copyright 2018 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...
ot keras_utils.is_v2_0():
raise ValueError('--dtype=fp16 is not supported in TensorFlow 1.') elif dtype == tf.bfloat16: policy = tf.compat.v2.keras.mixed_precision.experimental.Policy( 'mixed_bfloat16') tf.compat.v2.keras.mixed_precision.experimental.set_policy(policy) data_format = flags_obj.data_format if data_format...
bepo13/destinydb-stl-generator-v0
src/DestinyModelGenStl.py
Python
mit
6,240
0.005769
import numpy scale = 1000 def unit(v): return (v / numpy.linalg.norm(v)) def angle(v1, v2): v1_u = unit(v1) v2_u = unit(v2) angle = numpy.arccos(numpy.dot(v1_u, v2_u)) if numpy.isnan(angle): if (v1_u == v2_u).all(): return 0.0 else: return numpy.pi retu...
ertices
to the file in forward order for k in range(3): v = positions[indices[start+j+k]] v = (v + positionMin) * scale f.write(" vertex "+str(v[0])+" "+str(v[1])+" "+str(v[2])+"\n") ...
ray6/sdn
actualSDN.py
Python
mit
14,660
0.007572
from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER from ryu.controller.handler import set_ev_cls from ryu.ofproto import ofproto_v1_3 from ryu.ofproto import ether from ryu.lib.packet import packet from ryu.lib.packet import ether...
, src_ip=arp_pkt.dst_ip, dst_mac=arp_pkt.src_mac, dst_ip=arp_pkt.src_ip)) self._send_packet(datapath, in_port, pkt) pr
int('arp', get_mac, pkt_ethernet.src,) # add host in the direct topo def AddHost(self, dpid, host, in_port): #Add host into directed_topo self.directed_Topo.add_node(host) #Add edge switch's port to src host self.directed_Topo.add_edge(dpid, host, {'port':in_port}) #Add ...
transistorfet/nerve
nerve/http/servers/wsgi.py
Python
gpl-3.0
3,372
0.007711
#!/usr/bin/python3 # -*- coding: utf-8 -*- import nerve import os import cgi import traceback import urllib.parse class WSGIHandler (nerve.Server): def __init__(self, **config): super().__init__(**config) def __call__(self, environ, start_response): #nerve.logs.redirect(environ['wsgi.errors...
ems(): if key.startswith('HTTP_'): name = key[5:].lower().replace('_', '-') headers[name] = value request = nerve.Request(self, None, reqtype, uri,
postvars, headers=headers) controller = self.make_controller(request) controller.handle_request(request) redirect = controller.get_redirect() error = controller.get_error() headers = controller.get_headers() mimetype = controller.get_mimetype() output = controlle...
CptSpaceToaster/memegen
memegen/services/template.py
Python
mit
1,885
0.000531
import logging from ._base import Service from ..domain import Template log = logging.getLogger(__name__) class TemplateService(Service): def __init__(self,
template_store, **kwargs): super().__init__(**kwargs
) self.template_store = template_store def all(self): """Get all templates.""" templates = self.template_store.filter() return templates def find(self, key): """Find a template with a matching key.""" key = Template.strip(key) # Find an exact match ...
dhaase-de/dh-python-dh
dh/thirdparty/tqdm/_tqdm_gui.py
Python
mit
13,510
0
""" GUI progressbar decorator for iterators. Includes a default (x)range iterator printing to stderr. Usage: >>> from tqdm_gui import tgrange[, tqdm_gui] >>> for i in tgrange(10): #same as: for i in tqdm_gui(xrange(10)) ... ... """ # future division is important to divide integers and get as # a result preci...
line2), ('cur', 'est'), loc='center right') # progressbar
self.hspan = plt.axhspan(0, 0.001, xmin=0, xmax=0, color='g') else: # ax.set_xlim(-60, 0) ax.set_xlim(0, 60) ax.invert_xaxis() ax.set_xlabel('seconds') ax.legend(('cur', 'est'), loc='lower left') ...
mlperf/training_results_v0.6
Fujitsu/benchmarks/resnet/implementations/mxnet/3rdparty/tvm/topi/tests/python_cpp/test_topi_pooling.py
Python
apache-2.0
5,140
0.006226
"""Test code for pooling""" import numpy as np import tvm import topi import math from topi.util import get_const_tuple pool_code = { "avg": 0, "max": 1 } def verify_pool(n, ic, ih, kh, sh, padding, pool_type, ceil_mode, count_include_pad=True): iw = ih kw = kh sw = sh pt, pl, pb, pr = padding ...
, 0], 'avg', False, True) verify_pool(1, 256, 31, 3, 3, [1, 2, 1, 2], 'avg', False, True
) verify_pool(1, 256, 32, 2, 2, [1, 2, 1, 2], 'avg', False, False) verify_pool(1, 256, 31, 4, 4, [3, 3, 3, 3], 'avg', False, False) verify_pool(1, 256, 31, 4, 4, [0, 0, 0, 0], 'avg', False, False) verify_pool(1, 256, 32, 2, 2, [0, 0, 0, 0], 'max', False) verify_pool(1, 256, 31, 3, 3, [2, 1, 2, 1], '...
111pontes/ydk-py
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_infra_objmgr_cfg.py
Python
apache-2.0
90,489
0.018323
""" Cisco_IOS_XR_infra_objmgr_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR infra\-objmgr package configuration. This module contains definitions for the following management objects\: object\-group\: Object\-group configuration Copyright (c) 2013\-2016 by Cisco Systems, Inc. All rig...
Border Gateway Protocol (179) .. data:: irc = 194 Internet Relay Chat (194) .. data:: pim_auto_rp = 496 PIM Auto-RP (496) .. data
:: exec_ = 512 Exec (rsh, 512) .. data:: login = 513 Login (rlogin, 513) .. data:: cmd = 514 Remote commands (rcmd, 514) .. data:: lpd = 515 Printer service (515) .. data:: uucp = 540 Unix-to-Unix Copy Program (540) .. data:: klogin = 543 Kerberos login (543)...
KWierso/treeherder
tests/log_parser/test_performance_parser.py
Python
mpl-2.0
1,056
0
import json from treeherder.log_parser.parsers import (EmptyPerformanceData, PerformanceParser) def test_performance_log_parsing_malformed_perfherder_data(): """ If we have malformed perfherder data lines, we should just ignore them and still be able to parse th...
_DATA: {oh noes i am not valid json}", 1) try: # Empty performance data parser.parse_line("PERFHERDER_DATA: {}", 2) except EmptyPerformanceData: pass valid_perfherder_data = { "framework": {"name": "talos"}, "suites": [{ "name": "basic_compositor_video", ...
"value": 1234 }] }] } parser.parse_line('PERFHERDER_DATA: {}'.format( json.dumps(valid_perfherder_data)), 3) assert parser.get_artifact() == [valid_perfherder_data]
magus424/powerline
powerline/lib/debug.py
Python
mit
3,036
0.027339
#!/usr/bin/env python # vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import gc import sys from types import FrameType from itertools import chain # From http://code.activestate.com/recipes/523004-find-cyclical-references/ def print_cycles(objects, ...
i, step in enumerate(path): # next "wraps around" next = path[(i + 1) % len(path)] outstream.write("
%s -- " % str(type(step))) written = False if isinstance(step, dict): for key, val in step.items(): if val is next: outstream.write("[%s]" % repr(key)) written = True break if key is next: outstream.write("[key] = %s" % repr(val)) written = True break elif isi...
gpodder/mygpo
mygpo/administration/group.py
Python
agpl-3.0
1,212
0.00165
from datetime import datetime from collections import defaultdict DEFAULT_RELEASE = datetime(1970, 1, 1) _SORT_KEY = lambda eps: eps[0].released or DEFAULT_RELEASE class PodcastGrouper(object): """Groups episodes of two podcasts based on certain features The results are sorted by release timestamp""" ...
def group(self, get_features): episodes = self.__get_episodes() episode_groups = defaultdict(list) episode_features = map(get_features, episodes.items()) for features, episode_id in episode_features:
episode = episodes[episode_id] episode_groups[features].append(episode) # groups = sorted(episode_groups.values(), key=_SORT_KEY) groups = episode_groups.values() return enumerate(groups)
okfnepal/election-nepal
fabfile.py
Python
mit
21,828
0.000321
from __future__ import print_function, unicode_literals from future.builtins import open import os import re import sys from contextlib import contextmanager from functools import wraps from getpass import getpass, getuser from glob import glob from importlib import import_module from posixpath import join from mezza...
new_reqs = get_reqs() if old_reqs == new_reqs: # Unpinned requirements should always be checked. for req in new_reqs.split("\n"): if req.startswith("-e"): if "@" not in req: # Editable requirement without pinned commit. ...
# PyPI requirement without version. break else: # All requirements are pinned. return pip("-r %s/%s" % (env.proj_path, env.reqs_path)) ########################################### # Utils and wrappers for various comman...
nylas/sync-engine
migrations/versions/034_cascade_folder_deletes_to_imapuid.py
Python
agpl-3.0
4,899
0.000408
"""cascade folder deletes to imapuid Otherwise, since this fk is NOT NULL, deleting a folder which has associated imapuids still existing will cause a database IntegrityError. Only the mail sync engine does such a thing. Nothing else should be deleting folders, hard or soft. This also fixes a problem where if e.g. so...
='foreignkey') op.create_foreign_key('account_ibfk_8', 'accou
nt', 'folder', ['all_folder_id'], ['id'], ondelete='SET NULL') op.drop_constraint('account_ibfk_9', 'account', type_='foreignkey') op.create_foreign_key('account_ibfk_9', 'account', 'folder', ['starred_folder_id'], ['id'], ondelete='SET NULL') # for some r...
LibraryBox-Dev/LibraryBox-core
piratebox_origin/piratebox/piratebox/python_lib/messages.py
Python
gpl-3.0
1,109
0.038774
import string import socket import base64 import sys class message: def __init__(self, name="generate" ): if name == "generate": self.name=socket.gethostname() else: self.name=name self.type="gc" self.decoded="" def set ( self, content=" " ): ...
urn self.name def get_message ( self ): return self.decoded def set_message ( self , decoded):
self.decoded = decoded class shoutbox_message(message): def __init__(self, name="generate" ): message.__init__( self , name) self.type="sb"
k0pernicus/giwyn
giwyn/lib/gitconf/commands.py
Python
gpl-3.0
1,268
0.005521
import giwyn.lib.settings.settings from git import * def list_git_projects(): print("List of git projects:") #end="" -> avoid last '\n' character for git_object in giwyn.lib.settings.settings.GIT_OBJECTS: print(git_object) def push_ready_projects(): print("Repository to push...") any_repo_...
ings.GIT_OBJECTS: if git_project.current_status == "TO PUSH": print("Pushing {0} in the current branch...".format(git_project.entry)) git_project.git_object.remote().push() any_repo_to_push = True if not any_repo_to_push: print("There is no repository to push yet!...
n.lib.settings.settings.GIT_OBJECTS: if git_project.current_status == "CLEAN": print("Try to pull {0}, from the current branch...".format(git_project.entry)) #Pull from origin if git_project.git_object.remotes != []: git_project.git_object.remotes.origin.pull(...
DataCanvasIO/pyDataCanvas
datacanvas/dataset/parser/parser.py
Python
apache-2.0
435
0
# -*- coding: utf-8 -*- from ..common import get_module_class
class Parser(object): @staticmethod def get(parser_name): clazz = get_module_class(parser_name, __name__) return clazz() def loads(self, content): return content def dumps(self, content): return content def load(self, f): return NotImplemented def dump...
f): return NotImplemented
dirjud/pickup
event/models.py
Python
gpl-2.0
3,032
0.01715
from django.db import models from django.utils import timezone import pytz import datetime def hash(n): n = int(n) return ((0x0000FFFF & n)<<16) + ((0xFFFF0000 & n)>>16) class EventInstance(object): def __init__(self, event, event_time, date): self.date = date.date() self.time = date.time(...
) event= models.ForeignKey(Event, related_name="times") day = models.IntegerField(choices=DAY_CHOICES) time = models.TimeField()
def get_next(self, now): dow = now.weekday() td = datetime.timedelta(days=(self.day - dow) % 7) next_date = now + td return datetime.datetime.combine(next_date, self.time) class Signup(models.Model): ATTENDING = 0 NOT_ATTENDING = 1 status_choices = ( ( ATT...
themaxx75/lapare-bijoux
lapare.ca/lapare/apps/www/migrations/0011_auto_20151022_2037.py
Python
bsd-3-clause
375
0
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Mig
ration): dependencies = [ ('www', '0010_expo_info_url'), ] operations = [ migrations.RenameField( model_name='expo', old_name='info_url', new_
name='url', ), ]
rodrigobersan/X-Serv-18.1-Practica1
project/acorta/models.py
Python
gpl-2.0
219
0.004566
from __future__ import unicode_literals from django.db import models # Create your models here. clas
s Urls(models.Model): longurl = models.CharField(max
_length=256) shorturl = models.CharField(max_length=128)
alexandergraul/pvs-bot
launcher.py
Python
gpl-3.0
1,561
0.000641
import RoleManagement import bot_logger import purger async def run_op(client, message, bot_log): levels = { 'admin': ['admin'], 'high': ['admin', 'moderator', 'panda bat'], 'medium': ['trial moderator', 'moderator', 'admin', 'pa
nda bat'], 'low': ['@everyone'] } ops = {'+': [RoleManagement.assign_role, 'low'], '-': [RoleManagement.remove_role, 'low'], 'reduce': [RoleManagement.reduce_roles, 'high'],
'timein': [RoleManagement.timein_user, 'medium'], 'timeout': [RoleManagement.timeout_user, 'medium'], 'verify': [RoleManagement.verify_rank, 'low'], 'purge': [purger.purge_channel, 'high'], 'count': [RoleManagement.count_users, 'medium'], } # unwrap messa...
grangier/django-11599
tests/modeltests/custom_pk/models.py
Python
bsd-3-clause
5,234
0.001911
# -*- coding: utf-8 -*- """ 14. Using a custom primary key By default, Django adds an ``"id"`` field to each model. But you can override this behavior by explicitly adding ``primary_key=True`` to a field. """ from django.conf import settings from django.db import models, transaction, IntegrityError from fields impor...
Business.objects.filter(name__exact='Sears') [<Business: Sears>] >>> Business.objects.filter(pk='Sears') [<Business: Sears>] # Queries across tables, involving
primary key >>> Employee.objects.filter(business__name__exact='Sears') [<Employee: Dan Jones>, <Employee: Fran Jones>] >>> Employee.objects.filter(business__pk='Sears') [<Employee: Dan Jones>, <Employee: Fran Jones>] >>> Business.objects.filter(employees__employee_code__exact=123) [<Business: Sears>] >>> Business.obje...
takeshineshiro/horizon
openstack_dashboard/dashboards/project/access_and_security/tabs.py
Python
apache-2.0
5,203
0
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # Copyright 2012 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use t...
name = _("API Access") slug = "api_access_tab" template_name = "horizon/common/_detail_table.html" def get_endpoints_data(self): services = [] for i, service in enumerate(self.request.user.service_catalog): service['id'] = i services.append( keyst...
tabs = (SecurityGroupsTab, KeypairsTab, FloatingIPsTab, APIAccessTab) sticky = True
lmazuel/azure-sdk-for-python
azure-batch/azure/batch/models/pool_evaluate_auto_scale_parameter.py
Python
mit
1,498
0
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
a: The formula for the desired number of compute nodes in the pool. The formula is validated and its results calculated, but it is not applied to the pool. To apply the formula to the pool, 'Enable automatic scaling on a pool'. For more information about speci
fying this formula, see Automatically scale compute nodes in an Azure Batch pool (https://azure.microsoft.com/en-us/documentation/articles/batch-automatic-scaling). :type auto_scale_formula: str """ _validation = { 'auto_scale_formula': {'required': True}, } _attribute_map = { ...
tps12/Tec-Nine
rock/sedimentary.py
Python
gpl-3.0
2,309
0.004764
def deposit(materials, life, sea, climate): contributions = [] depositkeys = set() for m in materials: t = 0 i = len(m.substance) - 1 sources = [] keys = set() while t < m.total: dt = m.total - t layer = m.substance[i] if layer['thi...
t attributes by thickness rock[k] = sum([float(c['thickness']) * c['rock'][k] if k in c['rock'] else 0 for c in contributions])/thickness rock['clasticity'] = rock['clasticity'] * 2 if 'clasticity' in rock else 1 if life: if sea: ...
9: rock['name'] = 'chalk' elif rock['calcity'] > 0.75: rock['name'] = 'limestone' elif climate.koeppen[0] == u'C' and climate.temperature < 18: rock['bogginess'] = max(0, (climate.precipitation - 0.75) * 4) if rock['name'] is None: grain = 1e-...
svanschalkwyk/datafari
windows/python/Lib/test/test_io.py
Python
apache-2.0
120,213
0.001406
"""Unit tests for the io module.""" # Tests of io are scattered over the test suite: # * test_bufio - tests file buffering # * test_memoryio - tests BytesIO and StringIO # * test_fileio - tests FileIO # * test_file - tests the file interface # * test_io - tests everything else in the io module # * test_univnewlines - ...
ture__ import unicode_literals import os import sys import time import array import random import unittest import weakref import warnings import abc import signal import errno from itertools import cycle, count from collections import deque from UserList import UserList from test import test_support as support import ...
# Python implementation of io try: import threading except ImportError: threading = None try: import fcntl except ImportError: fcntl = None __metaclass__ = type bytes = support.py3k_bytes def _default_chunk_size(): """Get the default TextIOWrapper chunk size""" with io.open(__file__, "r", enc...
SoundGoof/NIPAP
nipap/nipap/errors.py
Python
mit
1,301
0.000769
class NipapError(Exception): """ NIPAP base error class. """
error_code = 1000 class NipapInputError(NipapError): """ Erroneous input. A general input error. """ error_code = 1100 class NipapMissingInputError(NipapInputError): """ Missing input. Most input is passed in dicts, this could mean a missing key in a dict. """ error_...
error_code = 1120 class NipapNoSuchOperatorError(NipapInputError): """ A non existent operator was specified. """ error_code = 1130 class NipapValueError(NipapError): """ Something wrong with a value For example, trying to send an integer when an IP address is expected. """ erro...
Azure/azure-sdk-for-python
sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2019_07_01/operations/_snapshots_operations.py
Python
mit
46,204
0.004697
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
napshotName": _SERIALIZER.url("snapshot_name", snapshot_name, 'str'), } url = _format_url_section(url, **path_format_arguments) # Construct parameters query_parameters = kwargs.pop("params", {}) # type:
Dict[str, Any] query_parameters['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') return HttpRequest( method="DELETE", url=url, params=query_parameters, **kwargs ) def build_list_by_resource_group_request( subscription_id: str, resource_group_n...
T-002/pycast
pycast/common/decorators.py
Python
mit
2,987
0.002009
# !/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2012-2015 Christian Schwarz # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitat...
:rtype: function """ def _optimized(self, *args, **kwargs): """ This method calls the pycastC function if optimization is enabled and the pycastC function is available. :param: PyCastObject self: reference to the calling object. Needs to...
so that all uts members are available. :param: list *args: list of arguments the function is called with. :param: dict **kwargs: dictionary of parameter names and values the function has been called with. :return result of the function call either from pycast or pycastC module. :...
davy39/eric
ThirdParty/Pygments/pygments/plugin.py
Python
gpl-3.0
1,903
0
# -*- coding: utf-8 -*- """ pygments.plugin ~~~~~~~~~~~~~~~ Pygments setuptools plugin interface. The methods defined here also work if setuptools isn't installed but they just return nothing. lexer plugins:: [pygments.lexers] yourlexer = yourmodule:YourLexer formatter pl...
or: pkg_resources = None LEXER_ENTRY_POINT = 'pygments.lexers' FORMATTER_ENTRY_POINT = 'pygments.formatters' STYLE_ENTRY_POINT = 'pygments.styles' FILTER_ENTRY_POINT = 'pygments.filters' def find_plugin_lexers(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(L...
ources.iter_entry_points(FORMATTER_ENTRY_POINT): yield entrypoint.name, entrypoint.load() def find_plugin_styles(): if pkg_resources is None: return for entrypoint in pkg_resources.iter_entry_points(STYLE_ENTRY_POINT): yield entrypoint.name, entrypoint.load() def find_plugin_filters(...
s-knibbs/py-web-player
pywebplayer/discover.py
Python
gpl-2.0
2,070
0.000483
import os import time from config import ComponentBase from transcode import Transcoder class MediaDiscovery(ComponentBase): DURATION_FORMAT = '%H:%M:%S' MAX_DEPTH = 4 def __init__(self, library): super(MediaDiscovery, self).__init__() self.library = library def search(self, paths,...
ation']) self.library.insert(name, abspath, length, size, tcoder.MIME_MAP[ext], info, ignore_duplicates=True)
num_items += 1 except OSError as e: self.logger.warning(str(e)) self.library.save() return self.search(sub_paths, depth + 1) + num_items def _duration_to_secs(self, duration): """Converts a duration string into seconds""" # TODO - Support sub second p...
vuolter/pyload
src/pyload/core/network/cookie_jar.py
Python
agpl-3.0
1,007
0.000993
# -*- coding: utf-8 -*- import time from datetime import timedelta class CookieJar: def __init__(self, pluginname, account=None): self.cookies = {} self.plugin = pluginname self.account = account def add_cookies(self, clist): for c in clist: name = c.split("\t")[5...
) def parse_cookie(self, name): if name in self.co
okies: return self.cookies[name].split("\t")[6] else: return None def get_cookie(self, name): return self.parse_cookie(name) def set_cookie( self, domain, name, value, path="/", exp=time.time() + timedelta(hours=744).total...
caulagi/hubot-py-wtf
test/code/bad.py
Python
mit
46
0.021739
# -*- coding:
utf-8 -*- #!/usr/bin/env
python
ElessarWebb/dummy
src/dummy/utils/argparser.py
Python
mit
1,745
0.05616
import logging from dummy.models import Test from dummy.utils import git from dummy.storage import StorageProvider from dummy import config logger = logging.getLogger( __name__ ) def discover_targets( args ): targets = [] if args.alltargets: for t in config.TARGETS.keys(): targets.append( t ) elif len( args...
target: targets.append( target ) return targets def discover_tests( args ): tests = [] # try to find the suites and append the testnames # of the suite for name in args.suite: logger.info( "Loading tests from suite `%s`" % name ) # make sure to have a valid test suite name try: suite = config.SUITES...
Adding test `%s` to tests." % fname ) tests.append( Test( fname )) except KeyError: logger.error( "We looked, but a test suite with name `%s` was not found." % name ) # queue the named tests for names in [ Test.glob( name ) for name in args.tests ]: for name in names: tests.append( Test( name )) # ...
osrf/docker_templates
docker_templates/library.py
Python
apache-2.0
2,737
0.000731
# Copyright 2015-2016 Open Source Robotics Foundation, 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 applicabl...
gs: ', tags) tag_data['Tags'] = tags tag_data['Architectures'] = os_code_data['archs'] tag_data['GitComm
it'] = commit_sha tag_data['Directory'] = commit_path if not at_least_one_tag: del manifest['release_names'][release_name] return manifest
ddico/odoo
addons/sale_expense/models/product_template.py
Python
agpl-3.0
1,032
0.001938
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models class ProductTemplate(models.Model): _inherit = 'product.template' def _default_visible_expense_policy(self): visibility = self.user_has_groups('hr_expense.group_hr_expense...
t_template in self - expense_products: product_template.visible_expense_policy = False super(ProductTemplate, expense_products)._compu
te_visible_expense_policy() visibility = self.user_has_groups('hr_expense.group_hr_expense_user') for product_template in expense_products: if not product_template.visible_expense_policy: product_template.visible_expense_policy = visibility
odahoda/noisicaa
noisicaa/builtin_nodes/pianoroll_track/track_ui.py
Python
gpl-2.0
53,058
0.001809
#!/usr/bin/python3 # @begin:license # # Copyright (c) 2015-2019, Benjamin Niemann <pink@odahoda.de> # # 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 y...
down_cast from noisicaa import constants from noisicaa import audioproc from noisicaa import core from noisicaa import music from noisicaa.ui import ui_base from noisicaa.ui import clipboard from noisicaa.ui import pianoroll from noisicaa.ui import s
lots from noisicaa.ui import int_dial from noisicaa.ui.track_list import tools from noisicaa.ui.track_list import base_track_editor from noisicaa.ui.track_list import time_view_mixin from noisicaa.builtin_nodes.pianoroll import processor_messages from . import model from . import clipboard_pb2 logger = logging.getLogg...
tantalor/megaera
megaera/local.py
Python
mit
1,305
0.010728
"""Accessors for an app's local configuration The local configuration is loaded from a YAML file. The default configuration is "local.yaml", in the app's root. An app's local configuration can change depending on the current environment, i.e., development and production. For example, pirate: ninja robot: de...
memcache try: config = memcache.get(cachekey) if config: return config except AssertionError: pass if os.path.exists(filename): config = yaml.load(file(filename).read()) # branch each value by environment config = dict([(key, branch(value)) for k
ey, value in config.iteritems()]) try: memcache.set(cachekey, config) except AssertionError: pass return config return dict() def config_get(key): """Return the value for the given key from the default config.""" return config()[key]
adykstra/mne-python
tutorials/stats-sensor-space/plot_stats_cluster_time_frequency.py
Python
bsd-3-clause
4,873
0
""" ========================================================================= Non-parametric between conditions cluster statistic on single trial power ========================================================================= This script shows how to compare clusters in time-frequency power estimates between condition...
weights=[1, -1]) evoked_contrast.plot(axes=ax2, time_unit='s') plt.s
how()
pignacio/chorddb
chorddb/terminal/__init__.py
Python
gpl-3.0
190
0
#! /usr/bin/env python # -*- c
oding: utf-8 -*- from __future__ import absolute_import, unicode_literals import logging from .render import render_tablature
__all__ = ['render_tablature']
mishpat/human-capital-search
humancapitalsearch.py
Python
mit
4,080
0.007108
import functools import os import numpy as np import pygmo as pg from simulation import simulate, statistical from solving import value_function_list from util import constants as cs, param_type class HumanCapitalSearchProblem(object): def fitness(self, params_nparray, gradient_eval=False): params_param...
ions = value_function_list.backwards_iterate(params_paramtype) # if display_plot
s: # plotting.plot_valuefunctions(optimal_value_functions) panel_data = simulate.simulate_data(params_paramtype, optimal_value_functions) # if save_panel_data: # np.savetxt('simulated_data.csv', panel_data.T, delimiter=',') simulated_coefficients, _, _, _ = statistical.ca...
lofar-astron/PyBDSF
bdsf/sourcecounts.py
Python
gpl-3.0
12,587
0.025582
"""Sourcecounts s is flux in Jy and n is number > s per str """ import numpy as N s=N.array([ 9.9999997e-05, 0.00010328281, 0.00010667340, 0.00011017529, 0.00011379215, 0.00011752774, 0.00012138595, \ 0.00012537083, 0.00012948645, 0.00013373725, 0.00013812761, 0.00014266209, 0.00014734542, 0.00015218249, 0.000157178...
89930650, 0.00092882907, 0.00095932081, \ 0.00099081360, 0.0010233402, 0.0010569346, 0.0010916317, 0.0011274681, 0.0011644807, 0.0012027085, 0.0012421905, \ 0.0012829694, 0.0013250869, 0.0013685870, 0.0014135153, 0.0014599183, 0.0015078448, 0.0015573446, 0.0016084694, \ 0.0016612725, 0.0017158090, 0.0017721358
, 0.0018303118, 0.0018903976, 0.0019524558, 0.0020165513, 0.0020827511, \ 0.0021511239, 0.0022217415, 0.0022946771, 0.0023700071, 0.0024478103, 0.0025281659, 0.0026111610, 0.0026968806, \ 0.0027854142, 0.0028768543, 0.0029712960, 0.0030688383, 0.0031695808, 0.0032736324, 0.0033810998, 0.0034920950, \ 0.0036067341, 0.00...
MitchTalmadge/Emoji-Tools
src/main/resources/PythonScripts/fontTools/unicode.py
Python
gpl-3.0
1,057
0.037843
from __future__ import print_function, division, absolute
_import from fontTools.misc.py23 import * def _makeunicod
es(f): import re lines = iter(f.readlines()) unicodes = {} for line in lines: if not line: continue num, name = line.split(';')[:2] if name[0] == '<': continue # "<control>", etc. num = int(num, 16) unicodes[num] = name return unicodes class _UnicodeCustom(object): def __init__(self, f): if isinsta...
ATNF/askapsdp
Tools/Dev/rbuild/askapdev/rbuild/utils/get_svn_revision.py
Python
gpl-2.0
1,823
0.002743
# @file get_svn_revision.py # Fetch the subversion revision number from the repository # # @copyright (c) 2006,2014 CSIRO # Australia Telescope National Facility (ATNF) # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # PO Box 76, Epping NSW 1710, Australia # atnf-enquiries@csiro.au # # This file ...
c., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. # # @author Robert Crida <robert.crida@ska.ac.za> # from runcmd import runcmd from get_vcs_type import is_git import os def get_svn_revision(): try: (stdout, stderr, returncode) = runcmd('svnversion', shell=True) if returncode == 0 and st...
if is_git(): return get_git_revision() return "unknown" except: return "unknown" def get_git_revision(): try: (stdout, stderr, returncode) = runcmd('git describe --tags --always', shell=True) if returncode == 0: return stdout.rstrip() else...
Georacer/last_letter
rqt_dashboard/src/rqt_dashboard/dashboard.py
Python
gpl-3.0
16,075
0.029425
import os import rospy, rospkg import sys import math import yaml from itertools import izip_longest from operator import add, sub from qt_gui.plugin import Plugin from python_qt_binding import loadUi from python_qt_binding.QtWidgets import QWidget from PyQt5 import QtGui, QtWidgets, QtCore from rqt_plot.rosplot impo...
.pubTimer.start(1000) for name in sorted(data.keys()): #sort based on name values = data[name] # print 'Adding: {}'.format(name) values['topic'] = prefix + values['topic'] values['warning'] = zip(*[iter(values['warning'])]*2) values['danger'] = zip(*[iter(values['dang
er'])]*2) gauges.append(GaugeSimple(**values)) gauges[-1].marker_set.connect(self.onClick) grouped_gauges = list(izip_longest(*(iter(gauges),)*3)) for i in xrange(len(grouped_gauges)): setattr(self, 'column{}'.format(i), QtWidgets.QVBoxLayout()) curr_column = getattr(self, 'column{}'.format(i)) for...
ActiveState/code
recipes/Python/576734_C_struct_decorator/recipe-576734.py
Python
mit
1,507
0.033842
import ctypes class C_struct: """Decorator to convert the given class into a C struct.""" # contains a dict of all known translatable types types = ctypes.__dict__ @classmethod def register_type(cls, typenam
e, obj): """Adds the new class to the dict of understood types.""" cls.types[typename] = obj def __call__(self, cls): """Converts the given class into a C struct. Usage: >>> @C_struct() ... class Account: ... first_name = "c_char_p" ... last_name = "c_char_p" ... b
alance = "c_float" ... >>> a = Account() >>> a <cstruct.Account object at 0xb7c0ee84> A very important note: while it *is* possible to instantiate these classes as follows: >>> a = Account("Geremy", "Condra", 0.42) This is strongly discouraged, because there is at present no way to ensure what...
svenstaro/OpenShadingLanguage
testsuite/texture-withderivs/run.py
Python
bsd-3-clause
133
0.015038
#!/usr/bi
n/env python command += testshade("-g 256 256 --center -od uint8 -o Cout out.tif
test") outputs = [ "out.txt", "out.tif" ]
ThiagoGarciaAlves/erpnext
erpnext/accounts/report/sales_register/sales_register.py
Python
agpl-3.0
7,220
0.024931
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.utils import flt from frappe import msgprint, _ def execute(filters=None): if not filters: filters = {} invoice_list = get...
list)), tuple([inv.name for inv in invoice_list])) tax_accounts = frappe.db.sql_list("""select distinct account_head from `tabSales Taxes and Charges` where parenttype = 'Sales Invoice' and docstatus = 1 and ifnull(base_tax_amount_after_discount_amount, 0) != 0 and parent in (%s) order by account_head""" %...
[inv.name for inv in invoice_list])) income_columns = [(account + ":Currency:120") for account in income_accounts] for account in tax_accounts: if account not in income_accounts: tax_columns.append(account + ":Currency:120") columns = columns + income_columns + [_("Net Total") + ":Currency:120"] + tax_columns...
cshallue/models
research/object_detection/meta_architectures/faster_rcnn_meta_arch_test.py
Python
apache-2.0
17,423
0.004018
# Copyright 2017 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...
ize, image_size, 3), (batch_size, None, None, 3), (None, None, None, 3)] expected_num_anchors = image_size * image_size * 3 * 3 expected_shapes = { 'rpn_box_predictor_features': (2, image_size, image_size, 512), 'rpn_features_to_crop': (2, image_si...
'rpn_objectness_predictions_with_background': (2, expected_num_anchors, 2), 'anchors': (expected_num_anchors, 4), 'refined_box_encodings': (2 * max_num_proposals, 2, 4), 'class_predictions_with_background': (2 * max_num_proposals, 2 + 1), 'num_proposals': (2,), 'pro...
ygol/odoo
addons/sale_stock/wizard/sale_order_cancel.py
Python
agpl-3.0
553
0.003617
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class SaleOrderCancel(models.TransientModel): _inherit = 'sale.order.cancel' display_delivery_alert = fields.Boolean('Delivery Alert', compute='_compute_display_delivery_al...
depends('order_id') def _compute_display_delivery_alert(self): for wizard in self: wizard.display_delivery_alert = bool(any(picking.state == 'done' for picking in wizard.order_id.picking_ids)
)
DeepThoughtTeam/tensorflow
tensorflow/python/ops/constant_op.py
Python
apache-2.0
7,338
0.004361
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache L
icense, 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 License for the specific language...
keflavich/pyspeckit-obsolete
pyspeckit/spectrum/readers/txt_reader.py
Python
mit
5,045
0.010109
""" ========================== PySpecKit ASCII Reader ========================== Routines for reading in ASCII format spectra. If atpy is not installed, will use a very simple routine for reading in the data. .. moduleauthor:: Adam Ginsburg <adam.g.ginsburg@gmail.com> .. moduleauthor:: Jordan Mirocha <mirochaj@gma...
if text_reader == 'simple': data, error, XAxis, T = simple_txt(filename, xaxcol = xaxcol, datacol = datacol, errorcol = errorcol, **kwargs) elif text
_reader == 'readcol': Tlist = readcol.readcol(filename, twod=False, **kwargs) XAxis = units.SpectroscopicAxis(Tlist[xaxcol]) data = Tlist[datacol] error = Tlist[errorcol] T = dummy_class() Tdict = readcol.readcol(filename, asDict=True, **kwargs) ...
kallimachos/archive
andpygame/android_example.py
Python
gpl-3.0
1,612
0.001861
import pygame # Import the android module. If we can't import it, set it to None - this # lets us test it, and che
ck to see if we want android-specific behavior. try: import android except ImportError: android = None # Event constant. TIMEREVENT = pygame.USEREVENT # The FPS the game runs at. FPS = 30 # Color constants. RED = (255, 0, 0, 255) GREEN = (0, 255, 0, 255) def main(): pygame.init() # Set the screen s...
# Map the back button to the escape key. if android: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) # Use a timer to control FPS. pygame.time.set_timer(TIMEREVENT, 1000 / FPS) # The color of the screen. color = RED while True: ev = pygame....
jeremiah-c-leary/vhdl-style-guide
vsg/tests/iteration_scheme/test_rule_300.py
Python
gpl-3.0
1,279
0.003909
import os import unittest from vsg.rules import iteration_scheme from vsg import vhdlFile from vsg.tests import utils sTestDir = os.path.dirname(__file__) lFile, eError =vhdlFile.utils.read_vhdlfile(os.path.join(sTestDir,'rule_300_test_input.vhd')) dIndentMap = utils.read_indent_file() lExpected = [] lExpected.ap...
assertEqual(oRule.identifier, '300') lExpected = [13, 17] oRule.analyze(self.oFile) self.assertEqual(lExpected, utils.extract_violation_lines_from_violation_object(oRule.violations)) def test_fix_rule_300(self): oRule = iteration_scheme.rule_300() oRule.fix(self.oFile) ...
[])
anselmobd/fo2
src/logistica/forms.py
Python
mit
5,361
0.000187
from datetime import datetime, timedelta from pprint import pprint from django import forms from utils.functions import shift_years from .models import ( NfEntrada, PosicaoCarga, ) class NotafiscalChaveForm(forms.Form): chave = forms.CharField( widget=forms.TextInput()) class NotafiscalRelFor...
=2, min_length=2, required=False, widget=forms.TextInput(attrs={'size': 2})) nf = forms.CharField( label='Número da NF', required=False, widget=forms.TextInput(attrs={'type': 'number'})) transportadora = forms.CharField( label='Transportadora', required=False, help_text...
TextInput()) cliente = forms.CharField( label='Cliente', required=False, help_text='Parte do nome ou início do CNPJ.', widget=forms.TextInput()) pedido = forms.CharField( label='Pedido Tussor', required=False, widget=forms.TextInput(attrs={'type': 'number'})) ped_c...
hansroh/aquests
aquests/protocols/dns/pydns/__init__.py
Python
mit
2,174
0.00276
# -*- encoding: utf-8 -*- # $Id: __init__.py,v 1.8.2.10 2012/02/03 23:04:01 customdesigned Exp $ # # This file is part of the pydns project. # Homepage: http://pydns.sourceforge.net # # This code is covered by the standard Python License. See LICENSE for details. # # __init__.py for DNS class. __version__ = '2.3.6' ...
DNSError from .Lib import DnsResult from .Base import * from .Lib import * Error=DNSError from .lazy import * Request = DnsRequest Result = DnsResult # # $Log: __init__.py,v $ # Revision 1.8.2.10
2012/02/03 23:04:01 customdesigned # Release 2.3.6 # # Revision 1.8.2.9 2011/03/16 20:06:39 customdesigned # Refer to explicit LICENSE file. # # Revision 1.8.2.8 2011/03/03 21:57:15 customdesigned # Release 2.3.5 # # Revision 1.8.2.7 2009/06/09 18:05:29 customdesigned # Release 2.3.4 # # Revision 1.8.2.6 2008/0...
tanglei528/nova
nova/virt/disk/vfs/guestfs.py
Python
apache-2.0
8,034
0
# Copyright 2012 Red Hat, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from eventlet import tpool from nova impo...
ack.common import log as logging from nova.virt.disk.vfs import api as vfs LOG = logging.getLogger(__name__) guestfs = None class VFSGuestFS(vfs.VFS): """This class implements a VFS module that uses the libguestfs APIs to access the disk image. The disk image is never mapped into the host filesystem, ...
LibreTime/libretime
shared/tests/logging_test.py
Python
agpl-3.0
1,238
0.000808
from pathlib import Path import pytest from loguru import logger from libretime_shared.logging import ( DEBUG, INFO, create_task_logger,
level_from_name, setup_logger, ) @pytest.mark.parametrize( "name,level_name,level_no", [ ("error", "error", 40),
("warning", "warning", 30), ("info", "info", 20), ("debug", "debug", 10), ("trace", "trace", 5), ], ) def test_level_from_name(name, level_name, level_no): level = level_from_name(name) assert level.name == level_name assert level.no == level_no def test_level_from_name_i...
Nat1405/newer-nifty
setup.py
Python
mit
1,483
0.003372
# Based on STScI'
s JWST calibration pipeline. from __future__ import print_function import os import subprocess import sys from setuptools import setup, find_packages, Extensio
n, Command from glob import glob # Open the README as the package long description readme = open('README.rst', 'r') README_TEXT = readme.read() readme.close() NAME = 'Nifty4NIFS' SCRIPTS = glob('scripts/*') PACKAGE_DATA = { '': ['*.dat', '*.cfg', '*.fits', '*.txt'] } setup( name=NAME, version="1.0b5", ...
bezhermoso/home
lib/ansible/runner/action_plugins/assemble.py
Python
gpl-3.0
4,340
0.002995
# (c) 2013, Michael DeHaan <michael.dehaan@gmail.com> # Stephen Fromm <sfromm@gmail.com> # Brian Coca <briancoca+dev@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by...
ions when the copy is done as a different user if self.runner.sudo and self.runner.sudo_user != 'root': self.runner._low_level_exec_command(conn, "chmod a+r %s" % xfered, tmp) # run the copy module module_args = "%s src=%s dest=%s original_basename=%s" % (module_args...
rc))) if self.runner.noop_on_check(inject): return ReturnData(conn=conn, comm_ok=True, result=dict(changed=True), diff=dict(before_header=dest, after_header=src, after=resultant)) else: res = self.runner._execute_module(conn, tmp, 'copy', module_args, inject=inje...
ahmedshabib/evergreen-gainsight-hack
sentiment Analyser/samr/data.py
Python
mit
93
0
from c
ollections import namedtuple Datapoint = namedtuple("Datapoint", "phrase sentime
nt")
j16sdiz/hangups
hangups/test/test_channel.py
Python
mit
2,184
0.000936
import pytest from hangups import channel @pytest.mark.parametrize('input_,expected', [ (b'79\n[[0,["c","98803CAAD92268E8","",8]\n]\n,[1,[{"gsid":"7tCoFHumSL-IT6BHpCaxLA"}]]\n]\n', ('98803CAAD92268E8', '7tCoFHumSL-IT6BHpCaxLA') ), ]) def test_parse_sid_response(input_, expected): assert channel._par...
l.PushDataParser() # TODO: could detect errors like these with some extra work assert list(p.get_submissions('11\n0123456789\n5e\n"abc"'.encode())) == [ '01
23456789\n' ] def test_incremental(): p = channel.PushDataParser() assert list(p.get_submissions(''.encode())) == [] assert list(p.get_submissions('5'.encode())) == [] assert list(p.get_submissions('\n'.encode())) == [] assert list(p.get_submissions('abc'.encode())) == [] assert list(p.get...
drpngx/tensorflow
tensorflow/contrib/data/python/ops/unique.py
Python
apache-2.0
2,748
0.005459
# Copyright 2017 The TensorFlow Auth
ors. 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 agreed to in writing, sof...
istributed 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. # ============================================================================== """Unique element dataset tra...
Thuruv/pilgrim
blood/forms.py
Python
mit
537
0.007449
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout,Submit from .models import Details, F
eedback from crispy_forms.bootstrap import TabHolder, Tab from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions class AddmeForm(forms.ModelForm): class Meta: model = Details exclude = [''] """Forms for the ``feedback_form`` app.""" class FeedbackForm(fo
rms.ModelForm): class Meta: model = Feedback fields = ('email', 'message')
mrknow/filmkodi
script.mrknow.urlresolver/lib/urlresolver9/lib/net.py
Python
apache-2.0
12,168
0.002959
''' common XBMC Module Copyright (C) 2011 t0mm0 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. Th...
gent), log_utils.LOGDEBUG) kodi.set_setting('current_ua', user_agent) kodi.set_setting('last_ua_create', str(int(time.time()))) else: user_agent = kodi.get_setting('current_ua') return user_agent class Net: ''' This class wraps :mod:`urllib2` and provides an easy wa
y to make http requests while taking care of cookies, proxies, gzip compression and character encoding. Example:: from addon.common.net import Net net = Net() response = net.http_GET('http://xbmc.org') print response.content ''' _cj = cookielib.LWPCookieJar() _...
mlperf/training_results_v0.7
Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/tvm/vta/python/vta/testing/simulator.py
Python
apache-2.0
2,565
0.00039
# 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 this file except in compliance # with the License. You may obt...
# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing...
vespian/inventory_tool
inventory_tool/object/ippool.py
Python
apache-2.0
8,065
0.00062
#!/usr/bin/env python3 # Copyright (c) 2014 Pawel Rozlach, Brainly.com sp. z o.o. # # 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 re...
ip_address(ip)) else: msg = "An attempt to release an ip {0} ".format(ip) msg += "which has not been allocated yet." raise MalformedInputException(msg) def release_all(self): """Mark all ip addresses in the pool as available""" self._allocated = [] d...
""" return self._network.overlaps(other._network) def book(self, ip): """Prevent IP from being allocated. Marks given IP as reserved/unavailable for allocation. Args: ip: ip to book. Raises: MalformedInputException: ip does not belong to this pool ...
christi3k/zulip
zerver/tests/test_realm.py
Python
apache-2.0
10,099
0.000594
from __future__ import absolute_import from __future__ import print_function import ujson from django.http import HttpResponse from mock import patch from typing import Any, Dict, List, Text, Union from zerver.lib.actions import ( do_change_is_admin, do_set_realm_property, do_deactivate_realm, ) from ze...
t_patch('/json/realm', data) self.assert_json_success(result) realm = get_realm('zulip') self.assertEqual(realm.description, new_description) event = events[0]['event'] self.assertEqual(event, dict( type='realm', op='update', prope...
escription', value=new_description, )) def test_realm_description_length(self): # type: () -> None new_description = u'A' * 1001 data = dict(description=ujson.dumps(new_description)) # create an admin user email = 'iago@zulip.com' self.login(emai...
makinacorpus/django
django/utils/datastructures.py
Python
bsd-3-clause
14,882
0.001344
import copy from django.utils import six class MergeDict(object): """ A simple class for creating new "virtual" dictionaries that actually look up values in more than one dictionary, passed in the constructor. If a key appears in more than one of the given dictionaries, only the first occurrence ...
f).pop(k, *args) try: self.keyOrder.remove(k) exce
pt ValueError: # Key wasn't in the dictionary in the first place. No problem. pass return result def popitem(self): result = super(SortedDict, self).popitem() self.keyOrder.remove(result[0]) return result def _iteritems(self): for key in self.key...
ekopylova/tcga-1
python_scripts/cgc_create_tcga_workflow_task.py
Python
bsd-3-clause
20,620
0.000533
#!/usr/bin/env python #----------------------------------------------------------------------------- # Copyright (c) 2016--, Evguenia Kopylova, Jad Kanbar, SevenBridges dev team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software...
ll_files) # At least one FASTA file analyzed not found in mapping file if len(files_not_added) > 0:
logger.error( 'Following files missing in mapping file:\n') # Check missing files are duplicates of those that have been added files_accounted_for = 0 for _file in files_not_added: # Remove prefix _*_ which signifies duplicate regex = re.compile('_._') ...
ifwe/wxpy
src/tests/wxPythonTests/testGauge.py
Python
mit
2,410
0.005809
"""Unit tests for wx.Gauge. Methods yet to test: __init__, Create, Pulse""" import unittest import wx import wxtest import testControl class GaugeTest(testControl.ControlTest): def setUp(self): self.app = wx.PySimpleApp() self.frame = wx.Frame(parent=None) self.testControl = wx.Gauge(par...
# C++ docs state: # This method is not implemented (returns 0) for most platforms. def testShadowWidth(self): """SetShadowWidth, GetShadowWidth"
"" if wxtest.PlatformIsMac() or wxtest.PlatformIsGtk() or \ wxtest.PlatformIsWindows(): for i in range(self.testControl.GetRange()): self.testControl.SetShadowWidth(i) self.assertEquals(0, self.testControl.GetShadowWidth()) else: # ...
flaviovdf/tag_assess
src/scripts/PrecisionRecall.py
Python
bsd-3-clause
4,909
0.010593
#!/usr/bin/env python # -*- encoding: utf-8 from __future__ import division, print_function from tagassess.dao.helpers import FilteredUserItemAnnotations from tagassess.dao.pytables.annotations import AnnotReader from tagassess.index_creator import create_occurrence_index from tagassess.probability_estimates.precomput...
print(user, tag, precision, recall, hidden) def load_dict_from_file(fpath): '''Loads dictionary from file''' return_val = {} with open(fpath) as in_file: for line in in_file: spl = line.split('-') key = int(spl[0].strip()) value = set(int(x.strip()) for x...
(cross_val_folder): '''Loads cross validation dictionaries used for the experiment''' filter_fpath = os.path.join(cross_val_folder, 'user_item_filter.dat') user_items_to_filter = load_dict_from_file(filter_fpath) val_tags_fpath = os.path.join(cross_val_folder, 'user_val_tags.dat') user_val...
1flow/1flow
oneflow/core/migrations/0101_auto__add_historicalarticle.py
Python
agpl-3.0
62,707
0.007926
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'HistoricalArticle' db.create_table(u'core_historicalartic...
': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions'
: ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'co...
samuelcolvin/pydantic
pydantic/color.py
Python
mit
16,607
0.001505
""" Color definitions are used as per CSS3 specification: http://www.w3.org/TR/css3-color/#svg-color A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`. In these cases the LAST color when sorted alphabetically takes preferences, eg. Color((0, 255, 255)).as_name...
return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})' else: h, s, li, a = self.as_hsl_tuple(alpha=True) # type: ignore return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})' def as_hsl_tuple(self, *, alpha: Optional[bool] = None) -> HslColorTuple: """ ...
ge 0 to 1. NOTE: this is HSL as used in HTML and most other places, not HLS as used in python's colorsys. :param alpha: whether to include the alpha channel, options are None - (default) include alpha only if it's set (e.g. not None) True - always include alpha, False - a...
keyvank/pyglare
pyglare/image/frame.py
Python
mit
343
0.061224
class Frame: def __init__(self,width,height,color): self.width = width self.height = height self.data = [] for h in range(height): row = [] for w in range(width):
row.append(color) self.data.append(row) def clear(self,color): for h in range(self.height): for w in range(self.width): self.data[h][w]
= color
gem/oq-hazardlib
openquake/hazardlib/const.py
Python
agpl-3.0
4,670
0.000428
# The Hazard Library # Copyright (C) 2012-2017 GEM Foundation # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. #...
ENT = 'Inter event' #: Standard deviation representing ground shaking variability #: within a single event. INTRA_EVENT = 'Intra event' #: Total standard deviation, defined as the square root of the sum #: of inter- and intra-event squared standard deviations, represents #: the total ground shak...
ingIntensityModel.get_poes`). TOTAL = 'Total'
toomastahves/math-pg
pkmkt2_code/task6.py
Python
unlicense
625
0.0096
from sympy import symbols, diff, N, Matrix import numpy as np from task4 import get_euler_dt X1, X2, X3 = symbols('X1 X2 X3') def get_vorticity_tensor(eq1, eq2, eq3): vkl = get_euler_dt(eq1, eq2, eq3) wkl = 0.5*(vkl - np.transpose(vkl)) return N(Matrix(wkl), 2) def get_vorticity_components(eq1, eq2, eq3)...
eq3) # Tuple, indexes from 0 to 8 w1 = wkl[7] - wkl[5] w2 = wkl[6] - wkl[2] w3 = wkl[3] - wkl[1] return [w1, w2, w3] #from testdata import eq1, eq2, eq3 #print
(get_vorticity_tensor(eq1, eq2, eq3)) #print(get_vorticity_components(eq1, eq2, eq3))