text
stringlengths
3.07k
12.6k
from ipaddress import ip_address import pytest from koalified.types import ( country, date, date_time, floating_number, ip, match, number, one_of, phonenumber, postal, strict_date, strict_datetime, string, string_boolean, ) def test_string_boolean(): assert...
import numpy as np from robust_smc.data import ExplosiveTANSimulator from robust_smc.sampler import LinearGaussianBPF, RobustifiedLinearGaussianBPF, LinearStudentTBPF from tqdm import trange from sklearn.metrics import mean_squared_error, median_absolute_error from experiment_utilities import pickle_save # Experime...
import os import os.path as osp import torch import numpy as np import scipy.sparse as sp from torch_sparse import coalesce from torch_geometric.data import (InMemoryDataset, Data, download_url, extract_zip) from torch_geometric.utils.convert import to_networkx import networkx #impo...
import os import random import shutil from collections import OrderedDict import numpy as np import torch import torch.nn as nn from imgaug import imgaug as ia from termcolor import colored from torch.autograd import Variable #### def convert_pytorch_checkpoint(net_state_dict): variable_name_list = list(net_stat...
import _pickle as cPickle import gzip import random import numpy as np import os,time,subprocess,glob from stackPH import lifeVect,histVect from scipy.ndimage.morphology import distance_transform_edt from skimage.filters import threshold_otsu from skimage.transform import resize import matplotlib.pyplot as plt from mpl...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import random import string import sys from django.conf import settings from django.core.urlresolvers import clear_url_caches from django.core.cache import cache from cms import api from cms.apphook_pool import apphook_pool from cms.appresolver import c...
####################################################################### # Copyright (C) # # 2016-2018 <NAME>(<EMAIL>) # # 2016 <NAME>(<EMAIL>) # # Permission given to modify the code as long as you keep this # # declar...
from flask import jsonify, request, url_for from flask_login import login_required from volunteercore import db from volunteercore.api import bp from volunteercore.volops.models import TagCategory, Tag from volunteercore.api.errors import bad_request from volunteercore.decorators import requires_roles # API GET endpo...
import json import logging import time import ccxt from ccxt.base.errors import ( BaseError, InsufficientFunds, OrderNotFound, NetworkError) from decimal import Decimal as D log = logging.getLogger(__name__) def handle_errors(f): def wrapper(*args, **kwargs): r = {'type...
"""Test Home Assistant package util methods.""" import asyncio import logging import os from subprocess import PIPE import sys from asynctest import MagicMock, call, patch import pkg_resources import pytest import homeassistant.util.package as package RESOURCE_DIR = os.path.abspath( os.path.join(os.path.dirname(...
# -*- coding: utf-8 -*- """Subspace Outlier Detection (SOD) """ # Author: <NAME> <<EMAIL>> # License: BSD 2 clause import numpy as np import numba as nb from sklearn.neighbors import NearestNeighbors from sklearn.utils import check_array from ..utils.utility import check_parameter from .base import BaseDetector @nb...
""" The business model core of the application. """ from typing import List, Union from PIL import Image from .annotated_image import AnnotatedImage from .scaled_region2d import ScaledRegion2d from .timer import Timer from src.model import Size2d, Region2d def clearImagesOutsideRange( annotatedImages: List[Ann...
"""Support for Timers.""" from datetime import timedelta import logging import voluptuous as vol from homeassistant.const import CONF_ICON, CONF_NAME, SERVICE_RELOAD import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_component import EntityComponent from homeassistant.helpers.event...
from rubicon.objc import objc_method, at from travertino.size import at_least from toga_cocoa.libs import ( NSBezelBorder, NSOutlineView, NSScrollView, NSTableColumn, NSTableViewUniformColumnAutoresizingStyle ) from toga_cocoa.widgets.base import Widget from toga_cocoa.widgets.internal.cells impor...
import tweepy import os import io import logging import setup # pylint: disable=unused-import from setup import TWITTER_HANDLES, TEAM_ABBREVIATIONS from PIL import ImageFont, Image, ImageDraw import plotly.graph_objects as go logger = logging.getLogger() auth = tweepy.OAuthHandler( os.getenv("TWITTER_API_KEY"), ...
from ursina import * class InstancedEntity(Entity): def __init__(self, **kwargs): self.instance_group:InstancedGroup = None super().__init__(priority = 10, **kwargs) # Watches if any of the known attributes are being changed, then notifies the group entity. def __setattr__(self, name, val...
# -*- coding: UTF-8 -*- import textwrap import pytest from six import StringIO from six.moves import urllib from pydruid.client import PyDruid from pydruid.query import Query from pydruid.utils.aggregators import doublesum from pydruid.utils.filters import Dimension try: from mock import Mock, patch except Impor...
# Copyright (c) 2013, Frappe and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe def execute(filters=None): columns, data = [], [] process_list = get_process_list(filters.get("method_filter")) columns = get_columns(process_list) mrec_data = get...
""" A module containing the :py:class:`Policy` class and associated exceptions. """ class PermissionsError(Exception): """ Base class for :py:class:`Policy` violations. """ class ForbiddenError(PermissionsError): """ The provided user cannot do this action. """ pass class UserRequiredE...
import io import sys from ..request import Request from .base import BaseInterceptor from .http import URLLIB3_BYPASS # Support Python 2/3 try: import mock except Exception: from unittest import mock if sys.version_info < (3,): # Python 2 from httplib import ( responses as http_reasons, ...
import winappdbg import argparse import winapputil from winappdbg.win32 import PVOID, DWORD, HANDLE class DebugEvents(winappdbg.EventHandler): """ Event handler class. event: https://github.com/MarioVilas/winappdbg/blob/master/winappdbg/event.py """ """ BOOL HttpSendRequest( ...
from collections import Counter import numpy as np import pandas as pd import os from scratch12.ex04 import summarize_by_class, calculate_class_probability from sklearn.metrics import confusion_matrix, classification_report def train_test_split(df, test_size): """df=데이터 프레임, test_size=테스트 세트의 비율 학습 세트(X_trai...
""" Copyright 2014 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 agr...
import logging import re import os from os.path import getsize, isdir, join from functools import partial logger = logging.getLogger(__name__) BYTE_UNIT_FACTORS = {"B": 1., "KB": 1.e-3, "MB": 1.e-6, "GB": 1.e-9} def get_dir_size(target_dir, unit="MB", details=False, verbose=0, exclude=""): """ Compute the total...
import os import time from typing import Callable, Dict, List, Tuple import torch from torch import Tensor from torch.utils.data import DataLoader from .collection import AvgCollecter, EMACollecter from .console import ConsoleWriter def send_device(vs, device): if device is None: return vs if i...
# Copyright (c) 2017 <NAME> and <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: redistributions of source code must retain the above copyright # notice, this list of conditions and the fo...
# Made with python3 # (C) @FayasNoushad # (C) @BXBotz # Copyright permission under MIT License # All rights reserved by FayasNoushad # License -> https://github.com/FayasNoushad/Translator-Bot-V2/blob/main/LICENCE import os from pyrogram import Client, filters from pyrogram.types import InlineKeyboardMarkup, InlineKey...
import argparse import tempfile from glob import glob import os from zipfile import ZipFile import shutil from distutils.dir_util import copy_tree import re parser = argparse.ArgumentParser(description='Import/update static files from a Webflow export to this project.') parser.add_argument('webflow_zipfile', help='Pa...
from plastron import ldp, ore, rdf from plastron.namespaces import dcterms, dcmitype, ebucore, fabio, pcdm, pcdmuse, premis from plastron.files import LocalFileSource, RepositoryFileSource from PIL import Image # alias the rdflib Namespace ns = pcdm @rdf.object_property('members', pcdm.hasMember) @rdf.object_proper...
import sys import matplotlib import matplotlib.pyplot as plt import numpy as np import pandas as pd def grad_U(Ui, Yij, Vj, ai, bj, mu, reg, eta): """ Takes as input Ui (the ith row of U), a training point Yij, the column vector Vj (jth column of V^T), reg (the regularization parameter lambda), and et...
#!/usr/bin/env python # Copyright 2020 The Amber 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 requi...
import click import os from typing import List from click import Context, Option from .canvas import Canvas from .configure_logging import configure_logging from .display_options import DISPLAY_OPTIONS, add_options from .effect_cache import EffectCache from .effect_controller import EffectController from .effect_publ...
# Copyright (c) 2022, NVIDIA CORPORATION. # # 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...
##https://github.com/dcm-oss/blockade/ # # Copyright (C) 2014 Dell, 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 requir...
import serial from matplotlib import pyplot as plt import numpy as np import mpl_toolkits.mplot3d.axes3d as p3 import telnetlib import threading import kalman import time ref_nodes = {} pos = np.array([0.0,0.0,0.0]) k_pos = np.array([0.0,0.0,0.0]) acc_pos = np.array([0.0,0.0,0.0]) count = 0 iter_time = 4 baseSum = np....
"""pyazo upload views""" import os from typing import Tuple from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.http import HttpRequest, HttpResponse from django.shortcuts import get_object_or_404, redirect from django...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015 <NAME> <<EMAIL>> # # This file is part of hg_delivery # # hg_delivery is free software; you can redistribute it and/or modify it under # the terms of the M.I.T License. # from pyramid.httpexceptions import HTTPFound from pyramid.view import view_conf...
# Changed 2020 by Zenseact AB load("@bazel_skylib//lib:shell.bzl", "shell") load("//:rules.bzl", "LinterInfo") SUPPORTED_LANGUAGES = [ "python", "golang", "jsonnet", "ruby", "rust", "cc", "java" ] # Aspects that accept parameters cannot be called on the command line. # As I want to call ...
"""Optimistic Adam module. Forked from snt.optimizers.Adam. Reference: [1] <NAME>, <NAME>, <NAME>, <NAME>. Training GANs with Optimism. In International Conference on Learning Representations 2018 Feb 15. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function...
# 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, software # distributed under the Li...
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
try: from unittest.mock import patch except ImportError: from mock import patch import unittest from django.contrib.auth.models import AnonymousUser from django.template import Context, Template, TemplateSyntaxError from django.test import TestCase as DjangoTestCase from django_comments_xtd.tests.models impor...
""" A simple bot that presses buttons when emerging from block or hit stun. """ import time import random import csv import xml.etree.ElementTree as ET import NotationParser import movelist from Bot import Bot from TekkenGameState import TekkenGameState from BotData import BotBehaviors from NotationParser import Parse...
import gdsfactory as gf from gdsfactory.add_padding import get_padding_points from gdsfactory.component import Component from gdsfactory.components.straight import straight from gdsfactory.cross_section import strip from gdsfactory.path import euler, extrude from gdsfactory.snap import snap_to_grid from gdsfactory.type...
# SPDX-FileCopyrightText: <NAME> for Adafruit Industries # SPDX-FileCopyrightText: <NAME> for Adafruit Industries # SPDX-FileCopyrightText: 2019 Liz Clark for Adafruit Industries # # SPDX-License-Identifier: MIT """ Prop-Maker based Darksaber Adapted from the Prop-Maker based Master Sword code by <NAME> & <NAME> Adafr...
from flask import Flask import os import zipfile from flask import Flask, render_template, request,redirect, url_for, request, abort,\ session,jsonify from flask import send_file from datetime import datetime import psycopg2 import numpy as np from base64 import b64encode from werkzeug.urls import url_parse from ke...
import numpy as np import matplotlib.pyplot as plt from sklearn.cross_validation import StratifiedShuffleSplit from sklearn.metrics import accuracy_score from tqdm import tqdm as tqdm import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from malenov.dataset import...
#!/usr/bin/python # by tbw_lucilu - github.com/lucilu1320 # (@tbw_lucilu) import requests from jsbeautifier import beautify import sys,re import string import urllib3 blacklisted = [ "await", "break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "enum", "export", "e...
import json import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State from covidash.dashboard.data_store import DataStore import covidash.dashboard.figures as figures from covidash.dashboard.figures import DATA_TYPE_MAPPING data_store = Data...
#!/usr/bin/env python # -*- coding:utf-8 -*- # author:owefsad # software: PyCharm # project: lingzhi-webapi from django.db.models import Count from dongtai.endpoint import R, UserEndPoint from dongtai.models.asset import Asset from dongtai.models.vul_level import IastVulLevel from iast.base.agent import get_project_vu...
#coding=utf-8 import os import re import sys import pwd import grp import fcntl import urllib import logging import argparse from urlparse import urlparse, parse_qs import urlparse from ProcessHandler.lib.errors import AppImportError, ArgumentError REDIRECT_TO=getattr(os, 'devnull', '/dev/null') def daemonize(enab...
''' v0.2.0pre2 For reading opreations of bitmap photo(*.bmp). An optimized version with higher efficiency. Raw code: http://exasic.com/article/index.php?md=py-bmp ''' import array as _array class Image: def __init__(self, width, height, path = None, bgcolor = 0xffffff, virtual_memory = False, reado...
import torch import torch.nn as nn architecture_config = [ (7, 64, 2, 3), "M", (3, 192, 1, 1), "M", (1, 128, 1, 0), (3, 256, 1, 1), (1, 256, 1, 0), (3, 512, 1, 1), "M", [(1, 256, 1, 0), (3, 512, 1, 1), 4], (1, 512, 1, 0), (3, 1024, 1, 1), "M", [(1, 512, 1, 0), (3...
import pandas as pd import numpy as np import logging from .constants import WILD_TYPE_VARIANT import collections from .variant import mutation_count, re_protein, re_coding, re_noncoding from .barcodemap import re_barcode, re_identifier from .constants import AA_CODES from .storemanager import ELEMENT_LABELS from .sfma...
class ConnectionWrapper: def __init__(self, basepath): self.basepath = basepath self.connections = [] def link(self, source, target): if not isinstance(source, EditCellWrapper): raise TypeError(type(target)) if not isinstance(target, Cell): raise TypeErro...
# -*- coding: utf-8 -*- """Converter for HGNC.""" import json import logging from typing import Iterable from tqdm import tqdm from ..path_utils import ensure_path from ..struct import Obo, Reference, Synonym, SynonymTypeDef, Term, from_species logger = logging.getLogger(__name__) PREFIX = 'hgnc' DEFINITIONS_URL ...
import numpy as np import torch import glob import cv2 import os import os.path as osp from .base import RGBDDataset from .stream import RGBDStream class TartanAir(RGBDDataset): # scale depths to balance rot & trans DEPTH_SCALE = 5.0 TEST_SET = ['westerndesert', 'seasidetown', 'seasonsforest_winter', 'o...
import json import asyncio from discord import Embed from cog.helpers import rbColor, strings, gifs from cog.interaction import Helpers from discord.ext import commands from discord.member import Member from random import choice, randint class VarietyHelp(): def get_8ball(): return choice(strings['ball8']...
import csv import os import numpy as np import matplotlib.pyplot as plt import time plt.switch_backend('agg') TODO = { ('tox21', 'random'): [ 'weave', 'graphconv', 'tf', 'tf_robust', 'irv', 'xgb', 'logreg', 'textcnn' ], ('clintox', 'random'): [ 'weave', 'graphconv', 'tf', 'tf_robust...
# Copyright 2020 Huawei Technologies Co., Ltd # # 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...
from js9 import j JSBASE = j.application.jsbase_get_class() class CodeDirs(JSBASE): def __init__(self): JSBASE.__init__(self) self.path = j.dirs.CODEDIR self.load() def load(self): data = j.core.state.stateGetFromDict("develop", "codedirs", "") self.tree = j.data.tre...
import logging import time from tqdm import tqdm from lab_api.swagger_client import LabService from lab_api.swagger_client.rest import ApiException from lab_client.handler import lab_api_handler class LabServiceConfig: """ Service configuration for deployment. # Arguments image (string): Docker...
import copy import logging import numpy as np import torch from fvcore.common.file_io import PathManager from PIL import Image from detectron2.data import detection_utils as utils from detectron2.data import transforms as T from detectron2.structures import Boxes, BoxMode, Instances from lib.utils.interactions import...
import torch import torchvision.transforms.functional as TF import random, math def roll_minmax(low, high): roll = random.random() return roll*(high-low) + low class RandomResizedProtectedCropLazy(torch.nn.Module): def __init__(self, size, min_area, max_area=1, interpolation=TF.InterpolationMode.BILINEAR,...
""" Referece Models --------------- Convert FEKO models on the reference antennas into usable healpix maps """ # Code developed by <NAME> and adapted here # https://github.com/JLBLine/MWA_ORBCOMM from pathlib import Path import healpy as hp import matplotlib import numpy as np import pkg_resources from embers.rf_t...
# Copyright (C) 2017 TU Dresden # Licensed under the ISC license (see LICENSE.txt) # # Authors: <NAME>, <NAME> import traceback import pint from sys import exit from copy import deepcopy from mocasin.mapper.partial import ProcPartialMapper, ComPartialMapper from mocasin.mapper.random import RandomPartialMapper from m...
import logging import os from pathlib import Path from typing import Any, Dict, Optional, Union from zipfile import ZipFile from labfunctions import defaults, secrets from labfunctions.conf.jtemplates import get_package_dir, render_to_file from labfunctions.errors import CommandExecutionException from labfunctions.typ...
import unittest from app.modules.shogi import Koma from app.modules.shogi_input import Shogi from app.modules.parse_input import ParseInput def create_shogi(): return Shogi("channel_id", [ {"id": "user1", "name": "name1"}, {"id": "user2", "name": "name2"}, ]) class ShogiTest(unittest.TestCase): def s...
import os import struct import collections import redis import numpy as np from default_config import get_default_config from utils import get_features_one, get_dist_one # ReID cfg_reid = get_default_config() body_bank_test = {} # Redis r = redis.Redis(host=os.getenv('SMART_SPACE_TRACKING_REDIS_PORT_6379_TCP_ADDR'),...
from typing import TYPE_CHECKING if TYPE_CHECKING: from utils.database import Database as PhaazeDatabase import json, math from utils.errors import MissingOfField, InvalidLimit, MissingUpdateContent, SysLoadError, ContainerNotFound, InvalidUpdateExec, SysStoreError from aiohttp.web import Request, Response from utils...
import requests from pyquery import PyQuery as pq from dateutil.parser import parse import datetime import pytz import csv import time from lib.dbModel import db, Portfolio, HistoryData, StockInfo, ProjectInfo import lib.stockUtil as stockUtil import lib.stockData.util as stockDataUtil ########### get data from twse ...
# -*- coding: utf-8 -*- """Convert between MQTT message payload data and OSC arguments types.""" from __future__ import absolute_import, unicode_literals import array import json import re import struct import logging from collections import namedtuple from .util import as_bool, parse_list try: # Python 3.2+ ...
class Vertice: def __init__(self, nodo, x, y, largura, altura): self.id = nodo self.adjacentes = {} self.x = x self.y = y self.largura = largura self.altura = altura def __str__(self): return self.id.__str__() + ' adjacentes: ' + [x.id for x in self.adjac...
import json from math import ceil from typing import Dict, List from openpyxl import Workbook from openpyxl.utils import get_column_letter from openpyxl.worksheet.table import Table, TableStyleInfo from arbitrageur.crafting import ProfitableItem, profit_per_item, profit_on_cost, profit_per_crafting_step from arbitrag...
# 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...
"""Flexmock test runner integrations.""" # pylint: disable=import-outside-toplevel, import-error import sys import unittest from contextlib import suppress from functools import wraps from typing import Any, Type from flexmock._api import flexmock_teardown def _patch_test_result(klass: Type[Any]) -> None: """Pat...
from __future__ import print_function import os import sys import socket import datetime import time import akumulid_test_tools as att import json try: import urllib2 as urllib except ImportError: import urllib import traceback host = '127.0.0.1' tcpport = 8282 httpport = 8181 # Test plan. # - Write data unti...
""" Provides a base test class for other test classes to inherit from. Includes the numpy testing functions as methods. """ import os.path import sys import unittest from inspect import getsourcefile import numpy as np import pytest from numpy.testing import ( assert_allclose, assert_almost_equal, assert...
import pymongo, re, time, sys, subprocess from pymongo import MongoClient from json import loads from bson.json_util import dumps import AutoInject.bin.get_Packages as gp import AutoInject.bin.system_Functions as sf client ...
__author__ = 'archanda' __date__ = '3-Oct-2021' __copyright__ = "Copyright 2021" __credits__ = ["archanda"] __license__ = "All rights reserved" __maintainer__ = "archanda" __email__ = "<EMAIL>" __status__ = "dev" from fastapi import FastAPI, Body, APIRouter, Request, Response, status from fastapi.responses import HTML...
# Copyright 2019 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 ...
# based on conv_qsar_fast by <NAME> import os import time import json import logging import numpy as np from sklearn.metrics import roc_auc_score, roc_curve, mean_squared_error, mean_absolute_error from graphconv import predict import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt logger = logging.ge...
import torch import torch.nn as nn from ..attack import Attack def project_simplex(v, z=1.0, axis=-1): """ Implements the algorithm in Figure 1 of <NAME>, <NAME>, <NAME>, <NAME>, "Efficient Projections onto the l1-Ball for Learning in High Dimensions", ICML 2008. https://stanford.edu/~jduchi/proj...
#!/anaconda3/envs/metis/bin/python # assumptions: # keeping duplicates, they look to be audits back at same timestamp, and count is low. # negative rates do not meet expectations and are filtered out. # higher than 60 people per turnstile per minute are unrealistic, and are filtered out. # the immediate week before th...
# SPDX-License-Identifier: Apache-2.0. import json import logging import os import sys from typing import List import psycopg2 import time import requests from retrying import retry from openlineage.common.test import match, setup_jinja env = setup_jinja() logging.basicConfig( format="[%(asctime)s] {%(pathname)...
""" This file contains a general purpose neural network that can be used for many applications """ import numpy as np import matplotlib.pyplot as plt def sigmoid(x): """ This function computes the sigmoid of x""" return 1.0/(1.0 + np.exp(-x)) def sigmoidDerivative(x): """ This function computes the sigmo...
# Copyright L.P.Klyne 2013 # Licenced under 3 clause BSD licence # $Id: TestPanelHtml.py 2609 2008-08-11 20:03:27Z graham.klyne $ # # Unit testing for WebBrick panel definition HTML conversions. # import sys import unittest # Extend python path to access other related modules # sys.path.append("..") sys.path.appen...
from __future__ import unicode_literals import json import logging import mimetypes import os from datetime import datetime import re from django.conf import settings from django.contrib.auth.decorators import login_required from django.contrib.gis.db.models import GeometryField from django.core.exceptions import Per...
import autograd.numpy as np from scipy.interpolate import RegularGridInterpolator from constants import * def cartesian_to_spherical(arr, dist_to_source_nm, psize_nm, theta_max=PI/18, phi_max=PI/18, interpolation='nearest'): """ Convert 3D cartesian array into spherical coordinates. """ # Spherical a...
# import tkinter module from tkinter import * # import other necessary modules import random import time import datetime # creating root object root = Tk() # defining size of window root.geometry("1200x6000") # setting up the title of window root.title("Message Encryption and Decryption") Tops = Frame(root, width ...
import numpy as np import os import sys from keras.applications import ResNet50, VGG16 from keras.applications.inception_v3 import InceptionV3 from keras.applications.resnet50 import preprocess_input from keras.layers import Dropout, Merge, Flatten, RepeatVector, Activation from keras.layers import Embedding, Conv2D, ...
#!/usr/bin/env python3 """ Demonstrate general use of simultaneous fitting of multiple (individually under-determined, i.e. coupled implicitly amongst,) datasets """ from abc import ABC, abstractmethod import numpy as np import matplotlib.pyplot as plt from optimizer_utils import ParameterController, Fitter, Dataset f...
""" Script to run transfer learning from a 3D model using different possible metrics and different possible chemprop options (features + MPNN, just features, or just MPNN) """ import os import argparse from nff.utils import (bash_command, parse_args, fprint, CHEMPROP_METRICS) def get_train_fo...
import os import sys import getopt import pytube import shutil import numpy as np from pytube import YouTube from tqdm import tqdm def video_segmentation(orginal_video_name,segment_file,main_folder_path): file_segments_data = np.genfromtxt(segment_file,dtype=[('f8'),('f8'),('S50')],delimiter='\t') if...
from __future__ import annotations from dataclasses import dataclass from typing import Optional MatchResult = Optional[tuple[int, int]] @dataclass class Child: up: int = -1 down: int = -1 next_l_index: int = -1 def __str__(self) -> str: return f"up={self.up}, down={self.down}, nextLIndex={...
from toontown.toonbase import ToontownGlobals, TTLocalizer from toontown.parties import ToontownTimeZone import calendar, datetime TIME_ZONE = ToontownTimeZone.ToontownTimeZone() TRICK_OR_TREAT = 0 WINTER_CAROLING = 1 CAROLING_REWARD = 100 SCAVENGER_HUNT_LOCATIONS = 6 Holidays = { ToontownGlobals.GRAND_PRIX: { ...
"""Module that defines scope classes to easily create name scopes or any other kind of scope.""" from typing import Optional, List, Any, Callable, Generator, Union import threading class Scope(object): """ General purpose variable scoping. PyMC4 scopes intended to store useful information during forward ...
#!/usr/bin/env dls-python2.7 """Wrapper around channel access control of the I10 chicane. Aids reading and writing from the many magnet PVs associated with the fast chicane. PvMonitors is a singleton and users should use get_instance. """ import cothread from cothread.catools import caget, camonitor, FORMAT_TIME c...
import logging import time from collections import OrderedDict from datetime import datetime from typing import Dict, List, Union from datetime_truncate import truncate from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import TemplateView from .models import DashboardStats, Interval,...
""" A set of utilities for manipulating and validating graph-like structures. """ import copy def apply_transitive_reduction(graph): """Attempts to remove any implicit dependencies from the dependant graph. For example, if C depends on B which depends on A (A->B->C), the A->C dependency should not b...