code
stringlengths
1
199k
""" This module implements a generic console interface that can be attached to any runnable python object. """ import code import __builtin__ import threading import exceptions class ConsoleError(exceptions.Exception): """Error associated with the console.""" pass class ObjectConsole: """ This class run...
import os from zeroinstall.injector import namespaces from zeroinstall.injector.reader import InvalidInterface, load_feed from xml.dom import minidom, Node, XMLNS_NAMESPACE import tempfile from logging import warn, info group_impl_attribs = ['version', 'version-modifier', 'released', 'main', 'stability', 'arch', 'licen...
import requests params = {'username':'Ryan', 'password':'password'} r = requests.post("http://pythonscraping.com/pages/cookies/welcome.php", params) print("Cookie is set to:") print(r.cookies.get_dict()) print("-------------") print("Going to profile page...") r = requests.get("http://pythonscraping.com/pages/cookies/p...
"""SCons.Tool.tar Tool-specific initialization for tar. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ __revision__ = "src/engine/SCons/Tool/tar.py rel_2.4.0:3365:9259ea1c13d7 2015/09/21 14:03:43 bdbaddog" impo...
from __future__ import print_function import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from Xlib import display, X, threaded,Xutil import time try: import thread except ModuleNotFoundError: import _thread as thread from Xlib.ext import damage from PIL import Image, ImageTk imp...
import ardurpc from ardurpc.handler import Handler class Base(Handler): """Handler for the Base Text-LCD type""" def __init__(self, **kwargs): Handler.__init__(self, **kwargs) def getWidth(self): """ Get the display width as number of characters. :return: Width :rtype...
from __future__ import division """ instek_pst.py part of the CsPyController package for AQuA experiment control by Martin Lichtman Handles sending commands to Instek PST power supplies over RS232. created = 2015.07.09 modified >= 2015.07.09 """ __author__ = 'Martin Lichtman' import logging logger = logging.getLogger(_...
from typing import List, Optional, Dict, cast from PyQt5.QtCore import pyqtSignal, QObject, pyqtProperty, QCoreApplication from UM.FlameProfiler import pyqtSlot from UM.PluginRegistry import PluginRegistry from UM.Application import Application from UM.i18n import i18nCatalog from UM.Settings.ContainerRegistry import C...
""" Python Reddit API Wrapper. PRAW, an acronym for "Python Reddit API Wrapper", is a python package that allows for simple access to reddit's API. PRAW aims to be as easy to use as possible and is designed to follow all of reddit's API rules. You have to give a useragent, everything else is handled by PRAW so you need...
from six import iteritems class MaxDisplacement(object): def __init__(self, data): self.translations = {} self.rotations = {} for line in data: sid = line[0] self.translations[sid] = line[1:4] self.rotations[sid] = line[4:] def write_f06(self, page_sta...
""" | Database (Hobza) of interaction energies for bimolecular complexes. | Geometries from <Reference>. | Reference interaction energies from Rezac and Hobza, JCTC (in press). - **cp** ``'off'`` <erase this comment and after unless on is a valid option> || ``'on'`` - **rlxd** ``'off'`` <erase this comment and after u...
from tkinter import * from tkinter.ttk import * class TkWindow(): registers = {} def __init__(self, parent, title, width=400, height=300): self.parent = parent #Tk or toplevel self.w = width self.h = height self.make_gui(title) self.loaded() def loaded(self): ...
"""A likelihood function representing a Student-t distribution. Author: Ilias Bilionis Date: 1/21/2013 """ __all__ = ['StudentTLikelihoodFunction'] import numpy as np import scipy import math from . import GaussianLikelihoodFunction class StudentTLikelihoodFunction(GaussianLikelihoodFunction): """An object ...
import pytest from argparse import Namespace from behave_cmdline import environment as env @pytest.fixture(scope="function") def dummy_context(): ns = Namespace() env.before_scenario(ns, None) yield ns env.after_scenario(ns, None)
''' This file is part of GEAR_mc. GEAR_mc is a fork of Jeremie Passerin's GEAR project. GEAR 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 y...
"""Various array operations. Author: Seth Axen E-mail: seth.axen@gmail.com """ import numpy as np from scipy.spatial.distance import pdist, squareform QUATERNION_DTYPE = np.float64 X_AXIS, Y_AXIS, Z_AXIS = np.identity(3, dtype=np.float64) EPS = 1e-12 # epsilon, a number close to 0 def as_unit(v, axis=1): """Return...
""" Created on Sat Dec 6 17:01:05 2014 @author: remi @TODO : in the function train_RForest_with_kfold we should keep all result proba for each class, this could be very intersting. """ import numpy as np ; #efficient arrays import pandas as pd; # data frame to do sql like operation import sklearn reload(sklearn) fro...
import gtk import highgtk.entity import highgtk.present.default.layout def add (inquiry): window = getattr (inquiry, "present_window", None) if window is None: inquiry.present_window = gtk.Dialog() title = getattr (inquiry, "title", None) if title is None: root = highgtk.enti...
import re s = open("neurolab/tool.py", "r").read() s = re.sub('^([ \t\r\f\v]*)(.+?)\.shape = (.*?), (.*?)$', '\g<1>\g<2> = \g<2>.reshape((\g<3>, \g<4>,)) #replacement for \"\\g<0>\"', s, flags=re.MULTILINE) s = re.sub('^([ \t\r\f\v]*)(.+?)\.shape = (\S+?)$', '\g<1>\g<2> = \g<2>.reshape(\g<3>) #replacement for \"\\g<0>\...
from odoo import fields, models class SaasSubscriptionLog(models.Model): _name = 'saas_portal.subscription_log' _order = 'id desc' client_id = fields.Many2one('saas_portal.client', 'Client') expiration = fields.Datetime('Previous expiration') expiration_new = fields.Datetime('New expiration') re...
from __future__ import unicode_literals import os import re import sys from .common import InfoExtractor from .youtube import YoutubeIE from ..compat import ( compat_etree_fromstring, compat_urllib_parse_unquote, compat_urlparse, compat_xml_parse_error, ) from ..utils import ( determine_ext, Ext...
import pyodbc import config def main(): # formatで`{`を使うため、`{`を重ねることでエスケープ con_str = 'Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};Dbq={0};'.format(config.PATH_ACCDB) conn = pyodbc.connect(con_str) cur = conn.cursor() cur.execute("select item_name from item") for c in cur.fetchall(): ...
from itertools import product def test_it(a, b): return sum(int(d1)*int(d2) for d1,d2 in product(str(a), str(b)))
import pexpect import traceback import time import os import sys import re addr = 'telnet 192.168.99.1 10000' uname = ['a', 'd', 'm', 'i', 'n'] passwd = ['p', 'a', 's', 's', 'w', 'd'] cmdline = "show statistics traffic 5/1/0-1\n" qq = ["e", "x", "i", "t", "\n"] logName = 'Traffic_' + time.strftime("%Y-%m-%d", time.loca...
import warnings as _warnings _warnings.resetwarnings() _warnings.filterwarnings('error') from tdi import html template = html.from_string(""" <node tdi="item"> <znode tdi="nested" tdi:overlay="foo"> <ynode tdi="subnested"></ynode> </znode> <xnode tdi="a"></xnode> </node> """.lstrip()).overlay(html.f...
""" Object Server for Swift """ from __future__ import with_statement import cPickle as pickle import errno import os import time import traceback from datetime import datetime from hashlib import md5 from tempfile import mkstemp from urllib import unquote from contextlib import contextmanager from ConfigParser import ...
""" Cisco_IOS_XR_ipv4_acl_cfg This module contains a collection of YANG definitions for Cisco IOS\-XR ipv4\-acl package configuration. This module contains definitions for the following management objects\: ipv4\-acl\-and\-prefix\-list\: IPv4 ACL configuration data Copyright (c) 2013\-2016 by Cisco Systems, Inc. All ...
__author__ = 'John Sirios' from twitter.pants.base.generator import TemplateData import unittest class TemplateDataTest(unittest.TestCase): def setUp(self): self.data = TemplateData(foo = 'bar', baz = 42) def test_member_access(self): try: self.data.bip self.fail("Access to undefined template da...
import zstackwoodpecker.test_state as ts_header TestAction = ts_header.TestAction def path(): return dict(initial_formation="template4",\ path_list=[[TestAction.delete_volume, "vm1-volume1"], \ [TestAction.reboot_vm, "vm1"], \ [TestAction.create_volume, "volume1", "=scsi"], \ [TestAction.attac...
from servicemanager.actions import actions from servicemanager.smcontext import SmApplication, SmContext, ServiceManagerException from servicemanager.smprocess import SmProcess from servicemanager.service.smplayservice import SmPlayService from servicemanager.serviceresolver import ServiceResolver import pytest from .t...
from __future__ import print_function import os import sys from subprocess import Popen, PIPE from getpass import getpass from shutil import rmtree import argparse def set_filename_version(filename, version_number): with open(filename, 'w+') as f: f.write("version = '{}'\n".format(version_number)) def set_i...
import zstackwoodpecker.operations.host_operations as host_ops import zstackwoodpecker.operations.resource_operations as res_ops import zstackwoodpecker.operations.volume_operations as vol_ops import zstackwoodpecker.test_util as test_util volume = None disconnect = False host = None def test(): global disconnect, ...
class DictDiffer(object): """ Calculate the difference between two dictionaries as: (1) items added (2) items removed (3) keys same in both but changed values (4) keys same in both and unchanged values """ def __init__(self, current_dict, past_dict): self.curr...
"""Functions for computing and applying pressure.""" from typing import Callable, Optional import jax.numpy as jnp import jax.scipy.sparse.linalg from jax_cfd.base import array_utils from jax_cfd.base import boundaries from jax_cfd.base import fast_diagonalization from jax_cfd.base import finite_differences as fd from ...
import unittest import graph class BreadthFirstSearchTest(unittest.TestCase): __runSlowTests = False def testTinyGraph(self): g = graph.Graph.from_file('tinyG.txt') bfs = graph.BreadthFirstSearch(g, 0) self.assertEqual(7, bfs.count()) self.assertFalse(bfs.connected(7)) se...
""" Verify that different ways of loading datasets lead to the same result. This test utility accepts the same command line parameters as neon. It downloads the CIFAR-10 dataset and saves it as individual JPEG files. It then proceeds to fit and evaluate a model using two different ways of loading the data. Macrobatches...
import datetime import mock from neutron_lib.callbacks import events from neutron_lib.callbacks import registry from neutron_lib.callbacks import resources from neutron_lib.plugins import directory from oslo_utils import timeutils from neutron.api.rpc.agentnotifiers import dhcp_rpc_agent_api from neutron.common import ...
from hubs.ha import haremote as ha from hubs.ha.hasshub import HAnode, RegisterDomain from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested from utils import timers import functools class Thermostat(HAnode): # deprecated version def __init__(self, HAitem, d): super(Thermostat, self).__init__(H...
import json import time import jps class MessageHolder(object): def __init__(self): self.saved_msg = [] def __call__(self, msg): self.saved_msg.append(msg) def test_pubsub_with_serialize_json(): holder = MessageHolder() sub = jps.Subscriber('/serialize_hoge1', holder, ...
from google.cloud import aiplatform_v1beta1 async def sample_query_context_lineage_subgraph(): # Create a client client = aiplatform_v1beta1.MetadataServiceAsyncClient() # Initialize request argument(s) request = aiplatform_v1beta1.QueryContextLineageSubgraphRequest( context="context_value", ...
""" Network Config ============== Manage the configuration on a network device given a specific static config or template. :codeauthor: Mircea Ulinic <ping@mirceaulinic.net> & Jerome Fleury <jf@cloudflare.com> :maturity: new :depends: napalm :platform: unix Dependencies ------------ - :mod:`NAPALM proxy minion <...
""" 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...
from __future__ import absolute_import, division, print_function, unicode_literals import argparse import os import re from collections import namedtuple import buckutils as buck import javautils as java BUCK_LOG_LINE_PATTERN = re.compile( r"^\[(?P<timestamp>[^]]+)\]\[(?P<level>[^]]+)\]\[command:(?P<command>[^]]+)\...
"""Executable for the Earth Engine command line interface. This executable starts a Python Cmd instance to receive and process command line input entered by the user. If the executable is invoked with some command line arguments, the Cmd is launched in the one-off mode, where the provided arguments are processed as a s...
import json import boto3 codecommit = boto3.client('codecommit') def lambda_handler(event, context): #Log the updated references from the event references = { reference['ref'] for reference in event['Records'][0]['codecommit']['references'] } print("References: " + str(references)) #Get the repository ...
""" /*************************************************************************** GeepsSpStats A QGIS plugin Spatial Statistics by PySAL ------------------- begin : 2014-07-01 git sha : $Format:%H$ copyri...
import argparse from gym.spaces import Discrete, Box import numpy as np from ray.rllib.agents.ppo import PPOTrainer from ray.rllib.examples.env.random_env import RandomEnv from ray.rllib.examples.models.mobilenet_v2_with_lstm_models import \ MobileV2PlusRNNModel, TorchMobileV2PlusRNNModel from ray.rllib.models impo...
""" Blob-management tool application code. """
from setuptools import setup NAME = "apicaller" DESCRIPTION = "APICaller makes the creating API client library easier." AUTHOR = "Jan Češpivo" AUTHOR_EMAIL = "jan.cespivo@gmail.com" URL = "https://github.com/cespivo/apicaller" VERSION = '0.1.2a' setup( name=NAME, version=VERSION, description=DESCRIPTION, ...
from mock import Mock, patch from nose.tools import assert_equal from pylons import app_globals as g from alluratest.controller import setup_unit_test from allura.model.repo import Commit from forgesvn.model.svn import SVNImplementation class TestSVNImplementation(object): def setUp(self): setup_unit_test()...
from openstack.baremetal.v1 import _common from openstack import exceptions from openstack import resource from openstack import utils class ValidationResult(object): """Result of a single interface validation. :ivar result: Result of a validation, ``True`` for success, ``False`` for failure, ``None`` f...
from __future__ import unicode_literals import re from setuptools import find_packages, setup def get_version(filename): content = open(filename).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content)) return metadata['version'] setup( name='Mopidy-Lcdplate', version=get_version('mop...
""" Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. """ class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ while a != 0 and b != 0: ...
import logging import sys from kmip.core import enums from kmip.demos import utils from kmip.pie import client if __name__ == '__main__': logger = utils.build_console_logger(logging.INFO) # Build and parse arguments parser = utils.build_cli_parser(enums.Operation.CREATE) opts, args = parser.parse_args(s...
import base64 import binascii import json import re import uuid import warnings import zlib from collections import deque from types import TracebackType from typing import ( # noqa TYPE_CHECKING, Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Type, Union, ...
__author__ = 'bett' import MySQLdb as db import pandas.io.sql as psql from config import db_config def getData(symbols,start,end): database = db.connect(**db_config) data=psql.frame_query("SELECT * FROM tbl_historical where start", database) return data; if(__name__=='__main__'): getData('000009.sz','20...
import SocketServer from abc import ABCMeta, abstractmethod import json import requests import six from .. import LOG as _LOG from ..signal.signal import DEFAULT_ORCHESTRATOR_URL from ..signal.event import LogEvent LOG = _LOG.getChild(__name__) @six.add_metaclass(ABCMeta) class SyslogInspectorBase(object): def __in...
class Solution: # @param {string} s # @return {boolean} def isValid(self, s): slist=' '.join(s).split(' ') print slist stack=[] for item in slist: if item in ('[','{','('): stack.append(item) else: if len(stack)==0: return False elif stack[-1:][0]==self.rev(item): stack = stack[:-...
import sys import unittest from copy import deepcopy from parameterized import parameterized from airflow.contrib.operators.ecs_operator import ECSOperator from airflow.exceptions import AirflowException from tests.compat import mock RESPONSE_WITHOUT_FAILURES = { "failures": [], "tasks": [ { ...
"""A spectral clusterer class to perform clustering.""" import numpy as np from spectralcluster import constraint from spectralcluster import custom_distance_kmeans from spectralcluster import laplacian from spectralcluster import refinement from spectralcluster import utils RefinementName = refinement.RefinementName L...
import collections import shlex from ooi import exception _MEDIA_TYPE_MAP = collections.OrderedDict([ ('text/plain', 'text'), ('text/occi', 'header') ]) def _quoted_split(s, separator=',', quotes='"'): """Splits a string considering quotes. e.g. _quoted_split('a,"b,c",d') -> ['a', '"b,c"', 'd'] """ ...
import time def progress(index, size, for_what='当前进度', step=10): block_size = int(size / step) if index % block_size == 0: crt = int(index / block_size) print('%s ==> [%d / %d]' % (for_what, crt, step)) def log_time(): def _log_time(func): # func() def wrapper(*args, **kwargs...
from pytz import utc from datetime import datetime from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from django.dispatch import receiver from django.db.models.signals import pre_save, post_save from django_pgjson.fields import JsonBField from simple_histor...
from __future__ import print_function import unittest import numpy as np from operator import mul import paddle.fluid.core as core import paddle.fluid as fluid from op_test import OpTest from testsuite import create_op def group_norm_naive(x, scale, bias, epsilon, groups, data_layout): if data_layout == "NHWC": ...
from distutils.core import setup setup(name='youtubecli', description='library for uploading a video file to YouTube', version='0.1', packages=['youtubecli'], classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programmi...
from . import series from . import images def _setup(): import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter('[%(name)s] %(levelname)s %(message)s') ch = logging.StreamHandler() ch.setFormatter(formatter) logger.addHandler(ch) _setup...
import unittest from copy import deepcopy from openprocurement.api.tests.base import snitch from openprocurement.tender.belowthreshold.adapters import TenderBelowThersholdConfigurator from openprocurement.tender.belowthreshold.tests.base import ( TenderContentWebTest, test_bids, test_lots, test_organiza...
import unittest class Test_PropertyMixin(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.storage._helpers import _PropertyMixin return _PropertyMixin def _make_one(self, *args, **kw): return self._get_target_class()(*args, **kw) def _derivedClass(self...
import pytest from model.group import Group from fixture.application import Application @pytest.fixture def app(request): fixture = Application() request.addfinalizer(fixture.destroy) return fixture def test_add_group(app): app.session.login(username="admin", password="secret") app.group.create(Grou...
import sys, os, arcpy g_ESRI_variable_1 = 'lyrFC' g_ESRI_variable_2 = 'lyrTmp' g_ESRI_variable_3 = 'ID' g_ESRI_variable_4 = 'lyrOut' g_ESRI_variable_5 = ';' import os, sys, math, traceback import arcpy from arcpy import env import Utilities targetPointOrigin = arcpy.GetParameterAsText(0) numberCellsHo = arcpy.GetParame...
from datetime import datetime from datetime import date from datetime import timedelta import re import Entity.User as User import Entity.Event as Event import Entity.RepeatingEvent as RepeatingEvent import Responder def createSingleEvent(name, place, date): event = Event.getByDate(date) if event: retur...
import logging from unittest.mock import patch from django.contrib.auth import get_user_model from django.test import TestCase from django.conf import settings from accounts.authentication import PersonaAuthenticationBackend, PERSONA_VERIFY_URL __author__ = 'peter' User = get_user_model() @patch('accounts.authenticatio...
from restclients.canvas import Canvas class ExternalTools(Canvas): def get_external_tools_in_account(self, account_id): """ Return external tools for the passed canvas account id. https://canvas.instructure.com/doc/api/external_tools.html#method.external_tools.index """ url =...
import os from eventlet.green import subprocess from eventlet import greenthread from neutron_lib.utils import helpers from oslo_log import log as logging from oslo_utils import encodeutils from neutron._i18n import _ from neutron.common import utils LOG = logging.getLogger(__name__) def create_process(cmd, addl_env=No...
import argparse import subprocess from subprocess import Popen, STDOUT, PIPE import os import sys import shutil def renameOutput(runid, barcodeid, endpoint): """ CGD needs the filename to be restructured. """ if endpoint == "uploadqcsheet": newfile = "/tmp/" + '_'.join([runid, barcodeid, "R1"]) ...
from django.apps import AppConfig class InstaappConfig(AppConfig): name = 'instaapp'
"""Utility for managing projects via the Cloud Resource Manager API.""" from gcloud.exceptions import NotFound class Project(object): """Projects are containers for your work on Google Cloud Platform. .. note:: A :class:`Project` can also be created via :meth:`Client.new_project() \ <gcl...
import io import os import re import abc import csv import sys import email import pathlib import zipfile import operator import functools import itertools import collections from configparser import ConfigParser from contextlib import suppress from importlib import import_module from importlib.abc import MetaPathFinde...
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('groups', '0001_initial'), ] operations = [ migrations...
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf import settings admin.autodiscover() from front.views import * from front.views import views as front_views from django.views.decorators.csrf import csrf_exempt if not settings.DEBUG: s = {'SSL': settings.ENABLE_SS...
""" Copyright 2015 Stefano Benvenuti <ste.benve86@gmail.com> 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...
""" Storage layer python client """ __author__ = "Praveen Garg, Amarendra K Sinha" __copyright__ = "Copyright (c) 2017 OSIsoft, LLC" __license__ = "Apache 2.0" __version__ = "${VERSION}" import aiohttp import http.client import json import time from abc import ABC, abstractmethod from foglamp.common import logger from ...
import math import six if six.PY2 from ConfigParser import SafeConfigParser else from configparser import SafeConfigParser class AggregateMicroPathConfig: config_file = "" table_name = "" table_schema_id = "" table_schema_dt = "" table_schema_lat = "" table_schema_lon = "" time_filte...
import jinja2 from jinja2.loaders import TemplateNotFound from jinja2.utils import open_if_exists import os def get_dist_templates_path(): return os.path.join(os.path.dirname(__file__), 'dist-templates') class RenderspecLoader(jinja2.BaseLoader): """A special template loader which allows rendering supplied .spe...
radius = float(input()) pi = 3.14159 volume = 4/(3*pi*radius**3) print('volume = %.3f' % volume)
from django.conf.urls import patterns,url from main import views urlpatterns = patterns('', url(r'^$',views.index,name='index'), url(r'^tags/$',views.tags,name='tags'), url(r'^tags/(?P<tag_name>\w+)/$',views.tag,name='tag'), url(r'^add_link/$',views.add_link,name='add_link'), )
import copy from logging import handlers import netaddr from nuage_neutron.plugins.common import constants from nuage_neutron.plugins.common import exceptions as nuage_exc from nuage_neutron.plugins.common.extensions import nuage_router from nuage_neutron.plugins.common import nuagedb from nuage_neutron.plugins.common....
import re from lxml import etree from nxpy.util import tag_pattern, whitespace_pattern class Flow(object): def __init__(self): self.routes = [] def export(self): flow = etree.Element('flow') if len(self.routes): for route in self.routes: flow.append(route.expo...
import glance_store from oslo_log import log as logging from oslo_utils import encodeutils import webob.exc from glance.api import policy from glance.api.v2 import images as v2_api from glance.common import exception from glance.common import utils from glance.common import wsgi import glance.db import glance.gateway f...
''' @author: Michael Wan @since : 2014-11-08 ''' from math import log import operator def createDataSet(): dataSet = [[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']] labels = ['no surfacing','flippers'] #change to discrete v...
import os import sys import subprocess import readline from lib.inventory import Inventory from lib.logger import Logger from lib.ssh import SSH_CONNECTION, SSH_Exception from lib import genesis GEN_PATH = genesis.GEN_PATH GEN_CONTAINER_NAME = genesis.container_name GEN_CONTAINER_RUNNING = genesis.container_running() G...
"""Tests for ceilometer/publisher/prometheus.py""" import datetime from unittest import mock import uuid from oslotest import base import requests from urllib import parse as urlparse from ceilometer.publisher import prometheus from ceilometer import sample from ceilometer import service class TestPrometheusPublisher(b...
"""Base models for point-cloud based detection.""" from lingvo import compat as tf from lingvo.core import metrics from lingvo.core import py_utils from lingvo.tasks.car import base_decoder from lingvo.tasks.car import detection_3d_metrics from lingvo.tasks.car import transform_util from lingvo.tasks.car.waymo import w...
import mc_unittest from rogerthat.bizz.profile import create_user_profile from rogerthat.bizz.system import update_app_asset_response from rogerthat.capi.system import updateAppAsset from rogerthat.dal.mobile import get_mobile_settings_cached from rogerthat.models.properties.profiles import MobileDetails from rogerthat...
from __future__ import absolute_import, print_function, division from pony.py23compat import basestring from functools import wraps from contextlib import contextmanager from pony.orm.core import Database from pony.utils import import_module def raises_exception(exc_class, msg=None): def decorator(func): de...
"""Tabular QL agent""" import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm import framework import utils DEBUG = False GAMMA = 0.5 # discounted factor TRAINING_EP = 0.5 # epsilon-greedy parameter for tr...
"""Keras initializers for TF 2. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.keras import backend from tensorflow.pyth...
import sys import os import pandas as pd from collections import defaultdict import numpy as np dirname = sys.argv[1] path = os.path.join(dirname, "weights.tsv") with open(path ,"r") as f: df = pd.read_csv(f, sep="\t") df = df[df["iter"] == 5] fc2r = defaultdict(list) features = set() for event, event_df in df.grou...
from graphics import * from Button import * from CreateNewUserScreen import * from ChangePasswordScreen import * import os class StartScreen: def is_game_in_progress(self,gid): for filename in os.listdir("games"): if str(gid) == filename: return True return False def ...
"Test the function for mapping Terraform arguments." import pytest import tftest ARGS_TESTS = ( ({'auto_approve': True}, ['-auto-approve']), ({'auto_approve': False}, []), ({'backend': True}, []), ({'backend': None}, []), ({'backend': False}, ['-backend=false']), ({'color': True}, []), ({'co...