text
stringlengths
3.07k
12.6k
""" This module provide a Mixin class `WorkspaceBuildingMixin` to build a workspace """ import torch from torch import Tensor from torch import IntTensor from torch import FloatTensor from torch import BoolTensor import warnings import transformers from typing import List, Dict from .beamsearch_utils import BeamHypoth...
""" Utility script for calculating the log loss and some useful plots """ import sys import matplotlib.pyplot as plt import numpy as np import seaborn as sns from sklearn.metrics import confusion_matrix from snmachine import snclassifier def plot_confusion_matrix(y_true, y_pred, title, target_names, normalize=Fals...
#!/usr/bin/env python # encoding: utf-8 # <NAME>, 2006-2015 (ita) """ Build as batches. Instead of compiling object files one by one, c/c++ compilers are often able to compile at once: cc -c ../file1.c ../file2.c ../file3.c Files are output on the directory where the compiler is called, and dependencies are more dif...
import tensorflow as tf import keras.layers as kl from keras import backend as K import numpy as np import gym from gym_puyopuyo.env import register, ENV_PARAMS from gym_puyopuyo.env.versus import PuyoPuyoVersusEnv FLAGS = None class BaseAgent(object): def __init__(self, session, envs): self.session = se...
""" Copyright (c) 2020 COTOBA DESIGN, Inc. 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, merge, publish, distri...
#!/usr/bin/python3 import gzip import random import traceback import xml.dom.minidom as MD from urllib.parse import urljoin from urllib.error import HTTPError from time import timezone as curr_tz from datetime import datetime, date, time, timedelta from util import * class TVChannel: def __init__(self, element, ...
#/usr/bin/env python # -*- coding: utf-8 -*- # Written by <NAME> on 2018/09/20 # So far, this file works best for English and Chinese. import sys, re from nltk.stem import PorterStemmer, WordNetLemmatizer # The English punctuations are from: https://keras.io/preprocessing/text/ English_PUNCTUATIONS = ''' !"#$%&\'()*+...
import xlwings as xw from common import translate_numbers_to_words from json import load as json_load #TODO: move to data file policy_dic = { "数据产品名称": "", "规则名称": "", "规则内容": "", "字段名": "", "运算符": "", "规则变量阈值": 0, "func_str": "" } # TODO: move to data file personal_data = ...
# -*- coding: utf-8 -*- from __future__ import absolute_import import logging import time import redis from ...utils import s, d class EventStore(object): def __init__(self): pass def add(self, event, pk, ts=None): raise NotImplementedError def replay(self, event, ts=0, end_ts=None, ...
import io from csv import DictReader from datetime import date from enum import Enum from typing import Dict, List import dateutil.parser import graphene from django.db import models, transaction from graphene_file_upload.scalars import Upload from atlas.constants import FIELD_MODEL_MAP from atlas.models import Chang...
#!/usr/bin/env python import argparse import random import json import sys with open('/usr/share/dict/words') as f: words = f.read().splitlines() def random_array_element(): return random.choice(['123', 'true', 'false', 'null', '3.1415', '"foo"']) def random_word(): return random.choice(words) def p...
# Copyright 2015 Google Inc. 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 applicable law or a...
from argparse import ArgumentParser, ArgumentTypeError from itertools import product from random import shuffle from time import sleep from typing import List from src.constants import * from src.cards import Card from src.deck import Deck from src.player import Player def check_snap(desk_pile: Deck, players: List[P...
from cas2vec_helper import * import tensorflow as tf import numpy as np def _build_counter_sequence(events, bins): """ Builds a counter sequence for specified series of events based on given bins (originally called slices) :param events: The series of events :param bins: The bins (slices) :re...
#!/usr/bin/env python3 # Copyright 2019 <NAME> # # 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 agre...
#! python3 # coding: utf-8 # youtube-dl downloader is used to download youtube_dl and patch it to work in Pythonista. # Replace function came from http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python # Download file was adapted from Python file downloader (https://gist.github.com/89edf...
import random import string import matplotlib.pyplot as plt import matplotlib.ticker as ticker plt.style.use('bmh') class BasicBurger(): def __init__(self, patties=1, bun=True): self.patties = patties self.bun = bun self.food_type = "Basic Burger" self.topping = None class Chees...
import sys import os from manager.zip_manager import load_dependencies from manager.s3_manager import download_from_s3, upload_to_s3_repo_sofr download_path = "/tmp/data-collector-repo-sofr-app.zip" s3_path = "s3://eternity02.deployment/lambda/data-collector-repo-sofr-app/deployment/data-collector-repo-sofr-app.zip" d...
import numpy as np import json import os import collections import re import sys sys.path.append("procgen") import gym import sagemaker import boto3 from rollout import default_policy_agent_mapping, keep_going, DefaultMapping, RolloutSaver from ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID from ray.rllib.env...
#file contains all of the methods of our api that interact with documentdb #the methods include creating, getting, deleting and updating the metadata documents import pydocumentdb.document_client as document_client import verify_oauth import datetime from datetime import timedelta from static.app_keys import db_client,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jun 24 07:53:02 2018 @author: mohamed """ # ============================================================================= # This library could be imported via: # from k5descendants import Zigzag as Z # ================================================...
# -*- coding: utf-8 -*- ######################################################################### # Initial software # Copyright <NAME>, <NAME>, <NAME>, <NAME>, 2018, v1.0 # This software is distributed under the terms of the License MIT ######################################################################### from __f...
from __future__ import (absolute_import, division, print_function, unicode_literals) import six import nose.tools from nose.tools import assert_raises from numpy.testing import assert_almost_equal import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as m...
import numpy as np import pandas as pd import sklearn import gc import statsmodels.api as sm import statsmodels.formula.api as smf import sklearn.decomposition from sklearn.cluster import KMeans, AgglomerativeClustering def transform_to_percentile(dataframe): ''' Apparently this is properly called the spearma...
import math import torch import torch.nn as nn from torch.nn.functional import normalize import torch.nn.functional as F import numpy as np class Swish(nn.Module): def forward(self,x): return x*x.sigmoid() def FCtanh(chin, chout, zero_bias=False, orthogonal_init=False): return nn.Sequential(Linear(chi...
#! /urs/bin/env python from __future__ import division import click import os from HTSeq import GFF_Reader import pandas as pd import sys INTERGENIC_INF = ['-', '-', '-', '-', '-', '-', '-', 'intergenic'] LNC_ORDER = ['divergent', 'sense_intronic', 'other_sense_overlap', 'antisense', 'interg...
import cv2 import numpy as np from enum import Enum import matplotlib.pyplot as plt class Direction(Enum): left = 0 right = 1 up = 2 down = 3 data = 4 class MRFStereo(): def __init__(self, smoothness_args, LABELS=16, init='ours'): self.size_of_labels = None self.LABELS = LABE...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from lab.src.data_utils import latexify sns.set_palette("muted") distance_ndpf = 'distance ($d_{\mathrm{NDPF}}$)' def plot_by_outcome(main, outcomes, x_label=""): main['repTeX'] = main.representation.apply(latexify) pt = pd.pivot_tab...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
from .entity import Entity from .vector import Vector from .pickup import PickupType from .sandbox import builtins from .color import Color3 from .event import Event, EventType from .util import * from .path import Path from .game_config import GameConfig as gc from .enemy_type import EnemyType from functools import p...
""" Reference: http://tcd.miovision.com/challenge/dataset/ """ import numpy as np f = open("res_test_resnet.csv", "r") results = [] for line in f.readlines(): results.append(line.strip().split(",")) r1 = np.array(results) f = open("src/MIO-TCD-Localization/MIO-TCD-Localization/gt_test.csv", "r") gt = [] for line...
import glob import sys import os import xml.etree.ElementTree as ET from lxml import etree import cv2 import csv import pathlib import random # importing sibiling package sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from models.Core.config import Config # Generate a dataset class Data...
""" @file Easy937-ReorderDataInLogFiles.py """ example_input_logs = [ "dig1 8 1 5 1", "let1 art can", "dig2 3 6", "let2 own kit dig", "let3 art zero"] example_output = [ "let1 art can", "let3 art zero", "let2 own kit dig", "dig1 8 1 5 1", "dig2 3 6"] from functools import total...
import re import subprocess from typing import Tuple import urllib3 import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 # disable insecure warnings urllib3.disable_warnings() # ---------- CONSTANTS ---------- # FLOAT_RE = r'\d+\.\d+' INT_RE = r'\d+' BYTES_RE = r'\d+ bytes' ...
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): if(self.next==None): return f'{self.value}' return f'{self.value} -> {self.next}' class LinkedList: def __init__(self): self.head = None self.tail = No...
# Import the required libraries # Import matplotlib for plotting import matplotlib.pyplot as plt # Import numpy for array functions import numpy as np # Import random to make random array import random as rand # Import imageio to make the gif import imageio # Global variable for tracking swaps swaps = 0 # ...
import io import json from collections import defaultdict import os import pandas as pd import sqlite3 import torch from torch.utils.data import Dataset class Corpus(): def __init__(self, pre_init_corpus=None): ''' ''' if pre_init_corpus: if isinstance(pre_init_corpus, dict): ...
""" Copyright (c) 2018 iCyP Released under the MIT license https://opensource.org/licenses/mit-license.php """ import bpy import bmesh import re from math import sqrt, pow from mathutils import Vector from collections import deque class Bones_rename(bpy.types.Operator): bl_idname = "vrm.bones_rename" bl_label ...
#!/usr/bin/env python3 # Copyright 2018 Google LLC # # 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 applicab...
# encoding: utf-8 """ @author: <NAME> @contact: <EMAIL> @version: 1.0 @file: dependency_t2t_reader @time: 2020/12/17 10:47 @desc: """ from typing import List, Dict import torch import warnings from random import randint from parser.data.base_bert_dataset import BaseDataset from parser.utils.logger import get_logg...
import time import pylint.epylint as linter import tempfile import logging import regex as re import os import subprocess import random logger = logging.getLogger(__name__) def parse(issues_str): if len(issues_str) == 0: return [] items = issues_str.split('\n')[1:-1] issues = [] for item in i...
# Copyright 2020 <NAME> # # 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, merge, publish, distribute, subl...
""" Moon Rover Driver """ # source: (limited access) # https://gitlab.com/scheducation/srcp2-competitors/-/wikis/Documentation/API/Simulation_API # Excavator Arm and Bucket # excavator_n/bucket_info # excavator_n/mount_joint_controller/command # excavator_n/basearm_joint_controller/command # excavator_n/dista...
import base64 import six import lxml.etree as etree from .header import Header from .namespaces import NAMESPACE, SOAP_ENV, WIN_SHELL def create_shell_payload(env=None, cwd=None): """ Create the XML payload to create a new shell. Parameters ---------- env : dict or None Key/value pairs for...
# Copyright (c) 2021 The Toltec Contributors # SPDX-License-Identifier: MIT from os import path import unittest from tempfile import TemporaryDirectory import subprocess def filter_index_entry(index_entry): return "\n".join( item for item in index_entry.split("\n") if not (item.startswith...
# Import ROS2 libraries from interactive_map_tester.pointGroup import PointsGroup import rclpy from rclpy.node import Node from cv_bridge import CvBridge, CvBridgeError from rclpy.qos import QoSProfile from rclpy.executors import MultiThreadedExecutor # Import message files from sensor_msgs.msg import Image from nav_m...
import coord_math import random from collections import Counter,defaultdict import tempfile import heapq import math import time from exploring_agent import PriorityQueue def disc(coord): x,y = coord x = int(x)#int(round((x-2)/5))*5+2 y = int(y)#int(round((y-2)/5))*5+2 return x,y STATIC_BLOCKED = "B" ...
import sys from PyQt5.QtCore import QThread, QEvent, QPoint, pyqtSignal, QTimer from PyQt5.QtGui import QIcon, QPixmap, QKeyEvent, QTransform, QImage, QCursor from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton, QLabel, QDesktopWidget, QLayout, \ QHBoxLayout, QVBoxLayout, QStyle from scrip...
from typing import Tuple, List import bpy import mathutils import random import math import numpy as np class BlenderObject: """A superclass with utility functions for blender objects for use in more specific subclasses""" def __init__(self, name: str) -> None: self.name = name def get_loc(self)...
import os import sys import logging import torch import torch.cuda.amp as amp import torch.distributed as dist sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', '..')) from torchkit.util.utils import AverageMeter, Timer from torchkit.util.utils import adjust_learning_rate, warm_up_lr from ...
from future.utils import iteritems from datetime import datetime import re import requests import redis import zipfile import json from io import BytesIO from requests.exceptions import ConnectionError, HTTPError, Timeout def get_lotw_users(**kwargs): """Download the latest offical list of `ARRL Logbook of the Wo...
import numpy as np import emcee import csv import math import corner from numpy.lib.function_base import cov from covariance import state_vector_covariance_matrix from sgp4propagator import SGP4 ''' The structure of this script is from this Jupyter notebook: https://github.com/aerospaceresearch/orbitdeterminator/blo...
import argparse import itertools import os import signal import time from contextlib import contextmanager from tqdm import tqdm import pandas as pd import requests from nltk.corpus import wordnet class TimeoutException(Exception): pass @contextmanager def time_limit(seconds): def signal_handler(signum, fra...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A demonstration of evoMPS by simulation of quench dynamics for the transverse Ising model. @author: <NAME> """ from __future__ import absolute_import, division, print_function import scipy as sp import scipy.linalg as la import matplotlib.pyplot as plt import evoMPS....
''' LED event manager Wires events to handlers ''' import gevent class LEDEventManager: processEventObj = gevent.event.Event() events = {} eventEffects = {} eventThread = None def __init__(self, strip, config): self.strip = strip self.config = config # hold self....
from configparser import ConfigParser, NoOptionError import abc from pathlib import Path from typing import Any, Dict, List, Optional import requests import os from src.logger import color_green, log, log_cyan, log_red import json from src.utils import HEADERS, KATTIS_RC_URL, MAP_TEMPLATE_TO_PLANG, PLanguage class Co...
from flask import Flask, redirect, render_template, request, session, jsonify from db.AnnouncementsController import AnnouncementsController from db.HoursController import HoursController from db.LinksController import LinksController app = Flask( __name__, template_folder="web/templates", static_folder="we...
import asyncio from datetime import datetime from functools import wraps from urllib.parse import parse_qs import aiohttp import bcrypt from sanic import Blueprint, response from sqlalchemy import func from sanic.response import json from dash import app, env from dash.crypto import Crypto from dash.data.moderator imp...
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2018, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 3 09:03:47 2018 @author: christinakronser Database to be found: https://drive.google.com/file/d/1KHmasvJFN4AWuflgicGeqvInMmNkKkio/view?usp=sharing """ import numpy as np import sqlite3 import statsmodels.api as sm import pandas as pd def multico...
""" Copyright 2021 Cognitive Scale, Inc. 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 https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or ag...
# -*- coding: utf-8 -*- """Utilities module """ import os from typing import Any, Callable, Iterable, List, Optional, Set from operator import itemgetter import numpy as np import pandas as pd from fastprogress import master_bar from .config import DTYPE from .consts import LABEL, QID, EID, CID, FEATURES, PROXIMITIES f...
"""A natural language medical domain parsing library. """ __author__ = '<NAME>' from typing import Optional from dataclasses import dataclass, field from enum import Enum, auto import sys import logging from io import TextIOBase import re from pprint import pprint from pathlib import Path import pandas as pd from zen...
# -*- coding: UTF-8 -*- import os import re import sys from random import randrange from datetime import datetime reload(sys) sys.setdefaultencoding('utf-8') SPLIT = '->' TIME_SPLIT = '@' TODO_HEADER = '- ' ARCHIVE_TITLE = 'new archive: ' files_obj = None actions_obj = None def todo_actions(): global actions_ob...
# -*- coding: utf-8 -*- import numpy as np import skimage.data import unittest from numpy.testing import (assert_allclose, assert_array_equal, assert_array_almost_equal) from Sandbox.jpeg.jpeg import JpegCompressor class TestImageFormatTransforms(unittest.TestCase): """Test conversion...
from IPython.display import display, Markdown, Latex, HTML import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from pathlib import Path import _pickle as cPickle def load(stage='raw', reapply=False, input_path='../Data', input_name='oasis3'): """[Returns the processed data...
import pytest from caspy import models import testapp.models from testapp import factories, fixtures pytestmark = pytest.mark.django_db() class TestClosureTable: treemgr = testapp.models.Thing.tree pathmgr = testapp.models.ThingPath.objects def test_path_str(self): path = testapp.models.ThingPat...
import sys import ee import os from sql2gee import SQL2GEE from sql2gee.utils.jsonSql import JsonSql # Quick hack, if using a local mac, assume you can initialise using the below... if sys.platform == 'darwin': ee.Initialize() else: EE_ACCOUNT = os.environ['EE_ACCOUNT'] EE_PRIVATE_KEY_FILE = 'privatekey.j...
""" diff.py Copyright 2008 <NAME> This file is part of w3af, http://w3af.org/ . w3af 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 Foundation version 2 of the License. w3af is distributed in the hope that it will be use...
# Copyright (c) 2018, INRIA # Copyright (c) 2018, University of Lille # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, t...
import time import keras import numpy as np from keras.layers import Concatenate from keras.models import load_model from keras_preprocessing.text import text_to_word_sequence, one_hot from sklearn.model_selection import train_test_split import os import re from sklearn.utils import shuffle def validate(x_left, x_...
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2014 California Institute of Technology. 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 th...
#coding:utf-8 from __future__ import absolute_import, division import math import torch import torch.nn as nn import torch.nn.functional as F class SemGraphConv(nn.Module): """ Semantic graph convolution layer """ def __init__(self, in_features, out_features, adj, bias=True): super(SemGraphC...
from copy import copy from typing import TYPE_CHECKING, List, Optional, Tuple from pypika import Table from pypika.terms import Criterion from tortoise.exceptions import OperationalError from tortoise.fields.relational import BackwardFKRelation, ManyToManyFieldInstance, RelationalField if TYPE_CHECKING: # pragma: n...
import pandas as pd import torch import json import os import argparse import random import pickle import itertools import data import data_config import train_code_adv import train_adae import train_code_base import train_coral import train_dae import train_vae import train_ae import train_code_mmd import train_dsn i...
import sys import random import pgzrun from pgzero.builtins import * from read_image import LevelImage WIDTH = 1400 HEIGHT = 1000 class Podlaha(Actor): def __init__(self, x): super().__init__("prekazka", pos=(x*50, 500)) class Prekazka(Actor): def step(self): self.x -= 5 class Blok(Prek...
""" Author: <NAME> Created: 19/02/2021 3:38 PM """ import pandas as pd import os import numpy as np from Storylines.check_storyline import get_acceptable_events, get_past_event_frequency from Climate_Shocks import climate_shocks_env from Storylines.storyline_params import month_fchange, month_len, prev_month, irrig_...
import gym import time import random import threading import numpy as np import os import pandas as pd from learning_tools.A3C_learner.constants import * import warnings from oscar.env.envs.general_learning_env import GeneralLearningEnv brain = None # brain is global in A3C NUM_ACTIONS = 0 frames = 0 class Agent:...
# -*- coding: utf-8 -*- """ SSVEP experiment module """ import time from threading import Lock from psychopy import visual import numpy as np from analysis import CCAAnalysis SCORE_TH = .1 class CheckerBoard: """Flickering radial checkerboard stimulation""" def __init__(self, window, size, position, n_frame...
# -*- coding: utf-8 -*- # A Shovel-Truck Simulator Minimal (Deterministic) - for checking failures-repairs times of trucks # Python Ver. 2.7.13 # salabim Ver. 2.2.9 __author__ = 'panagiotou' # import salabim as sim # # INPUT DATA SECTION # General RND_NUM_STREAM = 12345 # random number stream WARMUP_TIME =...
import csv import logging import typing as t from collections import defaultdict import discord from discord.ext import commands from bot.bot import Bot from bot.constants import Categories, Channels, Emojis, Roles log = logging.getLogger(__name__) MAX_CHANNELS = 50 CATEGORY_NAME = "Code Jam" TEAM_LEADERS_COLOUR = ...
from typing import List, Dict import numpy as np import pandas as pd import joblib import seaborn as sns import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from goatools.goea.go_enrichment_ns import GOEnrichmentStudyNS import larval_gonad.plotting from larval_gonad.gene_ontology import ( run...
import prodigy from multiprocessing import Process from time import sleep import atexit from pathlib import Path from prodigy.components import printers from prodigy.components.loaders import get_stream from prodigy.core import recipe, recipe_args from prodigy.util import TASK_HASH_ATTR, log from datetime import datet...
import re from sqlalchemy.orm import Session from flask_login import current_user from components.pagination import get_page, POSTS_PAGE_LENGTH, TOPICS_PAGE_LENGTH from models.user_model import User from models.topic_model import Topic from models.category_model import Category from models.post_model import Post cl...
from django import forms from django.core.exceptions import ValidationError from django.contrib.auth.forms import UserCreationForm from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.tokens import default_token_generator from kiosk.bot import slack_SendMsg from django.contrib.sites.shortcu...
# -*- coding: UTF-8 -*- # File: sessinit.py # Author: <NAME> <<EMAIL>> import os from abc import abstractmethod, ABCMeta from collections import defaultdict import re import numpy as np import tensorflow as tf import six from ..utils import logger, EXTRA_SAVE_VARS_KEY from .common import get_op_var_name from .varmani...
import torch import torch.nn as nn import torch.nn.utils.spectral_norm as SpectralNorm from utils.network_utils import * from networks.architectures.base_modules import * def ref_pad(conv, pad): return nn.Sequential(nn.ReflectionPad2d(pad), conv) class ResBlock(nn.Module): def __init__(self, ic, oc, use_sn, norm_ty...
import pandas as pd import numpy as np import lightgbm as lgb import xgboost as xgb from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import KFold, RepeatedKFold from scipy import sparse # 显示所有列 pd.set_option('display.max_columns', None) ...
#!/usr/bin/env python3 import argparse import json import os import sys from functools import reduce from typing import Set, List, Any import yaml from tools.codegen.selective_build.selector import ( combine_selective_builders, SelectiveBuilder, ) from tools.lite_interpreter.gen_selected_mobile_ops_header impo...
import itertools import gzip import numpy as np import os import struct import sys import tqdm from features import bulk_extract_features import go from sgf_wrapper import replay_sgf import utils # Number of data points to store in a chunk on disk CHUNK_SIZE = 4096 CHUNK_HEADER_FORMAT = "iii?" CHUNK_HEADER_SIZE = str...
from __future__ import print_function import os import time import re import sys # Java openBIS imports from ch.systemsx.cisd.openbis.generic.shared.api.v1.dto import SearchCriteria ############################################################################# # # The ETL environment setup. # ########################...
import re import math from objc_util import load_framework, ObjCClass, ObjCInstance, create_objc_class, on_main_thread, CGRect import ui import editor from pprint import pprint load_framework('ARKit') load_framework('SceneKit') UIColor = ObjCClass('UIColor') ARSCNView = ObjCClass('ARSCNView') ARWorldTrackingConfigu...
import os from io import StringIO from pathlib import Path from unittest.mock import MagicMock, Mock, patch import pytest from pydantic import ValidationError from cumulusci.utils import temporary_dir from cumulusci.utils.yaml.cumulusci_yml import ( GitHubSourceModel, _validate_files, _validate_url, c...
# ============================================================================= # Authors: PAR Government # Organization: DARPA # # Copyright (c) 2016 PAR Government # All rights reserved. # ============================================================================== import numpy import cv2 import random from maskge...
#Test Script 2 ''' Test Script made to: -create databin from csv -read pickled bins -create dataset based on specific features to extract -manipulate data to be inserted into LDA This Script should be separated into a data preprocessing script and another script should be written for the training of o...
import numpy as np import os import csv import matplotlib.pyplot as plt import cv2 import os.path as osp from hdn.core.config import cfg def plotPOT(im_root, res_root, anno_root, plot_root,tracker): for i in range(1, 31): for j in range(1,8): seq_name_prefix = "V%02d"%i seq_name = "V...
from typing import Any import numbers import dynet as dy from xnmt import batchers, param_collections from xnmt.modelparts import bridges, transforms, scorers from xnmt.transducers import recurrent from xnmt.persistence import serializable_init, Serializable, bare, Ref class Decoder(object): """ A template class...
# encoding: utf-8 """ Step implementations for graphical object (shape) related features """ from __future__ import absolute_import, print_function, unicode_literals import hashlib from behave import given, then, when from docx import Document from docx.enum.shape import WD_INLINE_SHAPE from docx.parts.document im...
# coding: utf-8 from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import numpy as np from scipy import stats SEED = 42 def assert_clean_rescale(rescale): assert rescale > 0, f"rescale should be > 0 {rescale} found...
# -*- coding: utf-8 -*- """ Evaluation metrics Author: <NAME> Copyright (c) 2020 - The Alan Turing Institute License: See the LICENSE file. ---------- https://github.com/alan-turing-institute/TCPDBench/blob/master/analysis/scripts/metrics.py """ def true_positives(T, X, margin=5): """Compute true positives wi...