prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
# 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 Li... | .matches_template_namespace('fake', value))
def test_apply_resource_a | lias_namespace(self):
namespaced = namespace.apply_resource_alias_namespace('compute')
self.assertEqual(namespaced, 'Tuskar::compute')
def test_remove_resource_alias_namespace(self):
stripped = namespace.remove_resource_alias_namespace(
'Tuskar::controller')
self.assertE... |
ent = Mock()
test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client)
self.instance_service.get_instance_from_instance_id = Mock(return_value=None)
result = self.instance_service.attach_nic_to_net(openstack_session=self.openstack_session,
... |
logger=self.mock_logger)
self.assertEqual(result, None)
def test_attach_nic_to_net_failure_exception(self):
mock_client = Mock()
test_nova_instance_service.novaclient.Client = Mock(return_value=mock_client)
mock_instance = M... | ce_attach = Mock(side_effect=Exception)
with self.assertRaises(Exception) as context:
result = self.instance_service.attach_nic_to_net(openstack_session=self.openstack_session,
net_id='test_net_id',
... |
#
# Alignak 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public Licen... | t will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <h... | m .alignak_test import *
from alignak.macroresolver import MacroResolver
from alignak.commandcall import CommandCall
class MacroResolverTester(object):
def get_hst_svc(self):
svc = self._scheduler.services.find_srv_by_name_and_hostname("test_host_0", "test_ok_0")
hst = self._scheduler.hosts.find_b... |
# Version 4.0
import csv
import sys
count = 10
offset = 0
if len(sys.argv) >= 3:
count = int(sys.argv[1])
offset = int(sys.argv[2]) - 1
start = offset*count
start = 1 if start== | 0 else start
end = start + count
r = csv.reader(sys.stdin)
rows = []
i = 0
for l in r:
rows.append(l[:1] + l[start:end])
i = i + 1
if(i > 1):
csv.wri | ter(sys.stdout).writerows(rows)
|
c language governing permissions and
# limitations under the License.
import re
import sys
import logging
from threading import Thread, Lock, Event
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty
from ncclient.xml_ import *
from ncclient.capabilities import Capabilities
... | def callback(self, root, raw):
"""Called when a new XML document is received. The *root* argument allows the callback to determine whether it wants to further process the document.
Here, *root* is a tuple of *(tag, attributes)* where *tag* is the qualified name of the | root element and *attributes* is a dictionary of its attributes (also qualified names).
*raw* will contain the XML document as a string.
"""
raise NotImplementedError
def errback(self, ex):
"""Called when an error occurs.
:type ex: :exc:`Exception`
"""
rai... |
from .__about__ import __version__
from .portworx import PortworxCheck
__all__ = ['__version__', 'PortworxChe | ck']
| |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
from zeeko._build_helpers import get_utils_extension_args, get_zmq_extension_args, _generate_cython_extensions, pxd, get_package_data
from astropy_helpers import setup_helpers
utilities = [pxd("..utils.rc"),
pxd("..utils.msg"),
... | d("..cyloop.statemachine"), pxd(".snail"), pxd(".base")]
dependencies = {
'base' : utilities + [ pxd("..cyloop.throttle") ],
'snail' : utilities + [ pxd("..cyloop.throttle"), pxd("..cyloop.statemachine") ],
'client' : utilities + base + [ pxd("..messages.receiver") ],
'server' : utilities + bas... | er") ],
}
def get_extensions(**kwargs):
"""Get the Cython extensions"""
extension_args = setup_helpers.DistutilsExtensionArgs()
extension_args.update(get_utils_extension_args())
extension_args.update(get_zmq_extension_args())
extension_args['include_dirs'].append('numpy')
package_name = __... |
#!/usr/bin/env python
# Encoding: utf-8
# -----------------------------------------------------------------------------
# Project : Broken Promises
# -----------------------------------------------------------------------------
# Author : Edouard Richard <edou4rd@gmail.com>
# ----------... | ot specify a file name, the program writes data to standard output (e.g. stdout)", default=None)
# Think to update the README.md file after modifying the options
options, a | rgs = oparser.parse_args()
assert len(args) > 0 and len(args) <= 3
if options.output_file:
sys.stdout = open(options.output_file, 'a')
channels = brokenpromises.channels.get_available_channels()
if options.channels_file:
with open(options.channels_file) as f:
channels = [line.replace("\n", "") for line in f.readl... |
#/usr/bin/env python
# -#- coding: utf-8 -#-
#
# contract/core/api.py - functions which simplify contract package feature access
#
# This file is part of OndALear collection of open source components
#
# This software is provided 'as-is', without any express or implied
# warranty. In no event will the authors be hel... | aram file_name: XML file name.
:type file_name: str.
:returns: BusinessContractWorkspace -- contract object graph container.
"" | "
package_desc = BusContractCorePackageDescriptor.get_instance()
root_obj = busxml.core.api.parse_file(file_name, package_desc)
return root_obj
def export_to_string(obj):
"""Export contract object graph to string
:param obj: Contract object graph container.
:type obj: BusinessContract... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from utils.init_weights import init_weights, normalized_columns_initializer
from core.mo... | _dims)
self.softplus = nn.Softplus()
# 2. value output
self.value_5 = nn.Linear(self.hidden_dim, 1)
self._reset()
def _init_weights(self):
self.apply(init_weights) |
self.fc1.weight.data = normalized_columns_initializer(self.fc1.weight.data, 0.01)
self.fc1.bias.data.fill_(0)
self.fc2.weight.data = normalized_columns_initializer(self.fc2.weight.data, 0.01)
self.fc2.bias.data.fill_(0)
self.fc3.weight.data = normalized_columns_initializer(self.... |
n | = int(input())
s = input()
letterlist = ['x', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
letter = {}
for l in letterlist:
letter[l] = 0
for i in range(n):
if s[i:i+1] in letterlist:
letter[s[i:i+1]] += 1
if letter['x'] > 0 and letter['0'] > 0:
letter['0'] -= 1... | del letter['x']
del letterlist[0]
res = '0x'
if any(c > 0 for c in letter.values()):
letterlist.reverse()
for l in letterlist:
res += l*letter[l]
print(res)
else:
print('No')
|
from django.apps import AppCo | nfig
| class TorrentsConfig(AppConfig):
name = 'torrents'
|
import sys
import json
def make_column_to_candidate_dict(header_row):
my_dict = {}
for colIndex, candidate in enumerate(header_row):
my_dict[colIndex] = candidate.strip()
return my_dict
def return_candidates_in_order(row, col_to_candidate_dict):
ballot = []
for i in range(0,len(row)):
... | ',\n'.join(candidate_lists)
php += '\n )'
return php
def get_ballot_arrays(filename):
ballots = []
heade | r = True
ids = False
with open(filename, 'r') as csv:
for line in csv.readlines():
row = split_line(line)
if header:
header = False
ids = True
elif ids:
col_to_candidate_dict = make_column_to_candidate_dict(row)
... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/structure/ta | tooine/shared_pillar_pristine_small_style_01.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN | MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
#!/usr/bin/eny python
#coding:utf-8
from gi.repository | import Gtk
class ButtonWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title='Button Demo')
self.set_border_width(10)
hbox = Gtk.Box(spacing=6)
self.add(hbox)
button = Gtk.Button('Click M | e')
button.connect('clicked', self.on_click_me_clicked)
hbox.pack_start(button, True, True, 0)
button = Gtk.Button(stock=Gtk.STOCK_OPEN)
button.connect('clicked', self.on_open_clicked)
hbox.pack_start(button, True, True, 0)
button = Gtk.Button('_Close', use_underline=Tr... |
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2012 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## 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 Foundati... | tSensitive(wizard, ['next_button'])
self.check_wizard(wizard, 'wizard-stock-transfer-create')
step = wizard.get_current_step()
step.destination_branch.set_active(0)
self.assertSensitive(wizard, ['next_button'])
self.click(wizard.next_button)
step = wizard.get_current_st... | _sellable()
self.check_wizard(wizard, 'wizard-stock-transfer-products')
module = 'stoqlib.gui.events.StockTransferWizardFinishEvent.emit'
with mock.patch(module) as emit:
with mock.patch.object(self.store, 'commit'):
self.click(wizard.next_button)
self.a... |
""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """
# Local imports
from lib2to3 import fixer_base
from lib2to3.fixer_util import BlankLine, syms, token
class FixItertoolsImports(fixer_base.BaseFix):
PATTERN = """
import_from< 'from' 'itertools' 'import' imports=any >
... | n children:
if remove_comma and child.type == token.COMMA:
child.remove()
else:
remove_comma ^= True
if children[-1].type == token.COMMA:
children[-1].remove()
# If there are no impo | rts left, just get rid of the entire statement
if not (imports.children or getattr(imports, 'value', None)) or \
imports.parent is None:
p = node.prefix
node = BlankLine()
node.prefix = p
return node
|
'''
Created on Jun 29, 2016
@author: Thomas Adriaan Hellinger
'''
import pytest
from roodestem.voting_systems.voting_system import Result
class TestResult:
| def test_null_result_not_tolerated(self):
with pytest.raises(TypeError):
Result()
def test_passed_multiple_winners(self):
res = Result(winner=['a', 'b', 'c' | ], tied=['b','c'])
assert res == Result(tied=['a', 'b', 'c'])
def test_passed_all_losers(self):
res = Result(loser=['a', 'b', 'c'])
assert res == Result(tied=['a', 'b', 'c'])
def test_passed_all_winners(self):
res = Result(winner=['a', 'b', 'c'])
assert res == R... |
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.status import HTTP_204_NO_CONTENT
from users.serializers import UserSerializer
from rest_framework.permissions import AllowAny
from django.contrib.auth import login, logout
from rest_framework.authentication import... | ication import CustomBaseAuthentication
class AuthLoginView(APIView):
authentication_classes = (CustomBaseAuthentication, SessionAuthentication)
def post(self, request):
login(request, | request.user)
return Response(status=HTTP_204_NO_CONTENT)
class AuthLogoutView(APIView):
def delete(self, request):
logout(request)
return Response(status=HTTP_204_NO_CONTENT)
class UserRegisterView(APIView):
permission_classes = (AllowAny,)
authentication_classes = () # TODO: R... |
"""
The consumer's code.
It takes HTML from the queue and outputs the URIs found in it.
"""
import asyncio
import json
import logging
from typing import List
from urllib.parse import urljoin
import aioredis
from bs4 import BeautifulSoup
from . import app_cli, redis_queue
_log = logging.getLogger('url_extractor')
... | ma: no cover
def main():
"""Run the URL extractor (the consumer).
"""
| app_cli.setup_logging()
args_parser = app_cli.get_redis_args_parser(
'Start a worker that will get URL/HTML pairs from a Redis queue and for each of those '
'pairs output (on separate lines) a JSON in format {ORIGINATING_URL: [FOUND_URLS_LIST]}')
args = args_parser.parse_args()
loop = app_... |
from math import log
def sort(a_list, base):
"""Sort the input list with the specified base, using Radix sort.
This implementation assumes that the input list does not contain negative
numbers. This algorithm is inspire | d from the Wikipedia implmentation of
Radix sort.
"""
passes = int(log(max(a_list), base) + 1)
items = a_list[:]
for digit_index in xrange(passes):
buckets = [[] for _ in xrange(base)] # Buckets | for sorted sublists.
for item in items:
digit = _get_digit(item, base, digit_index)
buckets[digit].append(item)
items = []
for sublists in buckets:
items.extend(sublists)
return items
def _get_digit(number, base, digit_index):
return (number // bas... |
.location)
sys.exit(1)
def progress_cmd(what, cmd):
"""Print cmd in a way a user could cut-and-paste to get the same effect"""
progress(what)
shell_text = "%s" % (" ".join(['"%s"' % x for x in cmd]))
progress(shell_text)
def run_cmd_blocking(what, cmd, quiet=False, check=False, **kw):
if not... | racker_instance), "--model=tracker", "--home=" + tracker_home])
def start_vehicle(binary, autotest, opts, stuff, loc):
"""Run the ArduPilot binary"""
cmd_name = opts.vehicle
cmd = []
if opts.valgrind:
cmd_name += " (valgrind)"
cmd.append("valgrind")
if opts.gdb:
cmd_name +... | texit.register(os.unlink, gdb_commands_file.name)
for breakpoint in opts.breakpoint:
gdb_commands_file.write("b %s\n" % (breakpoint,))
gdb_commands_file.write("r\n")
gdb_commands_file.close()
cmd.extend(["-x", gdb_commands_file.name])
cmd.append("--args")
if opts... |
import urllib2
from lxml import etree
####################################################################
# API
####################################################################
class Scrape_Quora:
regexpNS = "http://exslt.org/regular-expressions"
@staticmethod
def get_name(user_name):
url =... | tree.parse(response, htmlparser)
no_of_followers = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/li/a[text()="Followers "]/span/text()', namespaces={'re':Scrape_Quora.regexpNS})[0]
return no_of_followers
@staticmethod
def get_no_of_following(user_name):
| url = 'https://www.quora.com/profile/' + user_name
response = urllib2.urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
no_of_following = tree.xpath('//*[re:test(@id, "ld_[a-z]+_\\d+", g)]/li/a[text()="Following "]/span/text()', namespaces={'re'... |
f | rom .group_analysis import create_fsl_flame_wf, \
get_operation
__all__ = ['create_fsl_flame_wf', \
| 'get_operation']
|
ue', 'blank': 'True'}),
'render_max_age': ('django.db.models.fields.IntegerField' | , [], {'null': 'True', 'blank': 'True'}),
'render_scheduled_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'render_started_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'db_index': 'True'}),
'rendered_errors': ('django.... | d', [], {'null': 'True', 'blank': 'True'}),
'rendered_html': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'team': ('django.db.models.fields.related.ForeignKe... |
self.assertTrue(r)
@res_mock.patch_client
def test_session_finished_migrating(self, client, mocked):
lun = client.vnx.get_lun()
r = client.session_finished(lun)
self.assertFalse(r)
@res_mock.patch_client
def test_session_finished_not_existed(self, client, mocked):
... | ))
@res_mock.patch_client
def test_get_storage_group(self, client, mocked):
sg = client.get_storage_group('sg_name')
self.assertEqual('sg_name', sg.name)
@re | s_mock.patch_client
def test_register_initiator(self, client, mocked):
host = vnx_common.Host('host_name', ['host_initiator'], 'host_ip')
client.register_initiator(mocked['sg'], host,
{'host_initiator': 'port_1'})
@res_mock.patch_client
def test_register_in... |
#!/usr/bin/env python
import sys
import src.json_importing as I
import src.data_training as T
import src.data_cross_validation as V
imp | ort src.extract_feature_multilabel as EML |
if __name__ == '__main__':
print('Hello, I am Trellearn')
jsonFileName = sys.argv[1]
cards = I.parseJSON(jsonFileName)
X, Y, cv, mlb = EML.extract(cards)
V.validateML(X, Y)
exit(0)
|
/usr/share/pyshared/gwibber/lib/gtk/w | idgets.p | y |
# CodeIgniter
# http://codeigniter.com
#
# An open source application development framework for PHP
#
# This content is released under the MIT License (MIT)
#
# Copyright (c) 2014 - 2015, British Columbia Institute of Technology
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of thi... | DED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTIO | N OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
# Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
#
# http://opensource.o... |
import urllib.request, urllib.parse, urllib.error
from oauth2 import Request as OAuthRequest, SignatureMethod_HMAC_SHA1
try:
import json as simplejson
except ImportError:
try:
import simplejson
except ImportError:
from django.utils import simplejson
from social_auth.backends import Consum... |
class RdioOAuth1Backend(RdioBaseBackend):
"""Rdio OAuth authentication backend"""
name = 'rdio-oauth1'
EXTRA_DATA = [
('key', 'rdio_id'),
('icon', 'rdio_icon_url'),
('url', 'rdio_profile_url'),
('username', 'rdio_username'),
('streamRegion', 'rdio_stream_region'),
... | smethod
def tokens(cls, instance):
token = super(RdioOAuth1Backend, cls).tokens(instance)
if token and 'access_token' in token:
token = dict(tok.split('=')
for tok in token['access_token'].split('&'))
return token
class RdioOAuth2Backend(RdioBaseBack... |
from LSP.plugin.core.typing import Any, Callable
from types import MethodType
import weakref
__all__ = ['weak_method']
# An implementation of weak method borrowed from sublime_lib [1]
#
# We need it to be able to weak reference bound methods as `weakref.WeakMethod` is not available in
# 3.3 runtime.
#
# The reason ... | **kwargs: Any) -> Any:
self = self_ref()
fu | nction = function_ref()
if self is None or function is None:
print('[lsp_utils] Error: weak_method not called due to a deleted reference', [self, function])
return
return function(self, *args, **kwargs)
return wrapped
|
#------------------------------------------------------------------------------
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions describe... | s:
>>> arange(1, 4, 1)
array([1, 2, 3])
However brange() returns:
>>> brange(1, 4, 1)
array([ 1., 2., 3., 4.])
"""
return numpy.arange(min_value, max_value + increment / 2.0, increment)
def norm(mean, std):
""" Returns a single random value from a normal distribution. """
r... | m(counts)
return numpy.sqrt((numpy.sum((counts-mean)**2))/len(counts))
|
#!/usr/bin/env python
# Copyright 2016 Battelle Energy Alliance, 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 ... | l_path, parent_dir)
try:
reader = RecipeReader(parent_dir, rel_path)
recipe = reader.read()
except Exception as e:
print("Recipe '%s' is not valid: %s" % (real_path, e))
return 1
try:
script = recipe_to_bash(recipe,
base_repo=parsed.base[0],
ba... | head_sha=parsed.head[2],
pr=parsed.pr,
push=parsed.push,
manual=parsed.manual,
build_root=parsed.build_root,
moose_jobs=parsed.num_jobs,
args=args,
)
if parsed.output:
with open(parsed.output, "w") as f:
... |
"""
Test multiword commands ('platform' in this case).
"""
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
class MultiwordCommandsTestCase(TestBase):
mydir = TestBase.compute_mydir(__file__)
@no_debug_info_test
def test_ambiguous_subcommand(self):
self.e... | subcommand(self):
self.expect("platform \"\"", error=True, substrs=["Need to specify a non-empty subcommand."])
@no_debug_info_test
def test_help(self):
# <multiword> help brings up help.
self.expect("platform help",
substrs=["Commands to manage and create platforms.... | "Syntax: platform [",
"The following subcommands are supported:",
"connect",
"Select the current platform"])
|
#!/usr/bin/env python3
#
# Copyright (c) 2015-2017 Nest Labs, 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/lic... | g permissions and
# limitations under the License.
#
#
# @file
# | A Happy command line utility that tests Weave Ping among Weave nodes.
#
# The command is executed by instantiating and running WeavePing class.
#
from __future__ import absolute_import
from __future__ import print_function
import getopt
import sys
import set_test_path
from happy.Utils import *
import Weav... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
debug = True
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_DB = 0
REDIS_PASSWORD | = '820AEC1BFC5D2C71E06CBF947A3A6191'
GUAVA_API_URL = 'http | ://localhost:5000' |
from sklearn.tree import DecisionTreeClassifier
# weak classifier
# decision tr | ee (max depth = 2) using scikit-learn
class WeakClassifier:
# initialize
def __init__(self):
self.clf = DecisionTreeClassifier(max_depth = 2)
# train on dataset (X, y) with distribution weight w
def fit(self, X, y, w):
self.clf.fit(X, y, sample_weight = w)
# predict
def predict(self, X):
re... | rn self.clf.predict(X)
|
import time
from prometheus_client import Counter, Histogram
from prometheus_client import start_http_server
from flask import request
FLASK_REQUEST_LATENCY = Histogram('flask_request_latency_seconds', 'Flask Request Latency',
['method', 'endpoint'])
FLASK_REQUEST_COUNT = Counter('flask_request_count', ... | before_request(before_request)
app.after_request(after_request)
start_http_server(port, addr)
if __name__ == '__main__':
from flask import Flask
app = Flask(__name__)
monitor(app, p | ort=8000)
@app.route('/')
def index():
return "Hello"
# Run the application!
app.run()
|
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the to | p-level COPYRIGHT file for details.
#
# SPD | X-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RRrcov(RPackage):
"""rrcov: Scalable Robust Estimators with High Breakdown Point"""
homepage = "https://cloud.r-project.org/package=rrcov"
url = "https://cloud.r-project.org/src/contrib/rrcov_1.4-7.tar.gz"
list_url = "https://c... |
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
"""
Model for testing arithmetic expressions.
"""
from django.db import models
@python_2_unicode_compatible
class Number(models.Model):
integer = models.BigI | ntegerField(db_column='the_integer')
float = models | .FloatField(null=True, db_column='the_float')
def __str__(self):
return '%i, %.3f' % (self.integer, self.float)
class Experiment(models.Model):
name = models.CharField(max_length=24)
assigned = models.DateField()
completed = models.DateField()
start = models.DateTimeField()
end = model... |
import socket
import os
RUN_IN_TOPOLOGY = False
TOPOLOGY_FROM_RESOURCE_SERVER = False
HOSTNAME_1 = HOSTNAME_2 = HOSTNAME_3 = socket.get | hostname()
USE_SSL = False
ICAT_HOSTNAME = socket.gethostname()
PREEXISTING_ADMIN_PASSWORD = 'rods'
# TODO: allow for arbitrary number of remote zones
class FEDERATION(object):
LOCAL_IRODS_VERSION = (4, 2, 0)
REMOTE_IRODS_VERSION = (4, 2, 0)
RODSUSER_NAME_PASSWORD_LIST = [('zonehopper', '53CR37')]
RO... | REMOTE_HOST = 'buntest'
REMOTE_RESOURCE = 'demoResc'
REMOTE_VAULT = '/var/lib/irods/iRODS/Vault'
TEST_FILE_SIZE = 4*1024*1024
LARGE_FILE_SIZE = 64*1024*1024
TEST_FILE_COUNT = 300
MAX_THREADS = 16
|
1, 0, 'Loan Template', None, 1],
['loan_xls_output', 'Loan Output', 'string', None, 'S:\\Prime Brokerage (PB)\\Tools\\Stock Loan Collateral\\ExcelUpload - Cash Entry YYYYMMDD.xlsm', 1, 0, 'Loan Output', None, 1],
['ss_bb_output', 'SS/BB Output', 'string', None, 'S:\\Prime Brokerage (PB)\... | = []
if "http" in csv_file:
response = requests.get(csv_file)
text = response.content.decode(encoding)
else:
text = open(csv_file, 'rU')
reader = csv.reader(text, delimiter=delim)
arr = list(reader)
arr = list(zip(*arr))
arr = [x for x in arr if any(x)]
arr = list... |
header = ""
if has_header:
header = ','.join(arr[start])
arr = arr[start+1:]
return re.sub(r"[\*\.#/\$%\"\(\)& \_-]", "", header), arr
else:
return arr[start:]
return
def getFx(dt, fm_ccy, to_ccy, currclspricemkt, histclspricemkt):
if fm_ccy == 'CNY':
f... |
from gbdxtools im | port Interface
gbdx = None
def go():
print(gbdx.task_registry.list())
print(gbdx.task_registry.get_definition('HelloGBDX'))
if __name__ == "__main__":
gbdx = Interface()
go | ()
|
"""This module provides the main functionality of cfbackup
"""
from __future__ import print_function
import sys
import argparse
import json
import CloudFlare
# https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records
class CF_DNS_Records(object):
"""
commands for zones manipulation
"""
def ... | print("Zone: {0: <16} NS: {1}".format(
z["name"],
z["name_servers"][0],
))
for ns in z["name | _servers"][1:]:
print(" {0: <16} {1}".format("", ns))
def _all_zones(self):
cf = CloudFlare.CloudFlare(raw=True)
if self._ctx.zone_name:
raw_results = cf.zones.get(params={
'name': self._ctx.zone_name,
'per_page': 1,
... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Documents
#
"""
Documents
"""
from __future__ import | absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
i | mport os
import inspect
from . import pyarduino
this_file_path = os.path.abspath(inspect.getfile(inspect.currentframe()))
def get_plugin_path():
this_folder_path = os.path.dirname(this_file_path)
plugin_path = os.path.dirname(this_folder_path)
return plugin_path
def get_packages_path():
plugin_pa... |
'''MobileNetV2 in PyTorch.
See the paper "Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''expand + depthwise + pointwise'''
def __init... | n.Linear(1280, num_classes)
def _make_layers(self, in_planes):
layers = []
for expansion, out_planes, num_blocks, stride in self.cfg:
strides = [stride] + [1]*(num_blocks-1)
for stride in strides:
layers.append(Block(in_planes, out_planes, expansion, stride))... | ut_planes
return nn.Sequential(*layers)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.layers(out)
out = F.relu(self.bn2(self.conv2(out)))
# NOTE: change pooling kernel_size 7 -> 4 for CIFAR10
out = F.avg_pool2d(out, 4)
out = out.view(... |
#
# 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... | ax }} {{
puts "Configuration timed out."
exit 1
}}
}}
expect "]$ "
send "sudo su\r"
expect "]# "
send "echo \"<VirtualHost *:80>\r"
send " AddDefaultCharset UTF-8\r"
send " ProxyPreserveHost On\r"
send " ProxyRequests off\r"
send " ProxyVia Off\r"
send " ProxyPass / http://{haproxy_cp_ip}:500... | _security2.c>\r"
send " IncludeOptional modsecurity.d/owasp-modsecurity-crs/modsecurity_crs_10_setup.conf\r"
send " IncludeOptional modsecurity.d/owasp-modsecurity-crs/base_rules/*.conf\r\r"
send " SecRuleEngine On\r"
send " SecRequestBodyAccess On\r"
send " SecResponseBodyAccess On\r"
send " SecDebugLog /v... |
# Mostly from http://peterdowns.com/posts/first-time-with-pypi.html
from distutils.core import setup
setup(
name = 'pmdp',
packages = ['pmdp'],
version = '0.3',
description = 'A poor man\'s data pipeline',
author = 'Dan Goldin',
author_email = 'dangoldin@gmail.com',
url = 'https://github.com/dangoldin/po... | assifiers = [],
)
| |
to statistics file
verbose = 0
obstruents = {'b':'B', 'd':'D', 'g':'G'}
nasals = ['m', 'n', 'N']
# Vocales
vowels = ['a', 'e', 'i', 'o', 'u']
# Semivocales
semivowels = ['%', '#', '@', '$', '&', '!', '*', '+', '-', '3']
# Voiced consonants
voiced = ['b', 'B', 'd', 'D', 'g', 'G', 'm', 'n', 'N', '|', 'J', 'r', 'R']
# T... | obals()["phonemesPerWord"].append(float(float(phonemesInWord) / float(len(words[1:] | ))))
if verbose == 1:
print ipaSentence
if len(ipaSentence) > 0:
outFile.write(ipaSentence + '\n')
globals()["numUtterances"] += 1
#file.write(ipaSentence + '\n')
#file.close()
ou... |
#!/usr/bin/env python
#
# Copyright (c) 2013 In-Q-Tel, Inc/Lab41, 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
#
# Unles... | 260)
colors = ['red', 'blue', 'green', 'purple', 'cyan', 'black', 'brown', 'grey']
for idx in range(num_clusters):
plt.scatter(list_ar | rays[idx][:,0], list_arrays[idx][:,1], c=colors[idx])
plt.title(title)
plt.ylabel(ylabel)
plt.xlabel(xlabel)
#plt.show()
plt.savefig('/home/docker/foo.png')
plt.close()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2013 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual autho | rs.
#
# 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 und... | |
# -*- coding: utf-8 -*-
import warnings
from django import forms
from django.contrib.admin.sites import site
from django.contrib.admin.widgets import ForeignKeyRawIdWidget
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core.urlresolvers import reverse
from django.db import models
f... | except:
obj = None
return obj
class Media(object):
js = (static('filer/js/addons/popup_handling.js'), | )
class AdminFolderFormField(forms.ModelChoiceField):
widget = AdminFolderWidget
def __init__(self, rel, queryset, to_field_name, *args, **kwargs):
self.rel = rel
self.queryset = queryset
self.limit_choices_to = kwargs.pop('limit_choices_to', None)
self.to_field_name = to_fiel... |
"""
Copyright 2016 Andrea McIntosh
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 i... | S" 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 django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlres... | index.html"
context_object_name = 'latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsVi... |
import os
import sys
root_path = os.path.abspath("../../../")
if root_path not in sys.path:
sys.path.append(root_path)
import numpy as np
import tensorflow as tf
from _Dist.NeuralNetworks.Base import Generator4d
from _Dist.NeuralNetworks.h_RNN.RNN import Basic3d
from _Dist.NeuralNetworks.NNUtil import Activations... | (tf.bool, name=" | is_training")
self._tfx = tf.placeholder(tf.float32, [None, self.height, self.width, self.n_dim], name="X")
self._tfy = tf.placeholder(tf.float32, [None, self.n_class], name="Y")
def _build_model(self, net=None):
self._model_built = True
if net is None:
net = self._tfx
... |
# Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.
from djangoappengine.settings_base import *
from private_settings import SECRET_KEY
import os
# Activate django-dbindexer for th... | ASES['default']
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}
AUTOLOAD_SITECONF = 'indexes'
INSTALLED_APPS = (
# 'django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'django.contrib.staticfiles',
'django.contrib.markup',
... | ome last, so it can override a few manage.py commands
'djangoappengine',
)
MIDDLEWARE_CLASSES = [
# This loads the index definitions, so it has to come first
'autoload.middleware.AutoloadMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware... |
import utils
import re
import subprocess
#regexes
duration_regex = re.compile('Duration:\s*(?P<time>\d{2}:\d{2}:\d{2}.\d{2})')
stream_regex = re.compile('Stream #(?P<stream_id>\d+:\d+)(\((?P<language>\w+)\))?: (?P<type>\w+): (?P<format>[\w\d]+)')
crop_regex = re.compile('crop=(?P<widt | h>\d+):(?P<height>\d+):(?P<x>\d+):(?P<y>\d+)')
# detect crop settings
def detect_crop(src):
proc = subprocess.Popen(['ffmpeg', '-i', src, '-t', str(100), '-filter:v', 'cropdetect', '-f', 'null', '-'], stderr=subprocess.PIPE)
stdout, stderr = proc.communicate()
crops = crop_regex.findall(stderr)
return max(set(... | dout, stderr = proc.communicate()
match = duration_regex.search(stderr)
duration_str = match.group('time')
duration_secs = utils.timestring_to_seconds(duration_str)
return (duration_str, duration_secs)
# detects stream IDs
def detect_streams(src):
proc = subprocess.Popen(['ffmpeg', '-i', src], stderr=subproc... |
elf._create_element(u'ins', content, attrs)
# inline
def a(self, content, attrs=None):
"""Create a element.
Keyword arguments:
content -- some text
attrs -- dict object that contains attributes (default None)
"""
return self._create_element(u'a', conten... | content -- some text
attrs -- dict object that contains attributes (default None)
"""
return self._create_element(u'bdo', content, attrs)
def cite(self, content, attrs=None):
"""Create cite element.
Keyword arguments:
content -- some text
at... |
"""
return self._create_element(u'cite', content, attrs)
def code(self, content, attrs=None):
"""Create code element.
Keyword arguments:
content -- some text
attrs -- dict object that contains attributes (default None)
"""
return self._creat... |
# -*- coding: utf-8 -*-
import logging
from speaklater import make_lazy_string
from quokka.modules.a | ccounts.models import User
logger = logging.getLogger()
def lazy_str_setting(key, default=None):
from flask import current_app
return make_lazy_string(
lambda: current_app.config.get(key, default)
)
def get_current_user():
from flask.ext.securi | ty import current_user
try:
if not current_user.is_authenticated():
return None
except RuntimeError:
# Flask-Testing will fail
pass
try:
return User.objects.get(id=current_user.id)
except Exception as e:
logger.warning("No user found: %s" % e.message)... |
from .req import Req
class Records(Req):
def __init__(self, url, email, secret):
super().__init__(url=url, email=email, secret=secret)
def get(self, zone_id, layer='default'):
return self.do_get("/zones/{}/{}/records".format(zone_id, layer))
def create(self, zone, layer, name, ttl, rtype... | , zone, layer, record_id):
url = "/zones/{}/{}/records/{}".format(zone, layer, record_id)
return self.do_delete(url)
def update(self, zone, layer, record_id, **params):
url = "/zones/{}/{}/records/{}".fo | rmat(zone, layer, record_id)
return self.do_put(url, data=params)
|
# crop.py
# Derek Groenendyk
# 2/15/2017
# reads input data from Excel workbook
from collections import OrderedDict
import logging
import numpy as np
import os
import sys
from cons2.cu import CONSUMPTIVE_USE
# from utils import excel
logger = logging.getLogger('crop')
logger.setLevel(logging.DEBUG)
class CROP(obje... | Name of the crop
Returns
-------
nckc: list
List of crop coefficients
| """
try:
infile = open(os.path.join(self.directory,'data','scs_crop_stages.csv'),'r')
except TypeError:
logger.critical('scs_crop_stages.csv file not found.')
raise
lines = infile.readlines()
infile.close()
nckca = [float(item) for ite... |
"""Auto-generated file, do not edit by hand. BS metadata"""
from ..phonemetadata imp | ort NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_BS = PhoneMetadata(id='BS', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='9\\d\\d', possible_length=(3,)),
toll_free=PhoneNumberDesc(national_number_pattern='9(?:1[19]|88)', example_number='911... | ible_length=(3,)),
short_code=PhoneNumberDesc(national_number_pattern='9(?:1[19]|88)', example_number='911', possible_length=(3,)),
short_data=True)
|
return res
def nanargmax(a, axis=None):
"""
Return the indices of the maximum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the
results cannot be trusted if a slice contains only NaNs and -Infs.
Parameters
----------
a : array_like
... | eturn res
def nansum(a, axis=None, dtype=None, out=None, keepdims=np._NoValue):
"""
Return the sum of array elements over a given axis treating Not a
Numbers (NaNs) as zero.
In Numpy versions <= 1.8 Nan is returned for slices that are all-NaN or
empty. In later versions zero is returned.
Par... | . If `a` is not an
array, a conversion is attempted.
axis : int, optional
Axis along which the sum is computed. The default is to compute the
sum of the flattened array.
dtype : data-type, optional
The type of the returned array and of the accumulator in which the
element... |
is invite was sent to
from_actor = models.StringProperty() # ref - who sent this invite
for_actor = models.StringProperty() # ref - invited to what, probs a channel
status = models.StringProperty(default="active") # enum - active, blocked
key_template = 'invite/%(code)s'
class KeyValue(CachingModel):
actor ... |
value = models.TextProperty()
key_template = 'keyvalue/%(actor)s/%(keyname)s'
class OAuthAccessToken(CachingModel):
key_ = models.StringProperty() # the token key
| secret = models.StringProperty() # the token secret
consumer = models.StringProperty() # the consumer this key is assigned to
actor = models.StringProperty() # the actor this key authenticates for
created_at = properties.DateTimeProperty(auto_now_add=True)
# whe... |
##########################################################################
#
# Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved.
# Copyright (c) 2011-2012, John Haddon. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted ... | T, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF TH | E USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
from __future__ import with_statement
import IECore
import Gaffer
import GafferUI
## A dialogue which allows a user to edit the parameters of an
# IECore.Op in... |
: John Dennis <jdennis@redhat.com>
#
# Copyright (C) 2011 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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 3 of the... | ne_converter'] = 'utc'
if not 'datefmt' in cfg:
cfg['datefmt'] = ISO8601_UTC_DATETIME_FMT
if not 'format' in cfg:
| cfg['format'] = LOGGING_FORMAT_STDOUT
return super(IPALogManager, self).create_log_handlers(configs, logger, configure_state)
#-------------------------------------------------------------------------------
def standard_logging_setup(filename=None, verbose=False, debug=False,
filemode='w', ... |
option1=foo\n")
# Check that we get a TypeError when setting non-string values
# in an existing section:
self.assertRaises(TypeError, cf.set, "sect", "option1", 1)
self.assertRaises(TypeError, cf.set, "sect", "option1", 1.0)
self.assertRaises(TypeError, cf.set, "sect", "opti... | ptionError('option', 'section')
pickled = pickle.dumps(e1)
e2 = pickle.loads(pickled)
self.assertEqual(e1.mes | sage, e2.message)
self.assertEqual(e1.args, e2.args)
self.assertEqual(e1.section, e2.section)
self.assertEqual(e1.option, e2.option)
self.assertEqual(repr(e1), repr(e2))
def test_duplicatesectionerror(self):
import pickle
e1 = ConfigParser.DuplicateSectionErr... |
"""This example shows how to create a scatter p | lot using the `shell` package.
"""
# Major library imports
from numpy import linspace, random, pi
# Enthought library imports
from chaco.shell import plot, | hold, title, show
# Create some data
x = linspace(-2*pi, 2*pi, 100)
y1 = random.random(100)
y2 = random.random(100)
# Create some scatter plots
plot(x, y1, "b.")
hold(True)
plot(x, y2, "g+", marker_size=2)
# Add some titles
title("simple scatter plots")
# This command is only necessary if running from command line... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 05 17:10:34 2014
@author: Ning
"""
from util import *
from util.log import _logger
from feat.terms.term_categorize import term_category
import codecs
de | f parse(sentence):
for term in sentence.split():
yield term_category(term)
def tokenize():
rows = tsv.reader(conv.redirect("data|train.dat"))
with codecs.open("train.tokenized.dat",'w',encoding='utf-8') as fl:
for row in rows:
fl.write("%s\t%s\n" % | (' '.join(list(parse(row[0]))) , row[1]) )
rows = tsv.reader(conv.redirect("data|test.dat"))
with codecs.open("test.tokenized.dat",'w',encoding='utf-8') as fl:
for row in rows:
fl.write("%s\t%s\n" % (' '.join(list(parse(row[0]))) , row[1]) )
if __name__ == "__main__":
... |
,
(None, None, False),
],
# Format 10 = ((a[&Z=1,Y=2]:1.0[&X=3], b[&Z=1,Y=2]:3.0[&X=2]):1.0[&L=1,W=0], ...
# NHX Like mrbayes NEXUS common
10: [
('name', str, True),
('dist', str, True),
('name', str, True),
('dist', str, True),
]
}
def parse_network(n... | node.up = root
big.up = root
root.children = [node, big]
net.treenode = root
| # disconnect node by connecting children to parent
if disconnect:
# if tip is a hybrid
if not node.children:
# get sister node
sister = [i for i in node.up.children if i != node][0]
# connect sister to gparent
... |
###############################################################################
#
# Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>).
#
# 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 ... |
XMLRPC Import invoice
''',
'author': 'Micronaet S.r.l. - Nicola Riolini',
'website': 'http://www.micronaet.it',
'license': 'AGPL-3',
'depends': [
'base',
| 'xmlrpc_base',
'account',
],
'init_xml': [],
'demo': [],
'data': [
'security/xml_groups.xml',
#'operation_view.xml',
'invoice_view.xml',
'data/operation.xml',
],
'active': False,
'installable': True,
'auto_install': False,
}
|
import re
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
from django.core.urlresolvers import reverse
from django.utils.feedgenerat | or import Atom1Feed
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from .models import LoggedAction
lock_re = re.compile(r'^(?:Unl|L)ock | ed\s*constituency (.*) \((\d+)\)$')
class RecentChangesFeed(Feed):
site_name = Site.objects.get_current().name
title = _("{site_name} recent changes").format(site_name=site_name)
description = _("Changes to {site_name} candidates").format(site_name=site_name)
link = "/feeds/changes.xml"
feed_type =... |
import json
import random
import time
import urllib
import re
from scrapy.utils.misc import load_object
from scrapy.http import Request
from scrapy.conf import settings
import redis
from crawler.schedulers.redis.dupefilter import RFPDupeFilter
from crawler.schedulers.redis.queue import RedisPriorityQueue
try:
im... | ost=settings.get('REDIS_HOST'),
port=settings.get('REDIS_PORT'))
persist = settings.get('SCHEDULER_PERSIST', True)
timeout = settings.get('DUPEFILTER_TIMEOUT', 600)
retries = settings.get('SCHEDULER_ITEM_RETRIES', 3)
return cls(server, persist, timeout, retr... | tings)
def open(self, spider):
self.spider = spider
self.setup()
self.dupefilter = RFPDupeFilter(self.redis_conn,
self.spider.name + ':dupefilter', self.rfp_timeout)
def close(self, reason):
if not self.persist:
self.dupefilte... |
from sklearntools.kfold import ThresholdHybridCV
import numpy as np
from six.moves import reduce
from operator import __add__
from numpy.testing.utils import assert_array_equal
from nose.tools impor | t assert_equal
def test_hybrid_cv():
X = np.random.normal(size=(100,10))
y = np.random.normal(size=100)
cv = ThresholdHybridCV(n_folds=10, upper=1.)
folds = list(cv._iter_test_masks(X, y))
assert_array_equal(reduce(__add__, folds), np.ones(100, dtype=int))
assert_equal(len(folds), cv.get_n_spl... | rgv=[sys.argv[0],
module_name,
'-s', '-v']) |
string used to strengthen the
uniqueness of the message id. Optional domain if given provides the
portion of the message id after the '@'. It defaults to the locally
defined hostname.
"""
timeval = time.time()
utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
pid = os.getpid()... | default('Reply-To', reply_to)
# Every message sent needs a unique message id
message_id = make_msgid(get_from_email_domain())
headers.setdefault('Message-Id', message_id)
| subject = self.subject
if self.reply_reference is not None:
reference = self.reply_reference
subject = 'Re: %s' % subject
else:
reference = self.reference
if isinstance(reference, Group):
thread, created = GroupEmailThread.objects.get_or_crea... |
#!/usr/bin/env python
"""plot_softmax_results.py: Plot results of mnist softmax tests."""
from helper_scripts.mnist_read_log import plot_results
import matplotlib.pyplot as plt
# Produce cross entropy and accuracy plots for softmax models.
# Requires the training data for each of the models.
files = [r"""../mnist_s... | rob=0.9\log\validation"""
]
scalar_names = ['accuracy_1', 'cross_entropy_1']
ylabels = ['Validation Accuracy', 'Cross Entropy (Validation Set)']
legend = [r'$\alpha=0.1, keep\_prob=0.9$']
plot_results(files, scalar_names, ylabels, | legend, 'Softmax Models')
plt.show() |
# -*- coding: utf-8 -*-
#
# mfp documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a def... | d to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A li... | prefixes for module index sorting.
# modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and cust... |
#!/usr/bin/env python2.5
from optparse import OptionParser
from rosettautil.rosetta import rosettaScore
usage = "%prog [options] --term=scoreterm silent files"
parser=OptionParser(usage)
parser.add_option("--term",dest="term",help="score term to use")
(options,args) = parser.parse_args()
if len(args) < 1:
parser... | rrent_file,current_best_tag,current_best_score) = best_models[model_id]
except KeyError:
best_models[model_id] = (silent_file,tag,sco | re)
continue
if score < current_best_score:
#print "changed"
best_models[model_id] = (silent_file,tag,score)
#print best_models
#print silent_file
#print file,score , current_best_score
print "file","tag",options.term
for tag in best_models:
... |
####
#### Give a report on the "sanity" of the users and groups YAML
#### metadata files.
####
#### Example usage to analyze the usual suspects:
#### python3 sanity-check-users-and-groups.py --help
#### Get report of current problems:
#### python3 ./scripts/sanity-check-users-and-groups.py --users metadata/users.yaml... | if auth.get('noctua-go', False) or \
(auth.get('noctua', False) and auth['noctua'] | .get('go', False)):
#print('Has perms: ' + user.get('nickname', '???'))
## 1: If so, do they have a URI?
if not user.get('uri', False):
die_screaming(user.get('nickname', '???') +\
' has no "uri"')
... |
import requests
from Norman.errors import HttpMethodError
class BaseAPI(object):
"""
"""
_content_type = "application/json"
def __init__(self):
pass
def _json_par | ser(self, json_response):
response = json_response.json()
return response
def exec_reques | t(self, method, url, data=None):
method_map = {
'GET': requests.get,
'POST': requests.post,
'PUT': requests.put,
'DELETE': requests.delete
}
payload = data if data else data
request = method_map.get(method)
if not request:
... |
f.ctx.node)
e2 = z3.Const('__webproxy_e2_%s'%(self.proxy), self.ctx.node)
e3 = z3.Const('__webproxy_e3_%s'%(self.proxy), self.ctx.node)
e4 = z3.Const('__webproxy_e4_%s'%(self.proxy), self.ctx.node)
e5 = z3.Const('__webproxy_e5_%s'%(self.proxy), self.ctx.node)
e6 = z3.Const('__web... | self.ctx.packet)
| self.creqpacket = z3.Function('__webproxy_creqpacket_%s'%(self.proxy), self.ctx.address, z3.IntSort(), self.ctx.packet)
self.creqopacket = z3.Function('__webproxy_creqopacket_%s'%(self.proxy), self.ctx.address, z3.IntSort(), self.ctx.packet)
#self.corigbody = z3.Function('__webproxy_corigbody_%s... |
import sys
import random, string
import os
numberOfEmailsToGenerate = sys.argv[1]
try:
int(numberOfEmailsToGenerate)
print('Generating a CSV with ' + numberOfEmailsToGenerate + ' random emails')
print('This make take some time if the CSV is large ...')
except:
sys.exit('Pl | ease pass a number as the first arg')
numberOfEmailsToGenerate = int(numberOfEmailsToGenerate)
# Delete ./generated.csv, then create it
os.system('touch ./generated.csv')
for x in range(0, numberOfEmailsToGenerate):
randomString = ''.joi | n(random.choice(string.lowercase) for i in range(20))
os.system('echo ' + randomString + '@email.com' ' >> ./generated.csv')
|
stance(base, dict):
raise AssertionError("`base` must be of type <dict>")
if not isinstance(other, dict):
raise AssertionError("`other` must be of type <dict>")
combined = dict()
for key, value in iteritems(base):
if isinstance(value, dict):
if key in other:
... |
:rtype: A dictionary
:returns: A dictionary by eliminating keys that have null values
"""
final_cfg = {}
if not cfg_dict:
return final_cfg
for key, val in iteritems(cfg_dict):
dct = None
if isinstance(val, dict):
| child_val = remove_empties(val)
if child_val:
dct = {key: child_val}
elif (isinstance(val, list) and val
and all([isinstance(x, dict) for x in val])):
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.7.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... | t.TestCase):
""" V1beta1StorageClass unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1beta1StorageClass(self):
"""
Test V1beta1StorageClass
"""
mo | del = kubernetes.client.models.v1beta1_storage_class.V1beta1StorageClass()
if __name__ == '__main__':
unittest.main()
|
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from .....testing import assert_equal
from ..histogrammatching import HistogramMatching
def test_HistogramMatching_inputs():
input_map = dict(args=dict(argstr='%s',
),
environ=dict(nohash=True,
usedefault=True,
),
ignore_exception=dict(noha... | sedefault=True,
),
inputVolume=dict(argstr='%s',
position=-3,
| ),
numberOfHistogramLevels=dict(argstr='--numberOfHistogramLevels %d',
),
numberOfMatchPoints=dict(argstr='--numberOfMatchPoints %d',
),
outputVolume=dict(argstr='%s',
hash_files=False,
position=-1,
),
referenceVolume=dict(argstr='%s',
position=-2,
),
terminal_output=dic... |
from ..errors import ErrorFolderNotFound, ErrorInvalidOperation, ErrorNoPublicFolderReplicaAvailable
from ..util import MNS, create_element
from .common import EWSAccountService, folder_ids_element, parse_folder_elem, shape_element
class GetFolder(EWSAccountService):
"""MSDN: https://docs.microsoft.com/en-us/exch... | er=folder, account=self.account)
def get_payload(self, folders, additional_fields, shape):
payload = create_element(f"m:{self.SERVICE_NAME}")
payload.append(
shape_element(
tag="m: | FolderShape", shape=shape, additional_fields=additional_fields, version=self.account.version
)
)
payload.append(folder_ids_element(folders=folders, version=self.account.version))
return payload
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | ---------------------------------
from msrest.serialization import Model
class Bar(Model):
"""
The URIs that are used to perform a retrieval of a public blob, queue or
table object.
:param recursive_point: Recursive Endpoints
:type recursive_point: :class:`Endpoints
<fixtures.acceptancetest... | _map = {
'recursive_point': {'key': 'RecursivePoint', 'type': 'Endpoints'},
}
def __init__(self, recursive_point=None, **kwargs):
self.recursive_point = recursive_point
|
#
# gPrime - a web-based genealogy program
#
# Copyright (c) 2015 Gramps Development Team
#
# 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)... | 'primary_name.famnick',
'primary_name.private',
'primary_name.date',
'primary_name.suffix',
'primary_name.title',
'primary_name.group_as',
'primary_name.sort_as',
'primary_name.... | for field in [
'alternate_names.%s.type',
'alternate_names.%s.first_name',
'alternate_names.%s.call',
'alternate_names.%s.nick',
'alternate_names.%s.famnick',
'alternate_names.%s.private',
... |
rc = img.attrib['src']
if settings.STATIC_URL in src:
source = os.path.join(
settings.STATIC_ROOT,
src.replace(settings.STATIC_URL, '')
)
else:
source = os.path.join(
settings.MEDIA_ROOT,
src.replace(sett... | eated..."
print input_file
print output_file
print stdout_output_file
print stderr_output_file
print
if os.path.isfile(output_file):
# response['Content-Disposition'] = (
# 'filename="%s.pdf"' % os.path.basename(output_file)
# )
response = ... | en(output_file).read())
if not settings.DEBUG_PDF_PROGRAM:
os.remove(input_file)
os.remove(output_file)
for media_file in copied_media_files:
os.remove(media_file)
return response
return http.HttpResponse("PDF could not be created")
@non_mortal... |
"""
Progress Tab Serializers
"""
from rest_framework import serializers
from rest_framework.rever | se import reverse
class GradedTotalSerializer(serializers.Serializer):
earned = serializers.FloatField()
possible = serializers.FloatField()
class SubsectionSerializer(serializers.Serializer):
display_name = serializers.CharField()
due = serializers.DateTimeField()
format = serializers.CharField... | graded = serializers.BooleanField()
graded_total = GradedTotalSerializer()
# TODO: override serializer
percent_graded = serializers.FloatField()
problem_scores = serializers.SerializerMethodField()
show_correctness = serializers.CharField()
show_grades = serializers.SerializerMethodField()
u... |
## p7.py - parallel processing microframework
## (c) 2017 by mobarski (at) gmail (dot) com
## licence: MIT
## version: ex4 (simple fan-in of subprocess outputs)
from __future__ import print_function
# CONFIG ###################################################################################
HEAD_LEN_IN = 2
HEAD_LEN_... | tx = {}
args = shlex.split(CMD)
PIPE = subprocess.PIPE
for i in range(N):
ctx[i] = {}
proc = subprocess.Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=BUFSIZE)
ctx[i]['proc'] = proc
# metadata
ctx[i]['pid'] = proc.pid
ctx[i]['t_start'] = time()
ctx[i]['head_cnt_in'] = 0
ctx[i]['head_cnt_out'] = 0
d... | '] += 1
if len(head)<HEAD_LEN_IN: # End Of File
break
tail = IN.readline()
p.stdin.write(tail)
else: continue # not EOF
# EOF -> close all input streams
for i in range(N):
ctx[i]['proc'].stdin.close()
break
def pump_output():
done = set()
while True:
for i in range(N):
if i in done: ... |
ent 'generate' interface for
output Python intermediate code generating.
"""
def __init__(self, text, indent, block):
self.text = text
self.indent = indent
self.block = block
def generate(self):
raise NotImplementedError()
class TextNode(BaseNode):
""" Node for nor... | code.
context.update({'_stdout': [], 'escape': escape})
exec(self.intermediate, context)
return re.sub(r'(\s+\n)+', r'\n', ''.join(map(str, context['_stdout'])))
class LRUCache(object):
""" Simple LRU cache for template instance caching.
in fact, the OrderedDict in collections module... | (self, capacity):
self.capacity = capacity
self.cache = collections.OrderedDict()
def get(self, key):
""" Return -1 if catched KeyError exception."""
try:
value = self.cache.pop(key)
self.cache[key] = value
return value
except KeyError:
... |
"""Django middlewares."""
try:
# Python 2.x
from urlparse import urlsplit, urlunsplit
except ImportError:
# Python 3.x
from urllib.parse import urlsplit
from urllib.parse import urlunsplit
from django.conf import settings
from django.http import HttpResponsePermanentRedirect
try:
# Django 1.... | if hasattr(self, 'process_response'):
response = self.process_response(request, response)
return response
class SSLifyMiddleware(MiddlewareMixin):
"""Force all requests to use HTTPs. If we get an HTTP request, we'll just
force a redirect to HTTPs.
.. note::
You ... | licitly disabled SSLify, do nothing.
if getattr(settings, 'SSLIFY_DISABLE', False):
return None
# Evaluate callables that can disable SSL for the current request
per_request_disables = getattr(settings, 'SSLIFY_DISABLE_FOR_REQUEST', [])
for should_disable in per_request_disa... |
import argparse
import codecs
import sys
from .auth import parse_authentication
from .confluence_api import create_confluence_api
from .confluence import ConfluencePageManager
from .constants import DEFAULT_CONFLUENCE_API_VERSION
def main():
parser = argparse.ArgumentParser(description='Dumps Confluence page in ... | ain__':
mai | n()
|
#!/usr/bin/env python3
import fnmatch
import os
import re
import ntpath
import sys
import argparse
def get_private_declare(content):
priv_declared = []
srch = re.compile('private.*')
priv_srch_declared = srch.findall(content)
priv_srch_declared = sorted(set(priv_srch_declared))
priv_dec... | ))
priv_dec_str = ''.join(priv_srch_declared)
srch = re.compile('(?<![_a-zA-Z0-9])(_[a-zA-Z0-9]*?)[ ,\}\]\)";]')
priv_split = srch.findall(priv_dec_str)
priv_split = sorted(set(priv_split))
priv_declared += priv_split;
srch = re.compile('(?i)[\s]*local[\s]+(_[\w\d]*)[\s]*=.*')
... | rch.findall(content)
priv_local_declared = sorted(set(priv_local))
priv_declared += priv_local_declared;
return priv_declared
def check_privates(filepath):
bad_count_file = 0
def pushClosing(t):
closingStack.append(closing.expr)
closing << Literal( closingFor[t[0]... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
class HelperShift(models.Model):
"""
n-m relation between helper and shift.
This model then can be used by other apps to "attach" more data with OneToOne fields and signals.
The fields `present` and `manual_presence... | ")
)
present = models.BooleanField(
default=False,
verbose_name=_("Present"),
help_text=_("Helper was at shift")
)
manual_presence = models.BooleanField(
default=False,
editable=False | ,
verbose_name=_("Presence was manually set"),
)
def __str__(self):
return "{} - {} - {}".format(self.helper.event, self.helper, self.shift)
|
""" Tests the implementation of the solution to the Euclidean Minimum Spanning
Tree (EMST) problem """
import pytest
from exhaustive_search.point import Point
from exhaustive_search.euclidean_mst import solve, edist
def compare_solutions(actual, expected):
assert len(actual) == len(expected), "expected %d to equ... | right (%s) to | == %s (left is %s)" % (right, Point(3, 0), left)
else:
assert right == Point(0, 0) or right == Point(6, 0), \
"expected right (%s) to == %s or %s" % (right, Point(0, 0), Point(6, 0))
|
# Copyright 2014-2020 The PySCF Developers. 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 appl... | lmostEqual(np.max(np.absolute(vev1-vev2)), 0.0, 10)
def test_c_dfragf2(self):
qxi = np.random.random((self.naux, self.nmo*self.nocc)) / self.naux
qja = np.random.random((self.naux, self.nocc*self.nvir)) / self.naux
| gf_occ = aux.GreensFunction(np.random.random(self.nocc), np.eye(self.nmo, self.nocc))
gf_vir = aux.GreensFunction(np.random.random(self.nvir), np.eye(self.nmo, self.nvir))
vv1, vev1 = _agf2.build_mats_dfragf2_outcore(qxi, qja, gf_occ.energy, gf_vir.energy)
vv2, vev2 = _agf2.build_mats_dfra... |
#!/usr/bin/python
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(PauseAction(3000))
sequence.append(KeyComboAction("F10"))
sequence.append(KeyComboAction("Tab"))
sequence.append(KeyComboAction("Tab"))
sequence.append(KeyComboAction("Tab"))
sequence.append(KeyComboAction("Tab"... | TPUT: 'Start'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("space"))
sequence.append(utils.AssertPresentationAction(
"2. Activate timer",
["BRAILLE LINE: 'gnome-clocks application Clocks frame Pause push button'",
" VISIBLE: 'Pause push button', cursor=1",
"B... | ocks frame'",
"SPEECH OUTPUT: 'Pause push button'"]))
sequence.append(utils.StartRecordingAction())
sequence.append(KeyComboAction("KP_8"))
sequence.append(utils.AssertPresentationAction(
"3. Review current line",
["BRAILLE LINE: 'Pause Reset $l'",
" VISIBLE: 'Pause Reset $l', cursor=1",
"... |
from django.views.generic import ListView, DetailView, CreateView, \
DeleteView, UpdateView, \
ArchiveIndexView, DateDetailView, \
DayArchiveView, MonthArchiveView, \
TodayArchiveView, Wee... | rn reverse('baseapp_class_studying_list')
class Class_StudyingListView(Class_StudyingBaseListView, ListView):
def get_success_url(self):
from django.core.urlresolvers import reverse
return reverse('baseapp_class_studying_list')
class Clas | s_StudyingMonthArchiveView(
Class_StudyingDateView, Class_StudyingBaseListView, MonthArchiveView):
def get_success_url(self):
from django.core.urlresolvers import reverse
return reverse('baseapp_class_studying_list')
class Class_StudyingTodayArchiveView(
Class_StudyingDateView... |
### extends 'class_empty.py'
### block ClassImports
# NOTICE: Do not edit anything here, it is generated code
from . import gxapi_cy
from geosoft.gxapi import GXContext, float_ref, int_ref, str_ref
### endblock ClassImports
### block Header
# NOTICE: The code generator will not replace the code in this block
### end... | ile
:type sbf: GXSBF
:type file: str
:returns: `GXRA <geosoft.gxapi.GXRA>` Object
:rtype: GXRA
.. versionadded:: 5.0
**License:** `Geosoft Open License <https://geosoftgxdev.atlassian.net/wiki/spaces/GD/pages/2359406/License#License-open-lic>`_
... | GXSBF <geosoft.gxapi.GXSBF>`). SBFs can be created inside other data
containers, such as workspaces, maps, images and databases.
This lets you store application specific information together
with the data to which it applies.
.. seealso::
sbf.gxh
"""
ret_va... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.