id
stringlengths
3
8
content
stringlengths
100
981k
3342231
import textract import os from glob import glob import re class TextExtractor: def __init__(self, logger=None): self.logger = logger def __call__(self, path): if not os.path.exists(path): raise FileNotFoundError("No such file or directory: {}".format(path)) if os.path.isdi...
3342242
import numpy as np import math import argparse import time import yaml import sys import torch import torch.nn as nn import torch.distributed as dist import torch.optim from torch.autograd import Variable from torch.utils.data import DataLoader from torch.distributed import broadcast import torchvision.transforms as tr...
3342269
import os, sys original = "" with open(sys.argv[1], 'r') as wumbo: original = wumbo.read() # original = original \ # .replace("var ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function';", "var ENVIRONMENT_IS_NODE = false;") \ # .replace("var ENVIRONMENT_IS_WEB = typeof window === 'obje...
3342304
from benchmarking import benchmark @benchmark def bytes_concat() -> None: a = [] for i in range(1000): a.append(b'Foobar-%d' % i) a.append(b' %d str' % i) n = 0 for i in range(1000): for s in a: b = b'foo' + s if b == s: n += 1 ...
3342321
from enum import Enum from typing import Mapping, Iterable, Any, Optional, Dict import algoneer.dataschema import algoneer.dataset class AttributeSchema: class Type(Enum): Numerical = 1 Timestamp = 2 Integer = 3 Float = 4 Ordinal = 5 Categorical = 6 Boole...
3342361
import torch from torch import nn import torch.nn.functional as F from ..BaseModels import BaseGenerator, Encoder, BaseModel class VAE(BaseModel): def __init__(self, n_fil, z_dim, n_attrs, viz): super(VAE, self).__init__(viz) self.encoder = Encoder(n_attrs, 2*z_dim, n_fil) self.G = BaseGen...
3342376
from __future__ import print_function from airflow.operators import LivySparkOperator from airflow.models import DAG from datetime import datetime, timedelta import os """ Pre-run Steps: 1. Open the Airflow WebServer 2. Navigate to Admin -> Connections 3. Add a new connection 1. Set the Conn Id as "livy_http_conn...
3342384
import torch from torchvision import transforms from transformers import AutoTokenizer, AutoModelForSequenceClassification from shark_runner import shark_inference torch.manual_seed(0) tokenizer = AutoTokenizer.from_pretrained("microsoft/MiniLM-L12-H384-uncased") def _prepare_sentence_tokens(sentence: str): retu...
3342405
import enum class State(enum.Enum): WAITING = enum.auto() STARTED = enum.auto() FINISHED = enum.auto() for member in State: print(member.name, member.value) # WAITING 1 # STARTED 2 # FINISHED 3 class State(enum.Enum): WAITING = 5 STARTED = enum.auto() FINISHED = enum.auto() for member...
3342428
from Crypto.PublicKey import RSA from Crypto import Random from Crypto.Cipher import AES, PKCS1_OAEP from Crypto.Util import Counter import argparse import os import sys import base64 import platform import discover import modify # ----------------- # GLOBAL VARIABLES # CHANGE IF NEEDED # ---------...
3342435
from datetime import timedelta import pytest from feast.aggregation import Aggregation from feast.batch_feature_view import BatchFeatureView from feast.data_format import AvroFormat from feast.data_source import KafkaSource, PushSource from feast.entity import Entity from feast.field import Field from feast.infra.off...
3342509
import os, sys, struct from select import select from scapy.all import IP from fcntl import ioctl f = os.open("/dev/tap0", os.O_RDWR) try: while 1: r = select([f],[],[])[0][0] if r == f: packet = os.read(f, 4000) # print len(packet), packet ip = IP(packet) ...
3342519
users = { 'Alice' : 400, 'Bob' : 1500, 'Carol' : 21000 } def read_integer(prompt): while True: try: text = input(prompt) integer = int(text) if integer <= 0: print('Error: Positive Integer Required') else: return i...
3342587
from flask_appbuilder.security.sqla.models import User from sqlalchemy import Column, String class MyUser(User): ''' MyUser fields ''' domain = Column(String(32)) group = Column(String(32))
3342598
from .config import Config from .config import load from .config import register from .config import set_key_of_func_or_cls
3342600
import pandas as pd import seaborn as sns sns.set_theme(style="whitegrid") st_nns_1 = pd.read_csv("spatialtis_nns_time_1core.csv") go_nns_1 = pd.read_csv("giotto_nns_time_1core.csv") st_nns_4 = pd.read_csv("spatialtis_nns_time_4core.csv") go_nns_4 = pd.read_csv("giotto_nns_time_4core.csv") st_nns_1['core'] = "1 core"...
3342635
class Disjoint: def __init__(self): self.parent=None self.rank=0 self.element=None self.e=[] class Set: def __init__(self): #self.repre=Disjoint() self.repre=None def makset(self,x,data): self.repre=x x.parent=x x.rank=0 x.eleme...
3342682
from pathlib import Path import numpy as np import cv2 # TODO: consider using PIL instead of OpenCV as it is heavy and only used here import torch from ..geometry import Camera, Pose def numpy_image_to_torch(image): """Normalize the image tensor and reorder the dimensions.""" if image.ndim == 3: imag...
3342697
from __future__ import absolute_import import subprocess import unittest from os import path, devnull from tests.test_pil_engine import PILEngineTests class PerceptualdiffEngineTests(PILEngineTests): engine_class = 'needle.engines.perceptualdiff_engine.Engine' @classmethod def setUpClass(cls): t...
3342804
from time import time, process_time, clock def check1(): st = time() summ = 0 for i in range(50000000): summ += 1 return time() - st def check2(): st = process_time() summ = 0 for i in range(50000000): summ += 1 return process_time() - st
3342808
import math import typing from ParadoxTrading.EngineExt.Futures.InterDayPortfolio import POINT_VALUE, \ InterDayPortfolio, InstrumentMgr from ParadoxTrading.Fetch.ChineseFutures.FetchBase import FetchBase from ParadoxTrading.Indicator import ReturnRate from ParadoxTrading.Utils import DataStruct class CTAEqualRi...
3342812
from setuptools import setup, find_packages with open('README.md') as f: readme = f.read() with open("HISTORY.md") as history_file: history = history_file.read() with open('requirements.txt') as f: required = [ l.strip() for l in f.read().splitlines() if l.strip() and not l.strip().startswith("#"...
3342827
import logging from compas.geometry import distance_point_point from compas.datastructures import Mesh import os import compas_slicer.utilities as slicer_utils from compas_slicer.post_processing import simplify_paths_rdp_igl from compas_slicer.slicers import ScalarFieldSlicer import compas_slicer.utilities as utils fro...
3342830
import random import csv from collections import defaultdict, OrderedDict import copy import os import io import pandas as pd import torch import torchtext as tt import codecs from models.model import UNK_IDX, PAD_IDX, START_IDX, EOS_IDX class AttributeField(tt.data.RawField): def __init__(self, name, mappingdict...
3342884
import Parse import json with open("jsons.txt","r") as f: d = json.loads(f.read()) # 输出 result = Parse.process(d, "Result") with open("ResultModel.swift", "w") as w: w.writelines([line+'\n' for line in result]) print("finished")
3342905
from typing import Tuple from hypothesis import given from gon.base import (Contour, Point) from tests.utils import equivalence from . import strategies @given(strategies.contours) def test_vertices(contour: Contour) -> None: assert all(vertex in contour for vertex in contou...
3342915
import json import os from unittest.mock import MagicMock from src.secrets import (export, fetch) os.environ['SECRET_ID'] = 'SECRET' class TestSecrets: def setup(self): self.boto3_session = MagicMock() self.boto3_session\ .client.return_value\ .get_secret_value.return_val...
3342934
from test_junkie.rules import Rules class BadAfterTestRules(Rules): def after_test(self, **kwargs): raise Exception("Expected")
3342939
from __future__ import annotations import re import typing import pydantic from genshin.models.model import Aliased, APIModel from . import abyss, activities, characters __all__ = [ "Exploration", "FullGenshinUserStats", "GenshinUserStats", "Offering", "PartialGenshinUserStats", "Stats", ...
3342943
from thespian.actors import ActorSystemConventionUpdate, ActorSystemMessage class TestUnitConventionUpdate(object): def test_equality(self): c1 = ActorSystemConventionUpdate('addr1', 'cap1', True) assert c1, ActorSystemConventionUpdate('addr1', 'cap1' == True) def test_inequality(self): ...
3342946
from __future__ import absolute_import import logging from flask import request, json, abort, g, stream_with_context, Response from flask.views import MethodView from huskar_sdk_v2.consts import CONFIG_SUBDOMAIN, SERVICE_SUBDOMAIN from huskar_api import settings from huskar_api.extras.raven import capture_exception ...
3342979
import pytest from hamcrest import assert_that from allure_commons.utils import represent from allure_commons_test.report import has_test_case from allure_commons_test.result import has_step from allure_commons_test.result import has_parameter def params_name(request): node_id = request.node.nodeid _, name = ...
3342998
import json import boto3 def lambda_handler(event, context): """ 모델 레지스트리에서 최신 버전의 모델 승인 상태를 변경하는 람다 함수. """ try: sm_client = boto3.client("sagemaker") ############################################## # 람다 함수는 두개의 입력 인자를 event 개체를 통해서 받습니다. # 모델 패키지 이름과 모델 승인 유형을 받습...
3343003
import sys import logging import torch import torchvision import torch.nn as nn from dataset_mnistedge import * import torchvision.transforms as transforms from torch.autograd import Variable from trainer_cogan_mnistedge import * from net_config import * from optparse import OptionParser parser = OptionParser() parser....
3343024
from pymongo import MongoClient import json import pprint #please get mongodb up and running #run Mongo_script.txt to initiate the db and structure #client = MongoClient() client = MongoClient('mongodb://localhost:27017/') db_name = 'AIFinance8A' collection_name = 'transactions_obp' f_json = open('8A_3/transactions....
3343043
import torch import torch.nn.functional as F class Fusion(torch.nn.Module): def __init__(self): super(Fusion, self).__init__() def forward(self, data): v, q = data return F.relu(v+q) - torch.pow((v-q), 2)
3343044
menu_name = "Clock" from datetime import datetime from ui import Refresher def show_time(): now = datetime.now() return [now.strftime("%H:%M:%S").center(o.cols), now.strftime("%Y-%m-%d").center(o.cols)] #Callback global for pyLCI. It gets called when application is activated in the main menu callback = Non...
3343059
def env_dpdk_get_mem_stats(client): """Dump the applications memory stats to a file. Returns: The path to the file where the stats are written. """ return client.call('env_dpdk_get_mem_stats')
3343069
import sys import argparse sys.path.append(r"C:\DeepStack\interpreter\packages") from redis import StrictRedis, RedisError import torch import time import json import io import os import _thread as thread from multiprocessing import Process from sharedintelligence.commons import preprocess import torchvision.transform...
3343082
import torch from torch_sparse.tensor import SparseTensor def test_overload(): row = torch.tensor([0, 1, 1, 2, 2]) col = torch.tensor([1, 0, 2, 1, 2]) mat = SparseTensor(row=row, col=col) other = torch.tensor([1, 2, 3]).view(3, 1) other + mat mat + other other * mat mat * other o...
3343112
import numpy as np from polliwog.transform import apply_transform def test_apply_transform(): scale_factor = np.array([3.0, 0.5, 2.0]) transform = np.array( [ [scale_factor[0], 0, 0, 0], [0, scale_factor[1], 0, 0], [0, 0, scale_factor[2], 0], [0, 0, 0, 1...
3343115
from googlevoice import Voice from googlevoice.util import input voice = Voice() voice.login() phoneNumber = input('Number to send message to: ') text = input('Message text: ') voice.send_sms(phoneNumber, text)
3343130
import json import pandas import numpy as np def peaks_from_fasta(filename): with open(filename) as f: parts = (line.split(maxsplit=1) for line in f if line.startswith(">")) entries = [json.loads(part[1]) for part in parts] return pandas.DataFrame(entries) def df_from_fimo(filename): ...
3343138
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_migrate import Migrate from flask_wtf.csrf import CSRFProtect from app.config import config db = SQLAlchemy() migrate = Migrate() csrf = CSRFProtect() login_manager = LoginManager() login_manager.session_...
3343141
import datetime from iap.forms import ( AppleLatestReceiptInfoForm, AppleUnifiedPendingRenewalInfoForm, AppleUnifiedReceiptForm, AppleStatusUpdateForm, ) def test_valid_latest_receipt_info_form(): # An example response from Apple data = { "app_item_id": "000000000", "bid": "co...
3343155
import logging import time from kombu.mixins import ConsumerProducerMixin from celery_connectors.utils import ev from celery_connectors.utils import build_msg from celery_connectors.utils import get_exchange_from_msg from celery_connectors.utils import get_routing_key_from_msg from celery_connectors.run_publisher impor...
3343158
expected_output = { "interface": { "MgmtEth0/RP0/CPU0/0": { "interface_status": "Up", "ip_address": "10.1.17.179", "protocol_status": "Up", "vrf_name": "default", } } }
3343187
import json import metrics import sys def evaluate_coref(predicted_clusters, gold_clusters, evaluator): gold_clusters = [tuple(tuple(m) for m in gc) for gc in gold_clusters] mention_to_gold = {} for gc in gold_clusters: for mention in gc: mention_to_gold[mention] = gc predic...
3343195
from enum import Enum, unique from pathlib import Path from typing import List from hyperstyle.src.python.review.application_config import LanguageVersion from hyperstyle.src.python.review.common.file_system import Extension @unique class Language(Enum): JAVA = 'JAVA' PYTHON = 'PYTHON' KOTLIN = 'KOTLIN' ...
3343200
from fastapi.testclient import TestClient from app.main import app from unittest.mock import patch from unittest import TestCase from app.models import Role, User from app.schemas import GuestUser from app.api.dependencies import get_current_user client = TestClient(app) async def override_dependency_user(token: st...
3343212
from .base_options import BaseOptions class TrainOptions(BaseOptions): """This class includes training options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): parser = BaseOptions.initialize(self, parser) parser.set_defaults(phase='train') ...
3343221
from Crypto.Util.number import isPrime N = 56469405750402193641449232753975279624388972985036568323092258873756801156079913882719631252209538683205353844069168609565141017503581101845476197667784484712057287713526027533597905495298848547839093455328128973319016710733533781180094847568951833393705432945294907000234880...
3343280
from migen import * from migen.fhdl.specials import Tristate from migen.fhdl import verilog from migen.fhdl.decorators import ClockDomainsRenamer from migen.genlib.fifo import AsyncFIFO, SyncFIFO import subprocess class USB_ULPI(Module): clk = Signal() # USB 60MHz clock data = Signal(8) # Bidirectional ...
3343342
import pytest @pytest.fixture def hpy_abi(): return "debug" def make_leak_module(compiler): # for convenience return compiler.make_module(""" HPyDef_METH(leak, "leak", leak_impl, HPyFunc_O) static HPy leak_impl(HPyContext *ctx, HPy self, HPy arg) { HPy_Dup(ctx, arg); // ...
3343370
import random import cv2 import numpy as np import math class DualCompose: def __init__(self, transforms): self.transforms = transforms def __call__(self, x, mask=None): for t in self.transforms: x, mask = t(x, mask) return x, mask class OneOf: def __init__(self, tra...
3343416
class SocketIOError(Exception): pass class ConnectionError(SocketIOError): pass class ConnectionRefusedError(ConnectionError): """Connection refused exception. This exception can be raised from a connect handler when the connection is not accepted. The positional arguments provided with the exc...
3343444
import urllib.request import json import pprint url = 'http://localhost:18080/kabusapi/regulations/9433@1' req = urllib.request.Request(url, method='GET') req.add_header('Content-Type', 'application/json') req.add_header('X-API-KEY', '43e7cc3611fd476db35e93c36a3f77ef') try: with urllib.request.urlopen(req) as res...
3343454
import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * import traceback try: inc1 = demisto.args().get('incident_id_1') inc2 = demisto.args().get('incident_id_2') res = demisto.executeCommand("getIncidents", {'id': inc1}) if any(is_error(entry) for entry in...
3343457
import subprocess import os print("current OS is ", os.name) if os.name == "posix": subprocess.Popen(["python", "../../../scripts/local_http_pack_server.py"], shell=False, cwd="Data/TestData/PackManagerTest") else: subprocess.Popen(["python", "../../../scripts/local_http_pack_server.py"], shell=True, cwd="Dat...
3343504
from __future__ import print_function import unittest from ..client import Client class IsolatedTestCase(unittest.TestCase): def setUp(self): self.client = Client('localhost', 8097) def tearDown(self): print("tearDown: erasing everything...") documents = self.client.list_all_documents...
3343582
import numpy as np import mcubes import sys import os def read_matrix(filepath): """ Read matrix, i.e. from a text file containing one vector. :param filepath: file to read :type filepath: str :return: sdf values :rtype: numpy.ndarray """ values = [] with open(filepath, 'r') as f:...
3343591
import stix2 import stix2.base import stix2.custom import stix2.properties import stix2generator import stix2generator.exceptions import stix2generator.generation.object_generator _JSON_SIMPLE_TYPE_STIX_PROPERTY_MAP = { "string": stix2.properties.StringProperty, "number": stix2.properties.FloatProperty, "...
3343609
from boa.interop.Neo.Storage import Get,Put,Delete,GetContext def Main(operation, addr, value): if not is_valid_addr(addr): return False ctx = GetContext() if operation == 'add': balance = Get(ctx, addr) new_balance = balance + value Put(ctx, addr, new_balance) return new_balanc...
3343632
import asyncio import glob as _glob import itertools as _iter import pathlib as _path import random as _rand import functools from pyperator import IP from pyperator.nodes import Component from pyperator.utils import InputPort, OutputPort, FilePort from pyperator.decorators import log_schedule, component, inport, out...
3343699
class MutableInstance(dict): def __init__(self): self.__dict__ = self # This makes common tasks easier, not by much but conceptually it unifies things Foo = MutableInstance() Foo.x = 5 assert Foo['x'] == 5 Foo.y = 7 assert Foo.keys() == ['x', 'y'] assert Foo.values() == [5, 7] # And now you can pass it to anythin...
3343714
from h2o_wave import ui, data, Q from .common import global_nav from .synthetic_data import * async def show_purple_dashboard(q: Q): q.page['meta'] = ui.meta_card(box='', layouts=[ ui.layout( breakpoint='xs', zones=[ ui.zone('header'), ui.zone('title...
3343758
import numpy as np from torch.autograd import Variable, Function import torch import types class VanillaGradExplainer(object): def __init__(self, model): self.model = model def _backprop(self, inp, ind): output = self.model(inp) if ind is None: ind = output.data.max(1)[1] ...
3343760
from InterpreteF2.NodoAST import NodoArbol from InterpreteF2.Tabla_de_simbolos import Tabla_de_simbolos from InterpreteF2.Arbol import Arbol from InterpreteF2.Valor.Valor import Valor from InterpreteF2.Primitivos.TIPO import TIPO from InterpreteF2.Primitivos.COMPROBADOR_deTipos import COMPROBADOR_deTipos class AlterD...
3343832
import sys try: BatchPlacer.batchPlaceSelected() except: Dir = os.environ['UE4_PRODUCTIVITY'].replace("\\","/") + "/Maya" if Dir not in sys.path: sys.path.append(Dir) try: reload(BatchPlacer) except: import BatchPlacer BatchPlacer.main()
3343862
import math import random from dataclasses import dataclass from typing import Dict, Any, List import gym import numpy as np import pybullet as p from PIL import Image from gym import logger from racecar_gym.bullet import util from racecar_gym.bullet.configs import MapConfig from racecar_gym.bullet.positioning import...
3343975
import math from typing import List, Dict, Iterable, Optional, Tuple, Sequence, Union from warnings import warn import torch from torch import Tensor, nn, jit from typing_extensions import Final from torchcast.internals.utils import get_owned_kwarg, is_near_zero from torchcast.process.base import Process def num_o...
3343980
from Instrucciones.TablaSimbolos.Instruccion import Instruccion from Instrucciones.Excepcion import Excepcion import numpy as np class Min(Instruccion): def __init__(self, valor, tipo, strGram, linea, columna): Instruccion.__init__(self,tipo,linea,columna, strGram) self.valor = valor def ejecu...
3343994
from functools import wraps from django.shortcuts import get_object_or_404 def sms_admin_required(view_func): @wraps(view_func) def wrapper(request, event_slug, *args, **kwargs): from core.models import Event from core.utils import login_redirect from .views import sms_admin_menu_item...
3344039
import torch # import hyperparams as hyp import numpy as np import lidar_segmentation.utils_geom as utils_geom import lidar_segmentation.utils_samp as utils_samp # import lidar_segmentation.utils_improc as utils_improc import lidar_segmentation.utils_basic as utils_basic import torch.nn.functional as F from lidar_segme...
3344041
from sbibm.algorithms.sbi.mcabc import run as mcabc from sbibm.algorithms.sbi.smcabc import run as smcabc from sbibm.algorithms.sbi.snle import run as snle from sbibm.algorithms.sbi.snpe import run as snpe from sbibm.algorithms.sbi.snre import run as snre
3344048
import autopath class AppTestReduce: def test_None(self): raises(TypeError, reduce, lambda x, y: x+y, [1,2,3], None) def test_sum(self): assert reduce(lambda x, y: x+y, [1,2,3,4], 0) == 10 assert reduce(lambda x, y: x+y, [1,2,3,4]) == 10 def test_minus(self): assert reduce(la...
3344049
import FWCore.ParameterSet.Config as cms def customise(process): # ECAL TPG with 2009 beam commissioning TTF thresholds process.EcalTrigPrimESProducer.DatabaseFile = cms.untracked.string('TPG_beamv0_MC.txt.gz') # ECAL SRP settings for 2009 beam commissioning process.simEcalDigis.ecalDccZs1stSam...
3344084
from typing import Dict from taco.consensus.default_constants import DEFAULT_CONSTANTS, ConsensusConstants def make_test_constants(test_constants_overrides: Dict) -> ConsensusConstants: return DEFAULT_CONSTANTS.replace(**test_constants_overrides)
3344149
import uuid from groundstation.broadcast_event import BroadcastEvent class BroadcastPing(BroadcastEvent): def __init__(self, data): self.payload = self.normalize_payload(data) super(BroadcastPing, self).__init__() def validate(self): assert isinstance(self.payload, uuid.UUID)
3344157
import sqlite3 from tkinter import * from tkinter import messagebox newWindow = Tk() newWindow.title("Inventory System") newWindow.geometry("800x750") B1=Button(newWindow,text="Clothing") B2=Button(newWindow,text="Electronic Appliances") newWindow.mainloop()
3344160
def test_navigator_webdriver_active(session): assert session.execute_script("return navigator.webdriver") is True
3344182
import platform import urllib.request import json import threading import time from urllib.parse import urlencode from copy import deepcopy from .version import version from .notifier_name import notifier_name from .settings_data import SettingsData # Query params to be appended to each GET request. _NOTIFIER_INFO =...
3344232
from unittest import TestCase from games.tic_tac_toe import TicTacToeGameSpec from techniques.create_positions_set import create_positions_set class TestCreatePositionsSet(TestCase): def setUp(self): self._game_spec = TicTacToeGameSpec() def test_create_positions(self): number_of_positions =...
3344243
from pirates.instance.DistributedInstanceBase import DistributedInstanceBase from pandac.PandaModules import NodePath class DistributedInstanceWorld(DistributedInstanceBase, NodePath): def __init__(self, cr): DistributedInstanceBase.__init__(self, cr) self.jailContext = None return de...
3344244
import os from copy import deepcopy class ProfileHelper(): ''' ProfileHelper is a helper class to load and save the profiles to a file and load them from that file. Args: logger (Logger): initialized Logger class used for logging config (dict): The path to the config file. ''' def ...
3344390
import os import shutil import sys import time from unittest.mock import Mock import pytest import requests from tornado import ioloop from sudospawner import SudoSpawner @pytest.fixture(scope="module") def io_loop(request): """Same as pytest-tornado.io_loop, but re-scoped to module-level""" io_loop = ioloo...
3344393
import FWCore.ParameterSet.Config as cms from CalibTracker.SiStripESProducers.SiStripGainSimESProducer_cfi import * from SimGeneral.MixingModule.SiStripSimParameters_cfi import SiStripSimBlock stripDigitizer = cms.PSet( SiStripSimBlock, accumulatorType = cms.string("SiStripDigitizer"), hitsProducer = cms....
3344413
from dell_runtime import DellRuntimeProvider from qiskit import QuantumCircuit RUNTIME_PROGRAM = """ # This code is part of qiskit-runtime. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory ...
3344425
import os import cv2 import numpy as np import sys import pickle from optparse import OptionParser import time from keras_frcnn import config import keras_frcnn.resnet as nn from keras import backend as K from keras.layers import Input from keras.models import Model from keras_frcnn import roi_helpers from keras_frcnn ...
3344429
from nose.tools import * import networkx as nx from networkx import * def test_complement(): null=null_graph() empty1=empty_graph(1) empty10=empty_graph(10) K3=complete_graph(3) K5=complete_graph(5) K10=complete_graph(10) P2=path_graph(2) P3=path_graph(3) P5=path_graph(5) P10=p...
3344452
from polyphony import module from polyphony import testbench from polyphony import is_worker_running from polyphony.io import Port from polyphony.typing import int8 from polyphony.timing import clksleep, wait_value @module class Submodule: def __init__(self, param): self.i = Port(int8, 'in') self....
3344457
import logging from django.utils.translation import gettext as _ from django.shortcuts import render from saml2 import BINDING_HTTP_POST, BINDING_HTTP_REDIRECT from .utils import repr_saml logger = logging.getLogger(__name__) _not_valid_saml_msg = _('Not a valid SAML Session, Probably your request is ' ...
3344461
from __future__ import print_function, absolute_import, unicode_literals from uliweb.i18n import gettext_lazy as _ from uliweb.utils._compat import string_types __all__ = ['Layout', 'TableLayout', 'CSSLayout', 'BootstrapLayout', 'BootstrapTableLayout'] from uliweb.core.html import Buf, Tag, Div def min_times(nu...
3344466
import re import json import random from .splitters import split_into_sentences from .chain import Chain, BEGIN from unidecode import unidecode DEFAULT_MAX_OVERLAP_RATIO = 0.7 DEFAULT_MAX_OVERLAP_TOTAL = 15 DEFAULT_TRIES = 10 class ParamError(Exception): pass class Text: reject_pat = re.compile(r"(^')|('$...
3344481
import asyncio import uuid from urllib.parse import urlencode from telepot.namedtuple import InputTextMessageContent, InlineQueryResultArticle from bot import markdown_escape from message import Message @asyncio.coroutine def run(message, matches, chat_id, step): get_params = urlencode({'q': matches}) retur...
3344490
from common.params_pyx import Params, UnknownKeyName, put_nonblocking # pylint: disable=no-name-in-module, import-error assert Params assert UnknownKeyName assert put_nonblocking if __name__ == "__main__": import sys from common.params_pyx import keys # pylint: disable=no-name-in-module, import-error params = P...
3344493
class TypoCoderDiv2: def count(self, rating): b, c = False, 0 for r in rating: if r >= 1200 and not b: c += 1 b = True elif r < 1200 and b: c += 1 b = False return c
3344517
import xlrd import xlsxwriter import json import copy import yaml import sys from pathlib import Path class Excel: def __init__(self, file_name, mode='r'): if mode == 'r': self.workbook = xlrd.open_workbook(file_name) elif mode == 'w': self.workbook = xlsxwriter.Workbook(fi...
3344537
from django.conf import settings from django.conf.urls import url from django.contrib import admin from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext from .models import AnonymousFeedback, Feedback class FeedbackAdmin(admin.ModelAdmin): list_display = ['...
3344546
def GCD(x, y): if (x % y) == 0: return y else: return GCD(y, x % y) print("GCD is ", GCD(80, 12))