text
stringlengths
3.07k
22.1k
# main.py COPYRIGHT Fujitsu Limited 2021 from argparse import ArgumentParser from collections import OrderedDict import copy import os import torch from torchvision import transforms as T import torchvision.datasets as datasets from tqdm import tqdm #from cac import auto_prune import sys sys.path.append('../../') fro...
# Copyright 2013 <NAME> and <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 agreed to in wri...
# functions used to create the belif histogram of the model. import os import numpy as np import matplotlib.pyplot as plt from model.evaluate import model_predict from model.neural_model import * from model.train import * from model.utils import * def confidence_create(parameters, data_prob, data_label_pred, data_labe...
import tensorflow as tf import numpy as np def uvgg_pconv(name, input_layer, mask, concat_layer=None, concat_mask=None, n_in=None, n_out=None, weights=None, is_bnorm=False, is_train=False, is_reLU=True, is_trainable=True): """ If weights exist, weigh...
import requests import json import sys import time import argparse import datetime import dateutil.parser as dp import psycopg2 if sys.version_info[0] < 3: print ('python2 not supported, please use python3') sys.exit (0) # Parse command line args parser = argparse.ArgumentParser(description='TRX tokens payments sc...
import numpy as np import scipy.stats import pytest from skypy.utils.photometry import HAS_SPECLITE @pytest.mark.flaky def test_sampling_coefficients(): from skypy.galaxies.spectrum import dirichlet_coefficients alpha0 = np.array([2.079, 3.524, 1.917, 1.992, 2.536]) alpha1 = np.array([2.265, 3.862, 1.92...
import datetime import re from decimal import Decimal from collections import defaultdict from sqlalchemy import and_, or_ from grand_cedre.web.log import logger from grand_cedre.utils import start_of_month, end_of_month, get_or_create from grand_cedre.service import get_calendar_service from grand_cedre.models.contr...
# -*- coding: utf-8 -*- """ This is for setting the massive args object to default values, so you can experiment with YOLACT in Spyder or Jupyter without thinking at all about all the absurdly many command-line options. To use it to get eval args, do this: from default_args import get_default_args args = get_defa...
# -*- coding: utf-8 -*- # Copyright 2020 The Matrix.org Foundation C.I.C. # # 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 require...
import os import numpy as np from PIL import Image class FileLoader(): def cache(self, path): return True def save_cache(self, cache_path): pass def load_cache(self, cache_path): pass def __call__(self, path): raise NotImplemented class ImageLoader(FileLoader): de...
# https://github.com/LLSean/data-mining import os import sys import tensorflow as tf import logging logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) import numpy as np import argparse from util import * from sklearn.metrics import * class FFM(object): def __init__(self,...
#!/usr/bin/env python3 import os import csv import json from collections import OrderedDict import requests from cachecontrol import CacheControl from cachecontrol.caches.file_cache import FileCache from datetime import datetime from filters.local_authority_type import LocalAuthorityTypeMapping from filters.organisat...
import pandas as pd from selenium import webdriver from bs4 import BeautifulSoup from abc import ABC, abstractmethod from tqdm import tqdm from datetime import datetime from time import sleep import requests from src.news_scraping.scraper_ import NewsScraper """Scraping News""" def pprint(html: str): """pretty p...
import os import re import numpy from .loader_base import DatasetLoader from .loader_base import RegularFPSChannel from .loader_base import VideoAndPPGSession from .loader_base import VideoChannel class UBFCDatasetLoader(DatasetLoader): # abstract - to override def _get_session_records(self): retu...
import rfl.core as core import tflite class DataType: def __init__(self, value): self._value = value @property def bitwidth(self): table = { tflite.TensorType.INT8: 8, tflite.TensorType.UINT8: 8, tflite.TensorType.INT16: 16, tflite.TensorType.INT32: 32, tflite.TensorType.I...
""" Views """ __author__ = '<NAME>' __maintainer__ = '<NAME>' __copyright__ = 'ADS Copyright 2015' __version__ = '1.0' __email__ = '<EMAIL>' __status__ = 'Production' __credit__ = ['<NAME>'] __license__ = 'MIT' from flask import request, current_app from flask.ext.restful import Resource from flask.ext.discoverer imp...
import sys import os import shutil import time from multiprocessing import Process from PyQt5 import QtWidgets from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QPushButton, QGraphicsScene, QGraphicsPixmapItem from Ui_AppMainWindow import Ui_MainWindow from SetupAnchors import SetupAnchors from generator im...
import cmd2 import os import argparse from prettytable import PrettyTable from prettytable import MSWORD_FRIENDLY import random import string import json module = {} campaign_list = [] class main(list): """Main function to initialize variables and calls the cmd2 package for the godaddy module """ def __init__...
#!/user/bin/env python # coding=utf-8 """ @project : DeviceManager @ide : PyCharm @file : db_helper @author : wuhoubo @desc : 数据库交互 @create : 2019/5/27 21:03:31 @update : """ import threading import time from enum import unique, Enum import pymysql from helper.config_helper import ConfigHelper from model...
# The MIT License (MIT) # # Copyright (c) 2017-2018 <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, modif...
from contextlib import contextmanager from typing import Iterator from pychoir import ( NE, AllOf, And, AnyOf, EqualTo, GreaterThan, HasLength, IsInstance, IsNoneOf, Not, Or, ResultsTrueFor, ) def test_and(): assert AllOf is And assert [1] == [And(IsInstance(i...
# -*- coding: utf-8 -*- """ ======= py7file ======= A module wrapping and unifying the python standard lib file handling modules and built-in functions with a simple and intuitive high-level api. Think: os.path, shutil, file, open, ... with convenient method based access. The Py7File class allows to do simple copy, m...
from random import shuffle, choice from PIL import Image import os import numpy as np import matplotlib as plt import random import glob import matplotlib.pyplot as plt from matplotlib.pyplot import figure import time import pandas as pd import cv2 import math from random import randint def load_rgb_data(IMAGE_DIREC...
import random from flask import url_for import numpy from connector import cloudSqlCnx import config from datetime import datetime cnx = cloudSqlCnx() # Open connection def writeLogoView(brandName, brandArchetypeId, brandFieldId, fontFamilyId, fontWeightNum, textTransformId, primaryColorId, shapeId, ipAddress, reques...
import torch from torch import nn from flows.utils import \ standard_gaussian_log_likelihood_with_mask, \ sample_gaussian_with_mask, sum_except_batch, \ assert_correctly_masked import torch.nn.functional as F from egnn.models import EGNN class EGNN_output_h(nn.Module): def __init__(self, in_node_nf, o...
# coding=utf-8 # Created by <NAME> on 2016/4/26. import random class LeafNode : def __init__(self, keys, values): self.type = "leaf" self.keys = keys self.values = values self.parent = None def __str__(self): return '(key: ' + str(self.keys) + ', val: '+ str(self.value...
# -*- coding: utf-8 -*- """ Created on Tue Dec 15 15:28:30 2020 @author: """ import numpy as np from numpy import sqrt, arctan2, pi as π, cos, sin from scipy.spatial.transform import Rotation import sys _vec_0 = np.array([0., 0., 0.]) _vec_x = np.array([1., 0., 0.]) _vec_y = np.array([0., 1., 0.]) _vec_z = np.array(...
import os import socket import inspect import sys os.environ["LC_ALL"] = "en_US.UTF-8" def tcpPortConnectionTest(ipaddr, port, timeout=None): conn = None try: conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if timeout: conn.settimeout(timeout) try: con...
import copy import os import unittest from io import StringIO from pubmed_lookup import command_line, Publication, PubMedLookup article_url = 'https://www.pnas.org/content/109/12/4674' citation = ( '<NAME>, <NAME>, <NAME>, <NAME>, <NAME> (2012). ' 'Arabidopsis synchronizes jasmonate-mediated defense with ins...
#!/usr/bin/env python3 # -*-coding:utf-8 -*- # ============================================================================= """ @Author : <NAME> @File : gen_lidar_from_rosbags.py @Date created : 2021/10/19 @Maintainer : <NAME> @Email : <EMAIL> """ # ===============================...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat May 16 14:06:10 2020 @author: macbookariel """ # 16-05-20: # En este documento vamos a hacer la regresión lineal múltiple. # Para ello primero copiamos la plantilla de pre procesado de datos y cambiamos # lo que sea necesario # Plantilla de Pre Proce...
""" This module implements incremental reduced error pruning (IREP*) algorithm for growing classification rulesets. See https://www.let.rug.nl/nerbonne/teach/learning/cohen95fast.pdf """ # Author: <NAME> <<EMAIL>> # License: MIT import pandas as pd import math import random import copy from ruleset import base from ...
from tkinter import * from tkinter.scrolledtext import ScrolledText from tkinter.filedialog import askopenfile import subprocess import os version = "beta-v1.0.2" # class ArgumentEntry(Entry): # def __init__(self, master=None, index=None): # super().__init__(Entry) # self.master = mas...
import argparse import glob import json import os import random import xmltodict from fuzzywuzzy import process from pygments import highlight, lexers, formatters ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR_CHUMMER = os.path.join(ROOT_DIR, 'data') DATA_FILE_PROCESSED = os.path.join(ROOT_DIR, 'sr5_da...
# [ ] load .buildconfig.json.sh # [ ] check root: True from __future__ import print_function __all__ = ['BuildCommand', 'BuildTarget', 'BuildConfig'] import sys import os import json import hashlib import fnmatch import re import collections import pipes import shlex import yaml class SchemaDict(collections.Mutab...
# HLF 2D ("Hidden Linear Function, 2-Dimensional") # Examples from Google Cirq tutorial # https://quantumai.google/cirq/tutorials/hidden_linear_function import numpy as np import cirq def make_interesting_circuit( n_qubits = 3 ): """ Create smaller version of the HLF2D problem (3, 4 and 5 qubits) q is...
from transformers.data.processors.glue import DataProcessor from transformers import T5Tokenizer, PreTrainedTokenizer from dataclasses import dataclass from torch.utils.data.dataset import Dataset from torch.utils.data import DataLoader import torch import jsonlines import os import random from typing import List, Opti...
# Lint as: python # # Authors: Vittorio | Francesco # Location: Turin, Biella, Ivrea # # This file is based on the work of Francisco Dorr - PROBA-V-3DWDSR (https://github.com/frandorr/PROBA-V-3DWDSR) """Training class and some functions for training RAMS""" import tensorflow as tf from tensorflow.keras.utils import Pr...
import sys import os from pathlib import Path import pytest import chardet import pandas as pd import numpy as np sys.path.insert(0,os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from get_edgar.common.utils import clean_cname,csv_clean_cname,csv_getencoding,json_to_csv,match_cname,\ gen_ngrams, sear...
import requests import json import datetime import logging from urllib3.util.retry import Retry def createVoltSession(token, tenantName): now = datetime.datetime.now() apiToken = "APIToken {0}".format(token) s = requests.Session() s.headers.update({'Authorization': apiToken}) urlBase = "https://{0...
""" Input and Output ports for PortMidi. There is no need to use this module directly. All you need is available in the toplevel module. PortMidi documentation: http://portmedia.sourceforge.net/portmidi/doxygen/ """ import threading from ..ports import BaseInput, BaseOutput, sleep from . import portmidi_init as pm _...
import uuid from django.contrib.auth import get_user_model from rest_framework import status from rest_framework.exceptions import ValidationError from rest_framework.permissions import ( AllowAny, ) from rest_framework.response import Response from rest_framework.views import APIView from bot.bot_handlers.login ...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0. import argparse from awscrt import io, mqtt, auth, http from awsiot import mqtt_connection_builder import sys import threading import time import json from datetime import datetime, timedelta from astral import ...
import os import numpy as np import time import matplotlib.pyplot as plt; plt.ion() from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection import Planner def tic(): return time.time() def toc(tstart, nm=""): print('%s took: %s sec.\n' % (nm,(time.time() - tstart))) def ...
#!/usr/bin/env python from __future__ import print_function, unicode_literals, division import base64 import collections import io import gzip import os import re import struct import traceback import unicodedata try: from io import BytesIO except ImportError: # Python 2 legacy try: from cStringIO ...
import torch import torch.nn as nn import os from itertools import zip_longest from sklearn.metrics import roc_auc_score import numpy as np class Learner(): def __init__(self, net, results_dir='./tmp/results/'): self.net = net if hasattr(self.net, 'regression') and self.net.regression: ...
import sqlite3 from wtforms.validators import ValidationError from werkzeug.local import LocalProxy from SingSong.Database import get_db, close_db from SingSong import login_manager from flask import current_app from flask_login import UserMixin from itsdangerous import TimedJSONWebSignatureSerializer as Serializer imp...
# Copyright (c) 2020-2021 Science and Technology Facilities Council. # # All rights reserved. # # Modifications made as part of the fparser project are distributed # under the following license: # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the follow...
"""定义hook的执行 WebHook: def _if_valid_source(self): 验证是否合法来源的webhook 可以post一个自定义的key,{"sec_code":"my_password"},然后验证这个key是否符合 github的webhook按照github的签名方式来计算:header里有一个'X-Hub-Signature', 然后对payload用预先在github上预留的code进行签名,二者相符则签名通过 自定义的webhook,就直接在post发送的json里加一个{"sec_code":"....
from citylearn import CityLearn from pathlib import Path import numpy as np from tensorflow.keras.layers import Input, Dense, Lambda import tensorflow as tf import torch.optim as optim import random import torch tf.keras.backend.set_floatx('float64') # Select the climate zone and load environment climate_zone = 1 da...
#!/opt/conda/envs/pCRACKER_p27/bin/python # All rights reserved. from collections import Counter, defaultdict, OrderedDict import cPickle as pickle import errno from itertools import combinations, permutations import itertools import os import shutil import subprocess import matplotlib matplotlib.use('Agg') import mat...
from datetime import datetime from itertools import chain from random import randint from django.contrib.auth.decorators import login_required from django.contrib.formtools.wizard.views import SessionWizardView from django.http import HttpResponseRedirect, Http404, HttpResponse from django.utils.decorators impo...
# Copyright (c) 2021 PaddlePaddle Authors. 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 app...
import ast import asyncio import dataclasses import logging import re from copy import deepcopy from typing import Any, List, Optional, Tuple import pandas as pd import pyjq from aiohttp import ClientSession from jinja2 import Environment, StrictUndefined, Template, meta from jinja2.nativetypes import NativeEnvironmen...
import numpy as np import tensorflow as tf from model import policy_net, q_net class ReplayBuffer: """ A simple FIFO experience replay buffer for TD3 agents. """ def __init__(self, obs_dim, act_dim, size): self.obs1_buf = np.zeros([size, obs_dim], dtype=np.float32) self.obs2_buf = np.zeros([size, obs_dim], dty...
import numpy as np from scipy.optimize import linear_sum_assignment import copy import pmht.kalman as kalman class Target: def __init__(self, id, t_id, delta_t): self.id = id self.t_id = t_id self.delta_t = delta_t self.state = np.zeros((4, 1), dtype=np.float) self.P = np....
import ctypes from .internal import _SDL, errcheck from .enum import CEnum class DisplayMode(ctypes.Structure): _fields_ = ( ('format', ctypes.c_uint32), ('width', ctypes.c_int), ('height', ctypes.c_int), ('refresh_rate', ctypes.c_int), ('driver_data', ctypes.c_void_p) )...
""" path_disclosure.py Copyright 2006 <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 ...
# -*- encoding: utf-8 -*- from datetime import timedelta from django.test import TestCase from django.conf import settings from django.core.exceptions import ValidationError from interval.fields import timedelta_topgsqlstring from interval.fields import timedelta_tobigint from interval.fields import range_check fro...
#!/usr/bin/python3 import pandas as pd import sqlite3 import os import argparse import urllib.request import time import sys from zipfile import ZipFile from shapely.geometry import Point # Schema of geonames databases from # as of 07/01/2020 CITY_COLNAMES = ['Geonameid', 'Name', 'Asci...
from __future__ import annotations import random from functools import partial from io import BytesIO from typing import Generator from pyaes import AESModeOfOperationECB from pyaes.util import append_PKCS7_padding, strip_PKCS7_padding from . import utils from .common import Cipher from .exceptions import InvalidDat...
#!/usr/bin/env python3 # # Copyright 2013 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import shutil import tempfile import time import unittest from unittest import mock from cros.factory.test import even...
import functools import typing as tp import gin import haiku as hk import jax import jax.numpy as jnp import numpy as np from haiku._src import utils # pylint: disable=no-name-in-module from huf.module_ops import Linear from huf.module_ops import dropout as _dropout from huf.types import Activation from jax.experimen...
import subprocess from os.path import dirname, exists import yaml import logging import argparse from instances_connection import (logger, ReplaceCertificatesConfig, ReplaceCertificatesError) def get_dict_from_yaml(yaml_path): with open(yaml_pa...
import vtk #import tkinter import time # https://kitware.github.io/vtk-examples/site/ # See vtkInteractorStyle for key binding def cylinder(): colors = vtk.vtkNamedColors() # Set the background color. bkg = map(lambda x: x / 255.0, [26, 51, 102, 255]) colors.SetColor("BkgColor", *bkg) # This create...
''' Created on 17 avr. 2015 "Read the Hamamatsu header,DATA, Time Delays and Wavelenghs for the given __filepath @author: saldenisov ''' import numpy as np from dataclasses import dataclass from pathlib import Path from typing import Union, Tuple from devices.service_devices.project_treatment.openers.Opener import Op...
# coding: utf-8 # --- # # _You are currently looking at **version 1.3** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-machine-learning/resources/bANLa) course resource._ ...
# import dependencies import curses,time,os import getpass,sys,signal import shutil from distutils.dir_util import copy_tree from datetime import datetime # current directory os.chdir(".") menu = os.listdir() menu.sort() # Some global Strings file = "It is a File" copy = " Selected File: " search = "Ctrl + S to searc...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import os import getopt import sys from PIL import Image SINGLE_IMG_SIZE = 300 def supprted_format(ext): exts = ['.jpg', '.png', '.jpeg'] if ext.lower() in exts: return True return False def expand_user_path(p): p = os.path.expanduser(p) re...
import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Linear, ReLU, Sequential, LeakyReLU, Tanh, ELU from dgl.nn.pytorch.conv import GINConv from dgl.nn.pytorch.glob import SumPooling, AvgPooling, MaxPooling from torch.nn import BatchNorm1d from . import register_model from .base impor...
# -*- coding: utf-8 -*- import argparse import logging import os import pandas as pd from fooltrader import settings from fooltrader.api import event from fooltrader.api.finance import get_balance_sheet_items, get_income_statement_items, get_cash_flow_statement_items from fooltrader.api.quote import get_security_lis...
import numpy as np import logging tests = [ np.array( [[6, 1, 2, 21], [4, -6, 16, 2], [3, 8, 1, 2] ], dtype=np.float64), np.array( [[5, -3, 2, -8, 1], [1, 1, 1, 1, 0], [3, 5, 1, 4, 0], [4, 2, 3, 1, 3] ...
""" .. module:: Helper :platform: Platform Independent :synopsis: This module is for handling all misc utility functions """ import sys import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" import pysrt from typing import List, Optional from colorama import init, Fore, Back, Style import textwrap from typing imp...
#!/usr/bin/python # coding:utf-8 # https://github.com/zeusintuivo/SublimeText3-DeepL __version__ = "1.0.0" import platform python_version=platform.python_version() # try: # # Sublime environment assumption # import sublime # except ImportError: # # Outside of Sublime assumption, create a dummy Sublime # ...
from typing import List, Dict, Callable from expanded_checklist.checklist.test_suite import TestSuite from expanded_checklist.checklist.editor import Editor from munch import Munch import itertools from collections import OrderedDict, namedtuple from typing import Tuple, Collection import src.config as cfg import reg...
import pandas as pd import json itemList = ['1001','1004','1006','1011','1018','1026','1027','1028','1029','1031', '1033','1035','1036','1037','1038','1039','1042','1043','1052','1053','1054','1055', '1056','1057','1058','1082','1083','2003','2010','2015','2031','2033','2047','2051', '2052','2055','2065','2138',...
from pandas import read_csv from IPython.display import display import numpy as np import math from matplotlib import pyplot as plt import matplotlib ############################### ####<NAME> ##### ############################### def convert_GPS_lat_long(df): for index, row in df.iterrows(): lat_viejo = row["GP...
import torch import numpy as np import time import os from torch.utils.tensorboard import SummaryWriter from attack import FastGradientSignUntargeted from metrics import RetrivalAccMetric def fit(train_loader, val_loader, model, loss_fn, optimizer, scheduler, n_epochs, cuda, log_interval, model_save_dir, metr...
from typing import ( cast, Dict, Generator, Iterable, Optional, Tuple, Union, ) from dataladmetadatamodel.datasettree import DatasetTree from dataladmetadatamodel.mappableobject import MappableObject from dataladmetadatamodel.metadatapath import MetadataPath from dataladmetadatamodel.metada...
""" Drivemapping Wrapper: The following program acts as a wrapper to enable and obscure the drive mapping and removal process from endusers behind a GUI while keeping a log of the last error found, if any. The current version of this program includes a flag-launch option "--not_clicked", which could b...
import datetime import os import time from bsbolt.Align.AlignReads import BisulfiteAlignmentAndProcessing from bsbolt.CallMethylation.ProcessMethylationContigs import ProcessContigs from bsbolt.Impute.kNN_Impute import ImputeMissingValues from bsbolt.Index.RRBSIndex import RRBSBuild from bsbolt.Index.WholeGenomeIndex i...
#!/usr/bin/env python # GIMP Plug-in for the Sega Dreamcast MR file format # Copyright (C) 2019 by BBHoodsta # # Encoding based on logotools(pngtomr.c) source code by <NAME> (ADK) # http://napalm-x.thegypsy.com/andrewk/dc/ # # Decoding based on Selfboot Inducer (mrimage.pas) source code by SiZiOUS # http://sizious.co...
from functools import partial import torch import torch.nn as nn import torch.nn.functional as F import numpy as np def get_activation(name, inplace=True): if name == 'gelu': return nn.GELU() def get_normalization(name, channels): if name == 'ln': return nn.LayerNorm(channels) class MLP(nn.Module): def...
#!/usr/bin/env python3 """ result swatches """ import os, sys sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) from glob import glob import re import math from json_tricks import loads from pathlib import Path from lib.ColorUtils import ColorUtils c = ColorUtils() def read_json_fil...
import os import re from rdopkg import exception from rdopkg.utils.cmd import GerritQuery from rdopkg.utils.git import git from rdopkg.utils import specfile from rdopkg.utils import log from rdopkg.actionmods import rdoinfo def package(default=exception.CantGuess): pkg = os.path.basename(os.getcwd()) if not ...
from __future__ import print_function, division, absolute_import import argparse,time,logging,os import random, shutil, warnings import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torchvision import torchvision.transforms as transforms import tor...
# -*- coding: utf-8 -*- # Fielname = dmu380_offline_sim.py """ IMU fusion. Created on 2018-03-15 @author: dongxiaoguang """ # import import os import struct import platform import math import numpy as np from ctypes import * from ctypes import wintypes # globals VERSION = '1.0' R2D = 180.0 / math.pi class SIM_COMF...
# Importing important libraries from fenics import * import numpy as np import matplotlib.pyplot as plt import ufl import dolfin # Parameters for the solver parameters["form_compiler"]["quadrature_degree"] = 4 parameters["form_compiler"]["cpp_optimize"] = True parameters['allow_extrapolation'] = True # Loading the m...
""" Dungeon Assistant """ from __future__ import print_function import random import json import urllib import boto3 from boto3.dynamodb.conditions import Key, Attr VERSION = 1.0 # --------------- Helpers that build all of the responses ---------------------- def build_speechlet_response(title, output, reprompt_tex...
#! /usr/bin/env python3 ############################################################################### # # Copyright 2019-present PEERING POLICY MANGER project (<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 obta...
import json import base64 import datetime import random import math import requests from operator import itemgetter from collections import defaultdict, Counter from django.shortcuts import render, redirect from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from djan...
# -*- coding: utf-8 -*- """.. moduleauthor:: <NAME>""" from typing import AsyncIterable, Tuple, Optional, Callable, Dict, Type, Union, Iterable, List, \ final, Final from dataclasses import dataclass from pan.public.interfaces.pub_net_interface import NetSavable from pan.public.constants.net_tree_id_constants imp...
#!/usr/bin/env python """ * ******************************************************* * Copyright (c) VMware, Inc. 2016-2018. All Rights Reserved. * SPDX-License-Identifier: MIT * ******************************************************* * * DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT * WARRANTIES OR CONDI...
# <NAME> import csv import matplotlib.pyplot as plt import numpy as np import random import seaborn as sns def get_turnover_rates(turnover_f): """Reads in turnover data from a file. :param turnover_f: :return: """ fieldnames = ["player", "rate"] reader = csv.DictReader(open(turnover_f...
#This module deals with sound and music playback from random import choice from pygame.mixer import * from pygame.mixer import Sound as Mixer_sound pre_init(44100,-16, 2, 2048) init() set_num_channels(50) # event queue for scheduling end events from pyaudiogame import event_queue # Position is to controll the 3D audi...
# # dsdobjects/complex_utils.py # - copy and/or modify together with tests/test_complex_utils.py # import warnings from functools import reduce from itertools import chain, groupby class SecondaryStructureError(Exception): pass def make_pair_table(ss, strand_break = '+', ignore = set('.')): """ Return a sec...
import datetime as dt from pathlib import Path import bz2 import tarfile import numpy as np import iris from cosmic.config import CONSTRAINT_ASIA, CONSTRAINT_EU def convert_cmorph_0p25deg_3hrly_to_netcdf4_month(data_dir, output_dir, year, month): lat = np.linspace(-59.875, 59.875, 480) lon = np.linspace(0.1...
import os import numpy as np import pandas as pd from skbio.stats.composition import (closure, alr, alr_inv, multiplicative_replacement) from sklearn.preprocessing import LabelEncoder from cmdstanpy import CmdStanModel, CmdStanMCMC import tempfile import json import xarray as xr imp...
#Included: role, delrole import discord from discord.ext import commands from discord.ext.commands import Bot from discord.utils import find import asyncio import logging import os import time import requests import random from time import localtime, strftime from datetime import datetime import subproce...
import math import torch import torch.nn as nn import torch.nn.functional as F from .operations import OPS from tools.utils import parse_net_config class Block(nn.Module): def __init__(self, in_ch, block_ch, head_op, stack_ops, stride): super(Block, self).__init__() self.head_layer = OPS[head_op...