text
stringlengths
3.07k
22.1k
import sys import logging from flask import jsonify, request, url_for, make_response, abort, render_template from flask_api import status # HTTP Status Codes from flask_restplus import Api, Resource, fields, reqparse, inputs from service.models import Category, DataValidationError from service.train import Similarit...
# 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...
import copy import json import base64 from functools import partial import asyncio import collections from .values import DocStringLine, MetricValue from .registry import Registry from .task_manager import TaskManager REGISTRY = Registry(task_manager=TaskManager()) DEFAULT_GAUGE_INDEX_KEY = 'GLOBAL_GAUGE_INDEX' ...
#!/usr/bin/env python import logging import re import sys import yaml from lxml import etree BASE_LOG_FORMAT = '%(levelname)s: %(message)s' # CPE w/o 2.3 component: cpe:/a:nginx:nginx:0.1.0" REGEX_CPE = re.compile('^cpe:/([aho]):([^:]+):([^:]+)') # CPE w/ 2.3 component: cpe:2.3:a:f5:nginx:0.1.0:*:*:*:*:*:*:* REGEX...
from pydeation.document import Document from pydeation.animation.animation import VectorAnimation, AnimationGroup from pydeation.animation.object_animators import Show, Hide from abc import ABC, abstractmethod from collections import defaultdict import c4d class Scene(ABC): """abstract class acting as blueprint f...
import gym import gym.spaces import json import numpy as np import os import socket gym_version = tuple(int(x) for x in gym.__version__.split('.')) class Channel: def __init__(self): self.sock = None self.dirty = False self._value = None self.annotations = {} def set_socket(s...
"""Testssuite of the invoices-module.""" from typing import Any from typing import Dict from typing import List import datetime import pytest from pydantic import ValidationError from tia.balances import AccountingItem from tia.basemodels import TypedList from tia.client import Client from tia.company import Company...
#!/usr/bin/env python """ Usage: train.py [options] SAVE_FOLDER TRAIN_DATA_PATH VALID_DATA_PATH TEST_DATA_PATH train.py [options] [SAVE_FOLDER] *_DATA_PATH arguments may either accept (1) directory filled with .jsonl.gz files that we use as data, or a (2) plain text file containing a list of such directories (...
from insights import add_filter from insights.parsers.httpd_conf import HttpdConf from insights.specs import Specs from insights.tests import context_wrap HTTPD_CONF_1 = """ <Directory /> Options FollowSymLinks AllowOverride None </Directory> SSLProtocol -ALL +SSLv3 #SSLProtocol all -SSLv2 NSSProtocol SSLV3 ...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Business Applications # Copyright (C) 2012 OpenERP S.A. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the...
# ============================================================================= # Module: pheno # File: pheno/__init__.py # Author: <NAME> # Created: 02/12/2015 # # Copyright (c) <NAME> 2015, all rights reserved. # ============================================================================= # # Description: #...
# coding=utf-8 import datetime as dt import pytz import sqlalchemy as sa from sqlalchemy import func from sqlalchemy.event import listen from sqlalchemy.orm import relationship, foreign, remote from sqlalchemy.sql import select, insert, update from celery import schedules from celery.utils.log import get_logger fro...
# importing libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams["figure.figsize"] = (20,10) # importing the dataset dataset = pd.read_csv(r"C:\00git\Bangalore-Real-Estate-Price-Prediction-WebApp-master\dataset\Bengaluru_House_Data.csv") print(dataset.h...
# Copyright 2012 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 ...
# -*- coding: utf-8 -*- import click import logging from pathlib import Path import os from dotenv import find_dotenv, load_dotenv import json import pandas as pd import numpy as np import urllib import zipfile from tqdm import tqdm from glob import glob from collections import defaultdict from src.data.tcia import TCI...
import numpy as np import pandas as pd import re from joblib import dump, load from rdflib import Graph, Literal, RDF, URIRef, Namespace import pathlib def get_dir(path=''): """Return the full path to the provided files in the OpenPredict data folder Where models and features for runs are stored """ re...
import angr import claripy import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) from memory import factory def check(state, obj, exp_values, conditions=()): r = state.se.eval_upto(obj, len(exp_values) + 1, extra_constraints=conditions) if len(r) != len(exp_values) or set(r)...
#!/usr/bin python3 """ Graph functions for Display Frame of the Faceswap GUI """ import datetime import os import tkinter as tk from tkinter import ttk from math import ceil, floor import matplotlib matplotlib.use("TkAgg") import matplotlib.animation as animation from matplotlib import pyplot as plt, style from matpl...
from Models.Alphabet import Alphabet from Models.Automate import Automate from Models.Etat import Etat from Models.Transition import Transition class ExpressionReguliere: def __init__(self, expression:str): if not isinstance(expression, str): raise TypeError('Une expression est de type str') ...
# !/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 31 16:23:13 2018 @author: samschott """ import sys import os import re import platform from PyQt5 import QtWidgets, QtCore, QtGui _root = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) _icon_provider = QtWidgets.QFileIconPro...
import pandas as pd import numpy as np import math import tkinter as tk from tkinter import ttk from PIL import Image, ImageTk import os import sqlite3 from sqlite3 import OperationalError #file = str(os.path.realpath(__file__)) csv_file = "/Users/nedimdrekovic/Python/DB/simplemaps_worldcities/" + "world_cities.csv" s...
# -*- coding: utf-8 -*- ''' TTL SQLite Data Access Layer Latest version can be found at https://github.com/letuananh/texttaglib @author: <NAME> <<EMAIL>> @license: MIT ''' # Copyright (c) 2018, <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and a...
#!/usr/bin/env python # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required...
# coding: utf-8 import base64 from keras import models import tensorflow as tf import os import cv2 import numpy as np import scipy.fftpack graph = tf.get_default_graph() PATH = lambda p: os.path.abspath( os.path.join(os.path.dirname(__file__), p) ) TEXT_MODEL = "" IMG_MODEL = "" def pretreatment_get_text(img,...
# Purpose: compiler for line type definitions # Created: 12.01.2018 # Copyright (c) 2018, <NAME> # License: MIT License # Auszug acadlt.lin # # *RAND,Rand __ __ . __ __ . __ __ . __ __ . __ __ . # A,.5,-.25,.5,-.25,0,-.25 # *RAND2,Rand (.5x) __.__.__.__.__.__.__.__.__.__.__. # A,.25,-.125,.25,-.125,0,-.125 # *RANDX2,R...
import cv2 import torch import scipy.special import numpy as np import torchvision import torchvision.transforms as transforms from PIL import Image from enum import Enum from scipy.spatial.distance import cdist from ultrafastLaneDetector.model import parsingNet lane_colors = [(0,0,255),(0,255,0),(255,0,0),(0,255,255...
"""Contains decorator functions and functions for interacting with global data. """ from functools import wraps import requests from robin_stocks.robinhood.globals import LOGGED_IN, OUTPUT, SESSION def set_login_state(logged_in): """Sets the login state""" global LOGGED_IN LOGGED_IN = logged_in def set_...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys from scipy.io import loadmat import numpy as np from scipy import linalg import glob import pickle from six.moves import xrange # pylint: disable=redefined-builtin from six.moves import ...
# MIT License # Copyright (c) 2018 Hotox # 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,...
import inspect import logging import hashlib import gym import numpy as np from gym.spaces import Box, Tuple, Dict from mujoco_py import MjSimState from mujoco_worldgen.util.types import enforce_is_callable from mujoco_worldgen.util.sim_funcs import ( empty_get_info, flatten_get_obs, false_get_diverged, ...
# coding: utf-8 from __future__ import unicode_literals from ..compat import compat_urllib_parse_unquote from ..utils import ExtractorError, int_or_none, try_get, unified_timestamp from .common import InfoExtractor from .once import OnceIE class VoxMediaVolumeIE(OnceIE): _VALID_URL = r"https?://volume\.vox-cdn\....
#nga.py by ludoux # -*- coding: UTF-8 -*- import re import requests import os import sys import time from contextlib import closing import hashlib import json #=============先修改 headers = { 'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/53...
import random import time import pytest from ..platform import get_process_id, process_alive from ..locking import TimeoutTimer, ExclusiveLock, Lock, LockRoster, \ ADD, REMOVE, SHARED, EXCLUSIVE, LockTimeout, NotLocked, NotMyLock ID1 = "foo", 1, 1 ID2 = "bar", 2, 2 @pytest.fixture() def free_...
import os import torch from torchvision.datasets import CelebA, CIFAR10, LSUN, ImageFolder from torch.utils.data import Dataset, DataLoader, random_split, Subset from utils import CropTransform import torchvision.transforms as transforms import numpy as np from tqdm import tqdm import cv2 from PIL import Image # Chang...
# -*- coding: utf-8 -*- """ SSP Director ~~~~~~~~~~~~ Python client for Slideshow Pro's Director API. :license: MIT License, see LICENSE for more details. :documentation: See README.md for documentation. """ __version__ = '1.0' try: from urllib.request import urlopen from urllib.parse i...
import os import argparse import json import re from warnings import warn from keyword import iskeyword from collections import defaultdict from jinja2 import Environment, FileSystemLoader BASEDIR = os.path.dirname(__file__) env = Environment( loader=FileSystemLoader(f"{BASEDIR}/bindings_templates"), trim_blocks=...
import unicodedata import re import random import torch from torch.autograd import Variable # loading data files # indexing words # 一些标志符号(词) PAD_token = 0 SOS_token = 1 # 句子起始 EOS_token = 2 # 句子结束 USE_CUDA = False class Lang: def __init__(self, name): self.name = name self.trimmed = False ...
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
""" pygame-menu https://github.com/ppizarror/pygame-menu EXAMPLE - MULTI-INPUT Shows different inputs (widgets). """ __all__ = ['main'] import pygame import pygame_menu from pygame_menu.examples import create_example_window from typing import Tuple, Optional # Constants and global variables FPS = 60 WINDOW_SIZE = ...
# Copyright 2016-2020 The <NAME> at the California Institute of # Technology (Caltech), with support from the Paul Allen Family Foundation, # Google, & National Institutes of Health (NIH) under Grant U24CA224309-01. # All rights reserved. # # Licensed under a modified Apache License, Version 2.0 (the "License"); # you ...
# # Copyright (c) 2021, 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 ...
# -*- coding: utf-8 -*- """ @author: clausmichele """ import time import tensorflow as tf import cv2 import numpy as np from tqdm import tqdm def SpatialCNN(input, is_training=False, output_channels=3, reuse=tf.AUTO_REUSE): with tf.variable_scope('block1',reuse=reuse): output = tf.layers.conv2d(input, 128, 3, padd...
""" Driver script to do NOx/HONO (post campaign) analysis """ #!/usr/bin/python # - Packages import numpy as np from time import gmtime, strftime import time import glob import AC_tools as AC import sys import pandas as pd # import ARNA analysis/campaign code as a module import arna as ar def main(): """ Main...
# # Author: <EMAIL> # from collections import defaultdict from math import log import string, itertools import multiprocessing def chunks(l, n): """ Yield n successive chunks from l. """ newn = int(1.0 * len(l) / n + 0.5) for i in range(0, n - 1): yield l[i * newn:i * newn + newn] yield l...
from requests import Session import logging from typing import Iterator, Generator from datetime import date from gofiliate.lib import short_date_to_date, Figures, ListofFigures \ , GofiliateDataException, GofiliateException, GofiliateAuthException \ , AffiliateData, BaseWidgetReportRequest, AffiliateDetailsReq...
# # Write a symbol to python # import pybamm # need numpy imported for code generated in EvaluatorPython import numpy as np # noqa: F401 import scipy.sparse # noqa: F401 from collections import OrderedDict def id_to_python_variable(symbol_id, constant=False): """ This function defines the format for the py...
""" .. _kw_generate: Generate Keywords for SEM Campaigns =================================== A big part of setting up SEM campaigns consists of generating keywords, and properly mapping them to landing pages and ads, as well as putting them in the right campaign and ad group structure. Keyword research is the part o...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Goal) on 2019-05-07. # 2019, SMART Health IT. from . import domainresource class Goal(domainresource.DomainResource): """ Describes the intended objective(s) for a patient, group or o...
# -*- coding: utf-8 -*- """ Classes for downloading and working with Census API data. """ import os import json import collections import re import requests import pandas as pd from .util import check_response CENSUS_BASE_URL = 'https://api.census.gov/data.json' class CensusQuery(object): """ Download data f...
# Copyright (c) Facebook, Inc. and its affiliates. import logging import warnings from dataclasses import dataclass from typing import Dict import numpy as np from mmf.common.registry import registry from mmf.utils.configuration import get_global_config from mmf.utils.dataset import dataset_list_from_config from omeg...
from __future__ import print_function import googlemaps as gmaps import networkx as nx # import osmnx as ox import pickle import concurrent.futures import math import requests import urllib # Initiate cache geocode_cache = {} def getdistancematrix(coordinates, option=0): ''' Args: coordinates: list ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from io import StringIO import re from hwt.interfaces.utils import addClkRstn from hwt.simulator.simTestCase import SingleUnitSimTestCase from hwt.simulator.utils import pprintInterface, pprintAgents from hwt.synthesizer.interfaceLevel.emptyUnit import EmptyUnit from hwt...
import argparse import os import numpy as np from tqdm import tqdm import torch.backends.cudnn as cudnn # from mypath import Path from common import config from data import make_data_loader from model.sync_batchnorm.replicate import patch_replication_callback from model.deeplab import * from utils.loss import Segmentat...
# This file is part of the pyMOR project (https://www.pymor.org). # Copyright pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (https://opensource.org/licenses/BSD-2-Clause) """Visualization of grid data using OpenGL. This module provides a widget for displaying patch plots of s...
from data import DoomImage import numpy as np import time from torch.utils.data import DataLoader import tensorflow as tf from tqdm import tqdm from imageio import imwrite as imsave from data import Places, PlacesRoom, PlacesOutdoor from habitat_baselines.rl.models.resnet import ResNetEncoder import habitat_baselines.r...
""" Author: <NAME> """ __license__ = """ Copyright 2015 Parse.ly, 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 ...
# anvil_mods.py import pandas as pd import numpy as np import shapely import geopandas as gpd import quandl from fred import Fred # demo api key quandl.ApiConfig.api_key = "<KEY>" def formatIndicatorLikeQuandl(indicator, **kwargs): """ Uses the FRED module to access data not included in QUANDL's datas...
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved." __license__ = "Apache-2.0" import base64 import os import struct import urllib.parse import urllib.request import zlib import numpy as np from . import BaseDriver from .helper import guess_mime, array2pb, pb2array class BaseConvertDriver(Ba...
import pytest import numpy as np from encomp.units import Q from encomp.fluids import Fluid, HumidAir, Water from encomp.utypes import Density def test_Fluid(): fld = Fluid('R123', P=Q(2, 'bar'), T=Q(25, '°C')) assert fld.get('S') == Q(1087.7758824621442, 'J/(K kg)') assert fld.D == fld.get('D') w...
""" This module provides different kinds of iterators, all wrapped by the DataIterator class which should generally be the only one used in practice. The BaseIterator class allows "peeking" `checklines` lines into the data -- even if it's a consumable iterator -- in order to figure out what the dialect is and therefor...
""" abc-classroom.template ====================== """ import os import shutil from pathlib import Path from . import config as cf from . import github as gh from . import utils def new_update_template(args): """ Command line function that creates or updates an assignment template repository. Implementat...
import AST import scanner tokens = scanner.tokens precedence = ( ("nonassoc", "IFX"), ("nonassoc", "ELSE"), ("left", '=', 'ADDASSIGN', 'SUBASSIGN', 'MULASSIGN', 'DIVASSIGN'), ("left", '<', '>', 'LTE', 'GTE', 'NEQ', 'EQ'), ("left", '+', '-'), ("left", '*', '/'), ("left", 'DOTADD', 'DOTSUB')...
# Copyright (c) 2011-2020, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory # Written by <NAME>, <NAME>, and <NAME> # e-mail: <EMAIL> # LLNL-CODE-507071 # All rights reserved. # This file is part of PDV. For details, see <URL describing code and # how to downlo...
from __future__ import print_function import numpy as np import powderday.config as cfg import yt from yt.frontends.sph.data_structures import ParticleDataset from yt.geometry.selection_routines import AlwaysSelector import pdb ParticleDataset.filter_bbox = True ParticleDataset._skip_cache = True def octree_zoom_bb...
from __future__ import unicode_literals from django.contrib.auth import authenticate, login from django.http import JsonResponse from django.http import Http404 from django.shortcuts import render, redirect from django.views.decorators.csrf import csrf_exempt from scipy.io import wavfile from .forms import LoginForm, ...
#coding:utf-8 import cv2 import numpy as np import sys import os COLOR_BG = (255,0,0) COLOR_FG = (0,255,0) def mask2color(mask): r,c = mask.shape[:2] color = np.zeros((r,c,3),np.uint8) color[np.where((mask==0)|(mask==2))] = COLOR_BG color[np.where((mask==1)|(mask==3))] = COLOR_FG return color def...
#!/usr/bin/env python """Auxiliary numerical tools """ from math import acos, pi, sqrt from warnings import warn #from . import log as log import anuga.utilities.log as anuga_log import numpy as num #After having migrated to numpy we should use the native NAN. #num.seterr(divide='warn') num.seterr(divide='ignore') ...
import numpy as np import random import time import json from model.model_wrapper import Models from socketIO_client import SocketIO from utils.model_dump import * import os import logging import argparse logging.getLogger('socketIO-client').setLevel(logging.WARNING) random.seed(2018) datestr = time.strftime('%m%d')...
"""Live tests of common resource functionality. We can use (almost) any resource here - Account is a convenient choice. """ import jwt from stormpath.resources.base import Expansion from .base import AccountBase from .base import ApiKeyBase class TestResource(AccountBase): def test_dict_mixin(self): _...
from __future__ import division from datetime import datetime class Month(object): def __init__(self, date, student_loans, retirment, down_payment): self.date = date self.student_loans = student_loans self.retirement = re...
# Copyright 2017 Intel 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 in wri...
from dataclasses import dataclass, field from datetime import date as date_, datetime from typing import ClassVar, List, NamedTuple, Optional, Union from eventkit import Event from loguru import logger from base.contract import Contract, TagValue from source.base.util import EPOCH, UNSET_DOUBLE, UNSET_INTEGER logger.a...
import copy import numpy as np import torch class Memory: def __init__(self, memory_size, nb_total_classes, rehearsal, fixed=True): self.memory_size = memory_size self.nb_total_classes = nb_total_classes self.rehearsal = rehearsal self.fixed = fixed self.x = self.y = self...
# pylint: disable=not-context-manager # NOTE: The pylint not-content-manager warning is disabled pending the fix of # a bug in pylint. See https://github.com/PyCQA/pylint/issues/782 """Classes to handle Sonos UPnP Events and Subscriptions. The `Subscription` class from this module will be used in :py:mod:`soco.serv...
from __future__ import with_statement, print_function, absolute_import from itertools import * from functools import * import re from copy import copy import time import numpy as np from pandas import DataFrame from stitch.core.utils import * # ---------------------------------------------------------------------------...
#!/usr/bin/env python # -*- coding: utf-8 -*- """redistructure tests""" import uuid import unittest import redistructures # C0103 - invalid-name # pylint: disable=C0103 class BaseTest(unittest.TestCase): """Base unittest class""" def setUp(self): """Set up queue name""" self.name = str(uuid.uui...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author: <NAME> # @Date: 2016-11-16 16:23:55 # @Last Modified by: <NAME> # @Last Modified time: 2017-05-08 10:48:17 import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import glob import os import functools from pathlib impo...
""" parse_vcf.py Utility functions to upload vcf files """ import re import sys import pymongo import bson import json import vcf as py_vcf from datetime import datetime from helper import deep_update from . import connection, db def upload_vcf(vcf_file): """ Parse vcf files and upload variants usin...
# -*- coding: utf-8 -*- # Copyright (c) 2021, Teampro and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class EyenorDatasheet(Document): pass @frappe.whitelist() def get_header(doc): data = '' data +=...
import logging from cle.backends import Backend, Symbol, Segment, SymbolType from cle.backends.relocation import Relocation from cle.utils import ALIGN_UP from cle.errors import CLEOperationError, CLEError from cle.address_translator import AT l = logging.getLogger(name=__name__) class ExternSegment(Segment): de...
# -*- coding: utf-8 -*- """ Created on Wed Jun 26 18:29:41 2019 @author: <NAME> """ import cv2 from PIL import Image import matplotlib.pyplot as plt import tools import numpy as np from scipy import ndimage #from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img #%% #images #PS...
'''VGG for CIFAR10. FC layers are removed. (c) <NAME> ''' import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo import math import numpy as np from mypath import Path from torch.autograd import Variable __all__ = [ 'vgg19mlp' ] # model_urls = { # 'vgg11'...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import time import itertools import re import os from .TAD import TAD from .estructuras_de_datos import Pila,Nodo,Arbol # Procedimiento que construye un árbol a partir de su representación como paréntesis anidado def parentesis_a_arbol_etiquetado(parentesis,eti...
#!/usr/bin/env python """ 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 distribute...
from __future__ import division import numpy as np import climlab import pytest from climlab.radiation.rrtm import _climlab_to_rrtm, _rrtm_to_climlab from climlab.tests.xarray_test import to_xarray num_lev = 30 @pytest.mark.compiled @pytest.mark.fast def test_rrtmg_lw_creation(): state = climlab.column_state(num_...
import torch from torch.autograd import Variable from torch.nn import functional as F print(torch.__version__) import torch.nn as nn import torch.autograd as autograd from generative_playground.utils.gpu_utils import to_gpu, FloatTensor from generative_playground.data_utils.to_one_hot import to_one_hot class LSTMMode...
#!/usr/bin/env python """Hooks for git that perform linting. This file contains two git hooks: 1. A commit-msg hook, to lint the commit message. If lint fails, the commit is aborted, and the message is saved in a temporary file. 2. A pre-push hook, to lint files that will remotely change as a result of the push...
# white_signals.py """Contains class factories for white noise signals. White noise signals are defined as the class of signals that only modifies the white noise matrix `N`. """ from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import scipy.sparse from enterprise....
import os import pysam import pyfastaq from clockwork import utils class Error (Exception): pass class ContamRemover: '''Takes a BAM file in read name order (ie has not been sorted by reference). The reference should have sequence(s) that we want, and the rest are assumed to be contamination. ...
import numpy as np from itertools import combinations import dask.array as dsa from ..core import ( histogram, _ensure_correctly_formatted_bins, _ensure_correctly_formatted_range, ) from .fixtures import empty_dask_array import pytest bins_int = 10 bins_str = "auto" bins_arr = np.linspace(-4, 4, 10) ra...
#!/usr/bin/env python """Implementation of Closed-Form Matting. This module implements natural image matting method described in: <NAME>, <NAME>, and <NAME>. "A closed-form solution to natural image matting." IEEE Transactions on Pattern Analysis and Machine Intelligence 30.2 (2008): 228-242. The code can be...
#K-means Clustering #%reset -f #Importing Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.cluster import DBSCAN from pyclustertend import hopkins from sklearn.cluster import MeanShift, estimate_bandwidth from sklearn.metrics import silhouette_score #I...
"""Tests pertaining to the `signal_analog.detectors` module.""" import re import pytest import requests import betamax from betamax_serializers import pretty_json from email_validator import EmailNotValidError from signal_analog.combinators import Div, GT, LT from signal_analog.flow import Assign, Data, Detect, Progr...
# -------------------------------------------------------- # SoCo # Copyright (c) 2021 Microsoft # Licensed under The MIT License [see LICENSE for details] # Written by <NAME> # -------------------------------------------------------- import json import os import time import torch import torch.backends.cudnn as cudn...
from django.db.models import Q from rest_framework import serializers from rest_framework.exceptions import ValidationError from care.facility.api.serializers import TIMESTAMP_FIELDS from care.facility.api.serializers.facility import FacilityBasicInfoSerializer from care.facility.api.serializers.patient import Patient...
from django.core.exceptions import ValidationError from django.db.models import Q from django.forms import widgets from django.forms.fields import BooleanField, ChoiceField, MultipleChoiceField from django.utils.safestring import mark_safe from django.utils.text import format_lazy from django.utils.translation import n...
import json import numpy as np import matplotlib.pyplot as plt import os import yaml from sklearn.metrics import f1_score, roc_auc_score from fcos_core.config.paths_catalog import DatasetCatalog from Data.Preprocess import join_path def compute_iou(box1, box2): """ Compute IoU between two boxes....
#encoding: utf-8 from fastai.conv_learner import * class DPNConvnetBuilder(): """ # Args ps: float list, dropout rate of dense layers """ def __init__(self, f, n_classes, is_multi, is_reg, ps=None, xtra_fc=Non...
""" Lidar """ # requies glob to be installed: "pip3 install glob2" # requires rplidar to be installed: "pip3 install rplidar" import time import math import pickle import serial import numpy as np from donkeycar.utils import norm_deg, dist, deg2rad, arr_to_img from PIL import Image, ImageDraw class RPLidar(object): ...
# Authors: # <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # # License: BSD 3 clause """ Simulate the lid driven cavity dt rho + dx qx + dy qy = 0 dt qx + dx (qx^2/rho + c^2 rho) + dy (qx*qy/rho) = 0 dt qy + dx (qx*qy/rho) + dy (qy^2/rho + c^2 rho) = 0 """ import numpy as np import sympy as sp import matplotlib.pyplot...