content stringlengths 5 1.05M |
|---|
# Copyright 2020 The TensorFlow Quantum 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... |
import copy
import pytest
import os
import yaml
import numpy.testing as npt
from pyam import iiasa
# check to see if we can do online testing of db authentication
TEST_ENV_USER = 'IIASA_CONN_TEST_USER'
TEST_ENV_PW = 'IIASA_CONN_TEST_PW'
CONN_ENV_AVAILABLE = TEST_ENV_USER in os.environ and TEST_ENV_PW in os.environ
C... |
import os
import tqdm
import requests
import importlib
import sys
def http_get(url, path):
"""
Downloads a URL to a given path on disc
"""
if os.path.dirname(path) != '':
os.makedirs(os.path.dirname(path), exist_ok=True)
req = requests.get(url, stream=True)
if req.status_... |
from django.utils.safestring import mark_safe
from jinja2 import Markup
from canvas import template
from canvas.templatetags.helpers import TemplateComment
from canvas.templatetags.jinja_base import (global_tag, filter_tag, render_jinja_to_string,
jinja_context_tag, update_c... |
##Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
##Suppose the following input is supplied to the program:
##34,67,55,33,12,98
##Then, the output should be:
##['34', '67', '55', '33', '12', '98']
##('34', '67', '55', '33... |
print("Digite dois numeros: ")
x = int(input())
y = int(input())
while x != y:
if x < y:
print("Crescente")
else:
print("Decrescente")
print("Digite outos dois numeros: ")
x = int(input())
y = int(input())
|
#!/usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:liruihui
@file: config_cls.py
@time: 2019/09/17
@contact: ruihuili.lee@gmail.com
@github: https://liruihui.github.io/
@description:
"""
import argparse
import os
def str2bool(x):
return x.lower() in ('true')
def check_folder(dir):
if not os.path.... |
import datetime
import os
from easy_thumbnails.conf import Settings as ThumbnailSettings
import raven
def gettext_noop(s):
return s
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SITE_ROOT = os.path.dirname(PROJECT_DIR)
ENV = 'production'
DEBUG = False
ADMINS = (
('Rafael Kamas... |
import collections
import json
import logging
import sys
import regex as re
import requests
import discord
log = logging.getLogger(__name__)
class ActionParser:
bot = None
@staticmethod
def parse(raw_data=None, data=None):
from greenbot.dispatch import Dispatch
if not data:
... |
from pprint import pprint
# Default Configs for training
# NOTE that, config items could be overwriten by passing argument through command line.
# e.g. --voc-data-dir='./data/'
class Config:
# data
#voc_data_dir = '/home/cy/.chainer/dataset/pfnet/chainercv/voc/VOCdevkit/VOC2007/'
voc_data_dir = '/home/zy... |
# -*- coding: UTF-8 -*-
import datetime
import logging
import re
import traceback
import simplejson as json
import sqlparse
from django.contrib.auth.decorators import permission_required
from django.core.exceptions import PermissionDenied
from django.db import transaction
from django.db.models import Q
from django.htt... |
import collections
from copy import deepcopy
from robosuite.models.world import MujocoWorldBase
from robosuite.models.tasks import UniformRandomSampler
from robosuite.models.objects import MujocoGeneratedObject, MujocoXMLObject
from robosuite.utils.mjcf_utils import new_joint, array_to_string
class ManipulationTask(... |
# Generated by Django 3.0.9 on 2020-09-19 16:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quotations', '0004_auto_20200919_1002'),
]
operations = [
migrations.AddField(
model_name='quotation',
name='company... |
"""Yielding and Generators"""
import math
class FactIter:
"""Factorial iterator"""
def __init__(self, n):
self._n = n
self._i = 0
def __iter__(self):
return self
def __next__(self):
if self._i >= self._n:
raise StopIteration
else:
resu... |
import bpy
from bpy.utils import register_class, unregister_class
from bpy.types import Operator
class DrawBrushBlendToggle(Operator):
bl_label = "Set Weight Paint Brush"
bl_idname = "brush.draw_brush_blend_toggle"
bl_description = "Toggle between Draw Brush Add and Sub blend types"
bl_options = {'REGIST... |
import sys
N = int(sys.stdin.readline())
arr = [int(sys.stdin.readline()) for _ in range(N)]
arr.sort()
for a in arr:
print(a) |
import pandas as pd
import matplotlib.pyplot as plt
import statsmodels.api as sm
import scipy.stats as stats
import seaborn as sns
import sys
if len(sys.argv) < 2:
raise Exception('missing file argument')
filename = sys.argv[1]
print("Please wait while importing and cleaning the data...")
# we rea... |
import numpy as np
def mediapipe2openpose(keypoints):
mp_idx = MediaPipeSkeleton().keypoint2index
op_skel = OpenPoseSkeleton()
op_idx = op_skel.keypoint2index
op_kpts = np.zeros((len(keypoints), op_skel.keypoint_num, 2))
op_kpts[:,op_idx['Nose']] = keypoints[:,mp_idx['Nose']]
op_kpts[:... |
final_number = int(input("Enter an integer number: "))
for number in range (1, final_number + 1, 3):
print(number) |
from .base_error_code import BaseErrorCode
# ===================================================================
# Dicom Reading Related Exceptions
# ===================================================================
class BaseError(Exception):
def __init__(self, error_msg):
super().__init__(error_msg)
... |
# -- Imports ------------------------------------------------------------------
# base
import itertools
# third party
import numpy as np
from nltk.metrics.distance import edit_distance
# -- Definitions --------------------------------------------------------------
class EditDistance:
"""
Part of the auto-g... |
import hashlib
import json
import pathlib
from collections import defaultdict
from dataclasses import dataclass
from itertools import chain
from typing import ClassVar, Dict, List, Literal, Optional, Sequence, Set, Tuple
from pydantic import BaseModel, Field
from conda_lock.common import ordered_union
from conda_loc... |
"""
This file configers logging for the project.
In a file where you would like to use logging.
import logging
log = logging.getLogger(<name_of_logger>)
Setting <name_of_logger> to console logger will log to the console
Setting it to tracking_logger or main_logger will log to those files.
New loggers can also be set ... |
def check_goldbach_for_num(n, primes_set):
primes_set = sorted(primes_set)
left = 0
right = len(primes_set) - 1
index_s = None
index_b = None
while left <= right:
mid = (left + right) // 2
if n == primes_set[mid]:
return "number is prime"
elif right == left:
... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 15 00:51:31 2020
@author: Dilay Ercelik
"""
# Practice
# Return the number of even ints in the given array.
# Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
# Examples:
## count_evens([2, 1, 2, 3, 4]) → 3
## count_evens([2, 2, 0]... |
# -*- coding: utf-8 -*-
# Copyright © 2013 Jens Schmer, Michael Engelhard
from Move import Move
from random import choice
import sys
class Player(object):
def generate_move(self, game):
pass
def process_opponent_move(self, move):
pass
def process_result(self, result):
pass
class H... |
import os
import os.path
import shutil
import subprocess
import sys
def run(*args, **kwargs):
error_code = subprocess.call(*args, **kwargs)
if error_code != 0: # an error happened
sys.exit(error_code)
if os.path.isdir("./output"):
shutil.rmtree("./output")
if os.path.isdir("./temp"):
shutil.r... |
#This is an example Python script for calculating the volume of a right angle cylinder
print(2 * '\n') #lank lines
print(" Volume of Cylinder Calculator")
print(2 * '\n')
print(" 'Ent... |
from src.config_env import config_env
config = config_env.config() |
import matplotlib.pyplot as plt
import random
import numpy as np
# region train_regression
def train_regression(nn):
print(f"-----{nn.__name__}: Regression-----")
class MyNet(nn.Module):
def __init__(self, input_dim, out_dim):
super().__init__()
self.input_dim = input_dim
... |
from arch_servit import main
def test():
pass
def test2():
pass
|
from .context import rubik_solver
from .context import available_moves
import numpy as np
import unittest
benchmark_scrambles = [
("F' D U' L2 B2 D2 B2 D B F U L2 R2 B2 U' L F' D U2 F' D2 U L U' B' U' B2 U R2 U",
np.array([ 1, 2, 0, 1, 2, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1]),
np.array([ 7, 1, 4,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MIT License
#
# Copyright (c) 2018 Miha Purg <miha.purg@gmail.com>
#
# 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, ... |
# Copyright 2015 The TensorFlow 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... |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 22 10:47:42 2015
@author: dgevans
"""
import numpy as np
from scipy.interpolate import UnivariateSpline
class interpolate_wrapper(object):
'''
Wrapper to interpolate vector function
'''
def __init__(self,F):
'''
Inits with array of interpo... |
"""Animals Cog"""
import discord
from discord.ext import commands
class Animals(commands.Cog):
"""Sends a random cute picture of animals"""
def __init__(self, bot):
self.bot = bot
@commands.command(aliases=["kitty"], extras={"image": "https://i.imgur.com/J8vTsyK.gif"})
async def cat(self, ct... |
from ..callable import CALLABLE
class CALLBACK(CALLABLE):
def __init__(self):
pass
def call(self, loss):
pass |
from .crossref import CrossrefSource
from .meta import MetaSource
from .isbn import ISBNSource
from .datacite import DataCiteSource
SOURCES = [DataCiteSource, CrossrefSource, MetaSource, ISBNSource]
|
from django.apps import AppConfig
class MysettingsConfig(AppConfig):
name = 'mysettings'
|
#!/usr/bin/env python3
from processor.argparse import ArgumentParser
parser = ArgumentParser(log_dir=None, log_stem=None)
parser.add_argument("-n", default=2.0, type=float, help="Timeout between reporting")
parser.add_argument("--ip", default="127.0.0.1", help="Select an ip address")
parser.add_argument(
"--port"... |
# Copyright 2016 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.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import datetime
import mock
from google.appen... |
from __future__ import print_function, absolute_import
import argparse
def init_parser():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
# ************************************************************
# Datasets
# ********************************... |
def is_isogram(string):
char_only = ''
s = string.lower()
for c in s:
if c.isalpha():
char_only += c
if len(''.join(char_only)) == len(''.join(set(char_only))):
return True
else:
return False
|
# File to compute optimal LMP dispatch from load data and tariff rate pricing
# Kevin Moy, 11/3/2020
import cvxpy as cp
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# Import load and tariff rate data; convert to numpy array and get length
df = pd.read_csv("d... |
"""The sqlite model for a Movie."""
from sqlalchemy import Column, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.types import (
Boolean,
DateTime,
String,
)
from pornhub.db import base
class Clip(base):
"""The sqlite model for a Movie."""
__tablename__ = 'movie'
viewkey... |
"""
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 use this ... |
import logging
import re
from dls_ade import Server
from dls_ade import module_template as mt
from dls_ade import module_creator as mc
from dls_ade.exceptions import ParsingError
base_ioc_name_err_message = (
"IOC name should be of the form:\n"
" <Domain>/<Domain>-<Technical area>-IOC-<Number> or <Domain>/BL... |
from cherrypy.test import test
test.prefer_parent_path()
import md5, sha
import cherrypy
from cherrypy.lib import httpauth
def setup_server():
class Root:
def index(self):
return "This is public."
index.exposed = True
class DigestProtected:
def index(self):
re... |
#
# Copyright (c) 2015-2020 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from fm_api import constants as fm_constants
from fm_api import fm_api
import json
from six.moves import http_client as httplib
from nfv_common import debug
import nfv_common.alarm.handlers.v1 as alarm_handlers_v1
import nf... |
def damage(controller):
from bge import logic
# The health bar is in a different scene, so the scene must be found before the health bar can be found
scenes = logic.getSceneList()
for item in scenes:
if (item.name == "Overlay"):
# Make healthBar refer to the health bar object which i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
words = input("Введите предложение: ")
a = len(words)
s = 2
while s <= a:
words = words.replace(words[s], 'а')
s += 3
print(words)
|
#=========================================================================
# DORYMeshRouteUnitCL.py
#=========================================================================
# Cycle level implementation of a Y-DOR route unit.
#
# Author : Yanghui Ou
# Date : May 21, 2019
from directions import *
from pymtl3 import ... |
a = int(input())
for x in range(1,a+1):
if x % 2 != 0:
print(x)
|
'''
Done up to structured_code stage
'''
# from imp import reload
# import numpy as np
from VZcomp import utils
from VZcomp import representations as rep
# read file
lines = utils.list_from_file('omalley.qasm')
# get qumis representation
code_qumis = rep.qumis(lines=lines, n_qubits=2)
# transform to structured
utils.s... |
# Generated by Django 2.2.27 on 2022-03-28 09:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('osquery', '0012_auto_20220329_0642'),
]
operations = [
migrations.AddField(
model_name='pack',
name='event_routing_... |
import unittest
from pythark import Block
class TestBlock(unittest.TestCase):
def test_get_block(self):
block = Block()
resp = block.get_block("570934191207974498")
self.assertEqual(resp["success"], True)
def test_get_blocks(self):
block = Block()
resp = block.get_bloc... |
import sys
import re
def main():
fname = sys.argv[1]
file = open(fname)
good_line = re.compile(r"^.*\&.*\\$")
out_csv = ""
delimiters = r"&", r"$\pm$"
regexPattern = "|".join(map(re.escape, delimiters))
for line in file.readlines():
match = good_line.match(line.rstrip())
... |
def grace_from_params(params):
import horovod.tensorflow as hvd
world_size = hvd.size()
comp = params.get('compressor', 'none')
mem = params.get('memory', 'none')
comm = params.get('communicator', 'allreduce')
if comp == 'adaq':
from grace_dl.tensorflow.compressor.adaq import Adaq... |
from .fileview import FileView, FileViewModel
import csv
from .model import Model
class CSVView(FileView):
def __init__(self, filestream, delimiter=';', lineterminator='\n'):
super(CSVView, self).__init__(filestream=filestream)
self.delimiter = delimiter
self.lineterminator = lineterminato... |
print(inst.query('*IDN?'))
print(inst.query('*OPT?').split(','))
Keysight Technologies,N9030B,
['"550', 'B25', 'DP2', 'EP1', 'EXM', 'FS1', 'FS2', 'FSA', 'LFE', 'NF2', 'NUL', 'PFR', 'RTL', 'SSD', 'PC6', 'W7X', 'MTU"']
for q in [
'*IDN?',
# '*CAL?',
':FORM?',
':INST:SEL?',
# ':SENS:FREQ:STAR?',
... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from jax import lax
import jax.numpy as jnp
from numpyro.distributions.constraints import real_vector
from numpyro.distributions.transforms import Transform
from numpyro.util import fori_loop
def _clamp_preserve_gradients(x, min, ma... |
from django.http import HttpResponse
from django.urls import path
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from applications.blog import views
from applications.blog.apps import BlogConfig
from applications.blog.models import Post
app_name = BlogConfig.label
urlpatterns = [... |
import binascii
import codecs
import os
from io import BytesIO
from typing import Dict, Iterable, Optional, Sequence, Tuple, Union
from .fields import _TYPE_FIELD_VALUE_TUPLE, RequestField
writer = codecs.lookup("utf-8")[3]
_TYPE_FIELDS_SEQUENCE = Sequence[
Union[Tuple[str, _TYPE_FIELD_VALUE_TUPLE], RequestField... |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... |
class InstaloaderException(Exception):
"""Base exception for this script.
:note: This exception should not be raised directly."""
pass
class QueryReturnedBadRequestException(InstaloaderException):
pass
class QueryReturnedNotFoundException(InstaloaderException):
pass
class QueryReturnedForbidd... |
from .asetek_pro import ASETEK_PRO
|
"""Utils for pandas DataFrames."""
import warnings
from pathlib import Path
import joblib
import pandas as pd
def warn_read(extension):
"""Warn the user when an extension is not supported.
Args:
extension: The extension that is not supported.
"""
warnings.warn(
f"""There was an attem... |
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
###########################################################################
#
# Copyright (c) 2018 www.codingchen.com, Inc. All Rights Reserved
#
##########################################################################
'''
@brief leetcode algorithm
@author chenhui(hui.ch... |
import logging
from datetime import datetime
import uuid
from django.conf import settings
from OpenSSL import crypto
from .helpers import asn1_general_time_format
log = logging.getLogger(__name__)
def create_signed_client_cert(client_public_key, country, state, locality, organization,
organizational_unit... |
import numpy as np
import matplotlib
# Other backends that can potentially be used:
# http://matplotlib.org/faq/usage_faq.html
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
class Plot2D():
def __init__(self, app):
self.app = app
plt.ion()
plt.show()
... |
"""
Credits:
Copyright (c) 2017-2020 Matej Aleksandrov, Matej Batič, Grega Milčinski, Matic Lubej, Devis Peresutti (Sinergise)
Copyright (c) 2017-2020 Nejc Vesel, Jovan Višnjić, Anže Zupanc (Sinergise)
This source code is licensed under the MIT license found in the LICENSE
file in the root directory of this source tre... |
#!/usr/bin/python3
# __*__ coding: utf-8 __*__
'''
@Author: simonKing
@Os:Windows 10 x64
@Software: PY PyCharm
@File: __Html2Json.py
@Time: 2019/8/23 14:42
@Desc: Html2Json
'''
from bs4 import BeautifulSoup
from .__Tag import Tag
class PageParser:
'''
HTML to JSON
'''
def __init__(... |
from tabulate import tabulate
import toys
from toys.datasets import CIFAR10
from toys.metrics import MultiMetric
from toys.model_selection import GridSearchCV
from toys.networks import VGG11
from toys.supervised import GradientDescent
train_data = CIFAR10(test=False)
test_data = CIFAR10(test=True)
grid_search = Gri... |
#!/usr/bin/python
# Before executing the original manage.py code, we first setup the customized app.yaml file,
# and generate the custom static directories, as well as the minimized javascript and css files.
import build_helpers
import sys, logging, datetime
import site_configuration
logging.getLogger().setLevel(log... |
from displayminion import DisplayMinion
if __name__ == '__main__':
DisplayMinion().run()
|
from output.models.nist_data.list_pkg.negative_integer.schema_instance.nistschema_sv_iv_list_negative_integer_pattern_5_xsd.nistschema_sv_iv_list_negative_integer_pattern_5 import NistschemaSvIvListNegativeIntegerPattern5
__all__ = [
"NistschemaSvIvListNegativeIntegerPattern5",
]
|
import json
import os
import re
import socket
import sys
from codecs import encode, decode
from . import shared
dir_path = os.path.dirname(os.path.realpath(__file__))
tlds = None
dble_ext_str = "chirurgiens-dentistes.fr,in-addr.arpa,uk.net,za.org,mod.uk,org.za,za.com,de.com,us.com,hk.org,co.ca," \
"a... |
import glob
import numpy as np
import os
import sys
def main(arg):
jpeg_paths = sorted(glob.glob(os.path.join(arg[0], '*.'+arg[1])))
filename = (os.path.basename(os.path.dirname(arg[0]))+"_rear.txt")
# print(jpeg_paths)
with open(filename, "w") as f:
for s in jpeg_paths:
f.write(str(s) +"\n")
if _... |
import requests
import json
from datetime import datetime
from garnbarn_api.models import Assignment
from garnbarn_api.services.line_message_generator import GarnBarnMessagingApiFlexMessageGenerator
class LineApiError(Exception):
def __init__(self, line_error_object):
self.line_error_object = {
... |
import sys
import logging
import argparse
from argparse import RawTextHelpFormatter
from slack_utils.slack_utils import core, usage
def main():
parser = argparse.ArgumentParser(
prog='slack_utils',
description=" slack utility tool for Slack Administrator, \n see also https://github.com/mollinaca/s... |
#! /usr/bin/python3
# -*-coding: utf-8-*-
import random
def human_win(human_move_id, computer_move_id):
if human_move_id == computer_move_id:
return "Draw"
elif human_move_id == 0 and computer_move_id == 2:
return "YOU WIN!!!!!!!"
elif human_move_id > computer_move_id and human_move_id !=... |
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
# Used in the exec() call below.
from scout_apm.core.monkey import monkeypatch_method, unpatch_method
from scout_apm.core.tracked_request import TrackedRequest
logger = logging.getLogger(__name__)
class Instrument(obj... |
"""Functionality for working with stack traces."""
import traceback
def trace_str() -> str:
"""Gets a string of the current stacktrace."""
return "".join(traceback.format_stack())
|
#!/usr/bin/env python3
from aws_cdk import core
from markdown_it_synapse_lambda.markdown_it_synapse_lambda_stack import MarkdownItSynapseLambdaStack
app = core.App()
MarkdownItSynapseLambdaStack(app, "markdown-it-synapse-lambda", env={'region': 'us-east-1'})
app.synth()
|
# Copyright (c) 2018 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 app... |
import string
alphabet = list(string.ascii_lowercase)
nums = list(range(1,27))
alphanum = dict(zip(alphabet, nums))
lookup = []
cipher_shifted = []
ciphertext = []
secret = 0
print("All non-alpha characters are stripped, translated to lowercase")
print("i.e. 'Hello, world!' -> helloworld")
print("Note that for k va... |
#!/usr/bin/env python3
import random
import os
def main():
LENGTH = 50
ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789'
key = ''.join(random.choice(ALPHABET) for c in range(LENGTH))
with open('/home/%s/key' % os.environ['APP_NAME'], 'w') as key_file:
key_file.write(key)
if __name__ == '__mai... |
import torch
import torch.nn as nn
def get_t(first, frame_interval, s_h, n_frames, mode):
'''get relevant time indices'''
t = []
if mode == "all_frames": # only decode frames where labels are given
for n in range(1, n_frames + 1):
if n % frame_interval == 0 or n == n_frames:
... |
from eqsn import EQSN
import time
def test_x_gate():
q_sim = EQSN.get_instance()
_id = str(10)
q_sim.new_qubit(_id)
q_sim.X_gate(_id)
res = q_sim.measure(_id)
assert res == 1
q_sim.stop_all()
def test_y_gate():
q_sim = EQSN.get_instance()
_id = str(11)
q_sim.new_qubit(_id)
... |
#! /usr/bin/env python
from __future__ import unicode_literals
import csv
import json
import os
import re
import sys
import progressbar
from titlecase import titlecase
def get_csv_row_count(filename):
# subtract 1 for the headers
return sum(1 for line in open(filename, 'rU')) - 1
def dedupe_counties(counti... |
import sys
from qtpy import QtWidgets, QtGui, QtCore
from pathlib import Path
from pymodaq.daq_utils.gui_utils.custom_app import CustomApp
from pymodaq.daq_utils.gui_utils.dock import Dock
import pymodaq.daq_utils.gui_utils.layout
from pymodaq.daq_utils import config as config_mod
from pymodaq.daq_utils.daq_utils impo... |
"""
cfg load and parser
"""
import argparse
import os
from net.config.defaults import get_cfg
# import net.utils.checkpoint as cu
def parse_args():
parser=argparse.ArgumentParser(
description=" "
)
parser.add_argument(
"--cfg",
dest="cfg_file",
help="path to config file ... |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit it manually
# noinspection PyPep8Naming
class MedicinalProductSchema:
"""
Detailed definition of a medicinal product,... |
import argparse
parser = argparse.ArgumentParser(description='A test program.')
parser.add_argument("-p", "--print_string", help="Prints the supplied argument.", action="store_true")
args = parser.parse_args()
print(args.print_string)
|
import pandas as pd
class DataHandling:
pass |
import numpy as np
def split_by_words(X):
X = np.core.chararray.lower(X)
return np.core.chararray.split(X)
<selection>DELIMITERS = "!?:;,.\'-+/\\()"
def parse(string):
return "".join((" " if char in DELIMITERS else char) for char in string).split()
</selection><caret> |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 25 14:54:46 2019
@author: jtfl2
"""
import prody as pd
import os
import numpy as np
import cleaning
import motif as m
from functools import partial
import PeptideBuilder as pb
from symbols import *
#from Bio import Bio.PDB
#import Bio
# what is this c... |
"""Help with randomn functions."""
import random
from typing import Union
def random_generator(seed: Union[int, random.Random] = None) -> random.Random:
"""Create or return random generator.
Parameters
----------
seed : Union[int, random.Random]
Either a random generator or a seed or None.
... |
"""Interface with kubernets."""
import subprocess
class Kubernets:
"""Class to auxiliate kubernets interface."""
def __init__(self, cluster_name: str, zone: str, project: str,
namespace: str = "default"):
"""
__init__.
Args:
cluster_name (str): Kubernets... |
import logging
import queue
import random
import socket
import threading
import time
import slam.common.geometry as geometry
import slam.ssocket as ssocket
import slam.world.simulated as sworld
from slam.common.enums import ObservationType
class Sensor(threading.Thread):
def __init__(self, data_queue: queue.Queu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.