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 |
|---|---|---|---|---|---|---|---|---|
kishkaru/python-driver | tests/integration/long/test_ssl.py | Python | apache-2.0 | 10,956 | 0.003468 | # Copyright 2013-2016 DataStax, 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 writi... | _hostname specified
@test_category connection:ssl
"""
# find absolute path to client CA_CERTS
abs_path_ca_cert_path = os.path.abspath(CLIENT_CA_CERTS)
ssl_options = {'ca_certs': abs_path_ca_cert_path,
'ssl_vers | ion': ssl.PROTOCOL_TLSv1,
'cert_reqs': ssl.CERT_REQUIRED,
'check_hostname': True}
validate_ssl_options(ssl_options=ssl_options)
class SSLConnectionAuthTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
setup_cluster_ssl(client_auth=True)... |
lneuhaus/pyrpl | pyrpl/widgets/module_widgets/na_widget.py | Python | gpl-3.0 | 15,889 | 0.004217 | """
The network analyzer records the coherent response of the signal at the port
:code:`input` to a sinusoidal excitation of variable frequency sent to the
output selected in :code:`output_direct`.
.. note:: If :code:`output_direct='off'`, another module's input can be set
to :code:`networkanalyzer` to test ... |
decrease :code:`rbw` if the communication time between the Red Pitaya and
the client computer limits the acquisition speed.
* :att | r:`~pyrpl.software_modules.network_analyzer.NetworkAnalyzer.acbandwidth`
is the cutoff frequency of a high-pass filter applied to the input before
demodulation. A setting of zero disables the high-pass filter.
* :attr:`~pyrpl.software_modules.network_analyzer.NetworkAnalyzer.logscale`
enables the use of a logarit... |
venthur/pyff | src/lib/P300VisualElement/TestIt.py | Python | gpl-2.0 | 1,957 | 0.005621 | # TestIt.py
# Copyright (C) 2009 Matthias Treder
#
# 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 ... | 1:
screen.blit(background, [0, 0])
screen.blit(e.image, e.rect)
pygame.display.flip()
e.update()
pygame.time.delay(400)
e.highlight = [pos]
e.refresh()
pos = (pos + 1) % len(text)
for event in pygame.event.get():
if event.type in (pygame.KEYDOWN, pygame.MOUSEBUTTONDOWN):
... | k
|
lexdene/sniper-jinja | setup.py | Python | gpl-3.0 | 1,172 | 0 | from setuptools import setup
with open('README.rst') as f:
LONG_DESCRIPTION = f.rea | d()
with open('pip-req.d/install.txt') as f:
install_requires = []
for line in f:
if '#' in line:
# remove comment
line = line[:line.index('#')]
line = line.strip()
if line:
install_requires.append(line)
print(install_requires)
setup(
na... | .2",
description="a jinja2 plugin for sniper",
long_description=LONG_DESCRIPTION,
url="https://github.com/lexdene/sniper-jinja",
license='GPLv3',
author="Elephant Liu",
author_email="[email protected]",
packages=['sniper_jinja'],
platforms=['any'],
install_requires=install_requires,
... |
lionleaf/dwitter | dwitter/templatetags/insert_magic_links.py | Python | apache-2.0 | 2,048 | 0.003418 | import re
from django import template
register = template.Library()
def user_dweet_to_link(m):
text = m.group('text')
dweet_id = m.group('dweet_id')
username = m.group('username')
if username is None:
url = 'd/' + dweet_id
else:
url = 'u/' + username
result = '<a href="/{0}"... | text = re.sub(
r'(?:^|(?<=\s))' # start of string or whitespace
r'/?' # optional /
r'(?P<text>' # capture original pattern
r'[^a-zA-Z\d]?d/(?P<dweet_id>... | # or
r'[^a-zA-Z\d]?u/(?P<username>[\w.@+-]+)[^a-zA-Z\d]?)' # user reference
r'(?=$|\s|#)', # end of string, whitespace or hashtag
user_dweet_to_link,
text
)
text = re.sub(
r'(?P<text>' ... |
ray-project/ray | python/ray/tune/suggest/_mock.py | Python | apache-2.0 | 1,752 | 0 | from typing import Dict, List, Optional
from ray.tune.suggest.suggestion import Searcher, ConcurrencyLimiter
from ray.tune.suggest.search_generator import SearchGenerator
from ray.tune.trial import Trial
class _MockSearcher(Searcher):
def __init__(self, **kwargs):
self.live_trials = {}
self.count... | iable": 2}
return None
def on_trial_result(self, trial_id: str, result: Dict):
self.counter["result"] += 1
self.results += [result]
def on_trial_complete(
self, trial_id: str, result: Optional[Dict] = None, error: bool = False
):
self.counter["complete"] += 1
... | def _process_result(self, result: Dict):
self.final_results += [result]
class _MockSuggestionAlgorithm(SearchGenerator):
def __init__(self, max_concurrent: Optional[int] = None, **kwargs):
self.searcher = _MockSearcher(**kwargs)
if max_concurrent:
self.searcher = Concurrency... |
bufferx/stormed-amqp | stormed/method/codegen/queue.py | Python | mit | 3,261 | 0.028212 |
from stormed.util import WithFields
class Declare(WithFields):
_name = "queue.declare"
_class_id = 50
_method_id = 10
_sync = True
_content = False
_fields = [
('ticket' , 'short'),
('queue' , 'shortstr'),
('passive' , '... | ueue.bind-ok"
_class_id = 50
_method_id = 21
| _sync = False
_content = False
_fields = [
]
class Purge(WithFields):
_name = "queue.purge"
_class_id = 50
_method_id = 30
_sync = True
_content = False
_fields = [
('ticket' , 'short'),
('queue' , 'shortstr'),
... |
meteorfox/PerfKitBenchmarker | perfkitbenchmarker/linux_benchmarks/hpcc_benchmark.py | Python | apache-2.0 | 7,898 | 0.00899 | # Copyright 2014 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | las.net/
HPL also requires a MPI (Message Passing Interface) Library
OpenMPI: http://www.open-mpi.org/
MPI needs to be configured:
Configuring MPI:
http://techtinkering.com/2009/12/02/setting-up-a-beowulf-cluster-using-open-mpi-on-linux/
Once HPL is built the configuration file must be created:
Configuring HPL.dat:
... | t-file.html
http://www.netlib.org/benchmark/hpl/faqs.html
"""
import logging
import math
import re
from perfkitbenchmarker import configs
from perfkitbenchmarker import data
from perfkitbenchmarker import flags
from perfkitbenchmarker import regex_util
from perfkitbenchmarker import sample
from perfkitbenchmarker imp... |
mathiasertl/django-ca | ca/django_ca/acme/messages.py | Python | gpl-3.0 | 2,539 | 0.005908 | # This file is part of django-ca (https://github.com/mathiasertl/django-ca).
#
# django-ca 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, eith | er version 3 of the License, or (at your
# option) any later version.
#
# django-ca 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 shou... | o-ca. If not, see
# <http://www.gnu.org/licenses/>.
"""Specialized variants of ACME message classes."""
import josepy as jose
from acme import fields
from acme import messages
identifiers_decoder = messages.Order._fields["identifiers"].fdec # pylint: disable=no-member; false positive
class Order(messages.Order):
... |
RegulatoryGenomicsUPF/pyicoteo | utest/testUtils.py | Python | gpl-3.0 | 566 | 0.012367 | import unittest
from pyicoteolib.utils import DualSortedReader
from pyicoteolib.core impo | rt BED
class TestUtils(unittest.TestCase):
def test_dual_reader(self):
reader = DualSortedReader("test_files/mini_sorted.bed", "test_files/mini_sorted2.bed", BED, False, False)
merged_file = open("test_files/mini_sorted_merged.bed")
for line in reader:
if line:
... |
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(TestUtils))
return suite
|
engdan77/edoAutoHomeMobile | twisted/lore/test/test_lore.py | Python | mit | 42,212 | 0.002203 | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
# ++ single anchor added to individual output file
# ++ two anchors added to individual output file
# ++ anchors added to individual output files
# ++ entry added to index
# ++ index entry pointing to correct file and anchor
# ++ multiple entries ... | .reset()
def testProcessingFunctionFactory(self):
base = FilePath(self.mktemp() | )
base.makedirs()
simple = base.child('simple.html')
FilePath(__file__).sibling('simple.html').copyTo(simple)
htmlGenerator = factory.generate_html(options)
htmlGenerator(simple.path, self.linkrel)
self.assertXMLEqual(
"""\
<?xml version="1.0" ?><!DOCTYPE h... |
openstates/openstates.org | dashboards/urls.py | Python | mit | 685 | 0.00292 | from django.urls import path, re_path
from .views import (
user_overview,
api_overvi | ew,
dq_overview,
dq_overview_session,
dqr_listing,
)
from utils.common import states
# Only allow valid state abbreviations
state_abbrs = [s.abbr.lower() for s in states]
state_abbr_pattern = r"({})".format("|".join(state_abbrs))
urlpatterns = [
path("users/", user_overview),
| path("api/", api_overview),
path("dq_dashboard/", dqr_listing),
re_path(r"^dq_overview/(?P<state>{})/$".format(state_abbr_pattern), dq_overview),
re_path(
r"^dq_overview/(?P<state>{})/(?P<session>[-\w ]+)/$".format(state_abbr_pattern),
dq_overview_session,
),
]
|
hazelnusse/sympy-old | sympy/core/numbers.py | Python | bsd-3-clause | 44,106 | 0.004285 | from basic import Atom, SingletonMeta, S, Basic
from decorators import _sympifyit
from cac | he import Memoizer, MemoizerArg
import sympy.mpmath as mpmath
import sympy.mpmath.libmpf as mlib
import sympy.mpmath.libm | pc as mlibc
from sympy.mpmath.libelefun import mpf_pow, mpf_pi, mpf_e, phi_fixed
import decimal
rnd = mlib.round_nearest
# TODO: we should use the warnings module
_errdict = {"divide": False}
def seterr(divide=False):
"""
Should sympy raise an exception on 0/0 or return a nan?
divide == True .... raise ... |
freedomtan/tensorflow | tensorflow/python/framework/sparse_tensor.py | Python | apache-2.0 | 17,827 | 0.005441 | # 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... | dated values.
Example usage:
>>> st = tf.sparse.from_dense([[1, 0, 2, 0], [3, 0, 0, 4]])
>>> tf.sparse.to_dense(st.with_values([10, 20, 30, 40])) # 4 nonzero values
<tf.Tensor: shape=(2, 4), dtype=int32, numpy=
array([[10, 0, 20, 0],
[30, 0, 0, 40]], dtype=int32)>
"""
retu... | lf):
"""The `Operation` that produces `values` as an output."""
return self._values.op
@property
def dtype(self):
"""The `DType` of elements in this tensor."""
return self._values.dtype
@property
def dense_shape(self):
"""A 1-D Tensor of int64 representing the shape of the dense tensor."""... |
rockdreamer/redmine-docs-to-drive | model.py | Python | mit | 12,096 | 0.003142 | # coding: utf-8
from sqlalchemy import Column, DateTime, Index, Integer, String, Text, text, \
ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
class RedmineToDriveMapping(Base):
__tablename_... | rgs__ = {'polymorphic_identity': 'project_dmsf'}
class RedmineDocumentToDriveMapping(RedmineToDriveMapping):
__mapper_args__ = {'polymorphic_identity': 'document'}
class RedmineDocumentAttachmentToDriveMapping(RedmineToDriveMapping):
__mapper_args__ = {'polymorphic_identity': 'document_attachment'}
class ... | chments'
id = Column(Integer, primary_key=True)
container_type = Column(String(30))
container_id = Column(Integer)
filename = Column(String(255), nullable=False, server_default=text("''"))
disk_filename = Column(String(255), nullable=False, server_default=text("''"))
filesize = Column(Integer, ... |
fake-name/ReadableWebProxy | WebMirror/management/rss_parser_funcs/feed_parse_extractGhosttouchWordpressCom.py | Python | bsd-3-clause | 560 | 0.033929 |
def extractGhosttouchWordpressCom(item):
'''
Parser for 'ghosttouch.wordpress.com'
''' |
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
... | pe)
return False
|
sethshill/final | build/lib.linux-armv7l-2.7/bibliopixel/log.py | Python | mit | 1,041 | 0.000961 | import logging, sys
from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL
class InfoFilter(logging.Filter):
def filter(self, rec):
return rec.levelno in (logging.DEBUG, logging.INFO)
def _new_custom_logger(name='BiblioPixel',
fmt='%(levelname)s - %(module)s - %(message)s'):
... | 2.setFormatter(formatter)
logger.addHandler(h1)
logger.addHandler(h2)
return logger
logger = _new_custom_logger()
setLogLevel = logger.set | Level
debug, info, warning, error, critical, exception = (
logger.debug, logger.info, logger.warning, logger.error, logger.critical,
logger.exception)
|
ClearCorp/odoo-costa-rica | TODO-9.0/l10n_cr_account_trial_balance_currency_report/__openerp__.py | Python | agpl-3.0 | 2,013 | 0.002981 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Addons modules by CLEARCORP S.A.
# Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>).
#
# This program is free software: you can redistribute... | ARRANTY; without even the imp | lied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
######################... |
leifos/pagefetch | pagefetch_project/pagefetch/game_leaderboards.py | Python | mit | 5,894 | 0.005769 | __author__ = 'leif'
from game_models import HighScore, UserProfile
from ifind.common.utils import encode_string_to_url
from django.contrib.auth.models import User
from django.db.models import Max, Sum, Avg
# ranking based on highest total score (top x players)
# ranking of players based on level/xp
# top players in ... |
for i, hs in enumerate(highscores):
username = User.objects.get(id=hs['user'])
entry = {'rank': i+1, 'username': username, 'score': hs['highest_score']}
leaders.append(entry)
return leaders
def __str__(self):
return 'Highest Overall Scores'
... | UserProfile.objects.all()
schools = {}
score_list=[]
for user in users:
if user.school != "":
if user.school not in schools:
user_score = self._get_user_score_sum(user)
#list is [total_score_of_users,num_of_users]
... |
yandex/mastermind | src/python-mastermind/src/mastermind/errors.py | Python | gpl-2.0 | 508 | 0.003937 | class MastermindError(Exception) | :
@property
def code(self):
return MASTERMIND_ERROR_CODES[type(self)]
@staticmethod
def make_error(code, msg):
if code not in MASTERMIND_ERROR_CLS:
raise ValueError('Unknown error code {}'.format(code | ))
return MASTERMIND_ERROR_CLS[code](msg)
GENERAL_ERROR_CODE = 1024
MASTERMIND_ERROR_CODES = {
MastermindError: GENERAL_ERROR_CODE
}
MASTERMIND_ERROR_CLS = dict((v, k) for k, v in MASTERMIND_ERROR_CODES.iteritems())
|
bqbn/addons-server | src/olympia/promoted/migrations/0001_initial.py | Python | bsd-3-clause | 2,466 | 0.004461 | # Generated by Django 2.2.14 on 2020-07-09 10:37
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import olympia.amo.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('versions', '0008_auto_20200625_1114'),
(... | ialize=False, verbose_name='ID')),
('created', models.DateTimeField(blank=True, default=django.utils.timezone.now, editable=False)),
('modified', models.DateTimeField(auto_no | w=True)),
('group_id', models.SmallIntegerField(choices=[(1, 'Recommended'), (2, 'Verified - Tier 1'), (3, 'Verified - Tier 2'), (4, 'Line'), (5, 'Spotlight'), (6, 'Strategic')], null=True)),
('version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='promote... |
banesullivan/ParaViewGeophysics | examples/filters-general/normalize-array.py | Python | bsd-3-clause | 1,235 | 0 | """
Normalize Array
~~~~~~~~~~~~~~~
This example will demonstrate how to perform a normalization or any custom
mathematical operation on a single data array for an input data set.
This filter allow the user to select an array from the input data set to be
normalized. The filter will append another array to that data ... | sta import examples
import PVGeo
from PVGeo.filters import NormalizeArray
###############################################################################
# Create some input data. this can | be any `vtkDataObject`
mesh = examples.load_uniform()
title = 'Spatial Point Data'
mesh.plot(scalars=title)
###############################################################################
# Apply the filter
f = NormalizeArray(normalization='feature_scale', new_name='foo')
output = f.apply(mesh, title)
print(output)
... |
lukecwik/incubator-beam | sdks/python/apache_beam/examples/dataframe/wordcount_test.py | Python | apache-2.0 | 2,150 | 0.005581 | # -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "L... | rom apache_beam.examples.dataframe import wordcount
from apache_beam.testing.util import open_shards
class WordCountTest(unittest.TestCase):
SAMPLE_TEXT = """
a
a b
a b c
loooooonger words
"""
def create_temp_file(self, contents):
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(... | return f.name
def test_basics(self):
temp_path = self.create_temp_file(self.SAMPLE_TEXT)
expected_words = collections.defaultdict(int)
for word in re.findall(r'[\w]+', self.SAMPLE_TEXT):
expected_words[word] += 1
wordcount.run(['--input=%s*' % temp_path, '--output=%s.result' % temp_path])... |
mkhl/haskell.sugar | setup.py | Python | mit | 1,606 | 0.056145 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup
import py2app
import os, glob
def data_files(dirname = 'xml'):
"""Figure out the sugar structure and massage it into data_files format."""
def data_file(component):
return (os.path.join('..', '..', component),
glob.glob(os.pa... | tions',
])
for subdir in dirs.intersection(set(os.listdir(dirname))):
result.append(data_file(subdir))
return result
def sources(dirname):
"""Find (re)source files for our bundle and massage them into data_files format."""
return glob.glob(os.path. | join(dirname, '*'))
setup(
name = 'Haskell',
version = '0.0',
author = u'Martin Kühl',
author_email = '[email protected]',
url = 'http://github.com/mkhl/haskell.sugar',
description = 'A Sugar adding sweet Haskell support for Espresso',
data_files = sources('res') + data_files('xml'),
plugin = sources('src... |
fuhaha/tensorflow_study | docs/chapter6/distributed_mnist.py | Python | apache-2.0 | 4,760 | 0.004915 | import math
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# Flags for defining the tf.train.ClusterSpec
tf.app.flags.DEFINE_string("ps_hosts", "",
"Comma-separated list of hostname:port pairs")
tf.app.flags.DEFINE_string("worker_hosts", "",
... | saver=saver,
global_step=global_step,
save_model_secs=600)
mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
# The supervisor takes care of session initialization, restoring from
# a checkpoint, and closing when done or an... | # Loop until the supervisor shuts down or 1000000 steps have completed.
step = 0
while not sv.should_stop() and step < 1000000:
# Run a training step asynchronously.
# See `tf.train.SyncReplicasOptimizer` for additional details on how to
# perform *synchronous* training.
ba... |
tensorflow/tfx | tfx/components/base/base_driver.py | Python | apache-2.0 | 999 | 0.001001 | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in com | pliance 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, softwar | e
# 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.
"""Stub for pre-rename `tfx.dsl.components.base.base_driver`."""
from t... |
pombredanne/func | test/unittest/test_func_transmit.py | Python | gpl-2.0 | 8,415 | 0.010458 | #!/usr/bin/python
##
## Copyright 2008, Various
## Adrian Likins <[email protected]>
##
## This software may be freely redistributed under the terms of the GNU
## general public license.
##
import os
import socket
import subprocess
import time
import unittest
import simplejson
import func.utils
from func import y... | ).__init__()
#class TestListMinionJSONAsync(JSONBaseTest, ListMinionAsync):
# json = True
# async = True
# def __init__(self):
# super(TestListMinionJSONAsync, self).__init__()
class ClientGlob(objec | t):
def _test_add(self, client):
result = self.call({'clients': client,
'method': 'add',
'module': 'test',
'parameters': [1,2]})
self.assert_on_fault(result)
return result
def test_single_client(self... |
weaver-viii/subuser | logic/subuserlib/classes/gitRepository.py | Python | lgpl-3.0 | 6,303 | 0.013803 | #!/usr/bin/env python
# This file should be compatible with both Python 2 and 3.
# If it is not, please file a bug report.
"""
This is a Class which allows one to manipulate a git repository.
"""
#external imports
import os
import tempfile
#internal imports
import subuserlib.subprocessExtras as subprocessExtras
from ... | ras
>>> subuserlib.subprocessExtras.call(["git","init"],cwd="/home/travis/hashtest")
0
>>> subuserlib.subprocessExtras.call(["git","add","."],cwd="/home/travis/hashtest")
0
>>> subuserlib.subprocessExtras.call(["git","commit","-m","Initial commit"],cwd="/home/travis/hashtest")
0
"""
self... | sTree(self, subfolder, extraArgs=[]):
"""
Returns a list of tuples of the form:
(mode,type,hash,path)
Coresponding to the items found in the subfolder.
"""
if not subfolder.endswith("/"):
subfolder += "/"
if subfolder == "/":
subfolder = "./"
(returncode,output) = self.getRe... |
wasit7/tutorials | django/Pieng/myclass/myquiz/models.py | Python | mit | 647 | 0.034003 | from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Questions(models.Model):
# Fields
CHOICES = (
('a', 'a.'),('b', 'b.'),('c', 'c.'),('d', 'd.'),
| )
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
question = models.TextField(max_length=100)
a = models.CharField(max_length=30)
b = models.CharField(max_length=30)
c = models.CharField(max_length=30)
d = models.CharField(max_... | lf):
return u'%s' % self.question |
neo1691/subliminal | subliminal/subtitle.py | Python | mit | 8,191 | 0.001953 | # -*- coding: utf-8 -*-
import codecs
import logging
import os
import chardet
import pysrt
from .video import Episode, Movie
from .utils import sanitize, sanitize_release_group
logger = logging.getLogger(__name__)
#: Subtitle extensions
SUBTITLE_EXTENSIONS = ('.srt', '.sub', '.smi', '.txt', '.ssa', '.ass', '.mpl')... | ith.
:type video: :class:`~subliminal.video.Video`
:return: matches of the subtitle.
:rtype: set
"""
raise NotImplementedError
def __hash__(self):
return hash(self.provider_name + '-' + self.id)
def __repr__(self):
return '<%s %r [%s]>' % (self.__class_... | deo_path` and `language`.
:param str video_path: path to the video.
:param language: language of the subtitle to put in the path.
:type language: :class:`~babelfish.language.Language`
:param str extension: extension of the subtitle.
:return: path of the subtitle.
:rtype: str
"""
subtit... |
cloudify-cosmo/cloudify-manager | tests/integration_tests_plugins/mock_labels/setup.py | Python | apache-2.0 | 99 | 0 | from setuptools impo | rt setup
setup(name='mock_labels', version='0.0.1', packages=['mo | ck_labels'])
|
Juniper/neutron | neutron/tests/unit/ml2/drivers/cisco/nexus/test_cisco_mech.py | Python | apache-2.0 | 24,807 | 0.000322 | # Copyright (c) 2012 Open | Stack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this f | ile 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 KIN... |
beeva-fernandocerezal/rasa_nlu | rasa_nlu/__init__.py | Python | apache-2.0 | 297 | 0 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import rasa_nlu.version
logging.getLogge | r(__name__).addHandler(logging.NullHandler())
__version__ = rasa_nlu.version.__version__
| |
openstack/neutron-vpnaas | neutron_vpnaas/services/vpn/service_drivers/driver_validator.py | Python | apache-2.0 | 1,000 | 0 | # Copyright 2017 Eayun, 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... | , either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
class VpnDriverValidator( | object):
"""Driver-specific validation routines for VPN resources."""
def __init__(self, driver):
self.driver = driver
@property
def l3_plugin(self):
return self.driver.l3_plugin
def validate_ipsec_site_connection(self, context, ipsec_sitecon):
"""Driver can override this ... |
artus40/maraudes_project | notes/forms.py | Python | gpl-3.0 | 2,575 | 0.001554 | import datetime
from .models import Note, Sujet
from utilisateurs.models import Professionnel
from django import forms
from django_select2.forms import Select2Widget
# NOTES
class NoteForm(forms.ModelForm):
""" Generic Note form """
class Meta:
model = Note
fields = ['sujet', 'text', 'create... | {
'sujet': Select2Widget(),
'text': forms.Textarea(
attrs={'rows': 4}
),
| }
class SimpleNoteForm(forms.ModelForm):
""" Simple note with only 'sujet' and 'text' fields.
Usefull with children of 'Note' that defines all 'note_*'
special methods.
"""
class Meta(NoteForm.Meta):
fields = ['sujet', 'text']
class UserNoteForm(NoteForm):
""" Form that ... |
appop/bitcoin | src/test/bctest.py | Python | mit | 4,554 | 0.005051 | # Copyright 2014 BitPay Inc.
# Copyright 2016 The nealcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from __future__ import division,print_function,unicode_literals
import subprocess
import os
import json
impo... | y:
outputData = open(testDir + "/" + outputFn).read()
except:
logging.error("Output file " + outputFn + " can not be opened")
raise
if not outputData:
logging.error("Output data missing for " + outputFn)
raise Exception
# Run the test
... | = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE,universal_newlines=True)
try:
outs = proc.communicate(input=inputData)
except OSError:
logging.error("OSError, Failed to execute " + execprog)
raise
if outputData:
# Parse command out... |
maka-io/ooi-ui | ooiui/core/app/__init__.py | Python | mit | 651 | 0.003072 |
#!/usr/bin/env python
'''
ooiui.core.app.science
Defines the application for the Science UI
'''
import os
from flask import Flask
f | rom flask.ext.cache import Cache
from flask_environments import Environments
app = Flask(__name__, static_url_path='', template_folder='../../templates', stati | c_folder='../../static')
env = Environments(app, default_env='DEVELOPMENT')
basedir = 'ooiui/config'
if os.path.exists(os.path.join(basedir, 'config_local.yml')):
env.from_yaml(os.path.join(basedir, 'config_local.yml'))
else:
env.from_yaml(os.path.join(basedir, 'config.yml'))
cache = Cache(app, config={'CA... |
jtconnor/mec2 | setup.py | Python | gpl-2.0 | 3,761 | 0 | """A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.absp... | 'test': ['coverage'],
# },
# If there are data files included in your packages that need to be
# installe | d, specify them here. If using Python 2.6 or less, then these
# have to be included in MANIFEST.in as well.
# package_data={
# 'sample': ['package_data.dat'],
# },
# Although 'package_data' is the preferred approach, in some case you may
# need to place data files outside of your packages.... |
qstokkink/py-ipv8 | ipv8/attestation/wallet/irmaexact/__init__.py | Python | lgpl-3.0 | 360 | 0.002778 | from __future__ import division
import os
from functools import reduce
def secure_randint(bitspace):
delbits = 8 - (bitspac | e % 8)
bytez = os.urandom(bitspace // 8)
if delbits > 0:
b = (os.urandom(1)[0] & (0xFF >> delbits)).to_bytes(1, 'big', signed=False)
bytez = b + bytez
return reduce(lambda a, b: (a << 8) + b, bytez, | 0)
|
ChristophKirst/ClearMap | docs/build/latex/imageanalysis-7.py | Python | gpl-3.0 | 749 | 0.045394 | import os
import ClearMap.Settings as settings
filename = os.path.join(settings.ClearMapPath, 'Test/Data/ImageAnaly | sis/cfos-substack.tif');
import ClearMap.Visualization.Plot as plt
import ClearMap.IO as io
data = io.readData(filename, z = (0,26));
import ClearMap.ImageProcessing.BackgroundRemoval as bgr
dataBGR = bgr.removeBackground(data.astype('float'), size=(3,3), verbose = True);
from ClearMap.ImageProc | essing.Filter.DoGFilter import filterDoG
dataDoG = filterDoG(dataBGR, size=(8,8,4), verbose = True);
from ClearMap.ImageProcessing.MaximaDetection import findExtendedMaxima
dataMax = findExtendedMaxima(dataDoG, hMax = None, verbose = True, threshold = 10);
plt.plotOverlayLabel(dataDoG / dataDoG.max(), dataMax.astype('i... |
AnzenSolutions/ASWCP-Web | plugins/handlers/forgotpassword/forgotpassword.py | Python | mpl-2.0 | 1,694 | 0.008855 | from plugins.bases.handlers import HandlersBase
class forgotpassword(HandlersBase):
WEB_PATH = r"/forgotpassword"
STORE_ATTRS = True
STORE_UNREF = True
OPTS = {}
PAGE_TITLE = "Reset Password"
CSS_FILES = ["forgotpassword"]
def get(self):
self.show("forgotpassword", ac... | self.show("forgotpassword", msg_type="error", msg="Issue updating account's pa | ssword. Please try again.")
else:
self.show("forgotpassword", msg_type="error", msg="Passwords did not match or where left empty. Please try again.")
else:
self.show("forgotpassword", msg_type="error", msg="Unknown action requested.")
|
DK-Git/script.mdm166a | resources/lib/extraicons.py | Python | gpl-2.0 | 2,739 | 0.004016 | '''
XBMC LCDproc addon
Copyright (C) 2012 Team XBMC
Extra icon defines/enums
Copyright (C) 2012 Daniel 'herrnst' Scheller
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Soft... | tion; 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 Lic... | ic License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
#... |
Vvucinic/Wander | venv_2_7/lib/python2.7/site-packages/IPython/core/usage.py | Python | artistic-2.0 | 23,364 | 0.001198 | # -*- coding: utf-8 -*-
"""Usage information for the main IPython applications.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
# Copyright (C) 2001-2007 Fernando Perez. <[email protected]>
#
# Distributed under the terms of... | n
co | ntain special IPython syntax (magic commands, shell expansions, etc.).
Almost all configuration in IPython is available via the command-line. Do
`ipython --help-all` to see all available options. For persistent
configuration, look into your `ipython_config.py` configuration file for
details.
This... |
xuru/pyvisdk | pyvisdk/enums/perf_format.py | Python | mit | 209 | 0 |
######################################## |
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
PerfFormat = Enum(
' | csv',
'normal',
)
|
tsl143/addons-server | src/olympia/landfill/translations.py | Python | bsd-3-clause | 364 | 0 | # -* | - coding: utf-8 -*-
def generate_translations(item):
"""Generate French and Spanish translations for the given `item`."""
fr_prefix = u'(français) '
es_prefix = u'(español) '
oldname = unicode(item.name)
item.name = {'en': oldname,
'fr': fr_prefix + oldname,
'es':... | tem.save()
|
12AngryMen/votca-scripts | lib/Carlstuff/ctp/cube2xyz.py | Python | apache-2.0 | 3,451 | 0.066068 | from __future__ import division
import numpy as np
import sys as sys
class Atom(object):
def __init__(self, Z, pos):
self.Z = Z
self.pos = pos
self.VdW = 8 # a.u.
def DistFrom(self, pos):
return np.dot(self.pos - pos, self.pos - pos)**0.5
class ScalarField(object):
def __init__(self, atoms, scala... | == 6:
Nz = int(ln[0])
Cz = np.array( [float(ln[1]), float(ln[2]), float(ln[3])] )
# Atom line
elif len(ln) == 5:
Z = int(ln[0])
pos = np.array( [float(ln[2]), float(ln[3]), float(ln[4])] )
atoms.append( Atom(Z,pos) )
# Scalar-field line
else:
for item in ln:
item = float(item)
... | eld = np.array(scalarfield)
print ":", len(scalarfield), "grid points."
print "... Atoms ", len(atoms)
print "... Voxel numbers ", Nx, Ny, Nz, " TOTAL ", Nx*Ny*Nz
print "... Cube origin, axes ", C0, Cx, Cy, Cz
return ScalarField(atoms, scalarfield, C0, Cx, Cy, Cz, Nx, Ny, Nz)
field = Ar... |
TeamEOS/external_chromium_org | chrome/common/extensions/docs/server2/document_renderer.py | Python | bsd-3-clause | 4,116 | 0.003158 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import os
from document_parser import ParseDocument
from third_party.json_schema_compiler.model import UnixName
class DocumentRenderer(objec... | .append('<a href=%s>%s</a>' % (ref_dict['href'],
ref_dict['text']))
cursor_index = end_ref_index + 1
start_ref_index = document.find(START_REF, cursor_index)
new_document.append(document[cursor_index:])
return ''.join(new_document)
def Render(... | , render_title=False):
# Render links first so that parsing and later replacements aren't
# affected by $(ref...) substitutions
document = self._RenderLinks(document, path)
parsed_document = ParseDocument(document, expect_title=render_title)
toc_text, toc_warnings = self._table_of_contents_renderer... |
chmouel/python-swiftclient | swiftclient/openstack/common/setup.py | Python | apache-2.0 | 12,438 | 0.000241 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 OpenStack LLC.
# 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/... | uirements.txt", "w") as req_file:
output = subprocess.Popen(["pip", "-E", venv, "freeze", "-l"],
stdout=subprocess.PIPE)
requirements = output.communicate()[0].strip()
req_file.write(requirements)
def _run_shell_command(cmd):
output = subpr... | stdout=subprocess.PIPE)
out = output.communicate()
if len(out) == 0:
return None
if len(out[0].strip()) == 0:
return None
return out[0].strip()
def _get_git_next_version_suffix(branch_name):
datestamp = datetime.datetime.now().strftime('%Y%m%d')
if br... |
z-uo/imagemash | plugins/plugin_rotate.py | Python | gpl-3.0 | 11,247 | 0.003379 | #!/usr/bin/python3
#-*- coding: utf-8 -*-
#
#Copyright pops ([email protected]), 2010-2011
#
#This file is part of imagemash.
#
# imagemash 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 versi... | #######
if images:
self.im_changed(self.images[0])
### connexion ##################################################
self.imW.activated[str].connect(self.im_changed)
self.rotate90W.clicked.connect(self.rot90)
self.rotate180W.clicked.connect(self.r | ot180)
self.rotate270W.clicked.connect(self.rot270)
self.colorW.clicked.connect(self.color_clicked)
self.actionW.activated[str].connect(self.action_changed)
self.degreW.textChanged.connect(self.degre_changed)
self.apercuW.clicked.connect(self.apercu_clicked)
self.resetW.... |
Boussadia/weboob | modules/creditcooperatif/backend.py | Python | agpl-3.0 | 2,921 | 0.001713 | # -*- coding: utf-8 -*-
# Copyright(C) 2012 Kevin Pouget
#
# This file is part of weboob.
#
# weboob 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 Free Software Foundation, either version 3 of the License, or
# (at your optio... | eboob.capabilities.bank import ICapBank, AccountNotFound
from weboob.tools.backend import BaseBackend, BackendConfig
from weboob.tools.value import ValueBackendPassword, Value
from .perso | .browser import CreditCooperatif as CreditCooperatifPerso
from .pro.browser import CreditCooperatif as CreditCooperatifPro
__all__ = ['CreditCooperatifBackend']
class CreditCooperatifBackend(BaseBackend, ICapBank):
NAME = 'creditcooperatif'
MAINTAINER = u'Kevin Pouget'
EMAIL = '[email protected]'
... |
HyperloopTeam/FullOpenMDAO | lib/python2.7/site-packages/openmdao.lib-0.13.0-py2.7.egg/openmdao/lib/drivers/test/test_opt_conmin.py | Python | gpl-2.0 | 27,188 | 0.001802 | """
Test the CONMIN optimizer component
"""
import unittest
import numpy
# pylint: disable=F0401,E0611
from openmdao.main.api import Assembly, Component, VariableTree, set_as_top, Driver
from openmdao.main.datatypes.api import Float, Array, Str, VarTree
from openmdao.lib.casehandlers.api import ListCaseRecorder
from ... | ective('10*comp.result')
# pylint: disable=C0301
| map(self.top.driver.add_parameter,
['comp.x[0]', 'comp.x[1]', 'comp.x[2]', 'comp.x[3]'])
map(self.top.driver.add_constraint, [
'comp.x[0]**2+comp.x[0]+comp.x[1]**2-comp.x[1]+comp.x[2]**2+comp.x[2]+comp.x[3]**2-comp.x[3] < 8',
'comp.x[0]**2-comp.x[0]+2*comp.x[1]**2+comp.x[... |
vecnet/simulation-manager | sim_manager/tests/constants.py | Python | mpl-2.0 | 649 | 0.001541 | # This file is part of the Simulation Manager project for VecNet.
# For copyright and licensing information about this project, see the
# NOTICE.txt and LICENSE.md files in its top-level directory; they are
# ava | ilable at https://github.com/vecnet/simulation-manager
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License (MPL), version 2.0. If a copy of the MPL was not distributed
# with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
from path import path
# Root directory for tests th... | utput files
TEST_OUTPUT_ROOT = path(__file__).dirname() / 'output'
|
joshsamara/game-website | core/views/base.py | Python | mit | 691 | 0 | """Base views and view utilities."""
from django.views.generic import View
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
class Login | RequiredMixin(object):
"""Ensu | res that user must be authenticated in order to access view."""
@classmethod
def as_view(cls, **initkwargs):
"""Make views that inherit this require login."""
view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
return login_required(view)
class Home(View):
"""Default inde... |
pmisik/buildbot | master/buildbot/scripts/sendchange.py | Python | gpl-2.0 | 2,058 | 0.000486 | # This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... | perties,
repository=repository, vc=vc, project=project, revlink=revlink,
codebase=codebase)
except Exception:
print("change not sent:")
traceback.print_exc(file=sys.stdout)
return 1
else:
print("change sent successfully | ")
return 0
|
quantifiedcode-bot/invenio-deposit | invenio_deposit/autocomplete_utils.py | Python | gpl-2.0 | 3,068 | 0 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio 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... | 50):
from invenio_knowledge.api import get_kbd_values
result = get_kbd_values(name, searchwith=term)[:limit]
return map(mapper, result) if mapper is not None else result
return inner
|
def sherpa_romeo_publishers(dummy_form, dummy_field, term, limit=50):
"""Autocomplete publishers from SHERPA/RoMEO service."""
if term:
sherpa_romeo = SherpaRomeoSearch()
publishers = sherpa_romeo.search_publisher(term)
if publishers is None:
return []
return map(la... |
dvirsky/govsearch | scraper/scraper/spiders/resolutions.py | Python | bsd-3-clause | 2,802 | 0.003569 | # -*- coding: utf-8 -*-
import scrapy
from scraper.items import ResolutionItem
class ResolutionSpider(scrapy.Spider):
name = "resolutions"
allowed_domains = ["www.pmo.gov.il"]
start_urls = ["http://www.pmo.gov.il/Secretary/GovDecisions/Pages/default.aspx"]
def should_retry(self, response):
... | d scrap | y.Request(sel.extract(), callback=self.parse_resolution)
# parse next pages
for sel in response.xpath("//a[@class='PMM-resultsPagingNumber']/@href"):
url = response.urljoin(sel.extract())
yield scrapy.Request(url)
def parse_resolution(self, response):
"""Scrape rele... |
miyataken999/weblate | weblate/trans/fonts.py | Python | gpl-3.0 | 49,812 | 0 | # -*- coding: utf-8 -*-
#
# Copyright © 2012 - 2015 Michal Čihař <[email protected]>
#
# This file is part of Weblate <https://weblate.org/>
#
# 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, eith... | 7, 0xa8, 0xa9, 0xaa,
0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2,
0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0... | 5, 0xe6,
0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2,
0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe,
0xff, 0x100, 0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107, 0x108, 0x109,
0x10a, 0x10b, 0x10c, 0x10d, 0x10e, 0x10f, 0x110, 0x111, 0x112, 0x113,
0... |
pinguinkiste/bioconda-recipes | recipes/peptide-shaker/peptide-shaker.py | Python | mit | 3,271 | 0.000917 | #!/usr/bin/env python
#
# Wrapper script for Java Conda packages that ensures that the java runtime
# is invoked with the right options. Adapted from the bash script (http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in/246128#246128).
#
# Program Parameters
#
import os
import s... | sts(exec_dir):
shutil.copytree(real_dirname(sys.argv[0]), exec_dir, symlinks=False, ignore=None)
| else:
pass_args.append(arg)
# In the original shell script the test coded below read:
# if [ "$jvm_mem_opts" == "" ] && [ -z ${_JAVA_OPTIONS+x} ]
# To reproduce the behaviour of the above shell code fragment
# it is important to explictly check for equality with None
# in the sec... |
CharlesShang/TFFRCNN | lib/networks/VGGnet_test.py | Python | mit | 2,855 | 0.001401 | import tensorflow as tf
from .network import Network
from ..fast_rcnn.config import cfg
class VGGnet_test(Network):
def __init__(self, trainable=True):
self.inputs = []
self.data = tf.placeholder(tf.float32, shape=[None, None, None, 3])
self.im_info = tf.placeholder(tf.float32, shape=[None... | .conv(3, 3, 512, 1, 1, name='conv5_2')
.conv(3, 3, 512, 1, 1, name='conv5_3'))
(self.feed('conv5_3')
.conv(3, 3, 512, 1, 1, name='rpn_conv/3x3')
.conv(1, 1, len(anchor_scales) * 3 * 2, 1, 1, padding='VALID', relu=False, name='rpn_cls_score'))
(self.feed('rpn_conv/3x3')... | n(anchor_scales) * 3 * 4, 1, 1, padding='VALID', relu=False, name='rpn_bbox_pred'))
# shape is (1, H, W, Ax2) -> (1, H, WxA, 2)
(self.feed('rpn_cls_score')
.spatial_reshape_layer(2, name='rpn_cls_score_reshape')
.spatial_softmax(name='rpn_cls_prob'))
# shape is (1, H, WxA, 2... |
DailyActie/Surrogate-Model | 01-codes/scipy-master/scipy/sparse/linalg/isolve/tests/test_lsmr.py | Python | mit | 4,984 | 0.000201 | """
Copyright (C) 2010 David Fong and Michael Saunders
Distributed under the same license as Scipy
Testing Code for LSMR.
03 Jun 2010: First version release with lsmr.py
David Chin-lung Fong [email protected]
Institute for Computational and Mathematical Engineering
Stanford University
Michael Saunders ... | al(norm(A.dot(x) - b), 0)
def testColumnB(self):
A = eye(self.n)
b = ones((self.n, 1))
x = lsmr(A, b)[0]
assert_almost_equal(norm(A.dot(x) - b.ravel()), 0)
class TestLSMRReturns:
def setUp(self):
self.n = 10
self.A = lowerBidiagonalMatrix(20, self.n)
se... | self.returnValues = lsmr(self.A, self.b)
def testNormr(self):
x, istop, itn, normr, normar, normA, condA, normx = self.returnValues
assert_almost_equal(normr, norm(self.b - self.Afun.matvec(x)))
def testNormar(self):
x, istop, itn, normr, normar, normA, condA, normx = self.retur... |
sandeepkrjha/pgmpy | pgmpy/sampling/__init__.py | Python | mit | 693 | 0.002886 | from .base import (BaseGradLogPDF, GradLogPDFGaussian, LeapFrog,
ModifiedEuler, BaseSimulateHamiltonianDynamics, _return_samples)
from .HMC import HamiltonianMC, HamiltonianMCDA
from .NUTS import NoUTurnSampler, NoUTurnSamplerDA
from .Sampling import GibbsSa | mpling, BayesianModelSampling
__all__ = ['LeapFrog',
'ModifiedEuler',
'BaseSimulateHamiltonianDynamics',
'BaseGradLogPDF',
'GradLogPDFGaussian',
'_return_samples',
| 'HamiltonianMC',
'HamiltonianMCDA',
'NoUTurnSampler',
'NoUTurnSamplerDA',
'BayesianModelSampling',
'GibbsSampling']
|
Distrotech/reportlab | src/reportlab/__init__.py | Python | bsd-3-clause | 1,314 | 0.022831 | #Copyright ReportLab Europe Ltd. 2000-2015
#see license.txt for license details
__doc__="""The Reportlab PDF generation library."""
Version = "3.2.13"
__version__=Version
__date__='20151210'
import s | ys, os, imp
if sys.version_info[0:2]!=(2, 7) and sys.version_info<(3, 3):
raise ImportError("""reportlab requires Python 2.7+ or | 3.3+; 3.0-3.2 are not supported.""")
#define these early in reportlab's life
isPy3 = sys.version_info[0]==3
if isPy3:
def cmp(a,b):
return -1 if a<b else (1 if a>b else 0)
import builtins
builtins.cmp = cmp
builtins.xrange = range
del cmp, builtins
else:
from future_builtins import asc... |
soylentdeen/cuddly-weasel | MusicMaker/Output/plotter.py | Python | mit | 708 | 0.00565 | import Moog960
import numpy
import SpectralTools
import matplotlib.pyplot as pyplot
fig = pyplot.figure | (0)
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.clear()
syntheticScore = Moog | 960.Score(suffix='', observed = '../../Theremin/TWHydra.fits')
models = syntheticScore.getLabels(keySignature='CONVOLVED')
observed = syntheticScore.getLabels(keySignature='OBSERVED')
for model in models:
parameters = model.parameters
label = "T=%d log g=%.1f B=%.1f" % (parameters["TEFF"], parameters["LOGG"... |
ASPLes/turbulence | tools/tbc-ctl/tbc-setup-mod-radmin.py | Python | lgpl-2.1 | 4,910 | 0.016497 | #!/usr/bin/python
import os
import commands
import termios
import sys
def enable_echo(fd, enabled):
(iflag, oflag, cflag, lflag, ispeed, ospeed, cc) = termios.tcgetattr (fd)
if enabled:
lflag |= termios.ECHO
else:
lflag &= ~termios.ECHO
new_attr = [iflag, oflag, cflag, lflag, ispeed, o... | etstatusoutput ("ln -s %s/turbulence/mods-available/mod_radmin.xml %s/turbulence/mods-enabled/mod_radmin.xml" % (baseconfdir, baseconfdir))
if status:
print ("INFO: failed to enable module, ln command failed: %s" % output)
sys.exit (-1)
# flag you should reboot
s | hould_reboot = True
print ("INFO: configuration done!")
if should_reboot:
print ("INFO: you must reboot your turbulence server to make changes effective")
|
hankcs/HanLP | hanlp/pretrained/pos.py | Python | apache-2.0 | 2,166 | 0.007849 | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-29 01:57
from hanlp_common.constant import HANLP_URL
CTB5_POS_RNN = HANLP_URL + 'pos/ctb5_pos_rnn_20200113_235925.zip'
'An old school BiLSTM tagging model trained on CTB5.'
CTB5_POS_RNN_FASTTEXT_ZH = HANLP_URL + 'pos/ctb5_pos_rnn_fasttext_20191230_202639.zip'
'An... | l with FastText (:cite:`bojanowski2017enriching`) embeddings trained on CTB5.'
CTB | 9_POS_ALBERT_BASE = HANLP_URL + 'pos/ctb9_albert_base_20211228_163935.zip'
'ALBERT model (:cite:`Lan2020ALBERT:`) trained on CTB9 (:cite:`https://doi.org/10.35111/gvd0-xk91`). This is a TF component.'
CTB9_POS_ELECTRA_SMALL_TF = HANLP_URL + 'pos/pos_ctb_electra_small_20211227_121341.zip'
'Electra small model (:cite:`cl... |
ajstarna/RicochetRobots | Brobot/Move.py | Python | bsd-2-clause | 1,936 | 0.035124 | import random
import numpy as np
from copy import deepcopy
class Move:
''' the move data structure. field for colour of robot and direction of move. '''
intToColourConversion = ["BLUE", "RED", "GREEN", "YELLOW"] # index with robot number to get colour as string
def __init__(self, colour, direction):
self.colou... | ur = {0} and direction = {1}".format(self.intToColourConversion[self.colour], self.d | irection)
class AllMoves:
''' this class holds all possibe moves that can be made in Ricochet Robots '''
def __init__(self):
self.moveSet = self.createMoveSet() # a np array
def createMoveSet(self):
''' creates the move set with all possible colours and directions '''
moveSet = []
for colour in xrange... |
sema/django-2012 | website/mosaicportfolio/templatetags/htmlsanitizer.py | Python | mit | 564 | 0.010638 | import bleach
from django | import template
fr | om django.conf import settings
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
register = template.Library()
@stringfilter
def sanitize_html(value):
if isinstance(value, basestring):
value = bleach.clean(value,
tags=settings.HTML_SANITIZER... |
zlatozar/pytak | pytak/tests/fakeapi/GetInformationAboutYourself.py | Python | bsd-3-clause | 166 | 0.006024 | from py | tak.call import REST
class GetInformationAboutYourself(REST):
def fill_call_data(self):
| self.uri = "/api/muad/rest/users/@me[?query_parameters]"
|
citrix-openstack-build/nova | nova/db/sqlalchemy/migrate_repo/versions/153_instance_type_in_system_metadata.py | Python | apache-2.0 | 2,116 | 0 | # Copyright 2013 IBM Corp.
#
# 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 t... | ermissions and limitations
# under the License | .
from sqlalchemy import MetaData, select, Table
def upgrade(migrate_engine):
meta = MetaData()
meta.bind = migrate_engine
instances = Table('instances', meta, autoload=True)
instance_types = Table('instance_types', meta, autoload=True)
sys_meta = Table('instance_system_metadata', meta, autoload=... |
Crystal-SDS/dashboard | crystal_dashboard/dashboards/crystal/controllers/instances/models.py | Python | gpl-3.0 | 319 | 0.003135 | class Inst | ance:
"""
Instances class models.
"""
def __init__(self, instance_id, cont | roller, parameters, description, status):
self.id = instance_id
self.controller = controller
self.parameters = parameters
self.description = description
self.status = status
|
dkamotsky/program-y | src/programy/parser/exceptions.py | Python | mit | 3,289 | 0.006081 | """
Copyright (c) 2016 Keith Sterling
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, publish, distribute,... | copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ... | OM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class ParserException(Exception):
def __init__(self, message, filename=None, xml_exception=None, xml_element=None):
Exception.__init__(self, message)
self._message = message
self._filename = file... |
wscullin/spack | var/spack/repos/builtin/packages/xkill/package.py | Python | lgpl-2.1 | 1,898 | 0.000527 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-64... | 07 USA
##############################################################################
from spack import *
class Xkill(AutotoolsPackage):
"""xkill is a utility for forcing the X server to close connections to
clients. This program is very dangerous, but is useful for aborting
programs that have displayed ... | pp/xkill"
url = "https://www.x.org/archive/individual/app/xkill-1.0.4.tar.gz"
version('1.0.4', 'b04c15bfd0b619f1e4ff3e44607e738d')
depends_on('libx11')
depends_on('libxmu')
depends_on('[email protected]:', type='build')
depends_on('[email protected]:', type='build')
depends_on('util-macro... |
nedbat/coveragepy | tests/test_html.py | Python | apache-2.0 | 44,058 | 0.00084 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Tests that HTML generation is awesome."""
import datetime
import glob
import json
import os
import os.path
import re
import sys
from unittest import mock
impor... | r"created at \d{4}-\d{2}-\d{2} \d{2}:\d{2} \+\d{4}",
r"created at YYYY-MM-DD HH:MM +ZZZZ",
index,
)
index = re.sub(
| r"created at \d{4}-\d{2}-\d{2} \d{2}:\d{2}",
r"created at YYYY-MM-DD HH:MM",
index,
)
return index
def assert_correct_timestamp(self, html):
"""Extract the timestamp from `html`, and assert it is recent."""
timestamp_pat = r"created at (\d{4})-(\d{2... |
sdlarsen1/CMPUT291 | prjcode/Doctor.py | Python | gpl-3.0 | 9,331 | 0.014575 | import os
from LogInOut import logout
def doctorCommands(cursor, conn, staff_id):
loggedOut = False
while not loggedOut:
os.system("clear")
choice = int(raw_input('''Type integer value of desired task:
1. Get patient chart info.
2. Rec... | mber >")
if (hcno,chart_id) in patientCharts:
chartNotSelected = False
else:
print "Patient #%s does not have a chart #%s that is open" %(hcno,chart_id)
choice = raw_input("Enter 'quit' to exit task or enter anything to try another chart n | umber >").lower()
if choice == 'quit':
return False
medication = raw_input("Enter Drug Name >").lower()
cursor.execute('''
select lower(drug_name)
from reportedallergies
where hcno = ?
;
''', (hcno,))
directAllergies = cursor.fetchall()... |
exa-analytics/exatomic | exatomic/exa/util/tests/test_utility.py | Python | apache-2.0 | 964 | 0.001037 | # -*- codin | g: utf-8 -*-
# Copyright (c) 2015-2022, Exa Analytics Development Team
# Distributed under the t | erms of the Apache License 2.0
from os import path
from tempfile import mkdtemp
from exatomic.exa.util.utility import datetime_header, mkp, convert_bytes, get_internal_modules
def test_get_internal_modules():
lst = get_internal_modules()
assert len(lst) > 0
assert lst[0].__name__.startswith("exatomic")
... |
apirobot/shmitter | backend/shmitter/users/validators.py | Python | mit | 377 | 0 | from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import gettext_lazy as _
@deconstructible
class UsernameValidator(validators.RegexValidator):
regex = r'^[\w.]+$'
message = _(
'Enter a | valid username. This value may contain only letters, '
'numbers, underscores and | periods.'
)
|
fr33jc/bang-unstable | setup.py | Python | gpl-3.0 | 751 | 0.001332 | #!/usr/bin/env python
from setuptools import setup, find_packages
from bang import VER | SION
import os.path
ETC = os.path.join(os.path.dirname(__file__), 'etc')
with open(os.path.join(ETC, 'requireme | nts.pip')) as f:
reqs = [l.strip() for l in f if '://' not in l]
reqs.append('distribute')
setup(
name='bang',
version=VERSION,
author='fr33jc',
author_email='[email protected]',
packages=find_packages(exclude=['tests']),
package_data={'bang': ['bang.wav']},
l... |
open-synergy/opensynid-fleet | fleet_work_order/reports/fleet_work_order_analysis.py | Python | agpl-3.0 | 3,619 | 0 | # -*- coding: utf-8 -*-
# Copyright 2018 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields
from openerp import tools
class FleetWorkOrderAnalysis(models.Model):
_name = "fleet.work_order_analysis"
_description = "Fleet Work Order Analysis... | a.real_date_depart AS real_date_depart,
a.real_date_arrive AS real_date_arrive,
a.start_location_id AS start_location_id,
a.end_location_id AS end_location_id,
a.state AS state,
SUM(a.end_odometer - a.start_odometer) AS odometer,
SUM(a.dista... | |
custode/reviewboard | reviewboard/webapi/resources/draft_file_attachment.py | Python | mit | 4,019 | 0 | from __future__ import unicode_literals
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from djblets.util.decorators import augment_method_from
from djblets.webapi.decorators import webapi_login_required
from djblets.webapi.responses import WebAPIResponsePaginated
from reviewboard... | not be undone.
This can be used to remove old files that were previousl | y
shown, as well as newly added files that were part of the
draft.
Instead of a payload response on success, this will return :http:`204`.
"""
pass
@webapi_check_local_site
@webapi_login_required
@augment_method_from(WebAPIResource)
def get_list(self, *args, **k... |
CadeiraCuidadora/UMISS-backend | umiss_project/manage.py | Python | gpl-3.0 | 811 | 0 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "umiss_project.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure tha... | raise
ex | ecute_from_command_line(sys.argv)
|
googleapis/python-aiplatform | samples/generated_samples/aiplatform_v1beta1_generated_featurestore_service_update_entity_type_async.py | Python | apache-2.0 | 1,513 | 0.001322 | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | cloud-aiplatform
# [START aiplatform_v1beta1_generated_FeaturestoreService_UpdateEntityType_async]
from google.cloud import aiplatform_v1beta1
async de | f sample_update_entity_type():
# Create a client
client = aiplatform_v1beta1.FeaturestoreServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.UpdateEntityTypeRequest(
)
# Make the request
response = await client.update_entity_type(request=request)
# Handl... |
Fuchida/Archive | albme-py/script.py | Python | mit | 150 | 0.02 | def sum(*args):
total = 0
for number in args:
if isinstance(number, int):
| total += number
return tot | al
print(sum(1,5)) |
petteraas/SoCo | examples/plugins/socoplugins.py | Python | mit | 1,032 | 0 | #!/usr/bin/env python
# This illustrates how to use SoCo plugins
# an example plugin is provided in soco.plugins.example.ExamplePlugin
import time
from soco import SoCo
from soco.plugins import SoCoPlugin
def main():
speakers = [speaker.ip_address for speaker in SoCo.discover()]
if not speakers:
p... | oCo(speakers[0])
# get a plugin by name (eg from a config file)
myplugin = SoCoPlugin.from_name(
"soco.plugins.example.ExamplePlugin", soco, "some user"
)
# do something with your plugin
print("Testing", myplugin.name)
myplugin.music_plugin_play()
time.sleep(5)
# create a plu... | xample import ExamplePlugin
# create a new plugin, pass the soco instance to it
myplugin = ExamplePlugin(soco, "a user")
print("Testing", myplugin.name)
# do something with your plugin
myplugin.music_plugin_stop()
if __name__ == "__main__":
main()
|
richardliaw/ray | python/ray/tune/suggest/nevergrad.py | Python | apache-2.0 | 12,589 | 0 | import logging
import pickle
from typing import Dict, Optional, Union, List, Sequence
from ray.tune.result import DEFAULT_METRIC
from ray.tune.sample import Categorical, Domain, Float, Integer, LogUniform, \
Quantized
from ray.tune.suggest.suggestion import UNRESOLVED_SEARCH_SPACE, \
UNDEFINED_METRIC_MODE, UND... | raise ValueError("Instrumented optimizers should provide "
"None as parameter_names")
else:
if self | ._parameters is None:
raise ValueError("Non-instrumented optimizers should have "
"a list of parameter_names")
if len(self._nevergrad_opt.instrumentation.args) != 1:
raise ValueError(
"Instrumented optim... |
shrinidhi666/rbhus | etc/blend_lin/default.py | Python | gpl-3.0 | 5,828 | 0.025566 | #!/usr/bin/env python2
#-*- coding: utf-8 -*-
__author__ = "Shrinidhi Rao"
__license__ = "GPL"
__email__ = "[email protected]"
import os
import sys
import pwd
import time
import socket
import subprocess
import simplejson
rbhus_main_path = os.sep.join(os.path.abspath(__file__).split(os.sep)[0:-3])
sys.path.appen... | ,"#") + "." + outName.split(".")[-1]
outputNoutF = "/tmp/"+ str(taskId) +"_"+ str(frameId) +"_outputNodes.py"
wbd.writelines(outputNoutF +"\n\r")
wbd.flush()
wbd.close()
try:
os.system("cp -a "+ outputN +" "+ outputNoutF +" >& /dev/null")
except:
pass
try:
os.system("sed -i 's/re | nameOutputDir/"+"\\/".join(outDir.split("/")) +"/' "+ outputNoutF +" >& /dev/null")
except:
pass
if(layer != "default"):
try:
os.system("sed -i 's/renameRenderLayer/"+ layer +"/' "+ outputNoutF +" >& /dev/null")
except:
pass
if(renderer != "default"):
RENDERCMD = RENDERCMD +" -E "+ renderer
RENDERCMD ... |
looooo/pivy | examples/SoPyScript/glow.py | Python | isc | 1,768 | 0.007919 | from __future__ import print_function
# make the handler of the color field to call chicken_mcnuggets()
# instead of the default set handle_color() function
handler_registry['color'] = 'chicken_mcnuggets'
def chicken_mcnuggets():
# print color.getValue().getValue()
pass
# Initialize the color Packer (required of ... | nsparencyOverride(action.getState()):
# keep a copy of the transparency that we are putting in the state:
transpValue.assign(tr | ansparency.getValue())
# The color packer must be provided when the transparency is set,
# so that the transparency will be merged with current diffuse color
# in the state:
SoLazyElement.setTransparency(action.getState(), self, 1, transpValue, colorPacker)
def GLRender(action):
... |
ivanhorvath/openshift-tools | scripts/monitoring/cron-send-cpu-mem-stats.py | Python | apache-2.0 | 3,773 | 0.007951 | #!/usr/bin/env python2
'''
Simple monitoring scr | ipt to collect per process cpu percentage
and mem usage in bytes (vms or virt and rss)
usage:
cron-send-cpu-mem-stats process_name openshift.whatever.zabbix.key
or
cron-send-cpu-mem-stats 'something parameter more params' openshift.something.parameter.more.params
The script | will attach .cpu and .mem.{vms|rss} to the end of the zabbix key name for the values
Future enhancement can be to add multiple instances, that would add pid to the key, but those
would have to be dynamic items in zabbix
'''
# vim: expandtab:tabstop=4:shiftwidth=4
# Disabling invalid-name because pylint doesn't ... |
stefanwebb/tensorflow-models | tensorflow_models/initializations.py | Python | mit | 1,768 | 0.010747 | # MIT License
#
# Copyright (c) 2017, Stefan Webb. 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
# to us... | ded in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HO... | H THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def xavier_init(fan_in, fan_out, constant=1):
""" Xavier initialization of network weights"""
# ht... |
CyberPoint/libpgm | tests/run_unit_tests.py | Python | bsd-3-clause | 14,090 | 0.004116 | '''
A module that conducts unit tests on all top-level methods within each class.
Created on Jun 20, 2012
@author: ccabot
'''
import unittest
import sys
# add to PYTHONPATH
sys.path.append("../")
from libpgm.dictionary import Dictionary
from libpgm.graphskeleton import GraphSkeleton
from libpgm.orderedskeleton impo... | nstance.getparents(1), [5])
self.assertEqual(self.instance.getparents(4), [])
def test_getchildren(self):
self | .assertEqual(self.instance.getchildren(5), [1])
self.assertEqual(self.instance.getchildren(4), [])
def test_toporder(self):
self.instance.toporder()
self.assertTrue(self.instance.V.index(5)<self.instance.V.index(1))
self.assertTrue(self.instance.V.index(5)<self.instance.V.index(2))
... |
zhiwliu/openshift-ansible | roles/openshift_health_checker/openshift_checks/docker_image_availability.py | Python | apache-2.0 | 13,335 | 0.003975 | """Check that required Docker images are available."""
import re
from pipes import quote
from ansible.module_utils import six
from openshift_checks import OpenShiftCheck
from openshift_checks.mixins import DockerHostMixin
NODE_IMAGE_SUFFIXES = ["haproxy-router", "docker-registry", "deployer", "pod"]
DEPLOYMENT_IMAGE... | deployment_type = self.get_var("openshift_deployment_type")
if deployment_type == "origin" and "docker.io" not in regs:
regs.append("docker.io")
elif deployment_type == 'openshift-enterprise' and "re | gistry.access.redhat.com" not in regs:
regs.append("registry.access.redhat.com")
self.registries["configured"] = regs
# for the oreg_url registry there may be credentials specified
components = self.get_var("oreg_url", default="").split('/')
self.registries["oreg"] = "" if l... |
susemeee/Chunsabot-framework | chunsabot/modules/weather.py | Python | mit | 3,474 | 0.00489 | # -*- coding: utf-8 -*-
from chunsabot.botlogic import brain
from chunsabot.database import Database, Cache
from bs4 import BeautifulSoup as Soup
import requests
#from threading import Thread
from multiprocessing.pool import ThreadPool
class Weather:
cWEATHER_GET_URL = Database.load_config("weather_url_all")
... | ader)
i = 2
for d in data:
res.append(Wea | ther.prettify(i, d))
i += 1
if i > 6: break
res.append(weather_location_footer)
res = "\r\n".join(res)
result[region] = res
return result
@staticmethod
def prettify(i, data):
apm = [u'오전', u'오후']
day = u"[{0}일 후 {1}예보... |
jayhetee/coveragepy | coverage/control.py | Python | apache-2.0 | 44,134 | 0.000159 | # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
"""Core control stuff for coverage.py."""
import atexit
import inspect
import os
import platform
import sys
import traceback
from coverage import env, files
from ... | age.plugin import FileReporter
from coverage.plugin_support import Plugins
from coverage.python import PythonFileReporter
from coverage.results import Analysis, Numbers
from coverage.summary import SummaryReporter
from coverage.xmlreport import XmlReporter
# Pypy has s | ome unusual stuff in the "stdlib". Consider those locations
# when deciding where the stdlib is.
try:
import _structseq
except ImportError:
_structseq = None
class Coverage(object):
"""Programmatic access to coverage.py.
To use::
from coverage import Coverage
cov = Coverage()
... |
justinvanwinkle/flexiconfig | flexiconfig/__init__.py | Python | bsd-2-clause | 419 | 0 | # -*- coding: utf | -8 -*-
from __future__ import unicode_literals
import os
from simplejson import load
class Configuration(dict):
def __init__(self, conf_fns):
self.conf_fns = conf_fns
for conf_fn in self.conf_fns:
abs_conf_fn = os.path.abspath(conf_fn)
| if os.path.exists(abs_conf_fn):
with open(abs_conf_fn) as f:
self.update(load(f))
|
alfredhq/alfred-coordinator | setup.py | Python | isc | 530 | 0 | from setuptools import setup
setup(
name='alfred-c | oordinator',
version='0.1.dev',
license='ISC',
description='Streams tasks from listener to workers.',
url='https://github.com/alfredhq/alfred-coordinator',
author='Alfred Developers',
author_email='[email protected]',
py_modules=['alfred_coordinator'],
install_requires=[
'PyYAML'... | },
)
|
Torben-D/open62541 | tools/pyUANamespace/ua_builtin_types.py | Python | lgpl-3.0 | 59,096 | 0.01391 | #!/usr/bin/env/python
# -*- coding: utf-8 -*-
###
### Author: Chris Iatrou ([email protected])
### Version: rev 13
###
### This program was created for educational purposes and has been
### contributed to the open62541 project by the author. All licensing
### terms for this source is inherited by the terms and... | # and not as <Duration><Hawaii><UtcTime><String>2013-04-10 12:00 UTC</String>...
# Encoding may be partially handed down (iterative call). Only resort to
# type definition if we are not given a specific encoding to match
if encodingPart == None:
enc = self.parent.dataType().target().getEncoding()
... | e:
enc = encodingPart
# Check the structure of the encoding list to determine if a type is to be
# returned or we need to descend further checking aliases or multipart types
# such as extension Objects.
if len(enc) == 1:
# 0: ['BuiltinType'] either builtin type
# 1: [ [ 'Alia... |
Karel-van-de-Plassche/bokeh | bokeh/core/property/containers.py | Python | bsd-3-clause | 14,792 | 0.001149 | ''' Provide special versions of list and dict, that can automatically notify
about changes when used for property values.
Mutations to these values are detected, and the properties owning the
collection is notified of the changes. Consider the following model
definition:
.. code-block:: python
class SomeModel(Mo... | _notify_owners(self, old, hint=None):
for (owner, descriptor) in self._owners:
descriptor._notify_mutated(owner, old, hint=hint)
def _saved_copy(self):
raise RuntimeError("Subtypes must implement this to make a backup copy")
class PropertyValueList(PropertyV | alueContainer, list):
''' A list property value container that supports change notifications on
mutating operations.
When a Bokeh model has a ``List`` property, the ``PropertyValueLists`` are
transparently created to wrap those values. These ``PropertyValueList``
values are subject to normal proper... |
cropr/bjk2017 | cd_subscription/migrations/0005_auto_20161125_1908.py | Python | apache-2.0 | 2,446 | 0.003679 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cd_subscription', '0004_auto_20161125_1901'),
]
operations = [
migrations.AlterField(
model_name='cdsubscription... | 'Length badge image'),
),
migrations.AlterField(
model_name='cdsubscript | ion',
name='emailparent',
field=models.EmailField(blank=True, max_length=40, default='', verbose_name='Email parent'),
),
migrations.AlterField(
model_name='cdsubscription',
name='emailplayer',
field=models.EmailField(blank=True, max_length=40,... |
creative-workflow/pi-setup | lib/piservices/piservice.py | Python | mit | 5,056 | 0.013252 | import os, helper, config, glob, loader
from fabops import FabricTaskOperator
from policies import PiServicePolicies
from remote.integration import RemoteFileHelper
from initd import InitScript, InitScriptWithTemplate, AutogeneratedInitScript
pisetup_root_folder_on_pi ='/home/pi/pi-setup'
piservice_standart... | ),
'local_path' : os.path.realpath(loader.services_path+'/'+self.name),
| 'local_pi_setup_path' : os.path.realpath(os.path.dirname(__file__)+'/../../'),
'remote_pi_setup_path': pisetup_root_folder_on_pi
})
for key, value in self.default_attributes.iteritems():
if not hasattr(self, key):
self.__di... |
ImmobilienScout24/afp-core | src/unittest/python/aws_federation_proxy_mocks.py | Python | apache-2.0 | 323 | 0.003096 | """ Mock classes for use in aws_feder | ation_proxy_tests """
from __future__ import print_function, absolute_import, unicode_literals, division
from aws_federation_proxy.aws_federation_proxy import AWSFederationProxy
class MockAWSFederationProxyForInitTest(AWSFederationProxy):
def _setup_provider(self | ):
pass
|
AdamantLife/alcustoms | alcustoms/Programs/SQLExplorer.py | Python | gpl-3.0 | 16,142 | 0.019081 |
import pathlib
import pprint
import shutil
from alcustoms import sql
from alcustoms.tkinter import advancedtkinter, smarttkinter, style
import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
ttk = smarttkinter.ttk.ttk
from alcustoms.methods import minimalist_pprint_pformat
##################... | openfilename()
if not file:
return
file = pathlib.Path(file).resolve()
if not file.exists():
messagebox.showerror("Invalid File", "File does not exist")
| return
try:
file = shutil.copy(str(file),str(pathlib.Path.cwd().resolve() / "temp"))
except Exception as e:
messagebox.showerror("Copy Failure",f"Failed to create work-copy of database:\n{e}")
return
try:
db = sql.Database(file, row_factor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.