input
stringlengths
2.65k
237k
output
stringclasses
1 value
"""Create a new data feed. Create a new data feed. :param body: parameters to create a data feed. :type body: ~azure.ai.metricsadvisor.models.DataFeedDetail :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raise...
pass def to_map(self): result = dict() if self.req_msg_id is not None: result['req_msg_id'] = self.req_msg_id if self.result_code is not None: result['result_code'] = self.result_code if self.result_msg is not None: result['result_msg'] = self.result_msg if self.data is not None: result['data'] = self.data ...
#!/usr/bin/env python3 import base64 import getpass import os import pprint import shutil import sys import time from contextlib import suppress from pathlib import Path from time import sleep from typing import Dict, List import psutil from broker import cfg from broker._utils import _log from broker._utils._log im...
import io import logging import os import textwrap from base64 import b64decode from timeit import default_timer as timer import coloredlogs import discord import humanize import nltk from discord.ext import commands from dotenv import load_dotenv from nltk.tokenize import sent_tokenize from pathvalidate import saniti...
Reason: Error connecting to SlashNext Cloud' return action_result.set_status(phantom.APP_ERROR, msg) # Return success elif response['errorNo'] == 0: msg = 'Test Connectivity Successful' self.save_progress(msg) return action_result.set_status(phantom.APP_SUCCESS) # If there is an error then return the exact err...
<reponame>jaescalo/cli-global-traffic-manager #!/usr/bin/python # DISCLAIMER: """ This script is for demo purposes only which provides customers with programming information regarding the Developer APIs. This script is supplied "AS IS" without any warranties and support. We assume no responsibility or liability for t...
""" Skyline functions These are shared functions that are required in multiple modules. """ import logging from os.path import dirname, join, abspath, isfile from os import path from time import time import socket import datetime import errno import traceback import json import requests try: import urlparse except I...
<reponame>bshaffer/google-cloud-sdk # -*- coding: utf-8 -*- # # Copyright 2013 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licen...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
import warnings from complexity_considerations_package.binary_layer import BinaryConv2D import config if config.tf: from tensorflow.keras.layers import (GlobalAveragePooling2D, GlobalMaxPooling2D, Dense, multiply, add, Permute, Conv2D, Reshape, BatchNormalization, ELU, MaxPooling2D, Dropout, Lambda) import tensorf...
<reponame>bnb32/wholesome_bot from wholesomebot.environment.emotes import emotes import wholesomebot.environment.clean_info as cinfo import wholesomebot.environment.settings as cfg import wholesomebot.misc as misc from nltk.stem import WordNetLemmatizer from nltk.corpus import stopwords import re import random import...
import numpy as np import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg import glob import os import re #------------------------------------------------------ #Define a function that can calculate the calibration parameter and retunr them def camera_cal(images, nx, ny): # prepare object point...
use aidx = [atom_map[i] - 1 for i in unmapped] if prim_fn is geometric.internal.OutOfPlane: aidx = ImproperDict.key_transform(aidx) # this is needed for the code below, where we use # unmapped as the key, which must be sorted (in the # same way openff sorts unmapped = ImproperDict.key_transform(unmapped) par...
reserved public IP address created with the virtual cloud network. """ pulumi.set(__self__, "id", id) @property @pulumi.getter def id(self) -> str: """ OCID of the reserved public IP address created with the virtual cloud network. """ return pulumi.get(self, "id") @pulumi.output_type class GetNetworkLoadBal...
Each tokenizer may provide different semantics with respect to this list, and may ignore it altogether. Args: types_to_skip: Types (from the constants in the `token` module) or `unified_tokenizer.TokenKind`. Note that some of those constants are actually defined in the `tokenize` module. """ self.types_to_skip =...
infinity, otherwise we could do this: #assert(temp_reminder.prec() == 1) temp_reminder = (1 / simple_qexp / q**(-m)).add_bigoh(1) fab_pol = q.parent()([]) while (len(temp_reminder.coefficients()) > 0): temp_coeff = temp_reminder.coefficients()[0] temp_exp = -temp_reminder.exponents()[0] fab_pol += temp_coeff*q*...
# coding: utf-8 """ TGS API A production scale tool for BYOND server management # noqa: E501 OpenAPI spec version: 9.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six...
linkTo(self, linkFilePath): """ Creates a symlink to self to at the path in the L{FilePath} C{linkFilePath}. Only works on posix systems due to its dependence on L{os.symlink}. Propagates L{OSError}s up from L{os.symlink} if C{linkFilePath.parent()} does not exist, or C{linkFilePath} already exists. @param li...
<filename>Breakout/RainbowBreakout.py """ This is an attempt to recreate the algorithm that was used by deepmind in the first major paper they published about beating atari games. https://www.cs.toronto.edu/~vmnih/docs/dqn.pdf Uses some changes suggested in https://becominghuman.ai/lets-build-an-atari-ai-part-1-dqn-df...
<reponame>nuttamas/PycQED_py3 import adaptive from adaptive.learner import LearnerND import numpy as np from functools import partial from collections.abc import Iterable import logging log = logging.getLogger(__name__) log.error("`learnerND_optimize` is deprecated! Use `learnernND_minimize`.") # ###################...
<gh_stars>0 #!/usr/bin/env python import logging import sys sys.path.append("../../") sys.path.append("pylib") import time import datetime import pymongo import uuid import os import subprocess import os.path import settings from common.utils import getSiteDBCollection sys.path.insert(0, "../../") class LoggingMana...
# -*- coding: utf-8 -*- """ profiling.__main__ ~~~~~~~~~~~~~~~~~~ The command-line interface to profile a script or view profiling results. .. sourcecode:: console $ profiling --help :copyright: (c) 2014-2017, What! Studio :license: BSD, see LICENSE for more details. """ from __future__ import absolute_impo...
<filename>compare_file_lists.py #!/usr/bin/python3 # This scrpit has been created to compare two large areas of data storage and find which files are missing in the main data area, but are present in the backup and therefore need to be copied over still. # This script will compare lists of files (which have a directo...
curRow + (N - 1) * dimx pointCon = [] for constr in self.pointConstr: pointCon.append(y[curN: curN + constr.nf]) curN += constr.nf multiPointCon = [] for constr in self.multiPointConstr: multiPointCon.append(y[curN: curN + constr.nf]) curN += constr.nf pathCon = [] for constr in self.pathConstr: pathCon.appe...
as an integer. By default it's set to 100 which is a solid colour. highlight_color - Set the highlighted text colour, by default it's 'gold' button_color_focused - Using the same format as background you can set the colour to use for a button when it's focused. button_trans_focused - Using the same format as tr...
<gh_stars>1-10 """ To use, make sure that pyJsonAttrPatternFactory.py is in your MAYA_PLUG_IN_PATH then do the following: import maya maya.cmds.loadPlugin("pyJsonAttrPatternFactory.py") maya.cmds.listAttrPatterns(patternType=True) // Return: ["json"] """ import os import sys import json import traceback i...
from ._constants import ( COORD_X_CENTER, COORD_Y_CENTER, COORD_X_OUTER, COORD_Y_OUTER, VAR_LON_CENTER, VAR_LAT_CENTER, VAR_LON_OUTER, VAR_LAT_OUTER, ) from ._plot_helpers import ( infer_cmap_params, _get_var_label, _align_grid_var_dims, _align_plot_var_dims, ) from ._masking import _mask_antimeridian_quads...
WITH SHORT RIGHT LEG' '\x02YA' '\x03YAA' '\x03YAH' '\x03YAI' '\x03YAN' '\x0cYAN NUMERAL ' '\x07YANMAR ' '\x07YANSAYA' '\x03YAT' '\x03YAU' '\x04YAWN' '\x03YAY' '\x02YE' '\x03YEE' '\x03YEH' '\x1aYEH WITH HAMZA ABOVE WITH ' '\x1cYEH WITH TWO DOTS BELOW AND ' '\x08YEN SIGN' '\tYESIEUNG-' '\x04YEUX' '\x05YGIEA' '\x02YI' '\x...
<gh_stars>0 from .rpc.request import ( rpc_request ) from .exceptions import ( InvalidRPCReplyError ) _default_endpoint = 'http://localhost:9500' _default_timeout = 30 ################ # Network RPCs # ################ def get_shard(endpoint=_default_endpoint, timeout=_default_timeout) -> int: """ Get config fo...
<filename>pynos/versions/ver_7/ver_7_1_0/yang/brocade_port_profile_ext.py #!/usr/bin/env python import xml.etree.ElementTree as ET class brocade_port_profile_ext(object): """Auto generated class. """ def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def get_port_profile_for_intf_input_rbri...
<reponame>neurodata/graphbook-code # -*- coding: utf-8 -*- import seaborn as sns import numpy as np import matplotlib as mpl from matplotlib.colors import Colormap # from graspologic.plot.plot import _check_common_inputs, _process_graphs, _plot_groups from graspologic.plot.plot import ( _check_common_inputs, _proces...
if grid_size == 0: s = imsize/128. rangeXY = np.arange(20*s, 110*s+1, 10*s) - 1 # 10x10 elif grid_size == 1: s = imsize/128. rangeXY = np.arange(10*s, 120*s+1, 10*s) - 1 # 12x12 else: rangeXY = np.arange(imsize) # 128x128 or 256x256 self.rangeXY = rangeXY.astype(int) [xx,yy] = np.meshgrid(rangeXY,rangeXY) s...
<gh_stars>0 """ Authors: <NAME>, <NAME> Principal Investigator: <NAME>, Ph.D. from Brown University 12 February 2020 Updated: 27 November 2020 SCOT algorithm: Single Cell alignment using Optimal Transport Correspondence: <EMAIL>, <EMAIL>, <EMAIL> """ ### Import python packages we depend on: # For regular mat...
if k != 'local_vars'} qj('some log') mock_log_fn.assert_called_once_with(RegExp( r"qj: <qj_test> test_expected_locals_mods: 'some log' <\d+>: some log")) # Make sure that none of the existing variables got modified. self.assertEqual(local_vars, {k: v for k, v in locals().items() if (k != '__qj_magic_wocha_doin_...
<reponame>spenczar/precovery import dataclasses import glob import itertools import logging import os import struct from typing import ( Iterable, Iterator, Optional, Set, Tuple ) import numpy as np import sqlalchemy as sq from rich.progress import ( BarColumn, Progress, TimeElapsedColumn, TimeRemainingColumn...
<reponame>ValentinoUberti/mcimporter # -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations # ------------------------------------------------------------------------- # This is a sample controller # - index is the default action of any application # - user is req...
if (section, key) in self.sensitive_config_values: if super().has_option(section, fallback_key): secrets_path = super().get(section, fallback_key) return _get_config_value_from_secret_backend(secrets_path) return None def get(self, section, key, **kwargs): section = str(section).lower() key = str(key).lower() ...
# -*- coding: utf-8 -*- """ Created on Tue May 14 19:10:39 2019 @author: Sneha """ # -*- coding: utf-8 -*- """ Created on Sun Apr 21 11:57:42 2019 @author: Sneha """ import random import math import copy import numpy as np import matplotlib.pyplot as plt import time from IPython import get_ipython get_ipython().run...
is not None: x1 = x1[index1,] if flg1 is True: dot_x1 = dot_x1[index1,] else: dot_x1 = numpy.sum(x1**2, 1) else: if flg1 is False: dot_x1 = numpy.sum(x1**2, 1) if index2 is not None: x2 = x2[index2,] if flg2 is True: dot_x2 = dot_x2[index2,] else: dot_x2 = numpy.sum(x2**2, 1) alpha2 = alpha2[index2,] el...
rev_eds = _parser(_lexer(fmt)) self.assertEqual(result, _input(eds, rev_eds, inp)) @attr(platform='9-1_linux_intel') @attr('input') @attr(ed='E') def test_e_ed_input_116(self): inp = '''-100.''' fmt = '''(E5.4E1)''' result = [-1.0000000000000000e+02] eds, rev_eds = _parser(_lexer(fmt)) self.assertEqual(resul...
| wx.CANCEL) return result.returnedString def doExit(self): if self.components.document.GetModify(): save = self.saveChanges() if save == "Cancel": return False elif save == "No": return True else: if self.documentPath is None: return self.on_menuFileSaveAs_select(None) else: self.saveFile(self.documentPa...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # pyre-strict import asyncio import logging import math from typing import Any, DefaultDict, Dict, List, Optional fro...
<filename>src/python/pants/engine/target_test.py<gh_stars>0 # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from collections import namedtuple from dataclasses import dataclass from enum import Enum from typing import Any, Dict, Iterabl...
None: # Shape should match data if bad_map.ndim == 2 and bad_map.shape != data[0].shape: raise ValueError( f"2D bad_map should have the same shape as a frame ({data[0].shape})," f" but has shape {bad_map.shape}" ) elif bad_map.ndim == 3 and bad_map.shape != data.shape: raise ValueError( f"3D bad_map should hav...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from typing import Union from . import utilities, tables class Databas...
<filename>shaDow/utils.py import os import torch import glob import numpy as np import scipy.sparse as sp import yaml from sklearn.preprocessing import StandardScaler from shaDow.globals import git_rev, timestamp, Logger from torch_scatter import scatter from copy import deepcopy from typing import List, Union from...
of each star starsT = np.empty(nStars) for j in range(nStars): color_separation = (J_Hobs[j]-jhMod)**2+(H_Kobs[j]-hkMod)**2 min_separation_ind = np.argmin(color_separation) starsT[j] = teffMod[min_separation_ind] radeg = 180/np.pi sweetSpot = dict(x=xval, y=yval, RA=allRA[targetIndex], DEC=allDEC[targetIndex],...
== 3: if ftype == TType.I64: self.timestamp = iprot.readI64(); else: iprot.skip(ftype) elif fid == 4: if ftype == TType.I32: self.consistency_level = iprot.readI32(); else: iprot.skip(ftype) else: iprot.skip(ftype) iprot.readFieldEnd() iprot.readStructEnd() def write(self, oprot): if oprot.__class__ == ...
"threshold": 1e-2}, } vec5 = a.create(H2O) self.assertTrue(not np.allclose(vec4, vec5)) def test_flatten(self): """Tests that flattened, and non-flattened output works correctly.""" system = H2O n = 10 n_species = len(set(system.get_atomic_numbers())) # K1 unflattened desc = MBTR( species=[1, 8], k1={ "g...
<filename>main.py import json import webapp2 import random, string import os import cgi from google.appengine.ext import ndb from google.appengine.api import urlfetch import urllib from cStringIO import StringIO #Logging for....logging? import logging # RESTful permissions PERMISSION_ANYONE = 'anyone' PERMISSION_LOGG...
<reponame>SmirkCao/obscmd<filename>run.py<gh_stars>10-100 #!/usr/bin/python # -*- coding:utf-8 -*- import Queue import base64 import hashlib import logging import logging.config import logging.handlers import multiprocessing import os import sys import threading import time import traceback from optparse import OptionP...
<reponame>ccgenomics/somaticseq #!/usr/bin/env python3 import sys, argparse, gzip, os, re, subprocess, logging MY_DIR = os.path.dirname(os.path.realpath(__file__)) PRE_DIR = os.path.join(MY_DIR, os.pardir) sys.path.append( PRE_DIR ) import genomicFileHandler.genomic_file_handlers as genome import vcfModifier.copy_Te...
from __future__ import print_function import timeit import re import pandas as pd from datetime import datetime, timedelta from flask_restplus import Namespace, Resource from pymongo import MongoClient api = Namespace('automatic_analysis', description='automatic_analysis') uri = "mongodb://localhost:27017/gcm_gisa...
<gh_stars>1-10 """Module with widgets to control GeoGraphViewer.""" from __future__ import annotations import logging from typing import Dict, Optional import ipywidgets as widgets import traitlets from geograph.visualisation import geoviewer, widget_utils class BaseControlWidget(widgets.Box): """Base class for c...
# -*- coding: utf-8 -*- #try: # # Python 2.7 # from collections import OrderedDict #except: # # Python 2.6 from gluon.contrib.simplejson.ordered_dict import OrderedDict from gluon import current, A, DIV, H3, TAG, SQLFORM, IS_NOT_EMPTY, IS_EMAIL from gluon.storage import Storage def config(settings): """ Template s...
boxes and the top & bottom bounding boxes. lr_bbox = find_bbox_bbox(bboxes['left'], bboxes['right']) lr_hgt = abs(lr_bbox[0][Y] - lr_bbox[1][Y]) tb_bbox = find_bbox_bbox(bboxes['top'], bboxes['bottom']) tb_hgt = abs(tb_bbox[0][Y] - tb_bbox[1][Y]) if 0.75 <= float(lr_hgt)/float(tb_hgt) <= 1/0.75: bal_bbox = find_b...
#!/usr/bin/env python """ <NAME> Feb 2021 external calibration of two odometries """ import rospy from nav_msgs.msg import Odometry import numpy as np import message_filters import tf import random from geometry_msgs.msg._Pose import Pose from sklearn.linear_model import RANSACRegressor from utils import so3_estimatio...
not the global file must be deleted manually. :return: an ID that can be used to retrieve the file. """ raise NotImplementedError() @contextmanager def writeGlobalFileStream( self, cleanup: bool = False, basename: Optional[str] = None, encoding: Optional[str] = None, errors: Optional[str] = None, ) -> Ite...
<reponame>m-ajay/superset # 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 # "...
""" Created on Mon Aug 25 13:17:03 2014 @author: anthony """ import time from multiprocessing import Pool import matplotlib.pyplot as plt import numpy as np import scipy.interpolate as interp from .cp_tools import cp_loglikelihood from .cp_tools import cp_loglikelihood_proj from .cp_tools import cp_model from .cp_to...
import numpy as np import function class Conv2d(object): """ Implements the 2D convolutional layer. """ def __init__(self, in_channels, out_channels, kernel_size, strides=1, padding=(0, 0), num_pads=1): self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = kernel_size self.strides...
x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args): _gskernel.GsScreenDisplay_swiginit(self, _gskernel.new_GsScreenDisplay(*args)) __swig_destroy__ = _gskernel.delete_GsScreenDisplay def BindDevice(self, pDevice: 'GsPaintDevice') -> "void":...
<reponame>liudger/ml_tools<filename>scripts/ml_breakdown.py # -= ml_breakdown.py =- # __ by <NAME> # ____ ___ / / http://morganloomis.com # / __ `__ \/ / Revision 4 # / / / / / / / 2018-05-13 # /_/ /_/ /_/_/ _________ # /_________/ # # ______________ # - -/__ License __/- - - - - - - - - - - - - - - - - - - - - - - - ...
earlier_ed_cc7d_admits = earlier_ed_admits[earlier_ed_admits['curr_ward'] == 'CC7D'] earlier_ed_ccxd_admits = pd.concat([earlier_ed_cc6d_admits, earlier_ed_cc7d_admits]) earlier_ed_micu_admits = earlier_ed_admits[earlier_ed_admits['icustay_id'].isin(micu_icustay_ids.index)] earlier_ed_micu_boarder_admits = earlier...
run_target=self.ndb_device_0.run_target), common.PublishEventType.DEVICE_NOTE_EVENT), mock.call( api_messages.NoteEvent( note=device_note_collection_msg.notes[1], hostname=self.ndb_device_1.hostname, lab_name=self.ndb_device_1.lab_name, run_target=self.ndb_device_1.run_target), common.PublishEventType.DEVICE_NO...
# SECUREAUTH LABS. Copyright 2020 SecureAuth Corporation. All rights reserved. # This software is provided under a slightly modified version # of the Apache Software License. See the accompanying LICENSE file # for more information. # # Authors: # <NAME> <<EMAIL>> / Positive Technologies (https://www.ptsecurity.com/) #...
<gh_stars>10-100 import logging import os import argparse import random from tqdm import tqdm, trange import json import re import numpy as np import torch from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from torch.utils.data.distributed import DistributedSampler from Bert_toke...
<filename>treedlib/treedlib/templates.py from itertools import chain import re import lxml.etree as et from collections import defaultdict # NODESET: # =========== class NodeSet: """ NodeSet objects are functions f : 2^T -> 2^T --------------- They are applied compositionally and lazily, by constructing an xpath...
exception to be raised from expects :return: The HTTP response :rtype: :class:`aiohttp.ClientResponse` :raises: :class:`.UnhandledProviderError` Raised if expects is defined :raises: :class:`.WaterButlerError` Raised if invalid HTTP method is provided """ kwargs['headers'] = self.build_headers(**kwargs.get('head...
<reponame>luzsantamariag/terser<filename>meb/EmotionRecognition.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Dec 24 01:58:15 2019 @authors: <NAME> (<EMAIL>) <NAME> (<EMAIL>) """ from sklearn.metrics import confusion_matrix, accuracy_score, f1_score from tensorflow.keras.callbacks import Mo...
self.x_max_2 + offset + self.spacing, y_line) term_indx += 1 def _add_top_channels(self): """ Creates horizontal channels """ term_indx = 0 for ele in self.chany_t: chan = int(ele.attrib["index"]) # left to right channels if not chan in [int(e.attrib["index"]) for e in self.ft_top]: # Add connecting Vertic...
#!/usr/bin/env python """ Enumerate subgraphs & get amons """ import aqml.cheminfo as ci import aqml.cheminfo.math as cim import aqml.cheminfo.graph as cg import aqml.cheminfo.openbabel.amon_f as cioaf from aqml.cheminfo.rw.ctab import write_ctab import networkx as nx #import aqml.cheminfo.fortran.famon as fm from it...
<reponame>turkeydonkey/nzmath3 import unittest from nzmath.matrix import * import nzmath.vector as vector import nzmath.rational as rational import nzmath.poly.uniutil as uniutil Ra = rational.Rational Poly = uniutil.polynomial Int = rational.theIntegerRing # sub test try: from test.testMatrixFiniteField import * e...
<filename>utils/surface.py<gh_stars>100-1000 import maya.cmds as mc import maya.OpenMaya as OpenMaya import glTools.utils.base import glTools.utils.curve import glTools.utils.component import glTools.utils.mathUtils import glTools.utils.matrix import glTools.utils.shape import glTools.utils.stringUtils import math d...
you cover your eyes during a scary part in a movie?", "What is your guilty pleasure?", "Has anyone ever walked in on you when taking a shit in the bathroom?", "Do you pick your nose?", "Do you sing in the shower?", "Have you ever peed yourself?", "What was your most embarrassing moment in public?", "Have you eve...
1, 'size': 2, 'is_label': False, 'is_delay': False, 'args': [ Oper(OpType.REG, 'R{n}', True, False, 0, 0) ], 'tokens': [ (InstructionTextTokenType.InstructionToken, 'tas.b'), (InstructionTextTokenType.TextToken, ' '), (InstructionTextTokenType.TextToken, '@'), (InstructionTextTokenType.RegisterToken, 'R{n}')...
if key not in keys} obj.update(kwargs) if kwextra: obj.set_text('') else: return obj # Get properties from old object for key in ('ha', 'va', 'color', 'transform', 'fontproperties'): kwextra[key] = getattr(obj, 'get_' + key)() # copy over attrs text = kwargs.pop('text', obj.get_text()) x, y = kwargs.pop('posi...
0] # return list(set(list1) | set(list2)) def attainAllButSpecifiedIndices(P, indices): """ This function serves to get all points whose index is not present in indices. :param P: A PointSet object, which is a weighted set of points. :param indices: A numpy array of indices with respect to P. :return...
score#cl_weight*(1/npmean(distances_sel)) else: return None, None if enter == 1: if npmean(distances) <= 0.05: return 1.0 if npmean(distances) == 0.0: return 1.0 return score else: return None, None def envelope_score(self,map_target, primary_boundary, structure_instance,norm=True): """ Calculate the enve...
<gh_stars>100-1000 # -*- coding: utf-8 -*- """ chemdataextractor.text ~~~~~~~~~~~~~~~~~~~~~~ Tools for processing text. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import re import unicodedata from bs4 impor...
a blueprint/deployment resource to target_path. This mirrors ctx.download_resource, but for workflow contexts. See CloudifyContext.download_resource. """ return self._internal.handler.download_deployment_resource( resource_path=resource_path, target_path=target_path) def send_event(self, event, event_type='wor...
self.pad_amount:self.pad_amount + length] else: real = real[:, :length] return real def extra_repr(self) -> str: return 'n_fft={}, Fourier Kernel size={}, iSTFT={}, trainable={}'.format( self.n_fft, (*self.wsin.shape,), self.iSTFT, self.trainable ) class MelSpectrogram(torch.nn.Module): """This function is ...
from collections import namedtuple, defaultdict from torch.utils.data import Dataset from torch import Generator import torch import numpy as np from typing import Sequence, Optional, Dict, Union # UGH: Pytorch dataloaders don't support dataclasses, only namedtuples # See https://github.com/pytorch/pytorch/blob/9baf7...
an admin.") mvec_qs = ManualVariantEntryCollection.objects.order_by("-id") context = {"form": form, "mvec_qs": mvec_qs} return render(request, 'snpdb/data/manual_variant_entry.html', context=context) @require_POST def set_user_row_config(request): """ This is set from jqgrid.html setRowChangeCallbacks when chan...
str, Optional("output-bytes"): str, Optional("ipv6-transit-statistics"): { "input-bytes": str, "input-packets": str, "output-bytes": str, "output-packets": str, }, }, Optional("transit-traffic-statistics"): { "input-bps": str, "input-bytes": str, "input-packets": str, "input-pps": str, Optional("ipv6-tran...
<reponame>fief-dev/fief<filename>backend/tests/test_apps_auth_auth.py from typing import Dict, Optional import httpx import pytest from fastapi import status from fief.crypto.token import get_token_hash from fief.db import AsyncSession from fief.managers import GrantManager, LoginSessionManager, SessionTokenManager f...
# -*- coding: utf-8 -*- # Copyright (c) 2009 Las Cumbres Observatory (www.lcogt.net) # Copyright (c) 2010 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, includi...
Get Clone Sets Function def volume_group_clone_get_sets(args): obj = VolumeGroup(args.ip, args.port) try: res= obj.volume_group_clone_get_sets(args.name) return common.format_json_object(res) except SOSError as e: if (e.err_code == SOSError.SOS_FAILURE_ERR): raise SOSError( SOSError.SOS_FAILURE_ERR, "Get cl...
<filename>ixnetwork_restpy/testplatform/sessions/ixnetwork/traffic/trafficitem/configelement/stack/fipElpSwRjtFcf_template.py from ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class FipElpSwRjtFcf(Base): __slots__ = () _SDM_NAME = 'fipElpSwRjtFcf' _SDM_ATT_MAP = { 'HeaderFipVersion':...
return self._entity_data.get('vehiclescript') return "scripts/vehicles/jeep_test.txt" @property def actionScale(self): if "actionScale" in self._entity_data: return float(self._entity_data.get('actionScale')) return float(1) class BaseDriveableVehicle(BaseVehicle): pass @property def VehicleLocked(self): ...
Case where performance data are already in kWh/yr and no further # calculations are required if orig_perf_units == "kWh/yr" and any([ x not in modes for x in orig_perf.keys()]): perf_kwh_yr = orig_perf # Case where performance data are in units of kWh/yr, but are # broken out by operational mode (e.g, active, rea...
in enumerate(results[category]): if not self.leaderboard and score.score == 0: results[category][i] = ScoreMock( target=score.target, score='DNS', hits='', golds='', xs='', disqualified=False, retired=False, placing=None, ) return results class ByRoundAllShot(ByRound, BaseResultMode): slug = 'all-shot' ...
"""The tests for the MQTT siren platform.""" import copy from unittest.mock import patch import pytest from homeassistant.components import siren from homeassistant.components.siren.const import ATTR_VOLUME_LEVEL from homeassistant.const import ( ATTR_ASSUMED_STATE, ATTR_ENTITY_ID, ENTITY_MATCH_ALL, SERVICE_TURN_...
""" A Simple logging system 4 python based around the power of sqlite3. Advantages over python's built in logging module: 1. With logging I've often found myself going back to the config dict constantly to increase verbosity or remove noise and have to restart the program every time to find out whats going on. This is...
# ------------------------------------------------------------------------- # # Part of the CodeChecker project, under the Apache License v2.0 with # LLVM Exceptions. See LICENSE for license information. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception # # ------------------------------------------------------...
# coding=utf-8 # Copyright © 2018 Computational Molecular Biology Group, # Freie Universität Berlin (GER) # # Redistribution and use in source and binary forms, with or # without modification, are permitted provided that the # following conditions are met: # 1. Redistributions of source code must retain the above # co...
<gh_stars>10-100 from .preprocessing import * from os.path import dirname, join, expanduser from joblib import Parallel, delayed from .utils import * from tqdm import tqdm import pandas as pd import numpy as np import censusdata import json import sys import os import re def pad_logrecno(data): data["LOGRECNO"] = da...
<filename>flappy/envs/fwmav/controllers/arc_xy_arc_z.py<gh_stars>100-1000 import numpy as np class pid: def __init__(self): self.old_error = 0 self.integral = 0 self.int_max = 0 self.Kp = 0 self.Ki = 0 self.Kd = 0 self.p = 0 self.i = 0 self.d = 0 class ARCController(): def __init__(self,dt): sel...
os.path.realpath(filenames[0]) if os.path.exists(filename): output("%s already exists." % filename) sys.exit(1) if not input: # Create blank database, with just account username logger.info("Creating new blank database %s for user '%s'.", filename, username) db = skypedata.SkypeDatabase(filename) for ta...
<reponame>VeritasOS/krankshaft # TODO caching? # TODO stop **headers crap, make a headers object and pass that around... from . import util from .auth import Auth from .exceptions import \ Abort, KrankshaftError, InvalidOptions, ResolveError, ValueIssue from .serializer import Serializer from .throttle import Throttl...