text
stringlengths
3.07k
12.6k
import glob import json import os import time from pathlib import Path from urllib.parse import urljoin import click import requests from .providers import aws, azure, gcp from .utils import COLORS, Config, colored config_exist = glob.glob(str(Path.home() / ".pygrid/cli/*.json")) or None prev_config = ( max(conf...
# -*- coding: utf-8 -*- import asyncio import functools from enum import Enum from .jid import Jid from .stream import Stream, StreamCallbacks from .errors import Error from .utils import signalEvent, resolveHostPort from .namespaces import CLIENT_NS_URI from .stanzas import StreamHeader, StreamFeatures, Presence from...
import uuid class Teacher: def __init__(self, **kwargs): self.name = kwargs["name"] self.designation = kwargs["designation"] def create_quiz(self, subject, questions): quiz = Quiz(subject, questions) return quiz def assign_quiz(self, quiz, student): student.receiv...
import numpy as np def make_hashable(o): """ Makes a hashable object from a dictionary, list, tuple or set to any level, that contains only other hashable types (including any lists, tuples, sets, and dictionaries). Based on http://stackoverflow.com/questions/5884066/hashing-a-python-dictionary ...
import collections import random import matplotlib.pyplot as plt import numpy as np from environment.random_walk_19_states import RandomWalk def constant_factory(n): probability_list = np.ones(n) return lambda: probability_list / np.sum(probability_list) class Agent: def __init__(self, env, n): ...
"""============================================================= ~/fn_portal/tests/api/test_GearList.py Created: 21 Sep 2021 09:07:16 DESCRIPTION: The gear list api endpoint should return a list of available gears. By default it should only include active, documented gears but will return all gears if all=t (...
"""Retrieves text posts from reddit using the reddit API, and saves them in a csv format. Authors: <NAME>, <NAME>, <NAME>, <NAME> """ import datetime import argparse import requests import pathlib import csv TODAY = datetime.datetime.utcnow() ONE_MONTH_DELTA = datetime.timedelta(days=30) MINUS_ONE_MONTH = TODAY - O...
# -*- encoding: utf-8 -*- import enum from collections.abc import Set from copy import copy from enum import IntEnum from typing import AbstractSet @enum.unique class EcodeLocale(IntEnum): JA = 0 KO = 1 ZH_HANT = 2 ZH_HANS = 3 EN = 4 @classmethod def from_code(cls, code: str) -> 'EcodeLo...
# As documented in the NRPy+ tutorial module # Tutorial-GRMHD_Equations-Cartesian.ipynb # this module will construct useful quantities # for the IllinoisGRMHD implementation of # general relativistic hydrodynamics (GRHD) # # Author: <NAME> # zachetie **at** gmail **dot* com # Step 1: import all needed ...
import mdtraj as md import numpy as np import pytest from openff.toolkit.topology.molecule import Molecule from openff.toolkit.utils import get_data_file_path from openff.units import unit from openff.utilities.testing import skip_if_missing from openff.utilities.utilities import has_package from openff.interchange.co...
#!/usr/bin/env python -B #============================================================================== #title :scoring.py #description :functions related to scoring #author :<NAME> #date_created :06 November 2015 #version :0.1.0 #usage : #python_version :2.7.9 #=================...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-LOG 蓝鲸日志平台 is licensed under the MIT License. License for BK-LOG 蓝鲸日志平台: ------------------------------------------------...
""" Experiment utilities. """ from common.log import log, LogLevel import math import models import numpy import torch def training_arguments(parser): """ Default training arguments. :param parser: argument parser :type parser: argparse.ArgumentParser """ parser.add_argument('-n', '--normaliz...
#!/usr/bin/env python3 """An image analyser that finds the three most common colors in an image. Title: Dominant Colors Description: Develop a program that accepts an image either via the devices's camera (if it has one) or a file dialog. Your program should intelligently determine three of the most dominant colors i...
import cherrypy from girder.api.rest import Resource from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, RestException, boundHandler from girder.constants import AccessType, TokenScope from girder.models.file import File def _add_parents(d...
import sys from lxml import etree from pathlib import Path this_dir = Path(__file__).resolve().parent # Set up the customizer import. project_dir = this_dir.parents[1] x4_customizer_dir = str(project_dir.parent / 'X4_Customizer') if x4_customizer_dir not in sys.path: sys.path.append(x4_customizer_dir) # ...
# -*- coding: utf-8 -*- """ Test definition parsers """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import unittest from lxml import etree from chemdataextractor import Document from chemdataextr...
# -*- coding: utf-8 -*- # Copyright 2018 IBM Corp. 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 ...
#!/usr/bin/env python """ Write Toytree or TreeNode to newick string """ import re from .utils import NW_FORMAT # globals ILLEGAL_NEWICK_CHARS = r":;(),\[\]\t\n\r=" ITERABLE_TYPES = set([list, set, tuple, frozenset]) # formatters FF = "%0.6g" NF = "%s" DF = FF # ":" + FF class NewickWriter(object): """ W...
# Copyright 2021 Alibaba Group Holding Limited. 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 ...
# Copyright (c) 2018 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...
from __future__ import print_function, division import pandas as pd from datetime import timedelta from copy import deepcopy class TimeFrame(object): """A TimeFrame is a single time span or period, e.g. from "2013" to "2014". Attributes ---------- _start : pd.Timestamp or None if None and ...
"""isort:skip_file.""" import argparse import math import os import sys import time sys.path.append("../") import torch from ray import tune from torch.utils.data import DataLoader from tqdm import tqdm from beta_rec.core.train_engine import TrainEngine from beta_rec.models.vbcar import VBCAREngine from beta_rec.uti...
# -*- coding: utf-8 -*- ''' Story World Object =================== ''' from __future__ import annotations __all__ = ('World',) from builder import VERSION_MSG, __DEFAULT_LOG_LEVEL__, __VERSION__, __TITLE__ from builder.commands.optioncmd import OptionParser from builder.commands.scode import SCode, SCmd from build...
"""The core implementation of a hyperbolic tessellation of the Poincare disk by uniform, regular polygons. """ from collections import deque from collections import namedtuple from geometry import Point from geometry import orientation from hyperbolic import PoincareDiskLine from hyperbolic import PoincareDiskModel fr...
import cv2 import os import sys import numpy as np import pandas as pd from glob import glob import itertools from visionfuncs.io import sorted_glob from visionfuncs import cbcalib from visionfuncs import geometry from epypes.compgraph import CompGraphRunner from .io import open_images_all from .graph import CGCalibr...
''' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ SALT RSS Calibration This program performs the flux calibration and heliocentric velocity correction for a FITS file reduced by the SALT RSS pipeline. The target FITS file is typically a 2D flux spectrum of a galaxy, but may but may be other...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : wzdnzd # @Time : 2018-04-25 import logging import multiprocessing import os import random import re import sys import time import warnings import simplejson as json from simplejson.decoder import JSONDecodeError import requests from requests.exceptions im...
import pandas as pd import numpy as np import matplotlib.pyplot as plt url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/" + \ "csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_{}_global.csv" deaths = pd.read_csv(url.format('deaths'), index_col=1) cases = pd.read_csv(url.form...
# -*- coding: utf-8 -*- import logging from datetime import datetime from typing import Any, Dict, Optional from pyathena.error import DataError _logger = logging.getLogger(__name__) # type: ignore class AthenaQueryExecution(object): STATE_QUEUED: str = "QUEUED" STATE_RUNNING: str = "RUNNING" STATE_SU...
# -*- coding: utf-8 -*- import json import os import sys try: # For Python 3.0 and later from urllib import parse from urllib.request import urlopen, HTTPError, URLError, Request except ImportError: # Fall back to Python 2's urllib2 from urllib2 import urlopen, HTTPError, URLError, Request import pk...
from datetime import datetime from .... import conf from .utils import filter_hstore from ....utils.json import jsonb def ga4gh_service_info_v10(row, authorized_datasets=None): return { 'id': conf.beacon_id, 'name': conf.beacon_name, 'type': { 'group': conf.ga4gh_service_type_...
# MIT License # # Copyright (c) 2020 Gcom # # 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...
# coding=utf-8 """ Module to train a network using init files and a CLI. """ import argparse import os from typing import Dict, List, Tuple, Union import tensorflow as tf import deepreg.config.parser as config_parser import deepreg.model.optimizer as opt from deepreg.callback import build_checkpoint_callback from d...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu """ (c) 2013 - <NAME> Bytes Utils :author: <NAME> Generic byte functions. Should work in Python 3 and 2 """ import socket import struct import six import uuid import binascii from . import network def bytes_to_int(byte_array, big_endian=Tr...
""" Copyright 2017-present Airbnb, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, sof...
import warnings from functools import partial, wraps from collections.abc import Mapping class Assert: """ An object to collect assertions and print results after they've all been evaluated Examples -------- >>> from ploomber.validators import Assert >>> assert_ = Assert() >>> assert_...
"""memorised module - container for the memorise python-memcache decorator""" __author__ = '<NAME> <wes [at] 1stvamp [dot] org>' __docformat__ = 'restructuredtext en' __version__ = '1.0.1' from functools import wraps from hashlib import md5 import inspect import itertools import memcache from memorised import compat...
import numpy as np import numpy.testing as npt from stumpy import stamp, core import pytest import naive test_data = [ ( np.array([9, 8100, -60, 7], dtype=np.float64), np.array([584, -11, 23, 79, 1001, 0, -19], dtype=np.float64), ), ( np.random.uniform(-1000, 1000, [8]).astype(np.fl...
#!/usr/bin/env python from __future__ import print_function, division import numpy as np from rdkit import Chem from rdkit import rdBase from rdkit.Chem import AllChem from rdkit import DataStructs import rdkit.Chem.QED as QED import scripts.sascorer as sascorer import os import pickle import torch from chemprop.train...
from __future__ import annotations import typing as t import enum from sqlalchemy import ( Integer, String, ForeignKey, JSON, Table, Float, MetaData, Column, ) from sqlalchemy.orm import ( relationship, RelationshipProperty, ) from ...common.sqlalchemy import ( OptionalColu...
from copy import copy from dataclasses import dataclass, fields, is_dataclass from typing import TypeVar, Any, Generic, List, Optional, Tuple, Union, cast T = TypeVar("T") class Empty: def __repr__(self) -> str: return "<empty>" empty = Empty() class ImmerframeError(RuntimeError): pass class No...
import random import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.autograd as autograd from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from torch.nn import Parameter from bert import BertConfig, BertModel import bert from torchvision.mo...
# Copyright 2017 The TensorFlow 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 applica...
""" Calculation Parser | Cannlytics Author: <NAME> Contact: <<EMAIL>> Created: 6/8/2021 Updated: 6/8/2021 License: MIT License <https://opensource.org/licenses/MIT> """ import pandas as pd import numpy as np import re import random # Prepare testing dataset tags = np.array(['tag'+str(i) for i in np.random.randint(10...
import datetime #Django Imports from django import forms from django.conf import settings from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, Div, Submit from crispy_forms.bootstrap import FormActions #Local App Imports import contacts.models as cont import utils.forms as ut...
#deeperic import os import glob import csv import tensorflow as tf import numpy as np from PIL import Image def _read_raw_images(path, is_directory=True): """Reads directory of images in tensorflow Args: path: is_directory: Returns: """ images = [] png_files = [] jpeg_files = [] reader = t...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import torch from torch import nn import torchvision.models from torchvision.models.resnet import BasicBlock, Bottleneck import argparse import numpy as np import json import sys from types import SimpleNamespace from cdfsl import make_cdfsl_loader from core import EvaluateFewShot from datasets import ImagenetBasedDat...
#! /usr/bin/python # import datetime import logging import signal import time from dataclasses import dataclass from dataclasses_json import dataclass_json from rewop.collector.axpertcollector import AxpertCollector, AxpertResponse from rewop.collector.pylontechcollector import PylontechCollector, PowerSystemResponse...
""" This file contains the LPSolver part of the algorithm The LPSolver uses the symbolic bounds and the Gurobi solver to verify properties as Safe, or to produce candidates for counter examples. Author: <NAME> <<EMAIL>> """ import os import numpy as np import gurobipy as grb from src.algorithm.esip import ESIP c...
from setuptools import setup, Extension from setuptools.command.build_ext import build_ext from setuptools import Command import platform # force setuptools to use MS Visual Studio 2010 instead of 2008 on Python 2.x if platform.system() == 'Windows': import distutils.msvc9compiler orig_find_vcvarsall = distut...
#!/usr/bin/env python3 import argparse import concurrent.futures import glob import itertools import io import os import subprocess def cargo_boilerplate(binary): return ['cargo', 'run', '--bin', binary, '--release', '--'] # binjs_generate_prediction_tables takes a dictionary output path # whereas binjs_encode t...
import statistics import datetime def create_report(repositories: list) -> str: """ :param repositories: a list of dictionaries containing repositories metadata :return: the generated HTML report """ """ Generate an HTML report for the crawled repositories """ now = datetime.datetime...
import pytest from mikeio.xns11 import ( read, Xns11, QueryData, FileNotOpenedError, DataNotFoundInFile ) def test_query_validate(): # Bad topo id type with pytest.raises(TypeError): QueryData(666) # Bad reach type with pytest.raises(TypeError): QueryData("topoid1", reach_name=66...
# -*- coding: utf-8 -*- # # escpos/impl/daruma.py # # Copyright 2015 Base4 Sistemas Ltda ME # # 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 ...
import arcpy arcpy.env.overwriteOutput = True arcpy.CheckOutExtension('Spatial') import file_functions from file_functions import * import logging def least_cost_centerline(DEM, source): '''returns a rough centerline using least cost path from source''' check_use([DEM, source]) try: # make direct...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/16 11:50 # @Author : bxf # @File : TMP_PAGINATOR.py # @Software: PyCharm from concurrent.futures import ThreadPoolExecutor from model.FUNC.GROUP_OPT import * from model.util.TMP_DB_OPT import * from model.util.PUB_LOG import * class Pag...
import json import sys sys.path.append('..') from torch.utils.data.dataset import Dataset from pathlib import Path import pickle import pdb import torch import numpy as np import argparse import os import sys import librosa import numpy as np from tqdm import tqdm import warnings warnings.filterwarnings("ignore") def ...
# -*- coding: utf-8 -*- # Copyright 2013-2017 Ent. Services Development Corporation LP # # Redistribution and use of this software 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 copyrigh...
from controller import Worker import os import torch import sys import cv2 from PIL import Image #from multiprocessing import Pool class Job: "Model - data logic" def __init__(self, settings): if not isinstance(settings, type(None)): if 'youtube.com' in settings['video']: # if given YouTu...
import torch from torch.jit import script, trace import torch.nn as nn from torch import optim import torch.nn.functional as F import csv import random import re import os import unicodedata import codecs from io import open import itertools import math import numpy as np from scipy.spatial import distance from seq2se...
# -*- coding: utf-8 -*- from __future__ import print_function import argparse import sys import logging from .sniffer import Sniffer from .printer import MessagePrinter, PairedPrinter, PrintOptions VALID_LEVELS = 'debug, info, warn, error' VALID_PARTS = 'header, data, all, none' VALID_TRANSPORTS = 'auto, buffered, f...
from ..filters import run_filters, cheap_filters, all_filters from ..utils.misc import invert, values_map_to_same_key, one_hot from ..utils.graph_ops import get_node_cover from .alldiffs import count_alldiffs import numpy as np from functools import reduce # TODO: count how many isomorphisms each background node parti...
''' created on Dec 28, 2019 @author: georgeretsi ''' import argparse import torch.optim as optim from torchvision import datasets, transforms from torch.autograd import Variable import torchvision.models as models from scipy.special import erfinv import math from sparse_utils import * from wide_resnet import WideRe...
# -*- coding: utf-8 -*- """Solar resource downscaling utility methods. Created on April 8 2019 @author: gbuster """ import numpy as np import pandas as pd import logging from rex.utilities.solar_position import SolarPosition from rex.utilities.utilities import get_lat_lon_cols from nsrdb.all_sky import CLEAR_TYPES ...
import math from typing import Optional from absl import flags from functools import partial import jax from jax import random import jax.numpy as jnp import numpy as np from transformers import FlaxCLIPModel from nerf import utils FLAGS = flags.FLAGS @partial(jax.jit, static_argnums=[0]) def semantic_loss(clip_mod...
# -*- coding: UTF-8 -*- import time import traceback import threading import random import module.msgStream as msgStream from load_config import config from module.RSShubApiPackage import RSShubsPackage from module.RSS import pushlist, rsshubevendeal from helper import getlogger, data_read_auto, data_save, TempMemory ...
import os import numpy as np import cv2 as cv import random import paddle class DataLogger(object): def __init__(self): self.clear() def clear(self): self.value = 0 self.sum = 0 self.cnt = 0 self.avg = 0 def update(self, value, n=1): self.v...
#!/usr/bin/env python import multiprocessing if __name__ == '__main__': multiprocessing.set_start_method('forkserver') import re from itertools import product, chain import warnings import numpy as np import pandas as pd import seaborn as sn import matplotlib as mpl import matplotlib.pyplot as plt import nltk fr...
class Player: def __init__( self, username: str, player_class, ): self.username = username self.invetory = Inventory() self.player_class = player_class self.skills = None self.gender = None self._count = 0 self.direction...
"""Provides a coroutine to run yara rules against a set of files.""" # Standard Python Libraries from functools import lru_cache, partial from glob import iglob import hashlib import itertools import json import logging from multiprocessing import Pool import os import signal import string from typing import Any, Dict...
import creds from db import Messages, get_db from twilio.rest import Client from twilio.base.exceptions import TwilioRestException # Connect to Twilio account_sid = creds.twilio_account_sid auth_token = creds.twilio_auth_token twilio_client = Client(account_sid, auth_token) @app.command("/text_welcome") async def t...
#!/opt/splunk/bin/python """ Description: Use urlscan.io to get a look at what a particular website is requesting in the background. The script accepts a list of strings (domain, IP, and/or SHA256): | urlscanio $ioc$ or input from the pipeline (any field where the value is a domain, IP, and/or SHA256). The firs...
# Practice Python problems solved in as few lines as possible # Problems from: http://codingbat.com/python # Python > List - 1 > sum3 def sum3(nums): return nums[0] + nums[1] + nums[2] print("sum3: " + str(sum3([1, 2, 3]))) # Python > List - 1 > rotate_left3 def rotate_left3(nums): return [nums[1], nums[2...
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score, confusion_matrix from lifelines import CoxPHFitter from datautils.dataset import Dataset from datautils.data import Data from datautils.helper import save_output from tqdm import tqdm i...
"""Defines transformers NER pipe""" from typing import Dict, Iterable, Iterator, List, Sequence, Sized, cast import spacy import torch import torch.nn as nn import torch.nn.functional as F import transformers from spacy.gold import GoldParse, iob_to_biluo, spans_from_biluo_tags from spacy.tokens import Doc from camph...
import time import os import NTG_base import NTGGetCore import total import RPC_Thread def ProcessLink(input): found = 'https://pan.baidu.com/s/' in input if found == True: found = '#list/' in input if found == True: input = NTG_base.getSubstr(input, 'https://pan.baidu.c...
# Note these functions are similar to, but separate from name/title mungers # found in the ckanext importer. That one needs to be stable to prevent # packages changing name on reimport, but these ones can be changed and # improved. import re from ckan import model def munge_name(name): '''Munges the package name...
""" Very simple Lambda function to Stop/Start Instances depending on targets declared in the environment variables of this function. Updates: - 01 Oct. 2018: Adding support of suspend/resume for AGSs """ import boto3 import json import logging import os from typing import List, Dict, AnyStr, Callable LOGGER = lo...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging from collections import OrderedDict from typing import Callable, Dict, List # pyre-fixme[21]: Could not find module `gym`. import gym import numpy as np import reagent.types as rlt import torch from reagent.c...
import os import bookworm.sample_data as sample import bookworm.util as util import hypothesis.strategies as st from hypothesis import given, example class TestTempFileName: file_extensions = st.sampled_from(['.pdf', '.djvu']) file_names = st.tuples( st.characters(blacklist_characters=['\"']), file_...
#!/usr/bin/env python # This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2017 DataONE # # Licensed under the Apache License, Version 2.0 (t...
import os, hashlib, json, base64 # Print coloured debug messages if True debug_messages = True def debug(message, status='debug'): if debug_messages: colours = { "grey": "\033[0;37m", "yellow_bold": "\033[1;33m", "red": "\033[0;31m", "green": "\033[0;32m", ...
"""Converts variant data to parquet Most parsing is done with 'bytes' instead of 'string' for efficiency reasons. """ import collections import multiprocessing import os import shutil import subprocess import sys import tempfile import logging from logging import debug from pathlib import Path import pandas as pd...
from __future__ import absolute_import, division, print_function import copy import errno import json import os import os.path as osp import random import sys import time import warnings import yaml import numpy as np import PIL import torch from PIL import Image __all__ = [ 'mkdir_if_missing', 'check_isfile', 'r...
# linux-utils: Linux system administration tools for Python. # # Author: <NAME> <<EMAIL>> # Last Change: February 9, 2020 # URL: https://linux-utils.readthedocs.io """ Python API for Linux networking tools. The functions in this module make it possible to inspect the current network configuration of a Linux system, w...
from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse, Http404,HttpResponseRedirect from django.http import HttpResponse from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User # from app.forms import * from app.forms import Si...
def reporterror(errorr, suggest): print(errorr + suggest) #import modules from win10toast import ToastNotifier from external.contacts import contact_addnew import pyttsx3 import speech_recognition as sr import wikipedia import re import datetime import requests from pprint import pprint import pyautogui import psut...
import os import glob import torch import torch.nn as nn from torch import optim from torch.nn.utils.rnn import pad_sequence def random_init_weights(model): """randomly initialize weights""" for name, p in model.named_parameters(): if "weight" in name: if p.requires_grad: n...
# -*- encoding: utf-8 -*- ''' ------------------------- @File : utils.py @Time : 2022/01/07 19:14:00 @Author : <NAME> @Contact : <EMAIL> @Desc : utils scripts ------------------------- ''' import time, os, json import logging from datetime import datetime from tqdm import tqdm import matplotlib.py...
from __future__ import absolute_import import inspect import logging import warnings import threading import lore.env import lore.estimators from lore.util import timed, before_after_callbacks lore.env.require( lore.dependencies.XGBOOST + lore.dependencies.SKLEARN ) import xgboost logger = logging.getLogge...
from sklearn import * import time from numpy import * ''' # for real data: # imitating the real data # n_feature = 16 # feature1 Gender is 0 or 1 bool # feature2 Age in [14, 61] int # feature3 Height ...
import wx.dataview as wxdv class Url(object): """真正的数据行""" def __init__(self, app: str, gen_way: str, alias: str, relate_path: str, full_path: str, split_path: str, app_file: str, belong_app: str, code_app_name: str, url_level: str, op: bool=False ): self.op = op...
# Copyright (c) 2008-2016, <NAME> <<EMAIL>> # Copyright (c) 2016, <NAME> <<EMAIL>> # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # this file has not been updated for a while, so coding style needs some love #pylint: disable-msg=broad-except #pylint: disable-msg=attribute-defined-outside-init #pylint...
""" Utilities used in the code """ import os import time import typing from datetime import datetime import pytz from prompt_toolkit import print_formatted_text from prompt_toolkit.formatted_text import FormattedText from tzlocal import get_localzone DAY_IN_SECONDS = 60 * 60 * 24 PATH_MAX_SIZE = 30 class Text: ...
from multiprocessing import Pool, cpu_count import gzip import os try: import orjson as json except: import json # from pycountry import languages try: from utf8.utils import * from utf8.blacklist import * except: # to solve issue with ipython executing this import from utils import * from...
""" Module provides regularization energy functions for ddf. """ from typing import Callable import tensorflow as tf def gradient_dx(fx: tf.Tensor) -> tf.Tensor: """ Function to calculate gradients on x-axis of a 3D tensor using central finite difference. It moves the tensor along axis 1 to calculate the...
from PIL import Image from mmxai.interpretability.classification.lime.lime_multimodal import * from mmf.models.mmbt import MMBT from mmf.models.visual_bert import VisualBERT # prepare image, text and model for the explanation generation pipeline img_path = "tests/mmxai/interpretability/classification/lime/gun.jpeg" i...
import numpy as np import sys import math from itertools import combinations class Sphere: def __init__(self, name, mass, radius, xpos, ypos, zpos, xvel, yvel, zvel): self.name = name self.radius = radius self.mass = mass self.pos = np.array((xpos, ypos, zpos)) self.vel = n...