text
stringlengths
3.07k
22.1k
import gin import time import datetime import wandb import csv import os import time from typing import Union from copy import deepcopy import numpy as np from gym.wrappers import Monitor import cv2 from basics.abstract_algorithms import OffPolicyRLAlgorithm, RecurrentOffPolicyRLAlgorithm from basics.replay_buffer im...
from functools import lru_cache from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple, Union from cartopy.crs import PlateCarree from matplotlib.artist import Artist from matplotlib.axes._subplots import Axes from shapely.geometry import LineString, mapping from shapely.geometry.base import BaseGeometry...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Aug 8 20:20:55 2019 @author: philipp Main File to wrap up all functions :TO-DO: """ import os import json import configparser import subprocess import numpy as np import osgeo.gdal as gdal import matplotlib.pyplot as plt import pandas as pd impo...
""" Datatable classes """ import logging from json import dumps import sys from pyquerystring import parse from django.conf import settings from django.db.models import Q from django.utils.safestring import mark_safe from django.views.debug import ExceptionReporter from django.template.loader import select_template ...
# -*- coding: utf-8 -*- # Copyright © 2017 Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can # be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from __future__ import print_function as _ from __future__ import division as _ from...
import scipy.io import numpy as np import mat73 try: from pyDOE import lhs # Only needed for PINN's dataset except ImportError: lhs = None import torch from torch.utils.data import Dataset from .utils import get_grid3d, convert_ic, torch2dgrid def online_loader(sampler, S, T, time_scale, batchsize=1): ...
## ## Software PI-Net: Pose Interacting Network for Multi-Person Monocular 3D Pose Estimation ## Copyright Inria and UPC ## Year 2021 ## Contact : <EMAIL> ## ## The software PI-Net is provided under MIT License. ## import os import cv2 import numpy as np from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot...
import time import logging import sys import math from datetime import datetime from jobtech.common.customlogging import configure_logging import importers.mappings from importers import settings from importers.platsannons import loader, converter from importers.common import elastic, enricher from importers.indexmai...
# -*- coding: utf-8 -*- """ Program: ghost_circle Created: Apr 2020 @author: <NAME> (RRCC) <EMAIL> """ ### IMPORTS import random import math as m import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib.ticker import AutoMinorLocator from matpl...
""" Utilities para parsear resultados de las elecciones generales 2015 en espana. """ import urllib2 import simplejson import numpy as np import pandas as pd from pythonUtils.CodingText import * #"http://resultadosgenerales2015.interior.es/congreso/results/ES201512-CON-ES/ES/CA09/08/info.json" urlreq = "http://re...
############################################################################ # Copyright (c) 2015-2017 Saint Petersburg State University # Copyright (c) 2011-2015 Saint Petersburg Academic University # All Rights Reserved # See file LICENSE for details. ##################################################################...
import lms_code.lib.rep2 as rep2 import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import lms_code.plots.plot_all as lms_plot from codim1.core.tools import plot_mesh from codim1.post import evaluate_solution_on_element from functools import part...
# registrar.py - utilities to register function for specific purpose # # Copyright <NAME> <<EMAIL>> and others # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from __future__ import absolute_import from . import ( configitem...
# -*- coding: utf-8 -*- import sys import sqlite3 import urllib,urllib2 import json import time, datetime from workflow import Workflow3, ICON_WEB, web reload(sys) sys.setdefaultencoding('utf8') # Debit currency 扣款币种 # Trading currencies 交易币种 # ICON_DEFAULT = 'icon.png' #连接数据库 创建表 def connSqlite(): try: ...
# coding: utf-8 import argparse import json import logging import os import shutil import gc import torch from allennlp.data.token_indexers.elmo_indexer import ELMoTokenCharactersIndexer from allennlp.data.vocabulary import Vocabulary from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder from all...
# Copyright 2021 The Flax Authors. # # 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 utils import * from part_a.item_response import * def load_question_meta(): # load question_meta.csv path = os.path.join("../data", "question_meta.csv") if not os.path.exists(path): raise Exception("The specified path {} does not exist.".format(path)) # Initialize the data. data = { ...
import numpy as np import cv2 import os import time from collections import defaultdict, namedtuple from threading import Thread, Lock from multiprocessing import Process, Queue class ImageReader(object): def __init__(self, ids, timestamps, cam=None): self.ids = ids self.timestamps = timestamps...
from django import forms from django.core.validators import MinValueValidator from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.utils import timezone import re from decimal import Decimal from datetime import datetime from bakery.models import Groce...
""" This code is attributed to <NAME> (@kayzliu), <NAME> (@YingtongDou) and UIC BDSC Lab DGFraud-TF2 (A Deep Graph-based Toolbox for Fraud Detection in TensorFlow 2.X) https://github.com/safe-graph/DGFraud-TF2 """ import argparse import numpy as np import collections from sklearn.metrics import accuracy_score from tqd...
"""Collection of support tools for reading the Furniture / Fashion data. Author(s): <NAME>, <NAME> """ from __future__ import absolute_import, division, print_function, unicode_literals import csv import functools import os import math import numpy as np import sqlite3 # Static values for accessing annotation # M...
from __future__ import annotations import copy import logging import re from collections import OrderedDict import warnings from functools import partial from typing import TYPE_CHECKING, Mapping from uuid import UUID from sqlalchemy.ext.declarative import DeclarativeMeta from .utils import EnumValue if TYPE_CHECKI...
import ast import json import typing import networkx as nx from automates.program_analysis.CAST2GrFN.model.cast import ( AstNode, Assignment, Attribute, BinaryOp, BinaryOperator, Boolean, Call, ClassDef, Dict, Expr, FunctionDef, List, Loop, ModelBreak, ModelC...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ This is the training code for the link and code. Especially the neighbors_kmeans function implements the EM-algorithm to find the appropri...
#!/usr/bin/env python from __future__ import print_function import argparse import base64 import os import sys import logging import keyring from six import print_ as print from tzlocal import get_localzone from aws_google_auth import _version from aws_google_auth import amazon from aws_google_auth import configurat...
# (https://github.com/sandorex/extract-browser-data.py) # extract-browser-data # # Copyright 2020 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/l...
"""Unit tests for the :mod:`networkx.generators.lattice` module.""" import pytest import networkx as nx from networkx.utils import edges_equal from itertools import product class TestGrid2DGraph: """Unit tests for :func:`networkx.generators.lattice.grid_2d_graph`""" def test_number_of_vertices(self): ...
import math import sys from plexapi.myplex import MyPlexAccount from plexapi.playlist import Playlist from plexapi.exceptions import NotFound # Parse Arguments if len(sys.argv) < 4: print("Arguments: PLEX_USER PLEX_PASS PLEX_SERVER [PLEX_PLAYLIST]") exit(1) plex_user = sys.argv[1] plex_pass = sys.argv[2] plex...
# pyright: strict # -*- coding=UTF-8 -*- from __future__ import annotations from typing import TYPE_CHECKING, Iterator, Text, Tuple if TYPE_CHECKING: from ..context import Context import json import logging import os import warnings import cv2 import numpy as np import PIL.Image import PIL.ImageOps from ... im...
""" # ============================================================================= # Simulating the double pendulum using Runge–Kutta method (RK4) # ============================================================================= Created on Tue Jul 21 2020 @author: <NAME> """ import numpy as np import matplotlib....
#! /usr/bin/env python import argparse import os import cv2 import numpy as np from tqdm import tqdm from preprocessing import parse_annotation from utils import draw_boxes,get_boxes_dimensions from frontend import YOLO import json import pytesseract from PIL import Image import re pytesseract.pytesseract.tesseract_c...
from flask.ext.restful import Resource, marshal_with, abort from . import db, api from flask import g, request from fields import user_fields, token_fields, subreddit_fields, post_fields, comment_fields from parsers import user_parser, token_parser, subreddit_parser, post_parser, comment_parser from models import User,...
import numpy as np import pandas as pd class GroundFilter: pass class Zhang2003: """ Implements Zhang et. al (2003), a progressive morphological ground filter. This filter uses an opening operation combined with progressively larger filtering windows to remove features that are 'too steep'. This parti...
from logging import getLogger import types import numpy as np import scipy as sp import scipy.stats from statsmodels.sandbox.stats.multicomp import multipletests from scipy.special import comb logger = getLogger(__name__) # data transformation def rankdata(data): logger.debug('ranking the data') rdata = np.z...
# coding=utf-8 """ Word2vec 文本聚类 三种聚类算法:Kmeans DBSCAN GMM(其中GMM很慢) 200维词向量(从维基百科1.3G中文数据训练得到) 输入:prepro.py 形成的pkl文件 输出:聚类图形 每一类的每条微博内容 :"cluster1.txt" 、"cluster2.txt" 、"cluster3.txt" 、"cluster4.txt" 参数:weight权重 这是一个重要参数 """ import os import jieba import numpy as np from gensim.models.word2vec import Word2Vec from...
import copy import itertools from typing import TYPE_CHECKING, Optional, List import torch from torch.optim import Optimizer from avalanche.benchmarks.utils import AvalancheConcatDataset, \ AvalancheTensorDataset, AvalancheSubset from math import ceil from avalanche.models import TrainEvalModel, NCMClassifier fro...
import greenlet, logging, os, os.path, msgpack from collections import deque from mixins import mixins from util import VimError, VimExit from traceback import format_exc import cProfile, pstats, StringIO logger = logging.getLogger(__name__) debug, info, warn = (logger.debug, logger.info, logger.warn,) class Remote(...
## vectors and associated methods from math import cos, sin, acos, sqrt, pi from random import random # List of names imported from this module with import * __all__ = ['adjust_axis', 'adjust_up', 'comp', 'cross', 'diff_angle', 'dot', 'hat', 'mag', 'mag2', 'norm', 'object_rotate', 'proj', 'rotate', ...
"""Strip/reset AST in-place to match state after semantic analyzer pre-analysis. Fine-grained incremental mode reruns semantic analysis main pass and type checking for *existing* AST nodes (targets) when changes are propagated using fine-grained dependencies. AST nodes attributes are sometimes changed during semantic...
from __future__ import print_function from copy import copy, deepcopy from functools import wraps import logging from six.moves import StringIO import sys import unittest try: from nose.plugins.attrib import attr except ImportError: # This is an old version of nose def attr(tag): def func(f): ...
import argparse from collections import defaultdict as dd from datetime import datetime import glob import os import pickle import time from common_types import Rectangle import counters import cv2 import detector import dlib import imutils from imutils.video import FPS import intersection_configuration from matcher...
#coding:utf-8 from typing import Union, Optional as Opt from numpy import ndarray from torch import nn, sigmoid, log from torch.nn.utils.rnn import PackedSequence from .data import NegativeSampler from calm.processor import ngramIter class BilinearFactorModel(nn.Module, NegativeSampler): def __init__(self, n_inp...
#/usr/bin/env python3 # # PROGRAMMER: <NAME>. # DATE CREATED: 2019-02-23 # REVISED DATE: # PURPOSE: A class which implements a pretrained models from torch vision # and replaces its existing classfier with a custom network. # It's main use is to predict flower classes. # - Train the network...
#! /usr/bin/env python3 import os import sys import numpy as np import shutil import json5 from jsonref import JsonRef import argparse import subprocess import logging from .busdef import BusDef from ._optimize import ( map_ports_to_bus, get_mapping_fcost_global, get_mapping_fcost_local, MatchCost, ) f...
from __future__ import nested_scopes import traceback import os import warnings import pydevd_file_utils try: from urllib import quote except: from urllib.parse import quote # @UnresolvedImport try: from collections import OrderedDict except: OrderedDict = dict import inspect from _pydevd_bundle.pyd...
import datetime import xml.etree.ElementTree as et from itertools import cycle import tempfile import sqlalchemy as sa import sqlalchemy.orm from pyramid.httpexceptions import HTTPFound from clld.interfaces import IDataset, IMetadata, ILanguage, IIndex, IParameter from clld.web.adapters.base import Representation, In...
# -*- coding: UTF-8 -*- ################################################################################ # # Copyright (c) 2020 Baidu, 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...
"""Modèle un peu simpliste de hiérarchie LDAP + info métiers spécifiques.""" from __future__ import annotations import json from datetime import datetime from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Text, Tuple import ramda as r import structlog from abilian.core.entities import Entity, EntityQue...
from typing import Tuple import torch import pytest from skimage.io import imread from piq import srsim, SRSIMLoss # ================== Test function: `srsrim` ================== def test_srsim_to_be_one_for_identical_inputs(input_tensors: Tuple[torch.Tensor, torch.Tensor], device: str) -> None: prediction, _ = ...
from datetime import datetime from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.models import AnonymousUser, User from django.core.paginator import Paginator from django.db import transaction from django.db.models import Count from django.db.models.query import Prefetch f...
#!/usr/bin/env python ''' Tag To Header Version 2.0.1 By <NAME>, <NAME>(1), <NAME> and <NAME>(1) (1) Department of Pathology, University of Washington School of Medicine, Seattle, WA 98195 March 24, 2014 Isolate duplex tags, move them from within the sequenced read to the header region, and remove the spacer region. ...
#!/usr/bin/env python3 import os import urllib.request import json from munch import Munch, DefaultMunch import copy root = os.path.join(os.path.dirname(__file__), '..') def load(url): with urllib.request.urlopen(url) as f: return json.loads(f.read().decode()) data = DefaultMunch.fromDict({ 'zotero': load('...
from typing import Callable, Dict, FrozenSet, Iterable, List, Optional, Tuple, Union import os import click import hypothesis from ibm_cloud_sdk_core.authenticators.iam_authenticator import IAMAuthenticator from requests.models import Response from schemathesis.cli.context import ExecutionContext from schemathesis.cl...
# -*- coding: utf-8 -*- # Copyright (c) 2012 <NAME> # # See the file LICENSE for copying permission. import os import uuid import logging import leveldb import ujson as json from shutil import rmtree from threading import Thread, Event from leveldb import LevelDBError from .env import Environment from .constants im...
import itertools from chainer import configuration from chainer import function from chainer import cuda from chainer.utils import type_check from mylib.functions.activation.relu import ReLU from chainer.functions.connection.convolution_2d import Convolution2DFunction from chainer.functions.normalization.batch...
""" Test driver for KGTK Kypher query engine """ import sys import os import os.path import tempfile import io import argparse from kgtk.exceptions import KGTKException from kgtk.cli_argparse import KGTKArgumentParser, KGTKFiles DEFAULT_GRAPH_CACHE_FILE = os.path.join( tempfile.gettempdir(), 'kgtk-graph-cache-%...
from typing import List, Optional, Union, Tuple import torch import torch.nn.functional as F from transformers import GPT2LMHeadModel, LogitsProcessorList, LogitsProcessor, PreTrainedTokenizer from transformers.generation_utils import GenerationMixin, SampleOutput, SampleEncoderDecoderOutput, SampleDecoderOnlyOutput ...
import sys import torch.nn.functional as F from PIL import Image from torch import nn from torchvision import transforms import torchbearer import torchbearer as tb from dsketch.experiments.shared.args_losses import _Loss from dsketch.experiments.shared.utils import list_class_names from model import FEATURE_MAPS, SK...
""" Copyright (C) 2018-2020 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 i...
from abc import abstractmethod import io from typing import Any, Type, TypeVar, Union, overload from web3 import Web3 from .print import print_manifest_description from .errors import ModelNoContextError from .ledger import Ledger import credmark.cmf.types from credmark.dto import DTO, EmptyInput from .utils.contract_...
import abc from typing import Tuple import numpy as np from sklearn.metrics import auc from sklearn.utils.multiclass import type_of_target _available_uplift_modes = ("qini", "cum_gain", "adj_qini") class ConstPredictError(Exception): pass class TUpliftMetric(metaclass=abc.ABCMeta): @abc.abstractclassme...
import numpy as np import multiprocessing import os import os.path from mutual_information import mf from logging import getLogger logger = getLogger(__name__) class MutualInfoRandomizer: def __init__(self, observed_summary_statistics): self.observed = observed_summary_statistics self.case_N = ...
import os import sys import argparse import onnx import time import subprocess import numpy as np import tempfile from onnx import numpy_helper from collections import OrderedDict # Command arguments. parser = argparse.ArgumentParser() parser.add_argument('model_path', type=str, help="Path to the ONNX model") lib_gro...
import os, sys, logging import warnings import inspect from webob.exc import HTTPNotFound import tg from tg import request_local from tg.i18n import _get_translator from tg.request_local import Request, Response try: #pragma: no cover import pylons has_pylons = True except: has_pylons = False log = logg...
from __future__ import unicode_literals import functools import os import sys import re import errno import urllib3 import collections import six try: from json import loads as parse_json except ImportError: from simplejson import loads as parse_json from email.parser import Parser from urllib3.exceptions imp...
"""module for web map with films locations in certain years""" import argparse import functools from typing import Dict, List, Tuple, Union import folium import pandas as pd def create_map( path: str, location: Tuple[float, float], year: int, fast_procesing: bool, opened: bool, ) -> None: """c...
import logging from rest_framework import serializers from baserow.api.serializers import get_example_pagination_serializer_class from baserow.api.utils import get_serializer_class from baserow.contrib.database.fields.registries import field_type_registry from baserow.contrib.database.rows.registries import row_metad...
#!/usr/bin/env python # <NAME> <<EMAIL>> from __future__ import annotations from typing import Optional, TypeVar try: from pprint import pformat except ImportError: pformat = str # type: ignore import random import logging import asyncio import pyuavcan # type: ignore import pyuavcan.application # type: ign...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ## # @brief [py demo] muliti robot sync test # @author <NAME> (<EMAIL>) import rospy import os import threading, time import sys sys.dont_write_bytecode = True sys.path.append( os.path.abspath(os.path.join(os.path.dirname(__file__),"../../../../common/imp")) ) #...
#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : retrieve.py @Author : yyhaker @Contact : <EMAIL> @Time : 2020/03/16 19:14:19 ''' """ 构图方法:对于某个token 1. 检索出头或者尾部包含该词的三元组 2. 检索出三元组的相邻的三元组 3. 链接相同的实体,构建子图G """ import sys sys.path.append(".") import pickle import argparse import os import nltk ...
from __future__ import absolute_import, division, print_function import tensorflow as tf import numpy as np from numpy import linalg as LA import os #os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" #os.environ["CUDA_VISIBLE_DEVICES"]="0" #GPUconfig = tf.ConfigProto() #GPUconfig.gpu_options.per_process_gpu_memory_fracti...
"""Test graph data structure.""" import pytest @pytest.fixture def g3_fixt(): """Graph test fixture with 3 nodes.""" from graph_1 import Graph g = Graph() g.add_node(1) g.add_node(2) g.add_node(3) return g @pytest.fixture def trav_fixt(): """Graph test fixture with nodes and edges.""...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ Visualization routines using matplotlib """ import copy import logging import numpy as np from astropy import units as u from matplotlib import pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.colors import Normalize, L...
import unittest import numpy as np from sklearn.neighbors import KDTree as sk_KDTree from numba_neighbors import binary_tree as bt from numba_neighbors import kd_tree as kd # import os # os.environ['NUMBA_DISABLE_JIT'] = '1' class KDTreeTest(unittest.TestCase): def tree(self, data, leaf_size): return k...
''' This file contains the important function that is imported within the module ''' import numpy as np import matplotlib.pyplot as plt from time import time import os import glob from astropy.io import fits from functools import reduce from scipy.interpolate import LSQUnivariateSpline as spline from scipy.interpolat...
""" Simple implementation of URI-Templates (http://bitworking.org/projects/URI-Templates/). Some bits are inspired by or based on: * <NAME>'s example implementation (http://code.google.com/p/uri-templates/) * Addressable (http://addressable.rubyforge.org/) Simple usage:: >>> import uri ...
from __future__ import print_function import time from datetime import datetime, timedelta import argparse import os import math import warnings import torch import torch.backends.cudnn as cudnn import torch.nn.functional as F import torch.optim as optim import torch.utils.data.distributed from torchvision import data...
# -*- coding: utf-8 -*- # """*********************************************************************************************""" # FileName [ model.py ] # Synopsis [ the linear model ] # Author [ S3PRL ] # Copyright [ Copyleft(c), Speech Lab, NTU, Taiwan ] """**************************************...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: <NAME> # License: MIT from .bc import Periodic3D from .formulation import Maxwell3DBands from .geometry import * from .geometry import _is_on_plane from .materials import * from .simulation import Simulation class Lattice3D(Geometry): def __init__( ...
""" ARCHES - a program developed to inventory and manage immovable cultural heritage. Copyright (C) 2013 <NAME> and World Monuments Fund This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either ...
# Copyright 2020 - 2021 MONAI Consortium # 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...
import pytest from library import bcrypt from library.models import Genre, Author, Book, \ User, Order, OrderItem, Review, ReviewImage from sqlalchemy.exc import IntegrityError @pytest.fixture def initialize(session): genre = Genre(id=101, name='comedy') author1 = Author(id=101, firstname="test firstname...
# Copyright (c) 2020 The Khronos Group Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
import torchvision.transforms as ttf from factory import * from scipy.spatial.distance import cdist from tqdm import tqdm import sys import torch import os import argparse msls_cities = { 'train': ["trondheim", "london", "boston", "melbourne", "amsterdam", "helsinki", "tokyo", "toronto", "sa...
# Imports: import configparser import os import PySimpleGUI as Itf import datetime # Configs: config = configparser.ConfigParser() if not os.path.isfile('config.ini'): buch_launch_layout = [[Itf.Text('Buch Path: ', size=(10, 0)), Itf.Input('ex: C:/Pictures/Bildbuch', key='path'), ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import decimal import six from collections import Hashable from copy import deepcopy from flask import current_app, request from werkzeug.datastructures import MultiDict, FileStorage from werkzeug import exceptions from .errors import abort, SpecsError...
# Copyright 2021 Yalfoosh # # 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 ...
import sys import os import numpy as np import cv2 import scipy from scipy.stats import norm from scipy.signal import convolve2d import math import numpy as np from PIL import Image def roi(image): im = image h,w=im.shape[:2] r = cv2.selectROI(im) imCrop = im[int(r[1]):int(r[1] + r[3]), ...
"""Database related functionality.""" import os from contextlib import contextmanager from alembic.config import main as alembic_main import backoff import markus from pymysql.constants.CLIENT import MULTI_STATEMENTS from pymysql.constants.ER import LOCK_WAIT_TIMEOUT, LOCK_DEADLOCK from pymysql.err import DatabaseErr...
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import int from builtins import next from builtins import str from future import standard_library standard_library.install_aliases() import os import re im...
from django import template from django.conf import settings as _settings from django.http import QueryDict from django.utils.dateparse import parse_datetime from django.utils.html import conditional_escape from django.utils.safestring import mark_safe from json import dumps from datetime import datetime, timedelta im...
import traceback from typing import Any, Dict, List, Tuple, Union import urllib3 from dateparser import parse from pytz import utc from requests_ntlm import HttpNtlmAuth import demistomock as demisto from CommonServerPython import * from CommonServerUserPython import * urllib3.disable_warnings() SEVERITY_TRANSLATIO...
#!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
import argparse import copy from datetime import datetime from email.mime.text import MIMEText import getpass import os import platform import smtplib import subprocess import traceback import psutils.custom_errors as cerr import psutils.globals as psu_globals import psutils.scheduler as psu_sched from psutils.print_...
import copy from typing import List, Set, Tuple, Union from mltemplate.ci.yaml_order import PHASE_ORDER, sort_stages, STAGE_ORDER def is_ci_object(x): return isinstance(x, (Command, Phase, Job, Stage, Pipeline)) class Command: """Represents a shell command or group of commands to be executed on a console."...
import numpy as np import nltk import sklearn import pandas as pd import os import shlex import hashlib INPUT_FILE = './methodology/input/complete_set.xlsx' OUTPUT_FILE = './methodology/output/sentiment.csv' CV = 10 TRAIN_SIZE = 0.8 RANDOM_SEED = 42 SAMPLE_SIZE = 1500 K_BEST = 100 CLASSIFY = True dataset = pd.read_exc...
#Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe.utils import nowdate, cstr, flt, cint, now, getdate,get_datetime,time_diff_in_second...
from torch import reshape import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import pandas as pd from tqdm import tqdm device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class Conv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, **kw...
import os from libtbx.test_utils import approx_equal from rstbx.cftbx import coordinate_frame_helpers from dxtbx.imageset import ImageSetFactory from dxtbx.model.experiment_list import ExperimentListFactory from dxtbx.serialize import xds def test_to_xds(dials_data, tmpdir): file_names = dials_data("centroid_te...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # Copyright (c) Megvii, Inc. and its affiliates. import torch class DataPrefetcher: """ DataPrefetcher is inspired by code of following file: https://github.com/NVIDIA/apex/blob/master/examples/imagenet/main_amp.py It could speedup your pytorch dataloader...