prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
__auth | or__ = 'Said | Sef'
|
nt == 'call' and main_debugger.signature_factory:
send_signature_call_trace(main_debugger, frame, filename)
plugin_manager = main_debugger.plugin
is_exception_event = event == 'exception'
has_exception_breakpoints = main_debugger.break_on_caught_exceptions or main_d... | return self.trace_dispatch
except:
if type(condition) != type(''):
if hasattr(condition, 'encode'):
condition = condition.encode('utf-8')
... | nt_exc()
if not main_debugger.suspend_on_breakpoint_exception:
return self.trace_dispatch
else:
stop = True
try:
... |
# Copyright (c) 2013 Mirantis Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... | e
LOG.debug("Checking datanode count")
exit_code, stdout = remote.execute_command(
'sudo su -c "hadoop dfsadmin -report | '
'grep \'Datanodes available:\' | | '
'awk \'{print \\$3}\'" hadoop')
LOG.debug("Datanode count={count}".format(count=stdout.rstrip()))
return exit_code == 0 and stdout and int(stdout) == count
def mysql_start(remote):
LOG.debug("Starting MySQL")
remote.execute_command("/opt/start-mysql.sh")
def oozie_create_db(remote):
L... |
from __future__ import unicode_literals
from django.db import models
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
from rest_framework import serializers, viewsets, permissions
from rest_framework.compat import include, patterns, url
from rest_framework.decorators import link,... | :
expected = ['^notes$', '^notes/(?P<pk>[^/.]+)$']
for idx in range(len(expected)):
self.assertEqual(expected[idx], self.urls[idx].regex.pattern)
class TestNameableRoot(TestCase):
def setUp(self):
class NoteViewSet(viewsets.ModelViewSet):
| model = RouterTestModel
self.router = DefaultRouter()
self.router.root_view_name = 'nameable-root'
self.router.register(r'notes', NoteViewSet)
self.urls = self.router.urls
def test_router_has_custom_name(self):
expected = 'nameable-root'
self.assertEqual(expected... |
t sys
import os
import subprocess
import zipfile
import collections
import multiprocessing
import settings
import utils
# -------------------------------------------------------------------------------
EXPECTED_FAILURE_NOT_MET, DATABASE_LENGTH_MISMATCH, \
DATABASE_VALUE_MISMATCH, IMPORT_FAILURE, \
FILE_NOT_READABLE, ... | e_expect, pp, msg, *args):
"""
Report failure of a sub-test
File f failed a test for pp config pp, failure notice is msg,
*args is format()ting args for msg
"""
print("[FAILURE] " + messages[msg].format(*args))
self.failures.append((failfile, filename_expect, pp... | f passed the test, msg is a happy success note,
*args is format()ing args for msg.
"""
print("[SUCCESS] " + messages[msg].format(*args))
self.success.append(f)
def report_results(self):
"""Write results to ../results/run_regression_suite_failures.txt"""
count_succ... |
'''
Generates SquareCable grid.
'''
grid = np.full((b,b), u)
fix = np.ones((b,b))
grid = np.pad(grid, ((t-b)/2,), 'constant', constant_values=(0,))
fix = np.pad(fix, ((t-b)/2,), 'constant', constant_values=(0,))
grid = np.pad(grid, 1, 'constant', constant_values=(0,))
fix = np.pad(... | [1]-1] +
grid[index[0], index[1]+1] )
return new_grid
if w==-1:
coef = float(grid.shape[1])/grid.shape[0]
const = 2.0 if coef==1. else 5.5
w = 2./(1+const/(coef*scale))
for index, fixed in np.ndenumerate(fix):
if fixed: continue
... | * w *
( grid[index[0]-1, index[1]] +
grid[index[0]+1, index[1]] +
grid[index[0], index[1]-1] +
grid[index[0], index[1]+1] ))
return grid
# Base class
class PotentialGrid(object):
def update_grid(self, w=-1):
... |
import unittest
class TestColor(unittest.TestCase):
def test(self):
s | elf | .assertTrue(True)
|
import os
import sys
import random
import logging
import signal
main_path = os.path.abspath (os.path.dirname (__file__))
prev_path = main_path + "/.."
sys.path.append (prev_path)
from utils import _redis_connect, log_init
from command import *
from RedisHelper import RedisServer
from Config import Config
from sipcore ... | _redis, ckey, _id,
proto)
RedisServer.server_sip_create (self._redis, ckey, self | .s_id,
bind_ip, bind_port, self.rr, proto)
self._logger.debug (
"Contacting transmitter %d"%self.rr)
self.sip [(bind_ip, bind_port, proto)] = (self.s_id, self.rr)
self.s_id += 1
self.rr = self.inc_rr ()
self._logger.info (
... |
he pretty ones are usually unhappy. They expect everyone to be enamored of their beauty. How can a person be content when their happiness lies in someone else's hands, ready to be crushed at any moment? Ordinary-looking people are far superior, because they are forced to actually work hard to achieve their goals, inste... | , and had worked her way through them. Some people, he knew, would have buckled under, found a clutch, or given up. But she had | carved a place for herself and made it work. -- Nora Roberts",
"A clay pot sitting in the sun will always be a clay pot. It has to go through the white heat of the furnace to become porcelain. -- Mildred W. Struven",
"Barking hard work, being boy. -- Scott Westerfeld, Leviathan",
"Do I attri... |
# -*- coding: utf-8 -*-
|
__author__ = """Ivan Ogasawara"""
__email__ = 'ivan.ogasawara@gmail | .com'
__version__ = '0.1.0'
|
ration" "Device 0000"
0000:00:11.0 "Unassigned class [ff00]" "Intel Corporation" "Wellsburg SPSR" -r05 "Intel Corporation" "Device 7270"
0000:00:11.4 "SATA controller" "Intel Corporation" "Wellsburg sSATA Controller [AHCI mode]" -r05 -p01 "Cisco Systems Inc" "Device 0067"
0000:00:16.0 "Communication controller" "Intel ... | 1137:0043 (rev a2)",
},
'0000:10:00.0': {
'LSPCI_KS': LSPCI_KS_IGB_BOUND.format('10:00.0'),
'LSPCI_NS': "10:00.0 0200: 8086:1521 (rev 01)",
},
'0000:10:00.1': {
'LSPCI_KS': LSPCI_KS_IGB_BOUND.format('10:00.1'),
'LSPCI_NS': "10:00.1 0200: 8086:1521 (rev 01) | ",
},
}
NET_SETUP_ORPHAN = copy.deepcopy(NET_SETUP)
NET_SETUP_ORPHAN['CONFD_CLI'] = CONFD_CLI_ONE_MISSING
NET_SETUP_ORPHAN['0000:07:00.0']['LSPCI_KS'] = LSPCI_KS_IGB_UNBOUND.format('07:00.0')
QN_CONF = """
lc_procs = { svm_cleanup vpe confd orca }
install_root = "/cisco"
svm_cleanup = {
pgm = "$(install_r... |
"""This module contains the general information for EquipmentLocatorLed ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class EquipmentLocatorLedConsts:
ADMIN_STATE_INACTIVE = "inactive"
ADMIN_STATE_OFF = "off"
ADMI... | "color": MoPropertyMeta("color", "color", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, None, None, None, ["amber", "blue | ", "green", "red", "unknown"], []),
"id": MoPropertyMeta("id", "id", "uint", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, None, None, None, [], []),
"name": MoPropertyMeta("name", "name", "string", VersionMeta.Version2013e, MoPropertyMeta.READ_ONLY, None, 0, 512, None, [], []),
... |
expected_result = {
"error": False,
"results": [
{
"remote": "remote1",
"items": [
{
... | fake2/0.1@user/channel", "fake2_package_id2",
"fake2_options2", "fake2_settings2", "fake2_requires2", False)
info = self.recorder.get_info()
expected_result = {
"error": False,
"results": [
... | "recipe": {
"id": "fake1/0.1@user/channel"
},
"packages": [
{
... |
from test import support
import unittest
import sys
# Skip test if nis module does not exist.
nis = support.import_module('nis')
class NisTests(unittest.TestCase):
def test_maps(self):
try:
maps = nis.maps()
except nis.error as msg:
# NIS is probably not active, so this te... | for k, v in mapping.items():
if not k:
continue
if nis.match(k, nismap) != v:
self.fail("NIS match failed for key `%s' in map `%s'" % (k, nismap))
else:
# ju | st test the one key, otherwise this test could take a
# very long time
done = 1
break
if done:
break
if __name__ == '__main__':
unittest.main()
|
from autobahn.twisted.websocket import WebSocketServerFactory, \
WebSocketServerProtocol
from tws_game.lobby import Lobby
from tws_game.tetris import Tetris
from pprint import pprint
import json
class ClientConnection(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
def... | tServerProtocol.connectionLost(self, reason)
self.factory.unregister(self)
class TwsServerFactory(WebSocketServerFactory):
AVAILABLE_GAMES = {
'TETRIS': Tetris
}
def __init__(self, url):
WebSocketServerFactory.__init__(self, url)
self.clients = []
self.lobbies = {... | ef register(self, client):
if client not in self.clients:
print "registered client {}".format(client.peer)
client.lobby = None
self.clients.append(client)
def unregister(self, client):
if client in self.clients:
print "unregistered client {}".format(c... |
"""Migration for a given Submitty course database."""
def up(config, database, semester, course):
"""
Run up migration.
:param config: Object holding configuration details about Submitty
:type config: migrator.config.Config
:param da | tabase: Object for interacting with given database for environment
:type database: migrator.db.Database
:param semester: Semester of the course being migrated
:type semester: str
:param course: Code of course being migrated
:type course: str
"""
database.execute(
"""
CREATE TA... | ETE CASCADE,
user_id character varying(255) REFERENCES users (user_id) ON DELETE CASCADE,
team_id character varying(255) REFERENCES gradeable_teams (team_id),
accessor_id character varying(255) REFERENCES users (user_id) ON DELETE CASCADE,
"timestamp" timestamp with time ... |
# -*- coding: utf-8 -*-
################################################################ | ##############
#
# Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
################################################################## | ############
from . import b2s_image
|
port absolute_import
__all__ = ('urlpatterns',)
from django.conf.urls import include, patterns, url
from django.conf import settings
from django.http import HttpResponse
from django.views.generic import RedirectView
from sentry.web import api
from sentry.web.frontend import accounts, admin, generic
from sentry.web.... | ry.web.frontend.project_plugin_disable import ProjectPluginDisableView
from sentry.web.frontend.project_plugin_enable import ProjectPluginEnableView
from sentry.web.frontend.project_plugin_reset import ProjectPluginResetView
from sentry.web.frontend.project_notifications import ProjectNotificationsView
from sentry.web.... | frontend.project_release_tracking import ProjectReleaseTrackingView
from sentry.web.frontend.project_rules import ProjectRulesView
from sentry.web.frontend.project_rule_edit import ProjectRuleEditView
from sentry.web.frontend.project_rule_remove import ProjectRuleRemoveView
from sentry.web.frontend.project_settings imp... |
############################
## replaceLinesFull.py
############################
"""
Script for repl | acing special escape characters in the original yelp academic dataset files.
Special characters such as \n cause problems for the JSON to CSV conversions.
If you want to include review text in the edge fil | e, use this script to replace
special characters such as \n in the JSON review file. This script is much faster
than doing the replacement in R.
"""
with open("yelp_academic_dataset_review.json", "rt") as fin:
with open("reviewFullOut.json", "wt") as fout:
for line in fin:
fout.write(line.replace(r'\n... |
# -*- coding: utf-8 -*-
"""
terminal.prompt
~~~~~~~~~~~~~~~
Prompt support on terminal.
:copyright: (c) 2013 by Hsiaoming Yang.
"""
import getpass
import sys
# Python 3
if sys.version_info[0] == 3:
string_type = str
else:
string_type = (unicode, str)
def prompt(name, default=None):
"""... | pt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') and ' ' or ': '
while True:
try:
rv = raw_input(prompt)
except NameError:
rv = input(prompt)
if rv:
return rv
if default is not None:
return default
de... | ):
"""
Grabs hidden (password) input from command line.
:param name: prompt text
:param default: default value if no input provided.
"""
prompt = name + (default and ' [%s]' % default or '')
prompt += name.endswith('?') and ' ' or ': '
while True:
rv = getpass.getpass(prompt)
... |
import requests
import pytest
import subprocess
# ============================================================================
class TestAuto(object):
PREFIX = 'http://localhost:8089'
USER = 'testauto'
LIST_ID = ''
AUTO_ID = ''
NUM_BROWSERS = 2
@classmethod
def setup_class(cls):
c... | json={'title': 'Auto Test'})
assert res.json()['collection']['id'] == 'auto-test'
assert res.json()['collection']['title'] == 'Auto Test'
def test_create_auto(self):
params = {'scope_type': 'single-page',
| 'num_browsers': self.NUM_BROWSERS,
}
res = self.post('/api/v1/auto?user=testauto&coll=auto-test', json=params)
assert res.json()['auto']
TestAuto.AUTO_ID = res.json()['auto']
def test_add_urls(self):
params = {'urls': [
'https://twitter.com/webrecorde... |
from setuptools import setup, find_packag | es
setup(
name='plutokore',
packages=find_packages(),
version='0.10',
description='Python tool for analysing PLUTO simulation data',
author='Patrick Yates',
author_email='patrick.yates@utas.edu.au',
url='https://github.com/pmyates/plutokore',
keywords=['pluto', 'astrophsyics'],
lic... | setup_requires=['pytest-runner'],
tests_require=['pytest', 'pytest-datafiles'],
)
|
class Zvire(object):
def __init__(self,jmeno = "",druh = "",hmotnost =0):
self._jmeno = jmeno
self._druh = druh
self._hmotnost = hmotnost
@property
def jmeno(self):
return self._jmeno
@jmeno.setter
def jmeno(self,ajmeno):
self._jmeno = ajmeno
@proper... | uh = adruh
@property
def hmotnost(self):
return self._hmotnost
@hmotnost.setter
def hmotnost(self,ahm):
self._hmotnost = ahm
def __str__(self):
return "Zvire {} druhu {} a hmotnosti {} kg".format(
sel | f.jmeno,self.druh,self.hmotnost
)
k = Zvire()
k.jmeno = "Mikeš"
k.druh = "kočka"
k.hmotnost = 3
l = Zvire(jmeno = "Alík", hmotnost=5)
print(k)
print(type(k))
print(l)
print(type(l))
|
import socket as sk
from kivy.logger import Logger
def getWebsite():
return "www.google.com"
def getIpPort():
sock_info=sk.getaddrinfo(getWebsite(),80,proto=sk.IPPROTO_TCP)
return sock_info[0][-1]
def checkInternet():
sock=sk.socket()
sock.settimeout(1)
try:
sock.connect(getIpPort())
... | rn False
except Exception as e:
Logger.error(e)
return False
def checkSpeed():
import psutil
import ti | me
init=[psutil.net_io_counters().bytes_sent,psutil.net_io_counters().bytes_recv]
time.sleep(1)
final=[psutil.net_io_counters().bytes_sent,psutil.net_io_counters().bytes_recv]
readings=[(final[0]-init[0]),(final[1]-init[1])]
print(readings)
if readings[0] < 200 or readings[1] < 200:
retu... |
# -*- coding: utf-8 -*-
"""
fbone.modules.user
~~~~~~~~~~~~~~~~~~~~~~~~
user management commands
"""
from flask.ext.script import Command, prompt, prompt_pass
from werkzeug.datastructures import MultiDict
from .models import User
class CreateUserCommand(Command):
"""Create a user"""
"""!!!broke... | .email)
return
print '\nError creating user:'
for errors in form.errors.values():
print '\n'.join(errors)
|
class DeleteUserCommand(Command):
"""Delete a user"""
def run(self):
email = prompt('Email')
user = User.first(email=email)
if not user:
print 'Invalid user'
return
User.delete(user)
print 'User deleted successfully'
class ListUsersCommand(Comm... |
n('form_designer_formdefinitionfield', 'help_text', self.gf('django.db.models.fields.TextField')(null=True))
def backwards(self, orm):
# Changing field 'FormDefinitionField.help_text'
db.alter_column('form_designer_formdefinitionfield', 'help_text', self.gf('django.db.models.fields.CharField')(max... | ult': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [... | {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'... |
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | 'num_drives': 3}]}
vsa_ref = self.vsa_api.create(self.context, **param)
volumes = self.vsa_api.get_all_vsa_drives(self.context,
vsa_ref['id'])
user_data = vsa_utils.generate_user_data(vsa_ref, volumes)
user_data = base64.b64decod... | r_data)
elem = ElementTree.fromstring(user_data)
self.assertEqual(elem.findtext('name'),
param['display_name'])
self.assertEqual(elem.findtext('description'),
param['display_description'])
self.assertEqual(elem.findtext('vc_count'),
... |
"""Init | Extension."""
from flask_cache import Cache
cache = Cache()
def setup_app(app):
"""Init the extension with app context."""
c | ache.init_app(app)
return app
|
ation',
style='readonly', show_label=False),
Item('stim_threshold', label='Threshold',
tooltip=tooltips['stim_threshold']),
HGroup(Item('test_stim', enabled_when='can_test_stim',
show_labe... | _THRESHOLD' in config:
try:
stim_threshold = float(
| config['MNE_KIT2FIFF_STIM_CHANNEL_THRESHOLD'])
except ValueError:
warn("Ignoring invalid configuration value for "
"MNE_KIT2FIFF_STIM_CHANNEL_THRESHOLD: %r (expected "
"float)" %
(config['MNE_KIT2FIFF_STIM_CHAN... |
# PPFem: An educational finite element code
# Copyright (C) 2015 Matthias Rambausek
#
# 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 License, or
# (at your option) any ... | rt PDE
__all__ = ["Mesh", "Point", "Line", "Vertex", "Face" | , "Cell", "Mapping", "FunctionSpace", "Functional",
"LinearForm", "BilinearForm", "FormCollection", "DefaultSystemAssembler", "FEFunction", "FunctionEvaluator",
"PDE"]
__all__ += ppfem.user_elements.__all__ + ppfem.quadrature.__all__ + ppfem.user_equations.__all__
|
ile.close()
# Open again in case the user adds new mappings
known_translations_file = open(known_translations_file_name, "a")
# Generate candidates for the given author. This should only be called if the given author
# name does not represent a full name as this operation is somewhat expensive. Under the
# hood, it m... | nslations_file.flush()
line = line.replace(temp_author, author)
contributions.append(line)
print("==================================================================================\n")
contri | butors_file.close()
known_translations_file.close()
# Sort the contributions before writing them to the new file.
# Additionally, check if there are any duplicate author rows.
# This could happen if the same use |
# -*- coding: utf-8 -*-
"""This file is part of the microerp project.
This program is free software | : you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
optio | n) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU Lesser General Publ... |
import os
from django.contrib.gis.geos import Point
from data_importers.management.commands im | port BaseCsvStationsCsvAddressesImporter
"""
Define a stub implementation of address importer we can run tests against
"""
class Command(BaseCsvStationsCsvAddressesImporter):
srid = 4326
council_id = "ABC"
addresses_name = "addresses.csv"
stations_name = "stations.csv"
base_folder_path = os | .path.join(
os.path.dirname(__file__), "../fixtures/csv_importer"
)
def address_record_to_dict(self, record):
return {
"council": self.council,
"uprn": record.uprn,
"address": record.address,
"postcode": record.postcode,
"polling_stati... |
#!/usr/bin/env python
from Acspy.Nc.CommonNC import CommonNC
from Acspy.Nc.Supplier import Supplier
import datacapEx
from datacapEx import ExecBlockProcessedEvent, DataCapturerId, ExecBlockStartedEvent, ScanStartedEvent
import asdmEX
s = Supplier('pyTest-NC')
name = 'DATACAP1'
s.publishEvent(name)
ses... | xecBlockEntityRef = asdmEX.IDLEntityRef(execId,"X00000000","0","0")
sbId = asdmEX.IDLEntityRef(execId,"X00000000","0","0")
arrayId = "1"
time = 100
startExecBlock = datacapEx.ExecBlockStartedEvent(execBlockEntityRef,sbId,sessionId,arrayId,time)
s.publishEvent(startExecBlock)
endExecBlock = datacapEx.ExecBlockE | ndedEvent(execBlockEntityRef,sbId,sessionId,arrayId,datacapEx.SUCCESS,time+10)
s.publishEvent(endExecBlock)
print "All structures successfully sent!!"
s.destroyNotificationChannel()
|
from office365.runtime.client_value import ClientValue
class ServicePlanInfo(ClientValue):
"""Contains information about a service plan associated with a subscribed SKU. The servicePlans property of
the subscribedSku entity is a collection of servicePlanInfo."""
def __init__(self, _id=None, name=None, pr... | "Success" - Service is fully provisioned.
"Disabled" - Service has been disabled.
"PendingInput" - Service is not yet provisioned; awaiting service confirmation.
"PendingActivation" - Service is provisioned but requires explicit activation by administrator
... | osoft has added a new service to the product SKU and it has not been
activated in the tenant, yet.
:param str name: The name of the service plan.
:param str _id: The unique identifier of the service plan.
"""
super(ServicePlanInfo, self).__init__()
self.servicePlan... |
# SPDX-License-Identifier: MIT
import sys
try:
# Our match_hostname function is the same as 3.5's, so we only want to
# import the match_hostname function if it's at least that good.
if sys.version_info < (3, 5):
raise ImportError("Fallback to vendored code")
from ssl import CertificateError, ... | m a pypi module
from backports.ssl_match_hostname import CertificateError, match_hostname
except ImportError:
# Our vendored copy
from ._implementation import CertificateError, match_hostname
# Not needed, but documenting what we provide.
__all__ = ('Cer | tificateError', 'match_hostname')
|
import numpy as np
import pyroms
from pyroms_toolbox.BGrid_GFDL import BGrid_GFDL
def get_nc_BGrid_GFDL(grdfile, name='GFDL_CM2.1_North_Pacific', \
# xrange=(80,189), yrange=(96,198)):
xrange=(60,175), yrange=(120, 190)):
"""
Bgrd = get_nc_BGrid_GFDL(gr... | ape
N_t = z_t.shape[0]
mask_t = np.zeros((N_t, M_t, L_t))
for j in range(M_t):
for i in range(L_t):
try:
mask_t[0:kmt[j,i], j,i] = 1
| except:
mask_t[:, j,i] = 0
# compute mask at uv-point
M_uv, L_uv = kmu.shape
N_uv = z_uv.shape[0]
mask_uv = np.zeros((N_uv, M_uv, L_uv))
for j in range(M_uv):
for i in range(L_uv):
try:
mask_uv[0:kmu[j,i], j,i] = 1
except:
... |
# This file is part of OMG-tools.
#
# OMG-tools -- Optimal Motion Generation-tools
# Copyright (C) 2016 Ruben Van Parys & Tim Mercy, KU Leuven.
# All rights reserved.
#
# OMG-tools is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public |
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.
# This software 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. Se... | m; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from omgtools import *
import numpy as np
# create vehicle
vehicle = Quadrotor3D(0.5)
vehicle.set_initial_conditions([-3, -2, -0.5, 0, 0, 0, 0, 0])
vehicle.set_terminal_conditions([3, 2, 0.5])
vehicl... |
fr | om robot.api.deco import keyword
def defined_twice():
1/0
@keyword('Defined twice')
def this_time_using_custom_name():
2/0
def defined_thrice():
1/0
def definedThrice():
2/0
def Defined_Thrice():
3/0
@keyword('Embedded ${arguments} twice')
def embedded1(arg):
1/0
@keyword('Embedded ${arg... | ents match} TWICE')
def embedded2(arg):
2/0
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Radim Rehurek <radimrehurek@seznam.cz>
# Copyright (C) 2016 Manas Ranjan Kar <manasrkar91@gmail.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
USAGE:
$ python -m gensim.scripts.glove2word2vec --input <GloVe ve... | rmat='%(asctime)s : %(threadName)s : %(levelname)s : | %(message)s', level=logging.INFO)
logging.root.setLevel(level=logging.INFO)
logger.info("running %s", ' '.join(sys.argv))
# check and process cmdline input
program = os.path.basename(sys.argv[0])
if len(sys.argv) < 2:
print(globals()['__doc__'] % locals())
sys.exit(1)
parser =... |
from .. import cpso
from .._helpers import register
__all__ = [
"minimize",
]
def minimize(
fun,
bounds,
x0=None,
args=(),
maxiter=100,
popsize=10,
inertia=0.7298,
cognitivity=1.49618,
sociability=1.49618,
seed=None,
xtol=1.0e-8,
ftol=1.0e-8,
constraints=None,
... | zeResult`. Important attributes are:
- ``x``: the solution array
- ``fun``: the solution function value
- ``success``: a Boolean flag indicating if the optimizer exited successfully
- ``message``: a string which describes the cause of the termination
References
----------
... | International Conference on Neural Networks, 1995, 4: 1942-1948
.. [2] F. Van Den Bergh, *An analysis of particle swarm optimizers*, University of Pretoria, 2001
"""
competitivity = None
return cpso(
fun,
bounds,
x0,
args,
maxiter,
popsize,
iner... |
#!/usr/bin/python
import urllib2, base64
import shutil
import json
import json
import argparse
import os
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='''
This script will copy the step/jobentry images from a running carte (with kthin-server) to the img folder
''', formatter_class = arg... | r.add_argument('-u', '--user', help='The user to connect to carte as', default='cluster')
parser.add_ar | gument('-p', '--password', help='The password to connect to carte with', default='cluster')
parser.add_argument('-q', '--port', help='The port to connect to carte at', default='8001')
parser.add_argument('-d', '--destination', help='The top level destination directory', default='../app')
args = parser.parse_args(... |
OOP', #
'MUT', #
'REF', #
'INLINE', #
'TO', #
'ASSIGNMENTOPERATOR', #
'CASE', #
'DEFAULT', #
'ANDSYMBOL', #
'ORSYMBOL... | toBeCopied):
# self.lineNr = toBeCopied.lineNr
# self.rowNr = toBeCopied.rowNr
# self.kind = toBeCopied | .kind
# self.tokString = toBeCopied.tokString
def print_it(self): # for testing purposes
if self.kind == Tok.EOF:
print("EOF", end='')
elif self.kind == Tok.LCURLYBRACKET:
print("{", end='')
elif self.kind == Tok.RCURLYBRACKET:
print... |
#!/usr/bin/python
#
# Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite
# contributors
#
# This file is part of EvoSuite.
#
# EvoSuite is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser Public License as published by the
# Free Software Foundation, either vers... | ere to put stuff (default in subdirs of BASEDIR)
REPORTS="%s/reports" % BASEDIR
SCRIPTDIR="%s/scripts" % BASEDIR
LOGDIR="%s/logs" % BASEDIR
TESTDIR="%s/tests" % BASEDIR
os.makedirs(REPORTS)
os.makedirs(SCRIPTDIR)
os.makedirs(LOGDIR)
os.makedirs(TESTDIR)
MINSEED = int(sys.argv[2])
MAXSEED = int(sys.argv[3])
MAX_JOBS =... | gv[4]
exit(1)
CLASSES = []
f = open(CLASSES_FILE)
for line in f:
entry = line.rstrip().split()
CLASSES.append(entry)
f.close()
NUM_CLASSES=len(CLASSES)
CORES = int(sys.argv[6])
if CORES <= 0 :
print 'Wrong number of cores'
exit(1)
# Global counter of jobs created
JOB_ID=0
CALL_ID=0
CONFIG_ID=0
SEARC... |
# (c) 2012, Zettar Inc.
# Written by Chin Fang <fangchin@zettar.com>
#
# This file is part of Ansible
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at y... | nd is left-zero-padded, e.g. '001', it is taken as a
formatting hint when the range is expanded. e.g. [001:010] is to be
expanded into 001, 002 ...009, 010.
Note that when beg is specified with left zero padding, then the length of
end must be the same as that of beg, else an exception is raised.
'''
from __future__ i... | detect_range(line = None):
'''
A helper function that checks a given host line to see if it contains
a range pattern described in the docstring above.
Returnes True if the given line contains a pattern, else False.
'''
if '[' in line:
return True
else:
return False
def expa... |
# -*- coding: utf-8 -*-
# Copyright 2017 Onestein (<http://www.onestein.eu>)
# License AGP | L-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from . import test_employee_display_own_info
| |
"""
@package mi.dataset.driver.ctdpf_ckl.mmp_cds.driver
@file marine-integrations/mi/dataset/driver/ctdpf_ckl/mmp_cds/driver.py
@author Mark Worden
@brief Driver for the CtdpfCklMmpCds
Release notes:
initial release
"""
__author__ = 'Mark Worden'
__license__ = 'Apache 2.0'
from mi.core.log import get_logger
log = g... | figKeys.PARTICLE_MODULE: 'mi.dataset.parser.ctdpf_ckl_mmp_cds',
DataSetDriverConfigKeys.PARTICLE_CLASS: 'CtdpfCklMmpCdsParserDataParticle'
})
log.de | bug("My Config: %s", config)
self._parser = CtdpfCklMmpCdsParser(
config,
parser_state,
infile,
self._save_parser_state,
self._data_callback,
self._sample_exception_callback
)
return self._parser
def _build_harvester(s... |
# 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.
#---------------------------------------------------------------------... | force_change_password_next_login=True
)
)
)
self.assertEqual(user.display_name, 'Test Buddy')
user = self.graphrbac_client.users.get(user.object_id)
self.assertEqual(user.display_name, 'Test Buddy')
users = self.graphrbac_client.use... | )
users = list(users)
self.assertEqual(len(users), 1)
self.assertEqual(users[0].display_name, 'Test Buddy')
self.graphrbac_client.users.delete(user.object_id)
#------------------------------------------------------------------------------
if __name__ == '__main__':
unittest.... |
# Copyright 2011 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LI | CENSE-2.0
#
# Unless re | quired 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.
fr... |
rt warnings
import RPi.GPIO as GPIO
class Measurement(object):
"""Create a measurement using a HC-SR04 Ultrasonic Sensor connected to
the GPIO pins of a Raspberry Pi.
Metric values are used by default. For imperial values use
unit='imperial'
temperature=<Desired temperature in Fahrenheit>
""... | se the
speed of your reading but could increase variance in readings;
value = sensor.Measurement(trig_pin, echo_pin)
r = value.raw_distance(sample_size=5)
Adjusting the interval between individual samples can also
increase the speed of the reading. Increasing the speed will a... | is also a safe setting that should not cause errors.
e.g.
r = value.raw_distance(sample_wait=0.03)
"""
if self.unit == "imperial":
self.temperature = (self.temperature - 32) * 0.5556
elif self.unit == "metric":
pass
else:
raise Valu... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import SocketServer
from lib import const
class PowerIRSendHandler(SocketServer.Stream | RequestHandler):
def handle(self):
# print "connected from:", self.client_address
sent_data = ""
while True:
data = self.request.recv(1024)
if len(data) == 0:
break
sent_data += data
if sent_data == const.IR_SEND_ | MSG:
subprocess.call(const.IR_SEND_CMD, shell=True)
self.request.close()
if __name__ == "__main__":
address = (const.IR_SEND_HOST, const.IR_SEND_PORT)
try:
server = SocketServer.ThreadingTCPServer(address, PowerIRSendHandler)
print "power_ir_send_server listening", server.... |
# proxy module
from __future__ import absolute | _import
from envisage.plugins.refresh_code.refresh_code_plugin import *
| |
# -*- coding: utf-8 -*-
#
# Copyright 2015 Thomas Amland
#
# 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 spec... | tart = "restart"
Terminate = "terminate"
Failure = namedtuple('Failure', ['ref', 'exception', 'traceback'])
Supervise = namedtuple('Supervise', ['ref'])
Terminated = namedtuple('Terminated', ['ref'])
DeadLetter = namedtuple('DeadLetter', ['message', 'sender', 'recipient'])
|
import logging
access_logger | = logging.getLogger('aiohttp.access')
client_logger = logging.getLogger('aiohttp.client')
interna | l_logger = logging.getLogger('aiohttp.internal')
server_logger = logging.getLogger('aiohttp.server')
web_logger = logging.getLogger('aiohttp.web')
ws_logger = logging.getLogger('aiohttp.websocket')
|
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
__doc__ = """
gyptest.py -- test runner for GYP tests.
"""
import os
import optparse
import shlex
import subprocess
import sys
class Comma... | O: handle meta characters?
s = ' '.join(command)
else:
s = self.subst(command)
if not s. | endswith('\n'):
s += '\n'
sys.stdout.write(s)
sys.stdout.flush()
def execute(self, command, stdout=None, stderr=None):
"""
Executes a single command.
"""
if not self.active:
return 0
if type(command) == type(''):
command = self.subst(command)
cmdargs = shlex.split(... |
import pytz
from sqlalchemy.types import TypeDecorator
from sqlalchemy.ext.indexable import index_property
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy_utils import EncryptedType
from redash.utils import json_dumps, json_loads
from redash.utils.configuration import ConfigurationContainer
from .base impo... | list.append(self, value)
self.changed()
def remove(self, value):
list.remove(self, value)
self.changed()
@classmethod
def coerce(cls, key, value):
if not isinstance(value, MutableList):
if isinstance(value, list):
return MutableList(value)
... | e(key, value)
else:
return value
class json_cast_property(index_property):
"""
A SQLAlchemy index property that is able to cast the
entity attribute as the specified cast type. Useful
for JSON and JSONB colums for easier querying/filtering.
"""
def __init__(self, cast_type... |
#coding=utf-8
import unittest
import H | TMLTestRunner
import time
from config import globalparam
from public.common import sendmail
def run():
test_dir = './testcase'
suite = unittest.defaultTestLoader.discover(start_dir=test_dir,pattern='test*.py')
now = time.strfti | me('%Y-%m-%d_%H_%M_%S')
reportname = globalparam.report_path + '\\' + 'TestResult' + now + '.html'
with open(reportname,'wb') as f:
runner = HTMLTestRunner.HTMLTestRunner(
stream=f,
title='测试报告',
description='Test the import testcase'
)
runner.run(suit... |
ar sub dirs
tmpLog.debug('tar for {0} sub dirs'.format(len(dirs)))
with Pool(max_workers=multiprocessing.cpu_count()) as pool:
retValList = pool.map(tar_directory, dirs)
for dirName, (comStr, retCode, stdOut, stdErr) in zip(dirs, re... | method_name='get_panda_ids')
# look for the json just under the access point
jsonFilePath = os.path.join(workspec.get_access_point(), pandaIDsFile)
tmpLog.debug('looking for PandaID file {0}'.format(jsonFilePath))
retVal = []
if not | os.path.exists(jsonFilePath):
# not found
tmpLog.debug('not found')
return retVal
try:
with open(jsonFilePath) as jsonFile:
retVal = json.load(jsonFile)
except Exception:
tmpLog.debug('failed to load json')
return r... |
##############################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the commercial license agreement pro... | else:
self.name = m.group(2)
else:
kind = m.group(3)
if not(kind):
kind = 'strong'
self.specDependencies[m.group(2)] = kind
if self.name == '':
log.critical('Plugin name not set for spe... | self.importedSymbols.append(m.group(1))
else:
Library._parseNMline(self, line)
def addSymbolDependency(self, dep, symbol):
if dep in self.symbolDependencies:
self.symbolDependencies[dep]['total'] += 1
else:
self.symbolDependencies[dep] = {}
... |
_file(reference)
make_reference_dir(reference)
shutil.move(json_file, reference)
else:
print('Generated reflection json in {} does not match reference {}!'.format(json_file, reference))
with open(json_file, 'r') as f:
print(... | r_is_invalid_spirv(shader):
return '.invalid.' in shader
def shader_is_legacy(shader):
return '.legacy.' in shader
def shader_is_flatten_ubo(shader):
return '.flatten.' in shader
def shader_is_sso(shader):
return '.sso.' in shader
def shader_is_flatten_dimensions(shader):
return '.flatten_dim.' ... | args, paths):
joined_path = os.path.join(shader[0], shader[1])
vulkan = shader_is_vulkan(shader[1])
desktop = shader_is_desktop(shader[1])
eliminate = shader_is_eliminate_dead_variables(shader[1])
is_spirv = shader_is_spirv(shader[1])
invalid_spirv = shader_is_invalid_spirv(shader[1])
is_leg... |
b import glob
import logging
import warnings
warnings.filterwarnings('ignore', '.*', UserWarning)
warnings.filterwarnings('ignore', '.*', RuntimeWarning)
log = logging.getLogger(__name__)
RDFLIB_CONNECTION = ''
RDFLIB_STORE = 'IOMemory'
CWM_NS = Namespace("http://cwmTest/")
DC_NS = Namespace("http://purl.org/dc/el... | 03.rdf', # " " " "
]
TopDownTests2Skip = [
'OWL/FunctionalProperty/Manifest002.rdf', # requires second order predicate derivation
'OWL/FunctionalProperty/Manifest004.rdf',
'OWL/InverseFunctionalProperty/Manifest002.rdf | ',
'OWL/InverseFunctionalProperty/Manifest004.rdf',
'OWL/oneOf/Manifest003.rdf', # Requires quantification over predicate symbol (2nd order)
# 'OWL/AllDifferent/Manifest001.rdf', # Not sure why
'OWL/distinctMembers/Manifest001.rdf' # Not sure why
]
Tests2Skip = [
'OWL/InverseFunctionalProperty... |
tition | Dense Quantile |
# i0 | (0.2, 0.12) | 0 | 1 |
# i1 | (-0.5, 0.07) | 0 | 1 |
# i2 | (1.2, 0.2) | 0 | 0 |
# i3 | (4.0, 0.13) | 1 | 1 |
dense_column = array_ops.constant([0... | ready2, partitions, gains, splits = (
sess.run([
are_splits_ready, are_splits_ready2, partitions, gains, splits
| ]))
# During the first iteration, inequality split handlers are not going to
# have any splits. Make sure that we return not_ready in that case.
self.assertFalse(are_splits_ready)
self.assertTrue(are_splits_ready2)
self.assertAllEqual([0, 1], partitions)
# Check the gain on partitio... |
"""Constants for the cloud component."""
DOMAIN = 'cloud'
REQUEST_TIMEOUT = 10
PREF_ENABLE_ALEXA = 'alexa_enabled'
PREF_ENABLE_GOOGLE = 'google_enabled'
PREF_ENABLE_REMOTE = 'remote_enabled'
PREF_GOOGLE | _ALLOW_UNLOCK = 'google_allow_unlock'
PREF_CLOUDHOOKS = 'cloudhooks'
PREF_CLOUD_USER = 'cloud_user'
CONF_ALEXA = 'alexa'
CONF_ALIASES = 'aliases'
CONF_COGNITO_CLIENT_ID = 'cognito_client_id'
CONF_ENTITY_CONFIG = 'entity_config'
CONF_FILTER = 'filter'
CONF_GOOGLE_ACTIONS = 'google_actions'
CONF_RELAYER = 'relayer'
CONF... | 'cloudhook_create_url'
CONF_REMOTE_API_URL = 'remote_api_url'
CONF_ACME_DIRECTORY_SERVER = 'acme_directory_server'
MODE_DEV = "development"
MODE_PROD = "production"
DISPATCHER_REMOTE_UPDATE = 'cloud_remote_update'
class InvalidTrustedNetworks(Exception):
"""Raised when invalid trusted networks config."""
|
def extractTheevilduketranslationsBlogspotCom(item):
'''
Parser for 'theevilduketranslations.blogspot.com'
'''
vol, chp, frag, postfix = extractV | olChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return... | name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
|
#!/usr/bin/python
# JIRA commit acceptance python client for CVS
# Author: istvan.vamosi@midori.hu
# $Id$
import sys
import urlparse
import xmlrpclib
# configure JIRA access
# ("projectKey" can contain multiple comma-separated JIRA project keys like "projectKey = 'TST,ARP'".
# If you specify multiple key... | cceptance settings if you don't
# want to specify any exact project key.)
jiraBaseURL = '<JIRA base URL>'
jiraLogin = '<JIRA user name>'
jiraPassword = '<JIRA password>'
projectKey = '<JIRA project key>'
# get committer passed as arg[1]
committer = sys.argv[1]
# slurp log message from log message file passe... | e to open ' + sys.argv[2] + '.'
sys.exit(1)
# print arguments
print 'Committer: ' + committer
print 'Commit message: "' + commitMessage + '"'
# invoke JIRA web service
xmlrpcUrl = jiraBaseURL + '/rpc/xmlrpc'
try:
s = xmlrpclib.ServerProxy(xmlrpcUrl)
acceptance, comment = s.commitacc.acceptCommit(jiraLog... |
ce prerequisite.
"""
__author__ = "Xiaohui Qu"
__copyright__ = "Copyright 2011, The Materials Project"
__version__ = "1.0"
__maintainer__ = "Xiaohui Qu"
__email__ = "xhqu1981@gmail.com"
__status__ = "Experimental"
__date__ = "Jun 7, 2013"
import re
import math
import abc
import itertools
import copy
from pymatgen.se... | monty.dev import requires
from pymatgen.io.babel import BabelMolAdaptor
import six
from six.moves import zip
try:
import openbabel as ob
except ImportError:
ob = None
class AbstractMolAtomMapper(six.with_metaclass(abc.ABCMeta, PMGSONable)):
"""
Abstract molecular atom order mapping class. A mapping w... | @abc.abstractmethod
def uniform_labels(self, mol1, mol2):
"""
Pair the geometrically equivalent atoms of the molecules.
Args:
mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object.
mol2: Second molecule. OpenBabel OBMol or pymatgen Molecule object.
... |
o, Index):
expected_index = pd.Index(values, name=None)
o = klass(
np.repeat(values, range(1, len(o) + 1)), name='a')
else:
expected_index = pd.Index(values, name=None)
idx = np.repeat(o.index.values,... | ray([]))
self.assertEqual(s.nunique(), 0)
# GH 3002, datetime64[ns]
# don't test names though
txt = "\n".join(['xxyyzz20100101PIE', 'xxyyzz20100101GUM',
'xxyyzz20100101EGG', 'xxyyww20090101EGG',
'foofoo20080909PIE... | names=["person_id", "dt", "food"],
parse_dates=["dt"])
s = klass(df['dt'].copy())
s.name = None
idx = pd.to_datetime(
['2010-01-01 00:00:00Z', '2008-09-09 00:00:00Z',
'2009-01-01 00:00:00X'])... |
# -*- coding: utf-8 -*-
# Def | ine here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class TripadItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field() |
pass
|
ion_id_col 'version_id' does not "
"match inherited version_id_col 'version_id' and will not "
"automatically populate the inherited versioning column. "
"version_id_col should only be specified on "
"the base-most mapper that includes versioning.",
mapper,
... | table 'version_table' expected to "
r"update 1 row\(s\); 0 were matched.",
sess.commit
)
def test_conc | urrent_mod_err_noexpire_on_commit(self):
sess = self._fixture(expire_on_commit=False)
f1 = self.classes.Foo(value='f1')
sess.add(f1)
sess.commit()
# here, we're not expired overall, so no load occurs and we
# stay without a version id, unless we've emitted
# a S... |
fro | m sqlalchemy import Column, Integer, String, func, Boolean
from app import db
class CnesProfessional(db.Model):
__tablename__ = 'cnes_professional'
year = Column(Integer, primary_key=True)
region = Column(String(1), primary_key=True)
mesoregion = Column(String(4), primary_key=True)
| microregion = Column(String(5), primary_key=True)
state = Column(String(2), primary_key=True)
municipality = Column(String(7), primary_key=True)
establishment = Column(String(7), primary_key=True)
unit_type = Column(String(2), primary_key=True)
occupation_family = Column(String(4), primary_key=T... |
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import sys
from .server_tools import reset_database
class FunctionalTest(StaticLiveServerTestCase):
@classmethod
def setUpClass(cls):
for arg in sys.argv:... | if 'liveserver' in arg:
cls.server_host = arg.split('=')[1]
cls.server_url = 'http://' + cls.server_host
cls.against_staging = True
return
super().setUpClass()
cls.against_staging = False
cls.server_url = cls.live_server_url
@classmethod
def tearDownClass(cls):
if not cls.against_staging:
... | fox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def get_item_input_box(self):
return self.browser.find_element_by_id('id_text')
def check_for_row_in_list_table(self, row_text):
table = self.browser.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2014 Cloudwatt
# 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/l... | self.netns_mgr = NetnsManager('fake_vm_uuid', NIC1, NIC2)
self.netns_mgr.vrouter_client = mock.Mock()
self.netns_mgr._get_tap_name = mock.Mock()
self.netns_mgr._get_tap_name.return_value | = 'tap1234'
resp = requests.Response()
resp.status_code = status_code
self.mock_post.return_value = resp
self.netns_mgr._add_port_to_agent(NIC1)
def test_add_port_to_agent(self):
self._add_port_to_agent()
self.mock_post.assert_called_with(
'http://loc... |
8', 'KNUD_AGN', 'G1_TS', 'G2_TS',
# 'WEIGHT_TS', 'CHANDRA_GOOD', 'CHANDRA_AGN', 'CHANDRA_LX_HARD', 'CHANDRA_LX_SOFT',
# 'CHANDRA_LX_FULL', 'CHANDRA_ZETA', 'CHANDRA_ZSPEC', 'CHANDRA_CLASSZSPEC', 'CHANDRA_MODEL',
# 'CHANDRA_XMM_ID', 'XMM_GOOD', 'XMM_AGN', 'XMM_LX_HARD', 'XMM_LX_SOFT', 'XMM_LX_FULL', 'XMM_ZETA',
# 'XMM_ZS... | dent = cosmos_cat.field('ident')
cos_mag_auto = cosmos_cat.field('mag_auto')
cos_flux_rad = cosmos_cat.field('flux_radius')
cos_zphot = cosmos_cat.field('zphot')
# Read in catalogs with fit parameters from Lackner & Gunn.
print "Reading in catalogs of fit parameters"
n_fit_tot = 0
for i_cat in range(n_catfiles):
#... | tfiles[i_cat]
# Just extract the columns we want, and append to previous if i_cat!=0.
if i_cat == 0:
fit_ident = dat.field('ident')
fit_sersicfit = dat.field('sersicfit')
fit_bulgefit = dat.field('bulgefit')
fit_status = dat.field('mpfit_status')
fit_mag_auto = dat.field(... |
# -*- coding: utf-8 -*-
{%- if cookiecut | ter.pyapp_type == "asyncio" -%}
{%- set async = "async" -%}
{%- set appmod = "nicfit.aio" -%}
{%- else -%}
{%- set async = "" -%}
{%- set appmod = "nicfit" -%}
{%- endif %}
from {{ appmod }} import Application
from nicfit.console import pout
from . import version
{{ async | }} def main(args):
pout("\m/")
app = Application(main, version=version,
{%- if cookiecutter.gettext_domain != "None" %}
gettext_domain="{{ cookiecutter.gettext_domain }}")
{% else %}
gettext_domain=None)
{% endif %}
if __name__ == "__main__":
app.run()
|
#! /Users/rkrsn/anaconda/bin/python
from __future__ import print_function
from __future__ import division
from os import environ, getcwd
from pdb import set_trace
from random import uniform, randint, shuffle
import sys
# Update PYTHONPATH
HOME = environ['HOME']
axe = HOME + '/git/axe/axe/' # AXE
pystat = HOME + '/git... | rows=[k.cells for k in p],
discrete=True)
self.mod.append(choice(tmpTbl._rows))
# <<<<<<<<<<< Debug >>>>>>>>>>>>>>>
# set_trace()
return clone(self.test_DF, rows=[k.cells for k in self.mod], discrete=True)
def _planningTest():
# Test contrast sets
n ... |
verbose=True,
smoteit=False).main()
# <<<<<<<<<<< Debug >>>>>>>>>>>>>>>
set_trace()
if __name__ == '__main__':
_planningTest()
|
# Copyright (c) 2007 Roman Glass
# See LICENSE for details.
" | ""Play around with different SortingAlgorithms"""
from zope.interface import Interface, implements
from interfaces import IListManager
from baselist import *
from sortingalgorithms import *
from help import *
class ListM:
implements(IListManager)
def __init__(self):
self.n = NullList()
s... | self.n.accept(ParseV())
def sort(self):
self.n = self.n.accept(self.sort())
def changeSort(self, o):
self.sort = o
|
import caveGenerate
import yaml
filename = 'data/cavegen.map'
def addObjects():
o = list()
o.append('floor')
o.append('ground')
o.append('apple')
o.append('cherry')
o.append('enemy_poringp')
o.append('enemy_poringb')
return o
def writeMap(fn, m):
data = yaml.dump(m, default_flow_s... | ', 16)
floor = caveGenerate.init_matrix(50, caveGenerate.FLOOR)
map_str = caveGenerate.drawString(genmap)
map_floor = caveGenerate.drawString(floor)
m['layers_count'] = 2
m['layers'] = list()
m['layers'].append(map_floor)
m['layers'].append(map_str)
m['objects'] = addObjects()
retur... |
if __name__ == '__main__':
m = genMap()
print(m)
writeMap('../data/cavegen.yaml', m)
|
# Django settings for ssssss project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
import os
if 'SERVER_SOFTWARE' in os.environ:
from sae.const import (
MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB
)
else:
# Make `... | this to False, Django will make some optimizations so as not
# t | o load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the direc... |
class Board(object):
"""This class defines the board"""
def __init__(self, board_size):
"""The initializer for the class"""
self.board_size = board_size
self.board = []
for index in range(0, self.board_size):
self.board.append(['0'] * self.board_size)
def is_on... | self.board[(y_coordinate-1)].pop(x_coordinate)
def print_board(self):
"""Print the board"""
for row in self.board:
print(" ".join(row))
def is_piece_set(self, x_coordinate, y_coordinate):
"""Check to see if a piece is set """
if self.is_on_board(x_coordinate, y_co... | return bool(str(self.board[(y_coordinate-1)][(x_coordinate-1)]) != '0')
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.contrib.gis.db.models.fields
class Migration(migrations.Migration):
dependencies = [
('let_me_app', '0003_auto_20150713_2051'),
]
operations = [
| migrations.RemoveField(
model_name='site',
name='location',
),
migrations.RemoveField(
model_name='site',
| name='location_lat',
),
migrations.RemoveField(
model_name='site',
name='location_lon',
),
migrations.AddField(
model_name='site',
name='geo_point',
field=django.contrib.gis.db.models.fields.PointField(blank=True, null=True, sri... |
as a full-featured webcam.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/android_ip_webcam/
"""
import asyncio
import logging
from datetime import timedelta
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const imp... | 'mdi:came | ra',
'ffc': 'mdi:camera-front-variant',
'focus': 'mdi:image-filter-center-focus',
'gps_active': 'mdi:crosshairs-gps',
'light': 'mdi:flashlight',
'motion': 'mdi:run',
'night_vision': 'mdi:weather-night',
'overlay': 'mdi:monitor',
'pressure': 'mdi:gauge',
'proximity': 'mdi:map-marker-r... |
import metrics
def rate(artToCatSim, label, membershipData, categoryTree, artNamesDict, catNamesDict):
# countBefore1 = artToCatSim.count_nonzero()
# for article in membershipData:
# id_and_categories = article.split('\t')
# articleId = int(id_and_categories[0])
# del id_and_categories... | rmat(manualMetric))
childParentMetric = metrics.numberOfChildParentConnections(topConnections, categoryTree)
print("ChildParent: {}".format(childParentMetric))
exisitingConnsMetric = metrics.numberOfExistingConnections(artToCatSim, membershipData)
print("ExisitngConns: {}".format(exisitingConnsMe | tric))
variance = metrics.variance(artToCatSim)
print("Variance: {}".format(variance))
def getTopConnections(artToCatSim, number = None):
sorted = sort_coo(artToCatSim.tocoo())
if not number:
number = len(sorted)/10
top = sorted[-number:]
return top
def sort_coo(m):
from itertool... |
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | t.tests.lib import base
c | lass TestTestList(base.TestCase):
def test_testr_list_tests_no_errors(self):
# Remove unit test discover path from env to test tempest tests
test_env = os.environ.copy()
test_env.pop('OS_TEST_PATH')
import_failures = []
p = subprocess.Popen(['testr', 'list-tests'], stdout=su... |
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'fabs28_detached_award_financial_assistance_1'
def test_column_headers(database):
expected_subset = {'row_number', 'assistance_type', ... | antee',
'uniqueid_AssistanceTransactionUniqueKey'}
actual = set(query_columns(_FILE, database))
assert expected_subset == actual
def test_success(database):
""" FaceValueOfDirectLoanOrLoanGuarantee is required for loans (i.e., when AssistanceType = 07 or 08). """
det_award | = DetachedAwardFinancialAssistanceFactory(assistance_type='07', face_value_loan_guarantee=0,
correction_delete_indicatr='')
det_award_2 = DetachedAwardFinancialAssistanceFactory(assistance_type='08', face_value_loan_guarantee=20,
... |
# -*- coding: utf-8 -*-
# Copyright © 2013, 2014, 2017, 2020 Tom Most <twm@freecog.net>
#
# 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 License, or
# (at your option) a... | be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. I | f not, see <http://www.gnu.org/licenses/>.
#
# Additional permission under GNU GPL version 3 section 7
#
# If you modify this Program, or any covered work, by linking or
# combining it with OpenSSL (or a modified version of that library),
# containing parts covered by the terms of the OpenSSL License, the
# licensors o... |
# | Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class MyuniversityscraperPip | eline(object):
def process_item(self, item, spider):
return item
|
from django.urls import reverse
from course_discovery.apps.api.v1.tests.test_views.mixins import APITestCase, SerializationMixin
from course_discovery.apps.core.tests.factories import USER_PASSWORD, UserFactory
from course_discovery.apps.course_metadata.models import LevelType
fro | m course_discovery.apps.course_metadata.tests.factories import LevelTypeFactory
class LevelTypeViewSetTests(SerializationMixin, APITestCase):
list_path = reverse('api:v1:level_type-list')
def setUp(self):
supe | r().setUp()
self.user = UserFactory(is_staff=True, is_superuser=True)
self.client.login(username=self.user.username, password=USER_PASSWORD)
def test_authentication(self):
""" Verify the endpoint requires the user to be authenticated. """
response = self.client.get(self.list_path)
... |
#!/usr/b | in/env python3
# Sifer Aseph
"""Prints a "hello world" statement."""
def main():
"""Utterly standard."""
print("Hello cruel | world.")
if __name__ == "__main__":
main()
|
from django.conf.urls import patterns, include, url
| from darkoob.book import views as book_views
urlpatterns = patterns('',
url(r'^(?P<book_id>\d+)/(?P<book_title>[a-zA-Z0-9\-_]+)/$', book_views.page, name='book_p | age'),
url(r'^look/$', book_views.book_lookup),
url(r'^author/$', book_views.author_lookup),
# url(r'^rate/$', book_views.rate, name='rate'),
)
|
# -*- coding: utf-8 -*-
# $Id$
#
# Copyright (c) 2007 Otto-von-Guericke-Universität Magdeburg
#
# This file is part of ECReviewBox.
from StringIO import StringIO
from Products.Archetypes.Extensions.utils import installTypes, install_subskin
from Products.Archetypes.public import listTypes
from Products.CMFCore.utils... |
print >> out, "Successfully installed %s." % PRODUCT_NAME
return out.getvalue()
def uninstall(self, reinstall):
"""
Uninstall | s the product.
"""
out = StringIO()
print >> out, "Successfully uninstalled %s." % PRODUCT_NAME
return out.getvalue()
|
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public
# License as published by the Free Software Foundation; either version
# 2 of the License (GPLv2) or (at your option) any later version.
# There is NO WARRANTY for this software, express or impli... | dmin.options import NODE_ID_OPTION, MAX_BANDWIDTH_OPTION, MAX_CONCURRENCY_OPTION
# -- constants ----------------------------------------------------------------
DESC_LIST = _('list scheduled sync operations')
DESC_CREATE = _('adds a new scheduled sync operation')
DESC_DELETE = _('delete a sync schedu | le')
DESC_UPDATE = _('updates an existing schedule')
DESC_NEXT_RUN = _('displays the next scheduled sync run for a child node')
# A node sync is considered an update operation on the REST API
SYNC_OPERATION = 'update'
# -- commands -----------------------------------------------------------------
class NodeListSche... |
mport import_data_file as _import
from beamtools.import_data_file import objdict
from scipy.optimize import curve_fit
__all__ = ['spectrumFT', 'fit_ac', 'ac_x2t', 'sigma_fwhm']
class FitResult():
def __init__(self, ffunc, ftype, popt, pcov=0, indep_var='time'):
self.ffunc = ffunc
self.ftype = ft... | ters.
Takes x,y data and the desired background form (default to constant)
returns p, the polynomial coefficients. p is variable in length.
'''
if form is None | :
p = np.zeros((3))
if form.lower() in ['const','constant']:
p = min(y)
#p = np.hstack((p,[0,0]))
elif form.lower() in ['lin','linear']:
p = np.linalg.solve([[1,x[0]],[1,x[-1]]], [ |
( './.bzr/pending-merges',
''
),
( './.bzr/revision-history',
'mbp@sourcefrog.net-20051004104921-a98be2278dd30b7b\n'
'mbp@sourcefrog.net-20051004104937-c9b7a7bfcc0bb22d\n'
),
( './.bzr/stat-cache',
'### bzr hashcache v5\n'
'foo// f572d396fae9206628714fb2ce00f72e... | 8e\xd5\xcay\xe4l\xf7\xf | e\xf7u\r'
'\x1b\x95j\xb6\xfb\xc4\x11\x85\xea\x84\xd0\x12O\x03t\x83D\xad\xc4\x0f\xf0\x95"M\xbc\x95\x00\xc0\xe7f|6\x8aYi^B.u<\xef\xb1\x19\xcf\xbb\xce\xdc|\x038=\xc7\xe6R\x01\x00\x00'
),
( './.bzr/revision-store/mbp@sourcefrog.net-20051004104937-c9b7a7bfcc0bb22d.gz',
'\x1f\x8b\x08\x08A^BC\x00\x03mb... |
# -*- coding: utf-8 -*-
# Copyright 2016-2017 Versada <https://versada.eu/>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import logging
from odoo.service import wsgi_server
from odoo.tools import config as odoo_config
from . import const
from .logutils import LoggerNameFilter, OdooSentryHandler
_... | it(odoo_dir):
'''Attempts to get Odoo git commit from :param:`odoo_dir`.'''
if not odoo_d | ir:
return
try:
return raven.fetch_git_sha(odoo_dir)
except raven.exceptions.InvalidGitRepository:
_logger.debug(
u'Odoo directory: "%s" not a valid git repository', odoo_dir)
def initialize_raven(config, client_cls=None):
'''
Setup an instance of :class:`raven.Clie... |
""" environ settings """
import environ
BASE_D | IR = environ.P | ath(__file__) - 4
ENV_VAR = environ.Env()
|
from __future__ import unicode_literals, division, absolute_import
from builtins import * # pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
from flexget.plugin import PluginError
log = logging.getLogger('list_clear')
class ListClear(object... | 'phase': {'type': 'string', 'enum': plugin.task_phases, 'default': 'start'}
},
'required': ['what']
}
def __getattr__(self, phase):
# enable plugin in regular task phases
if phase.replace('on_task_', '') in plugin.task_phases:
re | turn self.clear
@plugin.priority(255)
def clear(self, task, config):
for item in config['what']:
for plugin_name, plugin_config in item.items():
try:
thelist = plugin.get_plugin_by_name(plugin_name).instance.get_list(plugin_config)
except ... |
from sympy import Sieve, sieve, Symbol, S, limit, I, zoo, nan, Rational
from sympy.core.compatibility import range
from sympy.ntheory import isprime, totient, mobius, randprime, nextprime, prevprime, \
primerange, primepi, prime, primorial, composite, compositepi, reduced_totient
from sympy.ntheory.generate import... | rime(1, 3) == 2
assert randprime(3, 5) == 3
| raises(ValueError, lambda: randprime(20, 22))
for a in [100, 300, 500, 250000]:
for b in [100, 300, 500, 250000]:
p = randprime(a, a + b)
assert a <= p < (a + b) and isprime(p)
def test_primorial():
assert primorial(1) == 2
assert primorial(1, nth=0) == 1
assert prim... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Ricardo Ribeiro"
__credits__ = ["Ricardo Ribeiro"]
__license__ = "MIT"
__version__ = | "1.0"
__maintainer__ = "Ricardo Ribeiro"
__email__ = "ricardojvr@gmail.com"
_ | _status__ = "Production"
|
from .views import (
SensorTypeViewSet, SensorViewSet, SensingPointViewSet, DataPointViewSet
)
def contribute_to_router(router):
router.register(r'sens | orType', SensorTypeViewSet)
router.register(r'sensor', SensorViewSet)
router.register(r'sensingPoint', | SensingPointViewSet)
router.register(r'dataPoint', DataPointViewSet)
|
rpms,
))
path, rpm_name = found_pkg.rsplit("/", 1)
result['rpm_name'] = rpm_name
result['base_url'] = "{koji_task_url}/{path}/".format(
koji_task_url=config.koji_task_url,
path=path,
)
# removes the package name from the beginning of rpm_name
version = rpm_name.split("{0... | r the
requested package in koji.
"""
pkg_name = "{name}-{ver}-{rel}.{arch}.rpm".format(
name=package,
ver=build_info["version"] | ,
rel=build_info["release"],
arch=arch,
)
return pkg_name
def get_package_version(remote, package):
installed_ver = None
if remote.os.package_type == "deb":
proc = remote.run(
args=[
'dpkg-query', '-W', '-f', '${Version}', package
],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.