text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/python3
"""
A script for running selfchecking tests in a python harness
"""
import os
import sys
import operator
import subprocess
class ComplianceTest(object):
"""
Represents a single selfchecking test
"""
def __init__(self,
src_filepath,
end_addr,
... |
# -*- coding: utf-8 -*-
from json import loads, dumps
from itertools import groupby
from time import strptime
from datetime import datetime, timedelta
from flask import g
from fcsite import models
from fcsite.models import entries
from fcsite.utils import sanitize_html
TYPE_PRACTICE = 1
TYPE_GAME = 2
TYPE_EVENT = 3
... |
def detect(sentence,illness):
res={
"scope":0,
"low_density":[0,0,0,0],
"high_density":[0,0,0,0],
"both_density":[0,0,0,0],
"none_density":[0,0,0,0]
}
if sentence.find("散发")!=-1:
res["scope"]=1
elif sentence.find("多发")!=-1:
res["scope"]=0
els... |
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import gym
class DeepQNetwork(nn.Module):
def __init__(self, lr, input_dims, fc1_dims, fc2_dims, n_actions):
super(DeepQNetwork, self).__init__()
self.input_dims = input_dims
... |
"""Test model with parameter changes to constant values at fixed timepoints.
Tests for expected state and state (forward) sensitivity trajectories.
d/dt x_ = p_ * q_
p_ = 1
q_ is a timecourse
for t in [ 0, 10), q_ = 1
t in [10, 20), q_ = 0
t in [20, 30), q_ = -1
t in [30, 40), q_ = 0
t in [40, 50],... |
"""
Crossmap settings and validation
"""
import yaml
from logging import error, warning
from os import getcwd, mkdir
from os.path import join, exists, dirname, basename, isdir
from .tokenizer import Kmerizer
from .subsettings import \
CrossmapDataSettings, \
CrossmapLoggingSettings, \
CrossmapServerSetting... |
# @Time : 2018/2/24 10:51
# @Desc : 业务相关公共方法
import collections
import json
import re
from ast import literal_eval
from urllib import parse
import six
from fishbase.fish_logger import logger
# 根据指定顺序获取有序字典
# 输入:
# index_list: 指定顺序
# params_name_dict: 参数名称字典
# tp: 参数数据列表,格式:[param1,param2,...]
# 输出:
# (flag,... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
OpenGL stereo demo using stereoCamera class
"""
from time import sleep
from sys import argv, exit
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
from stereoCamera import StereoCamera
sC = StereoCamera()
animationAngle = 0.0
frameRate = ... |
from typing import List
from fastapi import HTTPException
from fastapi.encoders import jsonable_encoder
from flair.data import Corpus
from flair.datasets import ColumnCorpus
from flair.models import TARSTagger
from flair.data import Sentence
from flair.trainers import ModelTrainer
import pandas as pd
from utils import ... |
import numpy
import math
import re
def process_input(file_contents):
line = 0
edges = dict()
elements = dict()
while line < len(file_contents):
vector2 = str()
vector4 = str()
core = list()
tile_no = int(file_contents[line].strip(" Tile:\n"))
line += 1
... |
import pymel.core as pm
import crab
# ------------------------------------------------------------------------------
class ZeroWSRotationsTool(crab.RigTool):
identifier = 'Transforms : Zero WS Transforms'
# --------------------------------------------------------------------------
def __init__(self):
... |
import sys
import numpy as np
import nibabel as nib
import os
import glob
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
import matplotlib.patheffects as path_effects
from unet.unet_config import unet_model_root_path, load_mconfig
from tools.... |
#build GUI for text file selection
import PySimpleGUI as sg
window_rows = [[sg.Text('Please select a .txt file for analysis')],
[sg.InputText(), sg.FileBrowse()],
[sg.Submit(), sg.Cancel()]]
window = sg.Window('Libra', window_rows)
event, values = window.Rea... |
#!/usr/bin/env python3
import glob, json, math, os, re, shutil, subprocess, sys
D8 = 'd8'
# D8 = '/home/alpstein/software/v8/out/native/d8' # xxx
ARRAY_COUNT = 'array_count'
ARRAY_NAME2INFO = 'array_name2info'
ARRAY_TYPE = 'array_type'
ASMJS_TEST_INPUT = 'asmjs_test_input'
ASMJS_TEST_OUTPUT = 'asmj... |
"""
Helper classes to interpret data send by the board
"""
import cPickle as pickle
from .conversion import *
from .helper import get_time
class ArbitrationIds:
status = 0x010
current = 0x020
position = 0x030
velocity = 0x040
adc6 = 0x050
optoforce_trans = 0x100
optoforce_recv = 0x101
... |
# this script modified from built-in predict.py script
# # original codes refer to fasterRCNN/predict.py
import threading
from threading import Timer
from shutil import copyfile
from os import remove, walk
import argparse
import itertools
import os
import os.path
import shutil
import socket
import subprocess # for cal... |
"""
Copyright 2021 Adobe
All Rights Reserved.
NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
with the terms of the Adobe license agreement accompanying it.
"""
from collections import OrderedDict
from datetime import datetime
from time import strftime, gmtime
import os
import sys
imp... |
import torch
import torch.nn as nn
import torch.optim as optim
import time
from tqdm import tqdm
from .early_stopping import EarlyStoppingWithSaveWeights
from .score import report_score
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed... |
import os
import random
import shutil
import numpy as np
import cv2
from pathlib import Path
from tqdm import tqdm
from random import shuffle
from keras.preprocessing import image
from image_processing import processImage
main_keywords = ['summer','winter','autumn','spring']
main_dir_path = Path(__file__).resolve().p... |
#!/usr/bin/env python
"""
This application is similar to ReadWriteProperty but it is just for beating on
the event message texts, an array of character strings.
"""
import sys
from bacpypes.debugging import bacpypes_debugging, ModuleLogger
from bacpypes.consolelogging import ConfigArgumentParser
from bacpypes.consol... |
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras.layers as tfkl
from tensorflow.keras import backend as K
import tensorflow_probability as tfp
tfd = tfp.distributions
tfpl = tfp.layers
tfb = tfp.bijectors
# Constants #
#############
KL_MODE = 'loss_fun' # 'regu', 'lo... |
import os
import argparse
import numpy as np
import pandas as pd
import scipy.io
import cv2
def convert_pose(vect): # 로드리게스로 얻는것이 무언인가? 헤드 포지션을 피치 야로 ?
M, _ = cv2.Rodrigues(np.array(vect).astype(np.float32))
vec = M[:, 2]
yaw = np.arctan2(vec[0], vec[2])
pitch = np.arcsin(vec... |
from typing import Union, Tuple, List
import numpy as np
__all__ = [
"random",
"bullseye",
"line",
"xor",
"spiral_2d",
"tori",
"skewer",
]
np.random.seed(42)
Data = Union[np.ndarray, np.memmap]
Label = Union[np.ndarray, List[int]]
def random(n: int = 100, dimensions: int = 10) -> Tuple... |
import numpy as np
import os
from rule.rules import Rules
from util.game_data import GameData
from util.execute_code import Execution
from util.placement_data import PlacementData
def test():
print('test')
class GameManager:
def __init__(self, challenger, oppositer, rule, board_size, board_info, problem):... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
''' code that exists outside of a class of a function, will run every time somebody imports your library'''
import pyspark
from pyspark.sql import SparkSession
import pyspark.sql.functions as f
from pyspark import SparkContext
import pyspark.sql
from pyspark.sql import... |
import io
import logging
import multiprocessing
from multiprocessing.pool import ThreadPool
import agate
import requests
logger = logging.getLogger(__name__)
class Geocoder:
"""
Wrapper on the Census Geocoding Services API batch service.
"""
URL = "https://geocoding.geo.census.gov/geocoder/geograph... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
r"""
Basic training script for PyTorch
"""
import argparse
import os
import shutil
import torch
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.data import make_data_loader,\
make_mt_data_loader
from maskrcnn_benchmark.solver... |
from functools import partial
from clu import parameter_overview
from flax import linen as nn
from flax.training import train_state
import jax
import jax.numpy as jnp
import ml_collections
import numpy as np
import optax
import tensorflow_datasets as tfds
from sharpened_cosine_similarity import SCS, MaxAbsPool
# import... |
import os
import pandas as pd
from typing import Dict, List, Set
from datetime import datetime
from requester import n_requests
daos_ids: Set[str] = set()
# queries
DAO_QUERY: str = '{{daos(where: {{register: "registered"}}, first: {0}, skip: {1}\
){{id name reputationHoldersCount}}}}'
EVENT_QUERY: str = '{{events(... |
import numpy as np
import numba as nb
@nb.njit(cache=True)
def as_rect(tlbr):
tlbr = np.asarray(tlbr, np.float64)
tlbr = np.rint(tlbr)
return tlbr
@nb.njit(cache=True)
def get_size(tlbr):
tl, br = tlbr[:2], tlbr[2:]
size = br - tl + 1
return size
@nb.njit(cache=True)
def area(tlbr):
si... |
"""uagen - generate realistic, filtered browser useragents.
Usage:
uagen
uagen [--force-update-db] FILTER...
uagen --list-filters
uagen (-h | --help)
uagen --version
Arguments:
FILTER...
Give a number of keyword filters like 'win', 'firefox'
Options:
--force-update-db Force an update of ... |
import boto
import logging
import venusian
import sys
from pyswfaws import decorators
class DistributedActivityWorker(object):
"""
This class is the base of all distributed activity workers.
In order to run an activity task in distributed mode, users must take this class (or a sub class) and instantiate... |
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.graphics import Color, Line
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from math import cos, sin, pi
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.properties import NumericProperty, Li... |
# TODO: add docstrings
import csv
import os
from enum import Enum
from operator import itemgetter
from collections import defaultdict
class Point(object):
def __init__(self, x, y, numpoints):
self.x = x
self.y = y
self.numpoints = numpoints
def __str__(self):
return 'Point: {... |
import torch
import numpy as np
import dgl
from torch import nn
from ..se3_dynamics.models import OurSE3Transformer, OursTFN
from .utils.utils_profiling import * # load before other local modules
class OurDynamics(torch.nn.Module):
def __init__(self, n_particles, n_dimesnion, nf=16, n_layers=3, act_fn=nn.ReLU(),... |
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.preprocessing import (MinMaxScaler, PowerTransformer,
QuantileTransformer, RobustScaler,
StandardScaler)
from statsmodels.stats.outliers_influence import variance_inflation_f... |
import pandas as pd
import numpy as np
from tqdm import tqdm
tqdm.pandas(desc="progress-bar")
from gensim.models import Doc2Vec
from sklearn import utils
from sklearn.model_selection import train_test_split
import gensim
from sklearn.linear_model import LogisticRegression
from gensim.models.doc2vec import TaggedDocumen... |
# coding:utf-8
import time
import json
import datetime
import tornado
from tornado.ioloop import IOLoop
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler
from tornado.concurrent import run_on_executor
from tornado import gen
from tornado.options import define, options, parse_comman... |
from discord.ext import commands
from collections import OrderedDict
from Connection import Connect
import math
import discord
cluster = Connect.get_connect()
db = cluster['emotes_db']
collection = db['emotes_collection']
class EmoteCommand(commands.Cog):
def __init__(self, bot):
self.bot = bot
... |
from typing import Union, Optional, Type
import torch
from torchvision.transforms.functional import to_tensor
import collections
from torch.utils.data.dataloader import default_collate
import numpy as np
from slam.common.utils import assert_debug, check_tensor
def custom_to_tensor(data: Union[torch.Tensor, np.ndar... |
# Lint as: python2, python3
"""Some utilities for configuring models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from REDACTED.transformer_lingvo.lingvo import compat as tf
from REDACTED.transformer_lingvo.lingvo.core import base_input_generator
fro... |
import Tkinter
from Solver import Solver
__author__ = 'nik-u'
from Tkinter import *
import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
class PlotDrawer:
edgefactor = 1.3
val_q... |
import numpy as np
import h5py
import os
from glob import glob
import cv2
from skimage.transform import rescale
print('__file__={0:<35} | __name__={1:<25} | __package__={2:<25}'.format(__file__,__name__,str(__package__)))
import sys
sys.path.append("/home/li3120/matlab/lib")
import matlab.engine
eng = matlab.engine. st... |
import os
import tempfile
import contextlib
import subprocess
import glob
import sys
from setuptools import setup, find_packages
import setuptools.command.build_ext
import setuptools.command.build_py
# https://stackoverflow.com/questions/6194499/pushd-through-os-system
@contextlib.contextmanager
def pushd(new_dir):
... |
from django.shortcuts import render, redirect
from .models import *
from Shop.models import *
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.utils import timezone
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExis... |
import asyncio
import json
import os
import random
import re
import praw
import logging
from duplicate import is_comment_duplicate, save_duplicate, is_title_duplicate
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(nam... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 15:57:57 2019
@author: <NAME> <<EMAIL>>
"""
# __all__ = ['data0', 'data1', 'load_data_0', 'load_data_1', 'plotTimestampHist']
__version__ = '0.0.1'
import numpy
import csv
import matplotlib.pyplot as plt
import locale
# class datasyncer:
class TimeSeries:
time... |
from .queue import get_dowonload_queue, get_record_queue
from .thread import BaseThread
from .response import Response
from .log import spider_logger as logger
from .request import Request, CrawlerRequest
import requests
import types
from requests.packages.urllib3 import exceptions
requests.packages.urllib3.disable_wa... |
import collections
import tensorflow as tf
import tensorflow.keras.applications as ka
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, Input, Lambda
from tensorflow.keras.models import Model, Sequential
from miso.layers.cyclic import *
# Input range is [0,1], not [0,255] as expected b... |
# 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, software
# distributed under t... |
from __future__ import division
import argparse
import logging
from io import BytesIO
import numpy as np
from PIL import Image
from sciencebeam_utils.beam_utils.io import (
read_all_from_path
)
from sciencebeam_gym.utils.bounding_box import (
BoundingBox
)
from sciencebeam_gym.preprocess.color_map import (... |
"""
Test smd0 and eventbuilder for handling step dgrams.
See https://docs.google.com/spreadsheets/d/1VlVCwEVGahab3omAFJLaF8DJWFcz-faI9Q9aHa7QTUw/edit?usp=sharing for test setup.
"""
import os, time, glob, sys
from psana.dgram import Dgram
from setup_input_files import setup_input_files
from psana import DataSource
imp... |
import pandas as pd
import numpy as np
from multiprocessing import Pool
from functools import partial
from primacy.utils import (
get_json_obj, write_json_obj,
convert_dict_to_dataframe,
get_primer_dataframe)
def min_max_scale_clipped(values, v_min, v_max):
scaled = np.divide(np.subtract(values, v_min... |
import unittest
from lega.utils.storage import FileStorage, S3FileReader, S3Storage
from test.support import EnvironmentVarGuard
from testfixtures import TempDirectory
import os
from io import UnsupportedOperation, BufferedReader
from unittest import mock
import boto3
class TestFileStorage(unittest.TestCase):
"""... |
#!/usr/bin/env python3
import os
import numpy as np
import sys
import math
import pandas as pd
import re
"""
This script compares the TADs and the genes therein in human and axolotl and outputs the TADs that a similar
in terms of the contained genes
"""
# Load the tads+genes files for human and axolotl separately
... |
import os
import cv2
from tools.Show_image import Show
from tools.blur import Blur
from tools.brightness import Brightness
from tools.canny_image import Canny
from tools.convert_color import Convert_color
from tools.crop import Crop
from tools.invert import Invert
from tools.dilate import Dilate
from tools.emboss_imag... |
import os
import sys
import configparser
from random import choice
from datetime import datetime
from configobj import ConfigObj
config = ConfigObj('./panel.ini')
conf = configparser.ConfigParser()
conf.read('./panel.ini')
sections = conf.sections()
all_options = [conf.options(sec) for sec in sections]
all_items = [... |
import os, datetime
import data_reader
import torch
import json
import numpy as np
import convai_model
import cand_retrieval
import utility
def load_model(use_cuda, model_folder):
model_path = os.path.join(model_folder, 'model.dat')
print ('load model from %s' % model_path)
setting = data_reader.read_sett... |
import math
from math import copysign
from x7.geom.colors import PenBrush
from x7.geom.geom import Vector
from x7.geom.typing import *
from x7.geom.model import *
from .common import ViewEvent
from ..digi import DigitizeController
from ..shapes import *
from ..digiview import CommandShapeAdd
from .add import ModeAdd
... |
from sklearn.feature_extraction.text import*
import nltk
nltk.download('stopwords')
import dash_bootstrap_components as dbc
import dash_html_components as html
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import dash_table
import jso... |
from random import randint
from nltk.corpus import words
import copy
from itertools import product
from wordfreq import word_frequency
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expec... |
"""
This file passes the rendering parameters to the Blender rendering script.
"""
import os
import subprocess
import time
from sys import platform
import logging
from src import constants as C
def run_render_series(rend_base_path: str, wl, ad, sd, ai, mf,
clear_rend_folder=True, clear_refere... |
import asyncio
import os
from dataclasses import asdict
import aiofiles
import aiohttp
import json
# 4153, 5810, 9310, 471 = no image
from aiostream import stream
from fewman_svg_parser import FewmanSVG
N = 9999
CONTRACT = '0xad5f6cdda157694439ef9f6dd409424321c74628'
ALL = range(0, N + 1)
URL = "https://api.opens... |
from django.shortcuts import render
from users.models import User
from django.http import HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from .models import Post, Topic, Tag
from .forms import PostForm
def index(request):
"""系统... |
# Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmcv.runner import get_dist_info
from torch.utils.data import DistributedSampler as _DistributedSampler
from torch.utils.data import Sampler
from mmselfsup.utils import sync_random_seed
class DistributedSampler(_DistributedSampler):... |
__author__ = '<NAME> <<EMAIL>>'
import errno
import glob
from io import BytesIO
import logging
import os.path
import os
from pkgutil import get_data
from urllib.parse import urljoin
from zipfile import ZipFile
from bs4 import BeautifulSoup
import psycopg2
import requests
log = logging.getLogger(__name__)
def lo... |
from enum import Enum
import json
import logging
import random
import re
import sentry_sdk
import spacy
from typing import Dict, Optional
from droidlet.dialog.dialogue_objects import DialogueObject, Say
from droidlet.interpreter import coref_resolve, process_spans_and_remove_fixed_value
from droidlet.base_util import h... |
from copy import deepcopy
from enum import Enum
INFINITY = 2 ** 30
class Square(Enum):
EMPTY = 0
BLACK = 1
WHITE = 2
def opposite(self):
if self == self.BLACK:
return self.WHITE
elif self == self.WHITE:
return self.BLACK
else:
raise Runtime... |
#!/usr/bin/env python
# encoding: utf-8
"""
'attract' is a music composition which plays with a Rossler attractor.
Copyright 2014 <NAME> <tiago at acaia \. ca>
This code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Found... |
#!/bin/python3
#pacman-rewind
import os
import re
import sys
# argument stuff ##########################################
#TODO use existing module instead e.g. argparse
class Arguments:
def __init__(self, args):
self.args = {}
self.options=[]
for a in args:
t = a.split('=')
... |
import cv2
import sys
from ..utils import model_utils
from ..utils.mtcnntf.utils import detect_face
import tensorflow as tf
import numpy as np
import os
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
ssd_model = None
pnet, rnet, onet = None, None, None
dlib_hog_model = None
dlib_68_landmark = N... |
import json
from django.contrib.auth.models import AnonymousUser
from django.core.urlresolvers import reverse
from django.test.client import RequestFactory
from nose.tools import eq_
from mkt.api.tests.test_oauth import RestOAuth
from mkt.constants.applications import DEVICE_GAIA, DEVICE_DESKTOP
from mkt.constants.r... |
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License, Version 2.0 (the "Li... |
#!/usr/bin/env python
from __future__ import with_statement
import os, time
import sys, stat
import errno
from fuse import FUSE, FuseOSError, Operations
import gdapi, gdfile, gdcache
class GoogleDriveFuse(Operations):
def __init__(self, mountpoint, cachedir, gdroot):
self.timestamp = int(time.time())
... |
from itertools import *
import math
import numpy as np
scanner_coordinates = [
[(404,-588,-901),
(528,-643,409)],
[(-336,658,858),
(-460,603,-452)]
]
def readfile(filename = "Day 19 sample input.txt"):
lines = open(filename, "r").readlines()
scanner_coordinates = []
current_scanner = Non... |
import json
import time
from datetime import datetime
import sys
import paho.mqtt.client as mqtt
import oci
from oci.config import from_file
from oci.ai_anomaly_detection.anomaly_detection_client import AnomalyDetectionClient
from oci.ai_anomaly_detection.models.model_training_details import ModelTrainingDetails
from... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2016 <NAME>, https://github.com/tywtyw2002, and https://github.com/treedust
#
# 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:/... |
import datetime
from pathlib import Path
from typing import Dict, List, Literal, Optional, Sequence, Set, Union, cast
from uuid import UUID
from bubop import logger, parse_datetime
from taskw import TaskWarrior
from taskw.warrior import TASKRC
from taskwarrior_syncall.sync_side import ItemType, SyncSide
from taskwarr... |
""" Testing the input/output methods for FIT files """
# Authors: <NAME> <<EMAIL>>
# <NAME>
# License: BSD 3 clause
import pytest
import numpy as np
from datetime import date
from numpy.testing import assert_allclose
from skcycling.datasets import load_fit
from skcycling.io.fit import load_power_from_fit... |
import torch
from GCL.losses import Loss
from GCL.models import get_sampler
def add_extra_mask(pos_mask, neg_mask=None, extra_pos_mask=None, extra_neg_mask=None):
if extra_pos_mask is not None:
pos_mask = torch.bitwise_or(pos_mask.bool(), extra_pos_mask.bool()).float()
if extra_neg_mask is not None:
... |
from django.shortcuts import render, HttpResponse
import jieba
import json
import math
import os
import pymysql
import re
# Create your views here.
def index(request):
return render(request, 'index.html')
def search(request):
keywords = request.GET.get('keywords', None)
if keywords :
if len(keyw... |
from __future__ import annotations
import itertools
import threading
import traceback
from datetime import datetime, timedelta
from time import sleep
import keyboard as kb
# functions to be run, you can change these!
from waiting import wait
import foe_desktops
from foe_bot_army import processArmy
from foe_bot_gold ... |
from flask import Blueprint
from flask import render_template
from flask import request
from flask import redirect
from flask import jsonify
from modules.product.models import Product
from shopyoapi.init import db, ma
from flask_login import login_required
from shopyoapi.enhance import base_context
from sqlalchemy i... |
from typing import Tuple, Dict, cast, Any, Iterable, Optional, Union
from vinum._typing import QueryBaseType
import pyarrow as pa
from vinum.errors import ParserError
from vinum.core.functions import is_aggregate_func
from vinum.parser.query import (
Column,
Literal,
Query,
Expression,
)
from vinum.ut... |
# -*- coding:utf-8 -*-
'''
@Author: LiamTTT
@Project: TCTPreprocess.py
@File: slide_reader.py
@Date: 2021/9/10
@Time: 10:22
@Desc: read slides
'''
import os
import openslide
import numpy as np
from loguru import logger
from collections import Iterable
from openslide import OpenSlide
from thirdparty.slide... |
from typing import List
import torch
from scipy.optimize import linear_sum_assignment
from detectron2.structures import Instances
from detectron2.utils.memory import retry_if_cuda_oom
from ..util.misc import interpolate
class Videos:
"""
This structure is to support Section 3.3: Clip-level instance tracking... |
from collections import namedtuple
# ----------------------------------------------------------------------
# Datatypes
# Types
TyBool = namedtuple("TyBool", [])
TyNat = namedtuple("TyNat", [])
TyArr = namedtuple("TyArr", ["left", "right"])
TyId = namedtuple("TyId", ["name"])
# Terms
TmTrue = namedtuple("TmTrue",... |
''' findKeyword.py (更正版)
keyword內容搜尋,子目錄下所有 doc docx txt
neoCaffe 2021-09-11 '''
import os, sys, docx
from win32com import client
#--- 找出目錄下(包含子目錄)特定類型檔案
# 參數 nPath 資料夾 / fTypes 要搜尋的類型
# 傳回一個list : 符合的檔案 fullpathname
def getFiles(nPath, fTypes):
matchedFiles = [] # 儲存符合的檔案
f_tree = os.walk(nPath)
... |
import torch
import torch.nn as nn
import numpy as np
import hyperLSTM
import pytorch_lightning as pl
from torch.utils.data import Dataset, DataLoader
from torch.nn import functional as F
class MyLayerNorm(nn.Module):
def __init__(self, input_dim):
super(MyLayerNorm, self).__init__()
self.gamma = ... |
#!/usr/bin/python3
from fastapi import FastAPI, BackgroundTasks
from typing import Optional, List
from pydantic import BaseModel
import asyncio
import uvicorn
import json
import sys
import os
import time
app = FastAPI()
appStats = {}
class StartParam(BaseModel):
cfg_file: str
z_index: int
net_ifaces: L... |
import numpy as np
import os
import cv2
def check_dir(dir):
if dir[-1] == '/':
dir = dir[:-1]
dir_tree = dir.split('/')
path = ''
for d in dir_tree:
if not os.path.isdir(path+d+'/'):
os.mkdir(path+d+'/')
path += d + '/'
class Bin_2_Array():
def __init__(self,input_fld):
"""Initial parameters... |
import datetime
import threading
import time
from modules.l2_miner.board_listener import BoardCacheInterface
from modules.l2_miner.real_backend_interface import RealBackendInterface
from modules.utils import sleep_if
from modules.utils import UnimplementedMethodCalled
class StorageInterface(object):
@property
... |
'''IOSXE specific Dialogs'''
# Python
import time
import logging
# Unicon
from unicon.eal.dialogs import Statement, Dialog, statement_decorator
from genie.libs.clean.stages.execute_dialogs import BreakBootDialog as \
CommonBreakBootDialog
from genie.libs.clean.stages.exe... |
import __main__
from pkg_resources import load_entry_point
__main__.pymol_argv = [ "pymol"]#, "-qc" ] # Quiet and no GUI "-qc"
import sys, time, os
import pymol
import pymol.cmd as cmd
#from pathlib import Path
#stdout = sys.stdout
#stderr = sys.stderr
pymol.finish_launching()
#sys.stdout = stdout
#sys.stderr = s... |
""" basicfem.py is the main script to execute the Basicfem solver. """
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from abc import ABCMeta, abstractclassmethod
from lib.solvers import *
from lib.output_utility import *
from lib.solver_input import *
def main():
"""
Main function t... |
#------------------------------------------------------------------------------------------------
#
# By: <NAME>
#
# Generating XML Files for Darkflow from .txt files generated by OpenLabeling
# USAGE: generate_xml.py [-h] [--format {yolo,voc}] [--bbox_txt BBOX_TXT]
# [--img_dir IMG_DIR] [--class_... |
############################################################################
# cpy_deploy.py: Deploy a CircuitPython program and its dependencies
# Version 0.01, 05/30/2019, <NAME>, <EMAIL>
############################################################################
"""CircuitPython Deployment Helper
This script assi... |
#!/usr/bin/python
#
# Copyright (c) 2011 Rime Project.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, m... |
import types
import inspect
from functools import wraps
from typing import Tuple
from flask import request
from .exceptions import (
NotAllowedType,
UndefinedParamType,
InvalidRequest,
TooManyArguments,
InvalidHeader
)
from .rules import CompositeRule, ALLOWED_TYPES
# request params. see: __get_r... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: <EMAIL>
# datetime: 2021/4/27 下午2:48
# project: dongtai-openapi
import json
import logging
import time
from dongtai.models.hook_type import HookType
from dongtai.models.strategy import IastStrategyModel
from dongtai.models.vulnerablity import IastVulnerabilityMod... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.