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
edublancas/learning
quizzes/Scheduler.py
Python
mit
100
0.03
#This cl
ass helps to create reminders for quizzes #based on the last quiz date and score performance
mrunge/openstack_horizon
openstack_horizon/dashboards/admin/aggregates/forms.py
Python
apache-2.0
2,793
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...
e api.nova.aggregate_set_metadata(request, id, metadata) message = _('Metadata successfully updated.') messages.success(request,
message) except Exception: msg = _('Unable to update the aggregate metadata.') exceptions.handle(request, msg) return False return True
alex-ip/geophys2netcdf
geophys2netcdf/metadata/_template_metadata.py
Python
apache-2.0
1,884
0.009554
''' Created on 20Jan.,2017 @author: Alex Ip ''' import re import json from _metadata import Metadata class TemplateMetadata(Metadata): """Subclass of Metadata to manage template metadata """ # Class variable holding metadata type string _metadata_type_id = 'Template' _filename_patt...
self.metadata_object = None template_json_file = open(source) self.template
= {str(key): str(value) for key, value in json.load(template_json_file).iteritems()} # Convert from unicode template_json_file.close() # Find all elements in templates element_set = set() for attribute_text in self.template.values(): for s in re.finditer('%%(....
smalley/cfapi
migrations/versions/4b2b7cde821f_add_org_name_to_search.py
Python
mit
2,641
0.006816
""" Adds organization name to the project search tsv Revision ID: 4b2b7cde821f Revises: 15593ff6a15f Create Date: 2015-11-30 17:21:56.928359 """ # revision identifiers, used by Alembic. revision = '4b2b7cde821f' down_revision = '15593ff6a15f' from alembic import op import sqlalchemy as sa def upgrade(): dropt...
trigger()" createtriggerfunc = ''' CREATE FUNCTION project_search_trigger() RETURNS trigger AS $$ begin new.tsv_body := setweight(to_tsvector('pg_catalog.english', coalesce(new.st
atus,'')), 'A') || setweight(to_tsvector('pg_catalog.english', coalesce(new.tags,'')), 'A') || setweight(to_tsvector('pg_catalog.english', coalesce(new.name,'')), 'B') || setweight(to_tsvector('pg_catalog.english', coalesce(new.description,'')), 'B') || setweight(to_t...
cmouse/buildbot
master/buildbot/test/unit/process/test_buildrequest.py
Python
gpl-2.0
28,617
0.001433
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
ildrequest.BuildRequest.canBeCollapsed(builder.master, brdict1, brdict2) rows = [ fakedb.Builder(id=77, name='A'), ] rows += self.makeBuildRequestRows(22, 122, None, 222, 'A') rows += self.makeBuildRequestRows(21, 121, None, 221, 'C') rows += self.makeBuildRequestRow...
C') rows += self.makeBuildRequestRows(20, 120, None, 220, 'C') self.bldr.getCollapseRequestsFn = lambda: Builder._defaultCollapseRequestFn yield self.do_request_collapse(rows, [22], []) yield self.do_request_collapse(rows, [21], [19, 20]) @defer.inlineCallbacks def test_collapse...
danielbair/aeneas
aeneas/tests/test_cew.py
Python
agpl-3.0
3,056
0.001963
#!/usr/bin/env python # coding=utf-8 # aeneas is a Python/C library and a set of tools # to automagically synchronize audio and text (aka forced alignment) # # Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it) # Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it) # Copyright (C) 2015-2017, A...
l(sr, 22050) self.assertEqual(sf, 3) self.assertEqual(len(intervals), 3) except ImportError: pass gf.delete_file(handler, output_file_path) def test_cew_synthesize_multiple_lang(self): handler, output_file_path = gf.tmp_file(suffix=".wav") try: ...
t = [ (u"en", u"Dummy 1"), # NOTE cew requires the actual eSpeak voice code (u"it", u"Segnaposto 2"), # NOTE cew requires the actual eSpeak voice code (u"en", u"Dummy 3"), # NOTE cew requires the actual eSpeak voice code ] import ae...
hackersql/sq1map
comm1x/src/core/injections/controller/shell_options.py
Python
gpl-3.0
8,306
0.013003
#!/usr/bin/env python # encoding: UTF-8 """ This file is part of Commix Project (http://commixproject.com). Copyright (c) 2014-2017 Anastasios Stasinopoulos (@ancst). 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 Soft...
nto the '" + os_shell_option + "' mode." print settings.print_warning_msg(warn_msg) return go_back, go_back_again # The "bind_tcp" option elif os_shell_option == "bind_tcp": go_back, go_back_again = bind_t
cp_config(separator, TAG, cmd, prefix, suffix, whitespace, http_request_method, url, vuln_parameter, alter_shell, filename, os_shell_option, go_back, go_back_again, payload, OUTPUT_TEXTFILE) return go_back, go_back_again # The "reverse_tcp" option elif os_shell_option == "reverse_tcp": go_back, go_back_aga...
yelley/sssd
src/config/SSSDConfigTest.py
Python
gpl-3.0
71,503
0.001566
#!/usr/bin/python ''' Created on Sep 18, 2009 @author: sgallagh ''' import unittest import os from stat import * import sys srcdir = os.getenv('srcdir') if srcdir: sys.path.append("./src/config") srcdir = srcdir + "/src/config" else: srcdir = "." import SSSDConfig class SSSDConfigTestValid(unittest.Tes...
.import_config(srcdir + "/testconfigs/sssd-valid.conf") ldap_domain = sssdconfig.get_domain('LDAP') ldap_domain.set_option('debug_level', 3) ldap_domain.remove_provider('auth') ldap_domain.add_pr
ovider('krb5', 'auth') ldap_domain.set_active(True) sssdconfig.save_domain(ldap_domain) of = '/tmp/testModifyExistingConfig.conf' #Ensure the output file doesn't exist try: os.unlink(of) except: pass #Write out the file sssdconfi...
reinaH/osf.io
website/routes.py
Python
apache-2.0
47,853
0.001526
# -*- coding: utf-8 -*- import os import httplib as http from flask import request from flask import send_from_directory from framework import status from framework import sentry from framework.auth import cas from framework.routing import Rule from framework.flask import redirect from framework.sessions import sessi...
, ), Rule( '/profile/<uid>/<addon>/settings/', 'get', addon_view
s.get_addon_user_config, js
ohduran/CrowdFinanceInfographic
virtualenv/lib/python3.5/site-packages/setuptools/command/install_egg_info.py
Python
mit
5,027
0.001989
from distutils import log, dir_util import os, sys from setuptools.extern.six.moves import map from setuptools import Command from setuptools.archive_util import unpack_archive import pkg_resources class install_egg_info(Command): """Install an .egg-info directory for the package""" description = "Install ...
).egg_name() + '.egg-info' if self.install_layout: if not self.install_layout.lower() in ['deb']: rai
se DistutilsOptionError("unknown value for --install-layout") self.install_layout = self.install_layout.lower() basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '') elif self.prefix_option or 'real_prefix' in sys.__dict__: # don't modify for virtualenv ...
pythonthusiast/Northed
main.py
Python
gpl-3.0
49
0.020408
_
_author__ = 'Eko Wibowo' pr
int('Hello Python!')
Nekmo/simple-monitor-alert
simple_monitor_alert/tests/base.py
Python
mit
3,106
0.001932
import os import sys from configparser import NoSectionError from simple_monitor_alert.alerts import Alerts from simple_monitor_alert.lines import Observable, ItemLine from simple_monitor_alert.monitor import Monitors from simple_monit
or_alert.sma import Results, Config, MonitorsInfo from simple_monitor_alert.utils.files import JSONFile BASE_DIR = os.path.dirname(os.path.abspath(__file__)) MONITORS_DIR = os.path.join(BASE_DIR, 'assets', 'monitors') class FakeJSONFile(JSONFile): def __init__(self, data): super(FakeJSONFile, self).__ini...
pass class FakeObservableResults(FakeJSONFile, Results): monitor = None def __init__(self, data=None, sma=None): data = data or {'monitors': {}} super(FakeObservableResults, self).__init__(data) self.sma = sma def get_observable_result(self, observable): monitor =...
asciidisco/plugin.video.netflix
resources/test/test_NetflixSession.py
Python
mit
321
0.003115
# -*- coding: utf-8 -*- # Module: NetflixSession # Author: asciidisco # Created on: 11.1
0.2017 # License: MIT https://goo.gl/5bMj3H """Tests for the `NetflixSession` module""" import unittest import mock from resources.lib.NetflixSession import NetflixSession class NetflixSessionTestCase(unittest.Te
stCase): pass
neonichu/status-boards
relativeDates.py
Python
mit
2,360
0.004237
import datetime def ungettext(a,b,count): if count: return b return a def ugettext(a): return a def timesince(d, now=None): """ Takes two datetime objects and returns the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, then "0 m...
o two adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" an
d "1 year, 5 days" are not. Adapted from http://blog.natbat.co.uk/archive/2003/Jun/14/time_since """ chunks = ( (60 * 60 * 24 * 365, lambda n: ungettext('year', 'years', n)), (60 * 60 * 24 * 30, lambda n: ungettext('month', 'months', n)), (60 * 60 * 24 * 7, lambda n : ungettext('week', 'w...
emanuelcovaci/TLT
blog/file/views.py
Python
agpl-3.0
2,918
0.004455
import json import os from django.contrib.admin.views.decorators import staff_member_required from django.db.models import Q from django.http import HttpResponse, HttpResponseForbidden, Http404 from django.http.respon
se import JsonResponse from django.conf import settings from django.shortcuts import get_object_or_404, redirect from django.views.static import serve from models import Post from forms import PostFormSet import blog.settings def files_filter(request): return JsonResponse({'results': list(Post.objects.filter(Q(...
Q(author__first_name__contains=request.GET["query"]) | Q(author__last_name__contains=request.GET["query"]), location="articolFiles") ...
rsms/smisk
lib/smisk/mvc/template/filters.py
Python
mit
375
0.026667
# encoding: utf-8 '''Temp
late filters ''' def j(s): """Escape for JavaScript or encode as JSON""" pass try: from cjson import
encode as _json except ImportError: try: from minjson import write as _json except ImportError: import re _RE = re.compile(r'(["\'\\])') def _json(s): return repr(_RE.sub(r'\\\1', s)).replace('\\\\','\\') j = _json
TUM-LMF/fieldRNN
train.py
Python
mit
20,521
0.00731
import tensorflow as tf import cPickle as pickle import rnn_model import cnn_model from dataloader import Dataloader #import psycopg2 import os import datetime import numpy as np import argparse from util.util import write_status_file, read_status_file, params2name import sys """ This file contains three functions. ...
int_every=5, init_from=None, max_ckpts_to_keep=5, ckpt_every_n_hours=10000, allow_gpu_mem_growth=True, gpu_memory_fraction=0.3, **kwargs): """ This function performs the training operation on a tensorflow rnn_model.py model :param model: ...
Testing data :param savedir: directory to store event and save files :param max_epoch: hard maximum for number of epochs :param log_every: Frequency of TensorFlow summary recordings :param save_every: checkpoint save frequency :param print_every: cons...
Thingee/cinder
cinder/keymgr/conf_key_mgr.py
Python
apache-2.0
4,809
0
# Copyright (c) 2013 The Johns Hopkins University/Applied Physics Laboratory # 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/...
ey has not been defined: ' 'some operations may fail unexpectedly')) raise ValueError(_('keymgr.fixed_key not defined')) return CONF.keymgr.fixed_key def create_key(self, ctxt, **kwargs): """Creates a key.
This implementation returns a UUID for the created key. A NotAuthorized exception is raised if the specified context is None. """ if ctxt is None: raise exception.NotAuthorized() return self.key_id def store_key(self, ctxt, key, **kwargs): """Stores (i.e., re...
Saruus/drPencilcode
app/models.py
Python
agpl-3.0
1,482
0.010121
from django.db import models # Models of drScratch class File(models.Model): filename = models.CharField(max_length=100) method = models.CharField(max_length=100) time = models.TextField() score = models.CharField(max_length=10) move = models.CharField(max_length=100) art = models.CharField(ma...
s.Model): name = models.CharField(max_length=200) user = models.CharField(max_length=100) date = models.TextField() question1a = models.CharField(max_length=10) question1b = models.CharField(max_length=10) question2a = models.CharField(max_length=10) question2b = models.CharField(max_length...
odels.CharField(max_length=100) question3b = models.CharField(max_length=10) question3c = models.CharField(max_length=10) question4 = models.CharField(max_length=10) question5 = models.CharField(max_length=10) question6 = models.CharField(max_length=500)
iLampard/alphaware
alphaware/preprocess/standardizer.py
Python
apache-2.0
996
0.00502
# -*- coding: utf-8 -*- from sklearn
.preprocessing import StandardScaler from sklearn_pandas import DataFrameMapper from ..base import FactorTransformer from ..e
nums import FactorType class FactorStandardizer(FactorTransformer): def __init__(self, copy=True, out_container=False, with_mean=True, with_std=True): super(FactorStandardizer, self).__init__(copy=copy, out_container=out_container) self.with_mean = with_mean self.with_std = with_std d...
cernops/CloudMan
export/urls.py
Python
apache-2.0
602
0.016611
from django.conf.urls.defaults import * from piston.resource import Resource from handlers import AllocationByTopHandler,AllocationByProjectHandler import settings alloc_by_top = Resource(AllocationByTopHandler) alloc_by_project = Resource(AllocationByProjectHandler) urlpatterns = patterns('', url(r'^allocationbyt...
', alloc_by_top , { 'emitter_format': 'xml' }), url(r'^allocationbytop(\.(?P<emitter_format>.+))$', alloc_by_top), url(r'^allocationbyproject$', alloc_by_project,{ 'emitter_format': 'xml' } ), url(r'^allocationbyproject(\.(?P<emitter_format>.+))$', all
oc_by_project), )
tafaRU/l10n-switzerland
__unported__/l10n_ch_sepa/wizard/wiz_pain_001.py
Python
agpl-3.0
4,378
0
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2011 Camptocamp SA (http://www.camptocamp.com) # All Right Reserved # # Author : Yannick Vaucher (Camptocamp) # # WARNING: This program as such is intended to be used by professional # programmers wh...
class WizardPain001(orm.TransientModel): _name = "wizard.pain001" _columns = { 'pain_001_file': fields.binary('XML File', readonly=True) } def _get_country_cod
e(self, payment): ''' return the coutry code or None from the bank defined in a payment order''' if payment.mode.bank_id.bank.country: return payment.mode.bank_id.bank.country.code elif payment.user_id.company_id.partner_id.country: return payment.user_id.company_...
BD2KGenomics/toil-old
src/toil/test/src/batchJobTest.py
Python
mit
2,389
0.01172
#!/usr/bin/env python """Test Batchjob class """ import unittest import os from toil.lib.bioio import system from optparse import OptionParser from toil.common import setupToil from toil.job import Job from toil.test impor
t ToilTest from toil.batchJob import BatchJob class JobTest(ToilTest): def setUp(self): super( JobTest, self ).setUp( ) self.testToil = os.path.join(os.getcwd(), "testJobDir") parser = OptionParser() Job.Runner.addToilOptions(parser) options, args = parser.parse_args() ...
tore = self.contextManager.__enter__() self.jobStore = jobStore def tearDown(self): self.contextManager.__exit__(None, None, None) system("rm -rf %s" % self.testToil) super( JobTest, self ).tearDown( ) def testJob(self): """ Tests functions of...
pcmoritz/ray-1
python/ray/tests/test_plasma_unlimited.py
Python
apache-2.0
7,447
0
import numpy as np import random import os import shutil import platform import pytest import ray from ray.test_utils import wait_for_condition from ray.internal.internal_api import memory_summary MB = 1024 * 1024 def _init_ray(): return ray.init( num_cpus=2, object_store_memory=700e6, _...
ed=400, fallback=400) del x2p del sentinel finally: ray.shutdown() @pytest.mark.skipif( platform.system() == "Windows", reason="Need to fix up for Windows.") def test_task_unlimited_multiget
_args(): try: address = _init_ray() # Too many refs to fit into memory. refs = [] for _ in range(10): refs.append(ray.put(np.zeros(200 * MB, dtype=np.uint8))) x2 = ray.put(np.zeros(600 * MB, dtype=np.uint8)) x2p = ray.get(x2) _check_spilled_mb(addr...
WillisXChen/django-oscar
oscar/lib/python2.7/site-packages/phonenumbers/data/region_NF.py
Python
bsd-3-clause
1,648
0.010316
"""Auto-generated file, do not edit by hand. NF metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_NF = PhoneMetadata(id='NF', country_code=672, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[13]\\d{5}', possible_number_pattern='\\...
tional_number_pattern='38\\d{4}', possible_number_pattern='\\d{5,6}', example_number='381234'), toll_free=PhoneNumberDesc(n
ational_number_pattern='NA', possible_number_pattern='NA'), premium_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), personal_number=PhoneNumberDesc(national_number_pattern='NA', possibl...
rainaashutosh/MyTestRekall
rekall-core/rekall/plugins/renderers/base_objects.py
Python
gpl-2.0
11,403
0.000351
# -*- coding: utf-8 -*- # Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # 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...
ass FunctionTextRenderer(BaseObjectTextRenderer): renders_type = "Function" def render_full(self, target, width=None, **_): table = text.TextTable( columns=[ dict(name="Address", style="address"), dict(name="OpCode", width=16), dict(name="Op",...
] for instruction in target.disassemble(): result.append(unicode(table.get_row( instruction.address, instruction.hexbytes, instruction.text))) return text.Cell("\n".join(result)) def render_compact(self, target, **options): return text.Cell(self.format_address(t...
RyodoTanaka/Coding_The_Matrix
python/chap_1/1.7.7.py
Python
bsd-3-clause
181
0.022099
#!/
usr/bin/env python # -*- coding: utf-8 -*- def myConcat(L): ret=str() for x in L: ret+=x return ret list=['I ', 'have ', 'a ', 'pen.'] print myConcat(l
ist)
fabioz/PyDev.Debugger
tests_python/test_extract_token.py
Python
epl-1.0
2,852
0.009852
# coding: utf-8 from __future__ import unicode_literals from _pydev_bundle._pydev_completer import (isidentifier, extract_token_and_qualifier, TokenAndQualifier) from _pydevd_bundle.pydevd_constants import IS_PY2 def test_isidentifier(): assert isidentifier('abc') assert not isidentifier('<') assert n...
', 0, 2) == TokenAndQualifier('', 'to') assert extract_token_and_qualifier('tok', 0, 3) == TokenAndQualifier('', 'tok') assert extract_token_and_qualifier('tok', 0, 4) == TokenAndQualifier('', 'tok') assert extract_token_and_qualifier('tok.qual', 0, 0) == TokenAndQualifier('',
'') assert extract_token_and_qualifier('tok.qual', 0, 1) == TokenAndQualifier('', 't') assert extract_token_and_qualifier('tok.qual', 0, 2) == TokenAndQualifier('', 'to') assert extract_token_and_qualifier('tok.qual', 0, 3) == TokenAndQualifier('', 'tok') assert extract_token_and_qualifier('tok.qual',...
jabooth/menpo-archive
menpo/fitmultilevel/fittingresult.py
Python
bsd-3-clause
13,883
0.000288
from __future__ import division import numpy as np from menpo.transform import Scale from menpo.visualize.base import GraphPlotter, MultipleImageViewer from menpo.fit.fittingresult import FittingResult class MultilevelFittingResult(FittingResult): r""" Object that holds the state of a MultipleFitter object (...
r.scaled_levels @property def fitted(self): r""" Returns the fitted state of each fitting object. """ return [f.fitted for f in self.fittings
] @FittingResult.error_type.setter def error_type(self, error_type): r""" Sets the error type according to a set of predefined options. """ if error_type is 'me_norm': for f in self.fittings: f.error_type = error_type self._error_stop = 0....
MartinHjelmare/home-assistant
homeassistant/components/homematicip_cloud/switch.py
Python
apache-2.0
5,355
0
"""Support for HomematicIP Cloud switches.""" import logging from homematicip.aio.device import ( AsyncBrandSwitchMeasuring, AsyncFullFlushS
witchMeasuring, AsyncMultiIOBox,
AsyncOpenCollector8Module, AsyncPlugableSwitch, AsyncPlugableSwitchMeasuring) from homematicip.aio.group import AsyncSwitchingGroup from homeassistant.components.switch import SwitchDevice from . import DOMAIN as HMIPC_DOMAIN, HMIPC_HAPID, HomematicipGenericDevice from .device import ATTR_GROUP_MEMBER_UNREACHAB...
hnakamur/saklient.python
saklient/cloud/errors/dnsaaaarecordnotfoundexception.py
Python
mit
688
0.010274
# -*- coding:utf-8 -*- from ...errors.httpbadrequestexception import HttpBadRequestException import saklient # module saklient.c
loud.errors.dnsaaaarecordnotfoundexception class DnsAaaaRecordNotFoundException(HttpBadRequestException): ## 不適切な要求です。対応するAAAAレコードが見つかりません。 ## @param {int} status # @param {str} code=None #
@param {str} message="" def __init__(self, status, code=None, message=""): super(DnsAaaaRecordNotFoundException, self).__init__(status, code, "不適切な要求です。対応するAAAAレコードが見つかりません。" if message is None or message == "" else message)
pllim/astropy
astropy/cosmology/tests/test_parameters.py
Python
bsd-3-clause
1,438
0.000695
# Licensed under a 3-clause BSD style license - see LICENSE.rst # STDLIB from types import MappingProxyType # THIRD PARTY import numpy as np import pytest # LOCAL from astropy.cosmology import parameters, realizations def test_realizations_in_dir(): """Test the realizations are in ``dir`` of :mod:`astropy.cosm...
, getattr(cosmo, n)) # All the metadata is included. Parameter values take precedence, so only # checking the keys. assert set(cosmo.meta.keys()).issubset(params.keys()) # Lastly, check the generation process. m = cosmo.to_format("mapping", cosmology_as
_str=True, move_from_meta=True) assert params == m
shincling/MemNN_and_Varieties
DataCoupus/list_document/namelist_question.py
Python
bsd-3-clause
2,479
0.003882
# -*- coding: utf8 -*- __author__ = 'shin' import jieba namelist_question=[] namelist_question.append('您好,请问您的姓名是?') namelist_question.append('请问您的姓名是?') namelist_question.append('请告诉我您的姓名') namelist_question.append('请您告诉我您的名字。') namelist_question.append('请问您要购买机票的用户姓名是?') namelist_question.append('请问您的名字是?') namelist...
append('请问尊姓大名?') namelist_question.append('请输入乘客姓名。') namelist_question.append('乘客的名字是什么?') namelist_question.append('乘客怎么称呼?') namelist_question.append('乘客叫
什么名字?') namelist_question.append('乘客的姓名是?') namelist_question.append('请问先生怎么称呼?') namelist_question.append('请问小姐怎么称呼?') namelist_question.append('请问老人家怎么称呼?') namelist_question.append('先生您怎么称呼?') namelist_question.append('小姐您怎么称呼?') namelist_question.append('先生您叫什么名字?') namelist_question.append('小姐您叫什么名字?') namelist_qu...
HybridF5/jacket
jacket/api/compute/openstack/compute/instance_actions.py
Python
apache-2.0
4,402
0
# Copyright 2013 Rackspace Hosting # 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...
msg = _("Action %s not found") % id raise exc.HTTPNotFound(explanation=msg) action_id =
action['id'] action = self._format_action(action) if soft_authorize(context, action='events'): events_raw = self.action_api.action_events_get(context, instance, action_id) action['events'] = [self._format_event(evt) for ...
louisgag/BlenderAndMBDyn
user_defined_element.py
Python
gpl-3.0
14,009
0.006781
# -------------------------------------------------------------------------- # BlenderAndMBDyn # Copyright (C) 2015 G. Douglas Baldwin - http://www.baldwintechnology.com # -------------------------------------------------------------------------- # ***** BEGIN GPL LICENSE BLOCK ***** # # This file is part of Blender...
datory = True self.material.is_card = True def assign(self, context): self.material.assign(self.entity.material) def store(self, context): super().store(context) self.entity.o
bjects[0].parent = self.entity.objects[1] self.entity.objects[0].matrix_parent_inverse = self.entity.objects[1].matrix_basis.inverted() self.entity.material = self.material.store() self.entity.objects = self.sufficient_objects(context) def draw(self, context): sel
jrversteegh/softsailor
softsailor/vr/tst/test_vr_wind.py
Python
gpl-3.0
2,867
0.023021
import unittest import testing_helper from datetime import datetime, timedelta from softsailor.utils import * from softsailor.vr.vr_wind import * from softsailor.vr.vr_weather import * from softsailor.vr.vr_settings import * class FakeWeather: lat_min = 0 lat_max = 0.75 lat_n = 4 lon_min = -0.1 l...
2,1), (3,2), (4, 3), (5, 4), (5, 4)], \ [(3,1), (3,2), (3, 3), (3, 4), (5, 4)], \ [(4,-1), (4,-2), (4, -3), (4, -4), (5, 4)], \ [(4,-1), (4,-2), (4, -3), (4, -4), (5, 4)]]) self.frames.append( \ [[(3,1), (4,2), (5, 3), (6, 4), (5, 4)], \ ...
,-2), (6, -3), (7, -4), (5, 4)], \ [(5,-1), (5,-2), (5, -3), (5, -4), (5, 4)]]) self.frames.append( \ [[(4,1), (5,2), (6, 3), (7, 4), (5, 4)], \ [(5,1), (5,2), (5, 3), (5, 4), (5, 4)], \ [(6,-1), (6,-2), (6, -3), (6, -4), (5, 4)], \ ...
jrbourbeau/cr-composition
comptools/binning.py
Python
mit
5,322
0.000188
from collections import namedtuple import numpy as np def get_energybins(config='IC86.2012'): """Function to return analysis energy bin information Parameters ---------- config : str, optional Detector configuration (default is 'IC86.2012'). Returns ------- energybins : namedtup...
+ log_energy_bins[:-1]) / 2 energy_min = 10**log_energy_min energy_max = 10**log_
energy_max energy_bins = 10**log_energy_bins energy_midpoints = 10**log_energy_midpoints energy_bin_widths = energy_bins[1:] - energy_bins[:-1] # Create instance of EnergyBins with appropriate binning energybins = EnergyBin(energy_min=energy_min, energy_max=energy_max, ...
sostenibilidad-unam/posgrado
posgradmin/posgradmin/views_academico.py
Python
gpl-3.0
17,170
0.003554
# coding: utf-8 from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import UserPassesTestMixin from django.views.generic import ListView from django.views import View from django.db.models import Q import posgradmin.models as models from posgradmin import authorization as auth from...
t.POST['sede'], aula=request.POST['aula'], horario=request.POST['horario']) curso.save() for ac_id in request.POST.getlist('academicos'): ac =
models.Academico.objects.get(pk=int(ac_id)) curso.academicos.add(ac) curso.academicos.add(request.user.academico) curso.save() return HttpResponseRedirect(reverse('mis_cursos')) class CursoView(LoginRequiredMixin, UserPassesTestMixin, View): login_url = setti...
Nic30/HWToolkit
hwt/synthesizer/dummyPlatform.py
Python
mit
775
0.002581
from hwt.synthesizer.rtlLevel.extract_part_drivers import extract_part_drivers from hwt.synthesizer.rtlLevel.remove_unconnected_signals import removeUnconnectedSignals from hwt.synthesizer.rtlLevel.mark_visibility_of_signals_and_check_drivers import markVisibilityOfSignalsAndCheckDrivers class DummyPlatform(): ""...
def __init__(self): self.beforeToRtl = [] self.beforeToRtlImpl = [] self.afterToRtlImpl = [] self.beforeHdlArchGeneration = [ extract_part_drivers, removeUnconnectedS
ignals, markVisibilityOfSignalsAndCheckDrivers, ] self.afterToRtl = []
eranroz/dnase
src/scripts/HMMTrainRegions.py
Python
mit
2,526
0.002771
""" This script trains a model based on different regions of chromosome 1, and evaluates the model as the likelihood of it for the whole chromosome 2. Useful to know whether it is sufficient to train only based on smaller data """ import os import numpy as np from config import RES_DIR from data_provider import SeqL...
region = training['chr1'][start: start + chromosomeLength / regionSize] state_transition = np.array( [ [0.0, 0.99, 0.01], # begin
[0.3, 0.9, 0.1], # open (may go to close but prefers to keep the state) [0.7, 0.1, 0.9] # closed (very small change to get to open) ] ) emission = np.array([ np.zeros(4), [0.02, 0.4, 0.5, 0.08], # open - prefers high values ...
cokelaer/spectrum
test/test_window.py
Python
bsd-3-clause
9,764
0.013212
from spectrum import * from numpy.testing import assert_almost_equal import pytest def test_class_Window(): w = Window(65, name='hann') w.enbw w.mean_square w.frequencies w.plot_time_freq() w.compute_response(NFFT=32) try: w = Window(64, name='wrong') assert False ex...
= Window(65, name="dummy") assert False except: assert True #unittest of create_window def test_create_window_error(): try: create_window('dummy') assert False except: assert True #test that create_window(N, name) works for all valid names @pytest.mark.parametriz...
t_window_name,length', [(name, size) for name, size in zip(window_names.keys(), [1,51,52])]) def test_create_window(test_window_name, length): create_window(length, name=test_window_name) #test that create_window(N, name) is indeed equivalent to the direct call window_name @pytest.mark.parametrize("name,par...
hkhamm/proj5-mongo
CONFIG.py
Python
artistic-2.0
563
0.003552
""" Configuration of 'memos' Flask app. Edit to fit development or deployment environment. """ # import random # localhost # PORT = 5000 # DEBUG = True # MONGO_PORT =
27017 # ix.cs.uoregon.edu PORT = 7420 # random.randint(5000, 8000) MONGO_PORT = 4152 DEBUG = False # Because it's unsafe to run outside localhost # both MONGO_URL = "mongodb://memos_user:peach-cobbler@localhost:4152/memos" # MONGO_USER = 'memos_user' # MONGO_PW = 'peach-cobbler' # MONGO_DB = 'memos' # MONGO_URL =
'mongodb://{$MONGO_USER}:{$MONGO_PW}@localhost:{$MONGO_PORT}/{$MONGO_DB}'
phac-nml/neptune
neptune/Utility.py
Python
apache-2.0
7,808
0.001281
#!/usr/bin/env python """ # ============================================================================= Copyright Government of Canada 2015-2017 Written by: Eric Marinier, Public Health Agency of Canada, National Microbiology Laboratory Funded by the National Micriobiology Laboratory and the Genome Canada / A...
] The reverse complement of the passed sequence. # ============================================================================= """ def reverseComplement(sequence): reverse = str(Seq(sequence, generic_dna).reverse_complement()) return reverse """ # =========
==================================================================== BUILD REFERENCES ---------------- PURPOSE ------- Builds string references (contig pieces) from the reference file. INPUT ----- [FILE] [referenceFile] The file from which to build the string reference. RETURN ------ [STRING ITERABLE] [re...
googleapis/python-aiplatform
samples/generated_samples/aiplatform_v1_generated_model_service_get_model_evaluation_async.py
Python
apache-2.0
1,506
0.000664
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# python3 -m pip install google-cloud-aiplatform # [START aiplatform_v1_generated_ModelService_GetModelEvaluation_async] from google.cloud import aiplatform_v1 async def sample_get_model_evaluation(): # Create a clien
t client = aiplatform_v1.ModelServiceAsyncClient() # Initialize request argument(s) request = aiplatform_v1.GetModelEvaluationRequest( name="name_value", ) # Make the request response = await client.get_model_evaluation(request=request) # Handle the response print(response) #...
kubeflow/pipelines
samples/contrib/kubeflow-katib/mpi-job-horovod.py
Python
apache-2.0
8,891
0.001462
# Kubeflow Pipeline with Katib component. # In this example you will create Katib Experiment using Bayesian optimization algorithm. # As a Trial template you will use Kubeflow MPIJob with Horovod MNIST training container. # After that, you will compile a Kubeflow Pipeline with your Katib Experiment. # Use Kubeflow Pip...
"-x", "PATH", "-mca", "pml", "ob1", "-mca", "btl", ...
py", "--lr", "${trialParameters.learningRate}", "--num-steps", "${trialParameters.numberSteps}" ], ...
nesaro/driza
pyrqt/carga/operaciones/compmedsim.py
Python
gpl-2.0
3,492
0.024482
#!/usr/bin/python # -*- coding: utf-8 -*- #Copyright (C) 2006 Inmaculada Luengo Merino, Néstor Arocha Rodríguez #This file is part of pyrqt. # #pyrqt 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 ver...
ta=[float(x) for x in dato.getCol(variable,caso=caso)] if opciones[u"Hipótesis alternativa"]==">": lateral="greater" elif opciones[u"Hipótesis alternativa"]=="<": lateral="less" else: lateral="two.sided" diccionario=r.t_test(lista,alternativ
e=lateral,mu=float(opciones["Media objetivo"]),conf_level=float(opciones[u"Significación"])/100) diccionario["confianza"]=float(opciones[u"Significación"])/100 return diccionario def initresultado(resultado,opciones): """Inicializa al objeto resultado, añadiendole lo que crea conveniente""" resultado.a...
agry/NGECore2
scripts/mobiles/generic/static/tatooine/staticstorm.py
Python
lgpl-3.0
1,106
0.027125
import sys from services.spawn import MobileTemplate from services.spawn import WeaponTemplate from resources.datatables import WeaponType from resources.datatables import Difficulty from resources.datatables import Options from java.util import Vector def addTemplate(core): mobileTemplate = MobileTemplate() mobi...
ector() weapontemplate = WeaponTemplate('object/weapon/melee/unarmed/shared_unarmed_default.iff', WeaponType.UNARMED, 1.0, 6, 'kinetic') weaponTemplates.add(weapontemplate) mobileTemplate.setWeaponTemplateVector(weaponTemplates) attacks = Vector() mobileTemplate.setDefaultAttack('creatureMeleeAttack') mobileTem...
s) core.spawnService.addMobileTemplate('staticstorm', mobileTemplate) return
hradec/gaffer
python/GafferUI/AnnotationsUI.py
Python
bsd-3-clause
5,068
0.040055
########################################################################## # # Copyright (c) 2021, Cinesite VFX Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions ...
Definitions( graphEditor, node, menuDefinition ) : def append( menuPath, name ) : menuDefinition.append( menuPath, { "command" : functools.partial( __annotate, node, name ), "active" : not Gaffer
.MetadataAlgo.readOnly( node ), } ) names = Gaffer.MetadataAlgo.annotationTemplates( userOnly = True ) if not names : append( "/Annotate...", "user" ) else : for name in names : append( "/Annotate/{}...".format( IECore.CamelCase.toSpaced( name ) ), name ) menuDefinition.append( "/Annotate/D...
stvstnfrd/edx-platform
lms/djangoapps/courseware/tests/test_lti_integration.py
Python
agpl-3.0
9,253
0.00281
"""LTI integration tests""" import json from collections import OrderedDict import mock import oauthlib import six from django.conf import settings from django.urls import reverse from six import text_type from lms.djangoapps.courseware.tests.helpers import BaseTestXmodule from lms.djangoapps.courseware.views.views...
the reversed handler urls""" return "https://{}{}".format(settings.SITE_NAME, reverse( 'xblock_handler_noauth', args=[ text_type(self.course.id), quote_slashes(text_type(self.lti_published.scope_ids.usage_id)), handler ] ...
test_lti_rest_bad_course(self): """Tests what happens when the lti listing rest endpoint gets a bad course_id""" bad_ids = [u"sf", u"dne/dne/dne", u"fo/ey/\\u5305"] for bad_course_id in bad_ids: lti_rest_endpoints_url = 'courses/{}/lti_rest_endpoints/'.format(bad_course_id) ...
kk1987/pycparser
examples/explore_ast.py
Python
bsd-3-clause
5,702
0.006314
#----------------------------------------------------------------- # pycparser: explore_ast.py # # This example demonstrates how to "explore" the AST created by # pycparser to understand its structure. The AST is a n-nary tree # of nodes, each node having several children, each with a name. # Just read the code, ...
nd #~ while_cond.show() # Note that it's a BinaryOp node - the basic constituent of # expressions in our AST. BinaryOp is the expression tree, with # left and right nodes as children. It also has the op attribute, # which is just the string representation of the operator. # #~ print wh
ile_cond.op #~ while_cond.left.show() #~ while_cond.right.show() # # That's if for the example. I hope you now see how easy it is to # explore the AST created by pycparser. Although on the surface it # is quite complex and has a lot of node types, this is the # inherent complexity of the C language every pars...
FR4NK-W/osourced-scion
python/lib/packet/ext/traceroute.py
Python
apache-2.0
3,783
0
# Copyright 2015 ETH Zurich # # 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...
N # Size of every hop information. def __init__(self, raw=None): # pragma: no cover self.hops = [] super().__init__(raw) def _parse
(self, raw): """ Parse payload to extract hop informations. """ hops_no = raw[0] data = Raw(raw, self.NAME, self.MIN_LEN + hops_no * self.HOP_LEN, min_=True) super()._parse(data) # Drop hops no and padding from the first row. data.pop(se...
michael-lazar/praw3
tests/test_handlers.py
Python
gpl-3.0
1,274
0
"""Tests for UnauthenticatedReddit class.""" from __future__ import print_function, unicode_literals from mock import patch from praw import handlers from random import choice from six.moves impo
rt cStringIO from .helper import PRAWTest, betamax, replace_handler class HandlerTest(PRAWTest): def setUp(self): super(HandlerTest, self).setUp() self.cache_store = cStringIO() def _cache_hit_callback(self, key): pass @replace_handler(handlers.RateLimitHandler())
def test_ratelimit_handlers(self): to_evict = self.r.config[choice(list(self.r.config.API_PATHS.keys()))] self.assertIs(0, self.r.handler.evict(to_evict)) @betamax() def test_cache_hit_callback(self): with patch.object(HandlerTest, '_cache_hit_callback') as mock: self.r.h...
skyostil/tracy
src/common/Log.py
Python
mit
1,941
0.009789
# Copyright (c) 2011 Nokia # # Permission is hereby granted, free of charg
e, to any person obtaining a copy # of this software and associated documentation files (the "So
ftware"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above co...
Gzsiceberg/kaggle-avito
ins2/gen_data.py
Python
mit
19,154
0.005325
from csv import DictReader from datetime import datetime, timedelta from collections import defaultdict import cPickle as pickle from math import exp, log, sqrt import random, gc from util import read_dump, write_dump, cache, read_tsv, convert_ts, data, next_row, get_category import argparse, ast, re, json def filter_...
"UserAgentOSID": "", "UserDeviceID": "", "UserAgentFamilyID": ""}) feature_map["user_cnt"] = [user_cnt_row] feature_map["user_info"] = [user_info] feature_map["ad_info"] = ad_infos feat...
ta = map(lambda x: (int(x["Position"]), int(x["ObjectType"]), x), rows) data.sort() price_data = [] ot_cnt = defaultdict(int) all_pos = [] all_ot = [] for i in range(len(data)): all_pos.append(data[i][0]) all_ot.append(data[i][1]) aid = int(data[i][2]["AdID"]) ...
natano/tiget
tiget/git.py
Python
isc
872
0.001147
import pkg_resources from tiget.conf import settings class GitError(Exception): pass def get_config(name): repo = settings.core.repository if repo is
None: raise GitError('no repository found') return repo.config[name] def is_repo_initialized(): repo = settings.core.repository if repo is None: return False ref = 'refs/heads/{}'.format(settings.core.branch) try: repo.lookup_reference(ref) except KeyError: retu...
ction.wrap() as trans: tigetrc = pkg_resources.resource_string('tiget', 'data/tigetrc') trans.set_blob(['config', 'tigetrc'], tigetrc) trans.add_message('Initialize Repository')
mkrcah/propsort
propsort/__init__.py
Python
mit
22
0
__author__ =
'mkrcah
'
kenshinx/rps
script/proxycheck/asyncore.py
Python
mit
20,290
0.001774
# -*- Mode: Python -*- # Id: asyncore.py,v 2.51 2000/09/07 22:29:26 rushing Exp # Author: Sam Rushing <[email protected]> # ====================================================================== # Copyright 1996 by Sam Rushing # # All Rights Reserved # # Permission to use, copy, modify,...
d that the above copyright notice appear in all # copies and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of Sam # Rushing not be u
sed in advertising or publicity pertaining to # distribution of the software without specific, written prior # permission. # # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, ...
django-json-api/rest_framework_ember
tests/test_parsers.py
Python
bsd-2-clause
4,172
0.001198
import json from io import BytesIO import pytest from rest_framework.exceptions import ParseError from rest_framework_json_api.parsers import JSONParser from rest_framework_json_api.utils import format_value from tests.views import BasicModelViewSet class TestJSONParser: @pytest.fixture def parser(self): ...
context): parser_context["request"] = rf.patch("/
") data = { "data": { "type": "BasicModel", }, } with pytest.raises(ParseError) as excinfo: parse(data, parser_context) assert "The resource identifier object must contain an 'id' member" == str( excinfo.value )
Kingside/six-four
setup.py
Python
mit
2,189
0.01736
#!/usr/bin/env python from setuptools import setup setup(name='sixfour', version='1.3.3', description='base64 Image Encoder and Embedder', author='Christopher Simpkins', author_email='[email protected]', maintainer='Christopher Simpkins', maintainer_email='[email protected]', ...
r images that embeds an appropriately formatted, encoded image in HTML, Markdown, CSS, LESS, or SASS files, or streams the raw image data through the standard output stream. `Six-Four Documentation <http://chrissimpkins.github.io/six-four/>`_ Tested in Python v2.7.6 & v3.3.2""", classifiers= [ ...
ded Audience :: Developers', 'Intended Audience :: End Users/Desktop', 'Intended Audience :: Information Technology', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: MacOS', 'Operating System :: Microsoft', 'Operating...
chipx86/reviewboard
reviewboard/hostingsvcs/evolutions/account_hosting_url.py
Python
mit
247
0
from __future__ import unicode_literals from django_evolution.mutations import AddField from django.db import models MUTATIONS = [
AddField('HostingServiceAccount', 'hosting_url', models.CharField,
max_length=256, null=True) ]
arrow-/pitstops
commit.py
Python
unlicense
862
0.00232
import os # This function only READS the Commit info. # There is no point in loading any commit in memory. # What purpose can that serve? Nothing. (Prove this) def load(cls, name, path): try: with open(path, 'rb') as commit_info_file: commit_info_dict = pickle.load(commit_info_file.read()) ...
:\n`%s`" % path) sys.exit(1) # This object hold only some info about a SINGLE Commit class Commit: def __init__(self, parent, branch, message, repo): self.message = message self.hash = self.make_hash(
) # self.repo.dstore.get_commits_by_branch(branch) # make changes to tree # save # make chages to main tree? # exit def make_hash(self): return "yash uuid"
xulesc/algos
psc/test_usm_bp.py
Python
gpl-3.0
1,016
0.030512
#!/usr/bin/python import Bio.PDB.PDBParser from Bio.PDB.PSC.usm import USM import os import numpy as np def get_ca_atom_list(model): atoms = [] for chain in model: for res in chain: try: atoms.append(res['CA']) except: pass return atoms def get_contact_map_complexities(in_dir...
ap(lambda x : x.coord, get_ca_atom_list(structure[0]))) structure_cm_string[filename] = usm.get_contact_map(coords)[1] for k1, v1 in structure_cm_string.iteritems(): for k2, v2 in structure_cm_string.iteritems(): dist = usm.dist(structure_cm_string[k1], structure_cm_string[k2]) print '%s - %...
k1, k2, dist) if __name__ == '__main__': np.set_printoptions(threshold='nan') get_contact_map_complexities('pdb_data')
wapiflapi/gxf
gxf/extensions/registers.py
Python
mit
1,628
0
# -*- coding: utf-8 -*- import gxf from gxf.format
ting import Token, Formattable @gxf.register() class Registers(gxf.DataCommand): '''
Shows registers. ''' def setup(self, parser): parser.add_argument("-m", "--mark", action='append', default=[], help="Highlight some registers.") parser.add_argument("-M", "--mark-used", action='store_true', help="Highlight currently used...
saigkrish/finance
PY/views.py
Python
apache-2.0
3,119
0.021481
from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render from django.utils.html import escape from django.views.decorators.csrf import ensure_csrf_cookie from django.contrib.auth import authenticate, login, logout import json # Create your views here. @ensure_csrf_cookie def index...
+=
"<br><br>Changeset details<br><br>" changeset = request.POST['dfcf_ip_changeset'] jchangeset = json.loads(changeset) for key in jchangeset: value = jchangeset[key] txt += str(key) + "::" + str(value) + "<br>" txt += "<br><br>" txt += escape(repr(request)) return...
eduNEXT/edunext-platform
import_shims/studio/contentstore/config/tests/__init__.py
Python
agpl-3.0
398
0.01005
"""Deprecated import support. Auto-generated by import_shims/generate_shims.sh.""" # pylint: disable=redefined-builtin,wrong-import-position,wildcard-import,useless-suppression,line-too-long from import_shims.warn import warn_deprecated_import warn_deprecated_import('contentstore.config.tests'
, 'cms.djangoap
ps.contentstore.config.tests') from cms.djangoapps.contentstore.config.tests import *
plotly/python-api
packages/python/plotly/plotly/validators/sankey/domain/_row.py
Python
mit
474
0.00211
import _plotly_utils.b
asevalidators class RowValidator(_plotly_utils.basevalidators.IntegerValidator): def __init__(self, plotly_name="row", parent_name="sankey.domain", **kwargs): super(RowValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edi...
lc"), min=kwargs.pop("min", 0), role=kwargs.pop("role", "info"), **kwargs )
Fenixin/Minecraft-Region-Fixer
regionfixer_core/interactive.py
Python
gpl-3.0
24,997
0.002961
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Region Fixer. # Fix your region files with a backup copy of your Minecraft world. # Copyright (C) 2020 Alejandro Aguilera (Fenixin) # https://github.com/Fenixin/Minecraft-Region-Fixer # # This program is free software: you can redistribute it and/or modify ...
more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # from cmd import Cmd import regionfixer_core.constants as c from regionfixer_core import world from regionfixer_core.scan import consol
e_scan_world, console_scan_regionset class InteractiveLoop(Cmd): def __init__(self, world_list, regionset, options, backup_worlds): Cmd.__init__(self) self.world_list = world_list self.regionset = regionset self.world_names = [str(i.name) for i in self.world_list] # if ther...
yuanyelele/solfege
solfege/make_screenshots.py
Python
gpl-3.0
6,516
0.001842
 import os import time from gi.repository import Gtk import solfege from solfege.profilemanager import ChangeProfileDialog from solfege.practisesheetdlg import PractiseSheetDialog from solfege.trainingsetdlg import TrainingSetDialog def run(cmd): print cmd os.system(cmd) def compress(fn): f, ext = os.p...
e.app.practise_lessonfile(u"solfege:lesson-files/csound-fifth-0.99") screenshot(xid, lang, "idbyname-intonation.png") solfege.app.practise_lessonfile(u"solfege:lesson-files/id-tone-cde-3") screenshot(xid, lang, "idtone.png") solfege.app.practise_lessonfile(u"solfege:lesson-files/bpm") screenshot(xid...
ng, "twelvetone.png") solfege.app.practise_lessonfile(u"solfege:lesson-files/nameinterval-2") solfege.win.get_view().new_question() screenshot(xid, lang, "nameinterval.png") solfege.app.practise_lessonfile(u"solfege:lesson-files/progression-2") screenshot(xid, lang, "elembuilder-harmonic-progression...
NdagiStanley/inventory
manage.py
Python
mit
807
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "inventory.settin
gs") try: from django.core.management import execute_from_command_line except ImportError:
# The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. A...
Eric89GXL/scikit-learn
sklearn/feature_selection/tests/test_rfe.py
Python
bsd-3-clause
3,356
0.000298
""" Testing Recursive feature elimination """ import warnings import numpy as np from numpy.testing import assert_array_almost_equal, assert_array_equal from nose.tools import assert_equal from scipy import sparse from sklearn.feature_selection.rfe import RFE, RFECV from sklearn.datasets import load_iris from sklear...
VC(kernel="linear") rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1) y_pred = rfe.fit(X, y).predict(X) clf = SVC() rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1, estimator_params={'kernel': 'linear'}) y_pred2 = rfe.fit(X, y).predict(X) assert_array
_equal(y_pred, y_pred2) def test_rfe(): generator = check_random_state(0) iris = load_iris() X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] X_sparse = sparse.csr_matrix(X) y = iris.target # dense model clf = SVC(kernel="linear") rfe = RFE(estimator=clf, n_features_to...
python-cmd2/cmd2
plugins/template/tests/test_myplugin.py
Python
mit
1,894
0.000528
# # coding=utf-8 import cmd2_myplugin from cmd2 import ( cmd2, ) ###### # # define a class which uses our plugin and some convenience functions # ###### class MyApp(cmd2_myplugin.MyPluginMixin, cmd2.Cmd): """Simple subclass of cmd2.Cmd with our SayMixin plugin included.""" def __init__(self, *args, **...
your app if you want to use # to use the capsys fixture to capture the output. cmd2.Cmd sets # internal variables to sys.stdout and sys.stderr on initialization # and then uses those internal variables instead of sys.stdout. It does # this so you can redirect output from within the app. The capsys fixture # can't captu...
you have extensive initialization needs, create a function # to initialize your cmd2 application. def init_app(): app = MyApp() return app ##### # # unit tests # ##### def test_say(capsys): # call our initialization function instead of using a fixture app = init_app() # run our mixed in comma...
fake-name/ReadableWebProxy
WebMirror/management/rss_parser_funcs/feed_parse_extractIanEnglishmanabroadBlogspotCom.py
Python
bsd-3-clause
577
0.032929
def extractIanEnglishmanabroadBlogspotCom(item): ''' Parser for 'ian-englishmanabroad.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagma
p = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseM
essageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) return False
pgurumur/netconf
core/lib/__init__.py
Python
isc
791
0.001264
# Copyright (c) 2015 Prabhu Gurumurthy <[email protected]> # Permission to use, copy, modify, and distribute this softw
are for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FI...
ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Tatsh-ansible/ansible
lib/ansible/modules/remote_management/foreman/katello.py
Python
gpl-3.0
16,607
0.002409
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Eric D Helms <[email protected]> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.0', ...
if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Lifecycle Found found for %s" % name) def find_product(self, name, org
anization): org = self.find_organization(organization) product = self._entities.Product(self._server, name=name, organization=org) response = product.search() if len(response) == 1: return response[0] else: self._module.fail_json(msg="No Product found fo...
freevo/freevo1
src/video/plugins/filmaffinity.py
Python
gpl-2.0
23,935
0.007312
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------- # Plugin for FILMAFFINITY support # ----------------------------------------------------------------------- # $Id$ # Version: 080607_01 # # Notes: FilmAffinity plugin. You can add FilmAffinity.com informations for video it...
self.reason = 'SYS_USE_NETWORK not enabled' return plugin.ItemPlugin.__init__(self) def config(self): return [ ('FILMAFFINITY_REMOVE_FROM_LABEL', ('\(.*?\)', '\[.*?\]', 'cd[0-9]+(-[0-9])?', 'title[0-9]+', 'by .*$'), _('Remove matching of this regexps from item name')), ...
EARCHSTRING', ('spanish','xvid','dvdrip','parte','[0-9]*','dvdscreener','mp3'), _('Remove matching of this regexps from search string')), ('FILMAFFINITY_AUTOACCEPT_SINGLE_HIT', True, _('Accept search automatically if it has only one result')) ] def initmyself(self): self.isdiscset =...
ajmarks/gymnast
gymnast/filters/stream_filter.py
Python
mit
2,087
0.003833
""" Abstract base class for stream filters """ import six from collections import namedtuple from warnings import warn from ..misc import ensure_str, MetaGettable base = namedtuple('StreamFilter', ('filter_name','decoder', 'EOD', 'encoder')) base.__new__.__defaults__ = (None, None) class StreamFilterBase(base)...
rs from the stream dictionary.""" if self.encoder: return self.encoder(data, **kwargs) + (self.EOD if self.EOD else b'') else: warn('Encoding for {} not implemented'.format(self.filter_name)) return data + (self.EOD if self.EOD else b'') @six.add_metaclass(Me...
filters are registered by calling PdfOperation.register() and passing a subclass of StreamFilterBase. Information on filters at can be found at https://partners.adobe.com/public/developer/en/ps/sdk/TN5603.Filters.pdf""" # Nothing to see here. Pay no attention to that man behind the curtain. _filte...
sebastian-software/jasy
jasy/script/api/Data.py
Python
mit
27,459
0.00346
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # Copyright 2013-2014 Sebastian Werner # import jasy.script.api.Text as Text from jasy.script.util import * import jasy.core.Console as Console from jasy import UserError class ApiData(): """ Container for all relevant API data. Automat...
if callName == "core.Module": self.setMain(callName, callNode.parent, self.id) staticsMap = getParameterFromCall(callNode, 1) if staticsMap: success = True self.statics = {} for staticsEntry in staticsM...
Invalid core.Module()", callNode.line) # # core.Interface # elif callName == "core.Interface": self.setMain(callName, callNode.parent, self.id) configMap = getParameterFromCall(callNode, 1) if configMap: ...
levilucio/SyVOLT
UMLRT2Kiltera_MM/MT_post__Par.py
Python
mit
9,121
0.017542
""" __MT_post__Par.py_____________________________________________________ Automatically generated AToM3 syntactic object (DO NOT MODIFY DIRECTLY) Author: gehan Modified: Sun Feb 15 10:31:27 2015 ______________________________________________________________________ """ from ASGNode import * from ATOM3Type import * ...
tring import * from graph_MT_post__Par import * class MT_post__Par(ASGNode, ATOM3Type): def __init__(self, parent = None): ASGNode.__init__(self) ATOM3Type.__init__(self) self.superTypes = ['MT_post__Proc', 'MT_post__MetaModelElement_T'] self.graphClass_ = graph_MT_post__Par self.isGra...
self._setHierarchicalLink(False) if(hasattr(self, '_setHierarchicalNode')): self._setHierarchicalNode(False) self.parent = parent self.MT_post__cardinality=ATOM3Text('\n#===============================================================================\n# You can access the value of the curre...
AlpineNow/python-alpine-api
alpine/alpineobject.py
Python
mit
2,190
0.002283
from __future__ import unicode_literals from __future__ import absolute_import import json import logging import logging.config import os class AlpineObject(object): """ Base Class of Alpine API objects """ # # alpine alpine version string # _alpine_api_version = "v1" _min_alpine_ver...
ting_file='l
ogging.json', default_level=logging.INFO, env_key='LOG_CFG'): """ Sets internal values for logging through a file or an environmental variable :param str default_configuration_setting_file: Path to logging config file. Will be overwritten by ...
Raukonim/piva
prac7_2.py
Python
gpl-3.0
897
0.069119
# -*- coding: utf-8 -*- """ Created on Wed Apr 22 09:37:42 2015 @author: raukonim """ from pylab import * from scipy.misc import lena from skimage.
data import camera close("all") interactive(True) imfourier=fftshift(fft2(lena())) dimen=imfourier.shape x,y=meshgrid(linspace(-1,1,dimen[0]), linspace(-1,1,dimen[1])) filt=sqrt(x*x+y*y) passhigh=filt>0.6 passlow=filt<0.15 passband=(passhigh+passlow)==0 result=zeros([dimen[0],dimen[1],3], "complex") result[:...
2]=passhigh*imfourier iresult=zeros([dimen[0],dimen[1],3], "complex") iresult[:,:,0]=ifft2(result[:,:,0]) iresult[:,:,1]=ifft2(result[:,:,1]) iresult[:,:,2]=ifft2(result[:,:,2]) filtrada=abs(iresult) filtrada[:,:,0]/=filtrada[:,:,0].max() filtrada[:,:,1]/=filtrada[:,:,1].max() filtrada[:,:,2]/=filtrada[:,:,2].max() ...
mahim97/zulip
zerver/management/commands/realm_emoji.py
Python
apache-2.0
2,486
0.001207
import sys from argparse import ArgumentParser, RawTextHelpFormatter from typing import Any from django.core.management.base import CommandParser from zerver.lib.actions import check_add_realm_emoji, do_remove_realm_emoji from zerver.lib.management import ZulipBaseCommand class Command(ZulipBaseCommand): help =...
rser.add_argument('name', metavar='<name>', type=str, nargs='?', default=None, help="name of the emoji") parser.add_argument('img_url', metavar='<image url>', type=str, nargs='?', help="URL of image to display for the emoji") self.add_realm_args(pa...
ons) assert realm is not None # Should be ensured by parser if options["op"] == "show": for name, url in realm.get_emoji().items(): print(name, url) sys.exit(0) name = options['name'] if name is None: self.print_help("./manage.py", "r...
beaker-project/beaker
Misc/rpmlint-config.py
Python
gpl-2.0
3,395
0.004418
from Config import addFilter # It's true, our server-side man pages are deficient addFilter(r'(beaker-server|beaker-lab-cont
roller)\.noarch: W: no-manual-page-for-binary') # Kid templates produce a .pyc without a corresponding .py when they are compiled addFilter(r'python-bytecode-without-source /usr/lib/python.*/site-packages/bkr/server/templates/.*\.pyc') # We ship the same logrotate config file for both server and lab-controller, # so ...
ker/server\.cfg') addFilter(r'non-readable /etc/sudoers\.d/beaker_proxy_clear_netboot') # These are intentionally non-executable, they are executed on test systems instead addFilter(r'non-executable-script /usr/share/bkr/lab-controller/(anamon|anamon\.init|anamon\.service)') # This is intentionally not-executable, th...
eldie1984/Scripts
pg/pruebas/prueba_ses.py
Python
gpl-2.0
1,904
0.028361
import paramiko ses_dict={} sesiones=[] upr=[] ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('yvasa850', username='e449806', password='Ema84nue') chan = ssh.invoke_shell() # Ssh and wait for the password prompt. chan.send('su - mwpsyz01 \n') buff = '' #i=0
while not 'Password:' in buff: resp = chan.recv(9999) buff += resp # i = i + 1 # print "%s: %s" %(i,resp) # if i==20 or resp.endswith('Password:'): # ssh.close() # exit() # Send the password and wait for a prompt. chan.send('Sam0la\'P\n') buff = '' i=0 while not 'mwpsyz01 >' in buf
f: resp = chan.recv(9999) buff += resp # i = i + 1 # print "%s: %s" %(i,resp) # if i==20 or resp.endswith('mwpsyz01 >'): # ssh.close() # exit() # ## Execute whatever command and wait for a prompt again. chan.send('uxlst ses ses=\* | grep -v "Commande" | grep -v "SESSION" | grep -v "\-\-\-...
Antiun/purchase-workflow
purchase_discount/__openerp__.py
Python
agpl-3.0
1,604
0
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (c) 2014-2015 Serv. Tecnol. Avanzados - Pedro M. Baeza # # This program is free software: ...
ted in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public Li
cense # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { "name": "Purchase order lines with discounts", "author": "Tiny, " "Acysos S.L., " "Serv. Tecnol. Avanzados - Pedro M. Ba...
h2oai/h2o-3
h2o-py/h2o/model/metrics_base.py
Python
apache-2.0
105,732
0.00419
# -*- encoding: utf-8 -*- """ Regression model. :copyright: (c) 2016 H2O.ai :license: Apache License Version 2.0 (see LICENSE for details) """ from __future__ import absolute_import, division, print_function, unicode_literals from h2o.model.confusion_matrix import ConfusionMatrix from h2o.plot import decorate_plot_...
sRegressionGLM', 'ModelMetricsRegressionGLMGeneric', 'ModelMetricsRegression', 'ModelMetricsRegr
essionGeneric'] types_w_mean_per_class_error = ['ModelMetricsBinomial', 'ModelMetricsBinomialGeneric', 'ModelMetricsOrdinal', 'ModelMetricsOrdinalGeneric'] + types_w_mult types_w_logloss = types_w_bin + types_w_mult+types_w_ord types_w_dim = ["ModelMetrics...
ml-101/templates
readers.py
Python
mit
1,577
0.001268
import tens
orflow as tf import tensorflow.contrib.slim as slim class BaseReader(object): def read(self): raise NotImplementedError() class ImageReader(BaseReader): def __init__(self): self.width = None self.height = None def get_image_size(self): return self.width, self.height ...
ename, num_classes, batch_size=256, feature_map=None): assert(self.width is not None and self.height is not None) assert(self.width > 0 and self.height > 0) reader = tf.TFRecordReader() tf.add_to_collection(filename, batch_size) # is this really needed? key, value = reader.read_...
ntt-sic/neutron
neutron/db/migration/alembic_migrations/versions/53bbd27ec841_extra_dhcp_opts_supp.py
Python
apache-2.0
2,051
0.002438
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0
(the "License"); you may # not us
e 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...
tenstartups/wal-e
wal_e/operator/backup.py
Python
bsd-3-clause
23,283
0
import errno import functools import gevent import gevent.pool import itertools import json import os import sys from io import StringIO from wal_e import log_help from wal_e import storage from wal_e import tar_partition from wal_e.exception import UserException, UserCritical from wal_e.worker import prefetch from wa...
= self._upload_pg_cluster_dir( start_backup_info, data_directory, version=version, *args, **kwargs) spec, uploaded_to, expanded_size_bytes = ret_tuple upload_good = True finally: if not upload_good: logger.warning(
'blocking on sending WAL segments', detail=('The backup was not completed successfully, ' 'but we have to wait anyway. ' 'See README: TODO about pg_cancel_backup')) if not while_offline: stop_back...
kkelk/MeanRecipes
meanrecipes/__main__.py
Python
bsd-2-clause
832
0.009615
#!/usr/bin/env python3 from flask import Flask, url_for, render_template, make_response, request from recipe import Recipe from sources.allrecipes import AllRecipesSource from average import average app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/recipe/search/<te...
) source = AllRecipesSource() intermediates = list(source.search(term)) working = Recipe(term, [], []) recipe = average(intermediates, working, silliness=float(silliness) / 100) resp = make_response(render_template('recipe.json', title=recipe.title, ingredients=recipe.ingredients, method=recipe.met...
resp.mimetype = 'application/json' return resp if __name__ == '__main__': app.run(debug = True)
h4/fuit-webdev
examples/lesson2/1.4/1.4.8.py
Python
mit
132
0
# -*- encoding: utf-8 -*- """ Строка со специальными символ
ами """ s = 'a\0b\0c' print s p
rint len(s)
bmya/odoo-support
web_support_client/models/__init__.py
Python
lgpl-3.0
382
0
# -*- coding: utf-8 -*- ############################################################################## # For copyright and license notices, see __openerp__.py file i
n module root # directory ############################################################################## from . import support from . import res_users # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidt
h=4:
zwChan/VATEC
~/eb-virt/Lib/site-packages/wheel/signatures/djbec.py
Python
apache-2.0
6,755
0.014656
# Ed25519 digital signatures # Based on http://ed25519.cr.yp.to/python/ed25519.py # See also http://ed25519.cr.yp.to/software.html # Adapted by Ron Garret # Sped up considerably using coordinate transforms found on: # http://www.hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html # Specifically add-2008-hwcd-4 and d...
ef xpt_add(pt1, pt2): (X1, Y1, Z1, T1) = pt1 (X2, Y2, Z2, T2) = pt2
A = ((Y1-X1)*(Y2+X2)) % q B = ((Y1+X1)*(Y2-X2)) % q C = (Z1*2*T2) % q D = (T1*2*Z2) % q E = (D+C) % q F = (B-A) % q G = (B+A) % q H = (D-C) % q X3 = (E*F) % q Y3 = (G*H) % q Z3 = (F*G) % q T3 = (E*H) % q return (X3, Y3, Z3, T3) def xpt_double (pt): (X1, Y1, Z1, _) ...
ZmG/openwhisk-tutorial
deploy_settings/urls.py
Python
apache-2.0
1,114
0.01167
# # Copyright 2015-2016 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language gover
ning permissions and # limitations under the License. # from django.conf import settings from django.conf.urls import patterns, include, url from django.views.generic import TemplateView from whisk_tutorial import views urlpatterns = patterns('', url(r'^$', views.homepage, name="home"), ) if settings.DEBUG is...
anuragkumarak95/wordnet
wordnet/bin/__init__.py
Python
gpl-3.0
90
0.011111
# Author Anurag Kumar 12 Sept, 2017 #init file for t
his module.. from .paint import pa
int
doordash/auto_ml
quantile_ml/utils_models.py
Python
mit
24,465
0.002984
import dill import os import sys from quantile_ml import utils_categorical_ensembling from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, ExtraTreesRegressor, AdaBoostRegressor, GradientBoostingRegressor, GradientBoostingClassifier, ExtraTreesClassifier, AdaBoostClassifier from sklearn.linear...
(model, LogisticRegression): return 'LogisticRegression' if isinstance(model, RandomForestClassifier): return 'RandomForestClassifier' if isinstance(model, RidgeClassifier): return 'RidgeClassifier' if isinstance(model, GradientBoostingClassifier): return 'GradientBoostingCla...
ce(model, ExtraTreesClassifier): return 'ExtraTreesClassifier' if isinstance(model, AdaBoostClassifier): return 'AdaBoostClassifier' if isinstance(model, SGDClassifier): return 'SGDClassifier' if isinstance(model, Perceptron): return 'Perceptron' if isinstance(model, Pass...
scheib/chromium
tools/binary_size/libsupersize/testdata/mock_toolchain/mock_readelf.py
Python
bsd-3-clause
11,261
0.007459
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import sys _HEADERS = """ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data...
.ro
.local PROGBITS 02c176f0 2c166f0 0c0e08 00 WA 0 0 16 [17] .data.rel.ro PROGBITS 02cd8500 2cd8500 104108 00 WA 0 0 16 [18] .init_array INIT_ARRAY 02ddc608 2ddc608 000008 00 WA 0 0 4 [19] .fini_array FINI_ARRAY 02ddc6f4 2ddc6f4 000008 00 WA 0 0 4 [20] .dynamic...
tseaver/google-cloud-python
tasks/google/cloud/tasks_v2beta2/proto/cloudtasks_pb2_grpc.py
Python
apache-2.0
29,408
0.00374
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from google.cloud.tasks_v2beta2.proto import ( cloudtasks_pb2 as google_dot_cloud_dot_tasks__v2beta2_dot_proto_dot_cloudtasks__pb2, ) from google.cloud.tasks_v2beta2.proto import ( queue_pb2 as google_dot_cloud_dot_tasks__v2beta2...
self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.ListQueues = channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/ListQueues", request_serializer=google_dot_cloud_dot_tasks__v2beta2_dot_proto_dot_cloudtasks__pb2.ListQueuesRequest.Ser...
self.GetQueue = channel.unary_unary( "/google.cloud.tasks.v2beta2.CloudTasks/GetQueue", request_serializer=google_dot_cloud_dot_tasks__v2beta2_dot_proto_dot_cloudtasks__pb2.GetQueueRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_tasks__v2beta2_dot_proto_...
zephyrplugins/zephyr
zephyr.plugin.jython/jython2.5.2rc3/Lib/pkgutil.py
Python
epl-1.0
19,027
0.001314
"""Utilities to support packages.""" # NOTE: This module must remain compatible with Python 2.3, as it is shared # by setuptools for distribution with Python 2.3 and up. import os import sys import imp import os.path from types import ModuleType from org.python.core import imp as _imp, BytecodeLoader __all__ = [ ...
onerror(name) except Exception: if onerror is not None: onerror(name)
else: raise else: path = getattr(sys.modules[name], '__path__', None) or [] # don't traverse path items we've seen before path = [p for p in path if not seen(p)] for item in walk_packages(path, name+'.', onerro...
xbmc/atv2
xbmc/lib/libPython/Python/Lib/lib-old/zmod.py
Python
gpl-2.0
2,363
0.007194
# module 'zmod' # Compute properties of mathematical "fields" formed by taking # Z/n (the whole numbers modulo some whole number n) and an # irreducible polynomial (i.e., a polynomial with only complex zeros), # e.g., Z/5 and X**2 + 2. # # The field is formed by taking all possible linear combinations of # a set of d ...
return ' '*(width - n) + s def lj(s, width): if type(s) is not type(''): s = `s` n = len(s) if n >= width: return s
return s + ' '*(width - n)
TheAlgorithms/Python
maths/jaccard_similarity.py
Python
mit
2,365
0
""" The Jaccard similarity coefficient is a commonly used indicator of the similarity between two sets. Let U be a set and A and B be subsets of U, then the Jaccard index/similarity is defined to be the ratio of the number of elements of their intersection and the number of elements of their union. Inspired from Wikip...
rue) 0.5 >>> setA = ['a', 'b', 'c', 'd', 'e'] >>> setB = ('c', 'd', 'e', 'f', 'h', 'i') >>> jaccard_similariy(setA,setB) 0.375 """ if isinstance(setA, set) and isinstance(setB, set): intersection = len(setA.intersection(setB))
if alternativeUnion: union = len(setA) + len(setB) else: union = len(setA.union(setB)) return intersection / union if isinstance(setA, (list, tuple)) and isinstance(setB, (list, tuple)): intersection = [element for element in setA if element in setB] i...