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
GadgetSteve/metrics
metrics/processargs.py
Python
mit
8,553
0.012043
"""Process command line arguments.""" import sys import os from optparse import OptionParser, BadOptionError usage_str = """python metrics [ options ] pgm1.ex1 [ pgm2.ex2 ... ] Metrics are computed for the source code files pgm1.ex1, pgm2.ex2, etc. At least one file name is required, else this message appears. Thre...
nt pKwds in self.__dict__ # set up option parser parser = MyOptionParser( '', version="%prog 0.8.1" ) parser.add_option("-f", "--files", dest="in_file_list", default=self.in_file_list, help="File containing list of p...
default= None, help="Name of a directory to recurse into. (Default is '.')" ) parser.add_option("-i", "--include", dest="include_metrics_str", default=self.include_metrics_str, help="list o...
nischalsheth/contrail-controller
src/config/utils/provision_bgp.py
Python
apache-2.0
7,230
0.002905
#!/usr/bin/python # # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # import json import copy from netaddr import IPNetwork from pprint import pformat from vnc_api.vnc_api import * from vnc_admin_api import VncApiAdmin def get_ip(ip_w_pfx): return str(IPNetwork(ip_w_pfx).ip) # end get_ip clas...
("BGP Router " + pformat(fq_name) + " already exists with uuid " + existing_obj.uuid) return except NoIdError: pass cur_id = vnc_lib.bgp_router_create(bgp_router_obj) cur_obj = vnc_lib.bgp_router_read(id=cur_id) # full-mesh with existing bgp ...
_fq_name=fq_name) bgp_router_ids = [bgp_dict['uuid'] for bgp_dict in bgp_router_list['bgp-routers']] bgp_router_objs = [] for id in bgp_router_ids: bgp_router_objs.append(vnc_lib.bgp_router_read(id=id)) for other_obj in bgp_router_objs: ...
dials/dials
tests/test_plot_reflections.py
Python
bsd-3-clause
445
0
from __future__ import annotations
import procrunner def test_run(dials_data, tmp_path): procrunner.run( (
"dials.plot_reflections", dials_data("centroid_test_data") / "experiments.json", dials_data("centroid_test_data") / "integrated.refl", "scan_range=0,5", ), working_directory=tmp_path, ).check_returncode() assert (tmp_path / "centroids.png").is_file()
healthchecks/healthchecks
hc/front/tests/test_add_discord.py
Python
bsd-3-clause
1,235
0
from django.test.utils import override_settings from hc.test import BaseTestCase @override_settings(DISCORD_CLIENT_ID="t1", DISCORD_CLIENT_SECRET="s1") class AddDiscordTestCase(BaseTestCase): def setUp(self): super().setUp() self.url = "/projects/%s/add_discord/" % self.project.code def test_...
tContains(r, "Connect Discord", status_code=200) self.assertContains(r, "discordapp.com/api/oauth2/authorize") # There should now be a key in session
self.assertTrue("add_discord" in self.client.session) @override_settings(DISCORD_CLIENT_ID=None) def test_it_requires_client_id(self): self.client.login(username="alice@example.org", password="password") r = self.client.get(self.url) self.assertEqual(r.status_code, 404) def tes...
yugangzhang/GitTest
CMS_Profile/94-sample.py
Python
bsd-3-clause
105,895
0.016292
#!/usr/bin/python # -*- coding: utf-8 -*- # vi: ts=4 sw=4 ################################################################################ # Code for defining a 'Sample' object, which keeps track of its state, and # simplifies the task of aligning, measuring, etc. ################################################...
({})].'.format(self.name, self.__class__.__name__) if append_md: md_current = { k : v for k, v in RE.md.items() } # Global md md_current.update(get_beamline().get_md()) # Beamline md # Self md #md_current.update(self.get_md()) ...
' for key, value in sorted(md_current.items()): text += '\n{}: {}'.format(key, value) logbook.log(text, logbooks=logbooks, tags=tags) def set_base_stage(self, base): self.base_stage = base self._init_axes(self._axes_definit...
conradstorz/raffle
run_raffle.py
Python
apache-2.0
364
0.013736
#!/usr/bin/python # Python 2/3 compatibility boilerplate from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import * # begin our implementation from raffle import * print(Fore.RED + 'Starting raffle.py.....') run(['john', 'mary', 'rodrigo', 'jane', 'julie', 'm
ichelle', 'goose', 'dan'])
mswart/pyopenmensa
tests/feed/test_lazy_canteen.py
Python
lgpl-3.0
1,685
0.000593
# -*- coding: UTF-8 -*- from datetime import date import re import pytest from pyopenmensa.feed import LazyBuilder @pytest.fixture def canteen(): return LazyBuilder() def test_date_converting(canteen): day = date(2013, 3, 7) assert canteen.dayCount() == 0 canteen.setDayClosed('2013-03-07') ass...
._days[day] = {'Hausgericht': ('Gulash', [], {})} assert canteen.hasMealsFor(day) is True canteen.setDayClosed(day) assert canteen.hasMealsFor(day) is False def test_add_meal(canteen): day = date(2013, 3, 7) canteen.addMeal(day, 'Hauptgericht', 'Gul
asch') assert canteen.hasMealsFor(day) def test_to_long_meal_name(canteen): day = date(2013, 3, 7) canteen.addMeal(day, 'Hauptgericht', 'Y'*251) canteen.hasMealsFor(day) def test_caseinsensitive_notes(canteen): day = date(2013, 3, 7) canteen.legendKeyFunc = lambda v: v.lower() canteen.se...
bitesofcode/projexui
projexui/resources/rc/__plugins__.py
Python
lgpl-3.0
343
0.017493
__recurse__ = False __toc__ = [r'projexui.resources.rc.pyqt4_projexui_apps_rc', r'projexu
i.resources.rc.pyqt4_projexui_default_rc', r'projexui.resources.rc.pyqt4_projexui_styles_rc', r'projexui.resources.rc.pyside_pro
jexui_apps_rc', r'projexui.resources.rc.pyside_projexui_default_rc', r'projexui.resources.rc.pyside_projexui_styles_rc']
deniscostadsc/playground
solutions/beecrowd/1005/1005.py
Python
mit
98
0
a = float(input()) b = float(input()) print('MEDIA = {:.
5f}'.format((a * 3.5 + b * 7.5
) / 11.0))
cbecker/LightGBM
examples/python-guide/simple_example.py
Python
mit
1,762
0
# coding: utf-8 # pylint: disable = invalid-name, C0111 import json import lightgbm as lgb import pandas as pd from sklearn.metrics import mean_squared_error # load or create your dataset print('Load data...') df_train = pd.read_csv('../regression/regression.train', header=None, sep='\t') df_test = pd.read_csv('../reg...
= df_test.dro
p(0, axis=1) # create dataset for lightgbm lgb_train = lgb.Dataset(X_train, y_train) lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train) # specify your configurations as a dict params = { 'task': 'train', 'boosting_type': 'gbdt', 'objective': 'regression', 'metric': {'l2', 'auc'}, 'num_lea...
MatthewCox/PyMoronBot
pymoronbot/config.py
Python
mit
4,668
0.000643
# -*- coding: utf-8 -*- import copy from ruamel.yaml import YAML from six import iteritems _required = ['server'] class Config(object): def __init__(self, configFile): self.configFile = configFile self._configData = {} self.yaml = YAML() self._inBaseConfig = [] def loadConf...
# not a collection, so just don't merge them pass else: try: # merge with + operator configData[key] += val except TypeError: # dicts can't merge with +...
try: for subKey, subVal in iteritems(val): if subKey not in configData[key]: configData[key][subKey] = subVal except (AttributeError, TypeError): # if eith...
PaddlePaddle/Paddle
python/paddle/fluid/contrib/mixed_precision/decorator.py
Python
apache-2.0
28,628
0.002655
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
, value=float(self._optimizer._learning_rate), dtype='float32', persistable=True) def backward(self, loss, startup_program=None, parameter_list=None, no_grad_set=None, ca...
ze. startup_program (Program|None): The startup Program for initializing parameters in `parameter_list`. parameter_list (list|None): A list of Variables to update. no_grad_set (set|None): A set of Variables should be ignored. callba...
jaffyadhav/django-resume-parser
manage.py
Python
unlicense
810
0
#!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "resumeparser.settings") 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. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv)
JuliaLang/JuliaBox
engine/src/juliabox/plugins/dns_gcd/impl_gcd.py
Python
mit
2,592
0.002315
__author__ = 'Nishanth' from juliabox.cloud import JBPluginCloud from juliabox.jbox_util import JBoxCfg, retry_on_errors from googleapiclient.discovery import build from oauth2client.client import GoogleCredentials import threading class JBoxGCD(JBPluginCloud): provides = [JBPluginCloud.JBP_DNS, JBPluginCloud.JB...
ordSet', 'type': 'A', 'name': name,
'ttl': ttl} ] }).execute() JBoxGCD.log_warn('Prior dns registration was found for %s', name)
GbalsaC/bitnamiP
venv/lib/python2.7/site-packages/sympy/core/tests/test_evalf.py
Python
agpl-3.0
11,270
0.011713
from sympy.core.evalf import PrecisionExhausted, complex_accuracy from sympy import pi, I, Symbol, Add, Rational, exp, sqrt, sin, cos, \ fibonacci, Integral, oo, E, atan, log, integrate, floor, ceiling, \ factorial, binomial, Sum, zeta, Catalan, Pow, GoldenRatio, sympify, \ sstr, Function, Eq, Mul, Pow, De...
(sin(exp(pi*sqrt(163))*pi), 15) == '-2.35596641936785e-12' assert NS(sin(pi*10**100 + Rational(7,10**5), evaluate=False), 15, maxn=120) == \ '6.99999999428333e-5' assert NS(sin(Rational(7,10**5), evaluate=False), 15) == \ '6.99999999428333e-5' # Check detection of various false identities def t...
rmula f = lambda n: ((1+sqrt(5))**n)/(2**n * sqrt(5)) assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046' # Some near-integer identities from # http://mathworld.wolfram.com/AlmostInteger.html assert NS('sin(2017*2**(1/5))',15) == '-1.00000000000000' assert NS('sin(2017*2**...
wikimedia/pywikibot-core
scripts/checkimages.py
Python
mit
76,106
0
#!/usr/bin/python3 """ Script to check recently uploaded files. This script checks if a file description is present and if there are other problems in the image's description. This script will have to be configured for each language. Please submit translations as addition to the Pywikibot framework. Everything that ...
اهلا و سهلا}}\n~~~~\n', 'de': '{{subst:willkommen}} ~~~~', 'en': '{{subst:welcome}}\n~~~~\n', 'fa': '{{subst:خوشامدید|%s}}', 'fr': '{{Bienvenue nouveau\n~~~~\n', 'ga': '{{subst:Fáilte}} - ~~~~\n', 'hr': '{{subst:dd}}--
~~~~\n', 'hu': '{{subst:Üdvözlet|~~~~}}\n', 'it': '<!-- inizio template di benvenuto -->\n{{subst:Benvebot}}\n~~~~\n' '<!-- fine template di benvenuto -->', 'ja': '{{subst:Welcome/intro}}\n{{subst:welcome|--~~~~}}\n', 'ko': '{{환영}}--~~~~\n', 'ru': '{{subst:Приветствие}}\n~~~~\n', 'sd':...
redhat-openstack/trove
trove/tests/unittests/instance/test_instance_models.py
Python
apache-2.0
11,729
0
# Copyright 2014 Rackspace Hosting # Copyright 2014 Hewlett-Packard Development Company, L.P. # 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/li...
ist = self.check self.backup.delete() self.db_info.delete() super(CreateInstanceTest, self).tearDown() def test_exception_on_invalid_backup_size(self): self.assertEq
ual(self.backup.id, self.backup_id) exc = self.assertRaises( exception.BackupTooLarge, models.Instance.create, self.context, self.name, self.flavor_id, self.image_id, self.databases, self.users, self.datastore, self.datastore_version, self.volume_size,...
garyp/djwed
wedding/admin.py
Python
mit
10,509
0.008945
from django import forms from djwed.wedding.models import * from djwed.wedding.admin_actions import * from django.contrib import admin class RequireOneFormSet(forms.models.BaseInlineFormSet): """Require at least one form in the formset to be completed.""" def clean(self): """Check that at least one fo...
'guest_site', 'venue', 'status', 'food_selection', 'bus_selection', 'last_updated', 'prelim', 'guest_invitee', 'last_update_s
ource', 'guest', 'table_assign', ) search_fields = [ 'guest__first_name', 'guest__last_name', 'guest__invitee__guest__last_name', 'guest__invitee__invite_code', ] list_editable = ( 'status', '...
eliran-stratoscale/rackattack-physical
rackattack/physical/tests/integration/main_faketestclients.py
Python
apache-2.0
8,351
0.001317
import yaml import time import random import threading import subprocess from rackattack.physical import pikapatch from rackattack import clientfactory from rackattack.physical import config from rackattack.api import Requirement, AllocationInfo from rackattack.physical.tests.integration.main import useFakeGeneralConfi...
ints=None, pool=pool)) for nodeIdx in xrange(nrHosts)]) return requirements def _generateAllocationInfo(self): allocationInfo = AllocationInfo(user="johabab", purpose="loadTests") retu
rn allocationInfo def allocate(self, nrHosts, pool="default"): self._updateNrAllocatedHosts() self._allocate(nrHosts, pool) def _allocateForBackground(self): nrHosts = self._getRandomNrHosts() self._allocate(nrHosts) def _allocate(self, nrHostsToAllocate, pool="default"): ...
pshowalter/solutions-geoprocessing-toolbox
clearing_operations/scripts/PointTargetGRG.py
Python
apache-2.0
24,658
0.005272
# coding: utf-8 # # Esri start of added imports import sys, os, arcpy # Esri end of added imports # Esri start of added variables g_ESRI_variable_1 = 'lyrFC' g_ESRI_variable_2 = 'lyrTmp' g_ESRI_variable_3 = 'ID' g_ESRI_variable_4 = 'lyrOut' g_ESRI_variable_5 = ';' # Esri end of added variables #---------------------...
GetParameterAsText(4) cellUnits = arcpy.GetParameterAsText(5) gridSize = arcpy.GetParameterAsText(6) labelStartPos = arcpy.GetParameterAsText(7) labelStyle = arcpy.GetParameterAsText(8) outputFeatureClass =
arcpy.GetParameterAsText(9) tempOutput = os.path.join("in_memory", "tempFishnetGrid") sysPath = sys.path[0] appEnvironment = None DEBUG = True mxd = None mapList = None df, aprx = None, None def labelFeatures(layer, field): ''' set up labeling for layer ''' if appEnvironment == "ARCGIS_PRO": if lay...
dlu-ch/dlb
test/dlb/0/test_di.py
Python
lgpl-3.0
16,694
0.001498
# SPDX-License-Identifier: LGPL-3.0-or-later # dlb - a Pythonic build tool # Copyright (C) 2020 Daniel Lutz <dlu-ch@users.noreply.github.com> import testenv # also sets up module search paths import dlb.di import dlb.fs import sys import re import logging import time import io import collections import unittest cla...
self.format_info_message("start...") msg = "first non-empty line in 'message' must not end with '.'" self.assertEqual(msg, str(cm.exce
ption)) with self.assertRaises(ValueError) as cm: self.format_info_message("done.") msg = "first non-empty line in 'message' must not end with '.'" self.assertEqual(msg, str(cm.exception)) class MessageThresholdTest(unittest.TestCase): def test_default_is_info(self): ...
vsoch/repofish
analysis/methods/1.run_find_repos.py
Python
mit
1,341
0.014169
from glob import glob import numpy import pickle import os # Run iterations of "count" to count the number of terms in each folder of zipped up pubmed articles home = os.environ["HOME"] scripts = "%s/SCRIPT/repofish/analysis/methods" %(home) base = "%s/data/pubmed" %os.environ["LAB"] outfolder = "%s/repos" %(base) ar...
atch_size) else: end = len(folde
rs) subset = folders[start:end] script_file = "%s/findgithub_%s.job" %(scripts,i) filey = open(script_file,'w') filey.writelines("#!/bin/bash\n") filey.writelines("#SBATCH --job-name=%s\n" %i) filey.writelines("#SBATCH --output=.out/%s.out\n" %i) filey.writelines("#SBATCH --error=.out/%s.er...
gasparmoranavarro/TopoDelProp
forms/frmSelec.py
Python
gpl-2.0
2,643
0.004162
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:/Users/Gaspar/.qgis/python/plugins/delPropiedad/forms_ui/frmSelec.ui' # # Created: We
d Jul 18 12:50:20 2012 # by: PyQt4 UI cod
e generator 4.8.6 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_frmSelec(object): def setupUi(self, frmSelec): frmSelec.setObjectName(_fromUtf8(...
nanodude/Torch200
Torch200.py
Python
gpl-3.0
2,015
0.002978
__author__ = 'Carlos' from time import sleep, time import minimalmodbus as mb import csv class Torch200: def __init__(self, com_port): mb.BAUDRATE = 9600 mb.TIMEOUT = 3 self.profile = mb.Instrument(com_port, 1) self.control = mb.Instrument(com_port, 2) self.start_time = No...
name = r'C:\Documents and Settings\Carlos\My Documents\Dropbox\torch\T200C+ ' + str(start_time) + r'.csv' csv_fp = open(file
name, 'wb') csv_out = csv.writer(csv_fp) csv_out.writerow(['time', 'set_point', 'ctrl_temp', 'prof_temp']) data = (meas_time - start_time, set_point, ctrl_temp, prof_temp) csv_out.writerow(data) else: if start_time is not None: ...
cjaymes/pyscap
src/scap/model/ocil_2_0/ChoiceQuestionResultType.py
Python
gpl-3.0
988
0.001012
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP is ...
or more details. # # You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http://www.gnu.org/licenses/>. from scap.model.ocil_2_0.QuestionResultType import QuestionResultType import logging logger = logging.getLogger(__name__) class ChoiceQuestionResultType(QuestionResu...
{'tag_name': 'answer', 'class': 'ChoiceAnswerType', 'max': 1}, ], }
acutesoftware/AIKIF
aikif/lib/cls_plan_BDI.py
Python
gpl-3.0
5,209
0.009023
# cls_plan_BDI.py import datetime class Plan_BDI(object): """ class for handling various plans fo
r AIKIF using Belief | Desires | Intentions """ def __init__(self, name, dependency): self.name = name self.id = 1 self.dependency = dependency self.plan_version = "v0.10" self.success = False self.start_date = datetime.datetime.now().strftime("%I:%M%...
def __str__(self): res = "---== Plan ==---- \n" res += "name : " + self.name + "\n" res += "version : " + self.plan_version + "\n" for i in self.beliefs.list(): res += "belief : " + i + "\n" for i in self.desires.list(): ...
SIM-TU-Darmstadt/mbslib
dependencies/mbstestlib/src/testsetXML2intermediateConverter.py
Python
lgpl-3.0
9,479
0.007068
#!/usr/bin/python #=============================================================================== # # conversion script to create a mbstestlib readable file containing test specifications # out of an testset file in XML format # #=============================================================================== # Input c...
e').length == 0: _state.error_occured_while_processing_xml = True pri
nt("No cases defined!") return dict([]) cases = dict([]) for case in mbs.getElementsByTagName('case'): # TODO: sanity check -> number collisions # parse case case_nr = case.getAttribute('nr') case_desc = case.getAttribute('desc') ca...
vgrem/Office365-REST-Python-Client
office365/sharepoint/files/move_operations.py
Python
mit
105
0
class MoveOperations: """Specifies criteria for how to move files.
""" no
ne = 0 overwrite = 1
livni/old-OK
src/knesset/mks/migrations/0004_add_members_residence.py
Python
bsd-3-clause
6,016
0.009142
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Member.area_of_residence' db.add_column('mks_member', 'area_of_residence', self.gf('dj...
dels.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}), 'current_party': ('django.db.models.fields
.related.ForeignKey', [], {'related_name': "'members'", 'blank': 'True', 'null': 'True', 'to': "orm['mks.Party']"}), 'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}), 'date_of_death': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank':...
zestedesavoir/Python-ZMarkdown
zmarkdown/blockparser.py
Python
bsd-3-clause
3,639
0
from __future__ import unicode_literals from __future__ import absolute_import from . import util from . import odict class State(list): """ Track the current and nested state of the parser. This utility class is used to track the state of the BlockParser and support multiple levels if nesting. It's just...
lf.pop() def isstate(self, state): """ Test that top (current) level is of given state. """ if len(self): return self[-1] == state else: return False class BlockParser: """ Parse Markdown blocks into an ElementTree object. A
wrapper class that stitches the various BlockProcessors together, looping through them and creating an ElementTree object. """ def __init__(self, zmarkdown): self.blockprocessors = odict.OrderedDict() self.state = State() self.zmarkdown = zmarkdown def parseDocument(self, line...
thesecretlab/snippet-expander
tests/test_source_document.py
Python
mit
1,336
0.004491
import unittest from source_document import SourceDocument from test_tagged_document import create_test_repo from tagged_document import TaggedDocument class SourceDocumentTests(unittest.TestCase): """Unit tests for the Document class""" def test_cleaning(self): # Tests removing snippets input...
contents, reference_text) def test_finding_documents(self): found_documents = SourceDocument.find("tests", ["txt"]) self.assertTrue(len(found_documents) == 7) def test_process
ing(self): # Tests rendering a snippet using tagged documents. repo = create_test_repo() tagged_documents = TaggedDocument.find(repo, ["txt"]) self.assertTrue(tagged_documents) input_path = "tests/sample.txt" reference_path = "tests/sample-expanded.txt" referen...
synw/django-alapage
alapage/management/commands/create_homepage.py
Python
mit
603
0.006633
from __future__ import print_function from d
jango.core.management.base import BaseCommand, CommandError from alapage.models import Page class Command(BaseCommand): help = 'Creates a homepage' def handle(self, *args, **options): content = "" #~ check if home exists home_exists = Page.objects.fil
ter(url='/').exists() #~ create page if not home_exists: Page.objects.create(url='/', title='Home', content=content) print("Homepage created") else: print("The homepage already exists with root url") return
dsaldana/phantoms_soccer2d
phantom_team/run_agent.py
Python
gpl-2.0
1,609
0.001243
#!/usr/bin/env python # ----
------------------------------------------------------------------------ # GNU General Pub
lic License v2 # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope t...
nkashy1/elastic-boogaloo
example.py
Python
mit
706
0.001416
from elastic_boogaloo import classifiers, distributions, scorers from elasticsearch import Elasticsearch es_client =
Elasticsearch('localhost:9200'
) scorer = scorers.ElasticsearchIndexTopScorer(es_client, 'megacorp') positive_distribution = distributions.ExponentialDistribution() negative_distribution = distributions.ExponentialDistribution() classifier = classifiers.UnopinionatedBinaryClassifier(scorer, positive_distribution, negative_distribution) print('Tra...
manhhomienbienthuy/scikit-learn
benchmarks/bench_plot_parallel_pairwise.py
Python
bsd-3-clause
1,272
0
# Author: Mathieu Blondel <mathieu@mblondel.org> # License: BSD 3 clause import time import matplotlib.pyplot as plt from sklearn.utils import check_random_state from sklearn.metrics.pairwise import pairwise_distances from sklearn.metrics.pairwise import pairwise_kernels def plot(func): random_state = check_ran...
l="one core") plt.plot(sample_sizes, multi_core, label="multi core") plt.xlabel("n_samples") p
lt.ylabel("Time (s)") plt.title("Parallel %s" % func.__name__) plt.legend() def euclidean_distances(X, n_jobs): return pairwise_distances(X, metric="euclidean", n_jobs=n_jobs) def rbf_kernels(X, n_jobs): return pairwise_kernels(X, metric="rbf", n_jobs=n_jobs, gamma=0.1) plot(euclidean_distances) p...
rananda/cfme_tests
cfme/tests/infrastructure/test_advanced_search_providers.py
Python
gpl-2.0
10,078
0.002977
# -*- coding: utf-8 -*- """This testing module tests the behaviour of the search box in the Provider section It does not check for filtering results so far.""" import fauxfactory import pytest from selenium.common.exceptions import NoSuchElementException from cfme.infrastructure import host from cfme.infrastructure.p...
lter_with_user_input_and_cancellation(single_provider): # Set up the filter search.fill_and_apply_filter( "fill_count(Infrastructure Provider.VMs, >=)", fill_callback={"COUNT": 0}, cancel_on_user_filling=True ) assert_no_cfme_exception() @pytest.mark.requires("test_can_open_advanced_se...
for fixture cleanup test_filter_save_cancel.filter_name = fauxfactory.gen_alphanumeric() logger.debug('Set filter_name to: {}'.format(test_filter_save_cancel.filter_name)) # Try save filter assert search.save_filter("fill_count(Infrastructure Provider.VMs, >)", test_filte...
weijia/djangoautoconf
djangoautoconf/management/commands/create_default_super_user.py
Python
bsd-3-clause
844
0.003555
from django.contrib.auth.models import User from django.core.management.base import BaseCommand from djangoautoconf.local_key_manager import get_default_admin_username, \ get_defa
ult_admin_password from djangoautoconf.management.commands.web_manage_tools.user_creator import create_admin def create_default_admin(): super_username = get_default_admin_username() super_password = get_default_admin_password() if not User.objects.filter(username=super_username).exists(): create_...
print("default admin created") else: print("default admin already created") class Command(BaseCommand): args = '' help = 'Create command cache for environment where os.listdir is not working' def handle(self, *args, **options): create_default_admin()
mattrobenolt/warehouse
warehouse/search/indexes.py
Python
apache-2.0
3,926
0
# Copyright 2013 Donald Stufft # # 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, so...
" BASIS, # WITHOUT WARR
ANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import, division, print_function from __future__ import unicode_literals import hashlib import os from elasticsearch impor...
ShaunKarran/homesense
esp8266/micropython/main.py
Python
gpl-3.0
403
0
import ujson
def json_load(file_name): with open(file_name, 'r') as f: data = ujson.loads(f.read()) return data def json_dump(file_name, data): with open(file_name, 'w') as f: f.write(ujson.dumps(data)) test_dict = { 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', } js
on_dump('test.json', test_dict) test_load = json_load('test.json') print(test_load)
EichlerLab/read_depth_genotyper
scripts/make_ml_output_summary.py
Python
mit
15,332
0.028111
import sys import socket import os import os.path from optparse import OptionParser #import scipy as scp import numpy as np import matplotlib.pyplot as plt import pylab import genome_management.kg_file_handling as kgf import math def file_exists(ls,file): for f in ls: if(f==file): return 1 ...
legend(leg) title("percent") print leg legend(leg) f.get_axes()[0].xaxis.set_ticks(range(21)) #f.add_axes([0,40,0,1],xticks=[0,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20],label='axis2
',axisbg='g') #[0,1,2,3,4,5,6,8,9,10,11,12,13,14,15,16,17,18,19,20]) f=figure(2) k=0 for pop,ihist in mode_hists.iteritems(): mode_hists[pop] = ihist/ihist.sum() #plot(x,hist,"|%s"%(colors[k])) #hist(x) vlines(x+float(k)/5,zeros,mode_hists[pop],color=colors[k],linew...
twitter/pants
contrib/python/src/python/pants/contrib/python/checks/checker/indentation.py
Python
apache-2.0
1,262
0.008716
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under th
e Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import tokenize from pants.contrib.python.checks.checker.common import CheckstylePlugin # TODO(wickman) Update this to sanitize line continuation styling as we have
# disabled it from pycodestyle.py due to mismatched indentation styles. class Indentation(CheckstylePlugin): """Enforce proper indentation.""" @classmethod def name(cls): return 'indentation' INDENT_LEVEL = 2 # the one true way def nits(self): indents = [] for token in self.python_file.tokens...
martazaryn/green-roofs-mappping
Green_Roof_MapPy/warsaw/views.py
Python
mit
3,276
0.025946
from django.contrib.auth import get_user_model, login, logout from django.contrib.auth.mixins import PermissionRequiredMixin, LoginRequiredMixin from django.db.models import Q # import for AJAX / dynamic searching from django.http import HttpResponseRedirect, Http404, HttpResponse from django.template import RequestCon...
stance=RequestContext(request)) #Needs expansion to show field for MultiPolygonField (now there is text Mpoly in the form, but no input place) class AddGree
nRoofView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): permission_required = ['warsaw.add_greenroof'] raise_exception = True model = GreenRoof #remember to import class form_class = AddGreenRoofForm def handle_no_permission(self): if not self.request.user.is_authenticated: return HttpResponseRed...
pudo/aleph
aleph/logic/collections.py
Python
mit
7,335
0.000273
import logging from datetime import datetime from collections import defaultdict from servicelayer.jobs import Job from aleph.core import db, cache from aleph.authz import Authz from aleph.queues import cancel_queue, ingest_entity, get_status from aleph.model import Collection, Entity, Document, Mapping from aleph.mod...
n model.""" log.debug("[%s] Aggregating model...", collection) aggregator.delete(origin=MODEL_ORIGIN) writer = aggregator.bulk() for document in Document.by_collection(collection.id): proxy = document.to_proxy(ns=collection.ns) writer.put(proxy, fragment="db", origin=MODEL_ORIGIN) fo...
, fragment="db", origin=MODEL_ORIGIN) writer.flush() def index_aggregator( collection, aggregator, entity_ids=None, skip_errors=False, sync=False ): def _generate(): idx = 0 entities = aggregator.iterate(entity_id=entity_ids, skip_errors=skip_errors) for idx, proxy in enumerate(ent...
MSC19950601/TextRank4ZH
textrank4zh/TextRank4Sentence.py
Python
mit
6,656
0.012715
#-*- encoding:utf-8 -*- ''' Created on Dec 1, 2014 @author: letian ''' import networkx as nx from Segmentation import Segmentation import numpy as np import math class TextRank4Sentence(object): def __init__(self, stop_words_file = None, delimiters='?!;?!。;…\n'): ''' `stop_words_file`:默认值为None...
iters=delimiters) self.sentences = None self.words_no_filter = None # 2维列表 self.words_no_stop_words = None self.words_all_filters = None self.graph = None self.key_sentences = None def train(self, text, lower = False, speech_tag_filter=T...
ard'): ''' `text`:文本内容,字符串。 `lower`:是否将文本转换为小写。默认为False。 `speech_tag_filter`:若值为True,将调用内部的词性列表来过滤生成words_all_filters。 若值为False,words_all_filters与words_no_stop_words相同。 `source`:选择使用words_no_filter, words_no_stop_words, words_all_filters中的哪一个来生成句子之间的相似度。 ...
hackultura/procult
procult/settings.py
Python
gpl-2.0
7,162
0.00014
# coding=utf-8 """ Django settings for procult project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ ""...
s/#databases # Alem disso, usando o dj-database-url que configura o banco a partir # da variavel de ambiente DATABASE_URL, e caso não encontre uma # utiliza um valor
padrão. # https://pypi.python.org/pypi/dj-database-url DATABASES = { 'default': dj_database_url.config( default='postgres://procult:123456@localhost/procult' ) } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'pt-BR' TIME_ZONE = 'America/Sao_Paulo' USE_...
t-brandt/acorns-adi
parallel/multiproc_utils.py
Python
bsd-2-clause
1,069
0.006548
import mutiprocessing ##########################
############################################ # Controllers for parallel execution, one per worker. # Return when a 'None' job (poison pill) is reached. ###################################################################### class Consumer(multiprocessing.Process): def __init__(self, task_queue, result_queue, b...
.__init__(self) self.task_queue = task_queue self.result_queue = result_queue self.block = block self.timeout = timeout def run(self): proc_name = self.name while True: next_task = self.task_queue.get(self.block, self.timeout) if next_task is ...
kkamkou/gitmostwanted.com
migration/versions/4a7b02b0a63_repos_mean_table.py
Python
mit
782
0.003836
"""repos_mean table Revision ID: 4a7b02b0a63 Revises: b75a76936b Create Date: 2015-11-05 11:25:32.920590 """ revision = '4a7b02b0a63' down_revision = 'b75a76936b' branch_labels = None depends_on = None from alembic import op from sqlalchemy.sql import func import sqlalchemy as sa def upgrade(): op.create_tabl...
Integer(), nullable=False), sa.Column('created_at', sa.Date(), nullable=False), sa.Column('value', sa.Float(), nullable=False), sa.ForeignKeyConstraint(
['repo_id'], ['repos.id'], name='fk_repos_mean_repo_id', ondelete='CASCADE' ), sa.PrimaryKeyConstraint('repo_id', 'created_at') ) def downgrade(): op.drop_table('repos_mean')
iotile/coretools
transport_plugins/awsiot/test/test_agent.py
Python
gpl-3.0
5,635
0.00213
import pytest import queue from iotile_transport_awsiot.mqtt_client import OrderedAWSIOTClient import time pytestmark = pytest.mark.skip("This distribution needs to be updated to work with asyncio gateway") def test_gateway(gateway, local_broker, args): """Make sure we can connect to the gateway by sending pack...
sert data == b'Hello world, this is tracing data!' def test_rpcs(gateway, hw_man, local_broker): """Make sure we can send rpcs.""" hw_man.connect(3, wait=
0.1) hw_man.controller() def test_script(gateway, hw_man, local_broker): """Make sure we can send scripts.""" script = bytearray(('ab'*10000).encode('utf-8')) progs = queue.Queue() hw_man.connect(3, wait=0.1) gateway.agents[0].throttle_progress = 0.0 hw_man.stream._send_highspeed(script, ...
sorenh/cc
vendor/Twisted-10.0.0/twisted/internet/ssl.py
Python
apache-2.0
7,496
0.002935
# -*- test-case-name: twisted.test.test_ssl -*- # Copyright (c) 2001-2009 Twisted Matrix Laboratories. # See LICENSE for details. """ SSL transport. Requires PyOpenSSL (http://pyopenssl.sf.net). SSL connections require a ContextFactory so they can create SSL contexts. End users should only use the ContextFactory cla...
del d['_context'] return d def __setstate__(self, state): self.__dict__ = state def getContext(self): """ Return an SSL context. """ return self._context class ClientContextFactory: """A context factory for SSL clients.""" isClient = 1 # S...
Lv2, SSLv3, and TLSv1. We disable SSLv2 below, # though. method = SSL.SSLv23_METHOD _contextFactory = SSL.Context def getContext(self): ctx = self._contextFactory(self.method) # See comment in DefaultOpenSSLContextFactory about SSLv2. ctx.set_options(SSL.OP_NO_SSLv2) r...
helloworldC2/VirtualRobot
porc/pages.py
Python
mit
2,872
0.000696
from .resource import Resource from collections import Iterator import copy try: # python 2 from urllib import quote except ImportError: # python 3 from urllib.parse import quote class Pages(Iterator): def __init__(self, opts, url, path, params): if isinstance(path, list): pag...
next page if self.response: self.response.raise_for_status() _next = self.response.links.get(val, {}).get('url') if _next: response = self._root_resource._make_request( 'GET', _next, params, **headers) self._handle_res(None...
'GET', '', params, **headers) self._handle_res(None, response) return response def _handle_res(self, session, response): """ Stores the response, which we use for determining next and prev pages. """ self.response = response def re...
RudolfCardinal/crate
crate_anon/crateweb/core/context_processors.py
Python
gpl-3.0
1,968
0
#!/usr/bin/env python """ crate_anon/crateweb/core/context_processors.py =============================================================================== Copyright (C) 2015-2021 Rudolf Cardinal (rudolf@pobox.com). This file is part of CRATE. CRATE is free software: you can redistribute it and/or modify ...
GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CRATE. If not, see <https://www.gnu.org/licenses/>. =============================================================================== **A common context dictionary for all Django requ
ests.** """ from typing import Any, Dict from django.conf import settings from django.http.request import HttpRequest from crate_anon.common.constants import CRATE_DOCS_URL, HelpUrl # noinspection PyUnusedLocal def common_context(request: HttpRequest) -> Dict[str, Any]: """ Returns a context used across t...
saketkc/moca
moca/helpers/exceptions.py
Python
isc
455
0.002198
from __future__ import print_function from __future__ import division from __future__ import absolute_import class MocaException(Exception): """Base class for MoCA Exceptions""" def __init__(self, ms
g): self.value = msg def __str__(self): """string representation of MoCA Exception Returns ------- mocastr: string representation """ mocastr = repr(self.value) r
eturn mocastr
siddhika1889/Pydev-Editor
tests/pysrc/extendable/static.py
Python
epl-1.0
143
0.020979
class TestStatic(object): @staticmethod def static1(self): pass @staticmethod d
ef
static2(self): pass
arizvisa/syringe
template/video/h264.py
Python
bsd-2-clause
2,279
0.005265
from ptypes import * v = 0 # FIXME: this file format is busted class seq_parameter_set_rbsp(pbinary.struct): class __pic_order_type_1(pbinary.struct): _fields_ = [ (1, 'delta_pic_order_always_zero_flag'), (v, 'offset_for_non_ref_pic'), (v, 'offset_for_top_to_botto...
(v, 'frame_crop_bottom_offset'), ] def __frame_crop(self): if self['frame_cropping_flag']: return __frame_crop_offset return dyn.clone(pbinary.struct,_fields_=[]) def __rbsp_trailing_bits(self): return 0 _fields_ = [ (8, 'profile_idc'), ...
(1, 'constraint_set1_flag'), (1, 'constraint_set2_flag'), (5, 'reserved_zero_5bits'), (8, 'level_idc'), (v, 'seq_parameter_set_id'), (v, 'pic_order_cnt_type'), (__pic_order, 'pic_order'), (v, 'num_ref_frames'), (1, 'gaps_in_frame_num_value_allowed_flag'), ...
Nikea/VisTrails
vistrails/core/db/locator.py
Python
bsd-3-clause
30,882
0.005375
############################################################################### ## ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: contact@vistrails.org ## ## This file is part of VisTrails. ## ## "Redistribution and use in source and binary for...
ledLocator(_UntitledLocator, CoreLocator): def load(self, klass=None): from vistrails.core.vistrail.vistrail import Vistrail if klass is None: klass = Vistrail obj = _UntitledLocator.load(self, klass.vtType) klass.convert(obj) obj.locator = self return obj...
def load(self, klass=None): from vistrails.core.vistrail.vistrail import Vistrail if klass is None: klass = Vistrail obj = _XMLFileLocator.load(self, klass.vtType) klass.convert(obj) obj.locator = self return obj def save(self, obj): is_b...
undeadpixel/mallet
test/fixtures/hmm_fixtures.py
Python
mit
1,846
0.008126
import mallet.hmm as h_mm import mallet.state as state # emissions def emissions(): return [ {'A': 0.25, 'B': 0.25, 'C': 0.5}, {'A': 0.55, 'B': 0.15, 'C': 0.3}, {'A': 0.675, 'B': 0.20, 'C': 0.125}, {'B': 0.5, 'C': 0.5}, {'A': 0.0, 'B': 0.5, 'C': 0.5} ] def invalid_...
, state_list[4]: 0.25 }, 4: {
state_list[4]: 0.15, state_list[5]: 0.85 }, 5: {} } def fake_transitions(state_list = None): if state_list is None: state_list = states() return { 1: { state_list[2]: 1.0, state_list[3]: 0.0 } } def states_w...
dwlehman/blivet
blivet/devicetree.py
Python
lgpl-2.1
42,702
0.001171
# devicetree.py # Device management for anaconda's storage configuration module. # # Copyright (C) 2009-2014 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at you...
return self._lvs_cache def dropLVMCache(self): """ Drop cached lvm information. """ self._pvs_cache = None # pylint: disable=attribute-defined-outside-init self._lvs_cache = None # pylint: disable=attribute-defined-outside-init def _addDevice(self, newdev, new=True): """ Add ...
e` Raise ValueError if the device's identifier is already in the list. """ if newdev.uuid and newdev.uuid in [d.uuid for d in self._devices] and \ not isinstance(newdev, NoDevice): raise ValueError("device is already in tree") # make sure this dev...
PeterHo/mysite
lists/migrations/0001_initial.py
Python
apache-2.0
420
0.002381
# -*- coding: utf-8
-*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(verbose_name='ID', serializ...
, ), ]
Yarrick13/hwasp
tests/wasp1/AllAnswerSets/aggregates_max_bug_1.test.py
Python
apache-2.0
92
0
inpu
t = """ % No auxiliary atoms at all. ouch :- #max{V:a(V)} = 0. "
"" output = """ {} """
eltoncarr/tubular
tubular/ec2.py
Python
agpl-3.0
19,451
0.001954
""" Convenience functions built on top of boto that are useful when we deploy using asgard. """ from __future__ import absolute_import from __future__ import unicode_literals import os import logging import time from datetime import datetime, timedelta import backoff import boto from boto.exception import EC2ResponseE...
cer`): List of ELBs to us in checking. Returns: :obj:`list` of :obj:`boto.ec2.elb.loadbalancer.LoadBalancer`: One or more ELBs used by the passed-in instance -or- None. """ instance_elbs = [] for elb in elbs: elb_instance_ids = [inst.id for inst in elb.instances] ...
tion(backoff.expo, BotoServerError, max_tries=MAX_ATTEMPTS, giveup=giveup_if_not_throttling, factor=RETRY_FACTOR) def active_ami_for_edp(env, dep, play): """ Given an environment, deployment, and play, find the base AMI id u...
spikeekips/serf-python
test/test_command_join.py
Python
mpl-2.0
1,679
0.008338
import pytest import serf from _base import FakeClient, FakeConnection def test_request_join () : _body = dict( Existing=('127.0.0.1:7901', ), Replay=True, ) _request = serf.get_request_class('join')(**_body) _request.check(FakeClient(), ) assert _request.is_checked ...
serf.get_request_class('join')(**_body) with pytest.raises(serf.InvalidRequest,
) : _request.check(FakeClient(), ) assert not _request.is_checked _body = dict( Existing=('127.0.0.1:7901', ), Replay=1, # invalid value, it must be bool ) _request = serf.get_request_class('join')(**_body) with pytest.raises(serf.InvalidRequest, ) : _...
UCL-INGI/Informatique-1
old_pythia/18_java/test/gendataset.py
Python
agpl-3.0
406
0.009901
# -*- coding: utf-8
-*- # Test datas
et script # Author: Sébastien Combéfis # Date: December 23, 2012 # Problem: Question de Bilan Final : Mission 1 from lib.pythia import * import random class TestDataSetQ1(TestDataSet): def __init__(self): TestDataSet.__init__(self, 'q1', 5) def genTestData(self): A = random.randint(1, 100...
JioCloud/python-ceilometerclient
ceilometerclient/exc.py
Python
apache-2.0
3,070
0.000326
# 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...
essage: return "%s (HTTP %s) ERROR %s" % ( self.__class__.__name__, se
lf.code, message) except (ValueError, TypeError, AttributeError): pass return "%s (HTTP %s)" % (self.__class__.__name__, self.code) class HTTPMultipleChoices(HTTPException): code = 300 def __str__(self): self.details = ("Requested version of OpenStack Images API is not" ...
rjdp/cement
cement/utils/test.py
Python
bsd-3-clause
2,208
0
"""Cement testing utilities.""" import unittest from tempfile import mkstemp, mkdtemp from ..core import backend, foundation from ..utils.misc import rando # shortcuts from nose import SkipTest from nose.tools import ok_ as ok from nose.tools import eq_ as eq from nose.tools import raises from nose.plugins.attrib imp...
r, msg) def eq(self, a, b, msg=None): """Shorthand for 'assert a == b, "%r != %r" % (a, b)'. """ return eq(a, b, msg) # The following are for internal, Cement unit testing only @attr('core') class CementCoreTestCase(CementTestCase): pass @attr('ext') class CementExtTestCase(CementTestCase)...
ss
popazerty/blackhole-vuplus
RecordTimer.py
Python
gpl-2.0
43,007
0.030321
import os from enigma import eEPGCache, getBestPlayableServiceReference, \ eServiceReference, iRecordableService, quitMainloop, eActionMap, setPreferredTuner from Components.config import config from Components.UsageConfig import defaultMoviePath from Components.TimerSanityCheck import TimerSanityCheck from Screens....
down elif
event == iRecordableService.evStart: print "RecordTimer.staticGotRecordEvent(iRecordableService.evStart)" @staticmethod def stopTryQuitMainloop(): print "RecordTimer.stopTryQuitMainloop" NavigationInstance.instance.record_event.remove(RecordTimerEntry.staticGotRecordEvent) RecordTimerEntry.receiveRecordEven...
JonSteinn/Kattis-Solutions
src/Fractal Area/Python 3/main.py
Python
gpl-3.0
448
0.017857
from math import pi def fractal_area(r,n): first = r**2 if n == 1: return first * pi second = 4 * (r/2)**2 if n == 2:
return (first + second) * pi rest = sum((r/2**i)**2 * 4*3**(i-1) for i in range(2,n)) return (first + second + rest) * pi def main(): for _ in range(int(input()))
: r,n = map(int, input().split()) print('%.6f' % fractal_area(r,n)) if __name__ == "__main__": main()
tommo/gii
tools/build/__init__.py
Python
mit
1,086
0.138122
import os import logging import argparse from gii.core import Project, app from gii.core.tools import Build cli = argparse.ArgumentParser( prog = 'gii build', description = 'Build GII Host(s) for current project' ) cli.add_argument( 'targets', type = str, nargs = '*', default = 'native' ) cli.add_argument( ...
'profile', help = 'release/debug ', default = 'debug' ) cli.add_argument( '--clean-bin', dest = 'clean-bin', help = 'Clean built binary files', action = 'store_true', default = False ) cli.add_argument( '--clean', dest = 'clean', help = 'Clean build files', action = 'sto
re_true', default = False ) cli.add_argument( '-v','--verbose', dest = 'verbose', help = 'Verbosal building log', action = 'store_true', default = False ) def main( argv ): app.openProject() args = cli.parse_args( argv[1:] ) code = Build.run( **vars( args ) ) exit( code )
lingpy/plugins
burmish/basics.py
Python
gpl-2.0
11,825
0.00882
# author : Johann-Mattis List # email : mattis.list@uni-marburg.de # created : 2014-09-10 19:49 # modified : 2014-09-10 21:17 """ Wordlist plugin for burmish data. """ __author__="Johann-Mattis List" __date__="2014-09-10" import unicodedata as ucd import re import sqlite3 import lingpyd from .unicode import * ...
elif kw['expand_nasals'] and char == nasal_char and vowel: out[-1] += char start = False nasal = True # check for weak diacritics elif char in semi_diacritics and not start and not vowel and not tone and out[-1] not in nogos: out[-1] += char ...
: out[-1] += char else: out += [char] start = False merge = True # check for vowels elif char in kw['vowels']: if vowel and kw['merge_vowels']: out[-1] += char else: ...
FRBs/DM
frb/dm_kde/sort_transient_data.py
Python
bsd-3-clause
4,742
0.015183
""" Module to correct pulsar and FRB DMs for the MW ISM """ from ne2001 import ne_io, density #ne2001 ism model import pygedm #ymw ism model import numpy as np import pandas as pd from astropy import units as u from astropy.coordinates import SkyCoord, Galactic import logging logging.basicConfig(format='%(asctime)s -...
able as a csv in the FRBs/FRB/frb/data/FRBs repo (FRB catalogue [Petroff et al. 2017]) Pulsar data is avaiable as a csv in the FRBs/pulsars/pul
sars/data/atnf_cat repo (v1.61 ATNF pulsar catalogue [Manchester et al. 2005]) Arguments: transient_type (str): Accepts 'frb' or 'pulsar'. transient_data (str): Path to data (in .csv format). ism_model (str): Model used to calculated the MW halo DM. ...
google/grr
grr/client/grr_response_client/components/chipsec_support/actions/__init__.py
Python
apache-2.0
99
0
#!/usr/
bin/env python """Conditional import for Chipsec. Only Linux is supported at this stag
e."""
dietrichc/streamline-ppc-reports
googleads/common.py
Python
apache-2.0
12,102
0.006363
# Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
oken') # The keys in the proxy dictionary that are used to construct a ProxyInfo # instance. _PROXY_KEYS = ('host', 'port') def GenerateLibSig(short_name): """Generates a library signature s
uitable for a user agent field. Args: short_name: The short, product-specific string name for the library. Returns: A library signature string to append to user-supplied user-agent value. """ return ' (%s, %s, %s)' % (short_name, _COMMON_LIB_SIG, _PYTHON_VERSION) def LoadFromStorage(path, product_yam...
SPbAU-ProgrammingParadigms/materials
python_2/common_objects.py
Python
unlicense
4,690
0.001066
import os import sys import string import random import math ################################################# # State balance = 0 def deposit(amount): global balance balance += amount return balance def withdraw(amount): global balance balance -= amount return balance ##################...
self.amount = amount class AdvancedBankAccount: MAX_BALANCE = 2 ** 64 def __init__
(self): self._balance = 0 self.__id = generate_id() def withdraw(self, amount): if not isinstance(amount, int): raise ValueError if self._balance < amount: raise WithdrawError(amount) self._balance -= amount return self._balance def depos...
ikvk/imap_tools
setup.py
Python
apache-2.0
1,092
0.001832
import os import re import setuptools def get_version(package: str) -> str: """Return package version as listed in __version__ variable at __init__.py""" init_py = open(os.path.join(package, '__init__.py')).read() return re.search(r"__version__\s*=\s*['\"]([^'\"]+)['\"]", init_py).group(1) with open("RE...
/imap_tools', license='Apache-2.0'
, long_description=long_description, long_description_content_type="text/x-rst", author='Vladimir Kaukin', author_email='KaukinVK@ya.ru', description='Work with email by IMAP', keywords=['imap', 'imap-client', 'python3', 'python', 'email'], classifiers=[ "Programming Language :: Pyth...
bruceg/bglibs
python/template/__init__.py
Python
lgpl-2.1
1,139
0.005268
# Copyright (C) 2000,2005 Bruce Guenter <bruce@untroubled.org> # #
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, or (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 copy of the GNU Lesser General Public # ...
geekonerd/smartplugs
data/transmit.py
Python
gpl-3.0
2,037
0.000491
import time import sys import RPi.GPIO as GPIO '''Stringhe binarie ON e OFF per le prese 1,2,3,4 mappate come a,b,c,d''' a_on = '' a_off = '' b_on = '' b_off = '' c_on = '' c_off = '' d_on = '0011100011000111011010001' d_off = '0011100011000111011010011' '''intervalli brevi/lunghi nel segnale e tra le r...
come PIN di invio dati''' GPIO.setup(PIN_DATA_DI_INVIO, GPIO.OUT) '''Ripetiamo la trasmissione per il numero di tentativi indicati''' for t in range(NUMERO_DI_TENTATIVI): for i in code: if i == '1': '''Bit = 1, accensione breve e poi spegnimento lungo del PIN...
GPIO.output(PIN_DATA_DI_INVIO, 1) time.sleep(intervallo_breve) GPIO.output(PIN_DATA_DI_INVIO, 0) time.sleep(intervallo_lungo) elif i == '0': '''Bit = 0, accensione lunga e poi spegnimento breve del PIN''' GPIO.outp...
coinwarp/python-altcoinlib
altcoin/core/key.py
Python
lgpl-3.0
1,510
0.000662
# Copyright (C) 2011 Sam Rushing # Copyright (C) 2012-2014 The python-bitcoinlib developers # Copyright (C) 2015 The python-altcoinlib developers # # This file is part of python-bitcoinlib. # # It is subject to the license terms in the LICENSE file found in the top-level # directory of this distribution. # # No part of...
range(padding, 32): new_buffer[idx] = mb[idx - padding] return new_buffer.raw def generate(self): global _ssl _ssl.EC_KEY_generate_key(self.k) return self.k __all__ = ( 'CAl
tcoinECKey', )
mikedh/trimesh
trimesh/voxel/encoding.py
Python
mit
27,436
0
"""OO interfaces to encodings for ND arrays which caching.""" import numpy as np import abc from ..util import ABC from . import runlength as rl from .. import caching try: from scipy import sparse as sp except BaseException as E: from ..exceptions import ExceptionModule sp = ExceptionModule(E) def _em...
or dim, size in enumerate(shape): axis = tuple(range(dim)) + tuple(range(dim + 1, ndims)) filled = np.any(dense, axis=axis) indices, = np.nonzero(filled) lower = indices.min() upper = indices.max() + 1 padding.append([lower, size - up
per]) slices.append(slice(lower, upper)) return DenseEncoding(dense[tuple(slices)]), np.array(padding, int) def _flip(self, axes): return FlippedEncoding(self, axes) def md5(self): return self._data.md5() def crc(self): return self._data.crc() @property ...
heyrict/exam
exam.py
Python
apache-2.0
16,883
0.001599
import os import pickle import random import re from datetime import datetime from data_processing import (InteractiveAnswer, _in_list, colorit, space_fill, split_wrd) BOARDER_LENGTH = 40 class Quest(): def __init__(self, q, sel=None, ta=None, args={}): ''' Class rep...
ot None: self.is_cached = True return qf if 'MainData.data' in os.listdir(): with open('MainData.data', 'rb') as f: qf = pickle.load(f) else: qf = self._load(queststr) with open('MainData.data', 'wb') as f: pick...
(QuestFormTextLoader): '''QuestForm Loader for excel files. Requires `pandas` module.''' def __init__(self, qcol, selcol=None, tacol=None, argcol={}): ''' Parameters ---------- questpattern : regex pattern for a question. necessary. qpattern : regex pattern for question ...
snyderks/advent-solutions
Day15.py
Python
mit
430
0
discs = [] # Create data discs.append((13, 11)) discs.append((5, 0)) discs.append((17, 11)) discs.append((3, 0)) discs.append((7, 2)) discs.append((19, 17)) discs.append((11, 0)) done = False t = 0 while d
one is False: done = True for i, disc in enumerate(discs): if (t + i + 1 + disc[1]) % disc[0] is not
0: done = False break if done: print(str(t)) break t += 1
Gehn/JustAChatBot
plugin_utils.py
Python
mit
5,651
0.028491
import json import datetime import threading from base_plugin import * import base_plugin #=============================================Messaging=================================== def send_message(recipient, message, mtype='chat'): ''' Send a message to recipient. :param recipient: The To field of your messa...
ile(item, path): ''' Syntactic sugar, write jsonified object to file. :param item: Any json-able item. :param path: path to log file. ''' with open(path, 'w+') as f: f.write(json.dumps(item)) def get_object_from_file(path):
''' Syntactic sugar, read jsonified object from file. :param path: path to log file where item is stored. Returns - json expanded item from log file. ''' with open(path, 'r') as f: item_str = f.read() return json.loads(item_str) def append_to_file(string, path): ''' Syntactic sugar, append string t...
datastreaming/mflow
examples/sender.py
Python
gpl-3.0
825
0.003636
import sys import os import time
try: import mflow except: sys.path.append(os.environ["PWD"] + "/../") import mflow import logging import numpy as np logger = logging.getLogger("mflow.mflow") logger.setLevel(logging.ERROR) address = "tcp://127.0.0.1:40000" stream = mflow.connect(address, conn_type=mflow.BIND, mode=mflow.PUSH, receive_...
= '{"htype": "array-1.0", "type": "int32", "shape": [10], "frame": %d}' % i data = np.zeros(10, dtype=np.int32) + i stream.send(header.encode(), send_more=True, block=True) stream.send(data.tobytes(), block=False) print("Sending message %d" % i) # Send out every 10ms ti...
JamesClough/networkx
networkx/readwrite/gml.py
Python
bsd-3-clause
23,163
0.000086
# encoding: utf-8 # Copyright (C) 2008-2016 by # Aric Hagberg <hagberg@lanl.gov> # Dan Schult <dschult@colgate.edu> # Pieter Swart <swart@lanl.gov> # All rights reserved. # BSD license. # # Author: Aric Hagberg (hagberg@lanl.gov) """ Read graphs in GML format. "GML, the G>raph Modelling Language, is ...
(rep) try: return literal_eval(rep) except SyntaxError: raise ValueError('%r is not a valid Python literal' % (orig_rep,)) e
lse: raise ValueError('%r is not a string' % (rep,)) @open_file(0, mode='rb') def read_gml(path, label='label', destringizer=None): """Read graph in GML format from path. Parameters ---------- path : filename or filehandle The filename or filehandle to read from. label : string, ...
rtfd/readthedocs.org
readthedocs/core/migrations/0003_add_banned_status.py
Python
mit
406
0
# -*- coding: utf-8 -*- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0002_make_userprofile_user_a_onetoonefield'), ] operations = [ migrations.AddField( model_name='userprofile', name='banned', ...
odels.BooleanField(default=False, verbose_name='
Banned'), ), ]
Azure/azure-sdk-for-python
sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2-beta/sample_get_operations.py
Python
mit
3,206
0.004055
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------...
_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) operations = list(document_model_admin_client.list_operations()) print("The following document model operations exist under my resource:") for operation in operations: print("\nOperation ...
atus: {}".format(operation.status)) print("Operation percent completed: {}".format(operation.percent_completed)) print("Operation created on: {}".format(operation.created_on)) print("Operation last updated on: {}".format(operation.last_updated_on)) print("Resource location of successful ...
rosmo/aurora
src/main/python/apache/aurora/common/cluster.py
Python
apache-2.0
3,365
0.007727
# # 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 ...
rait must be a Cluster.Trait subclass, got %s' % type(trait)) # TODO(wickman) Expose this in pystachio as a non-private or add
a load method with strict= return trait(trait._filter_against_schema(self)) def check_trait(self, trait): """Given a Cluster.Trait, typecheck that trait.""" trait_check = self.get_trait(trait).check() if not trait_check.ok(): raise TypeError(trait_check.message()) def with_traits(self, *tra...
landsat-pds/landsat_ingestor
ingestor/thumbnailer.py
Python
apache-2.0
3,430
0.005831
#!/usr/bin/env python import sys import os import numpy from osgeo import gdal, gdal_array TAIL_TRIM = 0.01 def get_band(filename, target_percent): ds = gdal.Open(filename) xsize = int(ds.RasterXSize * target_percent / 100.0) ysize = int(ds.RasterYSize * target_percent / 100.0) image = ds.GetRasterB...
um(
255, image)) image = image.astype('uint8') return image def thumbnail(root_scene, scene_dir, verbose=False): red_file = '%s/%s_B4.TIF' % (scene_dir, root_scene) grn_file = '%s/%s_B3.TIF' % (scene_dir, root_scene) blu_file = '%s/%s_B2.TIF' % (scene_dir, root_scene) if not os.path.exists(red_fil...
fake-name/ReadableWebProxy
common/memory.py
Python
bsd-3-clause
226
0.030973
import psutil def is_low_mem(): v = psutil.virtual_memory() threshold = v.total / 4 # If we have less then 25% ram free, we should stop feeding the
job system. if v.avai
lable < threshold: return True return False
commonssibi/gdcmdtools
gdcmdtools/put.py
Python
bsd-2-clause
15,440
0.009456
#!/usr/bin/env python # -*- coding: utf-8 -*- import csv import sys from apiclient.http import MediaFileUpload import apiclient.errors import urllib import requests import json import pprint import logging logger = logging.getLogger("gdput") #logger.setLevel(logging.ERROR) import random import os import json from ...
for (col,col_type) in zip(cols, self.csv_column_define): d = {"type":col_type, "name":c
ol} return_cols.append(d) return return_cols # read csv and convert to the fusion table def create_ft(self, target_file): table = { "name":self.title, "description":self.description, "isExportable":True,
yujanshrestha/pre-trained-keras-example
cam_animation.py
Python
mit
3,666
0.004364
import sys import os import argparse import tqdm import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from keras.models import load_model from vis.visualization.saliency import visualize_cam from train import DataGenerator from visualize import plot_row_item def get_model_predict...
_probability) plot_row_item(image_ax, labels_ax, cam, top_character_names, top_character_probabilities) weight_idx = os.path.basename(weight).split('.')[1] labels_ax.set_xlabel(npz_name) imag
e_ax.set_title(model_name + ', epoch ' + weight_idx) fig.add_subplot(image_ax) fig.add_subplot(labels_ax) plt.savefig(os.path.join(cam_path, 'cam_{}.png'.format(weight_idx))) plt.close(fig) if __name__ == '__main__': parser = argparse.ArgumentParser(description="Generate an animation of class-act...
domenicosolazzo/jroc
jroc/tasks/sparql/dbpedia/EntityAnnotationTask.py
Python
gpl-3.0
5,822
0.00687
from . import BasicTask from . import SPARQLAdapter class EntityAnnotationTask(BasicTask): """ EntityAnnotationTask: Annotate a list of entities with information from a SPARQL Endpoint """ __kernel = None # Kernel for this loader __inputKey = 'entities' # Expected input key def __init__(self, ...
or retrieving the types of a given entity" self.finish(data=None, failed=True, error=output) return self.getOutput() class EntityAnnotationPropertiesTask(BasicTask): __kernel = None # Kernel for this loader __inputKey = 'entity_name' # Expected input key __withPropertyValues = True ...
lse, withPropertyValues=True, properties=[]): super(EntityAnnotationPropertiesTask, self).__init__(name, initial_task) self.__withPropertyValues = withPropertyValues self.__requestedProperties = properties def execute(self, input): """ Execute a task """ ou...
danhuss/faker
setup.py
Python
mit
2,500
0
#!/usr/bin/env python import os from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)
) with open(os.path.join(here, 'README.rst'), encoding='utf-8') as
fp: README = fp.read() with open(os.path.join(here, 'VERSION')) as version_file: VERSION = version_file.read().strip() excluded_packages = ["docs", "tests", "tests.*"] if not os.environ.get('READTHEDOCS', False): excluded_packages += ["faker.sphinx", "faker.sphinx.*"] # this module can be zip-safe if th...
cihangxie/cleverhans
tests_tf/test_mnist_tutorial_cw.py
Python
mit
2,033
0
import unittest import numpy as np from cleverhans.devtools.checks import CleverHansTest class TestMNISTTutorialCW(CleverHansTest): def test_mnist_tutorial_cw(self): import tensorflow as tf from cleverhans_tutorials import mnist_tutorial_cw # Run the MNIST tutorial on a dataset of reduced...
in_end': 10000, 'test_start': 0, 'test_end': 1666, 'viz_enabled': False} g = tf.Graph() with g
.as_default(): np.random.seed(42) report = mnist_tutorial_cw.mnist_tutorial_cw(**cw_tutorial_args) # Check accuracy values contained in the AccuracyReport object self.assertTrue(report.clean_train_clean_eval > 0.85) self.assertTrue(report.clean_train_adv_eval == 0.00) ...
wellenreiter01/Feathercoin
contrib/seeds/makeseeds.py
Python
mit
5,457
0.003848
#!/usr/bin/env python3 # Copyright (c) 2013-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # # Generate seeds.txt from Pieter's DNS seeder # import re import sys import dns.resolver import collect...
# Skip bad results. if sline[1] == 0: return None # Extract uptime %. uptime30 = float(sline[7][:-1]) # Extract Unix timestamp of last success. lastsuccess = int(sline[2]) # Extract protocol version. version = int(sline[10]) # Extract user agent. agent = sline[11][1:-1] #...
t service flags. service = int(sline[9], 16) # Extract blocks. blocks = int(sline[8]) # Construct result. return { 'net': net, 'ip': ipstr, 'port': port, 'ipnum': ip, 'uptime': uptime30, 'lastsuccess': lastsuccess, 'version': version, '...
sciCloud/OLiMS
models/instrumenttype.py
Python
agpl-3.0
794
0.013854
from openerp imp
ort fields, models,osv from base_olims_model import BaseOLiMSModel from opene
rp.tools.translate import _ from fields.string_field import StringField from fields.text_field import TextField from fields.widget.widget import TextAreaWidget schema = (StringField('Title', required=1, ), TextField('Description', widget=TextAreaWidget( label...
tomfotherby/tower-cli
tests/test_commands_config.py
Python
apache-2.0
12,164
0
# Copyright 2015, Ansible, Inc. # Luke Sneeringer <lsneeringer@ansible.com> # # 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 requi...
ully.') # Ensure that the output seems to be correct. self.assertIn(mock.call('/etc/tower/tower_cli.cfg', 'w'), mock_open.mock_calls) self.assertIn(mock.call().write('username = luke\n'),
mock_open.mock_calls) def test_write_local_setting(self): """Establish that if we attempt to write a valid setting locally, that the correct parser's write method is run. """ # Invoke the command, but trap the file-write at the end # so we don't plow over real things...
eharney/cinder
cinder/image/image_utils.py
Python
apache-2.0
26,645
0
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in complianc...
hether O_DIRECT is supp
orted and set '-t none' if it is # This is needed to ensure that all data hit the device before # it gets unmapped remotely from the host for some backends # Reference Bug: #1363016 # NOTE(jdg): In the case of file devices qemu does the # flush properly and more efficiently than would be done #...
StYaphet/firefox-ios
taskcluster/scripts/get-secret.py
Python
mpl-2.0
2,717
0.004417
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import absolute_import, print_function, unicode_literals import argparse import ...
raise print("Outputting secret to: {}".format(path)) with open(path, 'a' if append else 'w') as f: value = data['secret'][key] if base64decode: value = base64.b64decode(value) if json_secret: v
alue = json.dumps(value) f.write(prefix + value) def fetch_secret_from_taskcluster(name): try: secrets = taskcluster.Secrets({ # BaseUrl is still needed for tasks that haven't migrated to taskgraph yet. 'baseUrl': 'http://taskcluster/secrets/v1', }) except taskc...
1995parham/Learning
ml/fasion-mnist/main.py
Python
gpl-2.0
1,163
0
import tensorflow as tf from tensorflow import keras print(tf.__version__) print(keras.__version__) fasion_mnist = keras.datasets.fashion_mnist (X_train_full, y_train_full), (X_test, y_test) = fasion_mnist.load_data() # pixel 0-255 # 28 x 28 images print(X_train_full.shape) print(X_train_full.dtype) # create valid...
X_train = X_train_full[:5000] / 255.0, X_train_full[5000:] / 255.0 y_valid, y_train = y_train_full[:5000], y_train_full[5000:] class_names = [ "T-shirt/top", "Trouser", "Pullover", "Dress", "Coat", "Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot", ] model = keras.models.Sequen...
.add(keras.layers.Dense(100, activation="relu")) # because we have 10 exclusive classes model.add(keras.layers.Dense(10, activation="softmax")) print(model.summary()) model.compile( loss="sparse_categorical_crossentropy", optimizer="sgd", metrics=["accuracy"], ) history = model.fit( X_train, y_train,...
loggerhead/Easy-Karabiner
tests/test_factory.py
Python
mit
11,690
0.000342
# -*- coding: utf-8 -*- from easy_karabiner.factory import * def test_create_keymap(): raw_keymap = [ 'KeyToKey', ['ctrl'], ['f12'], ] k = KeymapCreater.create(raw_keymap) s = ''' <autogen> __KeyToKey__ KeyCode::CONTROL_L, KeyCode::F12 </...
KeyCode::ESCAPE @end @begin KeyCode::COMMAND_R, ModifierFlag::CONTROL_R, ModifierFlag::OPTION_R, ModifierFlag::SHIFT_R @end
</autogen>''' util.assert_xml_equal(k, s) raw_keymap = [ 'KeyOverlaidModifier', ['caps'], ['ctrl'], ['esc'], ] k = KeymapCreater.create(raw_keymap) s = ''' <autogen> __KeyOverlaidModifier__ KeyCode::CAPSLOCK, @begin KeyCo...
viktorTarasov/PyKMIP
kmip/demos/pie/create.py
Python
apache-2.0
1,766
0
# Copyright (c) 2015 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/licenses/LICEN...
logger(logging.INFO) # Build and parse arguments parser = utils.build_cli_parser(enums.Operation.CREATE) opts, args = parser.parse_args(sys.argv[1:]) config = opts.config algorithm = opts.algorithm length = opts.length # Exit early if the arguments are not specified if algorithm is No...
arly from demo") sys.exit() algorithm = getattr(enums.CryptographicAlgorithm, algorithm, None) # Build the client and connect to the server with client.ProxyKmipClient(config=config) as client: try: uid = client.create(algorithm, length) logger.info("Successfully cr...