content
stringlengths
5
1.05M
import pandas as pd import matplotlib.pyplot as plt import os import seaborn data_dir = './simulation_data' data = [] for f in os.listdir(data_dir): data.append(pd.read_csv(os.path.join(data_dir,f))) print('Loaded data log:'+f) series =[] index = [] for i,df in enumerate(data): blocks = df['Blocks'][1] ...
import pandas as pd def cleanse(data_files, airport): input_df = import_relevant_cols(data_files) clean_df = remove_nulls(input_df) arrivals_df = keep_relevant_airports(clean_df, airport) return arrivals_df def import_relevant_cols(data_files): df_from_each_file = (pd.read_csv( f, ...
import mocap.datasets.amass_constants.utils as AMASS_UTILS FILES = [ AMASS_UTILS.convert_old_convention_to_new(f) for f in [ "ACCAD/Female1Running_c3dC4_SB__SB2__SB_Run_SB_to_SB_walk1_dynamics.pkl", "ACCAD/Male1General_c3dGeneral_SB_A4_SB__SB2__SB_Look_SB_Around_dynamics.pkl", # "ACCAD/...
#!/usr/bin/env python3 import sys from testrunner import run # Use a custom global timeout for slow hardware. On microbit (nrf51), the # test completes in 120s. TIMEOUT = 200 def testfunc(child): child.expect_exact('micro-ecc compiled!') child.expect_exact('Testing 16 random private key pairs and signature...
# _*_ coding: utf-8 _*_ """ Created by Allen7D on 2020/3/24. """ from app.libs.swagger_filed import BodyField __author__ = 'Allen7D' group_name_in_body = BodyField(name='name', type='string', description='权限组名称', enum=['活动策划员', '运维管理员']) auth_ids_in_body = BodyField(name='auth_ids', type='array', description='权限ID列...
from typing import List, Sequence, Optional from abc import ABC, abstractmethod from .snapshots import Snapshot from .time import Time from datetime import datetime from datetime import timedelta from calendar import monthrange class BackupScheme(ABC): def __init__(self): pass @abstractmethod def...
import numpy as np import pandas as pd from pandas import Series, DataFrame def A(): a = np.array([1, 2, 3]) b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) b[1,1]=10 print( a.shape ) print( b.shape ) print( a.dtype ) print( b ) def B(): persontype = np.dtype({ 'names':['name',...
""" This script generates a DBC file from our custom protobufs in order to make the transition to DBCs more seamless. This is a temporary measure so we can continue to use codegen-tooling, while switching over to using DBC decoders so we do not have to maintain the dump scripts. The idea is that we will eventually swi...
# Exercise 7.29 # Author: Noah Waterfield Price from Polynomial import Polynomial from numpy import exp import sys def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) x = float(sys.argv[1]) Nlist = sys.argv[2:] plist = [] for N in Nlist: coeffs = [1. / factorial(k) f...
import unittest from unittest.mock import patch, MagicMock from modules.user.data.user_pool_data import UserPoolData from modules.user.exceptions.user_pool.user_pool_add_error import UserPoolAddError from modules.user.exceptions.user_pool.user_pool_delete_error import UserPoolDeleteError from modules.user.exceptions.us...
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
"""Simulate RL datasets""" import numpy as np import pandas as pd import rl from modelmodel.misc import process_prng def rescorla_wagner(trials, acc, p, alpha=None, prng=None): """Create a RW learning dataset Parameters ---------- trials : list([int, ]) Trials coded by condition acc ...
#!/usr/bin/env python3 """ Demonstrates the difference between a classical and quantum walk. This involves traversing a number line in which the ends are connected, meaning that going past the right end of the line loops around to the left, and vice versa. A classical walker will randomly walk one step ...
import time import numpy as np from TorchTSA.model import VARModel from TorchTSA.simulate import VARSim B = np.array([ [0.5, -0.12], [0.35, 0.1] ]) sim = VARSim( _phi_arr=np.array([ [[0.5, 0.3], [-0.3, 0.4]], [[0.3, -0.2], [0.2, 0.1]] ]), _mu_arr=np.array([0.1, ...
import arcade import random import time from tile import Tile, TileType from board import Board from dashboard import Dashboard from constants import * # import logging import return_view import datetime # Logger (for debugging) # logging.basicConfig(level=logging.INFO, format='%(levelname)s - %(message)s') # Set ran...
from abc import ABC, abstractmethod from django.apps import AppConfig class AiravataAppConfig(AppConfig, ABC): """Custom AppConfig for Django Airavata apps.""" @property @abstractmethod def url_app_name(self): """Return the urls application namespace (typically, same as label).""" p...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
# Copyright 2020 Google LLC # # 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, ...
from flask import request from flask import current_app as app from datetime import datetime from flask_restful import Resource from flask_jwt_extended import ( JWTManager, jwt_required, create_access_token, create_refresh_token, get_jwt_identity ) from models....
""" README ====== This file contains Python codes. ==== """ """ Price a down-and-out option by the Crank-Nicolson method of finite differences. """ import numpy as np from FDCnEu import FDCnEu class FDCnDo(FDCnEu): def __init__(self, S0, K, r, T, sigma, Sbarrier, Smax, M, N, is_call=True): ...
from day23.script1 import parse, Program class Nat: def __init__(self): self.x = None self.y = None self.sent = [] def update(self, x, y): self.x = x self.y = y def solve(memory): pgms = [Program(list(memory), [i, -1]) for i in range(50)] nat = Nat() whil...
# coding: utf-8 """ Senzing REST API This is the Senzing REST API. It describes the REST interface to Senzing API functions available via REST. It leverages the Senzing native API which is documented at [https://docs.senzing.com](https://docs.senzing.com) # noqa: E501 OpenAPI spec version: 1.6.0 ...
#!/usr/bin/env python #_*_coding:utf-8_*_ import sys, os, re pPath = os.path.split(os.path.realpath(__file__))[0] sys.path.append(pPath) import readFasta import saveCode USAGE = """ USAGE: python CTDTClass.py input.fasta output amino_acids_group_1 amino_acids_group_2 ... amino_acids_group_N input.fasta: ...
import os import sys from azure.storage.blob import BlockBlobService, ContentSettings block_blob_service = BlockBlobService(account_name='mirisstorage', account_key='KdRI8bpF4kvMvzHzG4yf3jZs+AeKMH1KSQC/efvVPrE7rvXRkVLl5Wo3Ozr9OLJDcUEpfrAQzXZMGOpewe9hCA==') block_blob_service.cre...
import matplotlib matplotlib.use("WebAgg") import matplotlib.pyplot as plt import numpy as np import pandas as pd from nilearn.datasets import fetch_haxby from nilearn.input_data import NiftiMasker from kmapper import KeplerMapper, Cover from sklearn.manifold import TSNE from sklearn.cluster import DBSCAN from dyn...
import sys sys.path.append('c:/etc/code/table_detection_mrcnn_tensorflow') import mrcnn import mrcnn.config import mrcnn.model import mrcnn.visualize import cv2 import os # load the class label names from disk, one label per line # CLASS_NAMES = open("coco_labels.txt").read().strip().split("\n") CLASS_NAMES = ['BG'...
import turtle def drawcoolsquare(t, sz): for i in ["red", "purple", "hotpink", "blue"]: t=turtle.color(i) t=turtle.forward(sz) t=turtle.left(90) wn=turtle.Screen() wn.bgcolor("yellow") tt=turtle.Turtle tt=turtle.pensize(3) size=20 for i in range(30): drawcoolsquare(tt,size) siz...
from dataclasses import dataclass, field from typing import Type, Tuple import numpy as np import cv2 as cv from paiargparse import pai_dataclass from tfaip.data.pipeline.processor.dataprocessor import DataProcessorParams from calamari_ocr.ocr.dataset.imageprocessors.scale_to_height_processor import ( scale_to_h,...
class Solution: def longestValidParentheses(self, s): maxIdx = 0 # maintain a stack to store the indices stackIdx = [] stackIdx.append(-1) for i in range(len(s)): # if an opening bracket is encountered, push the index to stack if s[i] == '(': ...
from __future__ import absolute_import from .version import __version__ # noqa from .plugins import Aspect # noqa
from .base import * DEBUG = False SITE_URL = "https://gw-cloud.org" STATIC_URL = "/bilby/static/" ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'mail.swin.edu.au' EMAIL_PORT = 25 GWCLOUD_JOB_CONTROLLER_API_URL = "http://gwcloud-job-server:8000/job/apiv1" GWCLOUD_AUTH_API_URL = "http://gwcloud-auth:8000/auth/graphql" GWCLOUD...
from django.conf.urls import url from .views import * urlpatterns = [ url(r'^$', index), url(r'^login/$', login, name='login'), url(r'^logout/$', logout, name='logout'), url(r'^register/$', register, name='register'), url(r'^user/profile/(\d+)$', user_profile, name='user_profile'), url(r'^user/...
from flask import Blueprint, render_template from flask_login import current_user from json import dumps from werkzeug.exceptions import HTTPException mod = Blueprint('general', __name__, template_folder='../templates') # Landing Page Routing @mod.route("/") def homepage(): return render_template("index.html", c...
import telebot from helper import CheggHelper import os bot = telebot.TeleBot('YOUR_BOT_TOKEN', parse_mode=None) obj = CheggHelper() @bot.message_handler(commands=['ans']) def send_ans(message): try: ques_link = message.text.split(' ')[1] # print(ques_link) stat, filex, captionx = obj.getQ...
#!/usr/bin/python # -*- coding: UTF-8 -*- # Created by: jplin # Microsoft Research & XiaMen University # jplinforever@gmail.com # Copyright (c) 2019 import copy import glob import os import pickle import random from functools import lru_cache import tqdm import cv2 import imgaug.augmenters as iaa import numpy as np f...
"""src URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vie...
import os from contextlib import contextmanager import requests_mock mydir = os.path.dirname(__file__) URL_TO_RESPONSE_FILE_MAP = { ('https://kartta.hel.fi/ws/geoserver/avoindata/wfs' '?service=WFS&version=2.0.0&request=GetCapabilities'): ( 'wfs_capabilities_response.xml'), ('https://kartta.he...
# -*- coding: utf-8 -*- # # BitcoinLib - Python Cryptocurrency Library # BLOCK parsing and construction # © 2020 June - 1200 Web Development <http://1200wd.com/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # ...
import pytest import mpmath from mpsci.distributions import gumbel_min @pytest.mark.parametrize('scale', [1, 2]) def test_pdf_scale(scale): with mpmath.workdps(50): x = mpmath.mp.zero p = gumbel_min.pdf(x, 0, scale) assert mpmath.almosteq(p, 1/mpmath.e/scale) def test_pdf(): with m...
from django.db import models class TestModel(models.Model): field1 = models.CharField(max_length=100) field2 = models.IntegerField(default=1) field3 = models.SlugField()
""" created by nikos at 4/26/21 """ from ..base import MLBStatsAPIEndpointModel from mlb_statsapi.utils.stats_api_object import configure_api class PersonModel(MLBStatsAPIEndpointModel): date_formats = {'updatedSince': '%Y-%m-%dT%H:%M:%SZ'} @configure_api def award(self, **kwargs): return self.g...
""" to do : [02, 20, 24, 26, 27, 39, 43, 52, 53, 56, 69, 70, 82, 86, 93, 95, 98, 106, 107, 113] from: https://www.w3resource.com/python-exercises/basic/ """ from collections import deque from itertools import permutations import math #===================================================== FUNCTIONS ==========...
''' Different routines used by field, dset, grid etc. Note: g2g functionality was moved to gridtile.py due to dependence on f2py. ''' import scipy as sp def scalar2slice(*args): val=[] for i in args: if sp.isscalar(i): i=slice(i,i+1) val.append(i) return tuple(val) def find_nearest(arra...
""" API for yt.frontends._skeleton """
from django.conf import settings from django.conf.urls import url from django.contrib import admin from django.conf.urls.static import static from core import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.IndexView.as_view(), name='index') ] + static( settings.STATIC_URL, d...
# -*- coding: utf-8 -*- """ @author: 猿小天 @contact: QQ:1638245306 @Created on: 2020/2/6 2:04 验证码的生成 """ from django.http import HttpResponse from captcha.views import CaptchaStore, captcha_image from rest_framework import viewsets from rest_framework import permissions import base64 import json class imageView(viewse...
from os.path import exists import logging as log from utils import copy_dir, ensure_dir_owned_by_user import config def backup(): log.info('Backing up shared file lists...') source = config.get_shared_file_lists_dir() if not exists(source): log.info('Warning: ' + source + ' does not exist.') ...
import sys import state_signals from multiprocessing import Process import argparse import subprocess class StateSignalsResponder: """ This class runs state signals responder """ def __init__(self, redis_host: str, run_workload_method: str, timeout: int): self.__redis_host = redis_host ...
# coding=utf-8 # Copyright 2021 The Google Research Authors. # # 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...
import os from elasticsearch import helpers, Elasticsearch from pathlib import Path import json import hashlib import re import traceback from .config import Config import json import typing as t from configuration import RENDERED_DIR import pandas as pd from datetime import datetime def clean_string(string): ret...
l = list(map(int, input().split())) a, b = l[0], 0 for i in range(1, len(l)): if l[i] >= a: a, b = l[i], i print(a, b)
import datetime from ib_async import utils def test_to_ib_date(): assert utils.to_ib_date("20170804 21:31:28 GMT") == "20170804 21:31:28 GMT" assert utils.to_ib_date(1501882288) == "20170804 21:31:28 GMT" assert utils.to_ib_date(datetime.datetime(2017, 8, 4, 21, 31, 28)) == "20170804 21:31:28 GMT" c...
#!/usr/bin/env python3 # # This takes a stab at initialising your setup in a reasonable # way for quick testing. You should modify it to suit your project. # # You need to have the following packages (Debian names) installed: # build-essential python-dev python3-dev zlib1g-dev git virtualenv from subprocess import che...
# coding=utf-8 # Copyright 2021 RigL Authors. # # 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 agree...
from pypy.interpreter.astcompiler import ast, misc from pypy.interpreter.error import OperationError class UnacceptableExpressionContext(Exception): def __init__(self, node, msg): self.node = node self.msg = msg setattr(ast, "UnacceptableExpressionContext", UnacceptableExpressionContext) class ...
import signal from howdy import signal_handler signal.signal( signal.SIGINT, signal_handler ) import os, sys, logging, time from argparse import ArgumentParser # from howdy.core import core, core_admin def print_update_status( release ): print('here are the details for Plex update %s.' % release.version ) prin...
""" Copyright 2022-present ImNimboss 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, including without limitation the rights to use, copy, modify, merge, publish, distribute, ...
"""This module contains some auxiliary functions for the property testing.""" import glob import os import argparse import importlib import numpy as np import shutil import string from datetime import datetime from grmpy.grmpy_config import PACKAGE_DIR def collect_tests(): """This function collects all availabl...
def assignDmElement( n_lvl, data ): if n_lvl == 2: dm = { 'Rr0n0': data[:,0], 'Rr1n1': data[:,1], 'Rr1n0': data[:,2], 'Ir1n0': data[:,3] } elif n_lvl == 3: dm = { 'Rr0n0': data[:,0], 'Rr1n1': data[:,1], '...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.http import JsonResponse import requests # Constants RUN_URL = u'https://api.hackerearth.com/v3/code/run/' CLIENT_SECRET = 'cd70993ac2dbee9e7c7b2c533a104a7d621632fa' def home(request): if request.method ==...
"""Small python script that publishes a marker.""" import rospy from visualization_msgs.msg import Marker from geometry_msgs.msg import Vector3, Pose, Point, Quaternion from std_msgs.msg import Header, ColorRGBA class MarkerBasics(object): def __init__(self): self.marker_object_objectlister = rospy.Publis...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from google.appengine.ext import ndb from gaegraph.model import Node from gaeforms.ndb import property class reviews(Node): app = ndb.StringProperty(required=True) link = ndb.StringProperty(required=True) nota = ndb.IntegerPr...
"""Business logic testing.""" import pytest import datetime from rosters.logic import ( RosterGenerator, SolutionNotFeasible, TooManyStaff, ) from rosters.tasks import generate_roster pytestmark = pytest.mark.django_db def test_feasible_roster_generation(init_feasible_db): """Test feasible roster g...
############################################################################## # Copyright (c) 2016 ZTE Corp and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at...
import numpy as np import skgstat import logging logger = logging.getLogger(__name__) def interpolate_arrays(param_name, variograms, positions, values, new_positions, variogram_args={}, kriging_args={}): """Helper function for interpolate() that generates, stores and uses variograms the same way, but uses dat...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for artifact schemas""" import os import pytest import jsonschema from cidc_schemas.json_validation import load_and_validate_schema from .constants import SCHEMA_DIR ARTIFACT_OBJ = { "artifact_category": "Manifest File", "artifact_creator": "DFCI", "...
from datetime import datetime import pandas as pd pd.options.mode.chained_assignment = None import os from sklearn.feature_extraction.text import CountVectorizer from datetime import timedelta import tweepy from nltk.corpus import stopwords import nltk nltk.download('stopwords', quiet=True) stop = stopwords.words('e...
# AUTOGENERATED! DO NOT EDIT! File to edit: custom.ipynb (unless otherwise specified). __all__ = ['predict'] # Cell def predict(prompt, train_json_path="data/train.jsonl"): train = load_jsonl(train_json_path) df = pd.DataFrame(train) dls = TextDataLoaders.from_df(df, path=train_json_path, text_col='text',...
import go.exec as exec import os.path as path import os def test_goenv(): orig = exec.environ exec.environ = { 'PATH': '/usr/local/bin' } pkg = path.join(os.getcwd(), 'examples') v = exec.goenv(pkg, timeout=10) assert v.get('PATH') == ':'.join([ '/usr/local/bin', path.join(v.get('GOPATH'), 'bin'), ...
import datetime from response_model import * from controllers.google_controller import GoogleController from nlp_utils import parse_date, parse_time, extract_keywords, DAYS class PlanningController(object): def __init__(self, address, debug=False): self.DEBUG = debug self.ADDRESS = address ...
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
# ============LICENSE_START======================================================= # Copyright (c) 2018-2020 AT&T Intellectual Property. All rights reserved. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not...
import pdb import sys import json import time import probe import logging import requests import argparse import measuerments import socketIO_client import elasticsearch import elasticsearch.helpers import elasticsearch.exceptions from ripe.atlas.cousteau import MeasurementRequest ATLAS_LATEST_API = 'https://atlas.rip...
"""Snakemake wrapper for PALADIN alignment""" __author__ = "Tessa Pierce" __copyright__ = "Copyright 2019, Tessa Pierce" __email__ = "ntpierce@gmail.com" __license__ = "MIT" from os import path from snakemake.shell import shell extra = snakemake.params.get("extra", "") log = snakemake.log_fmt_shell(stdout=False, std...
from fastapi import HTTPException from starlette.requests import Request from starlette.responses import JSONResponse from sqlalchemy.exc import SQLAlchemyError async def db_error_handler(_: Request, exc: SQLAlchemyError) -> JSONResponse: return JSONResponse({"errors": str(exc)}, status_code=500)
# Copyright 2020 The SQLFlow 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 applicable law o...
x,y = map(int,input().split()) a = list(input()) i=0 for _ in range(y): while i<x-1: if a[i]=="B" and a[i+1]=="G": a[i],a[i+1]="G","B" i+=1 i+=1 i=0 print(*a,sep='')
from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import gym from gym.spaces import Discrete from hyperdopamine.interfaces.gym_lib import GymPreprocessing import numpy as np import gin.tf @gin.configurable def create_discretised_environment...
import os import click from pypgatk.commands.utils import print_help from pypgatk.ensembl.ensembl import EnsemblDataService this_dir, this_filename = os.path.split(__file__) @click.command('parse-gtf', short_help="Generate the DB file from a GTF, to be used by the vcf-to-proteindb command") @click.option('-c', '--c...
# -*- coding: utf-8 -*- class MazeAlgorithm: def __init__(self, maze): self.maze = maze def start(self): """Start or restart the algorithm. Return True if everything is ok.""" raise NotImplementedError() def step(self): """Make one step in the algorithm. Return T...
"""Testing file for TeamReader.""" from file_manager.team_reader import TeamReader def test_init(): """Test initialization method for TeamReader.""" # Check that reading files works properly tr_reg = TeamReader() tr_pre = TeamReader(prefix="p") tr_suf = TeamReader(suffix="q") assert tr_reg.t...
''' This code is highly based on https://github.com/carpedm20/deep-rl-tensorflow/blob/master/agents/statistic.py ''' import tensorflow as tf import numpy as np import baselines.common.tf_util as U class stats(): def __init__(self, scalar_keys=[], histogram_keys=[]): self.scalar_keys = scalar_keys ...
''' Sort an array of zeros and ones ''' def sortArray(array): ''' Sort a given array which should only include 0's and 1's Raise a value error on the first value which is not 0 or 1, otherwise returns a sorted array Logic: 1. Go over the supplied array once and: a. verify the input values b. count how many ...
import sys from util import * def create_file_CLI(dir_num): """ Please use this script in nodes with HDFS env. Each time create 10K * 50 files (10K in random dir) in TEST_DIR. """ for i in range(dir_num): file_index = 0 dir_name = TEST_DIR + random_string() # Create dir ...
EPMC_REST_API = "http://www.ebi.ac.uk/europepmc/webservices/rest/" EPMC_TARGET_VERSION = "5.2.1"
# -*- coding: UTF8 -*- from pupylib.PupyModule import * import os from modules.lib.windows.powershell_upload import execute_powershell_script __class_name__="CheckVM" ROOT=os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) @config(compat="windows", category="gather") class CheckVM(PupyModule): """ chec...
""" This file is part of WSQL-SDK The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS F...
import numpy as np import os import pandas as pd from diffcapanalyzer.chachifuncs import load_sep_cycles from diffcapanalyzer.chachifuncs import get_clean_cycles from diffcapanalyzer.chachifuncs import get_clean_sets from diffcapanalyzer.chachifuncs import clean_calc_sep_smooth from diffcapanalyzer.chachifuncs import ...
import asyncio import logging import socket import time __version__ = "1.1.6" from .data import LIP_PROTOCOL_MODE_TO_LIPMODE, LIPMessage, LIPMode from .exceptions import LIPConnectionStateError, LIPProtocolError from .protocol import ( CONNECT_TIMEOUT, LIP_ACTION_CHAR, LIP_EMPTY_RE, LIP_ERROR_RE, ...
try: import cupy except ImportError as error: import sys if "pytest" in sys.modules: # if run through pytest import pytest pytest.skip("Cupy not installed.") raise ImportError("Cupy not installed.") from error ############################################################################...
"""Auxiliary functions for the quadratic GQTPAR trust-region subsolver.""" import math from collections import namedtuple import numpy as np from scipy.linalg import cho_solve from scipy.linalg import solve_triangular from scipy.linalg.lapack import dpotrf as compute_cholesky_factorization from scipy.optimize._trustre...
def tcp_message(ctx, flow): message = flow.messages[-1] if not message.from_client: message.content = message.content.replace("foo", "bar")
from __future__ import division, print_function, absolute_import import re import glob import os.path as osp import warnings from lreid.data_loader.incremental_datasets import IncrementalPersonReIDSamples from lreid.data.datasets import ImageDataset class IncrementalSamples4mix(IncrementalPersonReIDSamples): """m...
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivat...
# @file Search insert position # @brief In a sorted list find position or potential position of a value # https://leetcode.com/problems/search-insert-position/ ''' Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order...
n = int(input()) s = input() c = len(set(s)) if n > 26: print(-1) else: print(n-c)
# -*- coding: utf-8 -*- breed_rule_list = { ('Plentiful', 'Plentiful'): (0.5, 0.5), ('Plentiful', 'Common'): (0.7, 0.3), ('Plentiful', 'Uncommon'): (0.85, 0.15), ('Plentiful', 'Limited'): (0.95, 0.05), ('Plentiful', 'Rare'): (0.99, 0.01), ('Common', 'Common'): (0.5, 0.5), ('Common', 'Uncommo...
from zah.urls import render def home(request, **kwargs): return render(request, 'home.html')
# Copyright (c) 2021, DjaoDjin inc. # All rights reserved. # # 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 copyright notice, # this list of conditions and t...
from alarmageddon.publishing import publisher import alarmageddon.result as result from alarmageddon.validations.validation import Validation, Priority import pytest @pytest.fixture(params=[ result.TestResult("name", Validation("low", Priority.LOW)), result.TestResult("name", Validation("normal", Priority.NOR...