code stringlengths 1 199k |
|---|
from math import sqrt
import numpy as np
''' *********************** USER-PARAMETERS *********************** '''
''' INITIAL STATE PARAMETERS '''
MAX_TEST_DURATION = 3000;
dt = 1e-3;
model_path = ["/home/adelpret/devel/sot_hydro/install/share"];
urdfFileName ... |
from pycp2k.inputsection import InputSection
from ._each119 import _each119
class _fock_gap1(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
sel... |
from distutils.core import setup
setup(name='pantheradesktop',
description = "Panthera Desktop Framework",
long_description = "Tiny desktop framework for easy application development in Python using PyQT/PySide",
author = "Damian Kęska",
author_email = "webnull.www@gmail.com",
version="0.1... |
from django.shortcuts import render, reverse, redirect
from django.http import HttpResponseRedirect, HttpResponse
from .models import bp_pages, bp_products, bp_users, ContactModel
from .forms import ContactForm, ShoppingForm, Login, Registreren
from cart.cart import Cart
def get_index(request):
text = bp_pages.obje... |
from psi4 import core
from psi4.driver import constants
def print_sapt_var(name, value, short=False, start_spacer=" "):
"""
Converts the incoming value as hartree to a correctly formatted Psi print format.
"""
vals = (name, value * 1000, value * constants.hartree2kcalmol, value * constants.hartree2kJ... |
__author__ = "Mikael Mortensen <mikaem@math.uio.no> and Nathanael Schilling <nathanael.schilling@in.tum.de>"
__date__ = "2015-04-07"
__copyright__ = "Copyright (C) 2015-2018 " + __author__
__license__ = "GNU Lesser GPL version 3 or any later version"
import numpy as np
from mpi4py import MPI
from ..optimization import ... |
from Tribler.community.market.wallet import ASSET_MAP
class Price(object):
"""Price is used for having a consistent comparable and usable class that deals with floats."""
def __init__(self, price, wallet_id):
"""
:param price: Integer representation of a price that is positive or zero
:p... |
"""Provide a class for simulation and result handling of FMU.
FMUFunction is Function factory similar to OpenTURNS'
PythonFunction.
It relies on the lower level OpenTURNSFMUFunction, which is similar to
OpenTURNS' OpenTURNSPythonFunction.
"""
import pyfmi
import numpy as np
import os
import openturns as ot
from . impor... |
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
res = []
remain = 0
while l1 != None or l2 != None:
value = (0 if l1 == None else l1.val) + (0 if l2 == None else l2.va... |
import praw
import time
from random import random
def makeResponseArray(replies, weights):
responseArray = []
i = 0
while i < len(replies):
responseArray.append([replies[i], weights[i]])
i += 1
return responseArray
def calcWeightSum(responseArray):
i = 0
weightSum = 0
while i... |
from django.conf.urls import url
from rango import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about/', views.about, name='about'),
url(r'^add_category/$', views.add_category, name='add_category'),
url(r'^category/(?P<category_name_url>\w+)/$', views.category, name='category'),
... |
"""
Script to analyze the "dark" images from the experiments in the EssentialLab
"""
import glob
import os
import numpy
import matplotlib.pylab as plt
import matplotlib.patches as patches
def processimage(inputimage, clip=3):
"""
Clip image brightness to "mean +- 3 STD" (by default). Another value can
be gi... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='ContactFormCategory',
fields=[
('id', models.AutoField(verbose_name='ID', se... |
import logging
from ibmsecurity.utilities import tools
logger = logging.getLogger(__name__)
requires_model = "Appliance"
uri = "/wga/reverseproxy"
def get_all(isamAppliance, instance_id, check_mode=False, force=False):
"""
Retrieving all statistics components and details - Reverse Proxy
"""
try:
... |
__author__ = 'alan'
class Solution(object):
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
r = [1]
p1 = p2 = p3 = 0
while len(r) < n:
t1, t2, t3 = r[p1] * 2, r[p2] * 3, r[p3] * 5
t = min(t1, t2, t3)
r.append(t)... |
from model.group import Group
class GroupHelper:
def __init__(self, app):
self.app = app
group_cache = None
def create(self, group):
wd = self.app.wd
self.open_group_page()
wd.find_element_by_name("new").click()
self.set_fields(group)
wd.find_element_by_name("... |
from tempest.api.identity import base
from tempest import auth
from tempest import clients
from tempest.common.utils import data_utils
from tempest import config
from tempest import test
CONF = config.CONF
class TestDefaultProjectId (base.BaseIdentityV3AdminTest):
@classmethod
def setup_credentials(cls):
... |
import unittest
from mock import Mock
from airflow.jobs import BackfillJob
from airflow.models import DagRun
from airflow.ti_deps.deps.dagrun_id_dep import DagrunIdDep
class TestDagrunRunningDep(unittest.TestCase):
def test_dagrun_id_is_backfill(self):
"""
Task instances whose dagrun ID is a backfil... |
from simplebus import SimpleBus
def create_simplebus():
bus = SimpleBus('unittests')
bus.config.from_object(SimpleBusConfig())
return bus
class SimpleBusConfig(object):
pass |
import logging
import os
import sys
import time
import boto
import boto.ec2
import yaml
from boto.ec2.blockdevicemapping import BlockDeviceMapping
from boto.ec2.blockdevicemapping import BlockDeviceType
from fabric.api import sudo, run, env
from fabric.decorators import task
import helper
__author__ = "Kyle Bush"
__cop... |
"""Tests for app functions."""
import os
import unittest
from clusterfuzz._internal.platforms.android import settings
from clusterfuzz._internal.tests.test_libs import helpers as test_helpers
DATA_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'settings_data')
def _read_data_file(filename):
retu... |
"""Chicago taxi example using TFX on Beam."""
import os
from absl import logging
from tfx.components.example_gen.csv_example_gen.component import CsvExampleGen
from tfx.components.schema_gen.component import SchemaGen
from tfx.components.statistics_gen.component import StatisticsGen
from tfx.orchestration import metada... |
"""
Exception definitions.
"""
class UnsupportedVersion(Exception):
"""Indicates that the user is trying to use an unsupported
version of the API.
"""
pass
class CommandError(Exception):
pass
class AuthorizationFailure(Exception):
pass
class NoUniqueMatch(Exception):
pass
class AuthSystemNot... |
"""Tests for open_spiel.python.algorithms.jpsro."""
import itertools
from absl.testing import absltest
from absl.testing import parameterized
from open_spiel.python.algorithms import jpsro
import pyspiel
GAMES = (
"sheriff_2p_gabriele",
)
SWEEP_KWARGS = [
dict( # pylint: disable=g-complex-comprehension
... |
''' config.py '''
import string
from heron.statemgrs.src.python.config import Config as StateMgrConfig
STATEMGRS_KEY = "statemgrs"
EXTRA_LINKS_KEY = "extra.links"
EXTRA_LINK_NAME_KEY = "name"
EXTRA_LINK_FORMATTER_KEY = "formatter"
EXTRA_LINK_URL_KEY = "url"
class Config:
"""
Responsible for reading the yaml config ... |
"""Library for heterogeneous SBMs with node features."""
from typing import List, Tuple
import numpy as np
def GetClusterTypeComponents(
num_clusters_list):
"""Given a list of # clusters per-type, compute cross-type cluster components.
This function expands num_clusters_lists into a list of cluster index lists ... |
import pytest
import sdk_install as install
import sdk_tasks as tasks
import sdk_marathon as marathon
import sdk_utils as utils
from tests.test_utils import (
PACKAGE_NAME,
SERVICE_NAME,
DEFAULT_BROKER_COUNT,
DYNAMIC_PORT_OPTIONS_DICT,
STATIC_PORT_OPTIONS_DICT,
DEFAULT_POD_TYPE,
service_cli
... |
import os
from oslo_log import log as logging
from taskflow.listeners import base
from taskflow.listeners import logging as logging_listener
from taskflow import task
from <project_name> import exception
LOG = logging.getLogger(__name__)
def _make_task_name(cls, addons=None):
"""Makes a pretty name for a task class... |
"""
@author: Raven
@contact: aducode@126.com
@site: https://github.com/aducode
@file: invoker.py
@time: 2016/2/1 23:05
"""
from socket import socket, AF_INET, SOCK_STREAM
from gaea.core.protocol.protocol import MsgType, Platform
from gaea.core.protocol.protocol import Protocol, RequestProtocol, KeyValuePair, Out
from g... |
advanced_builder = AdvancedDataViewBuilder()
advanced_builder.dataset_ids(dataset_ids)
for descriptor in descriptors:
advanced_builder.add_raw_descriptor(descriptor)
advanced_builder.add_relation(['formula'], 'Property Band gap')
advanced_builder.add_relation(['formula'], 'Property Color')
advanced_builder.add_rela... |
from django.db import models
from django.utils.translation import gettext_lazy as _
from filer.fields.file import FilerFileField
from fluent_contents.models.db import ContentItem
class FilerFileItem(ContentItem):
file = FilerFileField(verbose_name=_("file"), on_delete=models.CASCADE)
name = models.CharField(_("... |
"""Training-related part of the Keras engine.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import weakref
import numpy as np
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.ops import iterator_ops
from ... |
import logging
logger = logging.getLogger(__name__)
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse, Http404, HttpResponseServerError, HttpResponseBadRequest
from fir_irma import api
from fir_irma.models import IrmaScan
from fir_irma.settings import settings
ERROR_NOT_FOUND = 1
... |
from unittest.mock import patch, Mock
from django.conf import settings
from django.contrib.auth.models import Permission
from django.test import TestCase
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from bulk_sms.models import Broadcast, Batch
from bulk_sms.tests.factories imp... |
from rest_framework import serializers
from grades.models import *
class GradeSerializer(serializers.ModelSerializer):
class Meta:
model = Grade
fields = ('semester_code', 'average_grade', 'passed', 'a', 'b', 'c', 'd', 'e', 'f')
class CourseSerializer(serializers.ModelSerializer):
class Meta:
... |
import os
import sys
import MySQLdb
from util.config import get_conf
reload(sys)
sys.setdefaultencoding("utf-8")
class DBBase:
db = None
cursor = None
def __init__(self, dbconfig):
self._conf = get_conf(dbconfig)
def _connect(self, key, ttype):
_host = self._conf.get(key, "host")
... |
import re
from core.alive import alive
from core.twitterc import TwitterC
state = {'CHIS': 'Chiapas', 'NL': 'Nuevo Leon', 'VER': 'Veracruz',
'JAL': 'Jalisco', 'OAX': 'Oaxaca', 'GRO': 'Guerrero',
'BC': 'Baja California', 'SON': 'Sonora', 'RT': 'Retweet'}
class Seismology(object):
def __init__(self, voicesynthetize... |
import string
import random
from enum import Enum
import redis
import config
from config import SESSION_SALT, MYSQL, MYSQL_NAME
from flask import Flask, current_app, render_template,session
from flask_login import LoginManager
from flask_session import Session
from flask_session.sessions import RedisSessionInterface
fr... |
from pymongo import MongoClient
import datetime as dt
class MongoDbUtil:
@classmethod
def getDB(cls, user, password, host, port, dbname):
uri = "mongodb://{}:{}@{}:{}/{}?authMechanism=SCRAM-SHA-1".format(user, password, host, port, dbname)
client = MongoClient(uri)
db = client.get_defaul... |
__author__ = 'maru'
__copyright__ = "Copyright 2013, ML Lab"
__version__ = "0.1"
__status__ = "Development"
import sys
import os
sys.path.append(os.path.abspath("."))
from experiment_utils import *
import argparse
import numpy as np
from sklearn.datasets.base import Bunch
from datautil.load_data import *
from sklearn i... |
"""Tests for user-related one-off computations."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
import ast
import datetime
import re
from core.domain import collection_domain
from core.domain import collectio... |
"""Code for more fancy file handles.
Classes:
- UndoHandle File object decorator with support for undo-like operations.
Additional private classes used in Bio.SeqIO and Bio.SearchIO for indexing
files are also defined under Bio.File but these are not intended for direct
use.
"""
from __future__ import print_fun... |
import glob
import os
import re
import time
import azurelinuxagent.common.logger as logger
import azurelinuxagent.common.utils.shellutil as shellutil
from azurelinuxagent.common.rdma import RDMAHandler
class CentOSRDMAHandler(RDMAHandler):
rdma_user_mode_package_name = 'microsoft-hyper-v-rdma'
rdma_kernel_mode_... |
from csrv.model import actions
from csrv.model import events
from csrv.model import timing_phases
from csrv.model.actions.subroutines import trace
from csrv.model.cards import card_info
from csrv.model.cards import ice
class TraceForPowerCounter(trace.Trace):
DESCRIPTION = 'Trace 3 - if successful, place 1 power coun... |
"""
This module implements the Lowess function for nonparametric regression.
Functions:
lowess Fit a smooth nonparametric regression curve to a scatterplot.
For more information, see
William S. Cleveland: "Robust locally weighted regression and smoothing
scatterplots", Journal of the American Statistical Associa... |
"""Storage Execution Classes."""
class StorageExecution:
def __init__(self):
"""Initalize and run."""
import sys
import os
import json
# print "os.getcwd(): %s" % os.getcwd()
self.storage_cmd = self.get_args()
sys.path.append(self.storage_cmd.HOME_FOLDER)
... |
"""Tests for the flow."""
import time
from grr.lib import server_plugins
from grr.client import actions
from grr.client import vfs
from grr.lib import access_control
from grr.lib import action_mocks
from grr.lib import aff4
from grr.lib import data_store
from grr.lib import flags
from grr.lib import flow
from grr.lib i... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import ConfigParser
import importlib
import inspect
import logging
import os
import sys
from logging.config import fileConfig
from kafka_utils.kafka_cluster_manager.cluster_info.cluster_b... |
import os
import uuid
try:
from ipalib import api
from ipalib import errors
from ipapython.ipautil import kinit_keytab
ipalib_imported = True
except ImportError:
# ipalib/ipapython are not available in PyPy yet, don't make it
# a showstopper for the tests.
ipalib_imported = False
from oslo_c... |
"""Tests for the Windows Shortcut (LNK) parser."""
import unittest
from plaso.lib import definitions
from plaso.parsers import winlnk
from tests.parsers import test_lib
class WinLnkParserTest(test_lib.ParserTestCase):
"""Tests for the Windows Shortcut (LNK) parser."""
def testParse(self):
"""Tests the Parse fun... |
from webservice.NexusHandler import NexusHandler as BaseHandler
from webservice.webmodel import StatsComputeOptions
from webservice.NexusHandler import nexus_handler
from webservice.NexusHandler import DEFAULT_PARAMETERS_SPEC
from webservice.webmodel import NexusResults, NexusProcessingException
import BaseDomsHandler
... |
__author__ = 'Ahmed G. Ali'
import settings
db = settings.BIOSTUDIES_DB |
"""Tests for TracingReducer."""
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp
from tensorflow_probability.python.experimental.mcmc.internal import test_fixtures
from tensorflow_probability.python.internal import tensorshape_util
from tensorflow_probability.python.internal import test_util
@test... |
import sys
from src.base.solution import Solution
from src.tests.part1.q076_test_min_win_substr import MinWinSubStrTestCases
class MinWinSubStr(Solution):
def verify_output(self, test_output, output):
return test_output == output
def print_output(self, output):
print(output)
def run_test(sel... |
import copy
import json
from nova.openstack.common import log as logging
from oslo.config import cfg
from powervc_nova import _
from powervc_nova.network.powerkvm import agent
from powervc_nova.network.powerkvm.agent import micro_op_builder as mob,\
commandlet
from powervc_nova.network.powerkvm.agent import service... |
from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.utils import timezone
from django.http import HttpResponse, HttpRequest
from zilencer.models import Deployment, RemotePushDeviceToken, RemoteZulipServer
from zerver.decorator import has_request_variables, REQ
from zerv... |
import os.path
import tornado.auth
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
import pymongo
define("port", default=8000, help="run on the given port", type=int)
class Application(tornado.web.Application):
... |
__all__ = [
"LibcloudError",
"MalformedResponseError",
"InvalidCredsError",
"InvalidCredsException",
"LazyList"
]
class LibcloudError(Exception):
"""The base class for other libcloud exceptions"""
def __init__(self, value, driver=None):
self.value = value
self.driver = dr... |
import random
import uuid
from openstack import exceptions
from openstack.tests.functional.baremetal import base
class TestBareMetalNode(base.BaseBaremetalTest):
def test_node_create_get_delete(self):
node = self.create_node(name='node-name')
self.assertEqual(node.name, 'node-name')
self.ass... |
from bgp.models import Relationship
from utils.filters import (
BaseFilterSet,
CreatedUpdatedFilterSet,
NameSlugSearchFilterSet,
)
class RelationshipFilterSet(
BaseFilterSet, CreatedUpdatedFilterSet, NameSlugSearchFilterSet
):
class Meta:
model = Relationship
fields = ["id", "name", ... |
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from .test_configuration_common import ConfigTester
from .test_generation_utils import GenerationTesterMixin
from .test_modeling_common import ModelTesterMixin, ids_tensor
if is_torch_ava... |
"""An observer that returns env's info.
"""
from typing import Dict
from acme.utils.observers import base
import dm_env
import numpy as np
class EnvInfoObserver(base.EnvLoopObserver):
"""An observer that collects and accumulates scalars from env's info."""
def __init__(self):
self._metrics = None
def _accumul... |
import unittest
import requests_mock
from airflow.models import Connection
from airflow.contrib.hooks.openfaas_hook import OpenFaasHook
from airflow.hooks.base_hook import BaseHook
from airflow import AirflowException
from tests.compat import mock
FUNCTION_NAME = "function_name"
class TestOpenFaasHook(unittest.TestCase... |
from __future__ import unicode_literals
import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
import uuid
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(setting... |
"""Implements RigL."""
import gin
from rigl.rigl_tf2 import utils
import tensorflow as tf
def get_all_layers(model, filter_fn=lambda _: True):
"""Gets all layers of a model and layers of a layer if it is a keras.Model."""
all_layers = []
for l in model.layers:
if hasattr(l, 'layers'):
all_layers.extend(... |
from __future__ import absolute_import, division, print_function, with_statement
from funnel.queue import AsyncManager, SyncManager, Message
from time import time
from tornado.testing import AsyncTestCase
from tornado.ioloop import IOLoop
from funnel.testing import HOST
from unittest import TestCase
class TestAsyncMana... |
from __future__ import print_function
from collections import defaultdict, Counter, namedtuple, OrderedDict
import os
import os.path as op
import yaml
import fontforge
from fontaine.cmap import Library
from fontaine.font import FontFactory
from bakery_cli.scripts.vmet import get_metric_view
from bakery_cli.utils import... |
import os
import logging
from threading import Lock
from flask import Flask, Response, jsonify, request, make_response, json, url_for, render_template
from flask_api import status # HTTP Status Codes
from flasgger import Swagger
from redis import Redis
from redis.exceptions import ConnectionError
from promotion impo... |
"""A Billing Account Resource."""
import json
from google.cloud.forseti.common.gcp_type import resource
class BillingAccountLifecycleState(resource.LifecycleState):
"""Represents the Billing Account's LifecycleState."""
pass
class BillingAccount(resource.Resource):
"""BillingAccount Resource."""
RESOURC... |
from muntjac.data.item import \
IItem, IPropertySetChangeEvent, IPropertySetChangeNotifier, \
IPropertySetChangeListener
from muntjac.util import EventObject
class PropertysetItem(IItem, IPropertySetChangeNotifier): # Cloneable
"""Class for handling a set of identified Properties. The elements
containe... |
from fabric.api import *
@task
def js():
"""
update jumpscale
"""
run("jscode update -a jumpscale -r jp_jumpscale,jp_serverapps,jumpscale_core") |
import click
from parsec.cli import pass_context, json_loads
from parsec.decorators import custom_exception, json_output
@click.command('update_dataset_collection')
@click.argument("history_id", type=str)
@click.argument("dataset_collection_id", type=str)
@click.option(
"--deleted",
help="Mark or unmark history... |
import collections
from heat.engine import clients
from heat.common import exception
from heat.common import template_format
from heat.engine import parser
from heat.engine import resource
from heat.engine import scheduler
from heat.tests.common import HeatTestCase
from heat.tests.fakes import FakeKeystoneClient
from h... |
import collections
from oneview_redfish_toolkit.api.errors import \
OneViewRedfishException
from oneview_redfish_toolkit.api.errors import \
OneViewRedfishResourceNotFoundException
from oneview_redfish_toolkit.api.redfish_json_validator import \
RedfishJsonValidator
from oneview_redfish_toolkit import confi... |
from abc import ABCMeta, abstractmethod, abstractproperty
import json
import uuid
class ToJSON:
__metaclass__ = ABCMeta
@abstractmethod
def to_json_repr(self):
raise NotImplementedError
def to_json(self):
"Return a json representation of the object"
return json.dumps(self.to_json... |
from __future__ import print_function
import ctypes
from MTS.Packet import Packet
from MTS.word.HeaderWord import HeaderWord
c_uint8 = ctypes.c_uint8
class Header(ctypes.Union):
_fields_ = [
('word', ctypes.c_uint16),
('b', HeaderWord)
]
_anonymous_ = 'b'
def __init__(self, *args, **kwar... |
import os
import warnings
import numpy as np
from pyrates.utility.genetic_algorithm import CGSGeneticAlgorithm
from pandas import DataFrame, read_hdf
from copy import deepcopy
class CustomGOA(CGSGeneticAlgorithm):
def eval_fitness(self, target: list, **kwargs):
# define simulation conditions
worker_... |
from google.cloud import aiplatform_v1
def sample_create_specialist_pool():
# Create a client
client = aiplatform_v1.SpecialistPoolServiceClient()
# Initialize request argument(s)
specialist_pool = aiplatform_v1.SpecialistPool()
specialist_pool.name = "name_value"
specialist_pool.display_name = ... |
from flask import Flask,request
from pymongo import MongoClient
import time,os
app = Flask(__name__)
client = MongoClient(os.getenv('MONGOHQ_URL'))
db = client.DummyData
cn = db.keyLogs
@app.route('/',methods=['GET'])
def boo():
return "This server logs every value POST'd to it on url /log"
@app.route('/log',methods=[... |
"""WSGI Routers for the Assignment service."""
import functools
from keystone.assignment import controllers
from keystone.common import json_home
from keystone.common import router
from keystone.common import wsgi
build_os_inherit_relation = functools.partial(
json_home.build_v3_extension_resource_relation,
ext... |
"""Long or boring tests for vobjects."""
import vobject
from vobject import base, icalendar, behavior, vcard, hcalendar
import StringIO, re, dateutil.tz, datetime
import doctest, test_vobject, unittest
from pkg_resources import resource_stream
base.logger.setLevel(base.logging.FATAL)
def additional_tests():
flags =... |
"""Shared utils among the dataset implementation."""
import collections
import contextlib
import dataclasses
import enum
import itertools
import re
from typing import Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Type, TypeVar, Union
from unittest import mock
import chex
import jax3d.projects.nesf as j3d
f... |
import zstackwoodpecker.test_state as ts_header
import os
TestAction = ts_header.TestAction
def path():
return dict(initial_formation="template5", checking_point=1, faild_point=100000, path_list=[
[TestAction.create_mini_vm, 'vm1', 'cluster=cluster2'],
[TestAction.reboot_vm, 'vm1'],
[TestAction.create_vm_back... |
"""Models for activity references."""
import core.storage.base_model.gae_models as base_models
import feconf
from google.appengine.ext import ndb
class ActivityReferencesModel(base_models.BaseModel):
"""Storage model for a list of activity references.
The id of each model instance is the name of the list. This ... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
"""EmPOWER Feed Class."""
from datetime import datetime, timedelta
from tornado.httpclient import HTTPClient
from empower.persistence import Session
from empower.persistence.persistence import TblFeed
FEED_STATUS_ON = "on"
FEED_STATUS_OFF = "off"
class Feed(object):
"""Power consumption feed originating from an Ene... |
__author__ = 'Ulric Qin'
from frame.store import db
class Bean(object):
_tbl = ''
_id = 'id'
_cols = ''
@classmethod
def insert(cls, data=None):
if not data:
raise ValueError('argument data is invalid')
size = len(data)
keys = data.keys()
safe_keys = ['`%s... |
print "|--------------------------------------------|"
print "| Starting Perlin Noise Demo |"
print "|--------------------------------------------|"
scene.addAssetPath('mesh', 'mesh')
scene.addAssetPath('motion', 'ChrMaarten')
scene.addAssetPath('script', 'scripts')
scene.addAssetPath('script', 'behavio... |
from tempest.api.compute import base
from tempest import exceptions
from tempest.test import attr
class InstanceActionsV3TestJSON(base.BaseV3ComputeTest):
_interface = 'json'
@classmethod
def setUpClass(cls):
super(InstanceActionsV3TestJSON, cls).setUpClass()
cls.client = cls.servers_client
... |
"""
Copyright 2015 Parsely, 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 writing, software
dis... |
"""Tests for ceilometer/central/manager.py"""
from unittest import mock
from oslotest import base
from ceilometer.hardware import discovery as hardware
from ceilometer.polling.discovery import endpoint
from ceilometer.polling.discovery import localnode
from ceilometer.polling.discovery import tenant as project
from cei... |
from furl import furl
from lxml import etree
from share.harvest import BaseHarvester
class DataOneHarvester(BaseHarvester):
VERSION = 1
def do_harvest(self, start_date, end_date):
end_date = end_date.format('YYYY-MM-DDT00:00:00', formatter='alternative') + 'Z'
start_date = start_date.format('YYY... |
"""
MulticastQuerier - command ``find /sys/devices/virtual/net/ -name multicast_querier -print -exec cat {} \;``
============================================================================================================
This module provides processing for the output of the
``find -name multicast_querier ...`` command... |
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes.clie... |
"""Power operations"""
from .power_common import CommonPowerCommand
from .power_off import PowerOffCommand
from .power_on import PowerOnCommand
from .power_cycle import PowerCycleCommand |
from model.contact import Contact
import random
def test_delete_contact_by_id(app, db, check_ui):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(firstname="igor"))
old_contacts = db.get_contact_list()
contact = random.choice(old_contacts)
app.contact.delete_contact_by_id(contact.... |
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words."""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off."""
print words
word = words.pop(0)
print word
def print_la... |
"""
simple_service.py
Combine results from GA4GH and ExAC API to build
a simple web service.
"""
import flask
app = flask.Flask(__name__)
import ga4gh.client as client
import requests
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/echo/<echostring>')
def echo_route(echostring):
... |
import os
import sys
import copy
import random
import shutil
import numpy as np
SRC_ROOT = "/media/yeephycho/My Passport/Normal_patch"
DST_ROOT = "/media/yeephycho/New Volume/NORMAL_600"
def main(arguments):
filenames = os.listdir(SRC_ROOT)
shuffle_list = copy.deepcopy(filenames)
random.shuffle(shuffle_list... |
from collections import OrderedDict
import functools
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core.client_options import ClientOptions
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.