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 |
|---|---|---|---|---|---|---|---|---|
CiscoSystems/jujucharm-n1k | charms/precise/quantum-gateway/hooks/quantum_contexts.py | Python | apache-2.0 | 6,598 | 0.000303 | # vim: set ts=4:et
import os
import uuid
import socket
from charmhelpers.core.hookenv import (
config,
relation_ids,
related_units,
relation_get,
unit_get,
cached,
)
from charmhelpers.fetch import (
apt_install,
)
from charmhelpers.contrib.openstack.context import (
OSContextGenerator,
... | if config('run-internal-router') == 'none':
ctxt['handle_internal_only_router'] = False
if config('external-network-id'):
ctxt['ext_net_id'] = config('external-network-id')
if config('plugin'):
ctxt['plugin'] = config('plugin')
return ctxt
class Exte... | one
class QuantumGatewayContext(OSContextGenerator):
def __call__(self):
ctxt = {
'shared_secret': get_shared_secret(),
'local_ip': get_host_ip(), # XXX: data network impact
'core_plugin': core_plugin(),
'plugin': config('plugin')
}
return c... |
quarckster/cfme_tests | cfme/tests/infrastructure/test_individual_host_creds.py | Python | gpl-2.0 | 2,699 | 0.002964 | # -*- coding: utf-8 -*-
import pytest
import random
from cfme.utils import conf
from cfme.utils import error
from cfme.infrastructure import host
from cfme.infrastructure.provider.rhevm import RHEVMProvider
from cfme.infrastructure.provider.virtualcenter import VMwareProvider
from cfme.utils.blockers import BZ
from cf... | st_name):
for host_obj in conf.cfme_data.get('management_systems', {})[provider_key].get('hosts', []):
if host_name == host_obj['name']:
return host_obj
return None
# Tests to automate BZ 1278904
@pytest.mark.meta(blockers=[BZ(1516849,
forced_streams=['5.8', '5.... | er, provider):
"""
Tests host credentialing with good credentials
"""
test_host = random.choice(provider.data["hosts"])
host_data = get_host_data_by_name(provider.key, test_host.name)
host_collection = appliance.collections.hosts
host_obj = host_collection.instantiate(name=test_host.name, p... |
alissonperez/django-onmydesk | onmydesk/utils.py | Python | mit | 1,501 | 0.000666 | """Module with common utilities to this package"""
import re
from datetime import timedelta
import importlib
def my_import(class_name):
"""
Usage example::
Report = my_import('myclass.models.Report')
model_instance = Report()
model_instance.name = 'Test'
model_instance.save()... | reference_date):
'''
Convert a string like 'D-1' to a "reference_date - timedelta(days=1)"
:param str value: String like 'D-1', 'D+1', 'D'...
:param date reference_date: Date to be used as 'D'
:returns: Result date
:rtype: date
'''
n_value = value.strip(' ').replace(' ', '').upper()
... | re.match('^D[\-+][0-9]+$|^D$', n_value):
raise ValueError('Wrong value "{}"'.format(value))
if n_value == 'D':
return reference_date
elif n_value[:2] == 'D-':
days = int(n_value[2:])
return reference_date - timedelta(days=days)
elif n_value[:2] == 'D+':
days = int(n... |
tectronics/snapfly | src/launcher.py | Python | gpl-3.0 | 1,632 | 0.007362 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2010-2011
# Drakmail < drakmail@gmail.com >
# NomerUNO < uno.kms@gmail.com >
# Platon Peacel☮ve <platonny@ngs.ru>
# Elec.Lomy.RU <Elec.Lomy.RU@gmail.com>
# ADcomp <david.madbox@gmail.com>
#
# This program is free software: you can redistribute it and/... | t q.empty():
program = q.get()
if program.poll() == None:
programs.append(program)
q.task_done()
for program in programs:
q.put(program)
return True
def launch_command(cmd):
try:
p = Popen(cmd, stdout = devnull, stderr = devnull )
q.put(p)
exc... | xecute a command: %s : %s" % (repr(cmd), repr(e) ))
|
Distrotech/yum-utils | plugins/tsflags/tsflags.py | Python | gpl-2.0 | 1,294 | 0.002318 | # 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,... | write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# by Panu Matilainen <pmatilai@laiskiainen.org>
from yum.plugins import TYPE_INTERACTIVE
requires_api_version = '2.1'
plugin_type = (TYPE_INTERACTIVE,)
def init_hook(conduit):
parser = conduit.get... |
opts, args = conduit.getCmdLine()
conf = conduit.getConf()
if opts.tsflags:
flags = opts.tsflags.split(',')
for flag in flags:
if flag not in conf.tsflags:
conf.tsflags.append(flag)
|
ddboline/pytest | src/_pytest/unittest.py | Python | mit | 8,619 | 0.000348 | """ discovery and running of std-library "unittest" style tests. """
from __future__ import absolute_import, division, print_function
import sys
import traceback
# for transferring markers
import _pytest._code
from _pytest.config import hookimpl
from _pytest.outcomes import fail, skip, xfail
from _pytest.python impor... | ed
setup = getattr(cls, "setUpClass", None)
if setup is not None:
setup()
teardown = getattr(cls, "tearDownClass", None)
if teardown i | s not None:
self.addfinalizer(teardown)
super(UnitTestCase, self).setup()
def collect(self):
from unittest import TestLoader
cls = self.obj
if not getattr(cls, "__test__", True):
return
self.session._fixturemanager.parsefactories(self, unittest=True)... |
DataBiosphere/data-explorer | api/data_explorer/models/export_url_request.py | Python | bsd-3-clause | 3,966 | 0.000504 | # coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from data_explorer.models.base_model_ import Model
from data_explorer import util
class ExportUrlRequest(Model):
"""NOTE: This class is auto generated by the swag... | ExportUrlRequest
"""
return util.deserialize_model(dikt, cls)
@property
def cohort_name(self):
"""Gets the cohort_name of this ExportUrlRequest.
:return: The cohort_name of this ExportUrlRequest.
:rtype: str
"""
return self._cohort_name
@cohort_na... | rt_name(self, cohort_name):
"""Sets the cohort_name of this ExportUrlRequest.
:param cohort_name: The cohort_name of this ExportUrlRequest.
:type cohort_name: str
"""
self._cohort_name = cohort_name
@property
def filter(self):
"""Gets the filter of this Export... |
blmousee/pyctp | example/pyctp/dac2.py | Python | mit | 22,134 | 0.0188 | # -*-coding:utf-8 -*-
'''
dac的@indicator版本
提供更简单的使用方式和实现方式
'''
import operator
from collections import (
deque,
)
from .base import (
BaseObject,
fcustom,
indicator,
icache,
t2order_if,
)
from .dac import (
XBASE, #100
... | 0,'divisor vs == 0'
if not _ts.initialized:
_ts.initialized = True
_ts.ss = []
for i in range(len(_ts.ss),len(source1)):
#print 'new data:',source1[i]
_ts.ss.append((source1[i]+vs/2)/vs)
return _ts.ss
############
# 常用指标
#
############
@indicator
def ... |
_ts.initialized = True
_ts.sa = []
ss = _ts.sa[-1] if _ts.sa else 0
for i in range(len(_ts.sa),len(source)):
ss += source[i]
_ts.sa.append(ss)
#print id(_ts),id(source),source,_ts.sa
return _ts.sa
NSUM = ACCUMULATE
@indicator
def MSUM(source,mlen,_ts=Non... |
silverbp/master-builder | mb/lib/ioc.py | Python | apache-2.0 | 4,431 | 0.004288 | from __future__ import absolute_import
from __future__ import unicode_literals
import glob
import imp
import inspect
import os
import sys
from mb.config.config import get_default_config_file
from mb.lib import logger
from mb.lib import process
_log = logger.get_logger('[Ioc]')
# plugin types
from mb import build_co... | lugin_types:
if not _is_plugin_type(module_attr, plugin_type):
continue
_loaded_plugin_definitions[module_attr.__name__] = module_attr
_defined_commands = _config.commands
_defined_commands['_prerun'] = PluginConfig('MBPreRunCommand', {}, _config)
command_plugins = [k for (k, ... | commands.items():
if v.name not in command_plugins:
_log.warn('The following Command: {0} was not found and will not be available'.format(k))
del _defined_commands[k]
_log.debug('The following commands will be available: {0}'.format([k for (k, v) in _defined_commands.items() if not k.startswith('_'... |
davehorton/drachtio-server | deps/boost_1_77_0/libs/mpi/test/python/scatter_test.py | Python | mit | 1,318 | 0.008346 | # Copyright (C) 2006 Douglas Gregor <doug.gregor -at- gmail.com>.
# Use, modification and distribution is subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# Test scatter() collective.
from __future__ import print_function
... | ter_test(mpi.world, gps_generator, "GPS positions", 1)
scatter_test(mpi.world, string_generator, "strings", 0)
scatter_test(mpi.world, string_generator, "strings", 1)
scatter_test(mpi.world, string_list_generator, "li | st of strings", 0)
scatter_test(mpi.world, string_list_generator, "list of strings", 1)
|
VJalili/OIDCProvider | config.py | Python | lgpl-3.0 | 2,954 | 0.003047 | PORT = 8040
ISSUER = 'https://localhost' # do not include the port, it will be added in the code.
SERVICEURL = "{issuer}verify" # do not manually add issuer or port number, these will be added in the code.
SERVER_CERT = "certification/server.crt"
SERVER_KEY = "certification/server.key"
CERT_CHAIN = None
AUTHENTICATI... | 1",
"family_name": "familyName1",
"nickname": "nickname1",
"email": "email1@example.org",
"email_verified": False,
"phone_number": "+984400000000",
"address": {
"street_address": "address1",
"locality": "locality1",
"postal_code": "5719... |
"family_name": "familyName2",
"nickname": "nickname2",
"email": "email2@example.com",
"email_verified": True,
"address": {
"street_address": "address2",
"locality": "locality2",
"region": "region2",
"postal_code": "5719899999",
... |
timlinux/fabgis | docs/source/conf.py | Python | lgpl-2.1 | 10,614 | 0.005653 | # -*- coding: utf-8 -*-
#
# FabGIS documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 2 22:29:26 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All ... |
'navbar_fixed_top': "true",
# Location of link to s | ource.
# Options are "nav" (default), "footer" or anything else to exclude.
'source_link_position': "nav",
# Bootswatch (http://bootswatch.com/) theme.
#
# Options are nothing with "" (default) or the name of a valid theme
# such as "amelia" or "cosmo".
'bootswatch_theme': "slate",
# C... |
srishtyagrawal/database-iblt | avg.py | Python | mit | 113 | 0.035398 | import sys
#!/usr/bin/python
f = open(str(sys.argv[1]),'r' | )
sum = 0
for i in f:
sum += int(i)
| print sum
|
avanzosc/avanzosc6.1 | avanzosc_product_default_location/wizard/__init__.py | Python | agpl-3.0 | 1,106 | 0.003617 |
# -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2008-2013 AvanzOSC (Daniel). All Rights Reserved
# Date: 25/09/2013
#
# This program is free software: you can redistribute it and/or... | ither 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; witho | ut 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, see http://www.gnu.org/licenses/.
#
#######################... |
remmihsorp/minicps | scripts/pox/l2_learning.py | Python | mit | 5,918 | 0.00338 | """
Flow based learing switch
l2_learning listens to openflow events and uses a dedicated
class called LearningSwitch to manage the Switch learning logic
eg: flood, flow_mod, drop
Learn:
how to create a dedicate controller class
how to register a pox component to the core object
how to drop a packet
... | aised by nexus
core.openflow.addListeners(self)
self.transparent = transparent
def _handle_ConnectionUp(self, event):
"""
Event fired once the controller is connected
"""
log.debug("Connection %s" % (event.connection))
LearningSwitch(event.connection, sel... | """
launch argument are parsed from command line
"""
try:
global _flood_delay
_flood_delay = int(str(hold_down), 10) # base 10 conversion
assert _flood_delay >= 0
except:
raise RuntimeError("Expected hold_down to be a number.")
# create an instance of a l2_learning... |
datamade/python-legistar-scraper | scripts/guessdomains.py | Python | bsd-3-clause | 4,242 | 0.001886 | import re
import os
import csv
import time
import logging
import logging.config
from os.path import join
import scrapelib
path = '/home/thom/sunlight/python-opencivicdata/opencivicdata/division-ids/identifiers/country-us'
class Checker(scrapelib.Scraper):
OUTFILE = 'domains.csv'
SCRAPELIB_RPM = 10
SCRA... | self.timeout = self.SCRAPELIB_TIMEOUT
self.requests_per_minute = self.SCRAPELIB_RPM
self.retry_attempts = self.SCRAPELIB_RETRY_ATTEMPTS
self.retry_wait_seconds = self.SCRAPELIB_RETRY_WAIT_ | SECONDS
self.follow_robots = False
# if self.PROXIES:
# self.proxies = self.PROXIES
if self.FASTMODE:
self.cache_write_only = False
cache_dir = '.cache'
self.cache_storage = scrapelib.FileCache(cache_dir)
def __enter__(self):
self.outfile =... |
froyobin/horizon | openstack_dashboard/test/test_data/sahara_data.py | Python | apache-2.0 | 17,441 | 0 | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language | governing permissions and limitations
# under the License.
from openstack_dashboard.test.test_data import utils
from saharaclient.api import cluster_templates
from saharaclient.api import clusters
from saharaclient.api import data_sources
from saharaclient.api import job_binaries
from saharaclient.api import job_exec... |
elbadawyy/Hash-POS | API/Helper/Database.py | Python | lgpl-3.0 | 4,331 | 0.051951 | #! /usr/bin/python2.7
# -*- coding: utf-8 -*-
import ConfigParser
import sqlite3
from sqlite3 import Error
import os
from abc import ABCMeta, abstractmethod
curr_dir = os.path.dirname(os.path.realpath(__file__))
api_dir = os.path.abspath(os.path.join(curr_dir, '..'))
root_dir = os.path.abspath(os.path.join(api_dir, ... | ursor()
cur.execute(query)
conn.commit()
res = cur.fetchall()
return res
class Table:
__metaclass__ = ABCMeta
table=""
field_tuple=()
def add(self, value_tuple):
errcode=""
if not( | value_tuple) or not (value_tuple[0]) or(type(value_tuple) is not tuple) or (len(self.field_tuple) != len(value_tuple)):
errcode="255"
return errcode
API.addEntry(self.table, self.field_tuple,value_tuple)
errcode="0"
return errcode
def modify(self, id, field, value):
errcode=""
id=int(id)
if not (id... |
fe11x/django-oscar-alipay | alipay/warrant/__init__.py | Python | bsd-3-clause | 198 | 0.021739 | ##### | ################################################### | ###############################
#支付宝担保交易
####################################################################################### |
mathstuf/bodhi | bodhi/services/releases.py | Python | gpl-2.0 | 6,860 | 0.002041 | # 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,
# bu... | release, the release's original name must be specified in
the ``edited`` parameter.
"""
data = request.validated
edited = data.pop("edited", None)
# This has already been validated at this point, but we need to ditch
# it since the models don't care about a csrf argument.
data.pop('csrf_t... |
if edited is None:
log.info("Creating a new release: %s" % data['name'])
r = Release(**data)
else:
log.info("Editing release: %s" % edited)
r = request.db.query(Release).filter(Release.name==edited).one()
for k, v in data.items():
... |
Jeff-Tian/mybnb | Python27/Lib/idlelib/run.py | Python | apache-2.0 | 12,890 | 0.00225 | import sys
import linecache
import time
import socket
import traceback
import thread
import threading
import Queue
from idlelib import CallTips
from idlelib import AutoComplete
from idlelib import RemoteDebugger
from idlelib import RemoteObjectBrowser
from idlelib import StackViewer
from idlelib import... | socket_error(err, address):
import Tkinter
import tkMessageBox
root = Tkinter.Tk()
root.withdraw()
if err.args[0] == 61: # connection refused
msg = "IDLE's subprocess can't connect to %s:%d. This may be due "\
"to your personal | firewall configuration. It is safe to "\
"allow this internal connection because no data is visible on "\
"external ports." % address
tkMessageBox.showerror("IDLE Subprocess Error", msg, parent=root)
else:
tkMessageBox.showerror("IDLE Subprocess Error",
... |
harinisuresh/yelp-district-clustering | MapClusteringWithLDA.py | Python | mit | 895 | 0.011173 | """Cluster restaurants on map"""
import Clustering
import Map
import DataImporter
def create_topic_clusters_and_map(restaurants, restaurant_ids_to_topics, my_map, lda, use_human_labels=True):
data = Clustering.create | _data_array(restaurants, restaurant_ids_to_topics, my_map)
Clustering.plot_clusters(my_map, restaurants, rest | aurant_ids_to_topics, data, lda)
def run(my_map, reviews, restaurants):
restaurants = Clustering.filter_restaurants(restaurants)
normalized_restaurant_ids_to_topics, lda = Clustering.get_predictions(my_map, reviews, restaurants)
create_topic_clusters_and_map(restaurants, normalized_restaurant_ids_to_topics... |
citrix-openstack-build/sahara | sahara/plugins/mapr/versions/v4_0_1_mrv2/cluster_configurer.py | Python | apache-2.0 | 875 | 0 | # Copyright (c) 2014, | MapR Technologies
#
# 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 writ | ing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import sahara.plugins.mapr.versions.base_cluster_config... |
GarrettArm/TheDjangoBook | mysite_project/contact/urls.py | Python | gpl-3.0 | 212 | 0 | from django.urls import path
from . import views
app_name = "contact"
urlpatterns = [
path("thanks", view | s.ThanksView.as_view(), name="thanks"),
path("", views.ContactView.as_view(), | name="contact"),
]
|
HIPS/autograd | tests/test_scipy.py | Python | mit | 13,976 | 0.017602 | from __future__ import absolute_import
from builtins import range
from functools import partial
import numpy as npo
try:
import scipy
except:
from warnings import warn
warn('Skipping scipy tests.')
else:
import autograd.numpy as np
import autograd.numpy.random as npr
import autograd.scipy.signa... |
def test_gamma_cdf(): combo_check(stats.gamma.cdf, [0]) ([R(4)**2 + 1.1], [R(4)**2 + 1.1])
def test_gamma_pdf(): combo_check(stats.gamma.pdf, [0,1])([R(4)**2 + 1.1], [R(4)**2 + 1.1])
def test_gamma_logpdf(): combo_check(stats.gamma.logpdf, [0,1])([R(4)**2 + 1.1], [R(4)**2 + 1.1])
def test... | _cdf(): combo_check(stats.norm.cdf, [0,1,2])([R(4)], [R(4)], [R(4)**2 + 1.1])
def test_norm_sf(): combo_check(stats.norm.sf, [0,1,2])([R(4)], [R(4)], [R(4)**2 + 1.1])
def test_norm_logpdf(): combo_check(stats.norm.logpdf, [0,1,2])([R(4)], [R(4)], [R(4)**2 + 1.1])
def test_norm_logcdf(): combo_... |
maestromusic/maestro | maestro/gui/treeview.py | Python | gpl-3.0 | 9,172 | 0.005778 | # -*- coding: utf-8 -*-
# Maestro Music Manager - https://github.com/maestromusic/maestro
# Copyright (C) 2009-2015 Martin Altmayer, Michael Helmling
#
# 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 Foun... | uments).
- Before dropMimeData is called a DraggingTreeView will set the attributes dndSource and dndTarget
| of the receiving model to the sending widget and itself. If the drag was started in an external
application, dndSource will be None.
"""
def __init__(self, level, parent=None, affectGlobalSelection=True):
super().__init__(level, parent, affectGlobalSelection)
self.setDefaultD... |
mick-d/nipype | nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py | Python | bsd-3-clause | 1,115 | 0.012556 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..featuredetection import DumpBinaryTrainingVectors
def test_DumpBinaryTrainingVectors_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_ex... | hash=True,
),
)
inputs = DumpBinaryTrainingVectors.input_spec()
for key, metadata in list(input_map.items()):
for metakey, value in list(metadata.items()):
assert getattr(inputs.traits()[key], metakey) == value
def test_DumpBinaryTrainingVectors_outputs():
output_map = dict()
... | ts.traits()[key], metakey) == value
|
Chyroc/study-code | Language/Python/BuildInConstants.py | Python | mit | 170 | 0 | False |
True
None # 作为默认参数的初始值
NotImplemented
Ellipsis
# 以下不是用于项目的
'''
quit(code=None)
exit(code=None)
copyright
license
cr | edits
'''
|
shucommon/little-routine | python/python-crash-course/file_reader.py | Python | gpl-3.0 | 524 | 0.001908 | filename = 'pi_digits.txt'
with open(filename) as file_object:
| contents = file_object.read() # read all
#print(contents)
print(contents.rstrip())
with open(filename) as file_object:
for line in file_object: # read line by line
print(line.rstrip())
with open(filename) as file_object:
lines = file_object.readlines()
print(lines)
for line in lines:
... | as file_object:
file_object.write("I love programming.")
|
swoopla/compose | tests/integration/service_test.py | Python | apache-2.0 | 48,237 | 0.00141 | from __future__ import absolute_import
from __future__ import unicode_literals
import os
import shutil
import tempfile
from distutils.spawn import find_executable
from os import path
import pytest
from docker.errors import APIError
from six import StringIO
from six import text_type
from .. import mock
from .testcase... | f):
read_only = True
service = self.create_service('db', read_only=read_only)
container = service.create_container()
service.start_container(container)
assert container.get('Ho | stConfig.ReadonlyRootfs') == read_only
def test_create_container_with_security_opt(self):
security_opt = ['label:disable']
service = self.create_service('db', security_opt=security_opt)
container = service.create_container()
service.start_container(container)
self.assertEqua... |
shannpersand/cooper-type | _resources/FDK Adobe/Tools/FontLabMacros/MM Designs/SaveFilesForMakeInstances.py | Python | cc0-1.0 | 17,235 | 0.026748 | #FLM: Save Files for MakeInstances
###################################################
### THE VALUES BELOW CAN BE EDITED AS NEEDED ######
###################################################
kDefaultMMFontFileName = "mmfont.pfa"
kInstancesDataFileName = "instances"
kCompositeDataName = "temp.composite.dat"
#########... | lyphs as Type 1 composites (also known as SEAC glyphs). This script
must be run again to renew this data file whenever changes are made to composite
glyphs.
Both this sc | ript and the "makeInstances" program depend on info provided by an
external text file named "instances", which contains all the instance-specific
values. The "instances" file must be a simple text file, located in the same
folder as the MM FontLab file.
For information on how to format the "instances" file, please rea... |
tadhg-ohiggins/regulations-parser | regparser/notice/amendments/utils.py | Python | cc0-1.0 | 237 | 0 | def label_amdpar_from(instruction_xml):
label_parts = instruction_xml.get('label', '').split('-')
# <AMDPAR><EREGS_INSTRUCTIONS><INSTR | UCTION>...
amdpar = instruction_xml.getparent().getparent()
return label_par | ts, amdpar
|
pombredanne/PyGithub | github/Notification.py | Python | gpl-3.0 | 5,674 | 0.005111 | # -*- coding: utf-8 -*-
# ########################## Copyrights and license ############################
# #
# Copyright 2013 AKFish <akfish@gmail.com> #
# Copyright 2013 Peter Golm <golm.peter@gmail.com> ... | are Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY #
# W... | sser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <ht... |
cgwalters/mock | py/mockbuild/plugins/yum_cache.py | Python | gpl-2.0 | 4,641 | 0.00237 | # -*- coding: utf-8 -*-
# vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:textwidth=0:
# License: GPL2 or later see COPYING
# Written by Michael Brown
# Copyright (C) 2007 Michael E Brown <mebrown@michaels-house.net>
# python library imports
import fcntl
import glob
import os
import time
# our imports... | state)
for (dirpath, _, filenames) in os.walk(self.yumSharedCachePath):
for filename in filenames:
fullPath = os.path.join(dirpath, filename)
statinfo = os.stat(fullPath)
file_age_days = (time.time() - statinfo.st_ctime) / (60 * 60 ... | for ext in self.METADATA_EXTS:
if filename.endswith(ext) and file_age_days > self.yum_cache_opts['max_metadata_age_days']:
os.unlink(fullPath)
fullPath = None
break
if fullPath is Non... |
MatthewWilkes/mw4068-packaging | src/melange/src/melange/profiler.py | Python | apache-2.0 | 119 | 0.033613 | import gae_django
from soc.profiling import viewer
def main():
| viewer.ma | in()
if __name__ == '__main__':
main()
|
maartenq/ansible | lib/ansible/modules/cloud/vmware/vmware_host_firewall_manager.py | Python | gpl-3.0 | 8,047 | 0.002734 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2018, Abhijeet Kasurde <akasurde@redhat.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata... | = {}
firewall_system = host.configManager.firewallSystem
if firewall_system:
for rule_set_obj in firewall_system.firewallInfo.ruleset:
temp_rule_dict = dict()
| temp_rule_dict['enabled'] = rule_set_obj.enabled
self.firewall_facts[host.name][rule_set_obj.key] = temp_rule_dict
def ensure(self):
"""
Function to ensure rule set configuration
"""
fw_change_list = []
results = dict(changed=False, ru... |
xuelians/djmoney | balance/migrations/0003_auto_20170809_0736.py | Python | gpl-3.0 | 457 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-08-09 07:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration): |
dependencies = [
('balance', '0002_auto_20170809_0734'),
]
operations = [
migrations.AlterField(
model_name='transaction',
n | ame='date',
field=models.DateField(verbose_name='Date'),
),
]
|
xod442/sample_scripts | flo2_pid.py | Python | gpl-2.0 | 7,035 | 0.017342 | #!/usr/bin/env python
#--------------------------------------------------------------------------
# flo2_pid.py
# Rick Kauffman a.k.a. Chewie
#
# Hewlett Packard Company Revision: 1.0
# ~~~~~~~~~ WookieWare ~~~~~~~~~~~~~
# Change history....09/03/201... | "<input type=\"hidden\" name=\"imc_server\" value=%s>" % (imc_server)
print "<input type=\"hidden\" name=\ | "imc_user\" value=%s>" % (imc_user)
print "<input type=\"hidden\" name=\"imc_passw\" value=%s>" % (imc_passw)
print "<input type=\"hidden\" name=\"imc\" value=%s>" % (imc)
print "</form>"
print "<footer>"
print "<p>For more information on how to use this application <a href=\"/faq.html\">User Guide</a></p>"
print "<a... |
adrianhindes/cavity-sml | createOnlyNoise.py | Python | mit | 2,479 | 0.002824 | # Running Finesse
im | port subprocess
# Editing kat file
import fileinput
# Copying files
import shutil
# Adding Gaussian noise
from skimage import io, util
# Navigating directories
import os
# Cropping raw images
from PIL import Image
# Nice loading bars for loops
# Keras preprocessing package for augmentation
from keras.prepr... | mageDataGenerator, array_to_img, \
img_to_array, load_img
'''
Just generate noisy images, if raw ones have already
been generated by Finesse
'''
maxMode = 6
# Define data folders
dataFolder = 'rawData'
newDataFolder = 'newData'
# Image extension
ext = '.png'
# No. images to generate per raw ... |
hlzz/dotfiles | graphics/VTK-7.0.0/IO/Geometry/Testing/Python/Plot3DVectors.py | Python | bsd-3-clause | 3,828 | 0.000522 | #!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
#
# All Plot3D vector functions
#
# Create the RenderWindow, Renderer and both Actors
#
renWin = vtk.vtkRenderWindow()
renWin.SetMultiSamples(0)
ren1 = vtk.vtkRenderer()
... |
eval("hog" + vectorFunction).SetScaleFactor(1.0 / maxnorm)
exec("mapper" + vectorFunction + " = vtk.vtkPolyDataMapper()")
eval("mapper" + vectorFunction).SetInputConnection(
eval("hog" + vectorFunction).GetOutputPort())
exec("actor" + vectorFunction + " = vtk.vtkActor()")
eval | ("actor" + vectorFunction).SetMapper(eval("mapper" + vectorFunction))
exec("ren" + vectorFunction + " = vtk.vtkRenderer()")
eval("ren" + vectorFunction).SetBackground(0.5, .5, .5)
eval("ren" + vectorFunction).SetActiveCamera(camera)
eval("ren" + vectorFunction).AddLight(light)
renWin.AddRen... |
kashifpk/pyckapps.visit_counter | lib/dates.py | Python | apache-2.0 | 519 | 0.001927 | "Dates related functions"
from datetime import datetime, timedelta
def process_date_range(date_from, date_to):
"""
| Given a date range in st | ring format (yyyy-mm-dd), returns date objects
- date_to is inclusive
- if just date_from is given sets date_to = date_from + 1 day
"""
if not date_to:
date_to = date_from
date_from = datetime.strptime(date_from, '%Y-%m-%d')
date_to = datetime.strptime(date_to, '%Y-%m-%d') + t... |
borringrafael/fichas-equipes-ab | setup/wsgi.py | Python | gpl-3.0 | 399 | 0 | """
WSGI config for setup project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/h | owto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_ | application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "setup.production_settings")
application = get_wsgi_application()
|
institution/keyplay | keycode.py | Python | agpl-3.0 | 2,490 | 0.059438 | # coding: utf-8
# keycode table --------------------------------------------------------
g_keycodes = [
(1, 'ESC'),
(2, '1'),
(3, '2'),
(4, '3'),
(5, '4'),
(6, '5'),
(7, '6'),
(8, '7'),
(9, '8'),
(10, '9'),
(11, '0'),
(12, 'MINUS'),
(13, 'EQUAL'),
(14, 'BACKSPACE'),
(15, 'TAB'),
(16, 'Q'),
(17, 'W'),... | HANKAKU'),
(86, '102ND'),
(87, 'F11'),
(88, 'F12'),
(89, 'RO'),
(90, 'KATAKANA'),
(91, 'HIRAGANA'),
(92, 'HENKAN'),
(93, 'KATAKANAHIRAGANA'),
(94, 'MUHENKAN'),
(95, 'KPJPCOMMA'),
(96, 'KPENTER'),
(97, 'RIGHTCTRL'),
(98, 'KPSLASH'),
(99, 'SYS | RQ'),
(100, 'RIGHTALT'),
(102, 'HOME'),
(103, 'UP'),
(104, 'PAGEUP'),
(105, 'LEFT'),
(106, 'RIGHT'),
(107, 'END'),
(108, 'DOWN'),
(109, 'PAGEDOWN'),
(110, 'INSERT'),
(111, 'DELETE'),
(112, 'MACRO'),
(113, 'MUTE'),
(114, 'VOLUMEDOWN'),
(115, 'VOLUMEUP'),
(116, 'POWER'),
(117, 'KPEQUAL'),
(118, 'KPPLUSM... |
alphagov/notifications-api | migrations/versions/0178_add_filename.py | Python | mit | 1,400 | 0.007143 | """
Revision ID: 0178_add_filename
Revises: 0177_add_virus_scan_statuses
Create Date: 2018-03-14 16:15:01.886998
"""
from alembic import op
import sqlalchemy as sa
revision = '0178_add_filename'
down_revision = '0177_add_virus_scan_statuses'
def upgrade():
# Deleting the data here is ok because a full migrati... | ily_sorted_letter', ['billing_day'], unique=True)
op.drop_constraint('uix_file_name_billing_day', 'daily_sorted_letter', type_='unique')
op.drop_index(op.f('ix_daily_sorted_letter_file_name'), table_name='daily_sorted_letter')
op.drop_column('daily_ | sorted_letter', 'file_name')
|
SKA-ScienceDataProcessor/algorithm-reference-library | tests/processing_components/test_griddata_operations.py | Python | apache-2.0 | 1,227 | 0.005705 | """ Unit tests for image operations
"""
import logging
import unittest
import numpy
from processing_components.griddata.operations import create_griddata_from_image, convert_griddata_to_image
from processing_components.simulation.testing_support import crea | te_test_image
log = logging.getLogger(__name__)
class TestGridData(unittes | t.TestCase):
def setUp(self):
from data_models.parameters import arl_path
self.dir = arl_path('test_results')
self.m31image = create_test_image(cellsize=0.0001)
self.cellsize = 180.0 * 0.0001 / numpy.pi
def test_create_griddata_from_image(self):
m31mode... |
Slightgen/SG-remote | setup.py | Python | gpl-3.0 | 1,378 | 0.001451 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
import os
os.system('cp config/.lircrc ~/.lircrc')
os.system('cp config/hardware.conf /etc/lirc/hardware.conf')
os.system('cp config/lircd.conf /etc/lirc/lircd.conf')
os.system('cp config/lircmd.conf /etc/lirc/lircmd.conf')
os.system('mkdir ... | r='girish joshi',
au | thor_email='girish946@gmail.com',
description=('interface for ir remote controllers provided with slight-gen minicomp'
'operate the desktop using ir remote'),
license='GPLV3',
packages=['remote'],
test_suite='',
install_requires=['pyautogui', 'python-lirc' , 'clipboard'],
keywor... |
noironetworks/aci-integration-module | aim/db/migration/alembic_migrations/versions/baccabeffa81_remove_fks.py | Python | apache-2.0 | 4,936 | 0.000203 | # Copyright (c) 2017 Cisco Systems
# 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 require... | t op
def upgrade():
FK = 'foreignkey'
with op.batch_alter_table('aim_bridge_domains') as bat | ch_op:
batch_op.drop_constraint('fk_bd_tn', type_=FK)
with op.batch_alter_table('aim_subnets') as batch_op:
batch_op.drop_constraint('fk_bd', type_=FK)
with op.batch_alter_table('aim_vrfs') as batch_op:
batch_op.drop_constraint('fk_vrf_tn', type_=FK)
with op.batch_alter_table('aim... |
umlfri/umlfri2 | umlfri2/application/commands/diagram/moveconnectionlabel.py | Python | gpl-3.0 | 1,001 | 0.007992 | from umlfri2.application.commands.base import Command
from umlfri2.application.events.diagram import ConnectionMovedEvent
class MoveConnectionLabelCommand(Command):
def __init__(self, connection_label, delta): |
self.__diagram_name = connection_label.connection.diagram.get_display_name()
self.__connection_label = connection_label
self.__delta = delta
self.__label_position = None
@property
def description(self):
return "Moved label on connection in diagram {0}".format(self._... |
def _do(self, ruler):
self.__label_position = self.__connection_label.get_position(ruler)
self._redo(ruler)
def _redo(self, ruler):
self.__connection_label.move(ruler, self.__label_position + self.__delta)
def _undo(self, ruler):
self.__connection_label.move(r... |
hcwiley/the-front | the_front/the_front/artist/migrations/0003_auto__add_field_artistmedia_is_default_image.py | Python | gpl-2.0 | 5,455 | 0.007883 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'ArtistMedia.is_default_image'
db.add_column(u'artist_artistmedia', 'is_default_image',
... | 'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'m... | : u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'def... |
CarlosTenorio/vespapp-web | api/migrations/0019_auto_20160420_1833.py | Python | gpl-3.0 | 766 | 0.001305 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-04-20 16:33
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0018_auto_20160420_1231'),
]
operations = [
... | ),
migrati | ons.AlterField(
model_name='answer',
name='value',
field=models.CharField(max_length=128, verbose_name='Respuesta'),
),
]
|
fstagni/DIRAC | FrameworkSystem/scripts/dirac-admin-proxy-upload.py | Python | gpl-3.0 | 650 | 0.009231 | #!/usr/bin/env python
########################################################################
# | File : dirac-admin-proxy-upload.py
# Author : Adrian Casajus
########################################################################
from __future__ import print_function
import sys
from DIRAC.Core.Base import Script
from DIRAC.FrameworkSystem.Client.ProxyUpload import CLIParams, uploadProxy
__RCSID__ = "$Id$"
... |
if not retVal['OK']:
print(retVal['Message'])
sys.exit(1)
sys.exit(0)
|
spulec/moto | tests/test_cloudformation/fixtures/ec2_classic_eip.py | Python | apache-2.0 | 64 | 0 | template = {"Res | ources": {"EC2EIP": {"Type": "AWS::EC2::EIP" | }}}
|
RedHatQE/rhui-testing-tools | rhuilib/rhuimanager_sync.py | Python | gpl-3.0 | 3,081 | 0.004869 | """ RHUIManager Sync functions """
import re
from stitches.expect import Expect
from rhuilib.rhuimanager import RHUIManager
from rhuilib.util import Util
class RHUIManagerSync(object):
'''
Represents -= Synchronization Status =- RHUI screen
'''
@staticmethod
def sync_cds(connection, cdslist):
... | \[([^\n]*)\].*" + cdsname.replace(".", "\.") + "\s*\r\n([^\n]*)\r\n", re.DOTALL), [1, 2], 60)
connection.cli.exec_command("killall -s SIGINT rhui-manager")
ret_list | = []
for val in [res_list[0]] + res_list[1].split(" "):
val = Util.uncolorify(val.strip())
ret_list.append(val)
RHUIManager.quit(connection)
return ret_list
@staticmethod
def sync_repo(connection, repolist):
'''
sync an individual rep... |
kubevirt/vAdvisor | tests/store/test_event.py | Python | gpl-3.0 | 1,720 | 0 | from vadvisor.store.event import InMemoryStore
import pytest
from freezegun import freeze_time
from datetime import datetime, timedelta
@pytest.fixture
@freeze_time("2012-01-14 03:00:00")
def expired_store():
store = InMemoryStore(60)
# Insert old data
store.put('old')
store.put('old')
store.put('... | ):
assert new_store.get(elements=2) == ['new', 'new']
@freeze_time("2012-01-14 03:02:00")
def test_get_not_older_than(newest_store):
events = newest_store.get(
elements=2,
start_time=datetime.utcnow() - timedelta(seconds=20)
)
assert events == ['newest', 'newest']
@freeze_time("2012-... | nts=2,
stop_time=datetime.utcnow() - timedelta(seconds=20)
)
assert events == ['new', 'new']
|
Nadeflore/dakara-player-vlc | tests/test_background_loader.py | Python | mit | 9,182 | 0.002069 | from unittest import TestCase
from unittest.mock import call, patch
from path import Path
from dakara_player_vlc.background_loader import (
BackgroundLoader,
BackgroundNotFoundError,
)
class BackgroundLoaderTestCase(TestCase):
"""Test the loader for backgrounds
"""
@patch(
"dakara_playe... | round_loader.exists", return_value=True, autospec=True
)
def test_load_default_name_default_directory(self, mocked_exists):
"""Test to load one default background from defauld directory
"""
# create the instance
loader = BackgroundLoader(
default_directory=Path("defau... | default_background_filenames={"background": "background.png"},
)
# pre assert that there are no backgrounds
self.assertDictEqual(loader.backgrounds, {})
# load the backgrounds
loader.load()
# assert the backgrounds
self.assertDictEqual(
load... |
CygnusNetworks/nssct | nssct/controller.py | Python | gpl-2.0 | 2,163 | 0.02589 | # -*- encoding: utf-8 -*-
import logging
from . import report
logger = logging.getLogger(__name__)
class Controller(object):
"""The controller keeps the pieces (engine, collector, and plugins)
together. The collector is just passed on to the plugins, the controller
does not operate itself on a collector. A plugi... | d plugins.
@rtype: bool
"""
workleft = self.engine.step()
if self.pending_plugins and not workleft:
logger.error("some plugins failed to complete")
r | eturn False
return bool(self.pending_plugins)
def run(self, collector, plugins):
"""Start the given plugins and iterate engine steps until all plugins
finish."""
for plugin in plugins:
self.start_plugin(collector, plugin)
while self.step():
pass
|
dcos/shakedown | tests/acceptance/test_dcos_package_cli.py | Python | apache-2.0 | 414 | 0.004831 | from shakedown import *
def test_install_package_cli():
assert not package_installed('dcos-enterprise-cli')
install_package_and_wait('dcos-enterprise-cli')
assert package_installed('dcos-enterprise-cli')
def te | st_uninstall_package_cli():
assert package_installed('dcos-enterprise-cli')
uninstall_package_and_wait('dcos-enterprise-cli')
assert not package_installed('dco | s-enterprise-cli')
|
googleapis/artman | artman/tasks/python_grpc_tasks.py | Python | apache-2.0 | 10,137 | 0.000099 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | protos = list(protoc_utils.find_protos([path], []))
for proto in protos:
src_base_dirs = self._extract_base_dirs(proto)
sub_new_src = os.pa | th.join(
destination_directory,
self._transform(
src_base_dirs, os.path.sep, common_protos))
if paths is not None:
paths.add(sub_new_src)
dest = os.path.join(sub_new_src, os.path.basename(proto))
... |
alexbruy/QGIS | python/plugins/processing/algs/grass7/ext/r_li_mps.py | Python | gpl-2.0 | 1,280 | 0 | # -*- coding: utf-8 -*-
"""
***************************************************************************
r_li_mps.py
-----------
Date : February 2016
Copyright : (C) 2016 by Médéric Ribreux
Email : medspx at medspx dot fr
************************************... |
* 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. *
* *
***************************************************************************
"""
__author__ ... |
candlepin/virt-who | tests/suds/test_reader.py | Python | gpl-2.0 | 4,360 | 0.002753 | # -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or mod | ify it under
# the terms of the (LGPL) GNU Lesser 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; with | out even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Library Lesser General Public License
# for more details at ( http://www.gnu.org/licenses/lgpl.html ).
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, ... |
wwj718/ANALYSE | common/lib/xmodule/xmodule/modulestore/mixed.py | Python | agpl-3.0 | 34,661 | 0.003347 | """
MixedModuleStore allows for aggregation between multiple modulestores.
In this way, courses can be served up both - say - XMLModuleStore or MongoModuleStore
"""
import logging
from contextlib import contextmanager
import itertools
import functools
from contracts import contract, new_contract
from opaque_keys im... | _modulestore_type() == modulestore_type:
return store
return None
def fill_in_run(self, course_key):
"""
Some course_keys are used without runs. This function calls the corresponding
fill_in_run fu | nction on the appropriate modulestore.
"""
store = self._get_modulestore_for_courseid(course_key)
if not hasattr(store, 'fill_in_run'):
return course_key
return store |
wh20160213/WuhuaLearnToPython | python_study_level1/package1/studya4_socket_client.py | Python | lgpl-3.0 | 445 | 0.011331 | #!/usr/bin/python3
# 文件名:client.py
# 导入 socket、sys 模块
import socket
import sys
# 创建 socket 对象
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 获取本地主机 | 名
host = socket.gethostname()
# 设置端口好
port = 9999
# 连接服务,指定主机和端口
s.connect((host, port))
# 接收小于 1024 字节的数据
msg = s.recv(1024)
s.close | ()
print (msg.decode('utf-8')) |
tensorflow/minigo | bigtable_input.py | Python | apache-2.0 | 29,247 | 0.000615 | # Copyright 2018 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 agreed to in writing, ... | return
max_versions_rule = bigtable_column_family.MaxVersionsGCRule(1)
self.bt_table.create(column_families={
METADATA: max_versions_rule,
TFEXAMPLE: max_versions_rule})
@prop | erty
def latest_game_number(self):
"""Re |
krishna11888/ai | third_party/pattern/pattern/graph/commonsense.py | Python | gpl-2.0 | 11,504 | 0.007476 | #### PATTERN | COMMONSENSE #########################################################################
# Copyright (c) 2010 University of Antwerp, Belgium
# Author: Tom De Smedt <tom@organisms.be>
# License: BSD (see LICENSE.txt for details).
# http://www.clips.ua.ac.be/pages/pattern
####################################... | instance(concept1, list):
| concept1 = [isinstance(n, Node) and n or self[n] for n in concept1]
if isinstance(concept2, list):
concept2 = [isinstance(n, Node) and n or self[n] for n in concept2]
h = lambda id1, id2: heuristic[1](self.edge(id1, id2))
w = 0.0
for p1 in concept1[:k]:
... |
bitmazk/cmsplugin-redirect | cmsplugin_redirect/tests/south_settings.py | Python | mit | 586 | 0 | """
These settings are used by the ``manage.py`` command.
With normal tests we want to use the fast | est possible way which is an
in-memory sqlite database but if you want to create South migrations you
need a pers | istant database.
Unfortunately there seems to be an issue with either South or syncdb so that
defining two routers ("default" and "south") does not work.
"""
from cmsplugin_redirect.tests.test_settings import * # NOQA
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'd... |
boisvert42/npr-puzzle-python | 2018/1028_musical_all_of_us.py | Python | cc0-1.0 | 1,235 | 0.014599 | '''
NPR Puzzle 2018-10-28
https://www.npr.org/2018/10/28/660936138/sunday-puzzle-r | ow-row-row
Think of a famous Broadway musical in two words.
Change one letter in it to the preceding letter of the alphabet —
so B would become A, C would become B, etc.
Remove the space so you have a solid word.
The result will name something that all of us are part of. What is it?
'''
import sys
sys.path.append(... | tools as nct
from nltk.corpus import wordnet as wn
import re
#%%
# Get a list of musicals from Wikipedia
musicals = set(x for x in nct.wikipedia_category_members('Broadway_musicals') if x.count(' ') == 1)
#musicals = musicals.union(wikipedia_category_members('Off-Broadway_musicals'))
#musicals = musicals.union(wikipe... |
rockfruit/bika.lims | bika/lims/browser/worksheet/views/analyses_transposed.py | Python | agpl-3.0 | 4,358 | 0.006425 | # coding=utf-8
# This f | ile is part of Bika LIMS
#
# Copyright 2011-2016 by it's authors.
# Some rights reserved. See LICENSE.txt, AUTHORS.txt.
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from bika.lims.browser.bika_listing import | BikaListingTable
from bika.lims.browser.worksheet.views.analyses import AnalysesView
class AnalysesTransposedView(AnalysesView):
""" The view for displaying the table of manage_results transposed.
Analysis Requests are displayed in columns and analyses in rows.
Uses most of the logic provided by B... |
pacoqueen/bbinn | SQLObject/SQLObject-0.6.1/sqlobject/mysql/__init__.py | Python | gpl-2.0 | 306 | 0.009804 | from | sqlobject.dbconnection import registerConnection
def builder():
import mysqlconnection
return mysqlconnection.MySQLConnection
def isSupported():
try:
import MySQLdb
except ImportError:
return False
return True
registerConnection(['mysql'], builder, isSuppo | rted)
|
jankoslavic/numpy | numpy/lib/function_base.py | Python | bsd-3-clause | 132,305 | 0.000136 | from __future__ import division, absolute_import, print_function
import warnings
import sys
import collections
import operator
import numpy as np
import numpy.core.numeric as _nx
from numpy.core import linspace, atleast_1d, atleast_2d
from numpy.core.numeric import (
ones, zeros, arange, concatenate, array, asarr... | be equal to 1 unless bins of unity
width are chosen; it is not a probability *mass* function.
Overrides the `normed` keyword if given.
Returns
-------
hist : array
The values of the histogram. See `normed` and `weights` for a
description of the possible semantics.
bin_e... |
-----
All but the last (righthand-most) bin is half-open. In other words, if
`bins` is::
[1, 2, 3, 4]
then the first bin is ``[1, 2)`` (including 1, but excluding 2) and the
second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which *includes*
4.
Examples
--------
>>>... |
sander76/home-assistant | tests/components/system_log/test_init.py | Python | apache-2.0 | 11,361 | 0.000616 | """Test system log component."""
import asyncio
import logging
import queue
from unittest.mock import MagicMock, patch
import pytest
from homeassistant.bootstrap import async_setup_component
from homeassistant.components import system_log
from homeassistant.core import callback
_LOGGER = logging.getLogger("test_logg... | h patch("logging.ge | tLogger", return_value=logger) as mock_logging:
await hass.services.async_call(
system_log.DOMAIN, system_log.SERVICE_WRITE, {"message": "test_message"}
)
await hass.async_block_till_done()
mock_logging.assert_called_once_with("homeassistant.components.system_log.external")
a... |
grapesmoker/regulations-parser | regparser/grammar/amdpar.py | Python | cc0-1.0 | 17,063 | 0.000117 | # vim: set encoding=utf-8
# @todo: this file is becoming too large; refactor
import logging
import string
from pyparsing import CaselessLiteral, FollowedBy, OneOrMore, Optional
from pyparsing import Suppress, Word, LineEnd, ZeroOrMore
from regparser.grammar import atomic, tokens, unified
from regparser.grammar.utils ... | ).setParseAction(lambda m: tokens.Context(
[None, 'Interpretations', None,
_paren_join([m.p2, m.p3, m.p4, m.plaintext_p5, m.plaintext_p6])
], bool(m.certain)))
appendix = (
context_certainty
+ unified.marker_appendix
+ Optional(Marker("to") + unified.marker_part)
).setParseActi... | endix:' + m.appendix], bool(m.certain)))
section = (
context_certainty
+ atomic.section_marker
+ unified.part_section).setParseAction(lambda m: tokens.Context(
[m.part, None, m.section], bool(m.certain)))
# Paragraph components (used when not replacing the whole paragraph)
section_heading = Mark... |
slackpad/hashtagtodo-open | todo/stat_rollup.py | Python | mit | 1,528 | 0.002618 | from datetime import datetime
from collections import defaultdict
from todo.models.calendar import Calendar
from todo.models.event import Event
from todo.models.stat import Stat
from todo.models.user import User
def rollup_users():
rollup = defaultdict(lambda: defaultdict(int))
for user in User.get_all():
... | ict(int)))
for event in Event.query():
user = event.key.parent().parent().id()
(year, week, day) = event.created.isocalendar | ()
created[year][week][user] += 1
(year, week, day) = event.updated.isocalendar()
engaged[year][week][user] += 1
for year, weekly in created.iteritems():
for week, users in weekly.iteritems():
Stat.create_or_update('user-created-event', year, week, len(users.keys()))
... |
twaldear/flask-secure-headers | flask_secure_headers/tests/core_test.py | Python | mit | 5,918 | 0.038189 | import unittest
from flask import Flask
from flask_secure_headers.core import Secure_Headers
from flask_secure_headers.headers import CSP
class TestCSPHeaderCreation(unittest.TestCase):
def test_CSP_pass(self):
sh = Secure_Headers()
defaultCSP = sh.defaultPolicies['CSP']
""" test CSP policy update """
h = CS... | result = c.get('/')
self.assertEquals(result.headers.get('Content-Security-Policy'),"default-src 'none'")
self.assertEquals(result.headers.get('Public-Key-Pins'),"pin-sha256=test123")
def test_wrapper_update_function(self):
""" test updating policies from wrapper """
self.sh.rewrite(
{
'CSP':{'defau... |
'CSP':{'script-src':['self','code.jquery.com']},
'X_Permitted_Cross_Domain_Policies':{'value':'none'},
'X-XSS-Protection':{'value':1,'mode':False},
'HPKP':{'pins':[{'sha256':'test2256'}]},
}
)
def index(): return "hi"
with self.app.test_client() as c:
result = c.get('/')
self.assertEqual... |
cloudfoundry-community/splunk-firehose-nozzle | testing/integration/lib/helper.py | Python | apache-2.0 | 507 | 0.001972 | # Common functions used in this project
import os
d | ef get_integration_folder():
"""
returns the integration test folder
"""
return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
def get_config_fold | er():
"""
returns the config folder
"""
return os.path.join(get_integration_folder(), "config")
def get_project_folder():
"""
returns the project root folder
"""
return get_integration_folder().replace("/testing/integration", "/")
|
happyleavesaoc/aoc-mgz | mgz/const.py | Python | mit | 6,198 | 0.001613 | """Constants."""
# pylint: disable=too-many-lines
MODS = {
1: 'Wololo Kingdoms',
2: 'Portuguese Civilization Mod III',
3: 'Age of Chivalry',
4: 'Sengoku',
7: 'Realms',
101: 'King of the Hippo'
}
SPEEDS = {
100: 'slow',
150: 'standard',
169: 'standard', # de
178: 'standard', # ... | ilippines',
112: 'Bog Islands',
113: 'Mangrove Jungle',
114: 'Pacific Islands',
115: 'Sandbank',
116: 'Water Nomad',
117: 'Jungle Islands',
118: 'Holy Line',
119: 'Border Stones',
120: 'Yin Yang',
121: 'Jungle Lanes',
122: 'Alpine Lakes',
123: 'Bogland',
124: 'Mountai... | 'Golden Swamp',
140: 'Four Lakes',
141: 'Land Nomad',
142: 'Battle on Ice',
143: 'El Dorado',
144: 'Fall of Axum',
145: 'Fall of Rome',
146: 'Majapahit Empire',
147: 'Amazon Tunnel',
148: 'Coastal Forest',
149: 'African Clearing',
150: 'Atacama',
151: 'Seize the Mountain'... |
VectorBlox/PYNQ | python/pynq/iop/tests/test_pmod_cable.py | Python | bsd-3-clause | 7,289 | 0.025655 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of ... | i==0:
data1 = [0,0,0,0,0,0,0,1]
else:
data1 = data1[1:]+data1[:1]
data2 = [0,0,0,0,0,0,0,0]
tx[7-i].write(data1[7-i])
sleep(0.001)
data2[7-i] = rx[7-i].read()
assert data1==data2,\
'Sent {} != received {} at Pin {}.'.format(data1,data2,... | test_lshift0():
"""Test for left shifting the bit "0".
The sender will send patterns with the bit "0" left shifted each time.
"""
print('\nGenerating tests for left shifting a \"0\"...')
global tx,rx
for i in range(8):
if i==0:
data1 = [1,1,1,1,1,1,1,0]
... |
NikNitro/Python-iBeacon-Scan | sympy/assumptions/tests/test_assumptions_2.py | Python | gpl-3.0 | 1,849 | 0.000541 | """
rename this to test_assumptions.py when the old assumptions system is deleted
"""
from sympy.abc import x, y
from sympy.assumptions.assume import global_assumptions, Predicate
from sympy.assumptions.ask import _extract_facts, Q
from sympy.core import symbols
from sympy.logic.boolalg import Or
from sympy.printing im... | ) == None
assert _extract_facts(~(a(x) | b(y)), x) == ~a
def test_global():
"""Test for global assumptions"""
global_assumptions.add(Q.is_true(x > 0))
assert Q.is_true(x > 0) in global_assumptions
global_assumptions.remove(Q.is_true(x > 0))
assert not Q.is_true(x > 0) in global_assumptions
... | 0) in global_assumptions
global_assumptions.clear()
assert not Q.is_true(x > 0) in global_assumptions
assert not Q.is_true(y > 0) in global_assumptions
|
JensGrabner/mpmath | mpmath/calculus/polynomials.py | Python | bsd-3-clause | 7,877 | 0.001396 | from ..libmp.backend import xrange
from .calculus import defun
#----------------------------------------------------------------------------#
# Polynomials #
#----------------------------------------------------------------------------#
# XXX: extra preci... | roots must not be the zero polynomial")
# Constant polynomial with no roots
return []
orig = ctx.prec
tol = +ctx.eps
with ctx.extraprec(extraprec):
deg = len(coeffs) - 1
# Must be monic
lead = ctx.convert(coeffs[0])
if lead == 1:
coeffs = [ctx.con... | da x: ctx.polyval(coeffs, x)
if roots_init is None:
roots = [ctx.mpc((0.4+0.9j)**n) for n in xrange(deg)]
else:
roots = [None]*deg;
deg_init = min(deg, len(roots_init))
roots[:deg_init] = list(roots_init[:deg_init])
roots[deg_init:] = [ctx.mpc(... |
kobejean/tensorflow | tensorflow/contrib/eager/python/examples/revnet/main.py | Python | apache-2.0 | 9,700 | 0.007835 | # 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 required by applica... | se,
data_format=config.data_format,
dtype=config.dtype,
prefetch=config.eval_batch_size)
return ds_train, ds_train_one_shot, ds_validation, ds_test
def train_one_iter(model, inputs, | labels, optimizer, global_step=None):
"""Train for one iteration."""
logits, saved_hiddens = model(inputs, training=True)
values = model.get_moving_stats()
grads, loss = model.compute_gradients(saved_hiddens, labels)
# Restore moving averages when executing eagerly to avoid updating twice
model.restore_movi... |
AlexSzatmary/bake | examples/poisson/myBake/__init__.py | Python | mit | 19 | 0.052632 | #from api | import *
| |
mitodl/micromasters | grades/tasks.py | Python | bsd-3-clause | 7,724 | 0.002071 | """
Tasks for the grades app
"""
import logging
from celery import group
from celery.result import GroupResult
from django.contrib.auth.models import User
from django.core.cache import caches
from django.db import IntegrityError
from django.db.models import OuterRef, Exists
from django_redis import get_redis_connectio... | ed the course but don't have a certificate yet
users_need_cert = FinalGrade.objects.annotate(
course_certificate=Exists(course_certificates)
).filter(
course_run__course=course,
status=FinalGradeS | tatus.COMPLETE,
passed=True,
course_certificate=False
).values_list('user', flat=True)
if course.has_exam:
# need also to pass exam
users_need_cert = ProctoredExamGrade.objects.filter(
course=course,
passed=True,
... |
ITU-DB-MANAGEMENT-HM/itunder-backend-rest | controllers/lecturers.py | Python | apache-2.0 | 2,001 | 0.003998 | import re
import json
import requests
from flask import request
from constants import MOBIL_ITU_AUTH_URL
from middlewares import auth_func
from server import app
from models.setupdb import lecturers
@app.route('/api/lecturers', methods=['GET', 'POST', 'DELETE', 'PUT'])
def lecturer():
"""
GET request sho... | if not re.match("[^@]+@[^@]+\.[^@]+", data['email']):
return "Invalid email address!", 404
lecturers.addLecturer(data)
return "Success", 200
elif request.method == 'DELETE':
data = request.get_json()
lecturers.removeLecturer(data=data)
try:
d... | lecturers.listLecturersOfDepartment(data=dep))
except:
return "Please give proper department", 200
elif request.method == 'PUT':
data = request.get_json()
json.dumps(lecturers.updateLecturer(data))
try:
dep = (request.args["dep"])
return json.dum... |
mgadi/naemonbox | sources/psdash/gevent-1.0.1/greentest/test__socket_timeout.py | Python | gpl-2.0 | 1,258 | 0.000795 | import sys
import gevent
from gevent import socket
import greentest
class Test(greentest.TestCase):
def start(self):
self.server = socket.socket()
self.server.bind(('127.0.0.1', 0))
self.server.listen(1)
self.server_port = self.server.getsockname()[1]
self.acceptor = geven... | acce | ptor.kill()
del self.acceptor
del self.server
def test(self):
self.start()
try:
sock = socket.socket()
sock.connect(('127.0.0.1', self.server_port))
try:
sock.settimeout(0.1)
try:
result = sock.r... |
lakshmi-kannan/st2contrib | packs/twitter/sensors/twitter_search_sensor.py | Python | apache-2.0 | 3,371 | 0.000593 | from TwitterSearch import TwitterSearch
from TwitterSearch import TwitterSearchOrder
from st2reactor.sensor.base import PollingSensor
__all__ = [
'TwitterSearchSensor'
]
BASE_URL = 'https://twitter.com'
class TwitterSearchSensor(PollingSensor):
def __init__(self, sensor_service, config=None, poll_interval=... | gger.exception('Polling Twitter failed: %s' % (str(e)))
return
tweets = list(reversed(tweets))
if tweets:
self._set_last_id(last_id=tweets[-1]['id'])
for tweet in tweets:
self._dispatch_trigger_for_tweet(tweet=tweet)
def cleanup(self):
pass
... | :
pass
def update_trigger(self, trigger):
pass
def remove_trigger(self, trigger):
pass
def _get_last_id(self):
if not self._last_id and hasattr(self._sensor_service, 'get_value'):
self._last_id = self._sensor_service.get_value(name='last_id')
return se... |
BhallaLab/moose | moose-examples/squid/electronics.py | Python | gpl-3.0 | 3,885 | 0.008237 | # electronics.py ---
#
# Filename: electronics.py
# Description:
# Author: Subhasis Ray
# Maintainer:
# Created: Wed Feb 22 00:53:38 2012 (+0530)
# Version:
# Last-Updated: Tue Jul 10 10:28:40 2012 (+0530)
# By: subha
# Update #: 221
# URL:
# Keywords:
# Compatibility:
#
#
# Commentary:
#
#
... | +"/vclamp")
self.vclamp.gain = 0.0
self.vclamp.saturation = 1e10
self.iclamp = moose.DiffAmp(path+"/iclamp")
self.iclamp.gain = 0.0
self.iclamp.saturation = 1e10
self.pid = moose.PIDController(path+"/pid")
self.pid.gain = 0.5
self.pid.tauI = 0.02
s... | e.connect(self.pulsegen, "output", self.iclamp, "plusIn")
moose.connect(self.iclamp, "output", compartment, "injectMsg")
# Connect voltage clamp circuitry
moose.connect(self.pulsegen, "output", self.lowpass, "injectIn")
moose.connect(self.lowpass, "output", self.vclamp, "plusIn")
... |
tonygalmiche/is_plastigray | report/is_article_sans_cde_ouverte_fou.py | Python | mit | 3,344 | 0.007478 | # -*- coding: utf-8 -*-
from openerp import tools
from openerp import models,fields,api
from openerp.tools.translate import _
class is_article_sans_cde_ouverte_fou(models.Model):
_name='is.article.sans.cde.ouverte.fou'
_order='product_id'
_auto = False
product_id = fields.Ma... | pt2.is_gestionnaire_id,
pt2.product_nb_fournisseurs,
pt2.product_p | artner_id,
pt2.nb_cde_ouverte,
pt2.cde_ouverte_partner_id
from (
select
pt.id,
pt.id product_id,
pt.is_category_id,
pt.is_gestionnaire_id,
... |
Alir3z4/python-currencies | tests/test_currency.py | Python | gpl-3.0 | 1,997 | 0.000501 | from unittest import TestCase
from currencies import Currency, get_version, __VERSION__
from currencies.exceptions import CurrencyDoesNotExist
class TestCurrency(TestCase):
def test_get_version(self):
version = get_version()
self.assertIsInstance(version, str)
self.assertEqual(len(vers | ion.split('.')), len(__VERSION__))
def test_get_money_currency(self):
currency = Currency('USD')
self.assertIsInstance(curren | cy.get_money_currency(), str)
self.assertEqual(currency.get_money_currency(), 'USD')
def test_set_money_currency(self):
currency = Currency('USD')
self.assertEqual(currency.get_money_currency(), 'USD')
self.assertEqual(currency.get_money_format(13), '$13')
currency.set_mon... |
uptown/django-town | django_town/oauth2/management/commands/update_default_scope.py | Python | mit | 452 | 0.00885 | from django.core.management.base import BaseCommand
from django_town.oauth2.models import Client
from django_town.core.settings import OAUTH2_SETTINGS
class Command(BaseCommand):
def handle(self, *args, **options):
Client.objects.all().update(available_scope=OAUTH2_SETTINGS.default_scope)
print Cl... | t.objects.all()[0].available_scope
# print Client.objects.create(name=args[0], service=Servic | e.objects.get(name=args[1])) |
foobarbazblarg/stayclean | stayclean-2020-december/venv/lib/python3.8/site-packages/pip/_vendor/resolvelib/providers.py | Python | mit | 5,091 | 0 | class AbstractProvider(object):
"""Delegate class to provide requirement interface for the resolver."""
def identify(self, requirement_or_candidate):
"""Given a requirement or candidate, return an identifier for it.
This is used in many places to identify a requirement or candidate,
e.... | ne`.
:param candida | tes: An iterable of possible candidates.
:param information: A list of requirement information.
The `candidates` iterable's exact type depends on the return type of
`find_matches()`. A sequence is passed-in as-is if possible. If it
returns a callble, the iterator returned by that callab... |
shiminasai/ciat_plataforma | ciat_plataforma/context.py | Python | mit | 165 | 0.012121 | from comunicacion.foros.mode | ls import Imagen
def globales(request):
imagenes_global = Imagen.objects.all()[:9]
return {'imagenes_global':imagen | es_global} |
raonyguimaraes/mendelmd | individuals/templatetags/upload_tags.py | Python | bsd-3-clause | 3,137 | 0.00255 | from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def upload_js():
return mark_safe("""
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i+... | <i class="glyphicon glyphicon-upload"></i>
<span>{%=locale.fileupload.start%}</span>
</button>
{% } %}
{% if (!i) { %}
<button class="btn btn-warning cancel">
| <i class="glyphicon glyphicon-ban-circle"></i>
<span>{%=locale.fileupload.cancel%}</span>
</button>
{% } %}
</td>
</tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (... |
mick-d/nipype | nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py | Python | bsd-3-clause | 1,430 | 0.021678 | # AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from __future__ import unicode_literals
from ..tracks import StreamlineTractography
def test_StreamlineTractography_inputs():
input_map | = dict(gfa_thresh=dict(mandatory=True,
usedefault=True,
),
ignore_exception=dict(nohash=True,
usedefault | =True,
),
in_file=dict(mandatory=True,
),
in_model=dict(),
in_peaks=dict(),
min_angle=dict(mandatory=True,
usedefault=True,
),
multiprocess=dict(mandatory=True,
usedefault=True,
),
num_seeds=dict(mandatory=True,
usedefault=True,
),
out_prefix=dict(),
peak_... |
jdelacueva/django-isegory | setup.py | Python | agpl-3.0 | 1,049 | 0 | import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).r | ead()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-isegory',
version='0.1',
packages=['isegory'],
include_package_data=True,
license='AGPL',
description='A simple Django app to declare the provenance of a dataset.',
long_description=REA... | l='jdelacueva@derecho-internet.org',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: AGPL',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programmi... |
Flexget/Flexget | flexget/components/managed_lists/lists/regexp_list/cli.py | Python | mit | 4,835 | 0.003723 | import re
from argparse import ArgumentParser, ArgumentTypeError
from flexget import options
from flexget.event import event
from flexget.terminal import TerminalTable, console, table_parser
from flexget.utils.database import Session
from . import db
def do_cli(manager, options):
"""Handle regexp-list cli"""
... | )
)
else:
console("Regexp {} already exists in list {}".format(options.regexp, regexp_list.name))
def action_del(options):
with Session() as session:
regexp_list = db.get_list_by_exact_name(options.list_name)
if not regexp_list:
console('Could n... | name {}'.format(options.list_name))
return
regexp = db.get_regexp(list_id=regexp_list.id, regexp=options.regexp, session=session)
if regexp:
console('Removing regexp {} from list {}'.format(options.regexp, options.list_name))
session.delete(regexp)
else:
... |
google-research/google-research | cascaded_networks/models/tdl.py | Python | apache-2.0 | 2,301 | 0.008257 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | ."""
def __init__(self, *args, **kwargs):
"""Initialize OSD kernel."""
super().__init__()
self.reset()
def reset(self):
self.state = None
def forward(self, current_state):
if self.state is not None:
prev_state = self.state
else:
prev_state = torch.zeros_like(current_state)
... | ss ExponentiallyWeightedSmoothingKernel(nn.Module):
"""Exponentially Weighted Smoothing Kernel.
alpha=0.0
--> state(t) = current_state
Functionally equivalent to sequential ResNet
alpha=1.0
--> state(t) = prev_state
Functionally equivalent to tapped delay line for 1 timestep delay
0.0 < alpha < 1.0
... |
Asnelchristian/coala-bears | bears/general/LineCountBear.py | Python | agpl-3.0 | 1,107 | 0 | from coalib.bears.LocalBear import LocalBear
from coalib.results.Result import Result
from coalib.results.RESULT_SEVERITY import RESULT_SEVERITY
class LineCountBear(LocalBear):
LANGUAGES = {'All'}
AUTHORS = {'The coala developers'}
AUTHORS_EMAILS = {'coala-devel@googlegroups.com'}
LICENSE = 'AGPL-3.0'... | lf, filename, file, max_lines_per_file: int):
"""
Count the number of lines in a file and ensure that they are
smaller than a given size.
:param max_lines_per_file: Number of lines allowed per file.
"""
file_length | = len(file)
if file_length > max_lines_per_file:
yield Result.from_values(
origin=self,
message=('This file had {count} lines, which is {extra} '
'lines more than the maximum limit specified.'
.format(count=file_length... |
ioram7/keystone-federado-pgid2013 | build/python-keystoneclient/keystoneclient/v3/users.py | Python | apache-2.0 | 3,684 | 0 | # Copyright 2011 OpenStack LLC.
# Copyright 2011 Nebula, 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/LICENS... | d 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 keystoneclient import base
class User(base.Resource):
"""Represen... | Manager):
"""Manager class for manipulating Identity users."""
resource_class = User
collection_key = 'users'
key = 'user'
def _require_user_and_group(self, user, group):
if not (user and group):
msg = 'Specify both a user and a group'
raise exceptions.ValidationErro... |
tadgh/ArgoRevisit | third_party/nltk/chat/suntsu.py | Python | apache-2.0 | 6,223 | 0.00932 | # Natural Language Toolkit: Sun Tsu-Bot
#
# Copyright (C) 2001-2011 NLTK Project
# Author: Sam Huston 2007
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
from util import *
"""
Tsu bot responds to all queries with a Sun Tsu sayings
Quoted from Sun Tsu's The Art of War
Translated by LIONEL ... | rmy.",
"By attempting to govern an army in the same way as he administers a kingdom, being ignorant of the conditions which obtain in an army. This causes restlessness in the soldier's minds.",
"By employing the officers of his army without discrimination, throu | gh ignorance of the military principle of adaptation to circumstances. This shakes the confidence of the soldiers.",
"There are five essentials for victory",
"He will win who knows when to fight and when not to fight.",
"He will win who knows how to handle both superior and inferior forces.",
"He will win w... |
alphacsc/alphacsc | examples/csc/plot_lfp_data.py | Python | bsd-3-clause | 4,048 | 0.001482 | """
==============================
CSC to learn LFP spiking atoms
==============================
Here, we show how CSC can be used to learn spiking
atoms from Local Field Potential (LFP) data [1].
[1] Hitziger, Sebastian, et al.
Adaptive Waveform Learning: A Framework for Modeling Variability in
Neurophysiolo... | Transactions on Signal Processing (2017).
"""
###############################################################################
# First, let us fetch the data (~14 MB)
import os
from mne.datasets import fetch_dataset
from mne.utils import get_confi | g
url = ('https://github.com/hitziger/AWL/raw/master/Experiments/data/'
'LFP_data_contiguous_1250_Hz.mat')
folder_name = "LFP"
archive_name = "LFP_data_contiguous_1250_Hz.mat"
fname = fetch_dataset(
{"dataset_name": "LFP_data",
"url": url,
"archive_name": archive_name,
"folder_name": folder... |
blamed-cloud/AISuite | alphabeta.py | Python | mit | 6,127 | 0.0315 | #!/usr/bin/env python
#alphabeta.py
from __future__ import print_function
import sys
import random
#import player # I don't think this is needed anymore
import transpositions
UPPER_BOUND = 100
LOWER_BOUND = -100
DEFAULT_DEPTH = 5
VOLATILE_DEPTH = -3
ORDER_NORMAL = 1
ORDER_FREE = 2
#function for returning randomly f... | lity_measure(game):
return False
class ABPruning_Tree(object):
def __init__(self, game, depth_lim = DEFAULT_DEPTH, A = LOWER_BOUND, B = UPPER_BOUND, heuristic = None, i_am_max = True):
self.game = game
self.state = str(self.game)
self.children = {}
self.child_moves = {}
self.best_child = []
self.alpha = ... | value = 0
self.is_max = i_am_max
self.have_children = False
self.tpos_mngr = transpositions.Transposition_Manager(3)
self.choose_best_child = self.best_chance_selector
self.depth_sel = self.best_chance_sel
def re_init(self, depth, A, B):
self.depth_limit = depth
self.alpha = A
self.beta = B
self.v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.