text
stringlengths
3.07k
12.6k
""" This module contains functions for making playblasts and screenshots from modelpanels in Maya. Because of this GUI dependency this should not be loaded in batch mode. """ import os import datetime from pymel import core import maya.cmds as cmds class CaptureThumbnail(object): """ This class can capture t...
from tkinter import * from tkinter import messagebox import os from HelperFunc import resource_path, readLocalFile, writeLocalFile import settings cwd = os.getcwd() def openDsgConfig(): if settings.counter < 2: settings.counter += 1 dsgConfig() else: messagebox.showerror('Error', 'Pl...
import numpy as np import sys def create_states_actions(filename): lines = dict() with open(filename, 'r') as infile: lines = infile.readlines() lines = [i.strip() for i in lines] lines = np.array(lines) state = 0 total_states = 0 start_state = 0 goal_state = 0 state_gra...
"""Test utilities in xroms""" import cartopy import numpy as np import xarray as xr import xroms grid = xr.open_dataset("xroms/tests/input/grid.nc") ds = xroms.open_netcdf("xroms/tests/input/ocean_his_0001.nc") # ds = xr.open_dataset('xroms/tests/input/ocean_his_0001.nc') # combine the two: ds = ds.merge(grid, over...
# -*- coding: utf-8 -*- # Copyright 2020 <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 applica...
#!/usr/bin/env python3 # -*- coding: utf-8 -* import os from edcc_adapter import * from PalmprintImageFactory import * from PalmprintCodeRepository import * import time class PalmprintCodeDTO(object): def __init__(self, ID, instanceID, imagePath, code): self.palmprint = PalmprintDTO(ID, instanceID, image...
from django.contrib import admin from django.urls import reverse from django.utils.html import format_html from import_export import resources from import_export.admin import ImportExportModelAdmin from .models import Search, Field, Code, ChronologicCode # -- Searches --- class SearchResource(resources.ModelResource)...
# -*- coding: utf-8 -*- from typing import List, Optional, Text from ..nlu import SlotMap, NluIntentAlternative from ..asr import AsrToken class IntentMessage(object): def __init__(self, session_id, custom_data, site_id, input, intent, slots, alternatives, asr_tokens, asr_confidence): # type: (Text, Text,...
import os.path from data.base_dataset import BaseDataset, get_params, get_transform from data.image_folder import make_dataset from PIL import Image import pickle from pathlib import Path from torchvision import transforms import numpy as np from models.LandMarkDlib.Landmarks_dlib_fe import LandmarksDlibFE import torc...
import sys import random import os.path as osp import time import tqdm import torch import torch.nn.functional as F from torch import tensor from torch.optim import Adam from sklearn.model_selection import StratifiedKFold from torch_geometric.data import DataLoader, DenseDataLoader as DenseLoader device = torch.devic...
from typing import Callable, Dict import json from decimal import Decimal from collections import namedtuple import urllib.request import urllib.parse import asyncio import websockets # Define urls needed for order book streams URL_ORDER_BOOK = "https://api.binance.com/api/v1/depth" URL_ORDER_BOOK_PERP = "https://dap...
from .gamedata import getTeams, getScores, adjustScores from .pwr import PWRsystems from .regression import Regression from .simulate import simulateBracket, simulateGame, simulateGamelog from .teams import Team, Teams from .tiebreak import getPlayoffSeeding from .util import playoff_game_ids from joblib import ...
""" General utilities Answer-type utilities provided by <NAME> """ import logging import itertools import pandas as pd import numpy as np from datasets import load_dataset, load_metric import datefinder from nltk.tokenize import wordpunct_tokenize logging.basicConfig(format="%(asctime)s - %(message)s", level=logging...
# -*- coding: utf-8 -*- # date.py from __future__ import division from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import re import datetime from collections import Counter, OrderedDict from tableschema.config import DEFAULT_FIELD_FORMAT from mipqcto...
from __future__ import annotations import os import sqlite3 from typing import Any, Mapping, Type import numpy as np import pandas as pd import requests def revdict(d: dict) -> dict: return {v: k for k, v in d.items()} COLUMN_TYPES = { 'year_of_birth': np.int16, 'year_of_death': np.int16, 'gender_...
import xml.etree.ElementTree as ET from xml.dom import minidom ############################################################################### class Writer: """ A base class for DataWriter and MapWriter """ def __init__(self, root_node_name): root_node = ET.Element(root_node_name) root_node.se...
import codecs import unicodedata # ================ # Mandarin Companion Wordlists mc_words = {} # # {1 : set("A", "ABC"), ...} def do_mc_parsing(data_dir): parse_mc_file(data_dir + "MandarinCompanion1_secret_garden.txt", 1) parse_mc_file(data_dir + "MandarinCompanion2_sherlock_holmes.txt", 2) parse_mc...
import numpy as np import copy from subprocess import check_output, call import rosbag, rospy import tf from geometry_msgs.msg import Transform, Quaternion import yaml def validate_data(din): """ Script to verify if din is a dictionary compatible with Localization classes and functions. If not compatibl...
"""gRPC server to receive devices state""" from concurrent import futures from queue import Queue import logging import sys from dataclasses import dataclass, field import time import threading from typing import Dict import grpc import logger import daq.proto.session_server_pb2_grpc as server_grpc from daq.proto.se...
from multiprocessing.spawn import old_main_modules import os import json from loghelper import log # 这个字段现在还没找好塞什么地方好,就先塞config这里了 serverless = False config = { 'enable': True, 'version': 5, 'account': { 'cookie': '', 'login_ticket': '', 'stuid': '', 'stoken': '' }, 'mi...
import numpy.random import torch.nn import os import os.path as osp import sys from deltalogger.deltalogger import Deltalogger from reinforce_modules.utils import DefenseGame, get_defense_models from utils.train_utils import MixCLEVR_HDF5 sys.path.insert(0, osp.abspath('.')) import random import argparse from modules....
""" Configure and launch jobs. """ import os import re import sys import json import time import copy import shlex import socket import subprocess import multiprocessing defaults = { 'host': '', 'machine': '', 'maxcores': 0, 'maxnodes': 1, 'maxram': 0, 'maxtime': 1440, 'queue_opts': [], ...
from datetime import datetime, timedelta from azure.storage.blob import BlobBlock import os.path import mimetypes from django.core.files.storage import Storage from django.utils.deconstruct import deconstructible from azure.storage import CloudStorageAccount from storages.utils import setting from tempfile import Spool...
import numpy as np import torch import torchvision import torchvision.transforms.functional as TF from torchvision import transforms import capsule as cps _default_num_workers = 0 """How many subprocesses to use for data loading.""" class MnistData: def __init__(self, root_folder): """ Args: ...
from enum import Enum class TypeDescriptorType(Enum): """Type descriptor enum""" Byte = 'byte' Struct = 'struct' Enum = 'enum' class InterfaceType(Enum): """Interface type enum""" BitMaskable = 'BitMaskable' def is_struct_type(typename): return typename == TypeDescriptorType.Struct.val...
""" Serialization support for compiled functions. """ import sys import abc import io import copyreg import pickle from numba import cloudpickle # # Pickle support # def _rebuild_reduction(cls, *args): """ Global hook to rebuild a given class from its __reduce__ arguments. """ return cls._rebuild(*...
# Author: <NAME> <<EMAIL>> from __future__ import absolute_import, print_function import time import numpy as np import numpy.random as npr def gelman_rubin_diagonostic(samples, multivariate=False, norm_ord=np.inf): """Calculate the Gelman-Rubin statistic. Gelman, Andrew, and <NAME>. "Inference from iter...
from discord.ext import commands import asyncio import requests import json import logging currency_symbol_dict = {'USD': '$', 'BTC': '₿', 'ETH': 'Ξ', 'LTC': 'Ł', 'EUR': '€', 'JPY': '¥', 'RUB': '₽', 'AED': 'د.إ', 'BDT': '৳', 'BHD': 'BD', 'CNY': '¥', 'CZK': 'Kč', 'DKK': 'kr.', 'GBP': '£', ...
import os import numpy as np from sklearn.preprocessing import MinMaxScaler # TODO: this is just a stub of a proper backend storage (which we don't actually need at this stage). # all we need is a quick turnaround with a working PoC that will show us how good/bad evaluations from the model are database = [...
import sqlite3 import config import filters import generic TABLE_NAME="sample" COL_ID='id' COL_TIMESTAMP='timestamp' COL_COVID_PPM='covidPPM' COL_LOCATION_ID='locationID' COL_COLLECTOR_ID='collectorID' def drop_sample_table(db=config.DB_NAME): generic.drop_table(TABLE_NAME,db) def create_sample_table(db=config.D...
from resources.models.utils import get_municipality_help_options from munigeo.models import Municipality from resources.auth import has_permission, is_general_admin, is_staff from rest_framework import serializers, viewsets from django.contrib.auth.models import AnonymousUser import django_filters from rest_framework.p...
''' Author: <NAME> (@mirmirik) Twitter API'sine bağlanıp, takip edilen kullanıcılardan rastgele %50'sini takipten çıkarmak, sessize almak ya da bloklamak için yazılmış deneme / sandbox kodu. myTwitter.cfg dosyası içine ilgili değerlerin eklenmesi gerekmektedir. Konfigürasyon dosyası değerleri: [auth] ACCOUN...
from PyQt5 import QtCore, QtGui, QtWidgets, sip from PyQt5.QtCore import Qt from pandasgui.store import PandasGuiDataFrameStore, PandasGuiStore from pandasgui.widgets import base_widgets import tempfile import os from pandasgui.utility import traverse_tree_widget from pandasgui.widgets.json_viewer import JsonViewer...
#!/usr/bin/env python """ Prepare cross validation for fitpot. Usage: prepare_CV.py [options] Options: -h, --help Show this message and exit. -n N Number for N-fold CV. [default: 10] -m MAX Maximum value for the random number. [default: 10000.0] -s SGM Sigma value for the gaussian distribu...
''' ECB cut-and-paste Write a k=v parsing routine, as if for a structured cookie. The routine should take: foo=bar&baz=qux&zap=zazzle ... and produce: { foo: 'bar', baz: 'qux', zap: 'zazzle' } (you know, the object; I don't care if you convert it to JSON). Now write a function that encodes a user profile in th...
import sys sys.path.append('../') #code below used to deal with special characters on the file path during read_csv() sys._enablelegacywindowsfsencoding() import numpy as np import seaborn as sns import pandas as pd from sklearn.model_selection import cross_val_score import matplotlib.pyplot as plt import py...
from conch.analysis.segments import SegmentMapping def generate_segments(corpus_context, annotation_type='utterance', subset=None, file_type='vowel', duration_threshold=0.001, padding=0, fetch_subannotations=False): """ Generate segment vectors for an annotation type, to be used as input...
import os import re import pickle import numpy as np import pandas as pd from tqdm import tqdm # Assign labels used in eep conversion eep_params = dict( age = 'Age(Gyr)', log_central_temp = 'logT(cen)', core_hydrogen_frac = 'Xcen', hydrogen_lum = 'H lum (Lsun)', lum = 'L/Lsun', logg = 'logg', ...
import math import os import numpy as np import numpy.testing as npt import pytest import rowan import freud class TestRotationalAutocorrelation: """Test the rotational autocorrelation order parameter""" def test_equality(self): """Ensure that autocorrelation against identical values is 1""" ...
# Copyright 2016 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 ag...
from __future__ import division import torch from torch import nn import torch.nn.functional as F from inverse_warp import * import numpy as np def photometric_reconstruction_and_depth_diff_loss(tgt_img, ref_imgs, intrinsics, tgt_depth, ref_depths, explainability_ma...
from mzimg import Mzimg import argparse import threading,queue #-----------------------------------------多线程--------------------------------------# #-------------------------------------------------------------------------------------# # sava_page_url 多线程 class save_page_thread(threading.Thread): def __init__(self,...
import torch from dataloader import MovielensDatasetLoader from model import NeuralCollaborativeFiltering import numpy as np from tqdm import tqdm from metrics import compute_metrics import pandas as pd class MatrixLoader: def __init__(self, ui_matrix, default=None, seed=0): np.random.seed(seed) self.ui_matrix = ...
import numpy as np import pandas as pd import pytest from evident.data_handler import RepeatedMeasuresUnivariateDataHandler from evident.stats import calculate_eta_squared, calculate_rm_anova_power @pytest.fixture def rm_alpha_mock(): # Use modified data from tinyurl.com/ycktzet3 data_dict = { "S1": ...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import datetime import re from ralph.business.models import Venture, VentureExtraCost from ralph.discovery.models import ( Device, Devic...
# -*- coding: utf-8 -*- # Import Elasticsearch library import elasticsearch from elasticsearch_dsl import Search, Q, A # Import advanced python collections import collections # Import JSON operations import json # Import global functions from global_functions import escape #----------------- Main Functions ---------...
import random import cv2 import numpy as np COLORS_DARK = ["1771F1", "298A08", "FF6B00", "E20338", "761CEA"] COLORS_PASTELL = ['7777DD', '77DDDD', 'DD7777', 'DDDD77', '77DD77', 'DD77DD'] COLORS_BASE = ['FF0000', 'FFFF00', '00FF00', '00FFFF', 'FF00FF', '0000FF'] COLORS_BLACK_WHITE = ['000000', 'FFFFFF'] COLORS_MARK = ...
# Based on scripts at https://github.com/tensorflow/tensorflow/contrib/learn/python/learn/datasets/ '''Dataset utilities''' import pickle import collections from os import path from tensorflow.python.framework import dtypes import numpy as np Datasets = collections.namedtuple('Datasets', ['train', 'validation', 'te...
import datetime import re import time from tripleoci.config import log, CACHE_TIMEOUT from tripleoci.utils import Web, cache ZUUL_STATUSES = ["SUCCESS", "FAILURE", "RETRY_LIMIT", "POST_FAILURE", "TIMED_OUT"] JOB_REGEX = ( re.compile(r"(\S+) (https://zuul.opendev.org/t/openstack/build/\S+) " ...
import sys, cv2, pq, skimage, seed_reader import numpy as np from skimage import exposure #global parameters #~~~~~~~~~~~~~~~~~ alpha = 3.3 #power associated with intensity cost beta = 3500000 #factor associated with curvature cost radius = 38 #radius of the circle bfactor = 25 #how much predecesso...
# -*- coding: utf-8 -*- from dataclasses import replace import pytest from snl_d3d_cec_verify.cases import CaseStudy, MycekStudy @pytest.fixture def casedef(): return {"dx": (1, 2, 3, 4), "dy": (1, 2, 3, 4), "sigma": (1, 2, 3, 4)} @pytest.fixture def cases(casedef): return CaseStu...
#!/usr/bin/env python """This is a Python script for parsing the output of plumed driver and plotting the time-series data. """ import argparse import numpy as np import matplotlib.pyplot as plt from matplotlib import rc def initialize(): parser = argparse.ArgumentParser( description='This script parse...
from typing import Dict, Optional, Tuple import torch from e3nn import o3 import math class QuadraticNonLinearity(torch.nn.Module): def __init__(self, l_in: int, l_out: int, symmetric: bool = True) -> None: """Special non-linearity function for data in spectral domain. Code adapated from: https:/...
# ---------------------------------------------------------------------------- # sdfide # Copyright (c) 2022- <EMAIL> # All rights reserved. # # This file is under BSD 2-Clause License, see LICENSE file # # ---------------------------------------------------------------------------- """Interactive Design Environment f...
import numpy as np from scipy.linalg import block_diag import sys sys.path.insert(1,'../') from stderr_calibration import MinDist """Unit tests of minimum distance inference functions Intended for use with the "pytest" testing framework """ # Define small-scale problem used for some tests G = np.array([[1,0],[1,1...
try: import aiohttp except ImportError: raise RuntimeError("AsyncIber requires aiohttp") from datetime import datetime from typing import Union, Optional LOGIN_URL = "loginNew/login" WATTHOURMETER_URL = "escenarioNew/obtenerMedicionOnline/24" ICP_STATUS_URL = "rearmeICP/consultarEstado" CONTRACTS_URL = "cto/l...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, <NAME> <justrafi at google mail> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION...
"""Testing fixtures.""" from typing import Optional import collections import datetime import textwrap from collections import OrderedDict from dataclasses import dataclass import pytest from faker import Faker from git import Actor, Repo fake = Faker() # https://www.reddit.com/r/git/comments/nl36wl/the_top_1_commi...
from django.shortcuts import render from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseNotFound from django.template import RequestContext from django.core.urlresolvers import reverse from django.db.models import Q import re from manuscript.models import Author, Title, Chapter, Page, Par...
import smtplib from email import encoders import os from email.mime.base import MIMEBase import urllib.error import urllib.request from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from datetime import date, timedelta import calendar import json import re import settings ...
from rest_framework import viewsets from rest_framework.permissions import IsAuthenticated from .models import User, PersonDetail from .serializer import UserSerializer, PersonSerializer from django.contrib.auth import login, authenticate from rest_framework_simplejwt.tokens import RefreshToken from django.views.decora...
from rich.console import Console from rich.table import Table from rich.progress import Progress, BarColumn, TextColumn from rich.panel import Panel from rich.prompt import Prompt from collections import defaultdict from timeit import default_timer as timer import os import pathlib import subprocess import time import ...
from tkinter import ttk import tkinter as tk import random import threading import os import serial import subprocess import keyboard import time import sys from multiprocessing import Process # continually read from ardunio def read_line( ): port_name = '/dev/cu.usbmodem1432301'#changed by Spencer for arduino por...
""" Multipatch decoder corresponding to the one implemented in AtlasNet [1] with the adjustment as in [2]. [1] <NAME> et al. AtlasNet: A Papier-Mâché Approach to Learning 3D Surface Generation. CVPR 2018. [2] <NAME> et al. Shape Reconstruction by Learning Differentiable Surface Representations. CVPR 2020. Aut...
import sys import time import psutil import json import os import subprocess import shutil from pathlib import Path from glob import glob from invoke import task from galaxy.tools import zip_folder_to_file import github with open('src/manifest.json') as f: __version__ = json.load(f)['version'] REQUIREMENTS = '...
from common.transform_data import normalize_min_max, standar_z import pandas as pd import numpy as np import warnings __author__ = "<NAME>" __credits__ = ["<NAME>"] __email__ = "<EMAIL>" def matrix_features(pv_data, num_arm=60, var_standar_z=True, features=('fourier', 'time')): df_time_features = get_time_featur...
""" Experiments and evaluations. """ import inspect import operator import os import string import warnings from dataclasses import dataclass, field from typing import Callable, Optional, Type, Union import numpy as np import sklearn.pipeline from classicdata.dataset import Dataset from loguru import logger from tabul...
from tqdm import tqdm, trange from pathlib import Path from os.path import join, getsize from joblib import Parallel, delayed from torch.utils.data import Dataset # Additional (official) text src provided OFFICIAL_TXT_SRC = ['librispeech-lm-norm.txt'] # Remove longest N sentence in librispeech-lm-norm.txt REMOVE_TOP_N_...
# Copyright (c) 2020-present, Assistive Robotics Lab # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # """ Transformer classes with quaternion normalization. Reference: [1] https://pytorch.org/tutorials/beginner/transfo...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright (c) 2015, <NAME> <<EMAIL>> # A module for identifying Sony Playstation 1 games with Python 2 & 3 # It uses a MIT style license # It is hosted at: https://github.com/workhorsy/identify_playstation1_games # # Permission is hereby granted, free of charge, to any ...
#! /usr/local/bin/python3 # -*- coding: UTF-8 -*- # 抓取 煎蛋--妹子图 并存储 import hashlib import base64 from bs4 import BeautifulSoup import requests import re import random import shutil import os import time import queue import threading ''' url解码 ''' def parse(imgHash, constant): q = 4 hashlib.md5() constant...
import pandas as pd import numpy as np import os import seaborn as sns import matplotlib.pyplot as plt unique_per_db_and_species_column_order = ['dataId', 'database', 'uniqueTermCount', 'tax...
# auth: <NAME> # desc: some particles on the screen. this is not a fully fleshed out version, # but it has some basic components such as moving of cooling down particles. from random import random import pygame as pg import math import time def _to_unit_vector(v): vx = v[0] vy = v[1] mag = math.sqr...
""" A toy model for the experiment of analysis of memory effects Action: a = {+1, -1} State: s' = s + a Reward: r = beta1 * (s + a) + bate2 Optimal Q-value: Q(s,a; beta) = r = beta1 * (s + a) + beta2; # beta2 is more like a bias Expected Q-value: Q_hat(s,a; theta) = theta1 * (s + a) + theta2; TD-error: e = [r(s,a;...
import os import sys import re import json import subprocess import urllib.request from sphinx.errors import SphinxError ########################################################################### # # # Dredd documentation build configuration...
import math from typing import Iterable, Any, List import rx from rx import operators from rxbp.flowable import Flowable from rxbp.flowables.fromemptyflowable import FromEmptyFlowable from rxbp.flowables.fromiterableflowable import FromIterableFlowable from rxbp.flowables.fromrxbufferingflowable import FromRxBufferin...
from inspect import isfunction, signature from types import ModuleType from typing import ( Any, Callable, Dict, Generator, List, NamedTuple, Optional, Tuple, Union, get_type_hints, ) from hypothesis.strategies import SearchStrategy, builds, just from pydantic import BaseModel ...
import os import json import logging import random from datetime import datetime from functools import wraps from api.models import (User) from api.serializers import ( UserSerializer, CreateUserAccountSerializer, VerifyUserAccountSerializer, GeneratePasswordSerializer) from django.shortcuts import get...
#!/usr/bin/env python # coding=utf-8 """ Ant Group Copyright (c) 2004-2021 All Rights Reserved. ------------------------------------------------------ File Name : test_networkC Author : <NAME> Email: <EMAIL> Create Time : 2021/9/2 上午11:08 Description : description what the main function of this ...
# Python modules import os import shutil # 3rd party modules import pydicom # Our modules import vespa.analysis.fileio.dicom_siemens as dicom_siemens TAG_SOP_CLASS_UID = (0x0008, 0x0016) # This tag holds a description of the content of a Siemens file TAG_CONTENT_TYPE = (0x0029, 0x1008) def is_dicom(filename): ...
# Copyright 2020 The authors of the paper (https://arxiv.org/abs/2011.12081) # The paper's title: "Tackling Domain-Specific Winograd Schemas with Knowledge-Based Reasoning and Machine Learning" # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the ...
""" @name: Modules/House/Lighting/Controllers/controllers.py @author: <NAME> @contact: <EMAIL> @copyright: (c) 2010-2020 by <NAME> @note: Created on Apr 2, 2010 @license: MIT License @summary: Handle the home lighting system automation. First we have the basic information about the controller. Then ...
from lxml.etree import Element,SubElement,tostring from xml.dom.minidom import parseString import xml.dom.minidom import os import sys from PIL import Image import cv2 as cv from tqdm import tqdm def deal(txt_path,xml_path): files=os.listdir(txt_path) for file in tqdm(files): filename=os.path.splitext...
"""Moira list utility function tests""" from tempfile import NamedTemporaryFile import pytest from django.contrib.auth.models import AnonymousUser, User from zeep.exceptions import Fault from moira_lists.exceptions import MoiraException from moira_lists.factories import MoiraListFactory from moira_lists.models import...
import copy import json import math import numbers from collections import defaultdict import numpy as np import yaml from gym import Wrapper class SafeFallbackEncoder(json.JSONEncoder): def __init__(self, nan_str="null", **kwargs): super(SafeFallbackEncoder, self).__init__(**kwargs) self.nan_str...
import torch import torch.nn as nn import torch.nn.functional as F import models import models.backbone from models.GCMNet import Global_ContextBlock class PSPNet(nn.Module): def __init__(self, backbone: str, output_stride: int, num_classes: int, mode: bool): super(PSPNet, self).__init__() # Back...
from . import Command from .. import utils import datetime import nextcord import io import json import random from enum import Enum from urllib.parse import quote_plus, unquote_plus class MarketState(Enum): PRE = (1, "Premarket") REGULAR = (2, "Regular") POST = (3, "Postmarket") # Rounds the value to...
#!/usr/bin/env python3 ''' Produces report for rs file ''' from subprocess import CalledProcessError import subprocess import os import argparse import numpy as np import pandas as pd import re import sys EOL = chr(10) def check_output(x,shell=False): ans=subprocess.check_output(x,shell=shell) ans=str(ans,'as...
from steps.steps import * @given('"{user_name}" registers external dataClay with hostname "{host}" and port {port}') @when('"{user_name}" registers external dataClay with hostname "{host}" and port {port}') @then('"{user_name}" registers external dataClay with hostname "{host}" and port {port}') def step_impl(context,...
import logging import os import boto3 import requests import re import time from botocore.exceptions import ClientError from datetime import datetime def create_presigned_url(object_name): """Generate a presigned URL to share an S3 object with a capped expiration of 60 seconds :param object_name: string ...
import time from collections import defaultdict from INF553_YelpProject.src.utils.inputOutput_utils import csvReader, csvWriter def find_business_with_missing_data(data, data_schema): data.fillna(value = "Null", inplace = True) missing_data = data return missing_data def missing_data_deta...
# Vermont Police Tools - Tools for cleaning Vermont police data # # Written in 2020 by BTV CopWatch <<EMAIL>> # # To the extent possible under law, the author(s) have dedicated all copyright # and related and neighboring rights to this software to the public domain # worldwide. This software is distributed without any ...
import collections import itertools import numpy as np from qecsim import paulitools as pt import matplotlib.pyplot as plt import qecsim from qecsim import app from qecsim.models.generic import PhaseFlipErrorModel,DepolarizingErrorModel,BiasedDepolarizingErrorModel #from qecsim.models.planar import PlanarCode, PlanarMP...
from django.shortcuts import render, redirect from django.http import JsonResponse, HttpResponse from django.contrib.auth.decorators import login_required from django.contrib import messages from .models import ClassName, Student, Attendance from .forms import ClassNameForm, StudentForm, AttendanceForm from django.db i...
from downloader import Downloader from pymongo import MongoClient from descriptive_analysis import * from export_collection_data import * from datetime import datetime def connect_to_mongodb(): """ This function implements the connection to the mongoDb @returns connection (MongoClie...
import sys import os import numpy as np from matplotlib import gridspec sys.path.append(os.getcwd()) import matplotlib.pyplot as plt from load_model_data import * def main(): filename = None truth, context, target, npf = load_data_point(test_context_dataset = "Data/small_data/extreme_context_data_paths.pkl"...
"""Trace function arguments, return values and calls to other functions.""" import collections import attr from pytype.pytd import pytd from pytype.pytd import pytd_utils @attr.s class Attr(object): name = attr.ib() node_type = attr.ib() type = attr.ib() attrib = attr.ib() location = attr.ib() @attr.s c...
#!/usr/bin/python # Copyright (c) 2018, Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for detail...
# xpyBuild - eXtensible Python-based Build System # # Copyright (c) 2013 - 2018 Software AG, Darmstadt, Germany and/or its licensors # # 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 # # ...
import torch import torch.nn.functional as F from torch.autograd import Variable from math import exp def gaussian(window_size, sigma): gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)]) return gauss/gauss.sum() def create_window(window_size, channel): _1D_...