filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_0_5212
# Copyright 2020 The HuggingFace Team. 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...
the-stack_0_5214
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import numpy as np import os import xml.etree.ElementTree as ET from typing import List, Tuple, Union from fvcore.common.file_io import PathManager from detectron2.data import DatasetCatalog, MetadataCatalog from ...
the-stack_0_5215
from .file import read_file_upper class Solver: """ Solver for a wordsearch puzzle. Variables: directions {list} -- Two-digit permutations of [-1, 0, 1], excluding [0, 0]. """ directions = [ [ 0, -1], [-1, 0], [ 0, 1], [ 1, 0], [-1, -1], ...
the-stack_0_5216
import logging import typing import numpy as np from scipy import optimize from smac.configspace import ConfigurationSpace from smac.epm.base_gp import BaseModel from smac.epm.gp_base_prior import Prior from smac.utils.constants import VERY_SMALL_NUMBER from skopt.learning.gaussian_process.kernels import Kernel from...
the-stack_0_5217
#!/usr/bin/env python """ @package ion.agents.platform.resource_monitor @file ion/agents/platform/resource_monitor.py @author Carlos Rueda @brief Platform resource monitoring for a set of attributes having same rate """ __author__ = 'Carlos Rueda' import logging import pprint from gevent import Greenlet, sle...
the-stack_0_5220
# -*- coding: utf-8 -*- import numpy as np from PIL import Image from skimage.draw import disk import cv2 defocusKernelDims = [3,5,7,9] def DefocusBlur_random(img): kernelidx = np.random.randint(0, len(defocusKernelDims)) kerneldim = defocusKernelDims[kernelidx] return DefocusBlur(img, ke...
the-stack_0_5223
import numpy as np import random import logging import logging.config #logging.disable() logging.config.fileConfig('logging.conf') # create logger logger = logging.getLogger('simpleExample') # Setting the size of the field cells_number = 12 """ We are going to show the following path finding algorithms: Dijkstra...
the-stack_0_5224
from ethereum import utils def mk_multisend_code(payments): # expects a dictionary, {address: wei} kode = b'' for address, wei in payments.items(): kode += b'\x60\x00\x60\x00\x60\x00\x60\x00' # 0 0 0 0 encoded_wei = utils.encode_int(wei) or b'\x00' kode += utils.ascii_chr(0x5f + len(enc...
the-stack_0_5228
"""Tests for the ProtocolAnalyzer.""" import pytest from decoy import Decoy from datetime import datetime from opentrons.types import MountType, DeckSlotName from opentrons.protocol_engine import commands as pe_commands, types as pe_types from opentrons.protocol_runner import ProtocolRunner, ProtocolRunData, JsonPreAn...
the-stack_0_5229
import os import json if not os.path.exists('normal'): os.mkdir('normal') for data_type in ['train', 'dev', 'test']: with open('{}.json'.format(data_type), 'r') as f: data = json.load(f) dataset = [] for sample in data: token = sample['token'] h_pos = [sample['subj_start'], sam...
the-stack_0_5230
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: load-vgg19.py from __future__ import print_function import argparse import numpy as np import os import cv2 import six import tensorflow as tf from tensorpack import * from tensorpack.dataflow.dataset import ILSVRCMeta enable_argscope_for_module(tf.layers) def ...
the-stack_0_5232
import os class Config: SSL_REDIRECT = False @staticmethod def init_app(app): pass class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True class ProductionConfig(Config): @staticmethod def init_app(app): Config.init_app(app) ...
the-stack_0_5233
from django.contrib.auth import login, logout from django.contrib.auth.forms import AuthenticationForm from django.middleware import csrf from django.utils.translation import gettext_lazy as _ from rest_framework.authentication import SessionAuthentication from rest_framework.decorators import action from rest_framewor...
the-stack_0_5234
def extractVasaandypresWordpressCom(item): ''' Parser for 'vasaandypres.wordpress.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), (...
the-stack_0_5235
import torch from torch import nn import torch.nn.functional as F from torch.nn.modules.flatten import Flatten # Code for CIFAR ResNet is modified from https://github.com/itchencheng/pytorch-residual-networks class FashionMNIST(nn.Module): def __init__(self): super().__init__() self.net = nn.Se...
the-stack_0_5236
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.4.1 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- #...
the-stack_0_5238
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
the-stack_0_5239
from random import randint as r from time import sleep as s print("This is a story about an ant") sugar = 0 bank = 5_000_000 chocolate = 0 chocoxplode = 0 cost = 0 def intro(sugar, bank, chocolate, chocoxplode, cost): s(2) print("\nIt is a true story\n") s(2) print(f'Your sugar balance is {sugar}') s(2) ...
the-stack_0_5240
from backend.improvements.seastead import Seastead import pytest @pytest.fixture(scope="function") def setup_improvement(): imp = Seastead() return imp # Init testdata = [ ('food', 2), ('production', 0), ('gold', 0), ('science', 0), ('culture', 0), ('faith', 0), ('housing', 2), ...
the-stack_0_5241
# Copyright 2011 OpenStack Foundation # 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 requ...
the-stack_0_5243
import os import os.path import sys import unittest from subprocess import Popen from subprocess import PIPE class TestRun(unittest.TestCase): maxDiff = None def setUp(self): self.cwd = os.getcwd() os.chdir(os.path.dirname(__file__)) def tearDown(self): os.chdir(self.cwd) d...
the-stack_0_5244
''' Coding our First Game in PyGame - Cheat Codes and HomeScreen in PyGame ''' import pygame import random pygame.init() # print(x) # All 6 pygame modules successfully imported # Colors white = (255, 255, 255) red = (255, 0, 0) black = (0, 0, 0) # Creating Game Window screen_width = 900 screen_height =...
the-stack_0_5246
import cv2 import numpy as np from skimage.measure import compare_ssim as ssim def get_mse_psnr(x, y): if x.ndim == 4: mse_list = [] psnr_list = [] data_len = len(x) for k in range(data_len): img = x[k] ref = y[k] mse = np.mean((img - ref) ** 2) ...
the-stack_0_5247
import os import socket def getIP(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 1)) return s.getsockname()[0] lsquic_dir = os.path.expanduser('~/oqs/lsquic') #key_crt_dir = os.path.expanduser('~/SERVER_RSA_FILES/key_crt.pem') #key_srv_dir = os.path.expanduser('~/SERVER_RSA_FILES/ke...
the-stack_0_5249
"""Support for deCONZ lights.""" from __future__ import annotations from pydeconz.group import DeconzGroup as Group from pydeconz.light import ( ALERT_LONG, ALERT_SHORT, EFFECT_COLOR_LOOP, EFFECT_NONE, Light, ) from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP,...
the-stack_0_5250
from typing import List, Tuple from mock import Mock from synapse.events import EventBase from synapse.federation.sender import PerDestinationQueue, TransactionManager from synapse.federation.units import Edu from synapse.rest import admin from synapse.rest.client.v1 import login, room from tests.test_utils import e...
the-stack_0_5251
#!/usr/bin/env python3 # Copyright (c) 2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test descriptor wallet function.""" from test_framework.test_framework import VIDCoinTestFramework from tes...
the-stack_0_5256
from subprocess import call from os import path import hitchpostgres import hitchselenium import hitchpython import hitchserve import hitchredis import hitchtest import hitchsmtp # Get directory above this file PROJECT_DIRECTORY = path.abspath(path.join(path.dirname(__file__), '..')) class ExecutionEngine(hitchtest...
the-stack_0_5258
import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init class View(nn.Module): def __init__(self, size): super(View, self).__init__() self.size = size def forward(self, tensor): return tensor.view(self.size) class VAE(nn.Module): """Encode...
the-stack_0_5260
try: import matplotlib.pyplot as plt except: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt def plot_no_player_aces(q): fig, axis = plt.subplots(3, 6, sharey=True) fig.suptitle('Player Hand Values (No Aces) vs Dealer First Card Value', fontsize=10) size = 5 f...
the-stack_0_5262
import math tcase = int(input()) while(tcase): num = int(input()) lst = [] while(num / 10 != 0): lst.append(num % 10) num = math.floor(num / 10) print(lst[0] + lst[-1]) tcase -= 1
the-stack_0_5263
# Copyright (c) Facebook, Inc. and its affiliates. import itertools import logging from typing import Dict, List import torch from detectron2.config import configurable from detectron2.layers import ShapeSpec, batched_nms_rotated, cat from detectron2.structures import Instances, RotatedBoxes, pairwise_iou_rotated from...
the-stack_0_5265
from spaceone.core.service import * from spaceone.identity.manager import DomainManager from spaceone.identity.manager.domain_secret_manager import DomainSecretManager from spaceone.identity.model import Domain @authentication_handler(exclude=['create', 'list', 'get_public_key']) @authorization_handler(exclude=['crea...
the-stack_0_5270
#!/usr/bin/env python # -*- coding: utf-8 # Functions dealing with image cropping import logging import numpy as np from .image import Image, zeros_like logger = logging.getLogger(__name__) class BoundingBox(object): def __init__(self, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None): ...
the-stack_0_5272
# Copyright 2014 Google 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, ...
the-stack_0_5273
# Copyright (c) Chris Choy (chrischoy@ai.stanford.edu) and Wei Dong (weidong@andrew.cmu.edu) # # Please cite the following papers if you use any part of the code. # - Christopher Choy, Wei Dong, Vladlen Koltun, Deep Global Registration, CVPR 2020 # - Christopher Choy, Jaesik Park, Vladlen Koltun, Fully Convolutional Ge...
the-stack_0_5274
import sys import socket import threading import time server_ip_address = sys.argv[1] server_port = int(sys.argv[2]) users = int(sys.argv[3]) type_of_test = sys.argv[4] tests = 32 output_array = [] output = open(type_of_test+"_"+str(tests)+"_"+str(users)+".txt", 'w') def writer(output_array): for l...
the-stack_0_5277
"""This module contains the general information for FabricFcEstcCloud ManagedObject.""" from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class FabricFcEstcCloudConsts: pass class FabricFcEstcCloud(ManagedObject): """This is FabricFcEstc...
the-stack_0_5279
""" 封装文件操作: ● 递归读取所有文件目录形成列表 ● 递归删除空目录 ● 批量删除文件 """ import os def get_all_files(targetDir): """ 递归读取所有文件目录形成列表 :param targetDir: :return: """ files = [] listFiles = os.listdir(targetDir) for i in range(0, len(listFiles)): path = os.path.join(targetDir, listFiles[i]) ...
the-stack_0_5280
#!/usr/bin/env python # coding=utf-8 # Copyright (C) 2018 Copter Express Technologies # # Author: Oleg Kalachev <okalachev@gmail.com> # # Distributed under MIT License (available at https://opensource.org/licenses/MIT). # The above copyright notice and this permission notice shall be included in all # copies or substa...
the-stack_0_5281
#!/usr/bin/env python # Copyright 2012 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Uses different APIs to touch a file.""" import os import sys BASE_DIR = os.path.dirname(os.path.abspath( __file__....
the-stack_0_5282
""" Copyright (c) 2019-2022, Zihao Ding/Carnegie Mellon University All rights reserved. ******************************************************************** Project: imgprocess.py MODULE: util Author: Zihao Ding, Carnegie Mellon University Brief: ------------- Image processing func Date: ------------- 2022/03/17 ...
the-stack_0_5283
# -*- coding: utf-8 -*- # # 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_5285
# -*- coding: utf-8 -*- import functools from mock import Mock from bravado_core.model import _post_process_spec from bravado_core.spec import Spec def test_empty(): swagger_spec = Spec({}) callback = Mock() _post_process_spec( spec_dict=swagger_spec.spec_dict, spec_resolver=swagger_spec...
the-stack_0_5286
import unittest from mock import patch, Mock import pytest from nose.tools import * # noqa (PEP8 asserts) from admin.rdm_addons.utils import get_rdm_addon_option from osf_tests.factories import ( fake_email, AuthUserFactory, InstitutionFactory, ExternalAccountFactory, UserFactory, ProjectFac...
the-stack_0_5288
# Copyright Contributors to the Rez project # # 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 ...
the-stack_0_5289
# Copyright 2010 Chet Luther <chet.luther@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
the-stack_0_5291
# This is how we set compiler options globally - we define them here, import # this variable in every build file that has C code, and then set copts on every # target manually. This is clumsy, but it's also very simple. There will # probably be an easier way to do this in the future. # # See Bazel discussion: https://g...
the-stack_0_5293
import os import sys sys.path.insert(0, os.getcwd()) import time import glob import numpy as np import random import torch import darts.cnn.utils as utils import logging import torch.nn as nn import darts.cnn.genotypes import torch.utils import torchvision.datasets as dset import torch.backends.cudnn as cudnn from coll...
the-stack_0_5294
# -*- coding: utf-8 -*- """Utility methods for list objects. AUTHORS: - Thomas McTavish """ # While this software is under the permissive MIT License, # (http://www.opensource.org/licenses/mit-license.php) # We ask that you cite the neuronpy package (or tools used in this package) # in any publications and contact th...
the-stack_0_5296
# Adaptation of the original code from # https://github.com/idiap/fast-transformers/blob/master/fast_transformers/causal_product/__init__.py # Copyright (c) 2020 Idiap Research Institute, http://www.idiap.ch/ # Written by Angelos Katharopoulos <angelos.katharopoulos@idiap.ch>, # Apoorv Vyas <avyas@idiap.ch> # # Modific...
the-stack_0_5297
# Copyright (c) 2014 Clinton Knight. 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 requir...
the-stack_0_5300
#!/usr/bin/env python # -*- coding: utf-8 -*- '''Harmonic calculations for frequency representations''' import numpy as np import scipy.interpolate import scipy.signal from ..util.exceptions import ParameterError __all__ = ['salience', 'interp_harmonics'] def salience(S, freqs, h_range, weights=None, aggregate=None...
the-stack_0_5302
import logging from sklearn.base import BaseEstimator, TransformerMixin from sklearn.feature_selection import SelectKBest, chi2 import numpy as np from sklearn.feature_selection.univariate_selection import _clean_nans from discoutils.thesaurus_loader import Vectors from eval.utils.misc import calculate_log_odds, update...
the-stack_0_5304
import sys,tweepy,csv,re from textblob import TextBlob import matplotlib.pyplot as plt #alteration class SentimentAnalysis: def __init__(self): self.tweets = [] self.tweetText = [] def DownloadData(self): # authenticating consumerKey = 'qBIngtySLGxbyw6eo4Ihqxz2K' consu...
the-stack_0_5306
# manage.py import os import unittest import coverage from flask_script import Manager from flask_migrate import Migrate, MigrateCommand COV = coverage.coverage( branch=True, include='project/*', omit=[ 'project/tests/*', 'project/server/config.py', 'project/serve...
the-stack_0_5307
# pylint: disable=unused-import """ UBX Protocol Input payload definitions THESE ARE THE PAYLOAD DEFINITIONS FOR _SET_ MESSAGES _TO_ THE RECEIVER (e.g. configuration and calibration commands; AssistNow payloads) Created on 27 Sep 2020 Information sourced from u-blox Interface Specifications © 2013-2021, u-blox AG :...
the-stack_0_5308
# Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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_5310
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.core.db import db from indico.core.db.sqlalchemy.util.models import get_simple_column_attrs fr...
the-stack_0_5313
#!/usr/bin/env python3 import argparse import glob import json import logging import os import shlex import subprocess from pathlib import Path def runBazelBuildForCompilationDatabase(bazel_options, bazel_targets): query_targets = ' union '.join(bazel_targets) query = ' union '.join( q.format(query_targets...
the-stack_0_5314
# -*- coding: utf-8 -*- """ Created on Mon Mar 14 14:34:24 2022 @author: Manuel Huber """ import os.path import multiprocessing from multiprocessing import Process, Manager import ee import geemap import numpy as np Map = geemap.Map() import matplotlib.pyplot as plt from colour import Color #from ...
the-stack_0_5316
"""Templates for the policy_sentry YML files. These can be used for generating policies """ ACTIONS_TEMPLATE = """mode: actions name: '' actions: - '' """ CRUD_TEMPLATE = """mode: crud name: '' # Specify resource ARNs read: - '' write: - '' list: - '' tagging: - '' permissions-management: - '' # Skip resource constra...
the-stack_0_5317
from textstyle.en.stylometry.style_features import get_basic_style_features def test_get_basic_style_features(): text_corpus = [ "I like to eat broccoli and bananas.", "I ate a banana and spinach smoothie for breakfast.", "Chinchillas and kittens are cute.", "My sister adopted a ki...
the-stack_0_5322
import torch import torchvision.transforms as transforms import torchvision.datasets as datasets import torch.nn as nn import torch.nn.functional as F import numpy as np from matplotlib import pyplot as plt from DataLoaders import MNIST_Loaders from Network import Net import utils import AttackTools import optimizers ...
the-stack_0_5323
from argparse import ArgumentParser def parse_args(): parser = ArgumentParser( description='Kube-Hunter - hunts for security ' 'weaknesses in Kubernetes clusters') parser.add_argument( '--list', action="store_true", help="Displays all tests in kubehunter " ...
the-stack_0_5324
""" ========================================================================= BlockingCacheFL.py ========================================================================= A function level cache model which only passes cache requests and responses to the memory Author: Eric Tang (et396), Xiaoyu Yan (xy97) Date: 23 ...
the-stack_0_5325
#!/usr/bin/python # -*- coding: utf-8 -*- """ skeleton code for k-means clustering mini-project """ import pickle import numpy import matplotlib.pyplot as plt import sys sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit def Draw(pred, features, poi, mark_poi=False, name=...
the-stack_0_5327
import logging from django.contrib import messages from django.core.exceptions import PermissionDenied from django.db import transaction from django.shortcuts import get_object_or_404 from django.template import RequestContext from django.urls import reverse, reverse_lazy from django.utils.translation import ugettext_...
the-stack_0_5328
import face_detection.video_receiver as video_receiver import face_detection.face_detector as face_detector import configuration.general_settings as settings from model.vgg_adapted_model import FaceAnalyserModel def main(): # Initialize model model = FaceAnalyserModel(settings.model_weights_path) # Init...
the-stack_0_5329
from core.advbase import * from slot.a import * from slot.d import* def module(): return Summer_Ranzal class Summer_Ranzal(Adv): a1 = ('lo',0.4) a3 = ('primed_defense', 0.08) conf = {} conf['slots.a'] = Resounding_Rendition() + Breakfast_at_Valerios() conf['slots.frostbite.a'] = Primal_Crisis...
the-stack_0_5331
import os from setuptools import find_packages, setup from pufsim import version # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) # load readme file with open('README.rst') as readme: README = readme.read() # stamp the package prior to instal...
the-stack_0_5336
import dash_html_components as html import dash_bootstrap_components as dbc import dash_core_components as dcc # local imports from load_data import ( income_distribution_dropdown_values, median_income_dropdown_values ) # we use the Row and Col components to construct the sidebar header # it consists of a ti...
the-stack_0_5338
from __future__ import absolute_import from __future__ import division from __future__ import print_function # Imports import tensorflow as tf import time # Deopout rate RATE_DROPOUT = 0.5 def small_cnn(x, phase_train): # Dense Layer pool2_flat = tf.reshape(x, [-1, 4 * 4 * 64]) dense = tf.layers.dense(in...
the-stack_0_5339
# $Id: fact_base.py 081917d30609 2010-03-05 mtnyogi $ # coding=utf-8 # # Copyright © 2007-2008 Bruce Frederiksen # # 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, inclu...
the-stack_0_5340
# -*- coding: utf-8 -*- """ Created on Thu Sep 30 00:06:41 2021 @author: qizhe """ class Solution: def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int: """ 和答案一模一样,巧妙的地方在于充分利用了max min 的作用,从而考虑了各种情况 用时10min """ Area1 =...
the-stack_0_5341
load("@io_bazel_rules_go//go:def.bzl", "GoLibrary") load("@io_bazel_rules_go//go/private:mode.bzl", "get_mode") go_filetype = ["*.go"] def _compute_genrule_variables(resolved_srcs, resolved_outs): variables = {"SRCS": cmd_helper.join_paths(" ", resolved_srcs), "OUTS": cmd_helper.join_paths(" ", resol...
the-stack_0_5342
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import functools import glob import json import logging import multiprocessing as mp import numpy as np import os from itertools import chain import pycocotools.mask as mask_util from PIL import Image from detectron2.structures import BoxMode from ...
the-stack_0_5343
# qubit number=3 # total number=12 import numpy as np from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ import networkx as nx from qiskit.visualization import plot_histogram from typing import * from pprint import pprint from math import log2 from collectio...
the-stack_0_5346
# Echo server program import socket from time import ctime import os def psend(conn, prompt, data): conn.sendall(('[%s] %s' % (prompt, data.decode()) ).encode()) HOST = '' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-previleged port with socket.socket(socket.A...
the-stack_0_5347
"""DjPra1 URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/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 ...
the-stack_0_5348
#!/usr/bin/env python3 import sys from model import ModelW2W sys.path.extend(['..']) import tensorflow as tf from tensorflow.python.ops.rnn_cell import LSTMCell from tfx.bricks import embedding, rnn, rnn_decoder, dense_to_one_hot, brnn class Model(ModelW2W): def __init__(self, data, FLAGS): super(Mode...
the-stack_0_5349
from typing import Any, Dict, List, Optional, Tuple, Type, Union import gym import numpy as np import torch as th from torch.nn import functional as F from stable_baselines3.common import logger from stable_baselines3.common.noise import ActionNoise from stable_baselines3.common.off_policy_algorithm import OffPolicyA...
the-stack_0_5350
#!/usr/bin/python # # Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. # """This file contains code to support the hitless image upgrade feature.""" import argparse from builtins import object from builtins import str import copy from datetime import timedelta import re import sys import traceback sys...
the-stack_0_5352
# qubit number=4 # total number=38 import cirq import qiskit from qiskit.providers.aer import QasmSimulator from qiskit.test.mock import FakeVigo from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import ...
the-stack_0_5353
import pathlib from unittest import mock from unittest.mock import MagicMock import pytest from aiohttp import web from aiohttp.web_urldispatcher import SystemRoute @pytest.mark.parametrize( "show_index,status,prefix,data", [pytest.param(False, 403, '/', None, id="index_forbidden"), pytest.param(True, ...
the-stack_0_5355
# -*- coding: utf-8 -*- """Module scanning for the ROBOT vulnerability Refer to CVE-2017-13099, etc. Padding oracle for RSA-based key transport, refer to https://robotattack.org """ # import basic stuff import math # import own stuff import tlsmate.msg as msg import tlsmate.plugin as plg import tlsmate.tls as tls im...
the-stack_0_5356
from discord.ext import commands from lxml import html import aiohttp import asyncio import discord class google: """ Google search """ def __init__(self,bot): self.bot = bot @commands.command() async def g(self,ctx,*,qstr:str): """ Perform a google search """ p = {"q":qstr,"safe":"on...
the-stack_0_5357
import clr import sys sys.path.append('C:\Program Files (x86)\IronPython 2.7\Lib') import os import math clr.AddReference('acmgd') clr.AddReference('acdbmgd') clr.AddReference('accoremgd') # Import references from AutoCAD from Autodesk.AutoCAD.Runtime import * from Autodesk.AutoCAD.ApplicationServices import * from Aut...
the-stack_0_5358
# coding=utf-8 import numpy as np from pyhsmm.models import _HMMGibbsSampling, _HMMEM, _HMMMeanField from pyhsmm.internals.initial_state import UniformInitialState from autoregressive.models import _ARMixin from autoregressive.util import AR_striding from pyslds.models import _SLDSGibbsMixin, _SLDSVBEMMixin, _SLDSMe...
the-stack_0_5359
# 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 appli...
the-stack_0_5360
""" Unit tests cases. Copyright (c) 2003 Colin Stewart (http://www.owlfish.com/) 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...
the-stack_0_5362
# 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_5364
import argparse from typing import Tuple import albumentations as A from albumentations.pytorch.transforms import ToTensorV2 import torchvision from torch.utils.data import Dataset from pytorch_lightning import Trainer from pytorch_lightning.callbacks import ModelCheckpoint from deepext_with_lightning.callbacks impo...
the-stack_0_5366
import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_hosts_file(host): f = host.file('/etc/hosts') assert f.exists assert f.user == 'root' assert f.group == 'root' def t...
the-stack_0_5367
from ..sdoc import ( SLine, SAnnotationPush, SAnnotationPop, ) from ..syntax import Token from ..render import as_lines from ..utils import rfind_idx _COLOR_DEPS_INSTALLED = True try: from pygments import token from pygments import styles except ImportError: _COLOR_DEPS_INSTALLED = False else: ...
the-stack_0_5368
# [SublimeLinter @python:3] # -*- coding: utf-8 -*- from __future__ import unicode_literals, division, print_function, absolute_import import threading import win32api import win32con import win32gui class drag_accept_files(object): def __init__(self, wnd, callback): super(drag_accept_files, self).__in...
the-stack_0_5369
#!/usr/bin/env python3 # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 r""" TileLink-Uncached Lightweight Xbar generator """ import argparse import logging as log import sys from pathlib import Path import hjson import...
the-stack_0_5370
import os from urllib.request import urlretrieve import pandas as pd FREMONT_URL = 'https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD' def get_fremont_data(filename='Fremont.csv', url=FREMONT_URL, force_download=False): """Download and cache the fremont data Parameters ========== ...
the-stack_0_5371
"""Class for Braava devices.""" import logging from homeassistant.components.vacuum import SUPPORT_FAN_SPEED from .irobot_base import SUPPORT_IROBOT, IRobotVacuum _LOGGER = logging.getLogger(__name__) ATTR_DETECTED_PAD = "detected_pad" ATTR_LID_CLOSED = "lid_closed" ATTR_TANK_PRESENT = "tank_present" ATTR_TANK_LEVE...
the-stack_0_5373
""" Author: Daisuke Oyama Tests for normal_form_game.py """ from __future__ import division import numpy as np from numpy.testing import assert_array_equal from nose.tools import eq_, ok_, raises from quantecon.game_theory import ( Player, NormalFormGame, pure2mixed, best_response_2p ) # Player # class TestP...