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 |
|---|---|---|---|---|---|---|---|---|
shravan-shandilya/web3.py | tests/utilities/test_construct_data_filter_regex.py | Python | mit | 2,233 | 0.000448 | import pytest
from web3.utils.filters import (
construct_data_filter_regex,
)
def hex_and_pad(*i):
return '0x' + ''.join(
hex(v).rstrip('L')[2:].zfill(64)
for v in i
)
SINGLE_VALUE = [
[hex_and_pad(1)],
]
TWO_VALUES = [
[hex_and_pad(12345), hex_and_pad(54321)],
]
TWO_VALUES_WITH... | hex_and_pad(2, 1)],
]
@pytest.mark.parametrize(
"filter_set,data_value,should_match",
(
(SINGLE_VALUE, hex_and_pad(1), True),
(SINGLE_VALUE, hex_and_pad(0), False),
(SINGLE_VALUE, hex_and_pad(2), False),
(TWO_VALUES, hex_and_pad(12345, 54321), True),
(TWO_VALUES_WITH_WI... | _WITH_WILDCARD, hex_and_pad(1, 1), False),
(THREE_VALUES_WITH_WILDCARD, hex_and_pad(12345, 0, 54321), True),
(THREE_VALUES_WITH_WILDCARD, hex_and_pad(12345, 1, 54321), True),
(THREE_VALUES_WITH_WILDCARD, hex_and_pad(12345, 2**256 - 1, 54321), True),
(THREE_VALUES_WITH_WILDCARD, hex_and_p... |
evernym/plenum | plenum/test/ledger/conftest.py | Python | apache-2.0 | 1,170 | 0 | import pytest
from plenum.common.constants import DOM | AIN_LEDGER_ID
from plenum.common.txn_util import reqToTxn
from plenum.test.helper import sdk_signed_random_requests
NUM_BATCHES = 3
TXNS_IN_BATCH = 5
def create_txns(looper, | sdk_wallet_client, count=TXNS_IN_BATCH):
reqs = sdk_signed_random_requests(looper, sdk_wallet_client, count)
return [reqToTxn(req) for req in reqs]
@pytest.fixture(scope='module')
def created_txns(ledger, looper, sdk_wallet_client):
txns = []
for i in range(NUM_BATCHES):
txns.append(create_tx... |
ingvar1995/filebot | bot.py | Python | gpl-3.0 | 20,494 | 0.002781 | from tox import Tox
import os
from settings import *
from toxcore_enums_and_consts import *
from ctypes import *
from util import Singleton, folder_size
from file_transfers import *
from collections import defaultdict
class Bot(Singleton):
def __init__(self, tox):
"""
:param tox: tox instance
... | file(os.path.join(settings['folder'], f)):
self.send_file(unicode(os.path.join(settings['folder'], f)), friend_num)
else:
self.send_message(friend_num, 'Not enough rights'.encode('utf-8'))
elif me | ssage == 'help': # help
self.send_message(friend_num, """
help - list of commands\n
rights - get access rights\n
files - show list of files (get access)\n
id - get bot's id (get access)\n
share <ToxID> <file_name> - send file to friend (get access... |
joeryan/python-euler | test4.py | Python | mit | 816 | 0.006127 | # unittest module for project euler problem 4
# palindrome products
import unittest
import palprod
class TestPalinProd(unittest.TestCase):
def setUp(self):
self.palProd = palprod.PalProd()
def testInitial(self):
self.palProd.setDigits(2)
self.palProd.calcMaxProd()
| assert self.palProd.getMaxProd() == (9009), "incorrect answer %d" % self.palProd.getMaxProd()
def testFinal(self):
self.palProd.setDigits(3)
self.palProd.calcMaxProd()
assert self.palProd.getMaxProd() == (906609), "incorrect answer %d" % self.palProd.getMaxProd()
palProdTestSuite = ... | ttest.TestSuite()
palProdTestSuite.addTest(TestPalinProd("testInitial"))
palProdTestSuite.addTest(TestPalinProd("testFinal"))
runner = unittest.TextTestRunner()
runner.run(palProdTestSuite)
|
btenaglia/hpc-historias-clinicas | hpc-historias-clinicas/diagnosticos/migrations/0014_auto_20150506_0117.py | Python | bsd-3-clause | 802 | 0.002494 | # -*- coding: utf-8 -*-
from __future__ import | unicode | _literals
from django.db import models, migrations
import datetime
class Migration(migrations.Migration):
dependencies = [
('diagnosticos', '0013_auto_20150505_2053'),
]
operations = [
migrations.AlterField(
model_name='diagnosticos',
name='fecha',
fi... |
agoose77/hivesystem | hiveguilib/PQt/AntennaFoldState.py | Python | bsd-2-clause | 6,278 | 0.003982 | from __future__ import print_function
import weakref
from functools import partial
from .. import PersistentIDManager
def _hide(widgets):
for w in widgets: w.hide()
def _show(widgets):
for w in widgets: w.show()
def control_visibility(widget):
label = widget.parent().layout().labelForField(widget)
... | workerid, a):
if a not in self._widgets[workerid]: return
for on, off in self._widgets[workerid][a]:
on()
def gui_expands(self, persistent_id, a): |
workerid = self._persisent_id_manager.get_temporary_id(persistent_id)
self._parent().gui_expands(workerid, a)
def p_fold(self, workerid, a):
if a not in self._widgets[workerid]: return
for on, off in self._widgets[workerid][a]:
off()
def gui_folds(self, persistent_... |
DVS-P2P/bubblestorm | testbed/setup.py | Python | gpl-3.0 | 2,416 | 0.031056 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import subprocess
import os
import sys
import shutil
# svn:
#__version__ = subprocess.Popen(['svnversion','-n','.'],shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0].decode()
# git:
GIT_LOG_FORMAT_OPT... | .decode().split("\n")[0][1:-1]
(version_date,version_tag) = __version__.split('\t')
def getVersion():
return '{0}-{1}'.format(version_date,version_tag)
sdistMode = False
if len(sys.argv) > 1 and sys.argv[1] == "sdist":
sdistMode = True
if sdistMode:
sqlFiles = ['begin-transaction.sql', 'commit.sql', 'con... | 'node_sets.sql', 'schema-config.sql', 'schema-output.sql', 'workload.sql']
simulatorSqlFolder = '../simulator/sql/{0}'
testbedSqlFolder = 'src/testbed/sql/{0}'
def copyFile(fileName):
dstFile = testbedSqlFolder.format(fileName)
srcFile = simulatorSqlFolder.format(fileName)
... |
kaji-project/pynag | tests/test_command.py | Python | gpl-2.0 | 27,749 | 0.001189 | import os
import sys
# Make sure we import from working tree
pynagbase = os.path.dirname(os.path.realpath(__file__ + "/.."))
sys.path.insert(0, pynagbase)
from tests import tests_dir
import unittest2 as unittest
from mock import MagicMock, patch, __version__
try:
# open_mock comes with mock 1.0.1
from mock i... | ENABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS;%s' % (
self.timestamp, self.test_svc_group
)
self.command_open_mock.assert_called_with(self.command_file, 'a')
handle = self.command_open_mock()
handle.write.assert_called_once_with(expected + '\n')
def test_disable_servicegroup_... | self.command.disable_servicegroup_passive_host_checks(
servicegroup_name=self.test_svc_group,
command_file=self.command_file, timestamp=self.timestamp
)
expected = '[%s] DISABLE_SERVICEGROUP_PASSIVE_HOST_CHECKS;%s' % (
self.timestamp, self.test_svc_group
)
... |
dunkhong/grr | grr/server/grr_response_server/gui/selenium_tests/flow_archive_test.py | Python | apache-2.0 | 8,184 | 0.003299 | #!/usr/bin/env python
"""Test the flow archive."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import os
from absl import app
import mock
from grr_response_core.lib import utils
from grr_response_core.lib.rdfvalues import paths as rdf_paths
from grr... | token=self.token)
def RaisingStub(*unused_args, **unused_kwargs):
raise RuntimeError("somet | hing went wrong")
with utils.Stubber(archive_generator.CollectionArchiveGenerator, "Generate",
RaisingStub):
self.Open("/#/clients/%s" % self.client_id)
self.Click("css=a[grrtarget='client.flows']")
self.Click("css=td:contains('GetFile')")
self.Click("link=Results")
... |
SRabbelier/Melange | app/soc/modules/gsoc/views/helper/request_data.py | Python | apache-2.0 | 14,575 | 0.00741 | #!/usr/bin/env python2.5
#
# Copyright 2011 the Melange authors.
#
# 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 applic... | ef isBefore(date):
"""Returns True iff date is before utcnow | ().
Returns False if date is not set.
"""
return date and datetime.datetime.utcnow() < date
def isAfter(date):
"""Returns True iff date is after utcnow().
Returns False if date is not set.
"""
return date and date < datetime.datetime.utcnow()
def isBetween(start, end):
"""Returns True iff utcnow()... |
avmarchenko/exatomic | exatomic/interfaces/tens.py | Python | apache-2.0 | 2,737 | 0.008769 | ## -*- coding: utf-8 -*-
## Copyright (c) 2015-2018, Exa Analytics Development Team
## Distributed under the terms of the Apache License 2.0
#import six
##import numpy as np
#import pandas as pd
#from io import StringIO
##from exa import Series, TypedMeta
#from exa import TypedMeta
#from exatomic.core import Editor, Te... | labels[0] if labels[0] != '' else 0
# af['label'] = labels[1] if labels[1] != '' else None
# af['atom'] = labels[2] if labels[0] != '' else 0
# if i >= 1:
# data = pd.concat([data,af],keys=[o for o in range(i+1)])
# | #data = data.append(af)
# print('tens.py--------')
# print(data)
# print('---------------')
# else:
# data = af
# i+=1
# except:
# print('tens.py--------')
# print("R... |
japaniel/CloudFerry | cloudferrylib/os/actions/networks_transporter.py | Python | apache-2.0 | 1,058 | 0 | # Copyright (c) 2014 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You | may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under | the License is distributed on an AS IS BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and#
# limitations under the License.
from cloudferrylib.base.action import transporter
from cloudferrylib.utils import utils as... |
mbakke/ganeti | lib/server/rapi.py | Python | bsd-2-clause | 11,971 | 0.008186 | #
#
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2012, 2013 Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright no... | e media type remains unknown, the recipient SHOULD
# treat it as type "application/octet-stream".
req_con | tent_type = req.request_headers.get(http.HTTP_CONTENT_TYPE,
http.HTTP_APP_OCTET_STREAM)
if req_content_type.lower() != http.HTTP_APP_JSON.lower():
raise http.HttpUnsupportedMediaType()
try:
ctx.body_data = serializer.LoadJson(req.request_body... |
ddeepak6992/Algorithms | Binary-Tree/largest_BST_in_a_binary_tree.py | Python | gpl-2.0 | 953 | 0.006296 | # -*- coding: utf-8 -*-
"""
Created on Thu Nov 19 17:38:50 2015
@author: deep
"""
from binaryTree import BTree, generateRandomTree, inorder
def largestBST(root):
if root.left is None and root.right is None:
return True, 1, root.value, root.value
if root.left:
isBSTL, sizeL, minL, maxL = large... | isBSTL and isBSTR:
if maxL <= root.value <= minR:
return True, sizeL+sizeR+1, minL, maxR,
size = max(sizeL, sizeR)
return False, size , None, None
root1 = BTree()
root1.value = 0
root2 = BTree()
root2.value = 0
generateRandomTree(root2,2)
generateRandomTree(root1,2)
root1.lef | t.left.left = root2
inorder(root1)
print largestBST(root1)
|
yosukesuzuki/kay-template | project/kay/__init__.py | Python | mit | 4,770 | 0.01174 | # -*- coding: utf-8 -*-
"""
Kay framework.
:Copyright: (c) 2009 Accense Technology, Inc.
Takashi Matsuo <tmatsuo@candit.jp>,
Ian Lewis <IanMLewis@gmail.com>
All rights reserved.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
impor... | # Not on the system path. Build a list of alternat | ive paths where it
# may be. First look within the project for a local copy, then look for
# where the Mac OS SDK installs it.
paths = [os.path.join(PROJECT_DIR, '.google_appengine'),
'/usr/local/google_appengine']
for path in os.environ.get('PATH', '').replace(';', ':').split(':'):
p... |
pthevenet/tcp-ip | tp03/Lab3_246645_247680/Part5_246645_247680.py | Python | gpl-3.0 | 464 | 0.00431 | imp | ort websocket
import sys
args = sys.argv[1:]
if (len(args) < 1):
print("USAGE : python Part5_246645_247680.py command")
sys.exit()
cmd = args[0]
ws = websocket.create_connection("ws://tcpip.epfl.ch:5006")
# Sending cmd
print("SENDING : ", cmd)
ws.send(cmd)
# Listening
cnt = 0
try:
while True:
... | cnt += 1
print(result)
except:
ws.close()
print(cnt, "calls to recv")
|
GeorgeTG/easycolor | examples/style.py | Python | bsd-3-clause | 780 | 0 | from easycolor.style import wrap as _w
from easycolor.style import make_style, RESET
# wrap text, appends a style-reset
print(_w('yellow on red', fg='yellow', bg='red'))
print('normal text')
# NOTE: for complex formatting use the | parser module
# define some styles
black_on_white = make_style(fg='black', bg='white')
# we have to reset the background here
red_bold = make_style(fg='red', bg='reset', opt='bold')
# An options reset is only possible with a total reset
# we can however negate an option to remove it('!option').
green_bold_underline =... | ake_style(fg='green', opt=('!bold', 'underline'))
print(black_on_white + 'Black on white' + red_bold + 'Red bold' +
green_bold_underline + 'Green not bold underline' + RESET)
# everything was reset
print('normal text')
|
JuBra/GEMEditor | GEMEditor/rw/test/test_reference_rw.py | Python | gpl-3.0 | 5,903 | 0.001694 | import pytest
from GEMEditor.model.classes.cobra import Model
from GEMEditor.model.classes.reference import Reference, Author
from GEMEditor.model.classes.annotation import Annotation
from GEMEditor.rw import *
from GEMEditor.rw.annotation import annotate_element_from_xml
from GEMEditor.rw.reference import add_referenc... | _listOfAuthors)
assert author_list_node is not None
assert len(author_list_node) == 2
first_author_node = author_list_node.find(ge_author)
assert first_author_node is not None
assert first_author_node.get("firstname") == self.first_author.firstname
assert first_author_no... | ") == self.first_author.lastname
assert first_author_node.get("initials") == self.first_author.initials
second_author_node = first_author_node.getnext()
assert second_author_node is not None
assert second_author_node.get("firstname") == self.second_author.firstname
assert second... |
carlosalberto/carbon-fork | lib/carbon/writer.py | Python | apache-2.0 | 5,226 | 0.011864 | """Copyright 2009 Chris Davis
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
dist... | ster.update_many(metric, datapoints, dbIdentifier)
t2 = time.time()
updateTime = t2 - t1
except:
log.msg("Error writing to %s" % (dbIdentifier))
log.err()
instrumentation.increment('errors')
else:
pointCount = len(da | tapoints)
instrumentation.increment('committedPoints', pointCount)
instrumentation.append('updateTimes', updateTime)
if settings.LOG_UPDATES:
log.updates("wrote %d datapoints for %s in %.5f seconds" % (pointCount, metric, updateTime))
# Rate limit update operations
th... |
smmbllsm/aleph | aleph/archive/archive.py | Python | mit | 1,182 | 0 | import os
import six
from aleph.util import checksum
class Archive(object):
def _get_file_path(self, meta):
ch = meta.content_hash
if ch is None:
raise ValueError("No content hash available.")
path = os.path.join(ch[:2], ch[2:4], ch[4:6], ch)
file_name = 'data'
... | .extension)
return os.path.join(six.text_type(path), six.text_type(file_name))
def _update_metadata(self, filename, meta):
meta.content_hash = checksum(filename)
return meta
def upgrade(self):
"""Run maintenance on the store."""
pass
def archive_file(self, filename... | iven file into the archive.
Return an updated metadata object. If ``move`` is given, the
original file will not exist afterwards.
"""
pass
def load_file(self, meta):
pass
def cleanup_file(self, meta):
pass
def generate_url(self, meta):
return
|
GISAElkartea/tresna-kutxa | tk/material/migrations/0005_auto_20190105_0017.py | Python | agpl-3.0 | 956 | 0.002092 | # Generated by Django 2.1.4 on 2019-01-04 23:17
import django.contrib.postgres.fields.ranges
from django.db import migrations
from psycopg2.extras import NumericRange
class Migration(migrations.Migration):
dependencies = [
('material', '0004_auto_20181227_2232'),
]
operations = [
migrat... | grations.RunSQL('commit;'),
migrations.RunSQL('update material_activity set num_people = int4range(min_people, max_people);'),
migrations.RunSQL('commit;'),
migrations.RemoveField(
model_name | ='activity',
name='max_people',
),
migrations.RemoveField(
model_name='activity',
name='min_people',
),
]
|
leppa/home-assistant | homeassistant/util/aiohttp.py | Python | apache-2.0 | 1,424 | 0 | """Utilities to help with aiohttp."""
import json
from typing import Any, Dict, Optional
from urllib.parse import parse_qsl
from multidict import CIMultiDict, MultiDict
class MockRequest:
"""Mock an aiohttp request."""
def __init__(
self,
content: bytes,
method: str = "GET",
... | eep_blank_values=True))
@property
def _text(self) -> str:
"""Return the body as text."""
return self._content. | decode("utf-8")
async def json(self) -> Any:
"""Return the body as JSON."""
return json.loads(self._text)
async def post(self) -> "MultiDict[str]":
"""Return POST parameters."""
return MultiDict(parse_qsl(self._text, keep_blank_values=True))
async def text(self) -> str:
... |
jylaxp/django | tests/forms_tests/tests/test_formsets.py | Python | bsd-3-clause | 57,919 | 0.002262 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.forms import (
CharField, DateField, FileField, Form, IntegerField, SplitDateTimeField,
ValidationError, formsets,
)
from django.forms.formsets import BaseFormSet, formset_factory
from django.forms.utils import ErrorLi... | extra=3)
# Used in ``test_formset_splitdatetimefield``.
class SplitDateTimeForm(Form):
when = SplitDateTimeField(initial=datetime.datetime.now)
SplitDateTimeFormSet = formset_factory(SplitDateTimeForm)
class CustomKwargForm(Form):
def __init__(self, *args, **kwargs):
self.custom_kwarg = kwargs.pop... | , **kwargs)
class FormsFormsetTestCase(SimpleTestCase):
def make_choiceformset(self, formset_data=None, formset_class=ChoiceFormSet,
total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs):
"""
Make a ChoiceFormset from the given formset_data.
The data s... |
OCA/purchase-workflow | purchase_order_line_description_picking/tests/__init__.py | Python | agpl-3.0 | 59 | 0 | from . import test_purchase_order_line_description_ | picki | ng
|
Aaron1992/flask | flask/json.py | Python | bsd-3-clause | 8,303 | 0.000241 | # -*- coding: utf-8 -*-
"""
flask.jsonimpl
~~~~~~~~~~~~~~
Implementation helpers for the JSON support in Flask.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import io
import uuid
from datetime import datetime
from .globals import current_app, request
fro... | _json.dumps('/')
__all__ = ['dump', 'dumps', 'load', 'loads', 'htmlsaf | e_dump',
'htmlsafe_dumps', 'JSONDecoder', 'JSONEncoder',
'jsonify']
def _wrap_reader_for_text(fp, encoding):
if isinstance(fp.read(0), bytes):
fp = io.TextIOWrapper(io.BufferedReader(fp), encoding)
return fp
def _wrap_writer_for_text(fp, encoding):
try:
fp.write('')... |
perfectsearch/sandman | test/buildscripts/import_test.py | Python | mit | 1,871 | 0.003207 | #!/usr/bin/env python
#
# $Id: ImportTest.py 4183 2011-01-03 20:17:03Z dhh1969 $
#
# Proprietary and confidential.
# Copyright $Date:: 2011#$ Perfect Search Corporation.
# All rights reserved.
#
import unittest, os, tempfile, subprocess, sys
from testsupport import checkin, CODEROOT
CODE_FOLDER = CODEROOT + '/buildscr... | = sys.path[1:]\n')
f.write('newPath = [sys.path[0], "%s"]\n' % CODE_FOLDER)
f.write('for item in oldRestOfPath:\n\tnewPath.append(item)\n')
f.write('sys.path = newPath\n')
f.write('exitCode = 0\n')
items = [i for i in os.listdir(CODE_FOLDER) if i.endswith('.py')]
for ite... | item)
f.write('exitCode = 1\n')
else:
moduleName = item[0:-3]
f.write('try:\n\timport %s\nexcept:\n' % moduleName)
f.write('\ttraceback.print_exc()\n')
f.write('\texitCode = 1\n')
f.write('if exitCode: print("IMPORTS FA... |
lingdb/CoBL-public | ielex/lexicon/migrations/0145_fix_language_distributions.py | Python | bsd-2-clause | 3,447 | 0 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from django.db import migrations
idDistributionMap = {
80: {'normalMean': 3450, 'normalStDev': 125},
133: {'normalMean': 3350, 'normalStDev': 75},
134: {'normalMean': 2350, 'normalStDev': 50},
135: {'normalMean': 3500, 'no... | (apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [('lexicon', '0144_clean_lexeme_romanised_2')]
operations = [
migrations.R | unPython(forwards_func, reverse_func),
]
|
ehabkost/virt-test | qemu/tests/9p.py | Python | gpl-2.0 | 1,818 | 0.00165 | import os,logging
from autotest.client.shared import error
from virttest import utils_test
def run_9p(test, params, env):
"""
Run an autotest test inside a guest.
@param test: kvm test object.
@param params: Dictionary with test parameters.
@param env: Dictionary with the test environment.
""... | ir)
mount_status = session.get_command_status(cmd)
if (mount_status != 0):
logging.error("mount failed")
raise error.TestFail('mount failed.')
# Collect test parameters
timeout = | int(params.get("test_timeout", 14400))
control_path = os.path.join(test.virtdir, "autotest_control",
params.get("test_control_file"))
outputdir = test.outputdir
utils_test.run_autotest(vm, session, control_path,
timeout, ... |
Waino/LeBLEU | lebleu/__init__.py | Python | bsd-2-clause | 670 | 0.004478 | #!/usr/bin/env python
"""
LeBLEU - Letter-edit / Levenshtein BLEU
"""
import logging
#__all__ = | []
__version__ = '0.0.1'
__author__ = 'Stig-Arne Gronroos'
__author_email__ = "stig-arne.gronroos@aalto.fi"
_logger = logging.getLogger(__name__)
def get_version():
return __version__
# The public api imports need to be at the end of the file,
# so that the package global names are available to the mod | ules
# when they are imported.
from .lebleu import LeBLEU
# Convenience functions
def eval_single(*args, **kwargs):
lb = LeBLEU(**kwargs)
return lb.eval_single(*args)
def eval(*args, **kwargs):
lb = LeBLEU(**kwargs)
return lb.eval(*args)
|
torbjoernk/easybuild-framework | easybuild/framework/easyblock.py | Python | gpl-2.0 | 93,981 | 0.003458 | # #
# Copyright 2009-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (ht... | loaded modules
self.loaded_modules = []
# iterate configure/build/options
self.iter_opts = {}
# sanity check fail error messages to report (if any)
self.sanity_check_fail_msgs = []
# robot path
self.robot_path = build_option('robot_pa | th')
# original module path
self.orig_modulepath = os.getenv('MODULEPATH')
# keep track of initial environment we start in, so we can restore it if needed
self.initial_environ = copy.deepcopy(os.environ)
# initialize logger
self._init_log()
# should we keep qu... |
quickresolve/accel.ai | flask-aws/lib/python2.7/site-packages/ebcli/controllers/create.py | Python | mit | 18,430 | 0.001302 | # Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... | . See the License for the specific
# | language governing permissions and limitations under the License.
import re
import argparse
import os
from ..core import io, fileoperations, hooks
from ..core.abstractcontroller import AbstractBaseController
from ..lib import elasticbeanstalk, utils
from ..objects.exceptions import NotFoundError, AlreadyExistsError,... |
michaelnt/doorstop | doorstop/cli/tests/test_utilities.py | Python | lgpl-3.0 | 7,856 | 0 | # SPDX-License-Identifier: LGPL-3.0-only
"""Unit tests for the doorstop.cli.utilities module."""
import sys
import unittest
from argparse import ArgumentTypeError
from unittest.mock import Mock, patch
from warnings import catch_warnings
from doorstop import common, settings
from doorstop.cli import utilities
from do... | """Verify a non-integer is rejected."""
self.assertRaises(ArgumentTypeError, utilities.positive_in | t, 'abc')
|
fiorix/cyclone | appskel/foreman/modname/main.py | Python | apache-2.0 | 820 | 0.009756 | import web
import sys, os
from twisted.python import log
from twis | ted.internet import defer, reactor
|
def main(config_file):
log.startLogging(sys.stdout)
application = web.Application(config_file)
port = os.environ.get("PORT", 8888)
reactor.listenTCP(int(port), applic... |
PostCenter/botlang | botlang/environment/primitives/exceptions.py | Python | mit | 1,226 | 0 | from botlang.evaluation.values import NativeException
def is_exception(value):
return isinstance(value, NativeException)
def try_catch_complete(process, failure,
after_execution=lambda: None, prod=True):
exception = None
try:
value = process()
if is_exception(value... | {}""".format(python_exception))
failure(exception)
finally:
after_execution()
def public_try_catch(process, failure, after_execution=lambda: None):
try_catch_complete(process, failure, after_execution, True)
def develop_try_catch(process, failure, after_execution=lambda: None... | ion, False)
EXCEPTION_PRIMITIVES = {
'exception?': is_exception,
'try-catch': public_try_catch,
'try-catch-verbose': develop_try_catch
}
|
Unit4TechProjects/ChoiceOptimization | run.py | Python | gpl-2.0 | 3,621 | 0.020713 | import subprocess
import sys
import csv
import re
import os, os.path
from fnmatch import fnmatch
CONFIG = "DATA_FILE={}\nALLOW_GREEDY=true\n"
DATE_CHECK = re.compile("[0-9]{1,2}([/\\-\\.])[0-9]{1,2}\\1[0-9]{4}")
def print_command_err(command, ret_code):
make_arg = lambda x: x.replace(" ", "\\ ")
command = [make_a... | the file %s.\nPress Enter when finished" % (filename))
call_c | ommand(["java", "duty_scheduler.Scheduler"])
create_secondary_prefs(csv_files, [get_temp_file(filename) for filename in csv_files])
raw_input("Please fill in the number of secondary duties for each RA in the file secondary.csv.\nPress Enter when finished")
write_config_file("secondary.csv")
call_command(... |
DefaultUser/DontSleep | dontsleep.py | Python | gpl-3.0 | 10,120 | 0.006324 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#***************************************************************************
#* Copyright (C) 2014 by Sebastian Schmidt [schro.sb@gmail.com] *
#* *
#* ... | awake_Icon)
super(TrayIcon, self).__init__(icon, parent)
# overwrite status based on user input
self.manual_PreventSleep = False
self.configDialog = None
self.activated.connect(self._icon_activated)
menu = QMenu()
showConfigWindowAction = QAction... | ion.triggered.connect(self.toggleConfigWindow)
aboutAction = QAction("About", menu)
aboutAction.triggered.connect(self.showAboutDialog)
aboutQtAction = QAction("About Qt", menu)
aboutQtAction.triggered.connect(self.showAboutQt)
exitAction = QAction("Exit", menu)
exitActio... |
vincentpc/yagra | main.py | Python | apache-2.0 | 955 | 0 | #!/usr/bin/env python
# coding=utf-8
from webapp.web import Application
from handlers.in | dex import IndexHandler
from handlers.register import RegisterHandler
from handlers.user import UserHandler
from handlers.signin import SigninHandler
from handlers.signout import SignoutHandler
from handlers.upload import UploadHandler
from handlers.avatar import AvatarHandler
from handlers.error import ErrorHandler
fr... | rom handlers.ftypeerror import FiletypeErrorHandler
URLS = (
("/", "IndexHandler"),
("/register?", "RegisterHandler"),
("/user", "UserHandler"),
("/signin", "SigninHandler"),
("/signout", "SignoutHandler"),
("/upload", "UploadHandler"),
("/avatar/(.*)", "AvatarHandler"),
("/error", "Er... |
sidzan/netforce | netforce_document/netforce_document/models/document_categ.py | Python | mit | 2,734 | 0.00256 | # Copyright (c) 2012-2015 Netforce Co. Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publ... | ons of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARR | ANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OT... |
dominikl/openmicroscopy | components/tools/OmeroPy/test/unit/clitest/test_import.py | Python | gpl-2.0 | 8,731 | 0 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Test of the omero import control.
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import pytest
from path import path
import omero.clients
import uuid
from omero.cli import CLI, NonZeroR... | ore):
"""Test fake screen import"""
screen_dir = tmpdir.join("screen.fake")
screen_dir.mkdir()
fieldfiles = self.mkfakescreen(
screen_dir, with_ds_store=with_ds_store)
self.add_client_dir()
self.args += ["-f", "--debug=ERROR"]
self.args += [str(field... | f.cli.invoke(self.args, strict=True)
o, e = capfd.readouterr()
outputlines = str(o).split('\n')
reader = 'loci.formats.in.FakeReader'
assert outputlines[-len(fieldfiles)-2] == \
"# Group: %s SPW: true Reader: %s" % (str(fieldfiles[0]), reader)
for i in range(len(field... |
TuSimple/mxnet | python/mxnet/metric.py | Python | apache-2.0 | 43,258 | 0.000925 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | = [pred[name] for name in self.output_names]
else:
pred = list(pred.values())
if self.label_names is not None:
label = [label[name] for name in self.label_names]
else:
| label = list(label.values())
self.update(label, pred)
def update(self, labels, preds):
"""Updates the internal evaluation result.
Parameters
----------
labels : list of `NDArray`
The labels of the data.
preds : list of `NDArray`
Predicted... |
Seynen/egfrd | samples/mapk/model3-conc.py | Python | gpl-2.0 | 4,745 | 0.004004 | #!/usr/bin/env python
from egfrd import *
from logger import *
import sys
import math
model='mapk3-c'
V_str = sys.argv[1]
D_ratio_str = sys.argv[2]
D_mode = sys.argv[3]
ti_str = sys.argv[4]
mode = sys.argv[5]
T_str = sys.argv[6]
V = float(V_str)
D_ratio = float(D_ratio_str)
ti = float(ti_str)
T = float(T_str)
# ... | ki = math.log(2) / ti
D_ref = 1e-12
D_move = D_ref * D_ratio
if D_mode == 'normal':
D_react = D_move
elif D_mode == 'fixed':
D_react = D_ref
# V in liter, L in meter
L = math.pow(V * 1e-3, 1.0 / 3.0)
s = EGFRDSimulator()
s.set_world_size(L)
N = 180
matrix_size = min(max(3, int((3 * N) ** (1.0/3.0))), ... | lRegion([0,0,0],[L,L,L])
# not supported yet
#s.add_surface(box1)
radius = 2.5e-9
m = ParticleModel()
K = m.new_species_type('K', D_move, radius)
KK = m.new_species_type('KK', D_move, radius)
P = m.new_species_type('P', D_move, radius)
Kp = m.new_species_type('Kp', D_move, radius)
Kpp = m.new_species_type('Kpp', D_m... |
graphql-python/gql | tests/starwars/test_validation.py | Python | mit | 5,441 | 0.000368 | import pytest
from gql import Client, gql
from .schema import StarWarsIntrospection, StarWarsSchema
@pytest.fixture
def local_schema():
return Client(schema=StarWarsSchema)
@pytest.fixture
def typedef_schema():
return Client(
schema="""
schema {
query: Query
}
interface Character {
appearsIn:... | ...NameAndAppearances
friends {
...NameAndAppearances
}
}
}
}
fragment NameAndAppearances on Character {
name
appearsIn
}
"""
assert not validation_errors(client, query)
def test_non_existent... | = """
query HeroSpaceshipQuery {
hero {
favoriteSpaceship
}
}
"""
assert validation_errors(client, query)
def test_require_fields_on_object(client):
query = """
query HeroNoFieldsQuery {
hero
}
"""
assert validation_errors(c... |
arenaoftitans/arena-of-titans-api | aot/reload.py | Python | agpl-3.0 | 3,602 | 0.000555 | ################################################################################
# Copyright (C) 2015-2020 by Last Run Contributors.
#
# This file is part of Arena of Titans.
#
# Arena of Titans is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publ... | self):
self.app = Popen(["python3", "-m", "aot", "--debug"]) # noqa: S603,S607 (Popen usage)
def stop_app(self):
self.app.terminate()
cleanup(None, None)
@property
def loop(self):
return self._loop
@loop.setter
def loop(self, loop):
| self._loop = loop
def run_reload():
aot_event_handler = AotEventHandler()
aot_event_handler.start_app()
observer = Observer()
observer.schedule(aot_event_handler, "aot", recursive=True)
observer.start()
# Make dependent thread shutdown on SIGTERM.
# This is required for the containe... |
MengbinZhu/pfldp | ropp-7.0/grib_api-1.9.9/examples/python/clone.py | Python | gpl-3.0 | 910 | 0.01978 | import traceback
import sys
import random
from gribapi import *
INPUT='../../data/constant_field.grib1'
OUTPUT='out.grib'
VERBOSE=1 # verbose error reporting
def example():
fin = open(INPUT)
fout = open(OUTPUT,'w')
gid = grib_new_from_file(fin)
nx = grib_get(gid,'Ni')
ny = grib_get(gid,'Nj')
... | om() for i in range(nx*ny)]
grib_set_values(clone_id,values)
grib_write(clone_id,fout)
grib_release(clone_id)
grib_release(gid)
fin.close()
fout.close()
def main():
try:
e | xample()
except GribInternalError,err:
if VERBOSE:
traceback.print_exc(file=sys.stderr)
else:
print >>sys.stderr,err.msg
return 1
if __name__ == "__main__":
sys.exit(main())
|
linuxipho/mycroft-core | mycroft/skills/skill_data.py | Python | apache-2.0 | 5,706 | 0 | # Copyright 2018 Mycroft AI Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | >.
The function will not munge instances that's already been
munged
Args:
intent_parser: (IntentParser) object to update
name: (str) Skill name
skill_id: (int) skill identifier
"""
# Munge parser name
if str(skill_id) + ':' not in name:
intent_parser.name = str(... | se:
intent_parser.name = name
# Munge keywords
skill_id = to_alnum(skill_id)
# Munge required keyword
reqs = []
for i in intent_parser.requires:
if skill_id not in i[0]:
kw = (skill_id + i[0], skill_id + i[0])
reqs.append(kw)
else:
reqs.ap... |
icamgo/esp-idf | components/idf_test/integration_test/TestCaseScript/TCPStress/TCPConnection.py | Python | apache-2.0 | 12,186 | 0.001969 | import random
import re
import socket
import threading
import time
import TCPConnectionUtility
from NativeLog import NativeLog
from TCAction import PerformanceTCBase
DELAY_RANGE = [10, 3000]
CONNECTION_STRUCTURE = ("Connection handler", "PC socket", "Target socket id",
"Target port", "PC port"... | = CheckerBase.SLEEP_TIME/2
def __init__(self, utility, serial_checker, tcp_checker, connect_method, disconnect_method, test_case):
threading.Thread.__init__(self)
self.setDaemon(True)
self.utility = utility
self.connect_method = connect_method
self.disconnect_method = disco... | vent()
# following members are used in communication with checker threads
self.serial_checker = serial_checker
self.tcp_checker = tcp_checker
self.serial_notify_event = threading.Event()
self.tcp_notify_event = threading.Event()
self.serial_result = None
self.tcp_... |
qilicun/python | python2/PyMOTW-1.132/PyMOTW/threading/threading_daemon.py | Python | gpl-3.0 | 649 | 0.007704 | #!/usr/bi | n/env python
# encoding: utf-8
#
# Copyright (c) 2008 Doug Hellmann All rights reserved.
#
"""Daemon vs. non-daemon threads.
"""
#end_pymotw_header
import threading
import time
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
... | daemon():
logging.debug('Starting')
logging.debug('Exiting')
t = threading.Thread(name='non-daemon', target=non_daemon)
d.start()
t.start()
|
rtam2166/XBAS | task_share.py | Python | mit | 3,530 | 0.011331 | # -*- coding: utf-8 -*-
#
## @file task_share.py
# This file contains classes which allow tasks to share data without the risk
# of data corruption by interrupts.
#
# @copyright This program is copyright (c) JR Ridgely and released under the
# GNU Public License, version 3.0.
import array
import gc
import pyb
im... | eading
which can corrupt shared data includes th | e use of ordinary interrupts as
well as the use of a Real-Time Operating System (RTOS). """
## A counter used to give serial numbers to shares for diagnostic use.
ser_num = 0
def __init__ (self, type_code, thread_protect = True, name = None):
""" Allocate memory in which the shared data will ... |
gtoonstra/remap | examples/pagerank/pagerank.py | Python | mit | 1,106 | 0.028933 | import remap
# --- create file i/o objects to be used ----
def create_vertex_reader( filename ):
return remap.TextFileReader( filename, yieldkv=False )
def create_vertex_partitioner( outputdir, partition, mapperid ):
return remap.TextPartitioner( outputdir, partition, mapperid )
NUM_VERTICES = 10
# ---- pag... | _id in | out:
send_fn( vertex_id, "%f"%( val / len(out) ))
else:
return vertex, True
return vertex, False
|
WoLpH/EventGhost | plugins/XBMCEventReceiver/__init__.py | Python | gpl-2.0 | 8,990 | 0.010791 | # -*- coding: utf-8 -*-
#
# plugins/XBMCEventReceiver/__init__.py
#
# This file is a plugin for EventGhost.
# Copyright © 2005-2016 EventGhost Project <http://www.eventghost.net/>
#
# EventGhost is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published b... | mcip, xbmcipCtrl)
panel.AddLine(self.text.xbmchttpport, xbmchttpportCtrl)
panel.AddLine(self.text.zone, zoneCtrl)
panel.AddLine(self.text.port, portCtrl)
panel.AddLine(self.text.selfXbmceventbroadcast,selfXbmceventbroadcastCtrl)
panel.AddLine("Payload Delimiter", payDelimCtrl)
... | t(editCtrl.GetValue(),xbmcipCtrl.GetValue(),int(xbmchttpportCtrl.GetValue()),zoneCtrl.GetValue(),int(portCtrl.GetValue()),selfXbmceventbroadcastCtrl.GetValue(), payDelimCtrl.GetValue() )
v_header = urllib.quote("This is the Header")
v_message = urllib.quote("This is the Message")
host_... |
kensho-technologies/graphql-compiler | graphql_compiler/interpreter/expression_ops/operators.py | Python | apache-2.0 | 2,903 | 0.002067 | from typing import Any, Callable, Optional
# Define the various operators' behavior for values other than None.
# The behavior with respect to None is defined explicitly in the "apply_operator()" function.
_operator_definitions_for_non_null_values = {
"=": lambda left, right: left == right,
">": lambda left, ... | left_none = left_value is None
right_none = right_value is None
if left_none and right_none:
if operator in {"=", ">=", "<="}:
# The operation simplifies to None = None, which we define as True.
return True
elif operator == "!=":
# We have None != None, wh... | other comparisons vs None produce False.
return False
elif left_none or right_none:
# Only one of the values is None. We define this to always be False, for all operators.
return False
elif not left_none and not right_none:
# Neither side of the operator is None, apply opera... |
jakesyl/BitTornado | BitTornado/Client/Statistics.py | Python | mit | 6,510 | 0.000307 | import threading
class Statistics_Response:
pass # empty class
class Statistics:
def __init__(self, upmeasure, downmeasure, connecter, httpdl,
ratelimiter, rerequest_lastfailed, fdatflag):
self.upmeasure = upmeasure
self.downmeasure = downmeasure
self.connecter = ... | s
s.numCopies = 0.0
for i in self.picker.crosscount:
if i == 0:
s.numCopies += 1
else:
s.numCopies += 1 - float(i) / self.picker.numpieces
break
if self.picker.done:
s.numCopies2 = s.numCop | ies + 1
else:
s.numCopies2 = 0.0
for i in self.picker.crosscount2:
if i == 0:
s.numCopies2 += 1
else:
s.numCopies2 += 1 - float(i) / self.picker.numpieces
break
s.discarded = self.download... |
apeterson5813/nopower | tests/test_models.py | Python | mit | 294 | 0.006803 | from unitte | st import TestCase
from playhouse.test_utils import test_database
from peewee import *
from nopower.models import GeneratorList, Outage, GenerationResource
test_db = SqliteDatabase(':memory:')
class TestGeneratorListOutage(TestCase):
def create_test_data(self):
| pass
|
VHAINNOVATIONS/GE-Pressure-Ulcer | python_gui_decision_support_webportal/python/prevention_clinical_data.py | Python | apache-2.0 | 2,367 | 0.014787 | from sqlalchemy import Column, Integer, String, DateTime, Boolean
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class PreventionClinicalData(Base):
"""
Definition of PreventionClinicalData object. It will be used by SQLAlchemy's ORM to map the object to
the patient_turn... | tient_id',Integer)
clinical_rounding_time = Column('clinical_rounding_time',DateTime)
repositioning_flag = Column('repositioning_flag',Boolean)
final_position = Column('final_position',String)
repositioning_description = Column('repositioning_description',String)
| keyCol = 'id'
editCols = ['clinical_rounding_time','repositioning_flag','final_position','repositioning_description']
editColsLabels = ['Rounding Time','Repositioned?','Final Position','Notes']
editColsTypes = ['date','boolean','string','string']
displayTableName = 'Patient Prevention Clinical Data'
... |
nirs/vdsm | tests/passwords_test.py | Python | gpl-2.0 | 6,754 | 0 | #
# Copyright 2015-2020 Red Hat, 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 ... | ed, unprotect_passwords(protected))
def test_protect_nested_dicts(self):
unprotected = nested_dicts_unprotected()
protected = nested_dicts_protected()
self.assertEqual(protected, protect_passwords(unprotected))
def test_unprotect_nested_dicts(self):
protected = nested_dicts_pro... | .assertEqual(unprotected, unprotect_passwords(protected))
def test_protect_lists_of_dicts(self):
unprotected = lists_of_dicts_unprotected()
protected = lists_of_dicts_protected()
self.assertEqual(protected, protect_passwords(unprotected))
def test_unprotect_lists_of_dicts(self):
... |
openqt/algorithms | leetcode/python/ac/lc804-unique-morse-code-words.py | Python | gpl-3.0 | 2,281 | 0.003946 | # coding=utf-8
import unittest
"""804. Unique Morse Code Words
https://leetcode.com/problems/unique-morse-code-words/description/
International Morse Code defines a standard encoding where each letter is
mapped to a series of dots and dashes, as follows: `"a"` maps to `".-"`, `"b"`
maps to `"-..."`, `"c"` maps to `"-... | r example, "cab" can be written as "-.-.-....-",
(which is the concatenation "-.-." \+ "-..." \+ ".-"). We'll call such a
concatenation, the transformation of a word.
Return the number of different transformations among all words we have.
**Example:**
**Input:** words = ["gin", "zen", "gig", "msg"]
... | > "--...--."
"msg" -> "--...--."
There are 2 different transformations, "--...-." and "--...--.".
**Note:**
* The length of `words` will be at most `100`.
* Each `words[i]` will have length in range `[1, 12]`.
* `words[i]` will only consist of lowercase letters.
Similar Questions:
"""
c... |
TehJoE/Cat-Herder | cat_herder.py | Python | mit | 5,029 | 0.010141 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Li-aung "Lewis" Yip
minecraft@penwatch.net
Requires:
plac (command line argument parsing)
unshortenit (adf.ly resolving)
"""
STARTUP_SCRIPT_TEMPLATE = """#!/bin/bash
java -Xmx2G -XX:MaxPermSize=256M -jar {fn} nogui"""
import os
import json
from operator impor... | fZ
As above, but manually specifying the download cache and server install folders:
cat_herder.py install-from-share-code -s QtDNnlfZ -c /home/mc/cache -i /home/mc/install/
Installing with | manually specified pack name and pack version:
cat_herder.py install -p BevosTechPack -v BTP-11-Full -c /home/mc/cache -i /home/mc/install/
"""
if install_folder:
install_folder = os.path.realpath(install_folder)
else:
install_folder = os.path.realpath('./install/{pn}/{pv}'.format(pn=pa... |
MaestroGraph/sparse-hyper | experiments/gconv-simple.py | Python | mit | 17,048 | 0.003695 | import sys
import matplotlib as mpl
import torch.nn.functional as F
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from tensorboardX import SummaryWriter
from torch import nn
from torch.autograd import Variable
from tqdm import trange
import gaussian
import util
from util i... | rt ArgumentParser
import networkx as nx
import math
import torch
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
"""
Simple Graph convolution experiment. Given a set of random vectors, learn to express each as the sum of some of the
others
"""
def clean(axes=None):
if axes... | |
Karl-Marka/data-mining | scleroderma-prediction/getGeneDescLocal_Illumina.py | Python | gpl-3.0 | 1,180 | 0.016949 | import pandas as pd
def closeFunc():
print('''Type 'quit' and press enter to exit program''')
answer = input(': ')
if answer == 'quit':
quit()
else:
closeFunc()
def oligosList():
oligosPath = input('Path to the file containing the list of probes: ')
oligos = open(oligosPath)
... | eDescLocal_results.txt', sep = '\t')
closeFunc()
if __name__ == "__main__":
oligosList = oligosList()
ans | wer = input('Do you want full data? (yes/no) ')
if answer == 'no':
main(oligosList)
elif answer == 'yes':
main(oligosList, True)
else:
print('Wrong answer')
closeFunc() |
Chilledheart/chromium | tools/telemetry/third_party/gsutilz/third_party/boto/tests/unit/s3/test_website.py | Python | bsd-3-clause | 9,219 | 0.000434 | # Copyright (c) 2013 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights ... | x='index.html')
xml = config.to_xml()
self.assertIn(
'<IndexDocument><Suffi | x>index.html</Suffix></IndexDocument>', xml)
def test_suffix_and_error(self):
config = WebsiteConfiguration(suffix='index.html',
error_key='error.html')
xml = config.to_xml()
self.assertIn(
'<ErrorDocument><Key>error.html</Key></ErrorDocumen... |
uwekamper/matelight-scheduler | docs/conf.py | Python | bsd-3-clause | 7,794 | 0.002309 | # -*- coding: utf-8 -*-
#
# 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.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
imp... | The short X.Y version.
version = '' # Is set by calling `setup.py docs`
# The full version, including alpha/beta/rc tags.
release = '' # Is set by calling `setup.py docs`
# The language fo | r content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %... |
jidol/Examples | src/avl_tree.py | Python | gpl-2.0 | 5,481 | 0.000182 | from typing import Any
from binary_tree import BinaryTree, BinaryTreeNode
class AvlTree(BinaryTree):
def __init__(self, value):
super(AvlTree, self).__init__(value)
self.height = 1
def _left_rotate(self, node: BinaryTreeNode) -> BinaryTreeNode:
"""
Rotate node left
:... | return self._left_rotate(node)
# Case 3 - Left Right
if balance > 1 and value > node.left.value:
node.left = self._left_rotate(node.left | )
return self._right_rotate(node)
# Case 4 - Right Left
if balance < -1 and value < node.right.value:
node.right = self._right_rotate(node.right)
return self._left_rotate(node)
return node
|
fevxie/odoo-infrastructure | infrastructure/models/docker_image.py | Python | agpl-3.0 | 2,128 | 0 | # -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields
class infrast... | e', '=', 'postgresql')],
help='Compatible Postgresql Images',
)
odoo_image_ids = fields.Many2many(
'infrastructure.docker_image',
'infrastructure_odoo_pg_image_rel',
'pg_image_id', 'odoo_image_id',
strin | g='Odoo Images',
domain=[('service', '=', 'odoo')],
help='Compatible Odoo Images',
)
class infrastructure_docker_image_tag(models.Model):
_name = 'infrastructure.docker_image.tag'
_description = 'Docker Image Tag'
_order = 'sequence'
name = fields.Char(
'Name',
... |
julio73/scratchbook | code/work/alu/indenter.py | Python | mit | 1,460 | 0.026027 | # binary tag: refers to tags that have open and close el | ement
# eg: [a]some content[/a]
# standalone tag: refers t | o tags that are self contained
# eg: [b some content]
# Assuming that the text input is well formatted
# open input and output file
with open('textin.txt', 'r') as f1, open('textout.txt', 'w') as f2:
lines = f1.readlines()
# keep track of all binary tags (i.e. closeable tag)
closeables = set()
for line in li... |
XENON1T/pax | pax/plugins/DeleteLowLevelInfo.py | Python | bsd-3-clause | 2,081 | 0.002883 | from pax import plugin
import numpy as np
class DeleteLowLevelInfo(plugin.TransformPlugin):
"""This deletes low-level info from the datastructure, to make the output file smaller.
By default, this is what gets removed:
* hits for all but the main s1
* pulses for all but the main s1
* sum wav... | pulses_to_keep.extend(p.hits['found_in_pulse'].tolist())
else:
p.hits = p.hits[:0] # Set hits to an empty array
pulses_to_keep = np.unique(pulses_to_keep)
event.all_hits = event.all_hits[:0]
event.pulses = [p for i, p in enume... | s:
p.hits = p.hits[:0]
else:
raise ValueError("Illegal delete_hits_and_pulses value %s" % delopt)
return event
|
bobman/magnemo | main.py | Python | gpl-3.0 | 4,681 | 0.012818 | from flask import Flask, render_template, request
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required
from flask.ext.login import current_user
import os
import json
from flask_mail import Mail
import base64
def load_json():
... | self.title=title
self.text=text
self.user=user
self.top=top
self.left=left
self.height=height
self.width=width
def get_dataDict(self):
magnetData = {
"id":self.id,
"title":self.title,
"text":self.text,
"to... | curity
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# Create a user to test with
# @app.before_first_request
# def create_user():
#db.create_all()
# TODO: User creation via config file or installer
#user_datastore.create_user(email='admin@localhost', passwo... |
kwilliams-mo/iris | lib/iris/analysis/interpolate.py | Python | gpl-3.0 | 39,449 | 0.002966 | # (C) British Crown Copyright 2010 - 2013, Met Office
#
# This file is part of Iris.
#
# Iris 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 3 of the License, or
# (at your option) any l... | ', '.join([coord.name() for coord in dim_to_coord_map[data_dim]]), data_dim))
indices[data_dim] = min_index
return tuple(indices)
def _nearest_neighbour_indices_ndcoords(cube, sample_point, cache=None):
"""
See documentation for :func:`iris.analysis.interpolate.nearest_neighbour_indices`.
T... | ause this function can be slow for multidimensional coordinates,
a 'cache' dictionary can be provided by the calling code.
"""
# Developer notes:
# A "sample space cube" is made which only has the coords and dims we are sampling on.
# We get the nearest neighbour using this sample space cube.
... |
freelan-developers/chromalog | chromalog/mark/helpers.py | Python | mit | 5,224 | 0 | """
Automatically generate marking helpers functions.
"""
import sys
from .objects import Mark
class SimpleHelpers(object):
"""
A class that is designed to act as a module and implement magic helper
generation.
"""
def __init__(self):
self.__helpers = {}
def make_helper(self, color... | nce helper method that marks an object with the
{color_tag_true!r} color tag if `condition` is truthy, and with the
{color_tag_false!r} color tag other | wise.
:param obj: The object to mark for coloration.
:param condition: The condition to verify. If `condition` is
:const:`None`, the `obj` is evaluated instead.
:returns: A :class:`Mark<chromalog.mark.objects.Mark>` instance.
>>> from chromalog.mark.help... |
bozzzzo/qpid-proton | tests/python/proton_tests/common.py | Python | apache-2.0 | 19,016 | 0.006679 | #
# 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... | 0.1"))
@property
def timeout(self):
return float(self.default("timeout", "60", fast="10"))
@property
def verbose(self):
return int(self.default("verbose", 0))
class Skipped(SkipTest):
skipped = True
class TestServer(object):
""" Base class for creating test-specific message servers.
"""
de... | self.reactor = Container(self)
self.host = "127.0.0.1"
self.port = 0
if "host" in kwargs:
self.host = kwargs["host"]
if "port" in kwargs:
self.port = kwargs["port"]
self.handlers = [CFlowController(10), CHandshaker()]
self.thread = Thread(name="server-thread", target=self.run)
... |
kawamon/hue | desktop/core/ext-py/SQLAlchemy-1.3.17/lib/sqlalchemy/events.py | Python | apache-2.0 | 53,052 | 0 | # sqlalchemy/events.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Core event interfaces."""
from . import event
from . import exc
from . impo... | be established for any copies made of the target object,
i.e. those copies that are generated when
:meth:`_schema.Table.tometadata` is used.
"""
def after_parent_attach(self, target, parent):
"""Called after a :class:`.SchemaItem` is associated with
a parent :class:`.Sche... |
:func:`.event.listen` also accepts the ``propagate=True``
modifier for this event; when True, the listener function will
be established for any copies made of the target object,
|
gencer/sentry | src/sentry/deletions/__init__.py | Python | bsd-3-clause | 4,094 | 0.00171 | """
The deletions subsystem managers bulk deletes as well as cascades. It attempts
to optimize around various patterns while using a standard approach to do so.
For example, let's say you want to delete an organization:
>>> from sentry import deletions
>>> task = deletions.get(model=Organization)
>>> work = True
>>> ... | lt_manager.register(models.Group, defaults.GroupDeletionTask)
default_manager.register(models.GroupAssignee, BulkModelDeletionTask)
default_manager.register(models.GroupBookmark, BulkModelDeletionTask)
default_manager.register(models.GroupCommitResolution, BulkModelDeletionTask)
default_manager.register... | letionTask)
default_manager.register(models.GroupEmailThread, BulkModelDeletionTask)
default_manager.register(models.GroupHash, BulkModelDeletionTask)
default_manager.register(models.GroupMeta, BulkModelDeletionTask)
default_manager.register(models.GroupRedirect, BulkModelDeletionTask)
default_manag... |
suryakencana/niimanga | niimanga/views/main.py | Python | lgpl-3.0 | 4,364 | 0.000687 | """
# Copyright (c) 04 2015 | surya
# 21/04/15 nanang.ask@kubuskotak.com
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either | version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
... | the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# main.py
"""
from niimanga.configs.view import ZHandler
from niimanga.libs.crawlable import CrawlAble
from niimanga.models.manga import Manga
... |
BrainTech/openbci | obci/logic/configs/config_multiple_8.py | Python | gpl-3.0 | 2,287 | 0.012243 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import config_speller_8
import config_robot_8
class Config(object):
def __init__(self):
self.number_of_decisions = 8
speller = config_speller_8.Config()
robot = config_robot_8.Config()
self.state = []
self.actions = []
se... | te = 1
#SPELLER
speller_state = zero_state
for i, s in enumerate(speller.state):
self.state.append([x+speller_state for x in s])
self.actions.append(speller.actions[i])
self.letters | .append(speller.letters[i])
self.state[zero_state][-1] = 0 #GOTO MENU
self.actions[zero_state][-1] = "clear()"
zero_state += len(speller.state)
#ROBOT
robot_state = zero_state
for i, s in enumerate(robot.state):
self.state.append([x+robot_state for x in s])
... |
jimi-c/ansible | lib/ansible/modules/utilities/logic/wait_for.py | Python | gpl-3.0 | 24,145 | 0.003106 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Jeroen Hoekx <jeroen@hoekx.be>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
... | the presence of a file did not work correctly if the remote user did not have read access to that file | .
- Under some circumstances when using mandatory access control, a path may always be treated as being absent even if it exists, but
can't be modified or created by the remote user either.
- When waiting for a path, symbolic links will be followed. Many other modules that manipulate files do not follow symbol... |
teamfx/openjfx-8u-dev-rt | modules/web/src/main/native/Source/JavaScriptCore/inspector/scripts/codegen/cpp_generator.py | Python | gpl-2.0 | 14,357 | 0.00209 | #!/usr/bin/env python
#
# Copyright (c) 2014, 2016 Apple Inc. All rights reserved.
# Copyright (c) 2014 University of Washington. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributio... | e, (ArrayType, ObjectType)):
| return 'RefPtr<%s>' % CppGenerator.cpp_protocol_type_for_type(_type)
if isinstance(_type, AliasedType):
builder_type = CppGenerator.cpp_protocol_type_for_type(_type)
if is_optional:
return 'const %s* const' % builder_type
elif _type.aliased_type.qualif... |
ikben/bless | bless/ssh/certificate_authorities/rsa_certificate_authority.py | Python | apache-2.0 | 2,420 | 0.002066 | """
.. module: bless.ssh.certificate_authorities.rsa_certificate_authority
:copyright: (c) 2016 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
"""
from bless.ssh.certificate_authorities.ssh_certificate_authority import \
SSHCertificateAuthority
from bless.ssh.protocol.... | SSH Public Key associated with this CA.
Packed per RFC4253 section 6.6.
:return: SSH Public Key.
"""
key = pack_ssh_string(self.public_key_type)
key += pack_ssh_mpint(self.e)
key += pack_ | ssh_mpint(self.n)
return key
def sign(self, body):
"""
Sign the certificate body with the RSA private key. Signatures are computed and
encoded per RFC4253 section 6.6
:param body: All other fields of the SSH Certificate, from the initial string to the
signature key.... |
mhbu50/frappe | frappe/core/doctype/version/test_version.py | Python | mit | 1,227 | 0.02119 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
import frappe
import unittest, copy
from frappe.test_runner import make_test_objects
from frappe.core.doctype.versi | on.version import get_diff
class TestVersion(unittest.TestCase):
def test_get_diff(self):
frappe.set_user('Administrator')
test_records = make_test_objects('Event', reset = True)
old_doc = frappe.get_doc("Event", test_records[0])
new_doc = copy.deepcopy(old_doc)
old_doc.color = None
new_doc.color = '#faf... | d_values(diff)[0] is None)
self.assertEqual(get_new_values(diff)[0], '#fafafa')
new_doc.starts_on = "2017-07-20"
diff = get_diff(old_doc, new_doc)['changed']
self.assertEqual(get_fieldnames(diff)[1], 'starts_on')
self.assertEqual(get_old_values(diff)[1], '01-01-2014 00:00:00')
self.assertEqual(get_new_va... |
ISeaTeL/ISeaTeL_Cup_Site | oj_judge/models.py | Python | mit | 619 | 0.008078 | from django.db import models
from datetime import datetime
class JudgeResult(models.Model):
sid = models.IntegerField()
pid = models.IntegerField()
username = models.CharField(max_length=50)
result = models.CharField(max_length=50)
time = models.IntegerField()
memory = models.IntegerField()
... | (max_length=50)
def __str__(self):
return self.us | ername + ': ' + self.result
|
laysakura/shellstreaming | test/ostream/test_localfile.py | Python | apache-2.0 | 1,074 | 0.002793 | # -*- coding: utf-8 -*-
import nose.tools as ns
import os
from os.path import join
from tempfile import gettempdir
from relshell.record import Record
from relshell.recorddef import RecordDef
from relshell.batch import Batch
from shellstreaming.core.batch_queue import BatchQueue
from shellstreaming.ostream.localfile imp... |
q.push(batch) # [fix] - Batch's output format has to be customized by user
q.push(None)
# run ostream
ostream = LocalFile(TEST_FILE, output_format='csv', input_queue=q)
ostream.join()
# check contents
with open(TEST_FILE) as f:
| ns.eq_(f.read(),
'''"111"
"222"
"333"
'''
)
def _create_batches():
rdef = RecordDef([{'name': 'col0', 'type': 'INT'}])
return (
Batch(rdef, (Record(111), Record(222), )),
Batch(rdef, (Record(333), )),
)
|
magyarm/periphondemand-code | src/bin/core/generic.py | Python | lgpl-2.1 | 4,911 | 0.012014 | #! /usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Name: Generic.py
# Purpose:
# Author: Fabien Marteau <fabien.marteau@armadeus.com>
# Created: 21/05/2008
#-----------------------------------------------------------------------------
# Co... | 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 that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# alo... |
kpanic/lymph | iris/core/trace.py | Python | apache-2.0 | 983 | 0.001017 | import gevent
import gevent.pool
import uuid
import logging
def get_trace(greenlet=None):
greenlet = greenlet or gevent.getcurrent()
if not hasattr(greenlet, '_iris_trace'):
greenlet._iris_trace = {}
return greenlet._iris_trace
def spawn(*args, **kwargs):
greenlet = gevent.Greenlet(*args, **... |
g = _spawn(*args, **kwargs)
self.add(g)
return g
def trace(**kwargs):
get_trace().update(kwargs)
def set_id(trace_id=None):
trace_id = trace_id or uuid.uuid4().hex
trace(iris_trace_id=trace_id)
return tr | ace_id
def get_id():
return get_trace().get('iris_trace_id')
class TraceFormatter(logging.Formatter):
def format(self, record):
record.trace_id = get_id()
return super(TraceFormatter, self).format(record)
|
jawilson/home-assistant | homeassistant/components/template/cover.py | Python | apache-2.0 | 12,433 | 0.000563 | """Support for covers which integrate with other components."""
import logging
import voluptuous as vol
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
DEVICE_CLASSES_SCHEMA,
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SUPPORT_CLOSE,
SUPPORT_CLOSE_TILT,
SUPPORT_O... | entity_config,
unique_id,
)
)
return covers
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Template cover."""
async_add_entities(await _async_create_entities(hass, config))
class CoverTemplate(TemplateE... | e cover."""
def __init__(
self,
hass,
object_id,
config,
unique_id,
):
"""Initialize the Template cover."""
super().__init__(config=config)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, object_id, hass=hass
)
... |
hpfn/charcoallog | charcoallog/investments/admin.py | Python | gpl-3.0 | 915 | 0 | from django.contrib import admin
from charcoall | og.investments.models import NewInvestment, NewInves | tmentDetails
class NewInvestmentModelAdmin(admin.ModelAdmin):
list_display = ('user_name', 'date', 'money', 'kind', 'tx_op', 'brokerage')
readonly_fields = ('user_name',)
search_fields = ('date',)
date_hierarchy = 'date'
def get_queryset(self, request):
qs = super().get_queryset(request)
... |
gxxjjj/QuantEcon.py | quantecon/tests/test_lqcontrol.py | Python | bsd-3-clause | 2,299 | 0.00261 | """
Author: Chase Coleman
Filename: test_lqcontrol
Tests for lqcontrol.py file
"""
import sys
import os
import unittest
import numpy as np
from scipy.linalg import LinAlgError
from numpy.testing import assert_allclose
from quantecon.lqcontrol import LQ
class TestLQControl(unittest.TestCase):
def setUp(self):
... | # Initial Values
q = 1.
r = 1.
rf = 1.
a = .95
b = -1.
c = .05
beta = .95
T = 1
self.lq_scalar = LQ(q, r, a, b, C=c, beta=beta, T=T, Rf=rf)
Q = np.array([[0., 0.], [0., 1]])
R = np.array([[1., 0.], [0., 0]])
RF = np.eye... | , A, B, beta=beta, T=T, Rf=RF)
def tearDown(self):
del self.lq_scalar
del self.lq_mat
def test_scalar_sequences(self):
lq_scalar = self.lq_scalar
x0 = 2
x_seq, u_seq, w_seq = lq_scalar.compute_sequence(x0)
# Solution found by hand
u_0 = (-2*lq_scala... |
windj007/python-gremlin-rest | gremlin_rest/tests/all_tests.py | Python | apache-2.0 | 1,682 | 0.013674 | import unittest
from gremlin_rest import GremlinClient
class TestClient(unittest.TestCase):
def setUp(self):
self.client = GremlinClient('http://172.17.0.248:8182')
def tearDown(self):
for v in self.client.V().run():
self.client.delete_vertex(vertex_id = v.vertex_id)
def test... | = self.client.V().run()
print repr(vs)
self.assertEqual(len(vs) - init_cnt, 1)
self.client.delete_vertex(vertex_id = v.vertex_id)
self.assertEqual(len(self.client.V().run()), init_cnt)
def test_query_vertices(self):
print 'before', repr(self.client.V().run())
v1 = se... |
print 'all', repr(self.client.V().run())
print '12', repr(self.client.V().has('a', 12).run())
print '123', repr(self.client.V().has('a', 123).run())
print '1234', repr(self.client.V().has('a', 1234).run())
print 'qwe', repr(self.client.V().has('b', 'qwe').run())
self.ass... |
openafs-contrib/afspy | afs/model/DBServer.py | Python | bsd-2-clause | 971 | 0.014418 | """
Declares Model object of a database-server
"""
from afs.model.BaseModel import BaseModel
class DBServer(BaseModel):
"""
Model object of a database-server
"""
def __init__(self):
"""
initialize an empty object.
"""
# declare db-internal attributes
BaseMo | del.__init__(self)
## for db index
self.db_id = None
## list of DNS-hostnames
self.servernames = None
self.servernames_js = ""
## list of ipaddrs
self.ipaddr = " | "
## Flag if it is a clone or real db-server
self.is_clone = True
## type of db : vldb or ptdb
self.afsdb_type = ""
## local version of the DB
self.local_afsdb_version = ""
## rxdebug version string
self.version = ""
self.build_date = ""
#... |
asposebarcode/Aspose_BarCode_Cloud | Examples/Python/generating-saving/without-cloud-storage/generate-barcode-and-get-image-as-stream.py | Python | mit | 1,515 | 0.014521 | import asposebarcodecloud
from asposebarcodecloud.BarcodeApi import BarcodeApi
from asposebarcodecloud.BarcodeApi import ApiException
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open(r'../../data/config.properties'))
apiKey = config.get('AppConfig', 'api_key')
appSid = config.get(... | rcode Symbology
type = "datamatrix"
#Set Generated Barcode Image Format
format = "PNG"
try:
#invoke Aspose.BarCode Cloud SDK API to create barcode and get image stream
response = barcodeApi.GetBarcodeGenerate(text=text, type=type, format | =format)
if response.Status == "OK":
#download generated barcode from api response
outfilename = out_folder + name + "." + format
with open(outfilename, 'wb') as f:
for chunk in response.InputStream:
f.write(chunk)
... |
hujiajie/chromium-crosswalk | tools/telemetry/third_party/webpagereplay/third_party/dns/name.py | Python | bsd-3-clause | 21,899 | 0.002831 | # Copyright (C) 2001-2007, 2009, 2010 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... | text += '\\' + c
elif ord(c) > 0x20 and ord(c) < 0x7F:
text += c
else:
text += '\\%03d' % ord(c)
return text
def _validate_labels(labels):
"""Check for empty labels in the middle of a label sequence,
labels that are too long, and for too many labels.
@raises Nam... | el: a label is empty (i.e. the root label) and appears
in a position other than the end of the label sequence"""
l = len(labels)
total = 0
i = -1
j = 0
for label in labels:
ll = len(label)
total += ll + 1
if ll > 63:
raise LabelTooLong
if i < 0 and la... |
ivmech/iviny-scope | lib/xlsxwriter/test/comparison/test_set_start_page01.py | Python | gpl-3.0 | 1,929 | 0.001037 | ###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013, John McNamara, jmcnamara@cpan.org
#
import unittest
import os
from ...workbook import Workbook
from ..helperfunctions import _compare_xlsx_files
class TestCompareXLSXFiles(unittest.TestC... | rison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = ['xl/printerSettings/printerSettings1.bin',
'xl/worksheets/_rels/sheet1.xml.rels']
self.ignore_elements = {'[Content_Types]... | ""Test the creation of a simple XlsxWriter file with printer settings."""
filename = self.got_filename
####################################################
workbook = Workbook(filename)
worksheet = workbook.add_worksheet()
worksheet.set_start_page(1)
worksheet.set_pap... |
googleapis/python-monitoring-dashboards | scripts/fixup_dashboard_v1_keywords.py | Python | apache-2.0 | 6,186 | 0.00097 | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | '--output-directory',
required=True,
dest='output_dir',
help='the directory to output files fixed via un-flattening',
)
args = parser.parse_args()
input_dir = pathlib.Path(args.input_dir)
output_dir = pathlib.Path(args.output_dir)
| if not input_dir.is_dir():
print(
f"input directory '{input_dir}' does not exist or is not a directory",
file=sys.stderr,
)
sys.exit(-1)
if not output_dir.is_dir():
print(
f"output directory '{output_dir}' does not exist or is not a directory",
... |
bat-serjo/vivisect | vivisect/impemu/platarch/h8.py | Python | apache-2.0 | 464 | 0.002155 | import envi.archs.h8.emu as h8_emu
import envi.archs.h8.regs as h8_regs
import vivisect.i | mpemu.emulator as v_i_emulator
class H8WorkspaceEmulator(v_i_emulator.WorkspaceEmulator, h8_emu.H8Emulator):
taintregs = [h8_regs.REG_ER0, h8_regs.REG_ER1, h8_regs.REG_ER2]
def __init__(self, vw, logwrite=False, logread=False):
h8_emu.H8Emulator.__init__(self)
v_i_emulator.WorkspaceEmulator.... | ogread)
|
ods94065/opost | opost/settings.py | Python | mit | 6,192 | 0.00113 | # Django settings for opost project.
import os
import dj_database_url
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
('Opost Admin', 'ods94043@yahoo.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': dj_da... | lication'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'... | ib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.markup',
'django_extensions',
'postapi',
'postweb',
'rest_framework',
)
# A sample logging configuration. The only tangible logging
# performed by ... |
sysadmin75/ansible | test/lib/ansible_test/_internal/commands/integration/__init__.py | Python | gpl-3.0 | 36,116 | 0.003544 | """Ansible integration test infrastructure."""
from __future__ import annotations
| import contextlib
import datetime
import json
import os
import re
import shutil
import tempfile
import time
import typing as t
from ...encoding import (
| to_bytes,
)
from ...ansible_util import (
ansible_environment,
)
from ...executor import (
get_changes_filter,
AllTargetsSkipped,
Delegate,
ListTargets,
)
from ...python_requirements import (
install_requirements,
)
from ...ci import (
get_ci_provider,
)
from ...target import (
an... |
shoopio/shoop | shuup/core/utils/line_unit_mixin.py | Python | agpl-3.0 | 921 | 0 | # -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2017, Anders Innovations. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.core.exceptions import ObjectDoesNotExist
from shuup.core.... | tInterface(PiecesSalesUnit())
try:
shop_product = self.product.get_shop_instance(self.shop)
except ObjectDoesNotExist:
return UnitInterface(self. | product.sales_unit)
return shop_product.unit
|
bedubs/hkstairs | stairdb/admin.py | Python | gpl-3.0 | 1,433 | 0.020237 | from django.contrib import admin
from leaflet.admin import LeafletGeoAdmin
from models import Stair, Photo
from django.conf import settings
class OverrideLeafletGeoAdmin(LeafletGeoAdmin):
# straight hint @ https://github.com/makinacorpus/django-leaflet/pull/28#issuecomment-23943492
settings_overrides = {
... | 'attribution':'<a href="http://www.openstreetmap.org/copyright" target="_blank"> OpenStreetMap</a> contributors'
}),
],
'MINIMAP': False, # instantiate this later in the admin-map.js file to set basemap
}
class PhotoInline(admin.TabularInline):
model = Photo
ext... | = ['stairid','type','location']
inlines = [PhotoInline,]
ordering = ('stairid',)
class PhotoAdmin(OverrideLeafletGeoAdmin):
fields = ('image_tag','image','stairid','geom')
readonly_fields = ('image_tag',)
ordering = ('geom','stairid')
admin.site.register(Stair,StairAdmin)
admin.site.register(... |
yotchang4s/cafebabepy | src/main/python/idlelib/idle_test/test_debugger.py | Python | bsd-3-clause | 533 | 0.003752 | ''' Test idlelib.debugger.
Coverage: 19%
'''
from idlelib import debugger
from test.support import requires
requires('gui')
import unittest
from tkinter import Tk
class NameSpaceT | est(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.root = Tk()
cls.root.withdraw()
@classmethod
def tearDownClass(cls):
cls.root.destroy()
del cls.root
def test_init(self):
debugger.NamespaceViewer(self.root, 'Test')
if _ | _name__ == '__main__':
unittest.main(verbosity=2)
|
yankcrime/telegraf | scripts/build.py | Python | mit | 38,977 | 0.004413 | #!/usr/bin/python -u
import sys
import os
import subprocess
import time
from datetime import datetime
import shutil
import tempfile
import hashlib
import re
import logging
import argparse
################
#### Telegraf Variables
################
# Packaging variables
PACKAGE_NAME = "telegraf"
INSTALL_ROOT_DIR = "/us... | len(ver_list) != 3:
logging.warn("Could not determine how to increment version '{}', will just use provided version.".format(version))
return version
ver_list[1] = str(int(ver_list[1]) + 1)
ver_list[2] = str(0)
inc_version = '.'.join(ver_list)
logging.debug("Incremented version from '{}... |
def get_current_version_tag():
"""Retrieve the raw git version tag.
"""
version = run("git describe --always --tags --abbrev=0")
return version
def get_current_version():
"""Parse version information from git tag output.
"""
version_tag = get_current_version_tag()
# Remove leading 'v'
... |
bp-kelley/rdkit | Data/Pains/test_data/run_tests.py | Python | bsd-3-clause | 1,219 | 0.011485 | #
# Copyright (C) 2015 Greg Landrum
# This file is part of the RDKit.
# The contents are covered by the terms of the BSD license
# which is included in the file license.txt, found at the root
# of the RDKit source tree.
#
import unittest, os, csv
from rdkit import Chem, RDConfig
class TestCase(unittest.Test... | ine[2])
self.assertTrue(m is not None)
self.assertTrue(m.HasSubstructMatch(self.matchers[id_]))
| self.assertTrue(Chem.AddHs(m).HasSubstructMatch(self.matchers[id_]))
if __name__ == '__main__':
unittest.main()
|
cloudcopy/seahub | seahub/views/wiki.py | Python | apache-2.0 | 8,863 | 0.001805 | # -*- coding: utf-8 -*-
"""
File related views, including view_file, edit_file, view_history_file,
view_trash_file, view_snapshot_file
"""
import os
import hashlib
import json
import stat
import tempfile
import urllib
import urllib2
import chardet
from django.contrib.sites.models import Site, RequestSite
from django.... | ontent": index_content,
}, context_instance=RequestContext(request))
@login_required
@user_mods_check
def personal_wiki_pages(request):
"""
List personal wiki pages.
"""
try:
username = requ | est.user.username
repo = get_personal_wiki_repo(username)
pages = get_wiki_pages(repo)
except SearpcError:
return render_error(request, _('Internal Server Error'))
except WikiDoesNotExist:
return render_error(request, _('Wiki does not exists.'))
return render_to_response("wi... |
jmosky12/huxley | huxley/api/tests/test_user.py | Python | bsd-3-clause | 17,518 | 0.000228 | # Copyright (c) 2011-2014 Berkeley Model United Nations. All rights reserved.
# Use of this source code is governed by a BSD License (see LICENSE).
import json
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from huxley.accounts.models import User
f... | a user.'''
TestUsers.new_superuser(username='user2', password='user2')
self.client.login(username='user2', password='user2')
response = self.get_response(self.user.id)
self.assertEqual(response.status_code, 204)
self.assertFalse(User.obje | cts.filter(id=self.user.id).exists())
class UserDetailPatchTestCase(PartialUpdateAPITestCase):
url_name = 'api:user_detail'
params = {'first_name': 'first',
'last_name': 'last'}
def setUp(self):
self.user = TestUsers.new_user(username='user1', password='user1')
def test_anonymo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.