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 |
|---|---|---|---|---|---|---|---|---|
iraklikhitarishvili/data2class | base/document.py | Python | bsd-2-clause | 7,734 | 0.001422 | """
===================
Base Object Classes
===================
"""
from validation.validationresult.resultenum import ResultType
from validation.validators.document_validator import DocumentValidator
from validation.runner import ValidationsRunner
from base.enums import FieldType
from validation.validationresult.resul... | <base.objects.BaseObject.mapper>` ``dump`` function and returns it's result
"""
if self.mapper is not None:
self.fill_mapper_data()
else:
raise AttributeError("mapper isn't defined")
return self.mapper.dump()
def get_fields(sel | f) -> dict:
return self._fields
def is_valid(self):
"""
Calls :py:meth:`validate`
:return: whether data in object is valid or not
:rtype: boolFieldType
"""
return Result.is_valid(self.validate(self))
def validate(self, data):
return self.runner... |
familug/FAMILUG | Python/FCM28RawInput.py | Python | bsd-2-clause | 158 | 0.012658 | #!usr/ | bin/env python2
name = raw_input("Full name: ")
if name == 'Nguyen Viet Hung':
print 'Hi HVN'
namelist = name.split(' ')
for w in namelist:
prin | t w,
|
davidwilson-85/easymap | scripts_ins/local-analysis.py | Python | gpl-3.0 | 6,122 | 0.039203 | #This module will process the information in the .sam file to obtain the absolute frequency of aligments ending per nucleotide during local aligments.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-a', action="store", dest = 'input')
parser.add_argument('-b', action="store", dest = 'outpu... | #a reads alignment finishes in each nucleotide, separating the information according to which
di_left = dict() #side of the read is aligned (left or right). d2_1 and d2_2 are lists of all the positions
di_right = dict() #in which a reads aligment finishes, repeated as many times as that happ... | tal = dict()
d2_1 = []
d2_2 = []
rd_left = []
rd_right = []
for i, line in enumerate(lines):
if not line.startswith('@'):
sp = line.split('\t')
cont = sp[2]
if cont == c and cont != '*':
p = int(sp[3]) #Read position
cigar = sp[5].strip() #Then we define the CIGAR para... |
bletham/fstimer | fstimer.py | Python | gpl-3.0 | 206 | 0.004854 | #!/usr/bin/env python3
impo | rt fstimer.fslogger
import fstimer.timer
from gi.repository import Gtk
def main():
py | timer = fstimer.timer.PyTimer()
Gtk.main()
if __name__ == '__main__':
main()
|
silenius/amnesia | amnesia/modules/folder/exc.py | Python | bsd-2-clause | 280 | 0.003571 | # | -*- coding: utf-8 -*-
from amnesia.exc import AmnesiaError
class PasteError(AmnesiaError):
def __init__(self, container):
super()
self.container = container
def __str__(self):
return 'Paste into container {} failed'.format(self.containe | r.id)
|
sourtin/igem15-sw | gui/webshell/edf.py | Python | gpl-2.0 | 902 | 0.011086 | import cv2
import mahotas as mh
import datetime, uuid
import numpy as np
def edf(jpegs, user):
def stack(image):
stack,h,w = image.shape
focus = np.array([mh.sobel(t, just_filter=True) for t in image])
best = np.argmax(focus, 0)
image = image.reshape((stack,-1))
image = ima... | annel] for im in dat])) for channel in range(3)))
fname = "%s/%s.%s.EDF.png" % (user.replace('/', '').replace('..', ''), str(datetime. | datetime.now()), str(uuid.uuid4()))
cv2.imwrite("/home/pi/igem15-sw/captured/%s" % fname, r)
return "/captured/%s" % fname
|
os2webscanner/os2webscanner | django-os2webscanner/os2webscanner/migrations/0013_auto_20180501_1006.py | Python | mpl-2.0 | 414 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-05-01 08:06
from __future__ import unicode_literals
from django.db import migrations
class M | igration(migrations.Migration):
dependencies = [
('os2webscanner', '0012_auto_20180501_1004'),
]
operations = [
migrations.AlterModelTable( |
name='scanner',
table='os2webscanner_scanner',
),
]
|
Tendrl/monitoring-integration | tendrl/monitoring_integration/grafana/datasource_utils.py | Python | lgpl-2.1 | 3,062 | 0 | import json
import maps
import traceback
from requests impor | t get
from requests import post
from r | equests import put
from tendrl.commons.utils import log_utils as logger
from tendrl.monitoring_integration.grafana import constants
from tendrl.monitoring_integration.grafana import exceptions
from tendrl.monitoring_integration.grafana import utils
def _post_datasource(datasource_json):
config = maps.NamedDict(N... |
tik0/inkscapeGrid | share/extensions/Barcode/__init__.py | Python | gpl-2.0 | 1,757 | 0.003415 | #
# Copyright (C) 2014 Martin Owens
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundatio... |
ssanderson/numpy | numpy/core/tests/test_arrayprint.py | Python | bsd-3-clause | 9,360 | 0.004381 | # -*- coding: utf-8 -*-
from __future__ import division, absolute_import, print_function
import sys
import numpy as np
from numpy.compat import sixu
from numpy.testing import (
TestCase, run_module_suite, assert_, assert_equal
)
class TestArrayRepr(object):
def test_nan_inf(self):
x = np.array([np.n... | '[ inf-infj]', '[ inf-infj]',
'[ inf+nanj]', '[ inf+nanj]', '[ inf+nanj]',
'[-inf+0.j]', '[-inf+0.j]', '[-inf+0.0j]',
'[-inf+1.j]', '[-inf+1.j]', '[-inf+1.0j]',
'[-inf-1.j]', '[-inf-1.j]', '[-inf-1.0j]',
'[-inf+infj]', '[-inf+infj]', '[-inf+... | 0j]',
'[ nan+1.j]', '[ nan+1.j]', '[ nan+1.0j]',
'[ nan-1.j]', '[ nan-1.j]', '[ nan-1.0j]',
'[ nan+infj]', '[ nan+infj]', '[ nan+infj]',
'[ nan-infj]', '[ nan-infj]', '[ nan-infj]',
'[ nan+nanj]', '[ nan+nanj]', '[ nan+nanj]']
for res, v... |
rca/issuebranch | src/webapp/webapp/settings.py | Python | apache-2.0 | 3,048 | 0.000984 | """
Django settings for webapp project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
... | /settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
},
{"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
{"NAME": "django.contrib.auth.password_validation.CommonPass | wordValidator"},
{"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# ht... |
all3fox/algos-py | setup.py | Python | mit | 485 | 0 | from setuptools import setup, find_packa | ges
with open("README.rst") as readme:
long_description = readme | .read()
setup(
name='algos-py',
version='0.4.5',
license='MIT',
author='Aleksandr Lisianoi',
author_email='all3fox@gmail.com',
url='https://github.com/all3fox/algos-py',
packages=find_packages(),
description="Classic computer science algorithms in Python",
long_description=long_desc... |
saltstack/salt | salt/utils/mac_utils.py | Python | apache-2.0 | 14,345 | 0.000697 | """
Helper functions for use by mac modules
.. versionadded:: 2016.3.0
"""
import logging
import os
import plistlib
import subprocess
import time
import xml.parsers.expat
import salt.grains.extra
import salt.modules.cmdmod
import salt.utils.args
import salt.utils.files
import salt.utils.path
import salt.utils.platfor... | Logger(__name__)
__virtualname__ = "mac_utils"
__salt__ = {
"cmd.run_all": salt.modules.cmdmod._run_all_quiet,
"cmd.run": salt.modules.cmdmod._run_quiet,
}
def __virtual__():
"""
Load only on Mac OS
"""
if not salt.utils.platform.is_darwin():
return (
False,
"... | "utility only works on MacOS systems.",
)
return __virtualname__
def _run_all(cmd):
"""
Args:
cmd:
Returns:
"""
if not isinstance(cmd, list):
cmd = salt.utils.args.shlex_split(cmd, posix=False)
for idx, item in enumerate(cmd):
if not isinstance... |
QijunPan/ansible | lib/ansible/module_utils/network_common.py | Python | gpl-3.0 | 5,307 | 0.003769 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete wo... | RY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY | OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import socket
import struct
import signal
from ansible.module_utils.basic import get_exception
from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.six import iteritems
def to_list(val):
if isin... |
bmi-forum/bmi-pyre | pythia-0.8/packages/pyre/pyre/geometry/pml/parser/Cylinder.py | Python | gpl-2.0 | 1,012 | 0.005929 | #!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2005 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~... | lids.cylinder(radius=self._radius, height=self._height)
parent.onCylinder(cylinder)
return
def __init__(self, document, attributes):
AbstractNode.__init__(self, attributes)
self._radius = self._parse(attributes["radius"])
self._height = self._parse(attributes["height"])
... | return
# version
__id__ = "$Id: Cylinder.py,v 1.1.1.1 2005/03/08 16:13:45 aivazis Exp $"
# End of file
|
DLR-SC/DataFinder | src/datafinder/gui/user/controller/output/facade.py | Python | bsd-3-clause | 6,124 | 0.009144 | # $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
... | gTableView, self)
self.__resultController = SearchResultController(mainWindow.searchResultTableView, mainWindow,
self, | itemActionController)
self.__resultController.model = searchModel
self.__properties = dict(myRootLogView=self.__rootLogController,
myScriptLogView=self.__scriptLogController,
myResultView=self.__resultController)
... |
chintal/iec60063 | setup.py | Python | lgpl-3.0 | 3,796 | 0.000527 |
"""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
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirnam... | n
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
| # https://packaging.python.org/en/latest/requirements.html
install_requires=[],
# List additional groups of dependencies here (e.g. development
# dependencies). You can install these using the following syntax,
# for example:
# $ pip install -e .[dev,test]
extras_require={},
# If there... |
HEG-Arc/wheel | django/wheel/settings/base.py | Python | gpl-3.0 | 9,098 | 0.005386 | # -*- coding: UTF-8 -*-
"""Common settings and globals."""
import os
from os.path import abspath, basename, dirname, join, normpath
from sys import path
from django.core.exceptions import ImproperlyConfigured
def get_env_variable(var_name):
""" Get the environment variable or return exception """
try:
| return os.environ[var_name]
except KeyError:
error_msg = "Set the %s environment variable" % var_name
raise ImproperlyConfigured(error_msg)
########## PATH CONFIGURATION
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
# Absolute | filesystem path to the top-level project folder:
SITE_ROOT = dirname(DJANGO_ROOT)
# Site name:
SITE_NAME = basename(DJANGO_ROOT)
# Add our project to our pythonpath, this way we don't need to type our project
# name in our dotted import paths:
path.append(DJANGO_ROOT)
########## END PATH CONFIGURATION
########## D... |
jonfoster/pyxb1 | pyxb/binding/datatypes_facets.py | Python | apache-2.0 | 18,254 | 0.009532 | """Generated file that augments the standard schema L{datatype
definitions<pyxb.binding.datatypes>} with their respective
U{constraining facets<http://www.w3.org/TR/xmlschema-2/index.html#rf-facets>}. At
one time, the C{maintainer/xsdfacet.py} script could be used to
generate this. No idea if that's still true.
"""
i... | usive,
duration._CF_maxExclusive,
duration._CF_maxInclusive)
gMonth._CF_pattern = facets.CF_pa | ttern()
gMonth._CF_enumeration = facets.CF_enumeration(value_datatype=gMonth)
gMonth._CF_minExclusive = facets.CF_minExclusive(value_datatype=anySimpleType)
gMonth._CF_whiteSpace = facets.CF_whiteSpace(value=facets._WhiteSpace_enum.collapse)
gMonth._CF_minInclusive = facets.CF_minInclusive(value_datatype=gMonth)
gMonth... |
karas84/whatsapp-launcher | whatsapp-launcher.py | Python | gpl-2.0 | 62,338 | 0.000818 | #!/usr/bin/env python2
# -*- cod | ing: utf-8 -*-
# Created on: 01/28/15
from __future__ import print_function
__author__ = 'karas84'
import gi
gi.require_version('Unity', '7.0')
from gi.repository import Unity, GLib
import threading
import re
import subprocess
import sys
import os
import hashlib
import shutil
import Xlib
from Xlib import X, displ... | y
from queue import Queue
except ImportError:
# noinspection PyCompatibility
from Queue import Queue
badge_queue = Queue()
GLib.threads_init()
_NET_WM_NAME = display.Display().intern_atom('_NET_WM_NAME')
_NET_CLIENT_LIST = display.Display().intern_atom('_NET_CLIENT_LIST')
_NET_CLOSE_WINDOW = display.Displ... |
asapypy/theano_rnn_embed | rnn_theano_embed.py | Python | apache-2.0 | 6,256 | 0.011029 | import numpy as np
import theano as theano
import theano.tensor as T
from utils import *
import operator
import os
import sys
class RNNEMBEDTheano:
def __init__(self, word_dim, hidden_dim=100, embed_dim=100, bptt_truncate=4):
# Assign instance variables
self.word_dim = word_dim
self.hi... | sing backpropagation
backprop_gradient = bptt_gradients[pidx][ix]
# calculate The relative error: (|x - y|/(|x| + |y|))
relative_error = np.abs(backprop_gradient - estimated_gradient)/(np.abs(backprop_gradient) + np.abs(estimated_gradient))
# If the error is to large fail... | eck ERROR: parameter=%s ix=%s" % (pname, ix)
print "+h Loss: %f" % gradplus
print "-h Loss: %f" % gradminus
print "Estimated_gradient: %f" % estimated_gradient
print "Backpropagation gradient: %f" % backprop_gradient
print "Relative Error: ... |
Ameriks/velo.lv | velo/payment/migrations/0005_auto_20190121_1620.py | Python | gpl-3.0 | 518 | 0.001931 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2019-01-21 16:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0004_discountcampaign_discount_kind'),
]
operations = [
migratio... | l=True),
),
]
| |
mariusbaumann/pyload | module/plugins/accounts/RapiduNet.py | Python | gpl-3.0 | 1,907 | 0.007341 | # -*- coding: utf-8 -*-
import re
from time import time
from module.plugins.Account import Account
from module.common.json_layer import json_loads
class RapiduNet(Account):
__name__ = "RapiduNet"
__type__ = "account"
__version__ = "0.05"
__description__ = """Rapidu.net account plugin"""
... | T_PATTERN = r'class="tipsyS"><b>(.+?)<'
def loadAccountInfo(self, user, req):
validuntil = None
trafficleft = -1
premium = False
html = req.load("https://rapidu.net/", decode=True)
if re.search(self.PREMIUM_PATTERN, html):
premium = True
m = re.s... | validuntil = time() + (86400 * int(m.group(1)))
m = re.search(self.TRAFFIC_LEFT_PATTERN, html)
if m:
trafficleft = self.parseTraffic(m.group(1))
return {'validuntil': validuntil, 'trafficleft': trafficleft, 'premium': premium}
def login(self, user, data, req):
req... |
kinoreel/kino-gather | processes/tests/test_get_tmdb.py | Python | mit | 24,240 | 0.00157 | import unittest
import os
import sys
import responses
current_dir = (os.path.abspath(os.path.dirname(__file__)))
sys.path.insert(0, os.path.join(current_dir, '..', '..'))
from processes.get_tmdb import Main, RequestAPI, StandardiseResponse, GatherException
class TestMain(unittest.TestCase):
"""Testing GetAPI"""... | t0083658',
'genres': [{
| 'id': 878,
'name': 'Science Fiction'
}, {
'id': 18,
'name': 'Drama'
}, {
'id': 53,
'name': 'Thrill... |
neale/CS-program | 519-DeepLearning/assignment1/NN/Layers.py | Python | unlicense | 3,014 | 0.010949 | from __future__ import print_function
import numpy as np
""" This will be the interior of the sigmoid cross entropy function,
this is what also will be conputed at each layer. We can vectorize this
simply by using numpy matrix ops. The forward operation is simply a dot(W, x)
and the backward pass will accumulate gra... | or i in xrange(len(x)):
#print ("before ","in:",x[i].shape,"out :",grad[i].shape)
g = np.tile(grad[i][...,None],(1, self.i))
k = np.tile(x[i], (self.o, 1))
deltaW.append(g * k)
deltaB.append(np.dot(grad[i], np.identity(self.o)))
... | deltaB = deltaB.flatten()
mean = np.mean(deltaW, axis=0)
weight_decay = self.l2 * np.linalg.norm(self.W)
update = (m * self.Dw) - (lr * mean)# * weight_decay)
scale = np.linalg.norm(self.W.ravel())
uscale = np.linalg.norm(update.ravel())
... |
alanquillin/quark | quark/segment_allocations.py | Python | apache-2.0 | 11,496 | 0.000087 | # Copyright 2013 Openstack Foundation
# 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 requ... | id %s segment_type %s"
% (allocation["id"], network_id, segment_id,
self.segment_type))
return allocation
except Exception:
LOG.exception("Error in segment reallocation.")
LOG.info("Cannot find reallocatable se... |
% (network_id, segment_id, self.segment_type))
def allocate(self, context, segment_id, network_id):
allocation = self._try_allocate(
context, segment_id, network_id)
if allocation:
return allocation
raise quark_exceptions.SegmentAllocationFailure(... |
Breakthru/splitbills | finance/main.py | Python | gpl-3.0 | 2,074 | 0.010608 | import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget,QTableWidgetItem,QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 table - pythonspot.com'
... | ble selection change
self.tableWidget.doubleClicked.connect(self.on_click)
@pyqtSlot()
def on_click(self):
print("\n")
for currentQTableWidgetItem in self.tableW | idget.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
|
Z2PackDev/TBmodels | tests/test_supercell.py | Python | apache-2.0 | 4,214 | 0.000475 | #!/usr/bin/env python
"""Tests for constructing supercell models."""
import itertools
import numpy as np
from numpy.testing import assert_allclose
import pytest
from parameters import KPT, T_VALUES
import tbmodels
def get_equivalent_k(k, supercell_size):
return itertools.product(
*[
(np.li... | le, supercell_size):
"""
Test that the eigenvalues from a supercell model match the folded
eigenvalues of the base model, for the realistic InAs model.
"""
model = tbmodels.io.load(sample("InAs_nosym.hdf5"))
supercell_model = model.supercell(size=supercell_size)
for k in [(-0.4, 0.1, 0.45), ... | et_equivalent_k(k, supercell_size)
ev_folded = np.sort(
np.array([model.eigenval(kval) for kval in equivalent_k]).flatten()
)
assert ev_supercell.shape == ev_folded.shape
assert_allclose(ev_supercell, ev_folded, atol=1e-7)
def test_supercell_model_equal(sample, models_close... |
gmr/hockeyapp | backup/hockeyapptest.py | Python | bsd-3-clause | 963 | 0.006231 |
from unittest2 import TestCase
import os
import sys
import yaml
class TestConfig:
def __init__(self, data):
self.data = data
@property
def api_key_read_only(self):
return self.data["api_key_read_only"]
@property
def api_key_read_write(self):
return self.data["api_key_rea... | @property
def app_id(self):
return self.data["app_id"]
@property
def user(self):
return | self.data['user']
class HockeyAppTestCase(TestCase):
def setUp(self):
config_file = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'test-config.yml'))
if not os.path.exists(config_file):
print "CONFIG ERROR: Copy test-config.yml.example t... |
switchkiller/Python-and-Algorithms-and-Data-Structures | src/bitwise/set_bit.py | Python | mit | 659 | 0.013657 | #!/usr/bin/env python
__author__ = "bt3"
''' Set a bit in a binary number:
1) Shifts 1 over by i bits
2) make an OR with the number, only the va | lue at bit i will change and all the others bit
of the mask are zer | o so will not affect the num
'''
def set_bit(num, i):
mask = 1 << i
return bin( num | mask )
if __name__ == '__main__':
num = int('0100100', 2)
print set_bit(num, 0) #'0b100101'
print set_bit(num, 1) #'0b100110'
print set_bit(num, 2) # nothing change '0b100100'
print set_bit(num, 3... |
mahak/neutron | neutron/cmd/ovs_cleanup.py | Python | apache-2.0 | 2,691 | 0 | # Copyright (c) 2012 OpenStack Foundation.
# 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... | ware
# 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 oslo_config import cfg
from oslo_log import log as ... | eutron.conf.agent import cmd
from neutron.conf.agent import common as agent_config
from neutron.conf.agent.l3 import config as l3_config
from neutron.conf.plugins.ml2.drivers import ovs_conf
from neutron.conf import service as service_config
LOG = logging.getLogger(__name__)
# Default ovsdb_timeout value for this scr... |
akarol/cfme_tests | fixtures/pytest_store.py | Python | gpl-2.0 | 6,628 | 0.002112 | """Storage for pytest objects during test runs
The objects in the module will change during the course of a test run,
so they have been stashed into the 'store' namespace
Usage:
# as pytest.store
import pytest
pytest.store.config, pytest.store.pluginmanager, pytest.store.session
# imported directly ... | DRESS']
except KeyError:
# Fall back to having an appliance tell us what it thinks our IP
# address is
return self.current_appliance.ssh_client.client_address()
def write_line(self, line, **kwargs):
return write_line(line, **kwargs)
store = Store()
def pytest... | call to this hook
if store.config is None:
store.config = manager.getplugin('pytestconfig')
def pytest_sessionstart(session):
store.session = session
def write_line(line, **kwargs):
"""A write-line helper that should *always* write a line to the terminal
It knows all of py.tests dirty tric... |
indautgrp/frappe | frappe/website/doctype/blog_category/test_blog_category.py | Python | mit | 211 | 0.004739 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unico | de_literals
import frappe
te | st_records = frappe.get_test_records('Blog Category') |
dims/neutron | neutron/tests/api/test_subnetpools.py | Python | apache-2.0 | 14,988 | 0 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
# 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... | xes[0], prefixes)
@test.attr(type='smoke')
@test.idempotent_id('2cae5d6a-9d32-42d8-8067-f13970ae13bb')
def test_update_subnetpool_prefixes_extend(self):
# We can extend current subnetpool prefixes
created_subnetpool = self._create_subnetpool()
| pool_id = created_subnetpool['id']
old_prefixes = self._subnetpool_data['prefixes']
subnetpool_data = {'prefixes': [self.larger_prefix]}
self.client.update_subnetpool(pool_id, **subnetpool_data)
body = self.client.show_subnetpool(pool_id)
prefixes = body['subnetpool']['pre... |
PoornimaNayak/autotest-client-tests | cgroup_tests/memory_limit_test.py | Python | gpl-2.0 | 8,025 | 0.000249 | import os
import subprocess
import time
import logging
from autotest.client import utils
from autotest.client.shared import error, utils_cgroup
class MemoryLimit(object):
"""
Test memory sub system.
Use it to control memory resource.
1. Clear all cgroups and init modules and parent cgroup.
2. C... | ould equal with memory use")
def execute(cgroup_cls):
"""
Execute memory test.
:param cgroup_cls: Cgrou | p class
"""
if cgroup_cls is None:
raise error.TestNAError("Got a none cgroup class")
memory_limit_test = MemoryLimit(cgroup_cls._cgroup_dir, cgroup_cls.tmpdir,
cgroup_cls.bindir)
memory_limit_test.test()
|
csirtgadgets/cif-sdk-py | test/test_bind.py | Python | lgpl-3.0 | 1,103 | 0.003626 | from cifsdk.format.cifbind import Bind
import re
def test_format_bind():
data = [
{
'observable': "example.com",
'provider': "me.com",
'tlp': "amber",
'confidence': "85",
'reporttime': '2015-01-01T00:00:00Z',
'otype': 'fqdn'
... | 5",
'reporttime': '2015-01-01T00:00:00Z',
'otype': 'fqdn'
},
]
text = str(Bind(data))
assert re.findall(r'^// generated by: CIF at \S+', t | ext)
assert re.findall(r'\nzone "example.com" {type master; file "\S+";};\n', text)
assert re.findall(r'\nzone "example3.com" {type master; file "\S+";};', text)
if __name__ == '__main__':
test_format_bind() |
petekalo/django-sphinx-db | setup.py | Python | bsd-3-clause | 1,297 | 0.020046 | #!/bin/env python
import os
from distutils.core import setup
name = 'django_sphinx_db'
version = '0.1'
release = '3'
versrel = version + '-' + release
readme = os.path.join(os.path.dirname(__file__), 'README.rst')
download_url = 'https://github.com/downloads/smartfile/django-sphinx-db' \
'/... | icense = 'MIT',
packages = [
"django_sphinx_db",
"django_sphinx_db.backend",
"django_sphinx_db.backend.sphinx",
"django_sphinx_db.management",
"django_sphinx_db.management.commands",
],
classifiers = (
'Development Status :: 4 - Beta',
'Intended Au... | n Modules',
),
)
|
Pikecillo/genna | external/PyXML-0.8.4/test/dom/test_demo.py | Python | gpl-2.0 | 912 | 0.014254 | #!/usr/bin/env python
import os
def test(testSuite):
#rt = os.system("cd ../demo && python dom_from_html_file.py employee_table.html")
#if rt:
# return 0
rt = os.system("cd ../demo && python dom_from_xml_file.py addr_book1.xml")
| if rt:
return 0
#os.system("cd ../demo && python generate_html1.py")
#if rt:
# return 0
rt = os.system("cd ../demo && python iterator1.py addr_book1.xml")
if rt:
return 0
r | t = os.system("cd ../demo && python visitor1.py addr_book1.xml")
if rt:
return 0
rt = os.system("cd ../demo && python trace_ns.py book_catalog1.xml")
if rt:
return 0
rt = os.system("cd ../demo && python xll_replace.py addr_book1.xml")
if rt:
return 0
rt = os.system("c... |
DoWhatILove/turtle | programming/python/data_visualization/die.py | Python | mit | 325 | 0 | from random import randint
class Die():
'''A class representing a single die'''
def __init__(self, num_sides=6):
| '''assume a six-side die'''
self.num_sides = num_sides
def roll(self):
'''return a random number between 1 and number of sides'''
return randint(1, self.num_sides)
| |
b-cube/pipeline-demo | demo/bcube_owslib/swe/common.py | Python | mit | 17,850 | 0.013445 | from __future__ import (absolute_import, division, print_function)
from bcube_owslib.util import nspath_eval
from bcube_owslib.namespaces import Namespaces
from bcube_owslib.util import testXMLAttribute, testXMLValue, InfiniteDateTime, NegativeInfiniteDateTime
from dateutil import parser
from datetime import timedelt... | estXMLValue(x)) for x in element.findall(nspv("swe20:interval"))])
self.significantFigures = get_int(te | stXMLValue(element.find(nspv("swe20:significantFigures")))) # integer, min=0
class Boolean(AbstractSimpleComponent):
def __init__(self, element):
super(Boolean, self).__init__(element)
# Elements
"""
6.2.1 Boolean
A Boolean representation of a... |
zpincus/celltool | celltool/numerics/image_warp.py | Python | gpl-2.0 | 5,013 | 0.008378 | # Copyright 2007 Zachary Pincus
# This file is part of CellTool.
#
# CellTool is free software; you can redistribute it and/or modify
# it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
from scipy import ndimage
import numpy
def warp_images(from_points, ... | tra | nsform_y = t00*x1*y1 + t01*x1*y_fracs + t10*x_fracs*y1 + t11*x_fracs*y_fracs
transform = [transform_x, transform_y]
return transform
_small = 1e-100
def _U(x):
return (x**2) * numpy.where(x<_small, 0, numpy.log(x))
def _interpoint_distances(points):
xd = numpy.subtract.outer(points[:,0], points[:,... |
cpwr/mediasite | app/api/__init__.py | Python | gpl-2.0 | 17 | 0 | fr | om . import v1
| |
Khushbu27/Tutorial | test/functional/test_container.py | Python | apache-2.0 | 57,149 | 0 | #!/usr/bin/python
# Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | r-Meta-Test': value})
return check_response(conn)
def head(url, token, parsed, conn, name):
conn.request('HEAD', parsed.path + '/' + name, '',
{'X-Auth-Token': token})
return check_response(conn)
def get(url, token, parsed, conn, name):
... | esponse(conn)
def delete(url, token, parsed, conn, name):
conn.request('DELETE', parsed.path + '/' + name, '',
{'X-Auth-Token': token})
return check_response(conn)
name = uuid4().hex
resp = retry(put, name, 'Value')
resp.read()
s... |
tdyas/pants | src/python/pants/base/exception_sink.py | Python | apache-2.0 | 23,733 | 0.003792 | # Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import datetime
import faulthandler
import logging
import os
import signal
import sys
import threading
import traceback
from contextlib import contextmanager
from typing import Callable, I... | dle_sigterm(self, signum, _frame):
raise self.SignalHandledNonLocalExit(signum, "SIGTERM")
class E | xceptionSink:
"""A mutable singleton object representing where exceptions should be logged to."""
# NB: see the bottom of this file where we call reset_log_location() and other mutators in order
# to properly setup global state.
_log_dir = None
# We need an exiter in order to know what to do after ... |
immstudios/nebula-core | nebulacore/constants/run_modes.py | Python | gpl-3.0 | 439 | 0.020501 | RUN_AUTO = 0 # First item of this block is cued right after | last item of previous block
RUN_MANUAL = 1 # Playback stops at the end of the last item of previous block
RUN_SOFT = 2 # First item of this block is cued if previous block is running and current_time >= scheduled_time
RUN_HARD = 3 # First | item of this block starts immediately if previous block is running and current_time >= scheduled_time
RUN_SKIP = 4
|
grit-engine/grit-engine | dependencies/quex-0.34.1/quex/core_engine/state_machine/setup_pre_context.py | Python | mit | 3,013 | 0.008297 | #! /usr/bin/env python
import sys
import os
sys.path.insert(0, os.environ["QUEX_PATH"])
from copy import deepcopy
from quex.core_engine.state_machine.core import *
import quex.core_engine.state_machine.nfa_to_dfa as nfa_to_dfa
import quex.core_engine.state_machine.hopcroft_minimization as hopcroft
def do(the_state_... | inverse_pre_context)
pre_context_sm_id = | inverse_pre_context.get_id()
# (*) create origin data, in case where there is none yet create new one.
# (do not delete, otherwise existing information gets lost)
for state in the_state_machine.states.values():
if not state.is_acceptance(): continue
state.core().set_pre_context_id(pre_c... |
tukeJonny/NTPAmpMitigator | infra/utils.py | Python | mit | 960 | 0.012397 | #-*- coding: utf-8 -*-
#既存のフロールールを全て一旦削除
#それらのフロールールで指定していたMatchにIPアドレス情報(サブネット)を追加
#mi | tigate時はなんでもPacket-Inするルールは不要なので削除したまま
#mitigate後はなんでもPacket-Inするルールから突っ込んでいく
import logging
import socket
import struct
import ipaddress
#packet_in_handlerにて、受け取ったパケットのipv4がsubnetに属するか調べるのに必要
def is_ipv4_belongs_to_network(ipv4, network):
# netmask -> CIDR
| network, netmask = network
network_address = socket.inet_pton(socket.AF_INET, netmask)
cidr_value = bin(struct.unpack('!L', network_address)[0])[2:].index('0')
cidr = "{network}/{cidr_value}".format(**locals())
#check
ipv4 = ipaddress.ip_address(ipv4)
ipv4_network = ipaddress.ip_network(cidr.de... |
opatut/dudel | migrations/versions/2758f36a2fb5_initial.py | Python | gpl-3.0 | 4,644 | 0.015719 | """Initial table layout
Revision ID: 2758f36a2fb5
Revises: None
Create Date: 2014-03-11 09:56:35.692538
"""
# revision identifiers, used by Alembic.
revision = '2758f36a2fb5'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adju... | ], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('vote_choice',
sa.Column('id', sa | .Integer(), nullable=False),
sa.Column('comment', sa.String(length=64), nullable=True),
sa.Column('value_id', sa.Integer(), nullable=True),
sa.Column('vote_id', sa.Integer(), nullable=True),
sa.Column('choice_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['choice_id'], ['choice.id'], ),... |
huihoo/reader | apps/profile/models.py | Python | mit | 36,785 | 0.00908 | import time
import datetime
import stripe
import hashlib
import redis
import mongoengine as mongo
from django.db import models
from django.db import IntegrityError
from django.db.utils import DatabaseError
from django.db.models.signals import post_save
from django.db.models import Sum, Avg, Count
from django.conf impor... | : self.is_premium,
'preferences': json.decode(self.preferences),
'tutorial_finished': self.tutorial_finished,
'hide_getting_started': self.hide_getting_started,
'has_setup_feeds': self.has_setup_feeds,
'has_found_friends': self.has_ | found_friends,
'has_trained_intelligence': self.has_trained_intelligence,
'dashboard_date': self.dashboard_date
}
def save(self, *args, **kwargs):
if not self.secret_token:
self.secret_token = generate_secret_token(self.user.username, 12)
try:
... |
mlukasik/rumour-classification | main/postprocessing.py | Python | lgpl-3.0 | 1,647 | 0.009715 | '''
Copyright (c) 2014-2015, The University of Sheffield.
This file is part of the SDQ rumour classification software
(see https://github.com/mlukasik/rumour-classification),
and is free software, licenced under the GNU Library General Public License,
Version 2, June 1991 (in the distribution as file LICENSE).
Crea... | metric):
'''
Process results - overwrite their old content by
the mean 'metric' value over the | old content.
'''
for method in results.keys():
max_train=max(results[method].keys())
for train_perc in sorted(results[method].keys()):
samples=len(results[method][train_perc])
metric_val=np.mean([metric(a, b, train_perc=train_perc, max_train=max_train)
... |
openstack/keystone | keystone/assignment/schema.py | Python | apache-2.0 | 1,123 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use th | is 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 KI... | fic language governing permissions and limitations
# under the License.
from keystone.assignment.role_backends import resource_options as ro
from keystone.common.validation import parameter_types
# Schema for Identity v3 API
_role_properties = {
'name': parameter_types.name,
'description': parameter_types.de... |
jlec/ssllabs | ssllabsscanner.py | Python | mit | 1,310 | 0.046565 | #!/usr/bin/env python
"""Add Docstring"""
import requests
import time
API = "https://api.ssllabs.com/ap | i/v2/"
def requestAPI(path, payload={}):
"""This is a helper method that takes the path to the relevant
API call and the user-defined payload and requests the
data | /server test from Qualys SSL Labs.
Returns JSON formatted data"""
url = API + path
try:
response = requests.get(url, params=payload)
except requests.exception.RequestException as e:
print e
sys.exit(1)
data = response.json()
return data
def resultsFromCache(host, publish = "off", startNew = "off",... |
audip/doctorsfor.me | app/backup/_routes.py | Python | apache-2.0 | 618 | 0.008091 | from app import app, con, api
base_url = '/api'
parser = reqparse.RequestParser()
cursor = con.cursor()
class UserAPI(Resource):
| def get(self, id):
return {'hello': 'world'}
def put(self, id):
pass
def post(self, id):
pass
class LoginAPI(Resource):
def post(self):
args = parser.parse_args()
username =
sql_query = 'SELECT * FROM User WHERE '
class SignupAPI(Resource):
def pos... | int:id>', endpoint='user')
api.add_resource(LoginAPI, base_url + '/user/login', endpoint='login') |
lbovet/mechos | control/control_view.py | Python | gpl-3.0 | 1,057 | 0.013245 | ## Copyright 2011 Laurent Bovet <laurent.bovet@windmaster.ch>
##
## This file is part of Mechos
##
## Mechos is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation | , either version 3 of the License, or
## (at your option) any later version.
##
## 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 mor... | If not, see <http://www.gnu.org/licenses/>.
import gtk
import logging
class View(object):
logger = logging.getLogger("control.view")
def __init__(self, parent):
frame = gtk.Frame("Control")
frame.set_size_request(*parent.get_size_request())
parent.add(frame)
frame.show()
... |
cwarden/muttils | setup.py | Python | gpl-2.0 | 2,206 | 0.003626 | #!/usr/bin/env python
# $Id$
import sys
if not hasattr(sys, 'version_info') or sys.version_info < (2, 4):
raise SystemExit, 'Muttils requires Python 2.4 or later'
from distutils.core import setup
import os.path, subprocess, time
# simplified hg versioning
def runhg(cmd):
out, err = subprocess.Popen(['hg']... | runhg(cmd) + v[0]
if version.endswith('+'):
version += time.strftime('%Y%m%d')
elif os.path.isfile('.hg_archival.txt'):
kw = dict([[t.strip() for t in l.split(':', 1)]
for l in open('.hg_archival.txt')])
if 'tag' in kw:
version = kw['tag']
elif 'latesttag' in kw:
... | se:
version = kw.get('node', '')[:12]
if version:
fp = open('muttils/__version__.py', 'w')
fp.write('# this file is autogenerated by setup.py\n')
fp.write('version = "%s"\n' % version)
fp.close()
try:
from muttils import __version__
version = __version__.version
except ImportError:
... |
mic4ael/indico | indico/migrations/versions/20200331_1251_3c5462aef0b7_review_conditions_editable_types.py | Python | mit | 845 | 0.001183 | """Associate review-conditions with editable types
Revision ID: 3c5462aef0b7
Revises: 6444c893a21f
Create Date: 2020-03-31 12:51:40.822239
"""
from alembic import op
# revision identifiers, used by Alembic.
r | evision = '3c5462aef0b7'
down_revision = '6444c893 | a21f'
branch_labels = None
depends_on = None
def upgrade():
op.execute("""
UPDATE events.settings
SET name = 'paper_review_conditions'
WHERE module = 'editing' AND name = 'review_conditions'
""")
def downgrade():
op.execute("""
UPDATE events.settings
SET name = 'r... |
realms-team/basestation-fw | libs/smartmeshsdk-REL-1.3.0.1/libs/VManagerSDK/vmanager/models/blacklist_read_info.py | Python | bsd-3-clause | 3,125 | 0.00096 | # coding: utf-8
"""
Copyright 2015 SmartBear Software
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... | d 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 Licens | e for the specific language governing permissions and
limitations under the License.
Ref: https://github.com/swagger-api/swagger-codegen
"""
from pprint import pformat
from six import iteritems
class BlacklistReadInfo(object):
"""
NOTE: This class is auto generated by the swagger code generator prog... |
cwurld/django-phonegap | django_phonegap/__init__.py | Python | bsd-3-clause | 127 | 0.007874 | #!/usr/bin/env python
# -*- cod | ing: utf-8 -*-
__author__ = 'Chuck Martin'
__email__ = 'cwurld@yahoo.com'
__vers | ion__ = '0.1.0' |
makinacorpus/Geotrek | geotrek/flatpages/helpers_sync.py | Python | bsd-2-clause | 988 | 0.005061 | import os
from geotrek.flatpages.models import FlatPage
from geotrek.flatpages.views import FlatPageViewSet, FlatPageMeta
from django.db.models import Q
class SyncRando:
def __init__(self, sync):
self.global_sync = sync
def sync(self, lang):
self.global_sync.sync_geojson(lang, FlatPageViewS... | flatpages = flatpages.filter(Q(portal__name=self.global_sync.portal) | Q(portal=None))
for flatpage in flatpages:
name = os.path.join('meta', lang, flatpage.rando_url, 'index.html')
self.global_sync.sync_view(lang, FlatPageMeta.as_view(), name, pk=flatpage.pk,
... | url})
|
imtapps/generic-request-signer | generic_request_signer/check_signature.py | Python | bsd-2-clause | 2,169 | 0.001383 | import hashlib
import apysigner
import re
from generic_request_signer import constants
def generate_hash_for_binary(binary_data):
return {'binary_data': hashlib.md5(str.encode(binary_data)).hexdigest()}
def check_signature_for_binary(signature, private_key, full_path, binary):
binary_hash = generate_hash_f... | ture, private_key, full_path, payload):
"""
Checks signature received and verifies that we are able to re-create
it from the private key, path, and payload given.
:param signature:
Signature receive | d from request.
:param private_key:
Base 64, url encoded private key.
:full_path:
Full path of request, including GET query string (excluding host)
:payload:
The request.POST data if present. None if not.
:returns:
Boolean of whether signature matched or not.
"""
... |
tonk/ansible | lib/ansible/plugins/action/__init__.py | Python | gpl-3.0 | 58,185 | 0.003609 | # coding: utf-8
# Copyright: (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# Copyright: (c) 2018, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__m... | eritems, with_metaclass
from ansible.module_utils.six.moves import shlex_quote
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.parsing.utils.jsonify import jsonify
from ansible.release import __version__
from ansible.utils.display import | Display
from ansible.utils.unsafe_proxy import wrap_var, AnsibleUnsafeText
from ansible.vars.clean import remove_internal_keys
display = Display()
class ActionBase(with_metaclass(ABCMeta, object)):
'''
This class is the base class for all action plugins, and defines
code common to all actions. The base... |
harmsm/phylo_tools | compareAncestors.py | Python | unlicense | 4,269 | 0.007027 | #!/usr/bin/env python
__description__ = \
"""
compareAncestor.py
"""
__author__ = "Michael J. Harms"
__usage__ = "comapreAncestors.py ancestor_file1 ancestor_file2"
__date__ = "100726"
import sys, phyloBase
class CompareAncestorError(Exception):
"""
General error class for this module.
"""
pass
... | ed well supported
else:
ambig_state = " "
check_me = " "
if ambig_state == "-" or \
(same == "*" and ambig_state == " "):
check_me = "!"
out.append("%5i %s %s %s %s %s %6.2f%6.2f %s\n" % (p,s1[0][0],s2[0][0],
same,flipped,ambig_sta... | ile = argv[0]
ancestor2_file = argv[1]
except IndexError:
err = "Incorrect number of arguments!\n\n%s\n\n" % __usage__
raise CompareAncestorError(err)
out = compareAncestors(ancestor1_file,ancestor2_file)
print out
if __name__ == "__main__":
main()
|
red-hood/calendarserver | txdav/common/datastore/test/test_trash.py | Python | apache-2.0 | 75,866 | 0.001529 | ##
# Copyright (c) 2015 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | txn = self.store.newTransaction()
| # Not in trash
resource = yield self._getResource(txn, "user01", trash.name(), "")
self.assertTrue(resource is None)
# One object in collection
resourceNames = yield self._getResourceNames(txn, "user01", "calendar")
self.assertEqual(len(resourceNames), 1)
resourc... |
estaban/pyload | module/plugins/hoster/MegareleaseOrg.py | Python | gpl-3.0 | 1,724 | 0.00116 | # -*- coding: utf-8 -*-
############################################################################
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU Affero General Public License as #
# published by the Free Software Foundation, either version 3 of ... | #
# 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 Aff | ero 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/>. #
#####################... |
c2corg/v6_ui | c2corg_ui/format/header.py | Python | agpl-3.0 | 2,420 | 0 | import markdown
from markdown.blockprocessors import BlockProcessor
from markdown import util
import re
import logging
logger = logging.getLogger('MARKDOWN')
# copied from class markdown.blockprocessors.HashHeaderProcessor
class C2CHeaderProcessor(BlockProcessor):
""" Process Hash Headers. """
# Detect a he... | ock):
return bool(self.RE.search(block))
def run(self, parent, blocks):
block = blocks.pop(0)
m = self.RE.search(block)
if m:
before = block[:m.start()] # All lines before header
after = block[m.end():] # All lines after header
if before:
... |
self.parser.parseBlocks(parent, [before])
# Create header using named groups from RE
h = util.etree.SubElement(parent, 'h%d' % len(m.group('level')))
h.text = m.group('header').strip()
if m.group("fixed_id"):
h.set('id', m.group("fixed_id... |
jonashaag/django-autocomplete-light | test_project/charfield_pk_autocomplete/models.py | Python | mit | 590 | 0.00339 | from django.db import models
from django.utils.translation import ugettext_lazy as _
class Media(models.Model):
code = models.CharField(_(u'Code'), max_length=128, null=False,
b | lank=False, primary_key=True)
name = models.CharField(_('Name'), max_length=128, null=True,
blank=True)
class Meta:
verbose_name_plural = "media"
def __unicode__ | (self):
return self.name
class MediaFilter(models.Model):
media = models.ForeignKey(Media, verbose_name=_("Media"))
def __unicode__(self):
return u"Filter for %s" % self.media.name
|
openstack/nova | nova/tests/unit/pci/test_utils.py | Python | apache-2.0 | 15,220 | 0.000131 | # Copyright (c) 2013 Intel, Inc.
# Copyright (c) 2012 OpenStack Foundation
# 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/li... | 6")
self.assertEqual(self.parse_result, ('0000', '04', '12', '6'))
def test_parse_address_wrong(self):
self.assertRaises(exception.PciDeviceWrongAddressFormat,
utils.parse_address, "0000:04.12:6")
def | test_parse_address_invalid_character(self):
self.assertRaises(exception.PciDeviceWrongAddressFormat,
utils.parse_address, "0000:h4.12:6")
class GetFunctionByIfnameTestCase(test.NoDBTestCase):
@mock.patch('os.path.isdir', return_value=True)
@mock.patch.object(os, 'readlink')
def test_v... |
updownlife/multipleK | dependencies/biopython-1.65/Tests/test_LogisticRegression.py | Python | gpl-2.0 | 3,292 | 0.001519 | # Copyright 2004-2008 by Michiel de Hoon. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
# See the Biopython Tutorial for an explanation of the biological
# background of these... | , 0, 1, 1, 1, 1, 1, 1, 1, 1 | , 0, 0, 0, 0, 0, 0, 0]
for i in range(len(predictions)):
prediction = LogisticRegression.classify(model, xs[i])
self.assertEqual(prediction, predictions[i])
if prediction==ys[i]:
correct+=1
self.assertEqual(correct, 16)
def test_leave_one_out(self... |
decemcat/gpyblog | app.py | Python | gpl-2.0 | 1,295 | 0.004633 | import os
import os.path
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import const
import importlib
from config import ConfigReader
def convert_arr(handlers):
last_arr = []
for handler in handlers:
hans = handler[1].split(":")
last_arr.append((handl... | plit(":")
last_dict[key] = getattr(importlib.import_module(hans[0]), hans[1])
return last_dict
if __name__ == '__main__':
cr = ConfigReader()
handlers = cr.readAll(const.HANDLER_CONF, const.HA | NDLER_SECTION)
modules = cr.readAsDic(const.MODULE_CONF, const.UIMODULE_SECTION)
app = tornado.web.Application(
handlers=convert_arr(handlers),
template_path=os.path.join(os.path.dirname(__file__), 'templates'),
static_path=os.path.join(os.path.dirname(__file__), 'static'),
ui_m... |
ntt-sic/cinder | cinder/openstack/common/periodic_task.py | Python | apache-2.0 | 6,920 | 0 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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 applicab... | , so, go ahead an initialize it. If the attribute is present,
# then we're a subclass so make a copy of it so we don't step on our
# parent's toes.
try:
cls._periodic | _tasks = cls._periodic_tasks[:]
except AttributeError:
cls._periodic_tasks = []
try:
cls._periodic_last_run = cls._periodic_last_run.copy()
except AttributeError:
cls._periodic_last_run = {}
try:
cls._periodic_spacing = cls._periodic_spac... |
doctorzeb8/django-era | era/apps/user/views.py | Python | mit | 7,414 | 0.000944 | import string
from django import forms
from django.conf import settings
from django.contrib import auth
from django.contrib.auth import get_user_model
from django.contrib.auth.hashers import get_hasher
from django.utils.text import capfirst
from era import _
from era.views import BaseView, FormView, CollectionView, O... | 'link',
'link': 'reset'}]
def prepare_form(self, form):
form = super().prepare_form(form)
form.fields['password'].widget = forms.PasswordInput()
return form
def process_valid(self, form, **kw):
user = auth.authenticate(**for | m.cleaned_data)
if user:
if Confirm.objects.filter(user=user, key='registration').count():
self.send_message('error', _('sorry, unconfirmed data'))
else:
return self.process_login(user)
else:
self.send_message('error', _('sorry, invalid... |
hernanramirez/django-example | examples_prj/examples_prj/settings/local.py | Python | gpl-2.0 | 1,544 | 0 | """Development settings and globals."""
from __future__ import absolute_import
from os.path import join, normpath
from .base import *
# DEBUG CONFIGURATION
# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug
DEBUG = True
# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug
TEMPLA... | ettings/#caches
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
}
}
# END CACHE CONFIGURATION
# TOOLBAR CONFIGURATION
# See:
# http://django-debug-toolbar.readthedocs.org/en/latest/installation.html#explicit-setup
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWA... | S += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
DEBUG_TOOLBAR_PATCH_SETTINGS = False
# http://django-debug-toolbar.readthedocs.org/en/latest/installation.html
INTERNAL_IPS = ('127.0.0.1',)
# END TOOLBAR CONFIGURATION
|
lesguillemets/gae_twbots | colors/colors.py | Python | mit | 3,088 | 0.009394 | #!/usr/bin/env python2
# coding:utf-8
from twython import Twython
from colors import const
#import const
import numpy as np
import PIL.Image as img
import colorsys
import StringIO
import os
fr | om datetime import datetime
from datetime import timedelta
from random import randint
number_of_colours = 1094
def is_morning():
return 6 <= (datetime.utcnow() + timedelta(hours=9)).hour <= 9
class Colour(object):
def __init__(self, name, hexcode, url):
self.name = name
# 0-255
self.h... | int(hexcode[i:i+2],16) for i in range(0,6,2)
)
self.hsv = tuple(
colorsys.rgb_to_hsv(*map(lambda x: x/255.0, self.rgb)))
self.url = url or "https://en.wikipedia.org/wiki/{}".format(
name.replace(' ','_'))
@staticmethod
def from_string(line):
... |
lino-framework/book | lino_book/projects/dumps/c/dumps_foo_2.py | Python | bsd-2-clause | 256 | 0.035156 | # -*- coding: UTF-8 -*-
logger.info("Loading 3 objects (part 2 of 2) to table dumps_foo...")
# fields: id, designation, last_visit, bar
loader.save(create_d | umps_foo(3,['Three', 'Drei', 'Trois'],dt(2017,10,29,3,16,6),'10'))
loader.flush_deferred_objects | ()
|
quentinbodinier/custom_gnuradio_blocks | python/__init__.py | Python | gpl-3.0 | 1,615 | 0.001858 | #
# Copyright 2008,2009 Free Software Foundation, Inc.
#
# This application is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This application is di... |
'''
This is the GNU Radio CUSTOM_BLOCKS module. Place your Python package
description here (python/__init__.py).
'''
# import swig generated symbols into the custom_blocks namespace
try:
# this might fail if the module is python-only
from custom_blocks_swig import *
except ImportError:
pass
# import any pure pyt... | ptor import triggered_vector_interruptor
from vector_selector import vector_selector
from interference_predictor import interference_predictor
from moving_average import moving_average
from complex_to_power import complex_to_power
from input_selector import input_selector
from rephaser import rephaser
#
|
haiyangd/spotter | setup.py | Python | mit | 1,250 | 0.028 | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'spotter',
version = '1.7',
url = "http://github.com/borntyping/spotter",
author | = "Sam Clements",
author_email = "sam@borntyping.co.uk",
description = "A command line tool for watching files and running shell commands when they change.",
long_description = open('README.rst').read(),
license = 'MIT',
classifiers = [
'Development Status ... | Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Operating System :: Unix',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
... |
bqlabs/rainbow | rainbow/avahi.py | Python | gpl-2.0 | 908 | 0.001103 | # -*- coding: utf-8 -*-
# This file is part of the Rainbow Project
__author__ = 'Jesús Arroyo Torrens'
__email__ = 'jesus.arroyo@bq.com'
__copyright__ = 'Copyright (c) 2015 Mundo Reader S.L.'
__license__ = 'GPLv2'
def run():
_service = None
name = 'avahi-daemon'
try:
import time
import ps... | ame],
shell=False,
stdin=None,
stdout=None,
stderr=None,
close_fds=True)
_service = psutil.Process(subp.pid)
except:
| pass
return _service
def kill(_service=None):
if _service:
_service.kill()
|
sfcta/BikeRouter | Bike Model/bike_model/config/bike_network_config.py | Python | gpl-3.0 | 697 | 0.057389 | import os
from route_model.config.network_config import NetworkConfig
class BikeNetworkConfig(NetworkConfig):
"""store network configuration data"""
def __init__ | (self, changes={}):
NetworkConfig.__init__(self)
self['data_dir']=r"X:\Projects\BikeModel\data\bike_model\input\network\2010_04_10"
self['link_file']=os.path.join(self['data_dir'],'links.csv')
self['node_file']=os.path.join(self['data_dir'],'nodes.csv')
sel | f['dist_var']='DISTANCE'
self['dist_scl']=1/5280 #rescales with node distance x dist_scl= link distance
self['max_centroid']=2454
self['exclude_group']={'FT':('in',[1,2,101,102])}
self['use_dual']=True
for key in changes:
self[key]=changes[key]
|
OscarES/serpentinetracker | examples/optimisation/twoQuadExample.py | Python | gpl-3.0 | 1,666 | 0.013205 | import pylab as pl
import scipy | as sp
import serpentine as st
import latticeloader as ll
from | elements import *
import beamline
class twoQuadExample :
def __init__(self) :
# set twiss parameters
self.t = {}
self.t['betax'] = 6.85338806855804
self.t['alphax'] = 1.11230788371885
self.t['etax'] = 3.89188697330735e-012
self.t['etaxp'] = 63.1945125619190e-01... |
DmitriyFromBSUIR/Home_Automation_Server | Registration_Service/HTTP_Client.py | Python | apache-2.0 | 1,950 | 0.006154 | import sys
import ujson
from tornado import gen
import tornado.options
import tornado.ioloop
import tornado.httputil
import tornado.httpclient
from tornado.escape import json_decode, json_encode
import ssl
import aiohttp
if sys.platform == 'win32':
LinkAddressPackFilepath = "/home/root/Python_Workspace/HTTP_Client... | ST', body=body, headers="Content-Type: application/json")
raise gen.Return(response)
@tornado.gen.coroutine
def request():
data = read_json()
body = json_encode(data)
#http_response = yield json_fetch(http_cli | ent, body)
http_client = tornado.httpclient.AsyncHTTPClient()
http_response = yield json_fetch(http_client, body)
print(http_response.body)
if __name__ == "__main__":
tornado.options.parse_command_line()
#http_client = tornado.httpclient.AsyncHTTPClient()
#request(http_client)
tornado.iolo... |
south-coast-science/scs_core | src/scs_core/aws/data/byline.py | Python | mit | 8,542 | 0.005502 | """
Created on 25 Dec 2018
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
example:
{"device": "scs-bgx-401", "topic": "south-coast-science-demo/brighton/loc/1/climate",
"lastSeenTime": "2020-10-23T08:52:20Z", "last_write": "2020-10-23T08:52:20Z",
"message": "{\"val\": {\"hmd\": 68.4, \"tmp\": 19.8, \"bar\... | --------------------------------------------------------------
@property
def device(self):
| return self.__device
@property
def topic(self):
return self.__topic
@property
def pub(self):
return self.__pub
@property
def rec(self):
return self.__rec
@property
def message(self):
return self.__message
# ---------------------------... |
peter-reinholdt/propertyfit | gen_topology.py | Python | gpl-3.0 | 4,046 | 0.004202 | #!/usr/bin/env python
import re
import json
import argparse
import numpy as np
def parse_range(index_list):
indices = []
string = "".join(index_list)
terms = string.split(",")
for term in terms:
if "-" in term:
start, end = [int(x) for x in term.split("-")]
indices += l... | 6-10')
parser.add_argument('--start-guess-charge', '--charge', dest='charge', type=str, help='Name of file with reference charges, used as start-guess and for\
res | traints', required=True)
parser.add_argument('--start-guess-polarizability', '--polarizability', dest='polarizability', type=str, help='Name of file with reference polarizabilities, used as start-guess and for restraints')
parser.add_argument('--symmetry', dest='syms', type=str, default=[], nargs='+', action='append',... |
lxml/lxml | src/lxml/html/tests/test_frames.py | Python | bsd-3-clause | 1,557 | 0.003211 | import unittest, sys
from lxml.tests.common_imports import make_doctest, doctest
import lxml.html
from lxml.html import html_parser, XHTML_NAMESPACE
class FrameTest(unittest.TestCase):
def test_parse_fragments_fromstring(self):
parser = lxml.html.HTMLParser(encoding='utf-8', remove_comments=True)
... | htm | l, parser=parser)
self.assertEqual(len(etree_document), 1)
root = etree_document[0]
self.assertEqual(root.tag, "frameset")
frame_element = root[0]
self.assertEqual(frame_element.tag, 'frame')
def test_parse_fromstring(self):
parser = lxml.html.HTMLParser(encoding='ut... |
plotly/python-api | packages/python/plotly/plotly/validators/volume/caps/_y.py | Python | mit | 1,174 | 0 | import _plotly_utils.basevalidators
class YValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="y", parent_name="volume.caps", **kwargs):
super(YValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_class... | than
one would allow the creation of openings
parallel to the edges.
""",
| ),
**kwargs
)
|
Teagan42/home-assistant | homeassistant/components/hassio/auth.py | Python | apache-2.0 | 4,204 | 0.000476 | """Implement the auth feature from Hass.io for Add-ons."""
from ipaddress import ip_address
import logging
import os
from aiohttp import web
from aiohttp.web_exceptions import (
HTTPInternalServerError,
HTTPNotFound,
HTTPUnauthorized,
)
import voluptuous as vol
from homeassistant.auth.models import User
f... | .config_validation as cv
from homeassistant.helpers.typing import HomeAssistantType
from .const impor | t ATTR_ADDON, ATTR_PASSWORD, ATTR_USERNAME
_LOGGER = logging.getLogger(__name__)
SCHEMA_API_AUTH = vol.Schema(
{
vol.Required(ATTR_USERNAME): cv.string,
vol.Required(ATTR_PASSWORD): cv.string,
vol.Required(ATTR_ADDON): cv.string,
},
extra=vol.ALLOW_EXTRA,
)
SCHEMA_API_PASSWORD_RE... |
lesserwhirls/scipy-cwt | scipy/sparse/csc.py | Python | bsd-3-clause | 4,895 | 0.006946 | """Compressed Sparse Column matrix format"""
__docformat__ = "restructuredtext en"
__all__ = ['csc_matrix', 'isspmatrix_csc']
from warnings import warn
import numpy as np
from sparsetools import csc_tocsr
from sputils import upcast, isintlike
from compressed import _cs_matrix
class csc_matrix(_cs_matrix):
"... | t matrix vector products (CSR, BSR may be faster)
Disadvantages of the CSC format
- slow row slicing operations (consider CSR)
- changes to the sparsity structure are expensive (consider LIL or DOK)
Examples
========
>>> from scipy.sparse import *
>>> from scipy import *
>>> csc_... | [0, 0, 0, 0],
[0, 0, 0, 0]], dtype=int8)
>>> row = array([0,2,2,0,1,2])
>>> col = array([0,0,1,2,2,2])
>>> data = array([1,2,3,4,5,6])
>>> csc_matrix( (data,(row,col)), shape=(3,3) ).todense()
matrix([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])
>>> indptr = arr... |
godiard/memorize-activity | model.py | Python | gpl-2.0 | 18,923 | 0 | # Copyright (C) 2006, 2007, 2008 One Laptop per Child
#
# 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... | if 'equal_pairs' in attributes:
self.data['equal_pairs'] = a | ttributes['equal_pairs']
if 'font_name1' in attributes:
self.data['font_name1'] = attributes['font_name1']
if 'font_name2' in attributes:
self.data['font_name2'] = attributes['font_name2']
if 'origin' in attributes:
... |
childresslab/MicrocavityExp1 | hardware/microwave/mw_source_dummy.py | Python | gpl-3.0 | 9,607 | 0.003747 | # -*- coding: utf-8 -*-
"""
This file contains the Qudi hardware file to control the microwave dummy.
Qudi is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any... | w(self, frequency=None, power=None): |
"""
Configures the device for cw-mode and optionally sets frequency and/or power
@param float frequency: frequency to set in Hz
@param float power: power to set in dBm
@param bool useinterleave: If this mode exists you can choose it.
@return float, float, str: current... |
XiaoxiaoLiu/morphology_analysis | blast_neuron/plot_running_time.py | Python | gpl-3.0 | 2,344 | 0.015358 | __author__ = 'xiaoxiaol'
import sys
import os
import platform
if (platform.system() == "Linux"):
WORK_PATH = "/local1/xiaoxiaol/work"
else:
WORK_PATH = "/Users/xiaoxiaoliu/work"
p = WORK_PATH + '/src/morphology_analysis'
sys.path.append(p)
import bigneuron.recon_prescreening as rp
import bigneuron.plot_... | algorithms[i]).shape[0])
order = sample_size_per_algorithm.argsort()
algorithms_ordered = algorithms[order[::-1]]
time_csv="/data/mat/xiaoxiaol/data/reconstructions_2015_1214/auto_recons/running_time.csv"
output_time_csv= "/data/mat/xiaoxiaol/data/reconstructions_2015_1214/running_time_algorithm.csv"
algorithm_plugi... | ns_2015_1214/ported_neuron_tracing_spreadsheet.csv"
rp.summerize_running_time(time_csv, algorithm_plugin_match_csv,output_time_csv)
df_gold = pd.read_csv(GOLD_CSV)
df_silver = pd.read_csv(SILVER_CSV)
#print df_silver.columns
#print df_gold.columns
df_share = pd.merge(df_silver,df_gold,on="image_file_name")
plt_dis... |
ggilestro/majordomo | listeners/pipe.py | Python | mit | 2,193 | 0.00684 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# pipe.py
#
# Copyright 2014 Giorgio Gilestro <gg@kozak>
#
# 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 Licen... | debug("Listening from PIPE %s" % self.pipefile)
with open(self.pipefile) as fifo:
self.transmit(fifo.read().strip())
|
if __name__ == '__main__':
p = pipe("pipefile", "none")
|
brunorijsman/euler-problems-python | euler/problem001.py | Python | bsd-2-clause | 87 | 0.022989 | def sol | ve():
return sum([n for n in range(1,1000) if (n % 3 | == 0) or (n % 5 == 0)])
|
guolivar/dusty-acorn | air1/pacman.py | Python | mit | 5,315 | 0.047601 | # Routine to parse the data line received from the sensors
# 20160705
# Changed the format of the data from the sensor.
# New dust sensor with | more data and re-ordered the data channels
from random import randint
import serial # Serial communications
import os #OS calls to control the screensaver and play sounds
import time
class Pacman | (object):
""" The real pacman. Open serial port on initialisation. Further calls read a new line of data """
def __init__(self):
# Read the settings from the settings file
settings_file = open("./config.txt")
# Define test or live mode
self.mode_line = settings_file.readline().rstrip('\n')
# e.g. "/dev/ttyA... |
tensorflow/lingvo | lingvo/tasks/asr/decoder_utils_test.py | Python | apache-2.0 | 7,263 | 0.004681 | # Lint as: python3
# Copyright 2018 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 ... | ll_hidden_dim = 0
rnn_p = base_rnn_p.Copy()
decoder_utils.SetRnnCellNodes(decoder_p, rnn_p)
self.assertEqual(rnn_p.num_hidden_nodes, base_rnn_p.num_hidden_nodes)
# rnn_cell_hidden_dim is a symbol.
decoder_p.rnn_cell_hidden_dim = symbolic.Symbol("rnn_cell_hidden_dim")
rnn_p = base_rnn_p.Copy()
... |
class DecoderUtilsTokenizeTest(test_utils.TestCase):
def testTokenize(self):
s = "onetoken"
self.assertEqual(["onetoken"], decoder_utils.Tokenize(s))
s = "two tokens"
self.assertEqual(["two", "tokens"], decoder_utils.Tokenize(s))
s = " extra spaces are filtered "
self.assertEqual(["e... |
Asurada2015/TFAPI_translation | NeuralNekworks_function/Activefunction/tf_nn_dropout.py | Python | apache-2.0 | 2,296 | 0 | """tf.nn.dropout(x, keep_prob, noise_shape = None, seed = None, name = None)
解释:这个函数的作用是计算神经网络层的dropout。
一个神经元将以概率keep_prob决定是否放电,如果不放电,那么该神经元的输出将是0,
如果该神经元放 | 电,那么该神经元的输出值将被放大到原来的1/keep_prob倍。
这里的放大操作是为了保持神经元输出总个数不变。比如,神经元的值为[1, 2],keep_prob的值是0.5,
并且是第一个神经元是放电的,第二个神经元不放电,那么神经元输出的结果是[2, 0],也就是相当于,
第一个神经元被当做了1/keep_prob个输出,即2个。这样保证了总和2个神经元保持不变。
默认情况下,每个神经元是否放电是相互独立的。但是,如果noise_shape被修改了,
那么他对于变量x就是一个广播形式,而且当且仅当 noise_shape[i] == shape(x)[i] ,
x中的元素是相互独立的。比如, | 如果 shape(x) = [k, l, m, n], noise_shape = [k, 1, 1, n] ,
那么每个批和通道都是相互独立的,但是每行和每列的数据都是关联的,即要不都为0,要不都还是原来的值。
一荣俱荣,一损俱损"""
import tensorflow as tf
# tf.nn.dropout(x, keep_prob, noise_shape = None, seed = None, name = None)
a = tf.constant([[-1.0, 2.0, 3.0, 4.0]])
with tf.Session() as sess:
b = tf.nn.dropout(a, 0.5, n... |
dhuang/incubator-airflow | tests/providers/google/cloud/hooks/test_cloud_memorystore.py | Python | apache-2.0 | 25,373 | 0.003035 | #
# 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... | nstance.has_calls(
[
mock.call(name=TEST_NAME, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA),
mock.call(name=TEST_NAME, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA),
] |
)
mock_get_conn.return_value.create_instance.assert_called_once_with(
request=dict(
parent=TEST_PARENT_DEFAULT_PROJECT_ID,
instance=Instance(
name=TEST_NAME,
labels={"airflow-version": "v" + version.version.replace(".",... |
ivmech/iviny-scope | lib/xlsxwriter/test/comparison/test_chart_format16.py | Python | gpl-3.0 | 2,334 | 0.000428 | ###############################################################################
#
# 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... | workbook.close()
####################################################
got, exp = _compare_xlsx_files(self.got_filename,
self.exp_filename,
self.ignore_files,
self.ignore_elements)... | ame):
os.remove(self.got_filename)
if __name__ == '__main__':
unittest.main()
|
Parbhat/wagtail-cookiecutter-foundation | {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/settings/production.py | Python | mit | 4,977 | 0.00221 | from .base import * # flake8: noqa
DEBUG = env.bool('DJANGO_DEBUG', default=False)
TEMPLATES[0]['OPTIONS']['debug'] = DEBUG
SECRET_KEY = env('DJANGO_SECRET_KEY')
# Compress static files offline
# http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_OFFLINE
COMPRESS_OFFLINE =... | ter',
]
ALLOWED_HOSTS = [env("DJANGO_ALLOWED_HOST_NAME"), ]
DATABASES['default'] = env.db('PROD_DATABASE_URL')
INSTALLED_APPS += (
"wagtail.contrib.wagtailfrontendcache",
'gunicorn',
)
#support opbeat
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.c... | are',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'wagtail.wagtailcore.middleware.SiteMiddleware',
'wagtail.wagtailredirects.middleware.RedirectMiddleware',
)
WAGTAIL_SITE_NAME = '{{ cookiecutter.project_name }}'
# Send notificatio... |
ardinusawan/Sistem_Terdistribusi | Cluster/Manajer.py | Python | gpl-3.0 | 7,838 | 0.008421 | __author__ = 'Indra Gunawan'
import math, sys, time
import pp
import re
import collections, string, pickle
def isprime(n):
"""Returns True if n is prime and False otherwise"""
if not isinstance(n, int):
raise TypeError("argument passed to is_prime is not of 'int' type")
if n < 2:
return Fa... | p[14], p[15], p[16], p[17], p[18], p[19], p[20], p[21], p[22], p[23], p[24], p[25], p[26], p[27], p[28], p[29], p[30], p[31], p[32], p[33])
#print inputs
jobs = [(input, job_server.submit(count,(input,), depfuncs=(), modules=("re","collections","pickle",))) for input in inputs]
job_server.wait()
for input, job in jobs... | bagi2[0].split(",")
bagi4 =bagi[2].split(", ")
#job_server.destroy()
if counter == 0:
temp1 = bagi4
tempc1 = [int(i) for i in bagi3]
counter+=1
else:
tempLog = bagi4
tempCount = [int(i) for i in bagi3]
#menggabungkan dengan temp hasil hitung dengan temp utama... |
npuichigo/ttsflow | third_party/tensorflow/tensorflow/contrib/ndlstm/python/misc_test.py | Python | apache-2.0 | 2,875 | 0.010783 | # Copyright 2016 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 applicable ... | puts.eval()
self.assertEqual(tuple(result.shape), (2, 7 * 11 * 5))
def testPoolAsVectorDims(self):
with self.test_session():
inputs = constant_op.constant(_rand(2, 7, 11, 5))
outputs = misc.pool_as_vector(inputs)
variables.global_variables_initializer().run()
result = outputs.eval()... | 1, 3])
outputs = misc.one_hot_planes(inputs, 4)
variables.global_variables_initializer().run()
result = outputs.eval()
self.assertEqual(tuple(result.shape), (3, 1, 1, 4))
target = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1]])
self.assertAllClose(result.reshape(-1), target.resh... |
alirizakeles/zato | code/zato-server/src/zato/server/connection/http_soap/__init__.py | Python | gpl-3.0 | 1,596 | 0.006266 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2012 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
from httplib import BAD_REQUEST, CONFLICT, FORBIDDEN, M | ETHOD_NOT_ALLOWED, NOT_FOUND, UNAUTHORIZED
# Zato
from zato.common import TOO_MANY_REQUESTS, HTTPException
class ClientHTTPError(HTTPExce | ption):
def __init__(self, cid, msg, status):
super(ClientHTTPError, self).__init__(cid, msg, status)
class BadRequest(ClientHTTPError):
def __init__(self, cid, msg):
super(BadRequest, self).__init__(cid, msg, BAD_REQUEST)
class Conflict(ClientHTTPError):
def __init__(self, cid, msg):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.