id
stringlengths
3
8
content
stringlengths
100
981k
1755223
import pytest from tcrdist.storage import StoreIO, StoreIOMotif, StoreIOEntropy from collections import namedtuple def test_StoreIO_init__with_no_args(): """ StoreIO can be created without any input arguments, all pre-specified attrs exist and are None """ S = StoreIO() assert S._validate_attrs...
1755281
from typing import List from dataclasses import dataclass import dataclasses_json import json import stringcase from ..common.utils import OrderedEnum, ExtendedEncoder from ..common.modelcommon import ( ArmorPenetration, DamageType, Health, HealthRegen, Mana, ManaRegen, Armor, MagicResi...
1755302
import os, sys, time, shutil import fileops, cropframes import keyframes def main(): if sys.argv[1] == 'labels': main_dir = './full-clips/train/' annotations_file = '_new_shot_type_testuser.txt' dir_list = sorted(os.listdir(main_dir)) label_data = [] for dir_name in dir_list: if os.path.isdir(main_d...
1755350
import os.path as osp from mmcv.runner import HOOKS, Hook, master_only from mmcv.runner.checkpoint import save_checkpoint, get_state_dict, weights_to_cpu from torch.optim.swa_utils import AveragedModel from mmdet.core import EvalHook, DistEvalHook import torch import mmcv @HOOKS.register_module() class SWAHook(Hook)...
1755380
import unittest import math import sys import time from flaky import flaky from typed_python import Class, Final, ListOf, Held, Member, PointerTo, pointerTo from typed_python.test_util import currentMemUsageMb @Held class H(Class, Final): x = Member(int) y = Member(float) def f(self): return sel...
1755404
import json def hello(event, context): return { "statusCode": 200, "body": "Hello, I'm sub!" }
1755504
import argparse import dataclasses import itertools import os import sys import yaml sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from typing import Any, Dict, List, Optional, Tuple from libs.config import Config def get_arguments() -> argparse.Namespace: """parse all the arguments from com...
1755553
import os import logging from zeropdk.tech import Tech # noqa from zeropdk import klayout_extend # noqa logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) stdout_ch = logging.StreamHandler() logger.addHandler(stdout_ch) DEBUG = os.environ.get("ZEROPDK_DEBUG", "false") == "true" if DEBUG: logger...
1755561
from aydin.util.log.log import lprint class ProgressBar: """Progress Bar Parameters ---------- total : int """ def __init__(self, total=100): self.total = total def emit(self, val): """Member method to emit Parameters ---------- val : int ...
1755573
import math from itertools import combinations import numpy as np from pykdtree.kdtree import KDTree from src import districts from src.novelty_utils import edges_histograms, centers_histograms, dist_centers from src.constraints import fix_pop_equality class NoveltyArchive(object): def __init__(self, state, n_dist...
1755578
from passlib.hash import nthash as passlib_nthash, lmhash as passlib_lmhash from ldaptor import config def nthash(password=b""): """Generates nt md4 password hash for a given password.""" return passlib_nthash.hash(password[:128]).encode("ascii").upper() def lmhash_locked(password=b""): """ Generat...
1755586
import builtins import datetime from files_sdk.api import Api from files_sdk.list_obj import ListObj from files_sdk.exceptions import InvalidParameterError, MissingParameterError, NotImplementedError class InboxRecipient: default_attributes = { 'company': None, # string - The recipient's company. ...
1755625
import numpy as np import pandas as pd from tqdm import tqdm from prereise.gather.solardata.helpers import get_plant_id_unique_location from prereise.gather.solardata.nsrdb.nrel_api import NrelApi def retrieve_data(solar_plant, email, api_key, year="2016"): """Retrieve irradiance data from NSRDB and calculate th...
1755636
from __future__ import print_function, absolute_import import os.path as osp class MSMT(object): def __init__(self, root, combine_all=True): self.images_dir = osp.join(root) self.combine_all = combine_all self.train_path = 'train' self.test_path = 'test' self.train_list_f...
1755696
import numpy as np from anchor_free import anchor_free_helper def test_get_loc_label(): inputs = np.array([0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0]) output = anchor_free_helper.get_loc_label(inputs) answer = np.array([[0, 0], [0, 0], [0, 0], ...
1755701
from django.core.management.base import BaseCommand class Command(BaseCommand): args = '[event_slug...]' help = 'Archive signups for events' def add_arguments(self, parser): parser.add_argument( 'event_slugs', nargs='+', metavar='EVENT_SLUG', ) def...
1755766
from django.conf.urls import url from operations import views urlpatterns = [ url(r'user_ask/$', views.UserAsk.as_view(), name='user_ask'), url(r'user_love/$', views.UserFavView.as_view(), name='user_love'), url(r'user_delete_love/$', views.UserDeleteLove.as_view(), name='user_delete_love'), url(r'us...
1755774
import sys if sys.version_info < (3, 7): from ._yanchor import YanchorValidator from ._y import YValidator from ._xanchor import XanchorValidator from ._x import XValidator from ._visible import VisibleValidator from ._type import TypeValidator from ._templateitemname import Templateitemnam...
1755825
from typing import Union, Dict, Optional, List from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import] # Disable insecure warnings requests.packages.urllib3.disable_warnings() INTEGRATION_CONTEXT_BRAND = "DeHashed" BASE_URL = "https://api.dehashed.com/" RESULTS_FROM = 1 RESULTS_TO = 50 class Clie...
1755870
import requests, re, json, time class watcher: def twitterWatcher(self, user): dicTweet = {} if not user.startswith('http'): urlAccount = "https://twitter.com/"+user else: urlAccount = user req = requests.get(urlAccount) page = req.text if req.status_code == 200: try: tweets = re.fin...
1755880
import numpy as np import networkx as nx from scipy import sparse from label_propagation import LGC,HMN,PARW,OMNIProp,CAMLP from sklearn.grid_search import GridSearchCV from sklearn.cross_validation import train_test_split G = nx.karate_club_graph() labels = {'Officer':0, 'Mr. Hi':1} nodes = np.array([(n,labels[attr['...
1755990
import onir COMPONENTS = { 'rankers': onir.rankers.registry, 'vocabs': onir.vocab.registry, 'datasets': onir.datasets.registry, 'trainers': onir.trainers.registry, 'predictors': onir.predictors.registry, 'pipelines': onir.pipelines.registry, } def main(): for name, registry in COMPONENTS...
1756003
import argparse import os import torch class AbsPoseConfig: def __init__(self): description = 'Absolute Pose Regression' parser = argparse.ArgumentParser(description=description) self.parser = parser # Add different groups for arguments prog_group = parser.add_ar...
1756044
import ujson as json import os import threading import numpy as np from .hammingdb import HammingDb from zounds.persistence import TimeSliceEncoder, TimeSliceDecoder from zounds.timeseries import ConstantRateTimeSeries from zounds.timeseries import TimeSlice class SearchResults(object): def __init__(self, query, ...
1756063
from raptiformica.shell.execute import COMMAND_TIMEOUT from raptiformica.shell.git import clone_source from tests.testcase import TestCase class TestCloneSourceLocally(TestCase): def setUp(self): self.log = self.set_up_patch('raptiformica.shell.git.log') self.execute_process = self.set_up_patch( ...
1756115
class MediaAdapter: def __init__(self, moviePlayer): self.moviePlayer = moviePlayer def playMovie(self, filename): filename_detail = filename.lower().split('.') count_arr = len(filename_detail) if count_arr < 2: print("File not valid") return if filename_detail[count_arr - 1] == '...
1756122
import theano import theano.tensor as T import numpy as np import matplotlib.pyplot as plt plt.ion() import load # load data x_train, t_train, x_test, t_test = load.cifar10(dtype=theano.config.floatX) labels_test = np.argmax(t_test, axis=1) # define symbolic Theano variables x = T.matrix() t = T.matrix() # defin...
1756145
import numpy as np import pytest from landlab import FieldError, RasterModelGrid from landlab.components import FlowAccumulator, FlowDirectorSteepest from landlab.utils.distance_to_divide import calculate_distance_to_divide def test_no_flow_receivers(): """Test that correct error is raised when no flow recievers...
1756152
from kubespawner import KubeSpawner from traitlets.traitlets import Bool class IllumiDeskKubeSpawner(KubeSpawner): """Extends the KubeSpawner by defining the common behavior for our Spwaners that work with LTI versions 1.1 and 1.3 """ load_shared_folder_with_instructor = Bool( True, c...
1756174
from flask import Flask, request,jsonify import json from app.modules.map_distance.dist import distance from app.modules.weather.get_weather_method import get_the_place from app.modules.viki.en_wiki import Viki_media as wiki app = Flask(__name__) @app.route('/') def hello(): return jsonify({'msg':'Hello world'...
1756179
import matplotlib.colors as colors import matplotlib.cm as cmx import matplotlib.pyplot as plt import cv2 import scipy.io as sio import numpy as np img=cv2.imread('./att_seg_rgb.jpg') # img=img.transpose((1,2,0)) print(img.shape) att_dict=sio.loadmat('/data2/gyang/PGA-net/segmentation/sp_ag_weights_2020-06-05-16-13-46....
1756187
import sqlite3 import logging import os from db.peers import Peers from db.commands import Commands class LightningDB: """DB-dependent wrapper around SQLite3. Runs migration if `user_version` is older than `MAX_VERSION` and register a trigger for automated orphan removal. """ MAX_VERSION = 1 ...
1756210
from app import Boot import sys # this starts the simulation (int parameters are used for parallel mode) if __name__ == "__main__": try: processID = int(sys.argv[1]) parallelMode = True useGUI = False except: processID = 0 parallelMode = False useGUI = True i...
1756236
import os import re import sys import time import errno import signal import select from botnet import Command # Helpers def popen(*args, **keys): import subprocess defaults = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "stdin": subprocess.PIPE, "close_fds": True...
1756240
import re import forge # pylint: disable=C0103, invalid-name # pylint: disable=R0201, no-self-use def test_namespace(): """ Keep the namespace clean """ private_ptn = re.compile(r'^\_[a-zA-Z]') assert set(filter(private_ptn.match, forge.__dict__.keys())) == set([ '_config', '_cou...
1756249
import pytest import sru import torch @pytest.mark.parametrize( "cuda", [ False, pytest.param( True, marks=pytest.mark.skipif( not torch.cuda.is_available(), reason="no cuda available" ), ), ], ) @pytest.mark.parametrize("with_gra...
1756251
import pytest @pytest.fixture(scope="session") def storage_account(): yield "dagsterdatabrickstests" @pytest.fixture(scope="session") def container(): yield "dagster-databricks-tests" @pytest.fixture(scope="session") def credential(): yield "super-secret-creds"
1756261
import onnxruntime import torch import onnx import onnxsim class OnnxBackend: """ ONNX后端 """ def __init__(self): pass @staticmethod def convert(model, imgs, weights, dynamic, simplify): """ torch模型转为onnx模型 model: torch模型 imgs: [B,C,H,W]Tensor ...
1756265
from keras import backend as K from keras.engine.topology import Layer import numpy as np import tensorflow as tf from keras import regularizers, constraints, initializers, activations class Dense_New(Layer): def __init__(self, units, activation=None, use_bias=True, # ...
1756291
import shutil import time SECONDS_IN_HOUR = 3600 SECONDS_IN_MINUTE = 60 SHORTEST_AMOUNT_OF_TIME = 0 class InvalidTimeParameterError(Exception): pass def _get_delay_time(session): """ Helper function to extract the delay time from the session. :param session: Pytest session object. :return: Ret...
1756295
from sqlalchemy import * # noqa def test_first(dbs, TestModelA): dbs.add(TestModelA(title="Lorem")) dbs.add(TestModelA(title="Ipsum")) dbs.add(TestModelA(title="Sit")) dbs.commit() obj = dbs.first(TestModelA) assert obj.title == "Lorem" def test_create(dbs, TestModelA): dbs.create(Test...
1756308
from omegaconf import OmegaConf def test_netlist_write(): from pp.components.mzi import mzi c = mzi() netlist = c.get_netlist() # netlist.pop('connections') OmegaConf.save(netlist, "mzi.yml") if __name__ == "__main__": c = test_netlist_write()
1756345
from jinja2 import nodes, TemplateSyntaxError, Environment from jinja2.ext import Extension from jinja2.lexer import Token def fail_template(stream, message): raise TemplateSyntaxError( message, stream.current.lineno, stream.name, stream.filename ) class SqlvmExtension(Extension): """The SqlvmEx...
1756359
from pychecker2.Check import Check from pychecker2.Check import Warning from pychecker2.util import BaseVisitor, type_filter from pychecker2 import symbols from compiler import ast, walk class Returns(BaseVisitor): def __init__(self): self.result = [] def visitReturn(self, node): self.result...
1756445
from __future__ import absolute_import __author__ = 'katharine' import socket import struct import websocket from .. import BaseTransport, MessageTarget, MessageTargetWatch from .protocol import WebSocketRelayToWatch, WebSocketRelayFromWatch, endpoints, from_watch from libpebble2.exceptions import ConnectionError, P...
1756478
import time import jwt from django.contrib.auth import get_user_model from django.utils.translation import gettext as _ from rest_framework import exceptions from rest_framework.authentication import BaseAuthentication from rest_framework_jwt.authentication import JSONWebTokenAuthentication, jwt_get_username_fr...
1756491
import logging import os import tempfile from . import activationsfunc, compat, hyper, mat_gen, nodes, observables, type from ._version import __version__ from .compat import load_compat from .compat.utils.save import load from .model import Model from .node import Node from .ops import link, link_feedback, merge from...
1756603
import os from gino.ext.starlette import Gino from starlette.applications import Starlette from starlette.responses import JSONResponse, PlainTextResponse # Database Configuration PG_URL = "postgresql://{user}:{password}@{host}:{port}/{database}".format( host=os.getenv("DB_HOST", "localhost"), port=os.getenv(...
1756620
import re class LazyRegexCompiler: """Descriptor to allow lazy compilation of regex""" def __init__(self, pattern, flags=0): self._pattern = pattern self._flags = flags self._compiled_regex = None @property def compiled_regex(self): if self._compiled_regex is None: ...
1756624
import argparse import re parser = argparse.ArgumentParser(description='Merge CCS reports.') parser.add_argument('ccs_report', metavar='R', type=str, nargs='+', help='CCS report(s)') args = parser.parse_args() d = {} for ccs_report in args.ccs_report: file = open(ccs_report, "r") for line in file: if...
1756630
from __future__ import absolute_import, division, print_function import sys import warnings from glue.core import BaseData from glue.utils import defer_draw, color2hex from glue.viewers.profile.state import ProfileLayerState from glue.core.exceptions import IncompatibleAttribute, IncompatibleDataException import bqp...
1756634
from django.apps import AppConfig class QuerybuilderTestConfig(AppConfig): name = 'querybuilder.tests' label = 'querybuilder_tests' verbose_name = 'querybuilder Tests'
1756635
import torch import torch.nn as nn import torchvision.transforms as transforms from torch.utils.data import DataLoader import torchvision.datasets as datasets import numpy as np import glob import pandas as pd from collections import defaultdict from argparse import Namespace import os import sys sys.path.append('/w...
1756667
from typing import Any, Dict, Optional, Type, Union import six from dbnd._core.current import try_get_databand_run from dbnd._core.parameter.parameter_definition import ParameterDefinition from dbnd._core.parameter.parameter_value import ParameterFilters from dbnd._core.task.base_task import _BaseTask def get_remot...
1756669
import bpy from . import mcdata from .mcutils import * from .mccolutils import * # Operator to add the right click button on properties class MC_AddProperty(bpy.types.Operator): """Add the property to the menu""" bl_idname = "mc.add_property" bl_label = "Add property to Menu" @classmethod def poll...
1756675
import numpy as np a = np.ndarray(shape=(2,2), dtype=float, order='F') print(a) print(type(a)) a = np.arange(12) print(type(a)) a1 = np.array([[1,2],[3,4]]) np.pad(a1,((1,0),(1,0))) # (1,0),(1,0) (上,下),(左,右)
1756733
import asyncio import contextlib import json import jsonpickle import os import requests import sys import time import traceback import websockets from a2ml.api.utils import fsclient, dict_dig from a2ml.api.a2ml_credentials import A2MLCredentials from a2ml.api.utils.file_uploader import FileUploader, OnelineProgressPe...
1756739
import random from typing import Dict, Tuple, List, Any, Optional, Union, Sequence, cast import gym import numpy as np from allenact.base_abstractions.misc import RLStepResult from allenact.base_abstractions.sensor import Sensor from allenact.base_abstractions.task import Task from allenact.utils.system import get_lo...
1756753
import torch.utils.data as data import os import os.path #from plyfile import PlyData, PlyElement from Datasets.plyfile.plyfile import PlyData import numpy as np #import main import args as args def load_ply(dir,file_name, with_faces=False, with_color=False): path = os.path.join(dir,file_name) ply_data = PlyDa...
1756793
import pylibftdi as ftdi from adf4158 import ADF4158 from queue import Queue, Empty from threading import Thread import datetime class FMCW3(): def __init__(self): SYNCFF = 0x40 SIO_RTS_CTS_HS = (0x1 << 8) self.device = ftdi.Device(mode='b', interface_select=ftdi.INTERFACE_A) self.d...
1756806
import envi.archs.h8.emu as h8_emu import envi.archs.h8.regs as h8_regs import vivisect.impemu.emulator as v_i_emulator class H8WorkspaceEmulator(v_i_emulator.WorkspaceEmulator, h8_emu.H8Emulator): taintregs = [h8_regs.REG_ER0, h8_regs.REG_ER1, h8_regs.REG_ER2] def __init__(self, vw, **kwargs): ''' ...
1756826
def event_handler(obj, event): if event == lv.EVENT.VALUE_CHANGED: print("Value: %d" % obj.get_value()) # Create styles style_bg = lv.style_t() style_indic = lv.style_t() style_knob = lv.style_t() lv.style_copy(style_bg, lv.style_pretty) style_bg.body.main_color = lv.color_make(0,0,0) style_bg.body.grad_...
1756836
import re from itertools import chain import numpy as np from Orange.data import Domain, DiscreteVariable ANNOTATED_DATA_SIGNAL_NAME = "Data" ANNOTATED_DATA_FEATURE_NAME = "Selected" RE_FIND_INDEX = r"(^{} \()(\d{{1,}})(\)$)" def add_columns(domain, attributes=(), class_vars=(), metas=()): """Construct a new do...
1756910
from .helper import unittest, PillowTestCase, hopper from PIL import Image, SunImagePlugin import os EXTRA_DIR = 'Tests/images/sunraster' class TestFileSun(PillowTestCase): def test_sanity(self): # Arrange # Created with ImageMagick: convert hopper.jpg hopper.ras test_file = "Tests/ima...
1756950
COPY_GOOGLE_DOC_KEY = '<KEY>' DEPLOY_SLUG = 'al-qassemi' NUM_SLIDES_AFTER_CONTENT = 2 # Configuration AUDIO = True VIDEO = False FILMSTRIP = False PROGRESS_BAR = False
1756983
import json import os import threading import unittest from http.server import BaseHTTPRequestHandler, HTTPServer from test.support import EnvironmentVarGuard from urllib.parse import urlparse from kaggle_web_client import (KaggleWebClient, _KAGGLE_URL_BASE_ENV_VAR_NAME, ...
1756990
import numpy as np # Scalars product = np.dot(5, 4) print("Dot Product of scalar values : ", product) # 1D array vector_a = 2 + 3j vector_b = 4 + 5j product = np.dot(vector_a, vector_b) print("Dot Product : ", product)
1757022
from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.glm import H2OGeneralizedLinearEstimator # in this test, I compare H2O HGLM runs with and without stating starting values. def test_HGLM_R(): h2o_data = h2o.import_file(path=pyunit_ut...
1757091
from testflows.core import * from testflows.asserts import error from rbac.requirements import * from rbac.helper.common import * import rbac.helper.errors as errors @TestSuite def create_user_granted_directly(self, node=None): """Check that a user is able to execute `CREATE USER` with privileges are granted dire...
1757101
from ..src.model import * from ..materials.hyperelastic import * from ..src.bc import * import matplotlib.pyplot as plt ################################################################################################################ # Notes: General RVE models with periodic boundary conditions for composite materials....
1757131
import sys from PyQt5.QtWidgets import * from login import authenticate_login from PyQt5.QtCore import Qt from PyQt5.QtGui import QIcon, QColor, QPixmap class Login(QWidget): def __init__(self, queue, connection): super().__init__() try: # Sets window title self.setWindowTitle('BitsOJ v1.0.1 [ LOGIN ]') ...
1757151
import numpy as np import matplotlib.pyplot as plt import imageio import random import cv2 import os import re import pandas as pd import math from collections import OrderedDict import gc # check if in a ipython enviorment try: get_ipython() from tqdm.notebook import tqdm except Exception: from tqdm impor...
1757163
import os import pytest from numpy.testing import assert_allclose from numpy import ones, zeros, float64, array, append, genfromtxt from numpy.linalg import LinAlgError from touvlo.lin_rg import (normal_eqn, cost_func, reg_cost_func, grad, reg_grad, predict, h, LinearRegression, ...
1757171
import json # maybe a json format works for you data = { "keys": [ { "consumer_key": "", "consumer_secret": "", "access_token": "", "access_token_secret": "" } ] } with open("tokens_file.json", "w") as write: json.dump(data, write)
1757214
import ctypes import bgfx import unittest class TestImport(unittest.TestCase): def test_module(self): self.assertEqual(bgfx.__author__, '<NAME>') self.assertEqual(bgfx.__license__, 'BSD 2-clause') self.assertEqual(bgfx.__status__, 'Development') class TestEnums(unittest.TestCase): de...
1757233
def run(students, assignments, args, helpers): helpers.printf("Processor!\n") helpers.printf("{} students and {} assignments\n".format(len(students), len(assignments))) helpers.printf(args['message'] + '\n') return True
1757239
import __init__ import torch import torch.optim as optim import statistics from dataset import OGBNDataset from model import DeeperGCN from args import ArgsInit import time import numpy as np from ogb.nodeproppred import Evaluator from utils.ckpt_util import save_ckpt from utils.data_util import intersection, process_i...
1757306
from config_base import ConfigurationBase class GenerateClusterSynonymsConfig(ConfigurationBase): def __init__(self, fname): ConfigurationBase.__init__(self, fname) self.keywords_files = self.__getstring__("DEFAULT", "keyword_files").split(",") self.num_clusters = self.__getint__...
1757329
from flask_security import current_user from flask_socketio import emit from sqlalchemy.sql.expression import func from classes.shared import db, socketio from classes import Channel from classes import webhook from classes import settings from classes import topics from classes import RecordedVideo from functions im...
1757330
from __future__ import print_function, division import numpy as np import scipy.interpolate def detrend_huber_spline(time, flux, mask, knot_distance): """Robust B-Spline regression with scikit-learn""" try: from sklearn.base import TransformerMixin from sklearn.pipeline import make_pi...
1757333
import subprocess from argparse import ArgumentParser from pathlib import Path from shutil import copytree, rmtree import yaml from jinja2 import Environment, FileSystemLoader env = Environment( loader=FileSystemLoader('.'), extensions=['jinja2_markdown.MarkdownExtension'], ) parser = ArgumentParser() pars...
1757334
from maintenance.async_jobs import BaseJob from maintenance.models import RestartDatabase __all__ = ('RestartDatabaseJob',) class RestartDatabaseJob(BaseJob): step_manger_class = RestartDatabase get_steps_method = 'restart_database_steps' success_msg = 'Database restarted with success' error_msg = '...
1757421
from PyQt5.QtCore import Qt from math import inf keyMap = { Qt.Key_0: -inf, Qt.Key_1: 0, Qt.Key_2: 2, Qt.Key_3: 4, Qt.Key_4: 5, Qt.Key_5: 7, Qt.Key_6: 9, Qt.Key_7: 11, Qt.Key_8: 12, Qt.Key_9: 14, # Qt.Key_Equal:16, Qt.Key_Plus: 16, Qt.Key_Slash: 17, Qt.Key_Asteris...
1757437
import growattServer import datetime import getpass import pprint """ This is a very trivial script that logs into a user's account and prints out useful data for a "Mix" system (Hybrid). The first half of the logic is applicable to all types of system. There is a clear point (marked in the script) where we specifical...
1757450
from flask import Flask, request, render_template from flask_cors import CORS import sqlite3 app = Flask(__name__) CORS(app) @app.route("/get") def get(): conn = sqlite3.connect("data.db") c = conn.cursor() c.execute("select * from data") data = c.fetchall() return "<br>".join([i[0] for i in data...
1757451
import tensorflow as tf from tensorflow.keras.models import Model from fastmri_recon.models.subclassed_models.vnet import Vnet from fastmri_recon.models.utils.pad_for_pool import pad_for_pool_whole_plane class PostProcessVnet(Model): def __init__(self, recon_model, vnet_kwargs, from_kspace=False, **kwargs): ...
1757453
SEP = ':' def pair_key(p1, p2): return p1 + SEP + p2 if p1 <= p2 else p2 + SEP + p1 def highest_affinity_pair(views): user_views = dict() affinity = dict() mx = float('-inf') best = None for page, user in views: if page in user_views.setdefault(user, {}): continue ...
1757492
from .. import gcc # ----------------------------------------------------------------------------- def config_static(*args, obj_suffix='.obj', lib_prefix='', lib_suffix='.lib', exe_suffix='.exe', **kwargs): return gcc.config_static( obj_suffix=obj_suffix, li...
1757506
from math import sqrt from point_util import draw class Point(): def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f'Point ({self.x}, {self.y})' def __add__(self, other): return Point(self.x + other.x, self.y + other.y) def __sub__(self, othe...
1757513
import pymia.config.configuration as cfg import pymia.deeplearning.config as dlcfg # Some configuration variables, which most likely do not change. # Therefore, they are not added to the Configuration class NO_CLASSES = 2 # number of classes for the segmentation task FOREGROUND_NAME = 'Nerve' class ImageInformati...
1757519
import torch from torch import nn import numpy as np from library.model_layers import ResnetBlock import math import torch.nn.functional as F from torch.nn import init class Generator(nn.Module): def __init__( self, z_dim=256, n_label=10, im_size=32, im_chan=3, emb...
1757581
import kdb # open database with kdb.KDB() as db: ks = kdb.KeySet(100) # get keys db.get(ks, "user:/MyApp") # check if key exists try: key = ks["user:/MyApp/mykey"] except KeyError: # create a new key + append to keyset key = kdb.Key("user:/MyApp/mykey") ks.append(key) # change keys value key.value = ...
1757585
from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.conf import settings import jwt from datetime import datetime from envoy_auth.models import EnvoyToken UserModel = get_user_model() # from django.contrib.auth.models import User # from customers.models im...
1757619
import os import sys from schrodinger import structure as st import subprocess import argparse # Local import frag_pele_dirname = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) sys.path.append(frag_pele_dirname) import frag_pele.PlopRotTemp_S_2017.main as plop def convert_mae(ligands): """ Des...
1757628
from lightly.active_learning.config.sampler_config import SamplerConfig from lightly.openapi_generated.swagger_client import TagData from tests.api_workflow.mocked_api_workflow_client import MockedApiWorkflowSetup class TestApiWorkflowSampling(MockedApiWorkflowSetup): def test_sampling(self): self.api_wor...
1757656
from pirates.ai import HolidayGlobals from pirates.holiday import CatalogHolidayGlobals from pirates.piratesbase import PLocalizer def getCatalogItemsForHoliday(holidayId): holidayClass = HolidayGlobals.getHolidayClass(holidayId) if holidayClass != HolidayGlobals.CATALOGHOLIDAY: return [] holidayCo...
1757706
import os import numpy as np from open3d import * import cv2 # a = 'training/velodyne/000900.bin' # a = '/media/jintain/sg/permanent/datasets/KITTI/kitti_object_vis/data/object/training/velodyne/000000.bin' a = 'data/testing/valodyne/000003.bin' b = np.fromfile(a, dtype=np.float32) print(b) print(b.shape) points = n...
1757763
import csv class Cards: def getStarpowersID(): CardSkillsID = [] with open('Logic/Files/assets/csv_logic/cards.csv') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0 or line_c...
1757777
class Solution: def checkValidString(self, s: str) -> bool: low = high = 0 for c in s: low += 1 if c == '(' else -1 high += 1 if c != ')' else -1 if high < 0: return False low = max(low, 0) return low == 0
1757816
import os import urllib.request import json from bs4 import BeautifulSoup from skyutils.webscraper import get_flight_info def display_aircraft(ac): os.system('pkill vlc') os.system('cvlc alarm.wav &') get_flight_info(ac) with open('web/data.json') as f: data = json.load(f) ...