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
iTecAI/Stixai
Module/Stixai.py
Python
mit
1,343
0.010424
import random class ai: def __init__(self, actions, responses): self.IN = actions self.OUT = responses def get_act(self, action, valres): if action in self.IN: mList = {} for response in self.OUT: if self.IN[self.OUT.index(response)] == ...
print mList keys = [] vals = [] for v in sorted(mList.values(), reverse = True): for k in mList.keys(): if mList[k] == v: keys.append(k) vals.append(v) print keys pr...
else: resp = random.choice(self.OUT) return resp def update(ins, outs): self.IN = ins self.OUT = outs def test(): stix = ai(['attack', 'retreat', 'eat', 'attack', 'attack'], ['run', 'cheer', 'share lunch', 'fall', 'run']) ...
mukatee/pypro
src/pypro/snmp/loggers/csv_logger.py
Python
mit
1,847
0.003249
__author__ = 'teemu kanstren' import pypro.utils as utils import pypro.snmp.config as config class CSVFileLogger: files = {} def __init__(self): oids = config.SNMP_OIDS utils.check_dir() self.event_log = open(utils.event_log+".csv", "w", encoding="utf-8") event_header = "time...
cription self.event_log.write(line + "\n") self.event_log.flu
sh() if config.PRINT_CONSOLE: print(line)
maheshp/novatest
nova/virt/xenapi/volumeops.py
Python
apache-2.0
7,332
0.000546
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2010 Citrix Systems, Inc. # Copyright (c) 2013 OpenStack Foundation # # 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 # # ...
# Introduce VDI if 'vdi_uuid' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, vdi_uuid=connection_data['vdi_uuid']) elif '
target_lun' in connection_data: vdi_ref = volume_utils.introduce_vdi( self._session, sr_ref, target_lun=connection_data['target_lun']) else: # NOTE(sirp): This will introduce the first VDI in the SR vdi_ref = vol...
jenriquezdeceano/asit.mx
src/pagina/models.py
Python
gpl-3.0
502
0.033865
from django.db import models from django.utils.timezone import now # Create your models here. class Pagina(models.Model): titulo = models.CharField(max_length=200,
unique=True) contenido = models.TextField() imagen = models.ImageField(upload_to='pagina_img', default='media/default.png') orden = models.PositiveIntegerField() publicar = models.BooleanField() creado = models.DateField(default = now)
slug = models.SlugField(default='Slug default') def __str__(self): return self.titulo
ddu7/PyLC
041First Missing Positive.py
Python
mit
1,058
0.006593
# -*- coding: utf-8 -*- # Given an unsorted integer array, find the first missing positive integer. # # For example, # Given [1,2,0] return 3, # and [3,4,-1,1] return 2. # [1,3,4,2,5,8
,9,7] # Your algorithm should run in O(n) time and uses constant space. # 根据题目来看, find the first minimum missing positive integer, 所以一定是从1 开始的 # 本题的关键是合理利用下标, 即index值 # 第一次遍历, 将每个数与其下标对应, 1 对应 0, 2 对应 1... # 第二次遍历, 查看哪个index于其值不符, 即是first missing integer. class Solution(): def firstMissingPositive(self, A): ...
and A[i] - 1 < len(A) and A[i] != A[A[i] - 1]: A[A[i] - 1], A[i] = A[i], A[A[i] - 1] else: i += 1 for i, integer in enumerate(A): if integer != i + 1: return i + 1 return len(A) + 1 print Solution().firstMissingPositive([4,5,8,9,7...
Danielhiversen/home-assistant
homeassistant/components/sonos/binary_sensor.py
Python
apache-2.0
2,094
0.000478
"""Entity representing a Sonos power sensor.""" from __future__ import annotations import logging from typing import Any from homeassistant.components.binary_sensor import ( DEVICE_CLASS_BATTERY_CHARGING, BinarySensorEntity, ) from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const ...
Representation of a Sonos power entity.""" @property def unique_id(self) -> str: """Retu
rn the unique ID of the sensor.""" return f"{self.soco.uid}-power" @property def name(self) -> str: """Return the name of the sensor.""" return f"{self.speaker.zone_name} Power" @property def device_class(self) -> str: """Return the entity's device class.""" ret...
baidu/broc
client/TaskWorker.py
Python
apache-2.0
2,998
0.00467
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################################ # # Copyright (c) 2015 Baidu.com, Inc. All Rights Reserved # ################################################################################ """ Authors: zhousongsong(doublesongsong@gmail.c...
task = self._master.FetchTask() if isinstance(task, int) and task == -1: # master encounter error, break break if not task: #TODO no task to deal, sleep for a while continue response = dict() respon
se['result'] = True response['object'] = task # task whose type is LibCache and build cmd is empty, the lib is specified in Libs if task.TYPE == BrocObject.BrocObjectType.BROC_LIB and task.BuildCmd() is None: self._master.UpdateCache(task.Pathname()) s...
tensorflow/ngraph-bridge
examples/keras_sample.py
Python
apache-2.0
1,380
0.000725
# ============================================================================== # Copyright 2018-2020 Intel 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://ww...
============================= import tensorflow as tf from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions import numpy as np import ngraph_bridge # A simple script to run inference and training on resnet 50 model = ResNet50(weights='imagenet') batch_size = 128 img = np.r...
izers.SGD(), loss='categorical_crossentropy') preds = model.fit( preprocess_input(img), np.zeros((batch_size, 1000), dtype='float32')) print('Ran a train round')
edcast-inc/edx-platform-edcast
lms/djangoapps/instructor_task/tasks_helper.py
Python
agpl-3.0
64,173
0.003755
""" This file contains tasks that are designed to perform background operations on the running state of a course. """ import json from collections import OrderedDict from datetime import datetime from django.conf import settings from eventtracking import tracker from itertools import chain from time import time import...
k.DoesNotExist: # if the InstructorTask object does not exist, then there's no point # trying to update it. TASK_LOG.error(u"Task (%s) has no InstructorTask object for id %s", task_id, entry_id) else: TASK_LOG.warning(u"Task (%s) failed", task_id, exc_info=True) ...
re(einfo.exception, einfo.traceback) entry.task_state = FAILURE entry.save_now() class UpdateProblemModuleStateError(Exception): """ Error signaling a fatal condition while updating problem modules. Used when the current module cannot be processed and no more modules should be...
ewiger/plato
src/plato/__init__.py
Python
lgpl-3.0
1,105
0.002715
''' PyPlato is set of batching utilies useful in HPC scheduling context and shell (bash-like) automation in python. Copyright (C) 2013 Yauhen Yakimovich 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 Foundat...
HANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Pub
lic License for 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/> ''' import logging def getBasicLogger(name, level): logging.basicConfig(level=level, format='%(asctime)s %(name)-20s %(levelname...
sharmaking/DataApi
demo_32.py
Python
mit
439
0.078161
#!/usr/bin/python # -*- coding: utf-8 -*- from DataAp
i_32 import CDataProcess #from DataApi_Linux import CDataApi import datetime def main(): #HOST = '192.168.1.186' HOST = '180.166.168.126' #公网ip PORT = 18201 subStock = ["999999"] ApiInstance = CDataProcess(HOST,PORT, False, subStock, 0,1,datetime.datetime(2012,1,1,0,0,0),datetime.datetime(2012,01,1,0,0,0) ...
main()
lmazuel/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/troubleshooting_details_py3.py
Python
mit
1,841
0.005432
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRes
t Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class TroubleshootingDetails(Model): """Information gained from troubleshooting of specified ...
ummary of troubleshooting. :type summary: str :param detail: Details on troubleshooting results. :type detail: str :param recommended_actions: List of recommended actions. :type recommended_actions: list[~azure.mgmt.network.v2017_03_01.models.TroubleshootingRecommendedActions] """ _att...
dimagi/commcare-hq
corehq/apps/locations/tests/test_bulk_management.py
Python
bsd-3-clause
45,989
0.001719
from collections import defaultdict from decimal import Decimal from django.test import SimpleTestCase, TestCase from django.utils.functional import cached_property from unittest.mock import Mock, patch from corehq.apps.custom_data_fields.models import ( CustomDataFieldsDefinition, Field, ) from corehq.apps....
that were not matched by an expected error. This function has O(n**2) complexity on the number of errors. """ def find_and_remove(expected_error): for i, actual_error in enumerate(actual_errors): if expected_error in actual_error: del actual_errors[i] ret...
if missing_errors: errors.append("missing expected errors:") errors.extend(missing_errors) if actual_errors: if errors: errors.append("") errors.append("unexpected errors:") errors.extend(actual_errors) assert not errors, "\n".join(errors) class UploadTe...
sgerhart/ansible
lib/ansible/plugins/inventory/ini.py
Python
mit
16,758
0.003461
# Copyright (c) 2017 Ansible Project # 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 DOCUMENTATION = ''' inventory: ini version_added: "2.4" short_description: Uses an Ansibl...
ine in lines: self.lineno += 1 line = line.strip() # Skip empty lines and comments if not line or line[0] in self._COMMENT_MARKERS: continue # Is this a [section] header? That tells us what group we're parsing # definitions for, a...
n'].match(line) if m: (groupname, state) = m.groups() state = state or 'hosts' if state not in ['hosts', 'children', 'vars']: title = ":".join(m.groups()) self._raise_error("Section [%s] has unknown type: %s" % (title, ...
tradej/pcs
pcs/test/test_constraints.py
Python
gpl-2.0
103,383
0.005281
from __future__ import absolute_import from __future__ import print_function import os,sys import shutil import unittest parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,parentdir) import utils from pcs_test_functions import pcs,ac,isMinimumPacemakerVersion empty_cib = "empty....
expr) Resource: D5 Constraint: location-D5 Rule: score=INFINITY (id:location-D5-rule) Expression: date in_range 2005-001 to 2006-001 (id:location-D5-rule-expr) Resource: D6 Constraint: location-D6 Rule: score=INFINITY (id:loca
tion-D6-rule) Expression: (id:location-D6-rule-expr) Date Spec: years=2005 (id:location-D6-rule-expr-datespec) Ordering Constraints: Colocation Constraints: """) o,r = pcs("constraint remove location-C1-group") ac(o,"") assert r == 0 o,r = pcs("constraint remove loc...
hgijeon/the_PLAY
Structure/Scene/LoadingScene.py
Python
mit
245
0.004082
from .Scene import * from ..Vi
ew.LoadingScreenView import LoadingScreenView class LoadingScene(Scene): def initModel(self): pass def initMainView(self): self.mainView = LoadingScr
eenView(self, None, (1000, 1000))
thermokarst/qiime2
qiime2/core/type/grammar.py
Python
bsd-3-clause
20,252
0
# ---------------------------------------------------------------------------- # Copyright (c) 2016-2020, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
elf, fields): fields = tuplize(fields) for field in fields: if not isinstance(field, _AlgebraicExpBase): raise TypeError("Field %r is not complete type expression." % (field,)) self.template.validate_fields_expr(self, fields) re...
template, fields=fields) def equals(self, other): return self == other class _AlgebraicExpBase(_ExpBase): def __le__(self, other): first = self._is_subtype_(other) if first is not NotImplemented: return first second = other._is_supertype_(self) if second i...
brchiu/tensorflow
tensorflow/python/keras/engine/network.py
Python
apache-2.0
74,238
0.007207
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
e following are implemented as property functions: # self.trainable_weights # self.non_trainable_weights # self.input_spec # self.losses # self.updates self._init_set_name(name, ze
ro_based=True) self._activity_regularizer = None # This acts just like the `trainable` attribute of any layer instance. # It does not affect users of the underlying layers, only users of the # Network instance. self.trainable = True self._is_compiled = False self._expects_training_arg = Fals...
sillvan/hyperspy
hyperspy/io_plugins/__init__.py
Python
gpl-3.0
1,835
0.000545
# -*- coding: utf-8 -*- # Copyright 2007-2011 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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. # # HyperSpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the impli
ed warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with HyperSpy. If not, see <http://www.gnu.org/licenses/>. from hyperspy import messages from hyperspy.io_plugin...
zeyuanxy/code-forces
contest/665/C.py
Python
mit
688
0.005814
# -*- coding: utf-8 -*- # @Author: Zeyuan Shang # @Date: 2016-0
4-20 23:24:08 # @Last Modified by: Zeyuan Shang # @Last Modified time: 2016-04-21 00:08:03 import string d
ef choose(list, a, b): for x in list: if x != a and x != b: return x def solve(s): for i in xrange(0, len(s), 1a): if i > 0: left = s[i - 1] else: left = '0' if i + 1 < len(s): right = s[i + 1] else: right = '0'...
thelazier/dash
test/functional/feature_llmq_is_cl_conflicts.py
Python
mit
14,908
0.003019
#!/usr/bin/env python3 # Copyright (c) 2015-2021 The Dash Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. ''' feature_llmq_is_cl_conflicts.py Checks conflict handling between ChainLocks and InstantSend ''' from ...
other rawtx1 = self.create_raw_tx(self.nodes[0], self.nodes[0], 1, 1, 100)['hex'] rawtx2 = self.create_raw_tx(self.nodes[0], self.nodes[0], 1, 1, 100)['hex'] rawtx1_obj = FromHex(CTransaction(), rawtx1) rawtx2_obj = FromHex(CTransaction(), rawtx2) rawtx1_txid = self.nodes[0].sen...
[] n = 0 for out in rawtx1_obj.vout: if out.nValue == 100000000: inputs.append({"txid": rawtx1_txid, "vout": n}) n += 1 rawtx4 = self.nodes[0].createrawtransaction(inputs, {self.nodes[0].getnewaddress(): 0.999}) rawtx4 = self.nodes[0].signrawtransa...
olympiag3/olypy
tests/unit/test_olymap_char.py
Python
apache-2.0
8,125
0.002954
import olymap.char def test_get_char_attack(): tests = ( ({}, 0), ({'CH': {'at': ['60']}}, 60), ({'CH': {'de': ['1234']}}, 0), ({'IM': {'at': ['1234']}}, 0), ) for box, answer in tests: assert olymap.char.get_char_attack(box) == answer def test_get_char_break_point...
ests: assert olymap.char.get_faction(box, data) == answer def test_get_health(): tests = ( ({}, 'n/a'),
({'CH': {'he': ['100']}}, {'health': '100', 'status': None}), ({'CH': {'he': ['60']}}, {'health': '60', 'status': '(getting better)'}), ({'CH': {'he': ['60'], 'si': ['1']}}, {'health': '60', 'status': '(getting worse)'}), ({'CH': {'he': ['60'], 'si': ['0']}}, {'health': '60', 'status': '(get...
mattseymour/django
django/db/backends/base/introspection.py
Python
bsd-3-clause
7,643
0.002093
from collections import namedtuple # Structure returned by DatabaseIntrospection.get_table_list() TableInfo = namedtuple('TableInfo', ['name', 'type']) # Structure returned by the DB-API cursor.description interface (PEP 249) FieldInfo = namedtuple('FieldInfo', 'name type_code display_size internal_size precision sca...
continue for f in model._meta.local_fields: if isinstance(f, models.AutoField): sequence_list.append({'table': model._meta.db_table, 'column': f.column}) break # Only one AutoField is allowed per model, so don't bother continuing. ...
table, # we don't need to reset the sequence. if f.remote_field.through is None: sequence_list.append({'table': f.m2m_db_table(), 'column': None}) return sequence_list def get_key_columns(self, cursor, table_name): """ Backen...
jandom/rdkit
rdkit/ML/DecTree/UnitTestQuantTree.py
Python
bsd-3-clause
7,485
0.008016
## Automatically adapted for numpy.oldnumeric Jun 27, 2008 by -c # # Copyright (C) 2001,2003 greg Landrum and Rational Discovery LLC # """ unit tests for the QuantTree implementation """ from __future__ import print_function import unittest import io from rdkit import RDConfig from rdkit.ML.DecTree import BuildQuant...
uantTree.QuantTreeBoot(examples, attrs, nPossibleVals, boundsPerVar, maxDepth=1, recycleVars=1, randomDescript
ors=3) self.assertEqual(self.t1.GetLabel(), 49) self.assertEqual(self.t1.GetChildren()[0].GetLabel(), 3) self.assertEqual(self.t1.GetChildren()[1].GetLabel(), 54) if __name__ == '__main__': unittest.main()
baharev/apidocfilter
check.py
Python
bsd-3-clause
702
0.018519
from importlib import import_module from inspect import getdoc def attribs(name): mod = import_module(name) print name print 'Has __all__?', hasattr(mod, '__all
__') print 'Has __doc__?', hasattr(mod, '__doc__') print 'doc: ', getdoc(mod) if __name__=='__main__': attribs('cairo') attribs('zope') attribs('A.B.C') import hacked class Object(object): pass opt = Object() opt.ignore_errors = False a, d = hacked.get_all_...
) print(a) print(d)
mohitbs/mohitrepo
python/examples/lpthw/ex7.py
Python
gpl-2.0
448
0.004464
print "Mary had a little lamb." print "I
ts fleece was white as %s." % 'snow' print "And everywhere that Mary went." print "." * 10 #what'd that do? end1 = "C" end2 = "h" end3 = "e" end4 = "e" end5 = "s" end6 = "e" end7 = "B" end8 = "u" end9 = "r" end10 = "g" end11 = "e" end12 = "r" # watch that comma at the end. try removing it to see what happens print en...
nd7 + end8 + end9 + end10 + end11 + end12
UKTradeInvestment/export-wins-data
mi/sync_sectors.py
Python
gpl-3.0
2,373
0.000843
import logging logger = logging.getLogger(__name__) class SyncSectors: def __init__(self, sector_model, sectors, disa
ble_on=None, simulate=False): self.sector_model = sector_model self.sectors = sectors self.disable_on = disable_on self.simulate = simulate def log(self, msg, level=logging.DEBUG): logger.log(level, msg) def __call__(self, *args, **kwargs): self.process() d...
ess(self): self.add_new_sectors() self.update_existing_sectors() if self.disable_on: self.disable_sectors() def _get_sector(self, sector_id): try: return self.sector_model.objects.get(id=sector_id) except self.sector_model.DoesNotExist: re...
xian123/azure-linux-automation
remote-scripts/start-netperf-client.py
Python
apache-2.0
1,985
0.020655
#!/usr/bin/python from azuremodules import * import argparse import sys import time #for error checking parser = argparse.ArgumentParser() parser.add_argument('-H', '--serverip', help='specifies server VIP of server name', required=True) parser.add_argument('-u', '--udp', help='switch : starts the client in udp dat...
epTime) tmp = Run(cmd) status = isProcessRunning('netperf') if status == "True": time.sleep(60) Run('echo "ProcessRunning" >> iperf-client.txt') Run('echo "Waiting for 60 secs to let netperf process finish" >> iperf-client.txt') status = isProcessRunning('netper
f') if status == "True": Run('echo "ProcessRunning even after 60 secs delay" >> iperf-client.txt') else: Run('echo netperf process finished after extra wait of 60 secs >>iperf-client.txt') client = finalCommand RunTest(client) Run('echo "TestComplete" >> iperf-client.txt') AnalyseClientUpdateResult()
PaulWay/insights-core
insights/parsers/cinder_conf.py
Python
apache-2.0
1,823
0
""" Cinder configuration - file ``/etc/cinder/cinder.conf`` ======================================================= The Cinder configuration file is a standard '.ini' file and this parser uses the ``IniConfigFile`` class to read it. Sample configuration:: [DEFAULT] rpc_backend=cinder.openstack.common.rpc.imp...
nf.getboolean("DEFAULT", "glance_api_ssl_compression") False >>> conf.getint("DEFAULT", "glance_aip_version") 2 """ from .. import parser, IniConfigFile @parser("cinder.conf") class CinderConf(IniCon
figFile): """ Cinder configuration parser class, based on the ``IniConfigFile`` class. """ pass
chirpradio/chirpradio-machine
chirp/common/unicode_util.py
Python
apache-2.0
634
0.001582
# -*- coding: utf-8 -*- import unicodedata _CHARACTER_NORMALIZATIONS = { u"Ø": "O", u"ø": "o", } def simplify(text): """Simplify text by replacin
g diacritics. Args: text: A string Returns: A verison of 'text' where the diacritics are replaced by 7-bit ASCII characters. """ simplified_chars = [] for c in unicode(text): if unicodedata.category(c)[0] in ("L", "N"): c = unicodedata.normalize("NFD", c)[0] ...
simplified_chars.append(c) simplified = u"".join(simplified_chars) return simplified
daVinci1980/antebuild
internals/specs/cpp/dynlib.py
Python
bsd-3-clause
63
0.015873
from b
ase import CppBase class DynamicLib(CppBase): pass
hackoose/myicons
iconcollections/serializers.py
Python
bsd-2-clause
1,272
0.001572
import re fro
m rest_framework import serializers from .models import Collection, CollectionIcon class CollectionSerialize
r(serializers.ModelSerializer): """Collections's serializer""" class Meta: model = Collection read_only = ('token', ) class CollectionIconSerializer(serializers.ModelSerializer): """CollectionIcon's Serializer. """ class Meta: model = CollectionIcon def validate_width(...
jeorryb/datarambler
plugins/plantuml/generateUmlDiagram.py
Python
mit
2,006
0.000997
#!/usr/bin/env python import logging import os import tempfile from zlib import adler32 from subprocess import Popen, PIPE from pelican import logger def generate_uml_image(path, plantuml_code, imgformat): tf = tempfile.NamedTemporaryFile(delete=False) tf.write('@startuml\n'.encode('utf8')) tf.write(plant...
err = p.communicate() except Exception as exc: raise Exception('F
ailed to run plantuml: %s' % exc) else: if p.returncode == 0: # diagram was correctly generated, we can remove the temporary file (if not debugging) if not logger.isEnabledFor(logging.DEBUG): os.remove(tf.name) # renaming output image using an hash code, j...
gitrookie/functionalcode
code/FPinPython/test.py
Python
mit
207
0.004831
# test.
py def add_sum(n): result = [] for i in range(1, n+1): for j in range(1, n+1): if i + j == 7: result.append((i, j)) return result print(add_sum(6)
)
matslindh/codingchallenges
knowit2016/knowit10.py
Python
mit
1,694
0.001181
status = {'thief': True, 'wizard': True, 'warrior': True, 'priest': True} permadeath = {'wizard': False, 'warrior': False} survivor_goblins = 0 for room in range(1, 101): reanimated = False goblins = room while True: if status['thief']: goblins -= 1 if status['wizard']: ...
if not status['warrior'] and not permadeath['warrior']: status['warrior'] = True elif not status['wizard'] and not permadeath['wizard']: status['wizard'] = True else: reanimated = False if status['thief'] and not status['wizard'] and...
iest']: survivor_goblins += goblins break adventurers = sum([int(x[1]) for x in status.items()]) if goblins > 0 and adventurers * 10 <= goblins: if status['warrior']: status['warrior'] = False elif status['wizard']: status...
colonyhq/yowsup
yowsup/layers/axolotl/protocolentities/test_iq_keys_set.py
Python
gpl-3.0
999
0.002002
from yowsup.layers.protocol_iq.protocolentities.test_iq import IqProtocolEntityTest from yowsup.layers.axolotl.protocolentities import SetKeysIqProtocolEntity from yowsup.structs import ProtocolTreeNode class SetKeysIqProtocolEntityTest(IqProtocolEntityTest):
def setUp(self): super(SetKeysIqProtocolEntityTest, self).setUp() # self.ProtocolEntity = SetKeysIqProtocolEntity # # regNode = ProtocolTreeNode("registration", data = "abcd") # idNode = ProtocolTreeNode("identity", data = "efgh") # typeNode = ProtocolTreeN
ode("type", data = "ijkl") # listNode = ProtocolTreeNode("list") # for i in range(0, 2): # keyNode = ProtocolTreeNode("key", children=[ # ProtocolTreeNode("id", data = "id_%s" % i), # ProtocolTreeNode("value", data = "val_%s" % i) # ]) # ...
davidam/python-examples
statistics/bernoulli.py
Python
gpl-3.0
842
0.001188
from scipy.stats import bernoulli import matplotlib.pyplot a
s plt import numpy as np fig, ax = plt.subplots(1, 1) # Calculate a few first moments: p = 0.3 mean, var, skew, kurt = bernoulli.stats(p, moments='mvsk') # Disp
lay the probability mass function (pmf): x = np.arange(bernoulli.ppf(0.01, p), bernoulli.ppf(0.99, p)) ax.plot(x, bernoulli.pmf(x, p), 'bo', ms=8, label='bernoulli pmf') ax.vlines(x, 0, bernoulli.pmf(x, p), colors='b', lw=5, alpha=0.5) # Freeze the distribution and display the frozen pmf: rv = bernoulli(...
ingwinlu/simpleMediaCenter
simpleMediaCenter/helpers/twitch/__init__.py
Python
gpl-2.0
15,371
0.007417
#-*- encoding: utf-8 -*- import sys try: from urllib.request import urlopen, Request from urllib.parse import quote_plus except ImportError: from urllib import quote_plus from urllib2 import Request, urlopen try: import json except: import simplejson as json # @UnresolvedImport USER_AGENT = '...
while True: url = baseurl + Urls.OPTIONS_OFFSET_LIMIT.format(offset, limit) temp = self._fetchItems(url, Keys.FOLLOWS) if (len(temp) == 0): break; acc = acc + temp offset = offset + limit return acc def getTeams(self, index):...
tems(Urls.TEAMS.format(str(index * 25)), Keys.TEAMS) def getTeamStreams(self, teamName): ''' Consider this method to be unstable, because the requested resource is not part of the official Twitch API ''' quotedTeamName = quote_plus(teamName) url = Urls.TEAMSTREAM.for...
FedoraScientific/salome-smesh
src/Tools/blocFissure/CasTests/fissureCoude_4.py
Python
lgpl-2.1
4,424
0.027027
# -*- coding: utf-8 -*- from blocFissure.gmu.fissureCoude import fissureCoude class fissureCoude_4(fissureCoude): """ problème de fissure du Coude : ASCOU09A adaptation maillage """ # --------------------------------------------------------------------------- def setParamGeometrieSaine(self): """ ...
fissure (idem y,z) externe : True : fissure face externe, False : fissure face interne """ print "setParamShapeFissure", self.nomCas self.shapeFissureParams = dict(profondeur = 10, rayonPipe = 2.5, lenSegPipe =2.5, ...
longueur = 240, orientation = 90, lgInfluence = 30, elliptique = False, externe = True) # --------------------------------------------------------...
superduper/derpeddit
posts/serializers.py
Python
mit
1,715
0.001166
from rest_framework import serializers from core.serializers import ProfileSerializer from posts.models import Post, Vote, Comment from posts.serializers_fields import SubDocumentRelatedField, SubDocumentField class PostCreateSerializer(serializers.ModelSerializer): """ Used only when new post is created ...
PostSerializer(serializers.ModelSerializer): """ Read-only post serialization """ class Meta: model = Post owner = SubDocumentField(serializer=ProfileSerializer) comments_total = serializers.SerializerMethodField("get_comments_total") def get_comments_total(self, instance): ...
SubDocumentRelatedField(field="comments", serializer=CommentSerializer, many=True) class VoteSerializer(serializers.Serializer): """ Vote request parameter serializer """ positive = serializers.BooleanField(required=False) negative = serializers.BooleanField(required=False) def validate(self...
kombatcoin/KBK1
share/qt/clean_mac_info_plist.py
Python
mit
901
0.016648
#!/usr/bin/env python # Jonas Schnelli, 2013 # make sure the KombatKoin-Qt.app
contains the
right plist (including the right version) # fix made because of serval bugs in Qt mac deployment (https://bugreports.qt-project.org/browse/QTBUG-21267) from string import Template from datetime import date bitcoinDir = "./"; inFile = bitcoinDir+"/share/qt/Info.plist" outFile = "KombatKoin-Qt.app/Contents/Info...
pacocampo/Backend
semana2/lambda.py
Python
gpl-3.0
185
0.005405
g = map(l
ambda x: x**2, range(5)) print(g) g = list(map(lambda x: x**2, range(5))) print(g) lista = [1, 3, 5, 20, 50, 100] g = list(filter(lambda
x: x < 21 and x > 1, lista)) print(g)
ehartsuyker/securedrop
securedrop/secure_tempfile.py
Python
agpl-3.0
6,113
0
# -*- coding: utf-8 -*- import base64 import os import io import six from tempfile import _TemporaryFileWrapper from pretty_bad_protocol._util import _STREAMLIKE_TYPES from cryptography.exceptions import AlreadyFinalized from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.ciphe...
': raise AssertionError('You cannot write after reading!') self.last_action = 'write' # This is the old Python related code if six.PY2: # noqa if isinstance(data, unicode): data = data.encode('utf-8') elif isinstance(data, str): # noqa ...
rom the secure temporary file. This method may be called any number of times following instance initialization and once :meth:`write has been called at least once, but not before. Before the first read operation, `seek(0, 0)` is called. So while you can call this method any numb...
norus/procstat-json
tornado/platform/epoll.py
Python
gpl-3.0
2,147
0.001863
#!/usr/bin/env python # # Copyright 2012 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
epoll class _EPoll(object): """An epoll-based event loop using our C module for Python 2.5 systems""" _EPOLL_CTL_ADD = 1 _EPOLL_CTL_DEL = 2 _EPOLL_CTL_MOD = 3 def __init__(self): self._epoll_fd = epoll.epoll_create() def fileno(self): r...
s): epoll.epoll_ctl(self._epoll_fd, self._EPOLL_CTL_ADD, fd, events) def modify(self, fd, events): epoll.epoll_ctl(self._epoll_fd, self._EPOLL_CTL_MOD, fd, events) def unregister(self, fd): epoll.epoll_ctl(self._epoll_fd, self._EPOLL_CTL_DEL, fd, 0) def pol...
msrb/freeipa
ipalib/text.py
Python
gpl-3.0
18,653
0.001126
# Authors: # Jason Gerard DeRose <jderose@redhat.com> # # Copyright (C) 2009 Red Hat # see file 'COPYING' for use and warranty contextrmation # # 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,...
mand): ... msg1 = _('Foo!') ... msg2 = ngettext('%(count)d bar', '%(count)d bars', 0) ... Notice that these messages are bound to the ``'ipa_foo'`` domain:
>>> foo.msg1 Gettext('Foo!', domain='ipa_foo', localedir=None) >>> foo.msg2 NGettext('%(count)d bar', '%(count)d bars', domain='ipa_foo', localedir=None) For additional details, see `GettextFactory` and `Gettext`, and for plural forms, see `NGettextFactory` and `NGettext`. """ import threading import locale import g...
Shopify/shopify_python_api
test/refund_test.py
Python
mit
1,089
0.001837
import shopify from test.test_helper import TestCase class RefundTest(TestCase): def setUp(self): super(RefundTest, self).setUp() self.
fake("orders/450789469/refunds/509562969", method="GET", body=self.load_fixture("refund")) def test_should_find_a_specific_refund(self): refund = shopify.Refund.find(509562969, order_id=450789469) self.assertEqual("209.00", refund.transactions[0].amount) def test_calculate_refund_for_order(sel...
789469/refunds/calculate", method="POST", code=201, body=self.load_fixture("refund_calculate"), headers={"Content-type": "application/json"}, ) refund = shopify.Refund.calculate( order_id=450789469, refund_line_items=[{"line_item_id": 518995019...
nkhare/rockstor-core
src/rockstor/storageadmin/models/update_subscription.py
Python
gpl-3.0
1,351
0.00074
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it unde
r the terms of the GNU General Publ
ic License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. RockStor 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 G...
AbramovVitaliy/Abramov-RIS-13
lab4_5_6/project/models/fields/ThemeField.py
Python
mit
734
0.004087
from project.models.fields.Field import Field from project.models.fields.exceptions import FieldValidException THEME_MIN_LENGTH = 0 THEME_MAX_LEN
GTH = 128 class ThemeField(Field): def __init__(self, theme): self.set(theme) def set(self, theme): if x = chain_of_conditions() raise FieldValidException(x) if not isinstance(theme, str): raise FieldValidException("theme must be string") if len(theme) ...
+ " to " + str(THEME_MAX_LENGTH)) self._theme = theme def get(self): return self._theme
gaoce/TimeVis
setup.py
Python
mit
1,191
0.00084
from __future__ import print_function import os from setuptools import setup # Utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), f
name)).read() # Setup # 1. zip_safe needs to be False since we need access to templates setup( name="TimeVis", version="0.2", author="Ce Gao", author_email="gaoce@coe.neu.edu", description=("TimeVis: An interactive tool to query and visualize "
"time series gene expression data"), license="MIT", install_requires=[ "flask", "Flask-RESTful", "SQLAlchemy", "pandas", "scikits.bootstrap", ], packages=['timevis'], package_dir={"timevis": "timevis"}, package_data={ "timevis": [ ...
low-sky/py-low-sky
intervals.py
Python
mit
6,216
0.017535
import numpy as np import astropy.units as u import astropy.constants as con import warnings class VelocitySet(list): def __init__(self,input): if input is None: self.ranges = [] elif hasattr(input,'__iter__'):
self.ranges=input else: self.ranges = [input] # self._clean() def _clean(self): intervals = self.ranges result = VelocitySet(None) for elt in intervals: result = result+elt self.result = result.ranges def append(self,item): self....
ex): return self.ranges[index] def __len__(self): return(len(self.ranges)) def __repr__(self): return('Velocity set consisting of: \n\t'+''.join([elt.__repr__()+'\n\t' for elt in self.ranges])) def lower(self): lower = [] for elt in self.ranges: lower +...
AustereCuriosity/astropy
astropy/utils/state.py
Python
bsd-3-clause
1,936
0
""" A simple class to manage a piece of global science state. See :ref:`config-developer` for more details. """ __all__ = ['ScienceState'] class ScienceState(object): """ Science state subclasses are used to manage global items that can affect science results. Subclasses will generally override `v...
Get the current science state value. """ return cls.validate(cls._value) @classmethod def set(cls, value): """ Set
the current science state value. """ class _Context(object): def __init__(self, parent, value): self._value = value self._parent = parent def __enter__(self): pass def __exit__(self, type, value, tb): ...
JasonWyse/FacRankSvm_c
table10.py
Python
bsd-3-clause
2,481
0.038291
from parameter import * from parse_digit import * import os from os import system cmd = "make -C liblinear >/dev/null 2>/dev/null; make -C tools > /dev/null 2>/dev/null; mkdir log model 2>/dev/null" system(cmd) methodlist = ['partial-pairs','l2-loss-ranksvm'] solver = {"partial-pairs":0,"l2-loss-ranksvm":6} #remove...
nt "& \\multicolumn{3}{|c}{MQ2007-list}", if 'MQ2008-list' in data: print "& \\multicolumn{3}{|c}{MQ2008-list}", print "\\\\" print "& & Training & Pairwise "*len(data),"\\\\" print "Data set "+"& $C$ & time (s) & accuracy "*len(data) +"\\\\" print "\\hline" for method i
n methodlist: print output_name[method], o = [] for d in data: dp = log_path + d + '.' + method+ '.pairwise-accuracy.log' try: tmp_data = open(dp,'r').readlines() except: if (method == "partial-pairs"): traindata = path+data_path[d]+'.partial' if not os.path.exists(traindata): cmd = "tools/c...
franciscoruiz/django-nose
testapp/models.py
Python
bsd-3-clause
729
0
"""Models for django-nose test application. Based on the Django tutorial: https://docs.djangop
roject.com/en/1.8/intro/tutorial01/ """ from django.db import models class Question(models.Model): """A poll question.""" question_t
ext = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): """Return string representation.""" return self.question_text class Choice(models.Model): """A poll answer.""" question = models.ForeignKey(Question) choice_text = models....
AloneRoad/Inforlearn
components/xmpp_service/__init__.py
Python
apache-2.0
449
0.011136
from google.appengine.api import xmpp def send_message(jids, body, from_jid=None
, message_type=xmpp.MESSAGE_TYPE_CHAT, raw_xml=False): return xmpp.send_message(jids, body, from_jid, message_type, raw_xml) def from_request(cls, request): params = {'sender': request.REQUEST.get('from'), 'target': request.REQUEST.get('to'), 'message': request.REQUEST.get...
), } return cls(**params)
cubrid-talks/CUBRIDPy
trunk/CUBRIDPy/errors.py
Python
gpl-2.0
1,270
0.011811
""" This module implements Exception classes http://www.python.org/dev/peps/pep-0249/ """ class Error(St
andardError): """ Base class for all driver error exceptions """ def __init__(self, err_id = None, err_msg = None): self._err_id = err_id or -1 self._err_msg = err_msg #def __str__(self): # return '%d: %s' % (self._err_id, self._err_msg) class Warning(StandardError): ""...
ror): """ Exception for database errors """ pass class InternalError(DatabaseError): """ Exception for internal errors """ pass class OperationalError(DatabaseError): """ Exception for database operations errors """ pass class ProgrammingError(DatabaseError): """ ...
Kongsea/tensorflow
tensorflow/contrib/gan/python/train_test.py
Python
apache-2.0
27,212
0.006945
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
riminator_model(inputs, _), array_ops.one_hot( # TODO(haeusser): infer batch size from input random_ops.random_uniform([3], maxval=num_classes, dtype=dtypes.int32), num_classes)) class ACGANDiscriminator(object): def __call__(self, inputs, _, num_classes=10): return (discriminator_model(input...
sser): infer batch size from input random_ops.random_uniform([3], maxval=num_classes, dtype=dtypes.int32), num_classes)) def get_gan_model(): # TODO(joelshor): Find a better way of creating a variable scope. with variable_scope.variable_scope('generator') as gen_scope: pass with variable_sco...
github4ry/recipy
recipyGui/tests/test_recipyGui.py
Python
apache-2.0
5,698
0.001755
from recipyGui import recipyGui from os import remove from flask.ext.testing import TestCase from tinydb import TinyDB from dateutil.parser import parse import six class TestRecipyGui(TestCase): def create_app(self): self.dbName = 'recipyGui/tests/test.json' recipyGui.config['tinydb'] = self.dbNam...
u'environment': [], u'gitrepo': None, u'command': None
, u'gitcommit': None, u'date': u'{TinyDate}:2015-08-16T17:20:07', u'diff': None, u'unique_id': None }, # Run details that caused issue #42 { 'author': 'Robin', 'command': 'C:\\Anaconda3\\p...
jf-parent/webbase
{{cookiecutter.project_name}}/scripts/query.py
Python
mit
634
0
#! /usr/bin/env python import os import sys from IPython.terminal.embed import InteractiveShellEmbed from mongoalchemy.session impor
t Session HERE = os.path.abspath(os.path.dirname(__file__)) ROOT = os.path.join(HERE, '..') sys.path.append(ROOT) from server.model.user import User # noqa from server.model.notification import Notification # noqa from server.settings import config # noqa config.configure() session = Session.connect(config.get("...
query: from server.model.{model_name} import {Model}" # noqa ipshell(banner)
minixalpha/SourceLearning
webpy/sample/googlemodules/src/app/controllers/submit.py
Python
apache-2.0
626
0.014377
# Author: Alex Ksikes import web import config from app.models import submission from app.models import
rss from app.helpers import render from config import view class submit: def GET(self): return render.layout(view.submit_module(), title='Submit - Google Modules') def POST(self): i = web.input(url='', tags='', _unicode=False) success, err_msg = submission.sub...
i.tags) rss.update_rss() return render.layout(view.submitted_form(success, type='submit', err_msg=err_msg), title='Submit - Google Modules')
OpusVL/odoo-remittance-advice
remittance_advice/__openerp__.py
Python
agpl-3.0
1,877
0.002131
# -*- coding: utf-8 -*- ############################################################################## # # Remittance Advice for Odoo # Copyright (C) 2014 OpusVL # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the F...
on': '0.3', 'category': 'Accounting & Finance', 'summary': 'Add a Remittance Advice print option to Supplier Payment vouchers', 'description': """Add a Remittance Advice print option to Supplier Payment vouchers. The value for Your Reference in the table comes from the Supplier Invoice Number on the re...
], 'data': [ 'report_remittance_advice.xml', ], 'demo': [], 'test': [], 'installable': True, 'application': True, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
PyORBIT-Collaboration/JPARC_Accelerator
JPARC_Linac/jparc_linac_rf_fields/jparc_ttf_and_ez_field_generator.py
Python
mit
11,524
0.032801
#------------------------------------------------------------------------- # This script reads the SuperFish files with the field on the axis of RF gap # and generates tables of the TTF functions and their polynomial interpolations. # TTFs (T,S,Tp,Sp) are funcftions of the cappa variable = 2*pi*f/(c*beta). # The Super...
0]) y = float(res_arr[1]) func.add(x,y) #fix for the field at the 0 region func1 = Function() for i i
n range(1,func.getSize()): ind = func.getSize() - i x = -func.x(ind) y = func.y(ind) func1.add(x,y) for i in range(func.getSize()): x = func.x(i) y = func.y(i) func1.add(x,y) return func1 def DumpSplineIntoFile(fl_name,spline): """ Dumps spline with Ez(z) function into the file. """ fl_out = ope...
OpenHumans/open-humans
public_data/migrations/0004_migrate_data_20190508.py
Python
mit
1,674
0.002389
import re from django.db import migrations def add_project_member(apps, schema_editor): # Using historical versions as recommended for RunPython PublicDataAccess = apps.get_model("public_data", "PublicDataAccess") DataRequestProjectMember = apps.get_model( "private_sharing", "DataRequestProjectMe...
oject.objects.using(db_alias).get( id=int(match.group("id")) ) return project for pda in PublicDataAccess.objects.using(db_alias).filter(project_membership=None): project = id_label_to_project(pda.data_source) drpm = DataRequestProjectMember.objects.using(db_...
membership = drpm pda.save() def set_data_source(apps, schema_editor): # Using historical versions as recommended for RunPython PublicDataAccess = apps.get_model("public_data", "PublicDataAccess") db_alias = schema_editor.connection.alias for pda in PublicDataAccess.objects.using(db_alias).fi...
mjenrungrot/competitive_programming
UVa Online Judge/v126/12626.py
Python
mit
604
0
# ============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 12626.py # Description: UVa Online Judge - 12626 # ============================================================================= from collec...
er = Counter(line) ans = min(
counter["M"], counter["A"] // 3, counter["R"] // 2, counter["G"], counter["I"], counter["T"], ) print(ans)
bmi-forum/bmi-pyre
pythia-0.8/packages/mpi/mpi/LauncherMPICH.py
Python
gpl-2.0
2,569
0.003503
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Michael A.G. Aivazis # California Institute of Technology # (C) 1998-2005 All Rights Reserved # # <LicenseText> # # ~~~~~~~~~~~~~~~~~~~~~~~~...
le if not nodes: nodes = len(nodelist) if nodes < 2: self.inventory.nodes = 1 return [] # build the command args = [] args.append(self.inventory.command) args.append(self.inventory.extra) args.append("-np %d" % nodes)...
ic nodes specified explicitly if nodelist: file = open(machinefile, "w") for node in nodelist: file.write((nodegen + '\n') % node) file.close() args.append("-machinefile %s" % machinefile) # add the parallel version of the interpreter on t...
userzimmermann/zetup.py
zetup/conda.py
Python
lgpl-3.0
2,477
0
# zetup.py # # Zimmermann's Python package setup. # # Copyright (C) 2014-2015 Stefan Zimmermann <zimmermann.code@gmail.com> # # zetup.py 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 ve...
self.command = command def __call__(self, *args, **options): """Runs external conda executable with the given `args`. - Automatically adds ``--json`` arg and returns pythonized JSON output. - If called with ``json=False``, stdout is not captured and statu...
s.insert(0, self.command) if options.get('json', True): return json.loads(Popen( ['conda'] + args + ['--json'], env=os.environ, stdout=PIPE, universal_newlines=True ).communicate()[0]) return call(['conda'] + args, env=os.environ) def ...
frederica07/Dragon_Programming_Process
jp/ac/kyoto_su/aokilab/dragon/example_model/example.py
Python
bsd-2-clause
7,196
0.026891
#! /usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import urllib from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * from jp.ac.kyoto_su.aokilab.dragon.mvc.model import OpenGLModel from jp.ac.kyoto_su.aokilab.dragon.mvc.view import * from jp.ac.kyoto_su.aokil...
ertexes = m
ap(index_to_vertex, indexes) a_tringle = OpenGLTriangle(*vertexes) self._display_object.append(a_tringle) if first_string == "comment": second_string = a_list[1] if second_string == "eye_point_xyz": self._eye_point = map(float, a_list[2:5]) if second_string == "sight_point_xyz": ...
tntrung/pyCVML
misc/patch_norm.py
Python
gpl-2.0
294
0.013605
import numpy as np # ===== Patch normalization by mean intensity ======================== def mean
_intensity_norm(patch): mu = np(np.sum(patch))*1.0/(patch.shape[0]*shape[1]) return (patc
h - mu[np.newaxis,np.newaxis]) # ===== Patch normalization by mean intensity ========================
sigmike/ganeti
lib/runtime.py
Python
gpl-2.0
3,423
0.005259
# # Copyright (C) 2010 Google Inc. # # 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...
Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. """Module implementing configuration details at runtime. """ import grp import pwd import threading from ganeti import constants from ganeti import errors _priv = None _priv_lock = threading.Lock() def GetUid(user, _ge...
uid except KeyError, err: raise errors.ConfigurationError("User '%s' not found (%s)" % (user, err)) def GetGid(group, _getgrnam): """Retrieve the gid from the database. @type group: string @param group: The group name to retrieve @return: The resolved gid """ try: return _getgrnam(group).gr_gi...
hfp/libxsmm
samples/deeplearning/sparse_training/fairseq/fairseq/__init__.py
Python
bsd-3-clause
802
0
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. __all__ = ['pdb'] __version__ = '0.9.0' import sys # backwards compatibility to support `from fairseq.meters import AverageMeter` from fairs...
seq.optim # noqa impor
t fairseq.optim.lr_scheduler # noqa import fairseq.pdb # noqa import fairseq.tasks # noqa import fairseq.benchmark # noqa import fairseq.model_parallel # noqa
ejucovy/django-opendebates
opendebates/registration_urls.py
Python
apache-2.0
3,426
0.001751
""" URLconf for registration and activation, using django-registration's one-step backend. If the default behavior of these views is acceptable to you, simply use a line like this in your root URLconf to set up the default URLs for registration:: (r'^accounts/', include('registration.backends.simple.urls')), Thi...
sword_change'), url(r'^password/change/done/$', auth_views.password_change_done, name='password_change_done'), url(r'^password/reset/$', auth_views.password_reset,
{'html_email_template_name': "registration/password_reset_email.html", 'email_template_name': "registration/password_reset_email.txt", 'template_name': "registration/password_reset_form.html"}, name='password_reset'), ...
TheAlgorithms/Python
strings/boyer_moore_search.py
Python
mit
2,738
0.000365
""" The algorithm finds the pattern in given text using following rule. The
bad-character rule considers the mismatched character in Text. The next occurrence of that character to the left in Pattern is found, If the mismatched character occurs to the left in Pattern, a shift is proposed that aligns text block and pattern. If the mismatched character does not occur to the left in Pattern, a ...
hift is proposed that moves the entirety of Pattern past the point of mismatch in the text. If there no mismatch then the pattern matches with text block. Time Complexity : O(n/m) n=length of main string m=length of pattern string """ from __future__ import annotations class BoyerMooreSearch: def __init...
ifding/ifding.github.io
stylegan2-ada/metrics/inception_score.py
Python
mit
3,018
0.004307
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and rel...
images = tflib.convert_images_to_uint8(images) res
ult_expr.append(inception_clone.get_output_for(images)) # Calculate activations for fakes. for begin in range(0, self.num_images, minibatch_size): self._report_progress(begin, self.num_images) end = min(begin + minibatch_size, self.num_images) activations[begin:end] ...
aldengolab/fake-news-detection
data_cleaning/get_articles.py
Python
mit
1,318
0.013657
import json import csv import pandas as pd cred = pd.read_csv('credible.csv') noncred = pd.read_csv('noncredible.csv') noncred.reset_index(level=0, inplace=True) cred.columns = ['site','type'] noncred.columns = ['site', 'lang', 'type','notes', 'tmp'] cred['clean_site'] = cred['site'].apply(lambda x: x.split('.')[0].lo...
l['source'] if s not in sources: print(s) sources.add(l['source']) s = l['source'].replace(' ','').replace("'
","").replace('-','').lower() if s in true and s not in false: l['label']=0 data.append(l) elif s in false and s not in true: l['label']=1 data.append(l) else: pass print(len(data)) df = pd.DataFrame(data) df.to_csv('articles1.cs...
MarkNenadov/OntarioBabyNames
babynames/babynames/settings.py
Python
lgpl-3.0
5,393
0.001298
# Django settings for babynames project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'data_monging', # Or path to database file if using sqlite3. # The following settings are not used with sqlite3: 'USER': 'mark', 'PASSWORD': 'blah', '...
omain sockets or '127.0.0.1' for localhost through TCP. 'PORT': '', # Set to empty string for default. } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local t...
wdv4758h/ZipPy
lib-python/3/test/test_traceback.py
Python
bsd-3-clause
12,975
0.001927
"""Test cases for traceback module""" try: import _testcapi except ImportError: _testcapi = None from io import StringIO import sys import unittest import re from test.support import run_unittest, Error, captured_output from test.support import TESTFN, unlink from test.support import check_impl_detail import ...
"import sys; print(sys.stdout.encoding)"], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) stdout, stderr = process.communicate() output_encoding = str(stdout, 'ascii').splitlines()[0] def do_test(firstlines, message, charset, lineno): # Raise the message in a subprocess, and catch the output try: output = open(TESTFN,...
USGSDenverPychron/pychron
sandbox/export_spec.py
Python
apache-2.0
732
0.012295
import os import sys d = os.path.dirname(os.getcwd()) sys.path.append(d) from pychron.core.ui import set_toolkit set_toolkit('qt4') #e=ExportSpec(p='/Users/ross/Sandbox/aaaa_isotopes.h5') #for iso,det in # #from pychron.core.ui.dialogs import myConfirmationDialog # #from traits.api import HasTraits, Button #from...
ionDialog(
message='Timeout Confirm Test') # ret = dlg.open(timeout=10) # print 'ret', ret # # def traits_view(self): # return View('a') # # #A().configure_traits()
b3j0f/sync
docs/source/conf.py
Python
mit
11,487
0.006442
# -*- coding: utf-8 -*- # # b3j0f.sync documentation build configuration file, created by # sphinx-quickstart on Sun Jun 14 17:29:14 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # ...
e to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # A
dd any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robo...
rs2/pandas
pandas/tests/reshape/concat/test_sort.py
Python
bsd-3-clause
3,115
0.001605
import pandas as pd from pandas import DataFrame import pandas._testing as tm class TestConcatSort: def test_concat_sorts_columns(self, sort): # GH-4588 df1 = DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"]) df2 = DataFrame({"a": [3, 4], "c": [5, 6]}) # for sort=True/None...
result, expected) def test_concat_aligned_sort(self): # GH-4588 df = DataFrame({"c": [1, 2], "b": [3, 4], "a": [5, 6]}, columns=["c", "b", "a"]) result = pd.concat([df, df], sort=True, ignore_index=True) expected = DataFrame( {"a": [5, 6, 5, 6], "b": [3, 4, 3, 4], "c": [...
columns=["a", "b", "c"], ) tm.assert_frame_equal(result, expected) result = pd.concat( [df, df[["c", "b"]]], join="inner", sort=True, ignore_index=True ) expected = expected[["b", "c"]] tm.assert_frame_equal(result, expected) def test_concat_aligned_s...
keunwoochoi/music-auto_tagging-keras
example_feat_extract.py
Python
mit
1,936
0.00155
import time import numpy as np from keras import backend as K from music_tagger_cnn import MusicTaggerCNN from music_tagger_crnn import MusicTaggerCRNN import audio_processor as ap import pdb def librosa_exists(): try: __import__('librosa') except ImportError: return False else: re...
ch. Use multiple, different data samples together (at least 4) for reliable prediction.''' print('Running main() with network: %s and backend: %s' % (net, K._BACKEND)) # settin
g audio_paths = ['data/bensound-cute.mp3', 'data/bensound-actionable.mp3', 'data/bensound-dubstep.mp3', 'data/bensound-thejazzpiano.mp3'] melgram_paths = ['data/bensound-cute.npy', 'data/bensound-actionable.npy', ...
nilsonmorales/Puppyes-nightrc
usr/local/lib/python2.7/dist-packages/youtube_dl/extractor/daum.py
Python
gpl-3.0
2,601
0.001547
# encoding: utf-8 import re from .common import InfoExtractor from ..utils import ( compat_urllib_parse, determine_ext, ) class DaumIE(InfoExtractor): _VALID_URL = r'https?://tvpot\.daum\.net/.*?clipid=(?P<id>\d+)' IE_NAME = u'daum.net' _TEST = { u'url': u'http://tvpot.daum.net/clip/Clip...
, u'full id') query = compat_urllib_parse.urlencode({'vid': full_id}) info = self._download_xml( 'http://tvpot.daum.net/clip/ClipInfoXml.do?' + query, video_id, u'Downloading video info') urls = self._download_xml( 'http://videofarm.daum.net/controller/api/ope...
at_el in urls.findall('result/output_list/output_list'): profile = format_el.attrib['profile'] format_query = compat_urllib_parse.urlencode({ 'vid': full_id, 'profile': profile, }) url_doc = self._download_xml( 'http://video...
dctelf/poisonous-mushroom
2018_tests/test_repkeyXOR.py
Python
apache-2.0
650
0.006154
from unittest import TestCase import string import random from cryptochallenge import stringmanip, ciphers class TestRe
pkeyXOR(TestCase): def test_repkeyXOR(self): plaintext = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal" key = "ICE" my_result = ciphers.repkeyXOR(plaintext, key) my_result_hex = stringmanip.bytearrayToHexStr(my_result) expected_ctext_hex = "...
283165286326302e27282f" self.assertEqual(my_result_hex, expected_ctext_hex)
snowch/biginsight-examples
examples/ElasticsearchIntegrationWithSpark/import_from_elasticsearch.py
Python
apache-2.0
2,082
0.007205
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
<user> <pass> <tmpdir> <tmpHdfsDir>", file=sys.stderr) exit(-1) host = sys.ar
gv[1] port = sys.argv[2] user = sys.argv[3] password = sys.argv[4] tmpDir = sys.argv[5] tmpHdfsDir = sys.argv[6] conf = SparkConf().setAppName("Elasticsearch example") # see https://www.elastic.co/guide/en/elasticsearch/hadoop/current/configuration.html conf.set("es.n...
Accelerite/cinder
cinder/volume/drivers/hitachi/hbsd_iscsi.py
Python
apache-2.0
16,787
0
# Copyright (C) 2014, Hitachi, Ltd. # # 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...
om cinder.volume.drivers.hitachi import hbsd_common as common LOG = logging.getLogger(__name__) CHAP_METHOD = ('None', 'CHAP None', 'CHAP') volume_opts = [ cfg.BoolOpt('hitachi_add_chap_user', default=False, help='Add CHAP
user'), cfg.StrOpt('hitachi_auth_method', default=None, help='iSCSI authentication method'), cfg.StrOpt('hitachi_auth_user', default='%sCHAP-user' % basic_lib.NAME_PREFIX, help='iSCSI authentication username'), cfg.StrOpt('hitachi_auth_password', ...
ptsankov/bellog
src/config.py
Python
gpl-2.0
69
0.028986
confi
g = { 'XSB_PATH' : '/home/ptsankov/apps/xsb-src/XSB/bin
/xsb' }
open-synergy/opnsynid-hr
hr_timesheet_computation/__init__.py
Python
agpl-3.0
158
0
# -*- coding: utf-8 -*- # Copyri
ght 2018 OpenSynergy Indonesia # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from . import models,
reports
sbsdev/daisyproducer
daisyproducer/abacus_import/management/commands/importProductData.py
Python
agpl-3.0
4,413
0.004985
from daisyproducer.documents.models import Document, Version, Product from daisyproducer.abacus_import.management.commands.importABACUS import get_type, get_documents_by_product_number, get_documents_by_source_or_title_source_edition from django.core.management.base import BaseCommand, CommandError from django.db impor...
itle = lines[1].strip() else: logger.warn('Ignoring invalid verkaufstext "%s"', verkaufstext) if get_documents_by_product_number(product_number): # the product number is already assoc
iated with a document logger.debug('Product number "%s" already registered.', product_number) continue elif not get_documents_by_source_or_title_source_edition(source, title, source_edition): if (source, title, source_edition) not in warned_sou...
raphael0202/spaCy
spacy/bn/tag_map.py
Python
mit
2,736
0.001097
# coding: utf8 from __future__ import unicode_literals from ..symbols import * TAG_MAP = { ".": {POS: PUNCT, "PunctType": "peri"}, ",": {POS: PUNCT, "PunctType": "comm"}, "-LRB-": {POS: PUNCT, "PunctType": "brck", "PunctSide": "ini"}, "-RRB-": {POS: PUNCT, "PunctType": "brck", "Pu...
""}, "NN": {POS: NOUN, "Number": "sing"}, "NNP": {POS: PROPN, "NounType": "prop", "Number": "sing"}, "NNPS": {POS: PROPN, "NounType": "prop", "Number": "plur"}, "NNS": {POS: NOUN, "Number": "plur"}, "PDT": {POS: ADJ, "AdjType": "pdt", "PronType": "prn"}, "POS": {PO...
RBR": {POS: ADV, "Degree": "comp"}, "RBS": {POS: ADV, "Degree": "sup"}, "RP": {POS: PART}, "SYM": {POS: SYM}, "TO": {POS: PART, "PartType": "inf", "VerbForm": "inf"}, "UH": {POS: INTJ}, "VB": {POS: VERB, "VerbForm": "inf"}, "VBD": {POS: VERB, "Verb...
pkom/gesiesweb
gesiesweb/api/permissions.py
Python
gpl-3.0
188
0.005319
from rest
_framework.permissions import BasePermission class IsSuperUser(BasePermission): def has_object_permission(self, re
quest, view, obj): return request.user.is_superuser
LukeMurphey/splunk-network-tools
src/bin/speedtest.py
Python
apache-2.0
2,359
0.005511
import os import sys path_to_mod_input_lib = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modular_input.zip') sys.path.insert(0, path_to_mod_input_lib) from modular_input import Field, ModularInput, IntegerField from network_tools_app import speedtest, get_default_index class SpeedtestInput(ModularInput...
ndex = cleaned_params.get("index", "default") sourcetype = cleaned_params.get("sourcetype", "speedtest") source = cleaned_params.get("source", stanza) server = cleaned_params.get("server", None) runs = cleaned_params.get("runs", 3) self.logger.info("
Starting speedtest, stanza=%s", stanza) result = speedtest(host=server, runs=runs, index=index, logger=self.logger) # Output the results self.output_event(result, stanza=stanza, index=index, sourcetype=sourcetype, host=host, source=source) self.logger.info("Speedtest complete, stanza=%...
googleapis/python-aiplatform
samples/generated_samples/aiplatform_v1beta1_generated_job_service_update_model_deployment_monitoring_job_async.py
Python
apache-2.0
1,983
0.002017
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under th
e Apache License, Version 2.0 (the "License"); # you may
not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDI...
jobsafran/mediadrop
mediadrop/model/tests/group_example_test.py
Python
gpl-3.0
1,298
0.004622
# This file is a part of MediaDrop (http://www.mediadrop.net), # Copyright 2009-2015 MediaDrop contributors # For the exact contribution history, see the git revision log. # The source code contained in this file is licensed under the GPLv3 or # (at your option) any later version. # See LICENSE.txt in the main project ...
u'Baz Users', group.display_name) assert_almost_equals(datetime.now(), group.created, max_delta=timedelta(seconds=1)) def test_can_override_example_data(self): group = Group.example(name=u'bar', display_name=u'Bar Foo') assert_equals(u'Bar Foo', gr...
st(unittest.makeSuite(GroupExampleTest)) return suite
icoxfog417/TravelPenguinBot
tests/test_penguin_act.py
Python
mit
4,956
0.001414
import unittest import json from travel_penguin.travel.penguin_act import PenguinAct from travel_penguin.model.move import Direction, Distance from travel_penguin.model.place import Place from travel_penguin.env import Environment class TestPenguinAct(unittest.TestCase): def test_parse_places(self): plac...
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/travel_agent-71.png", "id" : "21a0b251c9b83921861
42c798263e289fe45b4aa", "name" : "Rhythmboat Cruises", "opening_hours" : { "open_now" : true }, "photos" : [ { "height" : 270, "html_att...
alneberg/sillymap
sillymap/burrows_wheeler.py
Python
mit
567
0.007055
def burrows_wheeler(text): """Calculates th
e burrows wheeler transform of <text>. returns the burrows wheeler string and the suffix array indices The text is assumed to not contain the character $""" text += "$" all_permutations = [] for i in range(len(text)): all_permutations.append((text[i:] + text[:i],i)) all_permutations.s...
[] # suffix array indices for w,j in all_permutations: bw_l.append(w[-1]) sa_i.append(j) return "".join(bw_l), sa_i
GrandPaRPi/p2ptv-pi
acestream/ACEStream/Utilities/LinuxSingleInstanceChecker.py
Python
mit
516
0.005814
#Emb
edded file name: ACEStream\Utilities\LinuxSingleInstanceChecker.
pyo import sys import commands class LinuxSingleInstanceChecker: def __init__(self, basename): self.basename = basename def IsAnotherRunning(self): cmd = 'pgrep -fl "%s\\.py" | grep -v pgrep' % self.basename progressInfo = commands.getoutput(cmd) print >> sys.stderr, 'LinuxSin...
alphagov/govuk-puppet
modules/collectd/files/usr/lib/collectd/python/redis_queues.py
Python
mit
4,100
0.000488
# 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; only version 2 of the License is applicable. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; witho...
elif node.key == 'Verbose': VERBOSE_LOGGING = bool(node.values[0]) elif node.key == 'Queues': QUEUE_NAMES = list(node.values) else: collectd.warning('redis_queues plugin: Unknown config key: %s.' % node.key) log_verbose('Configured ...
_verbose('Watching queue %s' % queue) if not QUEUE_NAMES: log_verbose('Not watching any queues') def read_callback(): log_verbose('Read callback called') queue_lengths = fetch_queue_lengths(QUEUE_NAMES) if queue_lengths is None: # An earlier error, reported to collectd by fetch_queue_...
makinacorpus/reportlab-ecomobile
tools/pythonpoint/__init__.py
Python
bsd-3-clause
199
0.020101
#Copyright ReportLab Europe Ltd. 2000-2004 #see license.txt for license details #history http://www.reportlab.co.uk/cgi-bin/viewcvs.cgi/public/reportlab/trunk/repor
tlab/tools/pythonpoint/__init__.py
lyft/incubator-airflow
airflow/example_dags/example_kubernetes_executor_config.py
Python
apache-2.0
3,017
0.000331
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
using a Kubernetes Executor Configuration. """ import os from airflow.example_dags.libs.helper import print_stuff from airflow.models import DAG from airflow.operators.python import PythonOperator from airflow.utils.dates import days_ago default_args = { 'owner': 'airflow', 'start_date': days_ago(2) } with D...
gs=default_args, schedule_interval=None, tags=['example'], ) as dag: def test_volume_mount(): """ Tests whether the volume has been mounted. """ with open('/foo/volume_mount_test.txt', 'w') as foo: foo.write('Hello') return_code = os.system("cat /foo/vol...
tusuzu/tmtp
standalone/tmtpl/document.py
Python
gpl-3.0
13,294
0.005491
#!/usr/bin/python # # This file is part of the tmtp (Tau Meta Tau Physica) project. # For more information, see http://www.sew-brilliant.org/ # # Copyright (C) 2010, 2011, 2012 Susan Spencer and Steve Conklin # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Genera...
roupname in self.groups: self.displayed_groups.append(groupname) # create the base document sz = svg() if 'tooltips' in self.cfg: # add the scripting we need to handle events sc = script() sc.set_xlink_href('tmtp_mouse.js') sc.set...
link_type('text/ecmascript') sz.addElement(sc) sz.set_onload('init(evt)') # # Add the tooltip text element # ttel = self.generateText(0, 0, 'tooltip', 'ToolTip', 'tooltip_text_style') ttel.setAttribute('visibility', 'hidden') ...
mezuro/kalibro_client_py
tests/configurations/test_reading.py
Python
lgpl-3.0
1,601
0.003748
from unittest import TestCase from mock import patch from nose.tools import assert_equal, assert_true from kalibro_client.configurations import Reading from tests.factories import ReadingFactory from tests.helpers import not_raises class TestReading(TestCase): def setUp(self): self.subject = ReadingFa...
reading_groups/{}".format(reading_group_id)) mock.assert_called_once_with(readings_hash) def test_save_prefix(self): assert_equal(self.subject.save_prefix(), "reading_groups/{}".format(self.subject.reading_group_id)) def test_update_prefix(self): assert_equal(self.subject.update_pr...
elete_prefix(self): assert_equal(self.subject.delete_prefix(), "reading_groups/{}".format(self.subject.reading_group_id))
Varriount/Colliberation
libs/twisted/python/test/test_win32.py
Python
mit
1,001
0.001998
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.trial import unittest from twisted.python.runtime import platform from twisted.python.win32 import cmdLineQuote class CommandLineQuotingTests(unittest.TestCase): """ Tests for L{cmdLineQuote}. """ def test_argWithou...
'an_argument'), 'an_argument') def test_argWithSpaces(self): """ Calling C{cmdLineQuote} with an argument containing spaces should return the argument surrounded by quotes. """ self.assertEqual(cmdLineQuote('An Argument'), '"An Argument"') def test_emptySt
ringArg(self): """ Calling C{cmdLineQuote} with an empty string should return a quoted empty string. """ self.assertEqual(cmdLineQuote(''), '""')