code
stringlengths
1
199k
from ajenti.ui import * from ajenti.ui.binder import Binder from api import * @plugin class LinuxBasicNetworkConfigSet (NetworkConfigBit): cls = 'linux-basic' title = 'Basic' def init(self): self.append(self.ui.inflate('network:bit-linux-basic')) self.binder = Binder(None, self) def refr...
import base64 import json import logging import time import threading import requests class OpenHabRestInterface(threading.Thread): prev_state = {} # stores item states update = False def __init__(self, host, port, user, pwd, group, queue): self.host = host self.port = port self.use...
from gwt.ui.ListBox import ( DOM, Event, Factory, FocusWidget, ListBox, )
""" Some standard utiltilies for defining functions. These are developer functions that are not covered by API guarantees. """ import pandas as pd from ..column import DataFrame, Column, build_col_broadcast, build_col_fun, build_col_literal from ..proto import types_pb2 from ..proto import structured_transform_pb2 as s...
import mock from neutron_lib import constants from oslo_config import cfg from oslo_utils import uuidutils from neutron.common import constants as n_const from neutron.objects.logapi import logging_resource as log_object from neutron.plugins.ml2.drivers.openvswitch.agent.common import constants \ as ovs_consts from...
import doctest from insights.parsers import cloud_init_log from insights.tests import context_wrap CLOUD_INIT_LOG = """ 2019-08-07 14:33:27,269 - util.py[DEBUG]: Reading from /etc/cloud/cloud.cfg.d/99-datasource.cfg (quiet=False) 2019-08-07 14:33:27,269 - util.py[DEBUG]: Read 59 bytes from /etc/cloud/cloud.cfg.d/99-dat...
import logging from marvin.cloudstackAPI import * from marvin.cloudstackTestCase import * from marvin.lib.base import * from marvin.lib.common import * from marvin.lib.utils import * from nose.plugins.attrib import attr class TestPublicIpAcl(cloudstackTestCase): attributes = { 'template_name': 'tiny linux k...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from caffe2.proto import caffe2_pb2 from caffe2.python import core, workspace, dyndep, test_util dyndep.InitOpsLibrary('@/caffe2/caffe2/contrib/warpctc:ctc_ops') workspace.GlobalInit(["python"...
"""Model Card Data Class. The Model Card (MC) is the document designed for transparent reporting of AI model provenance, usage, and ethics-informed evaluation. The model card can be presented by different formats (e.g. HTML, PDF, Markdown). The properties of the Model Card (MC) are defined by a json schema. The ModelCa...
"""Generate a channel token for GAE's channels API. This is called via an Ajax request. """ __author__ = \ 'jeffy@google.com (Jeff Posnick) and jjinux@google.com (JJ Behrens)' from google.appengine.api import channel from playlistpicker.handlers.basehandler import BaseHandler from playlistpicker.utils import channels...
NetworkOfferingId = '8d648af4-ceb9-4640-bded-7e2ce3a7a699' ZoneId = 'b9a0dc27-cea5-4602-9bdc-eef68412df46' VMServiceOfferingId = '12e34e93-e786-48f6-a66c-8b3f9aa3e0ff' TemplateId = '7f233e45-c9de-40d7-900e-496758ee3c50' DisplayText = 'Just a test.'
""" /*********************************** Copyright 2020 Ravishankar Mathur Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicab...
"""Tests for the profile page.""" from core.domain import exp_services from core.domain import rights_manager from core.domain import user_services from core.tests import test_utils import feconf import utils class SignupTest(test_utils.GenericTestBase): def test_signup_page_does_not_have_top_right_menu(self): ...
from __future__ import absolute_import, division, print_function, unicode_literals import json from pants.util.contextutil import temporary_file from pants_test.pants_run_integration_test import PantsRunIntegrationTest class TestOptionsQuietIntegration(PantsRunIntegrationTest): def test_pants_default_quietness(self):...
import os import mock import grpc from grpc.experimental import aio import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import future from google.api_core imp...
""" Simple flask-based API to access FreeLing functionalities. """ __author__ = "Víctor Peinado" __email__ = "vitojph@gmail.com" __date__ = "27/06/2013" import freeling from flask import Flask, Response, request from flask.ext.restful import Api, Resource import json PUNCTUATION = u""".,;:!? """ FREELINGDIR = "/usr/loc...
import logging import re from webkitpy.common.webkit_finder import WebKitFinder from webkitpy.layout_tests.port import chromium from webkitpy.layout_tests.port import win from webkitpy.layout_tests.port import config _log = logging.getLogger(__name__) class LinuxPort(chromium.ChromiumPort): port_name = 'linux' ...
"""Layer serialization/deserialization functions. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python import tf2 from tensorflow.python.keras.engine.base_layer import TensorFlowOpLayer from tensorflow.python.keras.engine.input_layer imp...
import errno import gym import logging import math import numpy as np import os import tree # pip install dm_tree from typing import Dict, List, Optional, Tuple, Union, TYPE_CHECKING import ray import ray.experimental.tf_utils from ray.util.debug import log_once from ray.rllib.policy.policy import Policy from ray.rlli...
from panda3d.core import * from panda3d.direct import * from toontown.toonbase import ToontownGlobals taskZoneId2pathId = {ToontownGlobals.SellbotFactoryInt: 'sellbotFactory', ToontownGlobals.CashbotMintIntA: 'cashbotMint', ToontownGlobals.CashbotMintIntB: 'cashbotMint', ToontownGlobals.CashbotMintIntC: 'cashbotMint...
from psycopg2 import IntegrityError from odoo.tests import TransactionCase from odoo.tools import mute_logger class GlobalTestOpenacademyCourse(TransactionCase): ''' Global test to openacademy course model ''' # Method seudo-constructor of test setUp def setUp(self): #Define global variables...
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...
""" This file contains information required by a problem for DCS I/O distribution. """ from typing import List, Dict from itertools import groupby from operator import itemgetter from io_distribution.dcs_objects import * from io_distribution.distance import * from io_distribution.solvers.base_solver import * class ...
"""This example runs a report from a saved query. """ import tempfile from googleads import ad_manager from googleads import errors SAVED_QUERY_ID = 'INSERT_SAVED_QUERY_ID_HERE' def main(client, saved_query_id): # Initialize appropriate service. report_service = client.GetService('ReportService', version='v202111')...
def save_array_as_PNG(img, fname, ftype_req = -1): """ Save an array as a PNG. img: a 3D NumPy array of type uint8 with shape (ny,nx,nc) fname: output file name ftype_req = filter type to be used The PNG specification defines 5 different possible filters which are numbered 0 to 4 (inclusivel...
__source__ = ' https://leetcode.com/problems/accounts-merge/' import unittest import collections class Solution(object): def accountsMerge(self, accounts): """ :type accounts: List[List[str]] :rtype: List[List[str]] """ em_to_name = {} graph = collections.defaultdict(...
from . import detection from argparse import ArgumentParser def size_tuple(size_str): w, h = size_str.split('x') return (int(w), int(h)) def main(): parser = ArgumentParser(description='Process some integers.') parser.add_argument('--fps', type=int, default=10) parser.add_argument('--size', type=size_tuple, defaul...
from __future__ import unicode_literals import sys from django.conf import settings from django.template.base import Library from django.utils import six from django.utils.encoding import smart_text from leonardo.module.web.widget import ApplicationWidget from leonardo.module.web.widget.application.reverse import app_r...
import json import uuid import sqlalchemy as sql from sqlalchemy import orm ENDPOINT_TYPES = ['public', 'internal', 'admin'] def upgrade(migrate_engine): """Split each legacy endpoint into separate records for each interface.""" meta = sql.MetaData() meta.bind = migrate_engine legacy_table = sql.Table('...
import os from django.test import TestCase from django.test.utils import override_settings from django.template import Template, Context from achilles import blocks @override_settings( TEMPLATE_DIRS=(os.path.join(os.path.dirname(__file__), 'templates/'),), TEMPLATE_LOADERS=('django.template.loaders.filesystem.L...
import os import multiprocessing import Queue import logging import sys import types import signal from ctypes import CDLL import cPickle as pickle import misc from crawler_exceptions import CrawlTimeoutError, CrawlError logger = logging.getLogger('crawlutils') try: libc = CDLL('libc.so.6') except Exception as e: ...
from lib.base import BaseVaporIOAction __all__ = [ 'ReadSensor' ] class ReadSensor(BaseVaporIOAction): def run(self, host, sensor_type, board_id, port_id, ssl=False): endpoint = "read/%s/%s/%s" % (sensor_type, board_id, port_id) data = self._get_request(host=host, endpoint=endpoint, ssl=ssl) ...
from dot import * def repr(s): return '"' + s + '"' Debug.turnon() BlockBegin("digraph G", bgcolor = repr('grey'), style = repr('filled'), ) update_node_class("base", shape = "plaintext", style = repr("rounded,filled"), fontname = repr("Monaco"), color = repr("white"), ) update_edge_...
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('indicators', '0080_disaggregated_value_migration'), ] operations = [ migrations.RemoveField( model_name='result', name='disaggregation_value', ), migrations.Dele...
"""Helper functions to add support for magnitude-based model pruning. # Adds variables and ops to the graph to enable # elementwise masking of weights apply_mask(weights) # Returns a list containing the sparsity of each of the weight tensors get_weight_sparsity() # Returns a list of all the masked weight te...
""" Tests For Cells Messaging module """ from nova.cells import messaging from nova import context from nova import exception from nova.openstack.common import cfg from nova import test from nova.tests.cells import fakes CONF = cfg.CONF CONF.import_opt('host', 'nova.config') CONF.import_opt('name', 'nova.cells.opts', g...
"""Init module for experimental.""" from tensorflow_model_analysis.experimental import preprocessing_functions
import unittest from approvaltests.core.reporter import Reporter from approvaltests.reporters.first_working_reporter import FirstWorkingReporter class ReporterForTesting(Reporter): def __init__(self, success, additional=None): if additional is None: additional = lambda : None self.additi...
import pynodegl as ngl from pynodegl_utils.misc import scene from pynodegl_utils.tests.cmp_fingerprint import test_fingerprint from pynodegl_utils.toolbox.colors import COLORS def _render_quad(cfg, corner=(-1, -1, 0), width=(2, 0, 0), height=(0, 2, 0), color=(1, 1, 1), opacity=1): quad = ngl.Quad(corner, width, hei...
import pytest from prometheus_client import CONTENT_TYPE_LATEST from tests.factories import UserFactory from tests.utils import get_view_for_user @pytest.mark.django_db def test_get_statistics(client): n_dutch = 3 for _ in range(n_dutch): u = UserFactory() u.user_profile.country = "NL" u...
import os, sys, types, time, copy import pygame import random PERMUTATION_THRESHOLD_INCREMENT = 40 WATCH_THE_LOGIC_MODE = False puzzle1 = [\ [-1,-1,[-1,23],[-1,21],-1,-1],\ [-1,[8,15],0,0,-1,-1],\ [[8,-1],0,0,0,-1,-1],\ [[27,-1],0,0,0,0,-1],\ [[5,-1],0,0,-1,-1,-1],\ [[14,-1],0,0,-1,-1,-1],\ [-1,-1,-1,-1,-1,-1]] puzzle2...
from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Famille.description' db.add_column(u'famille_famille', 'description', ...
import sys import array as pyarray from math import exp, log from collections import namedtuple from numpy import array, random, tile from pyspark import SparkContext, since from pyspark.rdd import RDD from pyspark.mllib.common import JavaModelWrapper, callMLlibFunc, callJavaFunc, _py2java, _java2py from pyspark.mllib....
"""This API defines FeatureColumn abstraction. FeatureColumns provide a high level abstraction for ingesting and representing features. FeatureColumns are also the primary way of encoding features for canned `tf.estimator.Estimator`s. When using FeatureColumns with `Estimators`, the type of feature column you should ch...
""" 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 ...
import android,time import random droid = android.Android() class Game: "Generic game class." def __init__(self,name): self.name=name def play(self): pass class GlobalThermonuclearWar(Game): "Implementation of global thermonuclear war." strategies = ["U.S. First Strike", "U.S.S.R. First Strike",...
'''Model utilities.''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import six import json import re from absl import flags from PIL import Image import collections import os import functools import numpy as np import tensorflow as tf import tensorflow.com...
import pytest pytest.importorskip("ethosu.vela") import tvm from tvm import relay from tvm.relay.backend.contrib.ethosu.tir.compiler import lower_to_tir def test_lower_to_tir(): data = relay.var("data", shape=(1, 1, 1, 1024), dtype="uint8") weight = relay.var("weight", shape=(1, 1, 1024, 1001), dtype="int8") ...
from requests import get from urllib import quote from sys import argv from multiprocessing import Pool import webbrowser import os import unicodedata from lockfile import FileLock import re glbl_port = None def dl_pg(ip, timeout=1): try: url = 'http://'+ip+':'+str(glbl_port) print "[*] Downloading html page from:...
from django.conf import settings from django.core.urlresolvers import reverse from django.test import TestCase from ..models import Feedback class CreateViewTestCase(TestCase): url = reverse('feedback:create') def _setup_session(self): # Setup the test client session # Based on snippets from: ht...
from operator import attrgetter from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType from pyangbind.lib.yangtypes import RestrictedClassType from pyangbind.lib.yangtypes import TypedListType from pyangbind.lib.yangtypes import YANGBool from pyangbind.lib.yangtypes import YANGListType from pyangbind.lib.ya...
from sqlalchemy import sql, types, util from sqlalchemy.engine import default from sqlalchemy.sql import compiler from sqlalchemy.sql.elements import quoted_name from sqlalchemy_hana import types as hana_types RESERVED_WORDS = { 'all', 'alter', 'as', 'before', 'begin', 'both', 'case', 'char', 'condition', 'conn...
from abc import ABCMeta from mycroft.plugin.util import load_class, load_plugin from mycroft.util import log class MustOverride(NotImplementedError): pass class OptionPlugin: """ >>> # --- mycroft/fruits/fruit_plugin.py --- >>> from abc import abstractmethod >>> from mycroft.plugin.base_plugin impor...
"""Linear Estimators.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import six from tensorflow.python.estimator import estimator from tensorflow.python.estimator.canned import head as head_lib from tensorflow.python.estimator.canned import op...
from insights.parsers.blkid import BlockIDInfo from insights.tests import context_wrap BLKID_INFO = """ /dev/sda1: UUID="3676157d-f2f5-465c-a4c3-3c2a52c8d3f4" TYPE="xfs" /dev/sda2: UUID="UVTk76-UWOc-vk7s-galL-dxIP-4UXO-0jG4MH" TYPE="LVM2_member" /dev/mapper/rhel_hp--dl160g8--3-root: UUID="11124c1d-990b-4277-9f74-c5a34e...
def infmem(): # Allocates unbounded amount of memory. x = 0 m = {} total = 0 threshold = 1000 while True: m[x] = "*" * x total += x x = x+1 if total > threshold: print("%d bytes allocated" % total) threshold *= 2
import logging from mako.template import Template from textwrap import TextWrapper from plugin import Plugin class TextResume(Plugin): template_file_extension = 'mako' def __init__ (self, template_file, resume_data, skip): self.skip = skip self.resume_data = resume_data self.template_fil...
from modelos import extraer_tipo_desde_codigo_factura, extraer_codigo_desde_codigo_factura from user_data import extraer_datos_factura_desde_access_db, marcar_factura_enviada_access_db from os import listdir from os.path import isfile, join, abspath import pyodbc DBfile = 'resources/factusol_database.mdb' conn = pyodbc...
import pytest import lluvia as ll def test_load_library(): session = ll.createSession(enableDebug=True, loadNodeLibrary = False) session.loadLibrary('lluvia/cpp/core/test/nodes/test_node_library.zip') desc = session.createComputeNodeDescriptor('nodes/Assign') assert(desc != None) program = session.g...
import pytest from testlink.testlinkerrors import TLResponseError from testlink.testlinkargs import registerMethod, getArgsForMethod from testlink.testlinkdecorators import decoApiCallAddAttachment,\ decoApiCallAddDevKey, decoApiCallWithoutArgs, \ decoMakerApiCallReplaceTLResponseError, decoMakerApiCallWithArgs, \ deco...
APPNAME = "Telechat-Py" VERSION = "0.1" BASE_DIR = "." # TODO MSG_DIR = BASE_DIR + "/msg" ACCT_FILENAME = "acct.db" ACCT_PASSWORDS = "pwd.db" LOG_FILENAME = "log" PRELOGIN_FILENAME = "prelogin.msg" POSTLOGIN_FILENAME = "postlogin.msg" WELCOME_HEADER = APPNAME + ' v' + VERSION + """ Copyright (C)...
""" 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 ...
__author__ = "Satish Palaniappan" ''' Copyright 2015 Satish Palaniappan 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...
import datetime import json import os from xml.dom.minidom import getDOMImplementation from ipf.data import Data, Representation from ipf.dt import * from ipf.sysinfo import SiteName from ipf.step import Step from .entity import * class AdminDomainStep(Step): def __init__(self): Step.__init__(self) ...
import os import re import pwd import shutil import socket import array import struct import fcntl import time import azurelinuxagent.logger as logger import azurelinuxagent.utils.fileutil as fileutil import azurelinuxagent.utils.shellutil as shellutil import azurelinuxagent.utils.textutil as textutil from azurelinuxag...
"""System for assigning and displaying ratings of explorations. """ __author__ = 'Jacob Davis' import datetime from core.domain import exp_services from core.platform import models import feconf (exp_models, user_models,) = models.Registry.import_models([ models.NAMES.exploration, models.NAMES.user]) transaction_se...
import os import time from io import BytesIO from zope.interface import implementer from twisted.internet.endpoints import UNIXClientEndpoint from twisted.web.iweb import IAgentEndpointFactory from twisted.web.client import Agent, readBody, FileBodyProducer from twisted.internet import reactor from twisted.web.http_hea...
"""Test forms.""" from werkzeug.datastructures import ImmutableMultiDict as IMultidict from osi_prototype.public.forms import LoginForm from osi_prototype.user.forms import EditForm, MessageForm, RegisterForm class TestRegisterForm: """Register form.""" def test_validate_user_already_registered(self, user): ...
import gin import os import util import numpy as np import gym def main(log_dir): logger = util.create_logger(name='data_collection') solution = util.create_solution(device='cpu:0') model_file = os.path.join(log_dir, 'model.npz') solution.load(model_file) trajectories = [] env = gym.make('AntBul...
try: import simplejson as json except ImportError: import json import random from weakref import WeakValueDictionary from riak.client.operations import RiakClientOperations from riak.node import RiakNode from riak.bucket import RiakBucket, BucketType from riak.mapreduce import RiakMapReduceChain from riak.resol...
import datetime import logging from django.conf import settings from .. import email logger = logging.getLogger(__name__) def sync_daily_email_blasts(blast): for l in blast.recipient_lists.all(): l.send(blast) blast.send_completed_on = datetime.datetime.now() blast.save() def sync_recipient_list(rec...
def get_key_version_attestation(project_id, location_id, key_ring_id, key_id, version_id): """ Get an HSM-backend key's attestation. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ring_id (string...
"""Generates some swift wrapper from some ops description protobuf.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from builtins import bytes import json import os import six import tensorflow.compat.v1 as tf from tensorflow.core.framework import types_pb...
'''Basic classes and functions for RVSPath items.''' import attr import geopandas as gpd import pandas as pd from typing import Any, Dict, Sequence, Tuple import os from shapely.geometry.base import BaseGeometry from shapely.geometry import LineString, Polygon import util _Geo_DataFrame_Driver = "GPKG" VERSION = 0.5 @a...
import sys import unittest import numpy as np import pygimli as pg from pygimli.physics import VESManager, ERTManager from pygimli.physics.em import VMDTimeDomainModelling np.random.seed(1337) class TestManagers(unittest.TestCase): def test_ERT(self, showProgress=False): dat = pg.getExampleFile('ert/gallery...
from tempy import Div, Content, B, P character = Div(klass='chr')( B()(Content('name')), P()('height:', Content('height')), P()('mass:', Content('mass')), P()('hair_color:', Content('hair_color')), P()('skin_color:', Content('skin_color')), P()('eye_color:', Content('eye_...
"""Data pipeline. Forked from simclr/tf2 codebase. """ import functools from typing import Optional from absl import logging from growneuron.imagenet import data_util import tensorflow.compat.v2 as tf import tensorflow_datasets as tfds def build_input_fn( builder, global_batch_size, topology, is_trainin...
import apache.thrift.metadata.lite_types as _fbthrift_metadata def gen_metadata_service_NullService() -> _fbthrift_metadata.ThriftMetadata: return _fbthrift_gen_metadata_service_NullService(_fbthrift_metadata.ThriftMetadata(structs={}, enums={}, exceptions={}, services={})) def _fbthrift_gen_metadata_service_NullSe...
import commands import logging import sys from libs import config_libs from libs import utils_libs from libs import verify_libs def main(): # Run the Testcases: test = test_gbp_l3p_neg() if test.test_gbp_l3p_neg_1() == 0: test.cleanup(tc_name='TESTCASE_GBP_L3P_NEG_1') if test.test_gbp_l3p_neg_2(...
import functools import json import logging from urllib import quote _logger = logging.getLogger(__name__) class JsonObject(dict): def __init__(self, *args, **kwargs): super(JsonObject, self).__init__(*args, **kwargs) json = json.dumps class Entity(JsonObject): def __init__(self, target_endpoint, cl...
""" Command-line tools for scitokens """
from App.Proxys import * data = IKVMCController( name = '', controlParamsList = [ ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ), ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0, 1.0 ) ), ...
"""restful_server URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Cla...
""" v2 Neutron Plug-in API specification. :class:`NeutronPluginBaseV2` provides the definition of minimum set of methods that needs to be implemented by a v2 Neutron Plug-in. """ from abc import ABCMeta, abstractmethod import six @six.add_metaclass(ABCMeta) class NeutronPluginBaseV2(object): @abstractmethod def...
class IndicatorTypes(): """ Vocabulary for Indicator Types. """ ADJUST_TOKEN = "Adjust Token" API_KEY = "API Key" AS_NUMBER = "AS Number" AS_NAME = "AS Name" BANK_ACCOUNT = "Bank account" BITCOIN_ACCOUNT = "Bitcoin account" CERTIFICATE_FINGERPRINT = "Certificate Fingerprint" ...
from pyparsing import ( Forward, Combine, Optional, Word, Literal, CaselessKeyword, CaselessLiteral, Group, FollowedBy, LineEnd, OneOrMore, ZeroOrMore, alphas, alphanums, printables, delimitedList, quotedString, Regex, __version__, Suppress, Empty ) grammar = Forward() expression = Forward() intNumber =...
""" This is dummy code to demonstrate the usefullness of classes """ import sys import numpy as np import calc_density import opacity_interpolation import utilities as utils class star(object): name = "Attributes out of the init function are shared by all objects!" def __init__(self, core_pressure, core_temp, t...
from uaitrain.operation.base_op import BaseUAITrainOp from uaitrain.api.get_train_job_running_info import GetUAITrainRunningInfoApiOp class BaseUAITrainRunningInfoOp(BaseUAITrainOp): def __init__(self, parser): super(BaseUAITrainRunningInfoOp, self).__init__(parser) def _add_job_info_args(self, info_par...
import time import uuid import unittest2 from networking_fortinet.tasks import tasks class TestTasks(unittest2.TestCase): def setUp(self, tasks_id=None): super(TestTasks, self).setUp() self.tasks_id = tasks_id if tasks_id else str(uuid.uuid1()) self.tasks = tasks.Tasks(self.tasks_id) def...
"""@package src.wi.tests.images_test @author Piotr Wójcik @author Krzysztof Danielowski @date 24.11.2012 """ from wi.tests import WiTestCase import groups_test import vm_test import unittest import random class ImagesTests(WiTestCase, unittest.TestCase): @staticmethod def _test_upload_image_private(self): ...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cloud_computing.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue...
import os import logging import multiprocessing as mp from typing import Sequence, Dict, Optional, Tuple, List, Union, Any import numpy as np from .metrics.base import Metric, Score, Signature IS_WINDOWS = os.name == 'nt' sacrelogger = logging.getLogger('sacrebleu') class Result: """A container to represent results...
"""Dual Moving Average Crossover algorithm. This algorithm buys apple once its short moving average crosses its long moving average (indicating upwards momentum) and sells its shares once the averages cross again (indicating downwards momentum). """ from zipline.api import order_target, record, symbol from zipline.fina...
from google.cloud import aiplatform_v1beta1 async def sample_create_artifact(): # Create a client client = aiplatform_v1beta1.MetadataServiceAsyncClient() # Initialize request argument(s) request = aiplatform_v1beta1.CreateArtifactRequest( parent="parent_value", ) # Make the request ...
import sys import json import time import anchore.anchore_utils gate_name = "ANCHORESEC" triggers = { 'VULNLOW': { 'description':'triggers if a vulnerability of LOW severity is found', 'params':'none' }, 'VULNMEDIUM': { 'description':'triggers if a vulnerability of MED severi...
from django.core.urlresolvers import reverse from django import http from mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.test import helpers as test class HypervisorViewTest(test.BaseAdminViewTests): @test.create_stubs({api.nova: ('extension_supported', ...
import urllib3 import socket import struct import logging from urllib3.packages.six.moves.queue import Empty urllib3.disable_warnings() logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.CRITICAL) class HTTPConnPool(urllib3.HTTPConnectionPool): def close(self): """ Close ...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('db', '0004_auto_20160719_0254'), ] operations = [ migrations.AlterField( model_name='doctor', name='email', field=mod...
from fabric.api import task, local @task def stat(): """create statistics for pep8""" local( "pep8 --statistics --filename *.py */*.py */*/*.py */*/*/*.py */*/*/*/*.py */*/*/*/*/*.py") @task def auto(): """run autopep8 on all python files""" local("autopep8 -i */*.py") local("autopep8 -i */*...
mapper_key_value = "likedeal"