text
stringlengths
3.07k
12.6k
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. import unittest import matplotlib import matplotlib.pylab as plt import numpy as np from pyiron_atomistics.atomistics.st...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from typing import List, Tuple import hydra import pytest import torch from hydra.experimental import compose, initialize from omegaconf import OmegaConf as OC from mtrl.agent.components.encoder import make_encoder from mtrl.agent.ds.mt_obs import...
import numpy as np from collections import deque def is_connected(topology): """ Determines if a topology is a connected structure. Parameters ---------- topology : 2d binary ndarray A binary matrix representing the topology. A value of 1 is a solid element, 0 is a void elem...
"""This module provided tools that helped to write tests. .. deprecated:: 7.1 This module will be **removed in Sopel 8**. It formerly contained mock classes for the bot, its wrapper, and its config object. As the module is deprecated, so are they, and they will be removed as well. New code shoul...
import argparse import json import zipfile from tqdm import tqdm import os import random from glob import glob from typing import Dict, List, Tuple from zipfile import ZipFile import numpy as np import pandas as pd import statsmodels.formula.api as smf from ee.ee_number import Number from tifffile import imread def ...
from pymongo import MongoClient import bson import requests from bson.json_util import loads from bson.json_util import dumps import json class FLServerUpdateInvoke: def __init__(self, mongo_url, mongo_db, collection_name): self.mongo_url = mongo_url self.proxies = { "http": "http://p...
#!/usr/bin/env python3 # Run this in Python 3. # Author: <NAME> # Released under Apache license 2.0. # This script calculates take-home pay for a given CTC, for both an employee and a consultant. # # Assumptions: # 1) GST comes out of your pocket — you can't pass the GST along by grossing it up. # 2) This is for fi...
import pandas as pd import re import nltk import string import json import requests from decouple import config import math import os import argparse import unicodedata # Global Variables stopwords = nltk.corpus.stopwords.words('english') special_characters = string.punctuation def get_arg_parser(): """Allows ar...
import numpy as np import stk class AxialPaddlewheel(stk.metal_complex.MetalComplex): """ Represents a metal complex topology graph. Two distinct metal building blocks, one with five functional groups, one with four. Binding ligand building blocks with two functional groups are required for ...
import functools import io from typing import BinaryIO, Callable, List, Optional, TextIO, TypeVar, Union import numpy as np import pretty_midi from smart_open import open from mirdata import annotations T = TypeVar("T") # Can be anything def coerce_to_string_io( func: Callable[[TextIO], T] ) -> Callable[[Opti...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2019 by ShabaniPy Authors, see AUTHORS for more details. # # Distributed under the terms of the MIT license. # # The full license is in the file LICENCE, distributed with this software. # ----------------...
import os from pywebvue import App from pywebvue.modules import VTK from vtkmodules.vtkIOXML import vtkXMLPolyDataReader from vtkmodules.vtkFiltersGeneral import vtkExtractSelectedFrustum from vtkmodules.vtkFiltersCore import vtkThreshold # ----------------------------------------------------------------------------...
"""This module creates and handles distance matrices""" import itertools import numpy as np import sys def create(id_list, distance): """Create a distance matrix (as Matrix object). Calculate distance measures between all pairs of sequences. Args: id_list (list): list of sequence identifiers ...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2021 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. try: import pplog as logging except ImportError: import logging logger = logging.getLogger(__name__) import numpy as np ...
import pandas as pd import numpy as np import copy class HoltWintersResults(object): """ Results class for HoltWinters Attributes ---------- fitted: array-like y_hat values fitted by the model. endog: array-like Original data to which the model was fit. index: pd.Index ...
import asyncio import discord import re from discord.ext import commands from Cogs import Nullify # bot = None # url_regex = re.compile(r"(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?") def setup(bot): # This module isn't actually a cog - but it is a place # ...
# -*- coding: utf-8 -*- __author__ = "<NAME>" import numpy as np import sys import time import h5py import keras.backend as K import tensorflow as tf #----------------------------------------------------- def display_hd5_weights(hd5_file): data = h5py.File(hd5_file, 'r') print('_'*80) print('*** we...
# ----------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # ----------------------------------------------------------------------------- ""...
# coding=utf-8 import dropbox import os.path import subprocess import os import re import requests import win32api import tempfile import zipfile import time import argparse def get_file_win_properties(fname): propNames = ('Comments', 'InternalName', 'ProductName', 'CompanyName', 'LegalCopyright', 'Produc...
from opal_common.fetcher.providers.http_fetch_provider import HttpFetcherConfig import os from enum import Enum from sys import prefix import opal_client from opal_client.opa.options import OpaServerOptions from opal_common.confi import Confi, confi from opal_common.config import opal_common_config from opal_common.sc...
#!/usr/bin/python2.4 # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Does scraping for Firefox 2.0.""" import pywintypes import time import types from drivers import keyboard from drivers imp...
import time import datetime import uuid import os import sys import stat import os.path import threading import tarfile import hashlib import string import shutil import errno from future.utils import iteritems from pandaharvester.harvestercore import core_utils from pandaharvester.harvestercore.plugin_base import Pl...
import os import json import subprocess from shutil import copyfile from subprocess import PIPE, run as subprocess_run from typing import List, Dict from retry import retry from src.contracts.secret.secret_contract import swap_json from src.util.config import Config, config from src.util.logger import get_logger log...
""" Copyright (c) IBM 2015-2017. All Rights Reserved. Project name: storm-thunder This project is licensed under the MIT License, see LICENSE Serializable configuration functionality Deployment DSL -------------- We support multiple types of the deployment syntax. 1. The fully Hjson parseable version where deployme...
from decimal import Decimal from math import ceil from os import listdir from os.path import join, exists import matplotlib.pyplot as plt class BillingData(): def __init__(self, host): self.host = host self.cpu_pct = list() self.net_sent_mb = list() self.net_recv_mb = list() ...
from enum import Enum from typing import Any from .exceptions import LexerError, ErrorCode escape_sequence = { '\\': '\\', '\'': '\'', '\"': '\"', 'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\b' } class Location: def __init__(self, lineno: int,...
import keras import matplotlib import numpy as np import pandas as pd import urllib3 import tensorflow as tf import _utils as ut import matplotlib.pyplot as plt import seaborn as sns import scipy.stats as stats import os def joinLocalData(): path1 ='.csv' path2 ='.csv' path3 ='.csv' pat...
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ##...
# Copyright 2018 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
import random from PIL import Image, ImageDraw, ImageFont import requests from lxml import etree import base64 from flask import Flask import demjson import os import traceback app = Flask(__name__) def url_encode(url): return str(base64.urlsafe_b64encode(str(url).encode()).decode()) def url_decode(url): r...
import hashlib import pathlib from functools import wraps from itertools import chain try: import magic # from sys-apps/file consider python-magic ? except ImportError: pass from dateutil import parser from augpathlib import PrimaryCache, EatCache, SqliteCache, SymlinkCache from augpathlib import XopenPath, R...
import numpy as np import argparse from tensorflow.keras.layers import Input, Flatten, Dense, Reshape, Dropout, Embedding, Multiply, Activation, Conv2D, ZeroPadding2D, LocallyConnected2D, Concatenate, GRU, Lambda from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.layers import LeakyReLU from ...
""" Generate gl.py and gl_compat.py See : tools/requirements.txt We are using the opengl-registry project to extract this information from https://raw.githubusercontent.com/KhronosGroup/OpenGL-Registry/master/xml/gl.xml A local version gl.xml can also be used. Usage: # Fetch gl.xml from Khronos Github repo python g...
# -*- coding: utf-8 -*- # Copyright (c) 2011-2014, Camptocamp SA # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this #...
import PySimpleGUI as sg import json import os # used to load theme for window elements try: conf = open('resources/config.json') theme = json.load(conf) if 'theme' in theme: sg.theme(theme['theme']) except FileNotFoundError: sg.theme('DarkBlue3') def template_editing_window(sections, section...
from MS import * from MA import * from MSV import * def insert_reads(parameter_set, dataset_name, sequencer_name, file_queue, file_queue_2=None, runtime_file=None, coverage=50): #parameter_set.by_name("Number of Threads").set(16) #parameter_set.by_name("Use all Processor Cores").set(False) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals import pytest from pytest import raises, approx from utf8config.core import ( validate_key, extract_comment, remove_post_comment, Field, Section, Config, ) def test_validate_key(): validate_key("DEFAULT"...
# -*- coding: utf-8 -*- # Copyright (c) 2012-2015, Cenobit Technologies, Inc. http://cenobit.es/ # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain th...
from enum import Enum from typing import Iterable, Tuple import numpy class StatisticType(Enum): R2 = "R^2" RMSE = "RMSE" MSE = "MSE" def _compute_statistics(measured_values, estimated_values, statistics): """Calculates a collection of common statistics comparing the measured and estimated val...
#!/usr/bin/python3 """ app.py MediaWiki API Demos Holidays viewer: A demo app that fetches the day's holidays from Wikipedia with options to search for holidays of other dates, and login to add new holidays. MIT license """ from datetime import datetime from flask import Flask, render_templ...
# <NAME> # !pip install tensorflow==1.4 import tqdm import numpy import os import tensorflow as tf print(tf.__version__) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' tf.logging.set_verbosity(tf.logging.ERROR) #tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) # # Hyper-Parameters # LEARNING_RATE = 0.0001 ...
#!/usr/bin/python3 '''Advent of Code 2018 Day 13 solution''' from typing import TextIO, Any, Dict, List, Tuple, Set Input = Dict[str, Any] Coords = Tuple[int, int] Cart = Tuple[int, int, int, int] def up(z: Coords, c: Cart, inputs: Input) -> Cart: '''Move cart up''' if inputs['map'][z[0]][z[1]] == '|': ...
from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D from keras.layers import LeakyReLU import keras.backend as K import numpy as np import cv2 import json import matplotlib.pyplot as plt import datetime import os import random...
''' handle aspects of covid data including as infection rates, death rates and hospital admissions ''' import json import csv import time import sched import logging from uk_covid19 import Cov19API logging.basicConfig(filename='logfile.log', level=logging.DEBUG) ''' open the config file and assign variables to its co...
import pickle from typing import Dict, List, Tuple import dgl import torch import torch.nn import torch.nn.functional from matplotlib import pyplot from openforcefield.topology import Molecule from nagl.dataset.dataset import MoleculeGraphDataLoader, MoleculeGraphDataset from nagl.dataset.features import ( AtomCo...
""" Class for managing the ftp mode """ import datetime import hashlib import math import re from ftplib import FTP from io import BytesIO, StringIO from os import mkdir, path, remove, rmdir, walk from StateManager import StateManager from utils import handle_failure, retry_function def log(*content): """ Lo...
#!/usr/bin/env python from ..common import * from urllib import parse import random from time import sleep import xml.etree.ElementTree as ET import datetime import hashlib import base64 import logging from urllib import error import re __all__ = ['icourses_download'] def icourses_download(url, merge=False, output_d...
import cv2 import numpy as np # cap = cv2.VideoCapture(0) #카몌라 불러오기 # if cap.isOpened() == False: #카메라 열림 확인 # exit() # while True : # ret, img = cap.read() #카메라 읽기 # cv2.imshow('preview', img) #읽은 이미지 보여주기 # if cv2.waitKey(10) >= 0 : #10ms간 대기, 입력이 있으면 종료 # break # # 연결 끊기 # cap....
# -*- coding: utf-8 -*- u"""Arquivo de configuração do Django.""" import datetime import logging from os.path import abspath from os.path import basename from os.path import dirname from os.path import join from os.path import normpath from configurations import Configuration from configurations import values DJANGO...
from flask import Flask, render_template, request, redirect, url_for from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///expenses_tracker.db' db = SQLAlchemy(app) #Database: #1)Table User: class User(db.Model): __tablena...
#!/usr/bin/env python3 import base64 import hashlib import itertools import json import os import re import sqlite3 import time import uuid import zipfile from pydub import AudioSegment EXTRA_DIGIT = re.compile('\d+$') DECK_ID = 1578170359311 MODEL_ID = 1578170379751 SEPERATOR = "\u001F" CARD_SQL = "INSERT INTO c...
''' api 存在问题: - 并发请求时,且前一请求正在查询会导致卡死 ''' import time from pymongo import MongoClient from flask import Flask, request, jsonify, Response from flask_restful import Api, Resource, reqparse from werkzeug.datastructures import Headers from conf.config import MongoDBConfig app = Flask(__name__) client = MongoClient(MongoD...
# Copyright © 2021 <NAME>, <NAME> and <NAME> # This file is part of the mdma library and licensed under the terms of the MIT license. # For a copy, see the LICENSE file in the root directory. from mdma import fit from experiments.causal_discovery.pcalg import estimate_skeleton, estimate_cpdag from mdma import utils fr...
import os import base64 import binascii from importlib import import_module from django.http import FileResponse from rest_framework.authentication import SessionAuthentication, BasicAuthentication, get_authorization_header from rest_framework.permissions import IsAuthenticated from rest_framework.response import Res...
import sys, sim """ Conversion factors for subsecondtime (femtoseconds) to other units """ class Time: FS = 1. PS = 1e3 NS = 1e6 US = 1e9 MS = 1e12 S = 1e15 """ Register an object as being a hooks listener. Will register hooks callback functions to the object's member functions with matching (lowerc...
import six import random from mission import Mission, MissionEnvironment, MissionStateBuilder # Simple multi-agent mission, with 2 agents and an observer based on: # https://github.com/Microsoft/malmo/blob/master/Malmo/samples/Python_examples/multi_agent_test.py class MultiAgent(Mission): def __init__(self, ms_p...
# Copyright (c) 2019 NVIDIA Corporation import torch from .metrics import word_error_rate def __ctc_decoder_predictions_tensor(tensor, labels): """ Decodes a sequence of labels to words """ blank_id = len(labels) hypotheses = [] labels_map = dict([(i, labels[i]) for i in range(len(labels))])...
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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 appli...
import os.path from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset from PIL import Image import imageio import random import torch import numpy as np def normalize(exp): # exp: H X W X C # Normalize data # x mean = -0.03465565666556358 # x std = 4.961168...
""" .. module:: WindPrediction WindPrediction ************* :Description: WindPrediction :Authors: bejar :Version: :Created on: 06/09/2017 9:47 """ from __future__ import print_function import os import sys import json import pandas as pd import numpy as np import math import keras.backend as K import pprint im...
# Copyright (C) 2017 <NAME> <<EMAIL>> """ Transform the fits image to jpeg form after some preprocessings, so as to generate images for the paper required. Three images are prepared 1. cropped region under cmap b {id}_b.jpeg 2. cropped region under cmap gray invert {id}_i.jpeg 3. cropped region under cmap b with mann...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ mod_mesma.py is a module containing functions to organize and preprocess the landsat data before running the decision tree and mesma. It contains the functions: mesma() Created on Mon Aug 16 15:00:25 2021 @author: <NAME> """ import ee # Define the MESM...
from ..flow.plotting import FlowPlot from ..flow import transform from matplotlib.colors import LogNorm, LinearSegmentedColormap from .conftest import create_linear_data, create_lognormal_data import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np import pytest sns.set(style="whit...
# Created by <NAME> and <NAME>. # Last edit 12-JAN-2020 # Short changelog: # 12-JAN-2020: added more information to header and ID line of output # fasta files. Adding contig identifier to fasta header was # required in particular. # 08-JAN-2020: removed functionality to slice on both reference and # target...
import json from django import http from django.shortcuts import render # Create your views here. from django.views import View from django.contrib.auth.mixins import LoginRequiredMixin from django_redis import get_redis_connection from apps.goods import models from utils.response_code import RETCODE class CartsVi...
import math import random import warnings from functools import partial from typing import Dict import calibration as cal import optuna import torch import torch.nn.functional as F from torch import Tensor, nn from torch.optim import Adam from torch.optim.lr_scheduler import OneCycleLR from torch.utils.data import Dat...
#!/usr/bin/python # Copyright 2016, IBM # Copyright 2016, <NAME> <<EMAIL>> # # 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 requir...
#add parent dir to find package. Only needed for source code build, pip install doesn't need it. import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(os.path.dirname(currentdir)) os.sys.path.insert(0,parentdir) import gym, logging from mp...
# -*- coding: utf-8 -*- # pylint:disable=protected-access """ Experiment node for EVC ======================= Experiment nodes connecting experiments to the EVC tree The experiments are connected to one another through the experiment nodes. The former can be created standalone without an EVC tree. When connected to a...
import os, copy from flask_api import status from models.main import * from models.appendix import * from models.segment import * from models.prescription import * from models.notes import ClinicalNotes from flask import Blueprint, request from flask_jwt_extended import (create_access_token, create_refresh_token, ...
import json import logging from pathlib import Path from typing import Union import hydra import numpy as np import torch import yaml from omegaconf import OmegaConf from torch.utils.data import DataLoader from src.data import ag_news from src.data.dataset import DownstreamDataset from src.eval_utils import centroid_...
from amdnet.hierarch_model import Hierarch_MEGNetModel, HierarchGraphModel from amdnet.data.graph import GaussianDistance from amdnet.data.crystal import CrystalGraph from amdnet.utils.preprocessing import get_graph_from_schnet_data from amdnet.layers import _CUSTOM_OBJECTS from tensorflow.keras.backend import relu fro...
import base58 import base64 import hashlib import rlp import secrets import math from nacl.hash import blake2b from nacl.encoding import RawEncoder from aeternity import identifiers def _base58_encode(data): """create a base58 encoded string with checksum""" return base58.b58encode_check(data) def _base58...
from torch.utils.data import Dataset from torch import tensor, cat, stack, FloatTensor, Tensor, save import ray from torch.nn.utils.rnn import pad_sequence from tqdm import tqdm import pickle from pathlib import Path from torch.utils.data import DataLoader from .BaseNet import StochasticActor from torch.optim import Ad...
""" Various utilities that don't fit anwhere else. """ from itertools import zip_longest from typing import Any, Callable, Dict, List, TypeVar, Union import random import torch import numpy import spacy from spacy.language import Language as SpacyModelType from models.custom_allennlp.elmo_dependencies.params import ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @Author: <NAME> (<EMAIL>) # @Date: 2020-07-29 # @Filename: test_configuration.py # @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause) import inspect import io import os import unittest.mock import pytest from sdsstools import Configuration, get_...
from torchvision import datasets, transforms import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from argparse import ArgumentParser from tqdm import tqdm import time import numpy as np ########### # file imports / path issues import os import sys ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse from collections import OrderedDict, namedtuple import inspect import functools import os import re import sys import types import warnings from tfi.base import _GetAttrAccumulator from tfi.par...
''' Name: Shashank ******* Roll No: 015 Implementation of the Unification Function ''' import re class Token(object): def __init__(self, tok_type, value): self.tok_type = tok_type self.value = value def __str__(self): return f"Token({self.tok_type}, {self.value})" def __repr__(se...
from robot.api.parsing import ( ModelTransformer, Token, EmptyLine, Comment, ModelVisitor, ForHeader, End, IfHeader, ElseHeader, ElseIfHeader, ) from robotidy.decorators import check_start_end_line from robotidy.utils import round_to_four, is_suite_templated class AlignTestCas...
# coding=utf-8 from __future__ import absolute_import, division, print_function import logging import scipy.stats import numpy as np import torch from tqdm import tqdm from torchvision import transforms from vit_iqa.modeling_vit_iqa import VisionTransformer, CONFIGS from torch.utils.data import DataLoader, Sequenti...
import os import unittest from datetime import datetime, timezone from time import monotonic from unittest.mock import MagicMock, call from sight_machine import BinaryLoggerBis, BinaryLoggable, InvalidClass class TestBinaryLoggerBis(unittest.TestCase): log_file = '/tmp/test_binary_logger.log' def setUp(self...
#!/usr/bin/env python from __future__ import print_function import os import sys import shlex import subprocess from private_key import d """ Utils """ def run_cmd(cmd): try: args = shlex.split(cmd) return subprocess.check_output(args) except Exception as ex: return str(ex) """...
# Copyright (c) 2019, <NAME>. All rights reserved. # # This work is licensed under the Creative Commons Attribution-NonCommercial # 4.0 International License. To view a copy of this license, visit # http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to # Creative Commons, PO Box 1866, Mountain View, CA 940...
# sql/functions.py # Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from .. import types as sqltypes, schema from .expression import ( ClauseList, Fu...
import aiohttp.web import dataclasses from functools import wraps import logging from typing import Any, Callable import json import traceback from dataclasses import dataclass import ray import ray.dashboard.utils as dashboard_utils from ray._private.job_manager import JobManager from ray._private.runtime_env.packagi...
#!/usr/bin/env python # -*- coding: utf-8 -*- from unittest import TestCase import mock import json import urllib2 from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from libdict.macmillan import models, query_site words = [ 'take-on', # multiple keys in last sense 'yours', # intr...
from ..utility import settings import bpy from bl_ui import ( properties_render, properties_data_camera, #properties_data_lamp, #properties_material, ) class PhotonRenderer(bpy.types.RenderEngine): # These three members are used by blender to set up the # RenderEngine; define its internal name, visible na...
import urllib.parse from random import randrange from typing import Optional from django.db import models from credo_classification.drf import DjangoPlusViewPermissionsMixin from users.models import User class Team(models.Model): """ CREDO Team imported from original CREDO Database. The id and name fie...
import numpy as np from matplotlib import transforms as mtransforms from matplotlib.ticker import ( FixedFormatter, FixedLocator, LogFormatter, LogLocator, MultipleLocator, Formatter) class FractionalOctaveFormatter(FixedFormatter): def __init__(self, n_fractions=1): if n_fractions...
import numpy as np import pandas as pd import yfinance as yf from yahoo_earnings_calendar import YahooEarningsCalendar import mktanalytics as ma from tqdm.notebook import tqdm def nearest(items, pivot): return min(items, key=lambda x: abs(x - pivot)) def get_atm_vol(undl_list, weeks=1, calc_strangle=False, target_pr...
# Python implementation of the KD Tree # Para su uso es necesario instalar la librería matplotlib from heapq import heappush, heappop from collections import namedtuple import matplotlib.pyplot as plt from treelib import Node, Tree from math import inf class Point: def __init__(self, data): sel...
# -*- coding: utf-8 -*- ''' General management functions for salt, tools like seeing what hosts are up and what hosts are down ''' # Import python libs import os import subprocess # Import salt libs import salt.key import salt.client import salt.output def status(output=True): ''' Print the status of all kn...
from django.conf import settings from django.views.generic import DetailView from django.contrib import messages from django.contrib.auth.decorators import login_required, permission_required from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.shortcuts import render, reverse, redirect,...
import rdflib from rdflib import URIRef, Literal from rdflib import RDFS, OWL, XSD import operator # Used in sorting from sets import Set # Defaults defaultLanguage = 'en' # Set up the graph g=rdflib.Graph() OPDS = rdflib.Namespace('http://joinedupdata.org/ontologies/philanthropy/') g.namespace_manager.bind('opds',...
"""Command-line interface to rhasspyasr-deepspeech-hermes""" import argparse import asyncio import logging import typing from pathlib import Path import paho.mqtt.client as mqtt import rhasspyhermes.cli as hermes_cli from rhasspyasr_deepspeech import DeepSpeechTranscriber from rhasspysilence import SilenceMethod from...
#!/usr/bin/env python # filename: scpcr_demultiplexing.py # # Copyright (c) 2015 <NAME> # License: The MIT license (http://opensource.org/licenses/MIT) # # 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 th...
# OTFlowProblem.py import math import torch from torch.nn.functional import pad from src.Phi import * def vec(x): """vectorize torch tensor x""" return x.view(-1,1) def OTFlowProblem(x, Phi, tspan , nt, stepper="rk4", alph =[1.0,1.0,1.0] ): """ Evaluate objective function of OT Flow problem; see Eq....
import torch from torch import nn import numpy as np import pandas as pd import gym import collections #使用cuda加速训练 device = 'cuda' if torch.cuda.is_available() else 'cpu' class DQNReplayer: def __init__(self, capacity): self.memory = pd.DataFrame(index=range(capacity), c...
import warnings from sklearn.svm import OneClassSVM from sklearn.model_selection import train_test_split from sklearn.multiclass import OneVsRestClassifier as ORC from sklearn.neighbors import KNeighborsClassifier as knn from sklearn.naive_bayes import GaussianNB import pandas as pd import get_images import get_landmar...