filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_2359
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import json import multiprocessing as mp from utils import iou_with_anchors def load_json(file): with open(file) as json_file: data = json.load(json_file) return data # 获取测试集视频信息 def getDatasetDict(opt): df = pd.read_csv(opt["vid...
the-stack_0_2360
# Copyright 2012 by Wibowo Arindrarto. All rights reserved. # This file is part of the Biopython distribution and governed by your # choice of the "Biopython License Agreement" or the "BSD 3-Clause License". # Please see the LICENSE file that should have been included as part of this # package. """Bio.SearchIO objects...
the-stack_0_2363
"""Editing JSON and JavaScript files in Sublime views""" import json from live.shared.js_cursor import StructuredCursor def json_root_in(view): return Entity(view, []) class Entity: def __init__(self, view, path): self.view = view self.path = path def __getitem__(self, key): r...
the-stack_0_2364
# -*- coding: utf-8 -*- # # Copyright 2019 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
the-stack_0_2365
from django.contrib import admin import nested_admin from django.utils.html import format_html from django.utils.translation import gettext as _ from mptt.admin import DraggableMPTTAdmin from .models import Tax, Category, Notification, Currency, Carrier # Register your models here. class CategoriesAdmin(DraggableMPTTA...
the-stack_0_2366
# quick-write python script to calculate, plot and write out the n(z) for the BOSS and 2dFLenS samples # we can compare the BOSS n(z) for the full NGP with the samples within the KiDS footprint # CH: 12th Dec 2019 from astropy.io import fits import numpy as np from matplotlib import rcParams import matplotlib.pyplot...
the-stack_0_2367
from os import getenv from fastapi import Request from fastapi.params import Depends from fastapi.templating import Jinja2Templates from pyngrok import conf, ngrok from lnbits.core.models import User from lnbits.decorators import check_user_exists from . import ngrok_ext, ngrok_renderer templates = Jinja2Templates(...
the-stack_0_2369
from enum import Enum import numpy as np from actions import Direction class Car(): def __init__(self, car): self.x = int(car['x']) self.y = int(car['y']) self.health = int(car['health']) self.resources = int(car['resources']) self.collided = bool(car['collided']) s...
the-stack_0_2370
#!/usr/bin/env python3 import copy import sys class Board: def __init__(self, rows, cols): self.rows = rows self.cols = cols self.board = [] self.initial_fill() def initial_fill(self): for i in range(self.rows): self.board.append(self.cols * [-1]) def ...
the-stack_0_2371
from copy import deepcopy from typing import List, Optional import matplotlib.pyplot as plt import numpy as np import pandas as pd import scanpy import scvi from anndata import AnnData from pyro import clear_param_store from pyro.nn import PyroModule from scvi import _CONSTANTS from scvi.data._anndata import _setup_an...
the-stack_0_2372
import json from packlib.base import ProxmoxAction class NodesNodeCertificatesInfoAction(ProxmoxAction): """ Get information about node's certificates. """ def run(self, node, profile_name=None): super().run(profile_name) # Only include non None arguments to pass through to proxmox a...
the-stack_0_2374
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Dec 14 21:24:17 2018 @author: Zhaoyi.Shen """ import sys sys.path.append('/home/z1s/py/lib/') from lanczos_filter import lanczos_filter import numpy as np import scipy as sp from scipy.signal import butter, lfilter, filtfilt def lfca(x, cutoff, truncat...
the-stack_0_2377
""" Author: Sijin Chen, Fudan University Finished Date: 2021/06/04 """ from .nn import NetworkWrapper from collections import OrderedDict from copy import deepcopy from typing import Callable import numpy as np class Optimizer: """ Meta class for optimizers """ def __init__(self, *args, **kwarg...
the-stack_0_2379
# USAGE # python cluster_faces.py --encodings encodings.pickle # import the necessary packages from sklearn.cluster import DBSCAN from imutils import build_montages import numpy as np import argparse import pickle import cv2 # construct the argument parser and parse the arguments ap = argparse.ArgumentParser() ap.add...
the-stack_0_2381
from django import forms from .models import Questionnaire class NewLandingForm(forms.Form): label = forms.CharField(max_length=64, required=True) questionnaire = forms.ModelChoiceField( Questionnaire.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None, required=...
the-stack_0_2383
""" Copyright (c) 2019-2022 Intel Corporation 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 w...
the-stack_0_2385
import pytest from page_objects.home_page import HomePage from page_objects.item_details import ItemDetails class TestProductDetails: @pytest.mark.skip("Skip for now") def test_product_details(self, driver): s = ItemDetails(driver) h = HomePage(driver) h.navigate_to_homepage() ...
the-stack_0_2386
LITHO_ROOT = "//" LITHO_VISIBILITY = [ "PUBLIC", ] LITHO_STUBS_VISIBILITY = [ "//litho-core/...", ] LITHO_TESTING_UTIL_VISIBILITY = [ "PUBLIC", ] LITHO_IS_OSS_BUILD = True def make_dep_path(pth): return LITHO_ROOT + pth LITHO_ROOT_TARGET = make_dep_path(":components") # Java source LITHO_JAVA_TAR...
the-stack_0_2390
# -*- coding: utf-8 -*- """Unit tests of everything related to retrieving the version There are four tree states we want to check: A: sitting on the 1.0 tag B: dirtying the tree after 1.0 C: a commit after a tag, clean tree D: a commit after a tag, dirty tree """ from __future__ import absolute_import, division,...
the-stack_0_2392
# Copyright 2018 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
the-stack_0_2394
# coding: utf8 from __future__ import unicode_literals from ...attrs import LIKE_NUM _num_words = ['zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'catorze', 'quinze', 'dezesseis', 'dezasseis', 'dezessete', 'dezassete', 'dez...
the-stack_0_2397
#!/usr/bin/env python3 # coding=utf-8 """ Parser that uses the ENTSOE API to return the following data types. Consumption Production Exchanges Exchange Forecast Day-ahead Price Generation Forecast Consumption Forecast """ import itertools import numpy as np from bs4 import BeautifulSoup from collections import defaul...
the-stack_0_2398
"""Support for ADS covers.""" import logging import voluptuous as vol from homeassistant.components.cover import ( ATTR_POSITION, DEVICE_CLASSES_SCHEMA, PLATFORM_SCHEMA, SUPPORT_CLOSE, SUPPORT_OPEN, SUPPORT_SET_POSITION, SUPPORT_STOP, CoverEntity, ) from homeassistant.const import CONF...
the-stack_0_2399
"""DataUpdateCoordinator for the Yale integration.""" from __future__ import annotations from datetime import timedelta from typing import Any from yalesmartalarmclient.client import YaleSmartAlarmClient from yalesmartalarmclient.exceptions import AuthenticationError from homeassistant.config_entries import ConfigEn...
the-stack_0_2400
""" weasyprint.layout.percentages ----------------------------- Resolve percentages into fixed values. :copyright: Copyright 2011-2018 Simon Sapin and contributors, see AUTHORS. :license: BSD, see LICENSE for details. """ from ..formatting_structure import boxes def _percentage(value, refer_to...
the-stack_0_2401
# -*- coding: utf-8 -*- # # django-otp-yubikey documentation build configuration file, created by # sphinx-quickstart on Sun Jul 22 16:13:25 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated fi...
the-stack_0_2404
"""Rules for writing tests with JUnit""" load("@bazel_skylib//lib:dicts.bzl", _dicts = "dicts") load( "@io_bazel_rules_scala//scala/private:common_attributes.bzl", "common_attrs", "implicit_deps", "launcher_template", ) load("@io_bazel_rules_scala//scala/private:common_outputs.bzl", "common_outputs") l...
the-stack_0_2406
""" Descriptor data structure. Descriptors are basic data structure used throughout PSD files. Descriptor is one kind of serialization protocol for data objects, and enum classes in :py:mod:`psd_tools.terminology` or bytes indicates what kind of descriptor it is. The class ID can be pre-defined enum if the tag is 4-b...
the-stack_0_2407
from tdw.controller import Controller from tdw.tdw_utils import TDWUtils from tdw.add_ons.object_manager import ObjectManager from magnebot import Magnebot, ActionStatus class CollisionDetection(Controller): """ Show the difference between arrived_offset values and collision detection settings. """ d...
the-stack_0_2410
import os import sys from _io import BytesIO from Tea.stream import BaseStream from alibabacloud_tea_fileform.models import FileField def _length(o): if hasattr(o, 'len'): return o.len elif isinstance(o, BytesIO): return o.getbuffer().nbytes elif hasattr(o, 'fileno'): ...
the-stack_0_2411
""" In this example a Bell state is made. """ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit import execute from qiskit_qcgpu_provider import QCGPUProvider Provider = QCGPUProvider() # Create a Quantum Register with 2 qubits. q = QuantumRegister(2) # Create a Quantum Circuit with 2...
the-stack_0_2414
#!/usr/bin/env python2.7 # -*- encoding: utf-8 -*- # 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 Apa...
the-stack_0_2417
# SPDX-License-Identifier: Apache-2.0 """ tf2onnx.tf2onnx - rewrite tensorflow graph to onnx graph """ import collections import sys import traceback import numpy as np from onnx import onnx_pb import tf2onnx import tf2onnx.onnx_opset # pylint: disable=unused-import import tf2onnx.tflite_handlers # pylint: disab...
the-stack_0_2418
import socket import json VALUE_TYPE_CONVERTER = { 'int': lambda v: int(v), 'float': lambda v: float(v), 'str': lambda v: str(v).strip(), 'boolean': lambda v: v.strip().lower() == 'true', 'json': lambda v: json.loads(v) } class Ok(object): """server ok response""" def __str__(self): ...
the-stack_0_2419
# -*- 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...
the-stack_0_2422
#!/usr/bin/env python3 import argparse import pono import smt_switch as ss from smt_switch.primops import And, BVAdd, BVSub, Equal, Ite from smt_switch.sortkinds import BOOL, BV def build_simple_alu_fts(s:ss.SmtSolver)->pono.Property: ''' Creates a simple alu transition system @param s - an SmtSolver from ...
the-stack_0_2423
import pygame from time import sleep import emoji print("{:=^70}".format("Bem-Vindo Ao Mini Jukebox")) print(""" Escolha os Artistas ou bandas abaixo para tocar uma música: (1) The Beatles (2) Pink Floyd (3) Tiny Tim (4) Nirvana (5) The Who (6) Paul McCartiney """) opUser = int(input("Digite um número da lista: ")) i...
the-stack_0_2425
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) Philipp Wagner. All rights reserved. # Licensed under the BSD license. See LICENSE file in the project root for full license information. import cPickle def save_model(filename, model): output = open(filename, 'wb') cPickle.dump(model, output) ...
the-stack_0_2426
from typing import List def convert_decimal_to_hex(dec_list: List[int]): hex_list: List[hex] = list() for dec in dec_list: hex_list.append(hex(dec)) response_data = ( { 'isResult' : True, 'code' : 'SUCCESS', 'data' : { ...
the-stack_0_2427
import websocket import socket try: import thread except ImportError: import _thread as thread import time import json import serial import serial.tools.list_ports import _thread import logging import time import datetime import serial import serial.tools.list_ports class MicroControllerConnection: """...
the-stack_0_2429
#!/usr/bin/env python # -*- coding: utf-8 -*- from utilities.models import * from honeycomb import * @db_session def load_statistics(statistic): """This function takes a string as parameter and returns a certain value, which is then displayed in the statistics bar on the url-settings page. """ if sta...
the-stack_0_2430
# (C) 2015 by Mareike Picklum (mareikep@cs.uni-bremen.de) # # 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, modif...
the-stack_0_2432
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Jan 23 10:56:33 2018 @author: barnabasnomo """ import numpy as np import random import os import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.autograd as autograd from torch.autograd import Varia...
the-stack_0_2433
import numpy as np import openpnm as op import openpnm.models.physics as pm class MeniscusTest: def setup_class(self): np.random.seed(1) self.net = op.network.Cubic(shape=[5, 1, 5], spacing=5e-5) self.geo = op.geometry.SpheresAndCylinders(network=self.net, ...
the-stack_0_2434
#!/usr/bin/env python3 import numpy as np import tensorflow as tf import morpho_dataset class Network: def __init__(self, threads, seed=42): # Create an empty graph and a session graph = tf.Graph() graph.seed = seed self.session = tf.Session(graph=graph, config=tf.ConfigProto(inte...
the-stack_0_2435
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (c) 2001, 2002, 2004, 2005 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL shou...
the-stack_0_2436
############################################################################### # # Tests for XlsxWriter. # # SPDX-License-Identifier: BSD-2-Clause # Copyright (c), 2013-2021, John McNamara, jmcnamara@cpan.org # from ..excel_comparison_test import ExcelComparisonTest from ...workbook import Workbook class TestCompar...
the-stack_0_2437
''' Created on Mar 10, 2019 @author: Burkhard A. Meier ''' import sys from PyQt5 import QtWidgets, QtGui from Section4.Designer_code.Video2_2_slots_Design import Ui_MainWindow class RunDesignerGUI(): def __init__(self): app = QtWidgets.QApplication(sys.argv) self.MainWindow = QtWidgets.QMainW...
the-stack_0_2438
""" Various tools for extracting signal components from a fit of the amplitude distribution """ from . import pdf from .Classdef import Statfit import numpy as np import time import random import matplotlib.pyplot as plt from lmfit import minimize, Parameters, report_fit def param0(sample, method='basic'): """Est...
the-stack_0_2440
# uncompyle6 version 3.3.5 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] # Embedded file name: c:\Jenkins\live\output\win_64_static\Release\python-bundle\MIDI Remote Scripts\Push2\color_chooser.py # Compiled at: 2018-11-30 15:48:11 from __futu...
the-stack_0_2444
import re, datetime from Helpers.freezable_list import FrozenDict from pytjson.Exceptions import ParseError class Datatype: # Initializer, will be overriden below TAGS = {} isScalar = re.compile(r'^[a-z0-9]*$') isBin = re.compile('^[01]{8}$') isOnlyNumbers = re.compile('^\-?(0|[1-9][0-9]*)$') i...
the-stack_0_2445
import folium import pandas import math import re data = pandas.read_excel("GVP_Volcano_List.xlsx",header = 1) map = folium.Map(tiles="Mapbox Bright") featureGroup = folium.FeatureGroup(name="Volcanoes") #Debug dumpfh = open('out.txt', 'w') lonData = data["Latitude"] latData = data["Longitude"] nameData = data["Vol...
the-stack_0_2446
# # Copyright (c) 2018 ISP RAS (http://www.ispras.ru) # Ivannikov Institute for System Programming of the Russian Academy of Sciences # # 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 # # h...
the-stack_0_2447
import abc import functools import logging import pkg_resources import six import textwrap from lymph.exceptions import Timeout, LookupFailure logger = logging.getLogger(__name__) docstring_format_vars = {k: textwrap.dedent(v).strip() for k, v in six.iteritems({ 'COMMON_OPTIONS': """ Common Options: --config=...
the-stack_0_2449
# -*- coding: utf-8 -*- from __future__ import with_statement import warnings from almost import Approximate from pytest import deprecated_call, raises from conftest import various_backends import trueskill as t from trueskill import ( quality, quality_1vs1, rate, rate_1vs1, Rating, setup, TrueSkill) warnings....
the-stack_0_2450
import itertools import json import os import random import numpy as np from gym import spaces from jsonmerge import Merger from utils.constants import * class PommermanJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.ndarray): return obj.tolist() elif is...
the-stack_0_2452
# Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this...
the-stack_0_2453
__description__ = \ """ Class for generating simulated epistasis maps with options for various distributions of values. """ __author__ = "Zach Sailer" from functools import wraps from epistasis.mapping import EpistasisMap from numpy import random class DistributionSimulation(EpistasisMap): """ Just like an ...
the-stack_0_2454
"""A transformer for gen3 project,reads genetrails_variants bcc, writes to DEFAULT_OUTPUT_DIR.""" import hashlib import os import json from gen3_etl.utils.ioutils import reader from defaults import DEFAULT_OUTPUT_DIR, DEFAULT_EXPERIMENT_CODE, DEFAULT_PROJECT_ID, default_parser, emitter, obscure_dates from gen3_etl.ut...
the-stack_0_2458
import numba import numpy as np from scipy.sparse import csr_matrix from .base import BasePointer, GraphBlasContainer from .context import handle_panic, return_error from .exceptions import GrB_Info class MatrixPtr(BasePointer): def set_matrix(self, matrix): self.instance = matrix class Matrix(GraphBla...
the-stack_0_2459
import json data_files = { 'colors.json', 'default_key_mappings.txt', 'unicode_names.json' } with open('dist-js/skulpt-designer-files.js', 'w') as output_file: for filename in data_files: with open(f'designer/data/{filename}') as data_file: data = data_file.read() lin...
the-stack_0_2460
import logging import os import re from collections import namedtuple from tigertag import Pluggable from tigertag.util import str2bool logger = logging.getLogger(__name__) FileInfo = namedtuple('FileInfo', 'name path hash temp ext_id') class Scanner(Pluggable): RESERVED_PROPS = ['NAME', 'ENABLED'] def __...
the-stack_0_2463
from . import ClientConstants as CC from . import ClientDefaults from . import ClientNetworkingContexts from . import ClientNetworkingDomain from . import ClientNetworkingJobs from . import ClientParsing from . import ClientThreading from . import HydrusConstants as HC from . import HydrusGlobals as HG from . import Hy...
the-stack_0_2464
import numpy as np from numpy import random SF = 0xF0 EF = 0x0F VAL_MIN = 0 VAL_MAX = 255 DU_LEN_MAX = 1024 NUM_OF_VECTORS = 10 VECTOR_HEADER = 'test_vectors.hpp' VECTOR_SRC = 'test_vectors.cpp' VECTOR_PY = 'test_vectors.py' vectors = [] for i in range(NUM_OF_VECTORS): du = random.randint(VAL_MIN, VAL_MAX, size...
the-stack_0_2465
import hashlib import logging import random from django.conf import settings from django.contrib.auth.models import Group from uniauth.processors import (BaseProcessor, NameIdBuilder) from . unical_attributes_generator import UnicalAttributeGenerator logger = logging.getLogger(__name_...
the-stack_0_2468
import random import pytest from conftest import get_api_data from assemblyline.common import forge from assemblyline.odm.random_data import create_users, wipe_users, create_heuristics, wipe_heuristics @pytest.fixture(scope="module") def datastore(datastore_connection): try: create_users(datastore_conn...
the-stack_0_2470
import os from ats.attributedict import AttributeDict statuses = AttributeDict() _StatusCodesAbr = dict( CREATED = "INIT", INVALID = "INVD", PASSED = "PASS", FAILED = "FAIL", SKIPPED = "SKIP", RUNNING = 'EXEC', FILTERED = 'FILT', TIMEDOUT = 'TIME', BATCHED = "BACH", HALTED = "HALT", E...
the-stack_0_2471
from distutils.version import LooseVersion import os import json import pytest import numpy as np import pandas as pd from sklearn import datasets import xgboost as xgb import matplotlib as mpl import yaml import mlflow import mlflow.xgboost from mlflow.models import Model from mlflow.models.utils import _read_example...
the-stack_0_2472
import os from dodo_commands.framework import ramda as R from dodo_commands.framework.config_io import ConfigIO class Layers: def __init__(self): self.config_io = ConfigIO() self.root_layer_path = None self.root_layer = None self.layer_by_target_path = {} self.selected_lay...
the-stack_0_2473
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. # -*- coding: utf-8 -*- """ # @Time : 2019/5/25 # @Author : Jiaqi&Zecheng # @File : train.py # @Software: PyCharm """ import time import traceback i...
the-stack_0_2476
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Contains common helpers for working with Android manifests.""" import hashlib import os import re import shlex import xml.dom.minidom as minidom from ut...
the-stack_0_2477
"""A Python Wrapper for accessing the ZeroTier API.""" import asyncio import logging import aiohttp import async_timeout from . import exceptions _LOGGER = logging.getLogger(__name__) WRITABLE_NETWORK = [ 'name', 'private', 'enableBroadcast', 'v4AssignMode', 'v6AssignMode', 'mtu', 'multi...
the-stack_0_2478
#!/usr/bin/env python import json from random import randint import momoko import tornado.ioloop import tornado.web from tornado import gen import tornado.options from tornado.options import options import tornado.httpserver from commons import JsonHandler, JsonHelloWorldHandler, PlaintextHelloWorldHandler, BaseHandler...
the-stack_0_2480
import logging import os import random import sys import time from threading import Thread from termcolor import cprint from core import OpenLeecher from kbhit import KBHit # Core class # Handles the core, can be threaded # Args : None class Core(Thread): def __init__(self): Thread.__init__(self, target...
the-stack_0_2482
import numpy as np import cv2 class UISketch: def __init__(self, img_size, img_path, scale, accu=True, nc=3): self.img_size = img_size self.scale = scale self.nc = nc if img_path is not "": self.img = cv2.imread(img_path) self.mask = cv2.imread(img_path,cv2....
the-stack_0_2483
from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpResponseRedirect, JsonResponse from django.shortcuts import get_object_or_404, render, redirect from django.urls import reverse_lazy from django.forms import formset_factory from django.views.generi...
the-stack_0_2484
# src/lyrical/ovh.py """Client for the lyrics.ovh REST API.""" from concurrent.futures import as_completed from dataclasses import dataclass from typing import List from urllib.parse import unquote, urlparse import click import desert import marshmallow import requests from requests.adapters import HTTPAdapter from re...
the-stack_0_2485
# qubit number=4 # total number=46 import pyquil from pyquil.api import local_forest_runtime, QVMConnection from pyquil import Program, get_qc from pyquil.gates import * import numpy as np conn = QVMConnection() def make_circuit()-> Program: prog = Program() # circuit begin prog += CNOT(0,3) # number=13 ...
the-stack_0_2486
#!/usr/bin/env python3 import pandas as pd import seaborn as sns import sys import matplotlib.pyplot as plt import numpy as np from macros import colors def algorithm_font(algorithm): return r'\textsf{{{}}}'.format(algorithm) def combined(algorithm, regularity): return '{}-{}'.format(algorithm, regularity)...
the-stack_0_2487
# 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 u...
the-stack_0_2488
# Copyright (c) Yugabyte, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, soft...
the-stack_0_2490
"""MCMC sampling methods.""" import logging import numpy as np logger = logging.getLogger(__name__) # TODO: combine ESS and Rhat?, consider transforming parameters to allowed # region to increase acceptance ratio def eff_sample_size(chains): """Calculate the effective sample size for 1 or more chains. Se...
the-stack_0_2492
# The MIT License (MIT) # # Copyright (c) 2016 Damien P. George (original Neopixel object) # Copyright (c) 2017 Ladyada # Copyright (c) 2017 Scott Shawcroft for Adafruit Industries # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the...
the-stack_0_2494
# *************************************************************** # Copyright (c) 2022 Jittor. All Rights Reserved. # Maintainers: # Zheng-Ning Liu <lzhengning@gmail.com> # Dun Liang <randonlang@gmail.com>. # # This file is subject to the terms and conditions defined in # file 'LICENSE.txt', which is part o...
the-stack_0_2495
import streamlit as st import pandas as pd import numpy as np import folium import geopandas import plotly.express as px from streamlit_folium import folium_static from folium.plugins import MarkerCluster from datetime import datetime st.set_page_config(layout='wide') @st.cache(allow_output_mutation=True) def get_da...
the-stack_0_2496
import asyncio import email.message import enum import inspect import json from typing import ( Any, Callable, Coroutine, Dict, List, Optional, Sequence, Set, Type, Union, ) from fastapi import params from fastapi.datastructures import Default, DefaultPlaceholder from fastapi.de...
the-stack_0_2503
import asyncio import re import subprocess import time from dataclasses import replace from pathlib import Path from typing import Any, AsyncIterator, Set from uuid import uuid4 as uuid import aiodocker import pytest from yarl import URL from neuro_sdk import CONFIG_ENV_NAME, DEFAULT_CONFIG_PATH, JobStatus from test...
the-stack_0_2506
#!/usr/bin/env python3 import sys import time import serial import minimalmodbus SERIAL_PORT = '/dev/ttyUSB0' SERIAL_SPEED = 9600 SERIAL_TIMEOUT = 0.5 SERIAL_PARITY = serial.PARITY_NONE MODBUS_DEBUG = False class SaimanEnergyMeter: """A simple class for Saiman Energy Meters (Дала СА4-Э720 П RS)""" def __ini...
the-stack_0_2507
from hub2hub import TechnicHub, ble_handler from time import sleep_ms # Initialize ble handler and a technic hub ble = ble_handler() Thub = TechnicHub(ble) # connect to a technic hub: press green button on the technic hub Thub.connect() # Servo motor connected to port A Motor = Thub.port.A.motor # move to 180 degre...
the-stack_0_2509
import time import logging from aiogram import types from aiogram.dispatcher.middlewares import BaseMiddleware HANDLED_STR = ['Unhandled', 'Handled'] class LoggingMiddleware(BaseMiddleware): def __init__(self, logger=__name__): if not isinstance(logger, logging.Logger): logger = logging.get...
the-stack_0_2510
import numpy as np from sklearn.metrics import accuracy_score from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.neural_network import MLPClassifier from sklearn.naive_bayes import BernoulliNB from sklearn.inspection import permutation_importance from sk...
the-stack_0_2511
# Copyright 2021 Open Source Robotics Foundation, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law...
the-stack_0_2512
#http://www.compaq.com/fortran/docs/ import os import sys from numpy.distutils.fcompiler import FCompiler from distutils.errors import DistutilsPlatformError compilers = ['CompaqFCompiler'] if os.name != 'posix' or sys.platform[:6] == 'cygwin' : # Otherwise we'd get a false positive on posix systems with # c...
the-stack_0_2514
import pandas as pd import matplotlib.pyplot as plt import numpy as np rbp_files = dict(snakemake.input) values = [] for rbp, f_name in rbp_files.items(): df = pd.read_csv(f_name) positives = len(df[df['class'] == 1]) negatives = len(df[df['class'] == 0]) neg_ratio = negatives / (positives + negati...
the-stack_0_2515
from unittest import TestCase from datetime import datetime from extract_ride_data import ZeroLogHeader, LogEntry, ZeroLogEntry class TestLogHeader(TestCase): def test_decode(self): log_text = '''Zero MBB log Serial number 2015_mbb_48e0f7_00720 VIN 538SD9Z37GCG06073 Firmware rev. ...
the-stack_0_2522
"""SAElections URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/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') Class...
the-stack_0_2523
#!/usr/bin/python # -*- coding: utf-8 -*- """ Documentation: Menu.py Classes and functions: Menu main class of this modul Description: the base class for the menus. All other menu classes should be derived from this one """ __author__ = "Fireclaw the Fox" __license__ = """ Simplified BSD (BSD 2-Clause)...
the-stack_0_2525
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
the-stack_0_2527
# Copyright 2017 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/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
the-stack_0_2531
import copy import numpy as np import torch from .utils.utils import get_optimizer_fn from .utils.schedule import ( PeriodicSchedule, get_schedule, ) from .agent import Agent from .dqn import legal_moves_adapter from .mlp import DistributionalMLP, ComplexMLP class RainbowDQNAgent(Agent): """An agent impl...