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
qgis/QGIS-Django
qgis-app/layerdefinitions/admin.py
Python
gpl-2.0
618
0
from django.contrib import admin from layerdefinitions.models import LayerDefinition, Review class LayerDefinitionInline(admin.TabularInline): model = Review list_display = ('review_date', 'comment', 'reviewer') @admin.register(LayerDefinition) class LayerDefinitionAdmin(admin.ModelAdmin): inlines = [L
ayerDefinitionInline
, ] list_display = ('name', 'description', 'creator', 'upload_date',) search_fields = ('name', 'description', 'provider') @admin.register(Review) class LayerDefinitionReviewAdmin(admin.ModelAdmin): list_display = ('resource', 'reviewer', 'comment', 'review_date',)
hexforge/pulp_db
src/pulp_db/kds/kds_pyapi.py
Python
apache-2.0
7,543
0.005568
import os from cffi import FFI ffi = FFI() # This is just a placeholder for the c implementation. # Some of it is thinking of the c and is not very pythony. # We are thinkling alot about chunking the data. # Stored separately to be more continuous. Meta gets queried. # overall_meta # meta1 # meta2 # meta3 # meta4 # me...
ref)) def le(self, ref): assert(self.query_context) return int(self.query_context.le(self.query_context, ref)) # Really this is all just number series. # Comparisons and joins etc. # Do do this better than conventional db we ne
ed meta. # Can do lots here have consitancy.
waxkinetic/fabcloudkit
fabcloudkit/tool/nginx.py
Python
bsd-3-clause
6,961
0.003735
""" fabcloudkit Functions for managing Nginx. This module provides functions that check for installation, install, and manage an installation of, Nginx. /etc/init.d/nginx: The "init-script" that allows Nginx to be run automatically at system startup. The existence of this file is ...
{log_ro
ot}/ngerror.log; location / {{ proxy_pass {proxy_pass}; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body...
juswilliams/bioscripts
CpG_by_feature/cpg_gene.py
Python
gpl-3.0
3,970
0.004282
#!/usr/bin/env python ''' Purpose: This script, using default values, determines and plots the CpG islands in relation to a given feature "type" (e.g. "gene" or "mRNA") from a GFF file which corresponds to the user-provided fasta file. Note: CpG Islands are determined by ObEx = (Observed CpG) / (Expected CpG) , def...
(potential CpG island) instances SeqRecList = cpgmod.compute(SeqRecord, Step, NumOfChunks, WinSize) MergedRecs = MergedRecs + SeqRecList # Create GFF DB GffDb = gffutils.create_db(GffFile, dbfn='GFF.db', force=True, keep_order=True, merge_strategy='merge', sort_attribute_values=Tr...
ue, disable_infer_genes=True) print "\nGFF Database Created...\n" # Filter out SeqRec below threshold DistArr = [] for Rec in MergedRecs: Cond1 = Rec.expect() > 0 if Cond1 == True: ObEx = (Rec.observ() / Rec.expect()) Cond2 = ObEx > ObExthresh Cond3 =...
EOSIO/eos
tests/restart-scenarios-test.py
Python
mit
5,013
0.011969
#!/usr/bin/env python3 from testUtils import Utils from Cluster import Cluster from WalletMgr import WalletMgr from TestHelper import TestHelper import random ############################################################### # restart-scenarios-test # # Tests restart scenarios for nodeos. Uses "-c" flag to indicate "...
se random.seed(seed) # Use a fixed seed for repeatability. cluster=Cluster(walletd=True) walletMgr=WalletMgr(True) try: TestHelper.printSystemInfo("BEGIN") cluster.setWalletMgr(walletMgr) cluster
.setChainStrategy(chainSyncStrategyStr) cluster.setWalletMgr(walletMgr) cluster.killall(allInstances=killAll) cluster.cleanup() walletMgr.killall(allInstances=killAll) walletMgr.cleanup() Print ("producing nodes: %d, topology: %s, delay between nodes launch(seconds): %d, chain sync strategy: %...
rustychris/freebird
software/freebird/datafile.py
Python
gpl-2.0
12,288
0.018066
""" Parse binary output files from freebird logger """ import os import numpy as np import re from numpy.lib import recfunctions import datetime from matplotlib.dates import date2num from contextlib import contextmanager from collections import namedtuple import array_append import derived import netCDF4 def freebird_...
""" Because the data files are often on removeable media, and keeping a file open might be a headache when trying to remove the media, extra care is
taken to only have the file open while it is actively read. Any access to self.fp should be through the opened context manager, which can be nested if necessary """ if self.fp is None: self.fp=open(self.filename,'rb') yield self.fp self.fp.cl...
eli261/jumpserver
apps/authentication/backends/openid/urls.py
Python
gpl-2.0
278
0
# -*- coding: utf-8 -*- # from django.urls import
path from . import views urlpatterns = [ path(
'login/', views.OpenIDLoginView.as_view(), name='openid-login'), path('login/complete/', views.OpenIDLoginCompleteView.as_view(), name='openid-login-complete'), ]
takumak/tuna
src/sessionfilemanager.py
Python
mit
192
0.015625
import umsgpack from configfilemanager im
port ConfigFileManagerBase class SessionFileManager(ConfigFileManagerBase)
: @classmethod def convertVersion(cls, obj, version): return obj
open-risk/portfolio_analytics_library
portfolioAnalytics/utils/portfolio.py
Python
gpl-2.0
2,867
0.004534
# encoding: utf-8 # (c) 2019 Open Risk (https://www.openriskmanagement.com) # # portfolioAnalytics is licensed under the Apache 2.0 license a copy of which is included # in the source distribution of correlationMatrix. This is notwithstanding any licenses of # third-party software included in this distribution. You ma...
:param psize: initialization values :param rating: list of default proba
bilities :param exposure: list of exposures (numerical values, e.g. `Exposure At Default <https://www.openriskmanual.org/wiki/Exposure_At_Default>`_ :param factor: list of factor indices (those should match the factors used e.g. in a correlation matrix :type psize: int :type rating: list...
NeCTAR-RC/horizon
openstack_dashboard/dashboards/identity/users/tables.py
Python
apache-2.0
7,853
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 # distributed under t...
" verbose_name = _("Create User") url = "horizon:identity:users:create" classes = ("ajax-modal",) icon = "plus" policy_rules = (('identity', 'ident
ity:create_grant'), ("identity", "identity:create_user"), ("identity", "identity:list_roles"), ("identity", "identity:list_projects"),) def allowed(self, request, user): return api.keystone.keystone_can_edit_user() class EditUserLink(policy.Poli...
benjello/openfisca-france-indirect-taxation
openfisca_france_indirect_taxation/examples/transports/plot_legislation/plot_ticpe_accises.py
Python
agpl-3.0
865
0.003497
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 15:48:31 2015 @author: thomas.douenne """ # L'objectif est de décrire l'évolution des montants des accises de la TICPE depuis 1993 # Import de fonctions
spécifiques à Openfisca Indirect Taxation from openfisca_france_indirect_taxation.examples.utils_example import graph_builder_bar_list from openfisca_france_indirect_taxation.examples.dataframes_from_legislation.get_accises import \ get_accise_ticpe_majoree # Recherche des paramètres de la législation liste = ['ti...
_bar_list(df_accises['accise majoree sans plomb'], 1, 1) graph_builder_bar_list(df_accises['accise majoree diesel'], 1, 1) graph_builder_bar_list(df_accises['accise majoree super plombe'], 1, 1)
thauser/pnc-cli
pnc_cli/swagger_client/models/license.py
Python
apache-2.0
5,572
0.000718
# coding: utf-8 """ Copyright 2015 SmartBear Software 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...
tr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dic
t()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str()
allotria/intellij-community
python/testData/inspections/PyUnresolvedReferencesInspection/PrefixExpressionOnClassHavingSkeletons/numpy/core/multiarray.py
Python
apache-2.0
8,049
0.001242
def array(p_object, dtype=None, copy=True, order=None, subok=False, ndmin=0): # real signature unknown; restored from __doc__ """ array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0) Create an array. Parameters ---------- object : array_like An arr...
ndim : int The array's number of dimensions. shape : tuple of ints Shape of the array. strides : tuple of ints The step-size required to move from one element to the next in memory. For example, a contiguous ``(3, 4)`` array of type ``...
row-to-row, one needs to jump 8 bytes at a time (``2 * 4``). ctypes : ctypes object Class containing properties of the array needed for interaction with ctypes. base : ndarray If the array is a view into another array, that array is its `base` ...
csningli/MultiAgent
examples/simple_move/simple_move_sim.py
Python
apache-2.0
2,835
0.017637
# MultiAgent # (c) 2017-2019, NiL, csningli@gmail.com import sys, random, datetime, math random.seed(datetime.datetime.now()) sys.path.append("../..") from mas.multiagent import * AREA_SIZE = 200 POS_ERROR = 5 MIN_SPEED = 100 MAX_SPEED = 500 class TargetModule(Module) : def __init__(self) : super(Targ...
m.read("pos", None) if target is not None and pos is not None: diff = vec2_sub(target, pos) resp.add_msg(Message(key = "angle", value = vec2_angle(diff))) resp.add_msg(Message
(key = "vel", value = vec2_min_max(vec2_scale(diff, 3), MIN_SPEED, MAX_SPEED))) super(SimpleMoveModule, self).act(resp) class SimpleMoveAgent(Agent) : def __init__(self, name) : super(SimpleMoveAgent, self).__init__(name) self.mods = [SimpleMoveModule(), TargetModule()] def focus(sel...
slackhq/python-slackclient
integration_tests/samples/openid_connect/sanic_example.py
Python
mit
4,583
0.002618
import json import jwt import logging import os logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) client_id = os.environ["SLACK_CLIENT_ID"] client_secret = os.environ["SLACK_CLIENT_SECRET"] redirect_uri = os.environ["SLACK_REDIRECT_URI"] scopes = ["openid", "email", "profile"] from slack_...
eq.args.get("state") if state_store.consume(state):
code = req.args.get("code") try: token_response = await AsyncWebClient().openid_connect_token( client_id=client_id, client_secret=client_secret, code=code ) logger.info(f"openid.connect.token response: {token_response}") ...
Distrotech/bzr
bzrlib/tests/commands/test_update.py
Python
gpl-2.0
1,571
0.000637
# Copyright (C) 2007, 2009, 2010 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is dis...
and_tree('local') remote_branch = branch.Branch.open(self.get_url('remote')) local_wt.branch.bind(remote_branch) remote_wt.commit('empty commit') self.start_logging_connections() update = builtins.cmd_update() # update ne
eds the encoding from outf to print URLs update.outf = tests.StringIOWrapper() # update calls it 'dir' where other commands calls it 'directory' update.run(dir='local') self.assertEquals(1, len(self.connections))
simplegeo/sqlalchemy
lib/sqlalchemy/orm/interfaces.py
Python
mit
37,723
0.003181
# interfaces.py # Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010 Michael Bayer # mike_mp@zzzcomputing.com # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ Semi-private module containing various base classes used throughout the ORM....
xt, row, instance, result, **flags): """Receive an object instance before that instance is appended to a result list. If this method returns EXT_CONTINUE, result appending will proceed normally. if this method returns any other value or None, result app...
this instance, giving this extension an opportunity to do the appending itself, if desired. mapper The mapper doing the operation. selectcontext The QueryContext generated from the Query. row The result row from the database. instance ...
nkgilley/home-assistant
tests/components/airly/__init__.py
Python
apache-2.0
23
0
""
"Tests for Airly.
"""
pniedzielski/fb-hackathon-2013-11-21
src/pythonCode.py
Python
agpl-3.0
155
0.03871
import sys for m
in range(0, 2): n = raw_input() for i in range(0, int(n)): print "\x11" + str(m) + ": " + raw_input() + "\x11" #sys.stdout.f
lush()
resurtm/recarguide
backend/cars/search/elastic.py
Python
mit
2,295
0
import datetime from django.conf import settings from elasticsearch import Elasticsearch instance = Elasticsearch([settings.ELASTICSEARCH_DSN]) index_prefix = 'recarguide_' def indices(): items = ['car'] return ['{}{}'.format(index_prefix, index) for index in items] def mappings(): items = { '...
: car.trim_name, 'category': category, 'subcategory': subcategory, 'price': car.price, 'year': car.year, 'car': car.mileage, 'description': car.description} def reind
ex_car(car): body = encode_car(car) body['timestamp'] = datetime.datetime.now() instance.index(index='{}car'.format(index_prefix), doc_type='{}car_type'.format(index_prefix), id=car.id, body=body) def search_cars(query_body, query='search'): ret...
joansalasoler/auale
src/auale/gui/widgets/board_animator.py
Python
gpl-3.0
7,553
0
# -*- coding: utf-8 -*- # Aualé oware graphic user interface. # Copyright (C) 2014-2020 Joan Sala Soler <contact@joansala.com> # # 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...
}') transition = Capture(house) transition.set_delay(step * self.__STEP_DELAY) transition.connect('started', self.capture
_animation.emit) self._push_transition(transition, match) return steps + len(houses) def _push_harvest_transitions(self, steps, match): """Add animations to harvest seeds onto the player's homes""" current = match.get_board() previous = match.get_board(-2) hous...
ajrichards/GenesDI
genesdi/qtlib/LeftDock.py
Python
gpl-3.0
7,251
0.008413
#!/usr/bin/python ''' Cytostream LeftDock Adam Richards adamricha@gmail.com ''' import sys,os from PyQt4 import QtGui,QtCore if hasattr(sys,'frozen'): baseDir = os.path.dirname(sys.executable) baseDir = re.sub("MacOS","Resources",baseDir) else: baseDir = os.path.dirname(__file...
ctor(fileList,parent=mainWindow.dockWidget, selectionFn=mainWind
ow.set_selected_file, fileDefault=mainWindow.log.log['selectedFile'], showModelSelector=showModelSelector,modelsRun=modelsRun) mainWindow.fileSelector.setAutoFillBackground(True) subsamplingDefault = mainWindow...
blueset/ehForwarderBot
ehforwarderbot/wizard.py
Python
agpl-3.0
28,382
0.002537
# -*- coding: utf-8 -*- """ Interactive wizard to guide user to set up EFB and modules. Since newer version of pip (>=9.0), which checks Python version prior to installation, is already widespread, we are dropping Python version check in wizard script, and assuming user is running an appropriate Python version. """ i...
====================\n" "# \n" "# This file determines what modules, including master channel, slave channels,\n" "# and middlewares, are enabled in this profile.\n" "# \n" "# \n" "# Master Channel\n" "# --------------\n" "#...
) config += "\nmaster_channel:\n\n" # TRANSLATORS: This part of text must be formatted in a monospaced font, and all lines must not exceed the width of a 70-cell-wide terminal. config += _( "# Slave Channels\n" "# --------------\n" "# \n" ...
ESEGroup/Paraguai
repositorios_memoria/__init__.py
Python
apache-2.0
98
0
from .usuar
io import RepositorioUsuarioEmMemoria fro
m .recurso import RepositorioRecursoEmMemoria
bskari/sparkfun-avc
control/extension_waypoint_generator.py
Python
mit
2,933
0
"""Implements the WaypointGenerator interface. Returns waypoints from a KML file. All WaypointGenerator implementations should have two methods: get_current_waypoint(self, x_m, y_m) -> (float, float) get_raw_waypoint(self) -> (float, float) reached(self, x_m, y_m) -> bool next(self) done(self) -> bo...
from control.telemetry import Telemetry from control.simple_waypoint_generator import SimpleWaypointGenerator class ExtensionWaypointGenerator(SimpleWaypointGenerator): """Generates waypoints extending through the actual waypoint to try to reduce oscillating. """ BEYOND_M = 5.0 BEYOND_M_2 = BEYO...
_init__(waypoints) self._extension_waypoint = waypoints[0] def get_current_waypoint(self, x_m, y_m): """Returns the current waypoint as projected BEYOND_M past.""" return self._extension_waypoint def next(self): """Goes to the next waypoint.""" super(ExtensionWaypointGe...
hankcs/HanLP
hanlp/metrics/parsing/span.py
Python
apache-2.0
3,222
0.00031
# MIT License # # Copyright (c) 2020 Yu Zhang # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, pub...
.2%} UF: {self.uf:.2%} " s += f"LP: {self.lp:.2%} LR: {self.lr:.2%} LF: {self.lf:.2%}" return s @property def score(self): return self.lf @property def ucm(self): return self.n_ucm / (self.n + self.eps) @property def lcm(s
elf): return self.n_lcm / (self.n + self.eps) @property def up(self): return self.utp / (self.pred + self.eps) @property def ur(self): return self.utp / (self.gold + self.eps) @property def uf(self): return 2 * self.utp / (self.pred + self.gold + self.eps) ...
plivo/plivo-python
tests/xml/test_sElement.py
Python
mit
2,927
0.00205
from unittest import TestCase from plivo import plivoxml from tests import PlivoXmlTestCase class SElementTest(TestCase, PlivoXmlTestCase): def test_set_methods(self): expected_response = '<Response><Speak><s><break strength="strong"/>' \ '<emphasis level="strong">This is Test...
>This is Test</w></s></Speak></Response>' content_break = 'This is Test' stre
ngth_break = 'strong' time_break = '250ms' content_lang = 'This is Test' xmllang_lang = "it" content_emphasis = 'This is Test' level_emphasis = 'strong' content_phoneme = 'This is Test' alphabet_phoneme = "ipa" ph_phoneme = "t&#x259;mei&#x325;&#x27E;ou&...
mitsei/dlkit
tests/resource/test_record_templates.py
Python
mit
1,495
0.005351
"""Unit tests of resource records.""" import pytest from ..utilities.general import is_never_authz, is_no_authz, uses_cataloging, uses_filesystem_only @pytest.mark.usefixtures("resource_record_class_fixture", "resource_record_test_fixture") class TestResourceRecord(object): """Tests for ResourceRecord""" @p...
k.usefixtures("bin_query_record_class_fixture", "bin_query_record_test_fixture") class TestBinQueryRecord(object): """Tests for BinQueryRecord""" @pytest.mark.usefixtures("bin_form_record_class_fixture", "bin_form_record_test_fixture") class TestBinFormRecord(object): """Tests for Bi
nFormRecord""" @pytest.mark.usefixtures("bin_search_record_class_fixture", "bin_search_record_test_fixture") class TestBinSearchRecord(object): """Tests for BinSearchRecord"""
Acehaidrey/incubator-airflow
tests/providers/amazon/aws/operators/test_s3_file_transform.py
Python
apache-2.0
5,277
0.000758
# # 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...
source_s3_key=input_path, dest_s3_key=output_path, transform_script=self.transform_script, script_args=script_args, replace=True, task_id="task_id", ) op.execute(None) assert script_args == mock_popen.call_args[0][0][3:] @mock.pat...
mazon.aws.hooks.s3.S3Hook.select_key', return_value="input") @mock_s3 def test_execute_with_select_expression(self, mock_select_key): input_path, output_path = self.s3_paths() select_expression = "SELECT * FROM s3object s" op = S3FileTransformOperator( source_s3_key=input_pa...
Akagi201/learning-python
flask/Flask-Script/test1/app/__init__.py
Python
mit
80
0
from flask import Flask app = Flask(__name__) a
pp.config.from_object('config')
linkedin/indextank-service
storefront/templatetags/google_analytics.py
Python
apache-2.0
2,712
0.002581
""" Google Analytics template tags and filters. """ from __future__ import absolute_import import re from django.template import Library, Node, TemplateSyntaxError from templatetags.utils import is_internal_ip, disable_html, get_required_setting SCOPE_VISITOR = 1 SCOPE_SESSION = 2 SCOPE_PAGE = 3 PROPERTY_ID_RE = ...
scope = var[2] except IndexError: scope = SCOPE_PAGE commands.append(CUST
OM_VAR_CODE % locals()) return commands def contribute_to_analytical(add_node): GoogleAnalyticsNode() # ensure properly configured add_node('head_bottom', GoogleAnalyticsNode)
OCA/l10n-switzerland
ebill_paynet/models/ebill_payment_contract.py
Python
agpl-3.0
1,855
0.001078
# Copyright 2019 Camptocamp SA # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import _, api, fields, models from odoo.exceptions import ValidationError class EbillPaymentContract(models.Model): _inherit = "ebill.payment.contract" paynet_account_number = fields.Char(string="Paynet ...
od_id", "paynet_service_id") def _check_paynet_service_id(self): for contract in self: if contract.is_paynet_contract and not contract.paynet_service_id: raise ValidationErr
or( _("A Paynet service is required for a Paynet contract.") )
Cadasta/cadasta-platform
cadasta/organization/serializers.py
Python
agpl-3.0
10,962
0
from django.conf import settings from django.db.models import Q from django.core.urlresolvers import reverse from core.util import slugify from django.utils.translation import ugettext as _ from rest_framework import serializers from rest_framework_gis import serializers as geo_serializers from django_countries.seriali...
ProjectRole from .forms import create_update_or_delete_project_role class OrganizationSerializer(core_serializers.SanitizeF
ieldSerializer, core_serializers.DetailSerializer, core_serializers.FieldSelectorSerializer, serializers.ModelSerializer): users = UserSerializer(many=True, read_only=True) class Meta: model = Organization fi...
romank0/kombu
kombu/log.py
Python
bsd-3-clause
4,115
0
from __future__ import absolute_import import os import logging import sys from logging.handlers import WatchedFileHandler from .five import string_t from .utils import cached_property from .utils.encoding import safe_repr, safe_str from .utils.functional import maybe_promise __all__ = ['LogMixin', 'LOG_LEVELS', 'g...
ormat(args[0], expand)), **kwargs) else: return self.logger.log( severity, self.annotate(' '.join(map(safe_str, args))), **kwa
rgs) def get_logger(self): return get_logger(self.logger_name) def is_enabled_for(self, level): return self.logger.isEnabledFor(self.get_loglevel(level)) def get_loglevel(self, level): if not isinstance(level, int): return LOG_LEVELS[level] return level @c...
Laurawly/tvm-1
python/tvm/topi/gpu/conv2d_nhwc.py
Python
apache-2.0
5,436
0.000368
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
d_reference_log(
target.kind.name, target.model, "conv2d_nhwc.gpu" ) cfg.fallback_with_reference_log(ref_log) tile_n = cfg["tile_n"].val tile_c = cfg["tile_c"].val num_thread_n = cfg["num_thread_n"].val num_thread_c = cfg["num_thread_c"].val vthread_n = cfg["vthread_n"].val vthread_c = cfg...
mikeakohn/naken_asm
tests/disasm/pic32.py
Python
gpl-3.0
2,606
0.023024
#!/usr/bin/env python3 import os, sys reg_nums = [] instructions = [] errors = 0 alias = [ "move", "negu", "not" ] # -------------------------- fold here ----------------------------- print("Disassembler: PIC32") for i in range(0, 32): reg_nums.append("$" + str(i)) fp = open("../comparison/pic32.txt", "r") out...
[0].split()[0] if a[0] in [ "di", "ei" ]: continue a[0] = a[0].split()[1] b[0] = b[0].split()[1] broken = False if len(a) != len(b) or name_a != name_b:
print(name_a + " " + name_b) broken = True else: for j in range(0, len(a)): a[j] = a[j].strip() b[j] = b[j].strip() if a[j] != b[j]: if not " " in a[j] and "(" in a[j] and a[j][0] != '(' and \ not " " in b[j] and "(" in b[j] and b[j][0] != '(': ...
goshow-jp/Kraken
Python/kraken_components/fabrice/fabrice_clavicle.py
Python
bsd-3-clause
7,805
0.004356
from kraken.core.maths import Vec3 from kraken.core.maths.xfo import Xfo from kraken.core.objects.components.base_example_component import BaseExampleComponent from kraken.core.objects.attributes.attribute_group import AttributeGroup from kraken.core.objects.attributes.scalar_attribute import ScalarAttribute from kra...
f __init__(self, name='clavicle', parent=None):
super(FabriceClavicle, self).__init__(name, parent) # =========== # Declare IO # =========== # Declare Inputs Xfos self.spineEndInputTgt = self.createInput('spineEnd', dataType='Xfo', parent=self.inputHrcGrp).getTarget() # Declare Output Xfos self.clavicleOut...
bssrdf/SparseLSH
sparselsh/__init__.py
Python
mit
277
0
# This module is part of
lshash and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php __title__ = 'sparselsh' __author__ = 'Brandon Roberts (brandon@bxroberts.org)' __license__ = 'MIT' __version__ = '0.0.2' from sparselsh.lsh import
LSH
jawilson/home-assistant
tests/components/denonavr/test_media_player.py
Python
apache-2.0
3,970
0.000252
"""The tests for the denonavr media player platform.""" from unittest.mock import patch import pytest from homeassistant.components import media_player from homeassistant.components.denonavr.config_flow import ( CONF_MANUFACTURER, CONF_MODEL, CONF_SERIAL_NUMBER, CONF_TYPE, DOMAIN, ) from homeassis...
d(hass, client): """Test generic command functionality.""" await setup_denonavr(hass) data = { ATTR_ENTITY_ID: ENTITY_ID, ATTR_COMMAND: "test_command", } await hass.services.async_call(DOMAIN, S
ERVICE_GET_COMMAND, data) await hass.async_block_till_done() client.async_get_command.assert_awaited_with("test_command") async def test_dynamic_eq(hass, client): """Test that dynamic eq method works.""" await setup_denonavr(hass) data = { ATTR_ENTITY_ID: ENTITY_ID, ATTR_DYNAMIC_...
mancoast/CPythonPyc_test
cpython/221_test_descr.py
Python
gpl-3.0
81,788
0.007947
# Test enhancements related to descriptors and new-style classes from test_support import verify, vereq, verbose, TestFailed, TESTFN from copy import deepcopy def veris(a, b): if a is not b: raise TestFailed, "%r is %r" % (a, b) def testunop(a, res, expr="len(a)", meth="__len__"): if verbose: print "...
f dicts(): if verbose: print "Testing dict operations..." testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__") testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__") testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__") d = {1:2,3:4} l1 = [] f...
r i in d.__iter__(): l.append(i) vereq(l, l1) l = [] for i in dict.__iter__(d): l.append(i) vereq(l, l1) d = {1:2, 3:4} testunop(d, 2, "len(a)", "__len__") vereq(eval(repr(d), {}), d) vereq(eval(d.__repr__(), {}), d) testset2op({1:2,3:4}, 2, 3, {1:2,2:3,3:4}, "a[b]=c", "__setitem__")...
ddboline/Garmin-Forerunner-610-Extractor_fork
ant/fs/test/commandpipe_test.py
Python
mit
1,838
0.005985
# Ant-FS # # Copyright (c) 2012, Gustav Tiger <gustav@tiger.name> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy...
# Test create file data = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09] request = CreateFile(len(data), 0x80, [0x04, 0x00, 0x00], [0x00, 0xff, 0xff]) print request print request.get() # Test create file response response_data = array.array('B', [2, 0, 0, 0, 4, 0, 0, 0, 128, 4, 1...
onse.get_data_type() == 0x80 #FIT assert response.get_identifier() == array.array('B', [4, 123, 0]) assert response.get_index() == 103
woolfson-group/isambard
isambard/external_programs/reduce.py
Python
mit
7,041
0.000142
"""This module provides an interface to the program Reduce. Requires the reduce executable and reduce_wwPDB_het_dict.txt located in a directory specified in global_settings. These can be downloaded from: http://kinemage.biochem.duke.edu/software/reduce.php For more information on Reduce, see [1]. References --------...
Using the original structure.") if path: reduced_mmol = input_path.read_text() else: reduced_mmol = input_file reduce_message = reduce_output.stderr.decode() if 'could not open' in reduce_message: print('Caution: the Reduce connectivity dictionary could not be ' ...
def reduce_output_path(path=None, pdb_name=None): """Defines location of Reduce output files relative to input files.""" if not path: if not pdb_name: raise NameError( "Cannot save an output for a temporary file without a PDB" "code specified") pdb_na...
sdiazpier/nest-simulator
testsuite/pytests/test_facetshw_stdp.py
Python
gpl-2.0
5,894
0
# -*- coding: utf-8 -*- # # test_facetshw_stdp.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 Lice...
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 14, 15] lut_1 = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13] lut
_2 = range(16) # identity config_0 = [0, 0, 1, 0] config_1 = [0, 1, 0, 0] reset_pattern = 6 * [1] # reset all # individual parameters for each synapse # reached every 36 runs (e^(-10/20) = 21.83510375) lut_th_causal = 21.835 lut_th_acausal = lut_th_causal ...
TomiBelan/fetchrev
syncgit.py
Python
apache-2.0
5,005
0.001399
#!/usr/bin/env python2 # Copyright 2012 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 require...
for hash in revs: batch_checker.std
in.write(hash + '^{}\n') result = batch_checker.stdout.readline() if not result.endswith('missing\n'): existing_revs.append(hash) batch_checker.stdin.close() batch_checker.wait() return existing_revs def local(input, output, args): local_root, remote_root = args pickle....
tbielawa/sphinxcontrib-showterm
docsite/source/conf.py
Python
apache-2.0
8,592
0.005703
# -*- coding: utf-8 -*- # # Juicer documentation build configuration file, created by # sphinx-quickstart on Thu May 21 00:27:23 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # Al...
unc: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by d
efault. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Opti...
ganwell/dht3k
setup.py
Python
mit
1,441
0
#!/usr/bin/env python import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst').read() doclink = """ Documentation ------------- The full...
ht3k', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming...
'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: PyPy', ], )
scrollback/kuma
kuma/users/providers/github/views.py
Python
mpl-2.0
1,715
0
import requests from allauth.account.utils import get_next_redirect_url from allauth.socialaccount.providers.oauth2.views import (OAuth2LoginView, OAuth2CallbackView) from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter from kuma.core.u...
dresses'] = email_data.json() return self.get_provider().sociallogin_from_response(request, extra_data) class KumaOAuth2LoginView(OAuth2LoginView): def dispatch(self, request): next_url = (get_next_redirect_url(request) or ...
on['sociallogin_next_url'] = next_url request.session.modified = True return super(KumaOAuth2LoginView, self).dispatch(request) oauth2_login = KumaOAuth2LoginView.adapter_view(KumaGitHubOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(KumaGitHubOAuth2Adapter)
rutsky/pytest-pylint
setup.py
Python
mit
906
0
# -*- coding: utf-8 -*- """ pytest-pylint ============= Plugin for py.test for doing pylint tests """ from setuptools import setup setup( name='pytest-pylint', des
cription='pytest plugin to check source code with pylint', long_description=open("README.rst").read(), license="MIT", version='0.3.0', author='Carson Gee', author_email='x@carsongee.com', url='https://github.com/carsongee/pytest-pylint', py_modules=['pytest_pylint'], e
ntry_points={'pytest11': ['pylint = pytest_pylint']}, install_requires=['pytest>=2.4', 'pylint', 'six'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2....
mef51/plawt
examples/subplotstest.py
Python
mit
1,910
0.014136
#!/usr/bin/python3 import numpy as np import matplotlib.pyplot as plt import plawt import matplotlib as mpl x = np.linspace(0, 2 * np.pi, 400) y = np.sin(x ** 2) ##### Vanilla Matplotlib ##### # Three subplots sharing both x/y axes # f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True, sharey=True) f, (ax1, ax2, ax3) ...
tter(x, 2 * y ** 2 - 1, color='r') ax1.set_title('panel a', fontsize=12) ax2.set_title('panel b', fontsize=12) ax3.set_title('pan
el c', fontsize=12) ax1.minorticks_on() # Fine-tune figure; make subplots close to each other and hide x ticks for # all but bottom plot. f.subplots_adjust(hspace=0.3, wspace=0) plt.savefig('subplotcompare.png') plt.close() ##### Same plot but with plawt ##### subtitledict = {'verticalalignment': 'center'} plawt.plot...
GrandComicsDatabase/django-templatesadmin
templatesadmin/edithooks/gitcommit.py
Python
bsd-3-clause
2,280
0.005263
from django import forms from django.utils.translation import ugettext_lazy as _ from templatesadmin import TemplatesAdminException from templatesadmin.edithooks import TemplatesAdminHook import subprocess import os, sys class GitCommitHook(TemplatesAdminHook): ''' Commit to git after saving ''' @cla...
finally: proc.stderr.close() msg = stderr_value.decode(enc).rstrip() if status !
= 0: if status == 1 and msg == '': if 'nothing to commit' in stdout_value: msg = 'nothing to commit' raise TemplatesAdminException(_("Error while executing %(command)s: %(msg)s") % dict( command=command, ...
birkelbach/python-canfix
canfix/messages/__init__.py
Python
gpl-2.0
1,516
0
#!/usr/bin/env python # CAN-FIX Protocol Module - An Open Source Module that abstracts communication # with the CAN-FIX Aviation Protocol # Copyright (c) 2012 Phil Birkelbach # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as publishe...
ith this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. from .nodealarm import NodeAlarm from .parameter import Parameter from .twoway import TwoWayMsg from .nodespecific import * from .nodeidentification import NodeIdentification from .bitrate...
t DisableParameter, EnableParameter from .nodereport import NodeReport from .nodestatus import NodeStatus from .updatefirmware import UpdateFirmware from .twowayconnection import TwoWayConnection from .nodeconfiguration import NodeConfigurationSet, NodeConfigurationQuery from .nodedescription import NodeDescription fro...
aleaf/pest_tools
res.py
Python
mit
16,441
0.010644
import numpy as np import pandas as pd import matplotlib.pyplot as plt import math class Res: def __init__(self, res_file): ''' Res Class Parameters ---------- res_file : str Path to .res or .rei file from PEST Attributes ---------- df : Pandas ...
ighted Residual'].values.max() std_w_res = group_df['Weighted Residual'].values.std() range_w_res = max_w_res - min_w_res # Absolute Residual Stats mean_abs_res = group_df['Absolute Residual'].values.mean() min_abs_res = group_df['Absolute Residua...
_df['Absolute Residual'].values.std() range_abs_res = max_abs_res - min_abs_res # Root Mean Square Error rmse = math.sqrt(((group_df['Residual'].values)**2).mean()) # RMSE/measured range if range_measured > 0.0: rmse_o...
jaumemarti/l10n-spain-txerpa
l10n_es_aeat_mod347/__openerp__.py
Python
agpl-3.0
5,103
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) # 2004-2011: Pexego Sistemas Informáticos. (http://pexego.es) # 2012: NaN·Tic (http://www.nan-tic.com) # 2013: Acysos (http://www.acysos.com) # ...
####################################### { 'name': "AEAT Model 347", 'version': "1.1", 'author': "Spanish Localization Team", 'website': "https://launchpad.net/openerp-spain", 'contributors': [ 'Pexego (http://www.pexego.es)', 'ASR-OSS (http://www.asr-oss.com)', 'NaN·tic (http...
'Joaquín Gutierrez (http://gutierrezweb.es)', ], 'category': "Localisation/Accounting", 'description': """ Presentación del Modelo AEAT 347 ================================ (Declaración Anual de Operaciones con Terceros) Basado en la Orden EHA/3012/2008, de 20 de Octubre, por el que se aprueban los diseñ...
tswast/google-cloud-python
texttospeech/google/cloud/texttospeech_v1beta1/__init__.py
Python
apache-2.0
1,400
0
# -*- coding: utf-8 -*- # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #
ERROR: type should be string, got " https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing per"
missions and # limitations under the License. from __future__ import absolute_import import sys import warnings from google.cloud.texttospeech_v1beta1 import types from google.cloud.texttospeech_v1beta1.gapic import enums from google.cloud.texttospeech_v1beta1.gapic import text_to_speech_client if sys.version_info...
mickael-grima/optimizedGPS
optimizedGPS/problems/utils/utils.py
Python
apache-2.0
895
0
# -*- coding: utf-8 -*- # !/bin/env python import os class SafeOpen(object): """ A safe opening: if the direc
tory doesn't exist, create it, and then open """ def __init__(self, filename, mode): self.filename = filename self.mode = mode def makeDir(self, directory): """ Check if the file directory exists, otherwise create the directory """ if not os.path.exi
sts(directory): os.makedirs(directory) def __enter__(self): self.makeDir('/'.join(self.filename.split('/')[:-1])) self.file = open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exc_val, exc_tb): self.file.close() def around(number): "...
Impactstory/depsy
scripts/github_users.py
Python
mit
2,346
0.00341
__author__ = 'jay' from pathlib import Path import os import json import requests data_dir = Path(__file__, "../../data").resolve() usernames_path = Path(data_dir, "github_usernames.json") users_path = Path(data_dir,
"github_users.json") users_url_template = "https://api.github.com/users/%s" class RateLimitException(Exception): pass def get_github_creds(): creds_str = os.environ["GITHUB_TOKENS"] cred_pairs =[] for pair_string in creds_str.split(","): cred_pairs.append(pair_string.split(":")) return ...
s_url = users_url_template % username r = requests.get(users_url, auth=(user, password)) print "got {status_code} response from {url}. X-RateLimit-Remaining: {rate_limit}".format( status_code=r.status_code, url=users_url, rate_limit=r.headers["X-RateLimit-Remaining"] ) if r.sta...
gotlium/django-feedme
feedme/urls.py
Python
mit
686
0
from django.conf.urls import patterns, url from .views import FeedList, ImportView, AddView from .ajax import mark_as_read urlpatterns = patterns( '', url(r'^$', FeedList.as_view(), name="feedme-feed-list"), url(r'^by_category/(?P<cat
egory>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-category'), url(r'^by_feed/(?P<feed_id>[-\w]+)/$', FeedList.as_view(), name='feedme-feed-list-by-feed'), url(r'^import/$',
ImportView.as_view(), name='feedme-import-google-takeout'), url(r'^ajax/mark_as_read/$', mark_as_read, name='feedme-mark-as-read-ajax'), url(r'^ajax/add/$', AddView.as_view(), name='feedme-add-ajax'), )
gion86/awlsim
awlsim/core/instructions/insn_assert_lt.py
Python
gpl-2.0
1,478
0.012855
# -*- coding: utf-8 -*- # # AWL simulator - instructions # # Copyright 2012-2014 Michael Buesch <m@bues.ch> # # 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 ...
icode_literals from awlsim.common.compat import * from awlsim.core.instructions.main import * #@nocy from awlsim.core.operators import * #from awlsim.core.instructions.main cimport * #@cy class AwlInsn_ASSERT_LT(AwlInsn): #+cdef __slots__ = () def __init__(self, cpu, rawInsn): AwlInsn
.__init__(self, cpu, AwlInsn.TYPE_ASSERT_LT, rawInsn) self.assertOpCount(2) def run(self): #@cy cdef S7StatusWord s s = self.cpu.statusWord val0 = self.cpu.fetch(self.ops[0]) val1 = self.cpu.fetch(self.ops[1]) if not (val0 < val1): raise AwlSimError("Assertion failed") s.NER = 0
jryu/recurringtasks
checklist/urls.py
Python
gpl-2.0
1,246
0
from django.conf.urls import url from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView from django.views.i18n import javascript_catalog from checklist import views urlpatterns = [ url(r'^$', views.Main.as_view(), name='main'), url(r'^check/$', views.CheckCreat...
.as_view(), name='task_update'), url(r'^tasks/delete/(?P<pk>\d+)$', views.TaskDelete.as_view(), name=
'task_delete'), url(r'^archives/(?P<year>[0-9]{4})-(?P<month>[0-9]+)-(?P<day>[0-9]+)/$', views.Archives.as_view(month_format='%m'), name='archives'), url(r'^trends/$', login_required( TemplateView.as_view(template_name="checklist/trends.html")), name='trends'), url(r'^trends/ajax/$...
ioam/lancet
doc/conf.py
Python
bsd-3-clause
2,993
0.003675
# -*- coding: utf-8 -*- import sys, os sys.path.append(os.path.dirname(os.path.abspath(__file__))) from builder.shared_conf import * # pyflakes:ignore (API import) paths = ['../param/', '.', '..'] add_paths(paths) # General information about the project. project = u'Lancet' copyright = u'2014, IOAM' ioam_project =...
ns = ['_build', 'test_data', 'reference_data', 'nbpublisher', 'builder'] # Add any paths that contain custom static files (such as style sheets) here
, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static', 'builder/_shared_static'] # Output file base name for HTML help builder. htmlhelp_basename = 'Lancetdoc' # The name of an image file ...
psb-seclab/malware_classifier
ostsa/classification/Classifier.py
Python
mit
16,877
0.006577
from ..storage import create_dirs from sklearn.metrics import accuracy_score, confusion_matrix, log_loss from sklearn.model_selection import cross_val_score, train_test_split from sys import version_info import matplotlib.pyplot as plot import numpy as np import pickle ################################################...
n it # comes to numpy arrays. If the classifier was saved in Python 2 # and Python 3 is used
to load it, an encoding will need to be # specified in order to prevent issues. data = pickle.load(file, encoding='latin1') if version_info >= (3, 0) \ else pickle.load(file) # If the file was correctly formatted, the data should con...
peragro/peragro-at
src/damn_at/analyzers/video/__init__.py
Python
bsd-3-clause
21
0
"""Vide
o A
nalyzer"""
greglinch/sourcelist
django-magic-link/django_magic_login/settings.py
Python
mit
3,560
0.001685
""" Django settings for django_magic_login project. Generated by 'django-admin startproject' using Django 1.10.3. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """...
'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.Authentica
tionMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'django_magic_login.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templ...
Lunatixz/script.skin.helper.service
resources/lib/ListItemMonitor.py
Python
gpl-2.0
70,988
0.012707
#!/usr/bin/python # -*- coding: utf-8 -*- import threading, thread import requests, re import random import xml.etree.ElementTree as etree from Utils import * import ArtworkUtils as artutils import SkinShortcutsIntegration as skinshortcuts class ListItemMonitor(threading.Thread): event = None exit = Fal...
self.liTitle = xbmc.getInfoLabel("%sListItem.Title" %self.widgetContainerPrefix).decode('utf-8') self.liLabel = xbmc.getInfoLabel("%sListItem.Label" %self.widgetContainerPrefix).decode('utf-8') except Exception as e:
logMsg(str(e),0) curFolder = "" self.liLabel = "" self.liTitle = "" #perform actions if the container path has changed if (curFolder != curFolderLast): self.resetWindowProps...
redhat-openstack/trove
trove/common/base_wsgi.py
Python
apache-2.0
27,852
0.000754
# Copyright 2014 Tesora, 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 ...
eventlet.sleep(0.1) if not sock:
raise RuntimeError(_("Could not bind to %(host)s:%(port)s " "after trying for 30 seconds") % {'host': host, 'port': port}) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # sockets can hang around forever without keepalive ...
jasonz93/python-tordatahub
tordatahub/errors/__init__.py
Python
apache-2.0
3,583
0.00614
#!/usr/bin/env python # -*- 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...
it__(self, status_code, request_id, error_code, error_msg): super(LimitExceededException, self).__init__(status_code, request_id, error_code, error_msg) class ServerInternalError(DatahubException): """ The Datahub server occured error. """ de
f __init__(self, status_code, request_id, error_code, error_msg): super(ServerInternalError, self).__init__(status_code, request_id, error_code, error_msg)
rtucker-mozilla/inventory
mcsv/tests/importer.py
Python
bsd-3-clause
18,133
0.000662
from django.core.exceptions import ValidationError from django.test import TestCase, Client from mcsv.importer import csv_import from systems.models import ( OperatingSystem, System, SystemRack, Allocation, Location, SystemStatus, SystemType ) from systems.tests.utils import create_fake_host import datetime ...
r,2012-01-01,2
013-01-01,something 7fooboz.mozilla.com,foo%1.1,asdf,foobar,2012-01-01,2013-01-01,something 8fooboz.mozilla.com,foo%1.1,asdf,foobar,2012-01-01,2013-01-01,something """ before = System.objects.all().count() ret = csv_import(test_csv, save=False) after = System.objects.all(...
gpotter2/scapy
scapy/layers/tls/crypto/prf.py
Python
gpl-2.0
12,924
0
# This file is part of Scapy # Copyright (C) 2007, 2008, 2009 Arnaud Ebalard # 2015, 2016, 2017 Maxence Tury # This program is published under a GPLv2 license """ TLS Pseudorandom Function. """ from __future__ import absolute_import from scapy.error import warning from scapy.utils import strxor from scapy.layers.tls...
fined in various sections of the RFC depending on the use of the generated PRF keystream - seed: the seed used by the expansion functions. - req_len: amount of keystream to be generated """ return _tls_P_SHA256(secret, label + seed, req_len) def _tls12_SHA384PRF(secret, label, seed, req_l...
512PRF(secret, label, seed, req_len): return _tls_P_SHA512(secret, label + seed, req_len) class PRF(object): """ The PRF used by SSL/TLS varies based on the version of the protocol and (for TLS 1.2) possibly the Hash algorithm of the negotiated cipher suite. The various uses of the PRF (key deriva...
saurabhbajaj207/CarpeDiem
venv/Lib/site-packages/pyasn1/codec/der/decoder.py
Python
mit
2,169
0.002766
# # This file is part of pyasn1 software. # # Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com> # License: http://pyasn1.sf.net/license.html # from pyasn1.type import univ from pyasn1.codec.cer import decoder __all__ = ['decode'] class BitStringDecoder(
decoder.BitStringDecoder): supportConstructedForm = False class OctetStringDecoder(decoder.OctetStringDecoder): supportConstructedForm = False # TODO: prohibit non-canonical encoding RealDecoder = decoder.RealDecoder tagMap = decoder.tagMap.copy() tagMap.update( {univ.BitString.tagSet: BitStringDecoder(...
niv.Real.tagSet: RealDecoder()} ) typeMap = decoder.typeMap.copy() # Put in non-ambiguous types for faster codec lookup for typeDecoder in tagMap.values(): if typeDecoder.protoComponent is not None: typeId = typeDecoder.protoComponent.__class__.typeId if typeId is not None and typeId not in typeMa...
zegra1989/pytree
rtree.py
Python
mit
14,094
0.000676
# -*- coding:utf-8 -*- # 使用 UTF-8 import sys reload(sys) sys.setdefaultencoding("utf-8") import sys from heap import Heap class Rectangle(object): """docstring for Rectangle""" def __init__(self, dimension, entry=None): super(Rectangle, self).__init__() self.dimension = dimension se...
e return True def __str_
_(self): return "Min:{0}, Max:{1}".format( self.min_dim, self.max_dim) class RNode(object): def __init__(self, degree, dimension): super(RNode, self).__init__() self.num = 0 self.isleaf = True self.degree = degree self.dimension = dimension ...
sobomax/virtualbox_64bit_edd
src/VBox/ValidationKit/testmanager/core/testset.py
Python
gpl-2.0
28,203
0.014608
# -*- coding: utf-8 -*- # $Id: testset.py $ """ Test Manager - TestSet. """ __copyright__ = \ """ Copyright (C) 2012-2015 Oracle Corporation This file is part of VirtualBox Open Source Edition (OSE), as available from http://www.virtualbox.org. This file is free software; you can redistribute it and/or modify it und...
Will not raise exceptions, unless the class instance is invalid. """ assert sMode in [ 'rb', 'r', 'rU' ]; # Try raw file first. sFile1 = os.path.join(config.g_ksFileAreaRootDir, self.sBaseFilename + '-' + sFilename); try: oFile = open(sFile1, sMode); ...
ive next. sFile2 = os.path.join(config.g_ksZipFileAreaRootDir, self.sBaseFilename + '.zip'); try: oZipFile = zipfile.ZipFile(sFile2, 'r'); oFile = oZipFile.open(sFilename, sMode if sMode != 'rb' else 'r'); cbFile = oZipFile.getinfo(sF...
cjng96/devCmdTool
mainRegList.py
Python
apache-2.0
10,374
0.031687
import os import urwid import subprocess from multiprocessing import Pool import urwidHelper as ur from tool import git, system, systemSafe, systemRet, programPath import tool import myutil from globalBase import * def _repoGetStatus(item): status = dict(M=0, E=None) if not item["repo"]: re...
SimpleFocusListWalker(ur.makeBtnListTerminal([], None))) self.lbHelp = urwid.Text("Insert: new name/group, Delete: remove name/group, R: toggle repo status") self.widgetFrame = urwid.LineBox(urwid.Pile( [("pack", self.headerText), ("pack", self.lbPath), ("pack", self.lbRepo),
("pack", self.lbNames), (8, self.widgetListName), ('pack', urwid.Divider('-')), ("pack", self.lbGroups), (8, self.widgetListGroup), ("pack", self.lbHelp)])) self.mainWidget = urwid.Overlay(urwid.Filler(self.widgetFrame), g.loop.widget, 'center', 80, 'middle', 30) def init(self): ...
sdpython/ensae_teaching_cs
_doc/examples/automation/jenkins_setup.py
Python
mit
1,450
0.002073
# -*- coding: utf-8 -*- """ Set up or update Jenkins Jobs ============================= Update Jenkins jobs for GitHub repositories. """ ######################################### # import import sys import os from pyquickhelper.loghelper import get_keyword ######################################### # logging from p...
delete_first=False,
location="d:\\jenkins\\pymy", disable_schedule=False)
raman-sharma/pyAudioAnalysis
analyzeMovieSound.py
Python
apache-2.0
6,014
0.045727
import os, sys, shutil, glob, numpy, csv, cPickle import scipy.io.wavfile as wavfile import audioBasicIO import audioTrainTest as aT import audioSegmentation as aS import matplotlib.pyplot as plt import scipy.spatial.distance minDuration = 7; def classifyFolderWrapper(inputFolder, modelType, modelName, outputMode=Fals...
"data/svmMovies8classes" dirOutput = inputFile[0:-4] + "_musicSegments" if os.path.exists(dirOutput) and dirOutput!=".": shutil.rmtree(dirOutput) os.makedirs(dirOutput) [Fs, x] = audioBasicIO.readAudioFile(inputFile) if modelType=='svm': [Classifier, MEAN, STD, classNames, mtWin, mtStep, stWin, s
tStep, computeBEAT] = aT.loadSVModel(modelName) elif modelType=='knn': [Classifier, MEAN, STD, classNames, mtWin, mtStep, stWin, stStep, computeBEAT] = aT.loadKNNModel(modelName) flagsInd, classNames, acc = aS.mtFileClassification(inputFile, modelName, modelType, plotResults = False, gtFile = "") segs, classes = ...
maaaaz/nmaptocsv
nmaptocsv.py
Python
lgpl-3.0
24,214
0.010325
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # This file is part of nmaptocsv. # # Copyright (C) 2012, 2019 Thomas Debize <tdebize at mail.com> # All rights reserved. # # nmaptocsv is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # ...
ptocsv 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 Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # ...
rint_function # Global imports import sys import re import csv import struct import socket import itertools import argparse import xml.etree.cElementTree as ET # Python 2 and 3 compatibility if (sys.version_info < (3, 0)): izip = itertools.izip fd_read_options = 'rb' fd_write_options = 'wb' else: izip...
iEngage/python-sdk
iengage_client/models/nlc.py
Python
apache-2.0
5,546
0.000541
# coding: utf-8 """ Stakeholder engagement API This API enables Intelligent Engagement for your Business. iEngage is a platform that combines process, augmented intelligence and rewards to help you intelligently engage customers. OpenAPI spec version: 1.0 Generated by: https://github.com/swagger...
lf._modified_date @modified_date.setter def modified_date(self, modified_date): """ Sets the modified_date of this NLC. :param modified_date: The modified_date of this NLC. :type: datetime """ self._modified_date = modified_date @property def classific...
elf._classification @classification.setter def classification(self, classification): """ Sets the classification of this NLC. :param classification: The classification of this NLC. :type: list[Bucket] """ self._classification = classification def to_dict(s...
CodethinkLabs/python-consonant
consonant/register/__init__.py
Python
gpl-2.0
6,463
0
# Copyright (C) 2013 Codethink Limited. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distribute...
for when a register file has an invalid format.""" def __init__(self, filename, msg): self.filename = filename self.msg = msg def __str__(self): return 'File "%s": %s' % (self.filename, self.msg) class UnknownSchemaError(Exception): """Exception for when an unknown schema is lo...
self.schema = schema def __str__(self): return '%s' % self.schema class UnknownServiceError(Exception): """Exception for when an unknown service is looked up via the register.""" def __init__(self, service): self.service = service def __str__(self): return '%s' % self....
lunixbochs/glshim
test/util/run.py
Python
mit
8,092
0.001977
import argparse import jinja2 import os import signal import subprocess import sys import traceback from blessings import Terminal from contextlib import contextmanager signals = dict((k, v) for v, k in signal.__dict__.iteritems() if v.startswith('SIG')) term = Terminal() TEST_ROOT = os.getcwd() env = jinja2.Environ...
: self.output = out self.build_failed = True return False with chdir(junk_dir): out, status = shell('make', '-j2') if status: self.output = out self.build_failed = True return False tmp = os.pat...
p') out = os.path.join(bin_dir, self.exe) if os.path.exists(out): os.unlink(out) os.rename(tmp, out) return True def run(self): bin_dir = os.path.join(TEST_ROOT, 'bin', self.dir) with chdir(bin_dir): self.output, status = shell('./' + self.exe...
cbclab/MDT
mdt/gui/maps_visualizer/design/ui_TabGeneral.py
Python
lgpl-3.0
33,361
0.001828
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'TabGeneral.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_TabGeneral(object): def setupUi(self, TabGeneral): TabGe...
ox(self.frame_3) self.general_volume_index.setObjectName("general_volume_index") self.gridLayout_2.addWidget(self.general_volume_index, 2, 1, 1, 1) self.horizontalLayout_10 = QtWidgets.QHBoxLayout() self.horizontalLayout_10.setContentsMargins(3, -1, -1, -1)
self.horizontalLayout_10.setObjectName("horizontalLayout_10") self.label_25 = QtWidgets.QLabel(self.frame_3) self.label_25.setObjectName("label_25") self.horizontalLayout_10.addWidget(self.label_25) self.maximumVolume = QtWidgets.QLabel(self.frame_3) self.maximumVolume.setObje...
shankari/e-mission-server
bin/debug/fix_usercache_processing.py
Python
bsd-3-clause
1,917
0.010955
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import # Fixes usercache processing # If there are any errors in the usercache processing, fix them and reload the data # Basic flow # - Copy data back to user cache # - Attempt ...
dler as euah import emission.net.usercache.abstract_usercache as enua def fix_usercache_errors(): copy_to_usercache() move_to_long_term() def copy_to_usercache(): # Step 1: Copy data back to user cache error_it = edb.get_timeseries_error_db().find() uc = edb.get_usercache_db() te = ...
logging.debug("Copying entry %s" % error["metadata"]) save_result = uc.save(error) remove_result = te.remove(error["_id"]) logging.debug("save_result = %s, remove_result = %s" % (save_result, remove_result)) logging.info("step copy_to_usercache DONE") def move_to_long_term(): ...
timm-tem/RPi_mediaserver
piface/output7off.py
Python
gpl-3.0
966
0.005176
# THIS IS THE PYTHON CODE FOR PiFACE OUTPUT OFF # # Copyright (C) 2014 Tim Massey # # 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 you...
u should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # Also add information on how to contact you by electronic and paper mail. #!/usr/bin/python im
port pifacedigitalio pifacedigital = pifacedigitalio.PiFaceDigital() pifacedigital.output_pins[7].turn_off()
kampanita/pelisalacarta
python/main-classic/servers/flashx.py
Python
gpl-3.0
2,876
0.003133
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Conector para flashx # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ # ------------------------------------------------------------ import re from core import logger from core import jsunpac...
k(match) # Extrae la URL # {file:"http://f11-play.flashx.tv/luq4gfc7gxixexzw6v4lhz4xqslgqmqku7gxjf4bk43u4qvwzsadrjsozxoa/video1.mp4"} video_urls = [] media_urls = scrapertools.find_multiple_matches(match, '\{file\:"([^"]+)"') for media_u
rl in media_urls: if not media_url.endswith("png"): video_urls.append(["." + media_url.rsplit('.', 1)[1] + " [flashx]", media_url]) for video_url in video_urls: logger.info("pelisalacarta.servers.flashx %s - %s" % (video_url[0], video_url[1])) return video_urls # Encuentra vídeos...
spulec/PyQS
example/api/example.py
Python
mit
1,239
0
import logging import json from flask import Blueprint, current_app, request, jsonify from api.helpers import construct_response from api import tasks blueprint = Blueprint('api', __name__) @blueprint.route('/example', methods=['POST']) def example(): queues = current_app.config.get('QUEUES') queue_name = qu...
status = 200 except Exception as e: response_message = ( f'Something went wrong submitting message ' 'to queue {queue_name}! {e}' ) status = 500 return construct_response(response_mes
sage, message_data, status) @blueprint.route('/health', methods=['GET']) def health(): return jsonify('OK'), 200 @blueprint.route('/', methods=['GET']) def hello(): return 'Hello!'
pozytywnie/django-facebook-auth
facebook_auth/utils.py
Python
mit
2,967
0.000674
import json try: from urllib.parse import urljoin from urllib.parse import urlencode except ImportError: from urlparse import urljoin from urllib import urlencode import facepy from django.conf import settings from django.utils import ti
mezone from django.conf import settings from django.core import signing from django.core.urlresolvers import reverse from django.utils import encoding from . facepy_wrapper import utils GRAPH_MAX_TRIES = 3 FACEBOOK_TIMEOUT = getattr(settings, 'FACEBOOK_AUTH_B
ACKEND_FACEBOOK_TIMEOUT', timezone.timedelta(seconds=20).total_seconds()) FACEBOOK_API_VERSION = getattr(settings, 'FACEBOOK_API_VERSION', '2.1') class InvalidNextUrl(Exception): pass class Next(object): salt = 'facebook_auth.urls.Next' def encode(self, data): data = s...
ghajba/CodingContestConfig
python/ContestMain.py
Python
mit
3,187
0.001883
import os from glob import glob from filecmp import cmp from ContestCode import dummy_message from ContestCode import do_level_1 from ContestCode import do_level_2 from ContestCode import do_level_3 from ContestCode import do_level_4 PATH = "." FOLDER_PREFIX = "level" DEFAULT_FOLDER = PATH + '/' + FOLDER_PREFIX de...
xpected == result, "Actual result [%s] is not as expected [%s]!" % (result, expec
ted) if __name__ == '__main__': do_setup_testing() do_it_nasty("level1", False, do_level_1) do_it_nasty("level2", False, do_level_2) do_it_nasty("level3", False, do_level_3) do_it_nasty("level4", False, do_level_4)
martjanz/shub2sqlite
import.py
Python
mit
2,628
0.036149
import sys, getopt import os.path import sqlite3, json import requests import config # config file from scrapinghub import Connection """ Scrapinghub2Sqlite 1. Create sqlite database (if not exists yet, obviously) a. Create tables 2. get all projects from scrapinghub 3. check for new projects (not stored yet in lo...
id in project_ids: project = connection[project_id] cursor.execute('''SELECT * FROM shub_projects WHERE shub_id = ?''', (project.id,)) # insert if no
t exist if len(cursor.fetchall()) == 0: print "Guardando proyecto " + str(project.id) + "..." db.execute('''INSERT INTO shub_projects (shub_id) VALUES (?)''',\ [project.id]) # get finished jobs getJobs(db, project.jobs(state='finished')) # get deleted jobs if getDeleted: getJobs(db, proj...
mindbody/API-Examples
SDKs/Python/swagger_client/models/get_waitlist_entries_request.py
Python
bsd-2-clause
10,823
0.000092
# coding: utf-8 """ MINDBODY Public API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: v6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 impor...
edule_ids(self): """Gets the class_schedule_ids of this GetWaitlistEntriesRequest. # noqa: E501 The requested class schedule IDs. If a class ID is present, the request automatically disregards any class schedule IDs in the request.<br /> Either `ClassSche
duleIds`, `ClientIds`, `WaitlistEntryIds`, or `ClassIds` is required; the others become optional.<br /> Default: **all ClassScheduleIds** # noqa: E501 :return: The class_schedule_ids of this GetWaitlistEntriesRequest. # noqa: E501 :rtype: list[int] """ return self._class_schedule_ids...
jdemel/gr-misc
examples/uhd_fft_qt.py
Python
gpl-3.0
16,000
0.006938
#!/usr/bin/env python ################################################## # Gnuradio Python Flow Graph # Title: UHD FFT Qt # Author: Johannes Demel # Generated: Wed Jan 29 13:51:16 2014 ################################################## from PyQt4 import Qt from gnuradio import eng_notation from gnuradio import gr from...
self._dsp_label_
tool_bar = Qt.QToolBar(self) self._dsp_label_tool_bar.addWidget(Qt.QLabel("DSP Freq"+": ")) self._dsp_label_label = Qt.QLabel(str(self.dsp_label)) self._dsp_label_tool_bar.addWidget(self._dsp_label_label) self.top_grid_layout.addWidget(self._dsp_label_tool_bar, 3, 4, 1, 1) self.c...
annapowellsmith/openpresc
openprescribing/frontend/management/commands/send_monthly_alerts.py
Python
mit
7,849
0.000382
# -*- coding: utf-8 -*- import logging from django.core.management.base import BaseCommand from django.core.management.base import CommandError from django.db.models import Q from frontend.models import EmailMessage from frontend.models import ImportLog from frontend.models import OrgBookmark from frontend.models imp...
for which a test alert should be ' 'sent to `recipient-email`') ) parser.add_argument( '--practice', help=('If specified, a Practice code for which a test alert ' 'should be sent to `recipient-email`')) parser.add_argument( ...
hich should be sent to ' '`recipient-email`')) parser.add_argument( '--url', help=('If specified, a URL for a test search ' 'alert with name `search-name` which should be sent to ' '`recipient-email`')) parser.add_argument( ...
KMSkelton/cgm_flask
schema.py
Python
mit
920
0.003261
from marshmallow import post_load from marshmallow_sqlalchemy import field_for from m
odels import ma, User, Device, Measurement class UserSchema(ma.Schema): id = field_for(User, 'id', dump_only=True) class Meta: # Fields to expose fields = ('id', 'name', 'username') model = User @post_load def make_user(self, data): return User(**data) class DeviceSch...
= field_for(Device, 'id', dump_only=True) class Meta: # Fields to expose fields = ('id', 'model', 'manufacturerID') model = Device @post_load def make_device(self, data): return Device(**data) class MeasurementSchema(ma.Schema): id = field_for(Measurement, 'id', dump_...
taedori81/shoop
shoop/admin/modules/products/views/edit_cross_sell.py
Python
agpl-3.0
3,483
0.000287
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2015, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from __future__ import unicode_literals from django.contrib import messages...
rom django.views.generic import UpdateView from shoop.admin.base import MenuEntry from shoop.admin.forms.widgets import ProductChoiceWidget from shoop.admin.toolbar import PostActionButton, Toolbar from shoop.admin.utils.urls import get_model_url from shoop.core.models import ( Product, ProductCrossSell, ProductCr...
pe, ProductMedia ) class ProductCrossSellForm(ModelForm): class Meta: model = ProductCrossSell fields = ( "product2", "weight", "type", ) def __init__(self, **kwargs): self.product = kwargs.pop("product") super(ProductCrossSellForm, ...
irmen/Pyro4
examples/stockquotes-old/phase3/aggregator.py
Python
mit
1,432
0.001397
from __future__ import print_function import Pyro4 @Pyro4.expose class Aggregator(object): def __init__(self): self.viewers = {} self.symbols = [] def add_symbols(self, symbols): self.symbols.extend(symbols) def available_symbols(self): return self.symbols
def view(self, viewer, symbols): print("aggregator gets a new viewer, for symbols:", symbols) self.viewers[viewer] = symbols def quotes(self, market, stockquotes): for symbol, value in stockquotes.items(): for viewer, symbols in self.viewers.items(): if symbol...
register(aggregator) ns = Pyro4.locateNS() ns.register("example.stockquote-old.aggregator", agg_uri) for market, market_uri in ns.list(prefix="example.stockmarket-old.").items(): print("joining market", market) stockmarket = Pyro4.Proxy(market_uri) stockmarket.listener(aggregator) ...
albermax/xcsvm
xcsvm/xcsvm/tests/solvers/llwmr.py
Python
mit
7,407
0
from ...utils.tests import base as base from ...utils.tests import mpi as mpit # key order: dataset; epsilon; C __REFERENCE_RESULTS__ = { "dryrun": { 0.1: { 0.1: { "accuracy": 1-0.9300, }, 1: { "accuracy": 1-0.9300, }, ...
at32_ld(): do_llwmr_tld({"dtype": "float32"}) @base.testattr("slow") def test_dtype_float64_sd(): do_llwmr_tsd({"dtype": "float64"}) @base.testattr("slow") def test_dtype_float64_ld(): do_llwmr_tld({"dtype": "float64"}) ############################################################################### # ...
test_idtype_uint32_sd(): do_llwmr_tsd({"idtype": "uint32"}) @base.testattr("slow") def test_idtype_uint32_ld(): do_llwmr_tld({"idtype": "uint32"}) @base.testattr("slow") def test_idtype_uint64_sd(): do_llwmr_tsd({"idtype": "uint64"}) @base.testattr("slow") def test_idtype_uint64_ld(): do_llwmr_tld...
t0mk/python-stdnum
stdnum/de/vat.py
Python
lgpl-2.1
2,168
0
# vat.py - functions for handling German VAT numbers # # Copyright (C) 2012, 2013 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, o
r (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a ...
License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301 USA """Ust ID Nr. (Umsatzsteur Identifikationnummer, German VAT number). The number is 10 digits long and uses the ISO 7064 Mod 11, 10 check digit algorithm. >>> compact('...
SpringboardEdu/drip-py
drip/drip.py
Python
mit
4,987
0.001404
import json import requests import logging from mixins import DripQueryPathMixin logger = logging.getLogger(__name__) class DripPy(DripQueryPathMixin): """ The main class that interacts with Drip https://www.getdrip.com/docs/rest-api#subscribers """ def __init__(self, token, account_id, endpoint...
criber[2] is not None: customer["remove_tags"] = [subscriber[2]] payload.append(customer) self.send_request(url, {"batches": [{"subscribers": pa
yload}]}) return {} def send_request(self, request_url, payload=None, method="POST"): """ Dispatches the request and returns a response Args: request_url (str): The URL to request from payload (dict): Optional method (str): Defaults to POST, other...
oczkers/gdown
gdown/modules/crocko.py
Python
gpl-3.0
1,644
0.00365
# -*- coding: utf-8
-*- """ gdown.modules.crocko ~~~~~~~~~~~~~~~~~~~ This module contains handlers for crocko. """ import re from datetime import datetime from ..module import browser, acc_info_template def getApikey(username, passwd): r = browser() content = re.search('<content type="text">(.+)</content>', r.post('http://a...
group(1) if content == 'Invalid login or password': return False else: return content def accInfo(username, passwd, proxy=False): """Returns account info.""" # get apikey acc_info = acc_info_template() apikey = getApikey(username, passwd) if not apikey: acc_info['st...
mementum/backtrader
tests/test_ind_priceosc.py
Python
gpl-3.0
1,613
0
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2020 Daniel Rodriguez # # This
program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This
program is distributed 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with th...
drepetto/chiplotle
chiplotle/hpgl/abstract/hpglescape.py
Python
gpl-3.0
331
0.024169
from chiplotle.hpgl.abstract
.hpgl import _HPGL class _HPGLEscape(_HPGL): _escape = chr(27) ## PUBLIC PROPERTIES ## @property def format(self): return '%s.%s' % (self._escape, self._name) ## OVERRIDES ##
def __repr__(self): return 'Escape(%s, %s)' % (repr(self._escape), self._name)
lanius/flask-mitten
example/app.py
Python
bsd-3-clause
1,645
0.000608
# -*- coding: utf-8 -*- from flask import (Flask, request, session, render_template, url_for, redirect, jsonify) app = Flask(__name__) app.debug = True app.secret_key = 'dummy secret key' from flaskext.mitten import Mitten mitten = Mitten(app) # apply Mitten @app.route('/
') def index(): if session.get('logged_in'): return redirect(url_for('home')) return render_template('index.html') @app.route('/home/') def home(): if not session.get('logged_in'): return redirect(url_for('index')) retur
n render_template('home.html') # A POST request is protected from csrf automatically @app.route('/login/', methods=['GET', 'POST']) def login(): if request.method == 'GET': return render_template('login.html') else: username = request.form.get('username') password = request.f...
mbauskar/frappe
frappe/desk/page/setup_wizard/setup_wizard.py
Python
mit
8,424
0.025878
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: See license.txt from __future__ import unicode_literals import frappe, json, os from frappe.utils import strip, cint from frappe.translate import (set_default_language, get_dict, send_translations) from frappe.geo.country_info import get_...
"#,###.##") # replace these as float number formats, as they have 0 precision # and are currency number formats and not for floats if number_format=="#.###": number_format = "#.###,##" elif number_format=="#,###": number_format = "#,###.##" system_settings = frappe.get_doc("System Settings", "System Settings...
ge_code(args.get("language")), "time_zone": args.get("timezone"), "float_precision": 3, 'date_format': frappe.db.get_value("Country", args.get("country"), "date_format"), 'number_format': number_format, 'enable_scheduler': 1 if not frappe.flags.in_test else 0, 'backup_limit': 3 # Default for downloadable ba...