text
stringlengths
3.07k
12.6k
import numpy as np from sklearn.preprocessing import OneHotEncoder import pandas as pd import copy def divide_age(dataset) : dataset['DAYS_BIRTH'] = (-dataset['DAYS_BIRTH'])//365 dataset.loc[(dataset['DAYS_BIRTH'] < 25) & (20 <= dataset['DAYS_BIRTH']), 'DAYS_BIRTH'] = 0 dataset.loc[(dataset['DAYS_BIRTH'] ...
#!/usr/bin/env python3 import os import requests, shutil, socket from datetime import datetime, timedelta from time import sleep from pathlib import Path import localconfig from camera import Camera from common import fmt_bytes, get_data_from_pic_stem, get_score class Task: def is_due(self, dt0, dt1): ""...
import re import six from okonomiyaki.versions import EnpkgVersion from simplesat.errors import ( InvalidConstraint, InvalidDependencyString, SolverException ) from .kinds import Any, Equal from .multi import MultiConstraints from .parser import ( _RawConstraintsParser, _RawRequirementParser, _DISTRIBUT...
from __future__ import annotations from typing import Optional, Any, TYPE_CHECKING import os import logging import pam # type: ignore import sys import socket import json from .config import configured_value if TYPE_CHECKING: from .layout import Layout logger = logging.getLogger(__name__) conf_greeter_user = c...
#!/usr/bin/env python import argparse import logging import os import sys import gi gi.require_version("Gtk", "3.0") gi.require_version("Gdk", "3.0") from .config import load_steady, ConfigError from .gui_handlers import SetupHandler, ConfigHandler from .msikeyboard import MSIKeyboard, UnknownModelError from .parsi...
import geopandas as gpd # imports for visuzalization import holoviews as hv import hvplot.pandas import numpy as np import pandas as pd import panel as pn import param # imports for geometry import shapely from holoviews import opts from . import obsreader import pyiwfm pn.extension() def ensure_version(verstr, min_...
#!/usr/bin/env python __author__ = "<EMAIL>" """ Input: fasta, each sequence is an individual gene given an input transcript sequence --- -> randomly select N positions to have a SNP, N = <length> / 300 -> generate two haplotypes, one is the original, one is mutated (store this in Haplotypes) -> for each haplotype, s...
# Copyright (c) 2019 <NAME> # # 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, distribute, ...
""" Requires: llvmdev-7.0.1 with all targets enabled """ import re import inspect from llvmlite import ir import llvmlite.binding as llvm import numba.cuda import numba as nb from .utils import get_version if get_version('numba') >= (0, 49): from numba.core import sigutils, registry else: from numba import ...
import os from argparse import ArgumentParser import numpy as np import pandas import torch import torchvision.transforms as transforms from torch import nn from torch.utils.data import DataLoader from torchvision.datasets import CIFAR10 import src import src.torch_utils as arch def train_loop(dataloader, model, los...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token from django.conf import settings from django.db import models from ckeditor.fields import RichTextField # Create your mo...
from flask import Flask, render_template, request, redirect, url_for, g, session, send_file import sqlite3 import secrets import os import uuid import mimetypes import pathlib from rq import Queue from redis import Redis app = Flask(__name__) app.queue = Queue(connection=Redis('xss-bot')) app.config.update({ 'SEC...
#!/usr/bin/env python3 import argparse import os import subprocess from bs4 import BeautifulSoup import re from datetime import datetime import copy def gen_ann_module(name, ns, prefix): revdate = datetime.today().strftime('%Y-%m-%d') str = """<?xml version="1.0" encoding="utf-8"?> <module> <namespace uri="...
import datetime import mimetypes from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from dox import managers # http://docs.djangoproject.com/en/dev/internals/contributing/#model-style # https://code.djangoproject.com/browser/django/trunk/dja...
# Copyright 2019 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...
import numpy as np import pandas as pd import random import sys def init_random_seeds(): # always use the same seed, always initialise before you do anything else RANDOM_SEED = 42 random.seed(RANDOM_SEED) np.random.seed(RANDOM_SEED) # faker.Faker.seed(RANDOM_SEED) def init_display_options(): ...
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from torch.optim.lr_scheduler import StepLR import torchvision import timeit from optimnew import * def add_noise(img): n...
from __future__ import division from magma import * import magma as m from magma.backend.coreir_ import CoreIRBackend from magma.frontend.coreir_ import DefineCircuitFromGeneratorWrapper from .util import DeclareCoreirCircuit from bit_vector import BitVector import math @cache_definition def DefineCoreirMux(width=...
#!/usr/bin/env python """ Copyright 2017 ThoughtSpot 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, pu...
# The MIT License (MIT) # Copyright (c) 2016 <NAME> # # 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, m...
import re import random from utils.misc.is_number import is_number from utils.misc.get_romans import get_romans # Can probably combine the two utility functions below def create_entry_objects(toc_entries, toc_page_numbers, doc): toc_entry_objects = [] romans = get_romans() starting_page = 0 # Reduce the...
import logging import multiprocessing import os import subprocess import traceback from argparse import ArgumentParser import sys LOG_LEVEL = logging.INFO LOG_FILE_LEVEL = logging.DEBUG logger = logging.getLogger('paxos') deptran_home = os.path.split(os.path.realpath(__file__)) deptran_home = deptran_home[0] g_log_d...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import copy import urllib from datetime import datetime, timedelta from threading import Lock from twicorder.utils import collect_key_values, Singleton from twicorder.search.queries import RequestQuery class CachedUser(object): def __init__(self, user_data): ...
import os import coloredlogs from coloredlogs import ColoredFormatter import logging from logging.handlers import TimedRotatingFileHandler import cythonbuilder DEFAULT_DATE_FORMAT = '%H:%M:%S' DEFAULT_FIELD_STYLES = dict( asctime=dict(color='white'), hostname=dict(color='white'), levelname=dict(color='...
#!/usr/bin/env python # coding: utf-8 import numpy as np from sklearn.neighbors import NearestNeighbors import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") def wraptopi(phi): return np.mod(phi + np.pi, 2*np.pi) - np.pi def best_fit_transform(A, B): ''' Ca...
# -*- coding: utf-8 -*- #@Author: <NAME> #@Date: 2019-11-18 20:53:24 #@Last Modified by: <NAME> #@Last Modified time: 2019-11-18 21:44:1 import numpy as np import torch import torch.nn.functional as F import os import time def compute_pairwise_distance(x): ''' computation of pairwise distance ma...
__all__ = [ 'build_actions_chain', 'build_document_action_chain', 'build_field_action_chain', 'get_all_document_types' ] import logging from copy import copy from typing import Iterable, Type from dictdiffer import patch, diff import mongoengine_migrate.flags as flags from mongoengine_migrate.excepti...
import os #basepath = 'C:\\Users\wb5888\Documents\la-tools-test\IDR_Drop' basepath = '/media/steven/big_boi/la-tools-test/IDR_Drop' os.chdir(basepath) print('working in directory {}.'.format(basepath)) from bs4 import BeautifulSoup from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Opt...
from collections import OrderedDict import json import os import re import shutil import yaml import xml.etree.cElementTree as ET from xml.etree import ElementTree from xml.etree.ElementTree import Element SOURCE_DIR = os.path.join(os.path.dirname(__file__), 'config') DEST_DIR = os.path.join( os.path.dirname(__fil...
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django.db.models import FileField from django.conf import settings from django.contrib.gis.db import models from django.contrib.auth.models import User from django.contrib.postgres...
import numpy as np np.set_printoptions(precision=6, suppress=True, linewidth=320) from numpy import where, zeros, ones, mod, conj, array, dot, angle, complex128 #, complex256 from numpy.linalg import solve # Set the complex precision to use complex_type = complex128 def calc_W(n, npqpv, C, W): """ Calculatio...
import warnings import numpy as np from pandas.api.types import is_object_dtype __all__ = [ "_checkColumnTypes", "_checkColumnTypesEqual", "_classHandler", "_percentHandler" ] def _checkColumnTypes(df, cols, column_mapping): """ Checks that each dataframe column listed in cols has Pandas dtyp...
# python imports import os import glob # third-party imports import numpy as np import nibabel as nib from matplotlib import pyplot as plt import pandas as pd from pandas import ExcelWriter # project imports from multi_affine import datagenerators from multi_affine import networks from multi_affine.utils import load_...
import networkx as nx from sklearn import preprocessing import glob import warnings import pandas as pd from IPython.display import display import matplotlib.pyplot as plt pd.options.display.max_columns = 20 warnings.filterwarnings("ignore") import numpy as np def read_label(): label = {} for i in range(3, ...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import absolute_import import sys sys.path.append(r"../..") ##This is your Project Root## from pushkin_gs.definition import ROOT_DIR # ROOT_DIR = os.path.abspath('..') #This is the father folder # ROOT_DIR = os.path.abspath('.') #This is your current Work Root i...
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import re import json import time import requests from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions from selenium.webdriver.common.by import By """ 匯入欲搶購的連結、登入帳號、登入密碼及其他...
""" (*)~--------------------------------------------------------------------------- Pupil - eye tracking platform Copyright (C) 2012-2019 Pupil Labs Distributed under the terms of the GNU Lesser General Public License (LGPL v3.0). See COPYING and COPYING.LESSER for license details. ------------------------------------...
from PIL import Image, ImageDraw import numpy as np import os import time from seetaface.api import * import torch TARGET_DIR = 'imgs/' files = [f for f in os.listdir(TARGET_DIR)] npz = np.load('all4.npz') known_face_encodings = npz['encode'] known_face_names = npz['names'] sids = npz['sids'] init_mask = FACE_DETECT...
# -*- coding: utf-8 -*- # utils import ftplib from collections import OrderedDict import time import os import threading class ScanerInitException(Exception): def __init__(self): Exception.__init__(self) class Ftp(object): """ 文件传输基类 # """ def __init__(self, host, port=21): ftp =...
import sklearn from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, WhiteKernel from scipy.interpolate import interp1d import numpy as np # plt.figure() def generate_slow_background(x, scale=500, npoints=1000): kernel = 1.0 * RBF(length_scale=scale) ...
import random import copy class MyDict(dict): def __getitem__(self, key): key = tuple([tuple(x) for x in key]) return super().__getitem__(key) def __setitem__(self, key, value): key = tuple([tuple(x) for x in key]) return super().__setitem__(key, value) def bfs(start_node, e...
from . import s3_utils import boto3 from botocore import UNSIGNED from botocore.config import Config import m3u8 import math from . import scraper import ffmpeg import os from datetime import datetime from datetime import timedelta from pytz import timezone import time import sys from pathlib import Path from . impor...
### effective area tables and tools # Tables -------------------------------------- # in the form (etamax, value) # if eta < etamax, apply this value # else proceed to next pair # eta should be either the eta of the supercluster or the eta of the electron, # which is specified below scaling_03_04 = 16./9. areas = dic...
import time import tensorflow as tf import scipy.io as sio import numpy as np from scipy.spatial import cKDTree flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('num_evecs', 120, 'number of eigenvectors used for representation') flags.DEFINE_integer('num_model', 5000, '') flags.DEFIN...
#!/usr/bin/env python import tensorflow as tf import read_inputs import numpy as N #read data from file data_input = read_inputs.load_data_mnist('MNIST_data/mnist.pkl.gz') #FYI data = [(train_set_x, train_set_y), (valid_set_x, valid_set_y), (test_set_x, test_set_y)] data = data_input[0] #print ( N.shape(data[0][0])[0...
# Copyright (c) 2017, <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: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the...
import logging import os import platform import shutil import socket import sys import tempfile import time import zipfile import yaml from future.standard_library import install_aliases from .exception import PyngrokNgrokInstallError, PyngrokSecurityError install_aliases() from urllib.request import urlopen try: ...
# 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...
# Copyright (c) 2012-2013 SHIFT.com # # 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, dist...
import argparse import os from pattern3.metrics import levenshtein_similarity from corpus.alignment import Voice from util.string_util import normalize os.environ['CUDA_VISIBLE_DEVICES'] = '3' from os import makedirs from os.path import abspath, exists, join, splitext, basename import numpy as np import pandas as p...
# + import theforce.cl as cline from theforce.calculator.active import FilterDeltas from theforce.util.aseutil import init_velocities, make_cell_upper_triangular from ase.md.npt import NPT from ase.md.langevin import Langevin from ase.io import read from ase import units import numpy as np import os def md(atoms, dyn...
import logging from typing import Dict, List, Tuple import torch from allennlp.common.util import pad_sequence_to_length from allennlp.data.token_indexers import PretrainedTransformerIndexer from allennlp.data.token_indexers.token_indexer import IndexedTokenList, TokenIndexer from allennlp.data.tokenizers.token import...
""" Part of weight_app :copyright: (c) 2012 by <NAME>. :license: BSD, see LICENSE for more details. """ from flask import Blueprint, Response, request, abort, redirect, flash, \ url_for, render_template from jinja2 import TemplateNotFound from flask.ext.login import login_required, login_user, logout_user,...
############################################ # title: DSBalance (micro-economics simulator for demand and supply ) # version: 1.0 # date: 2021/12/03 # author: okimebarun # url: https://github.com/okimebarun/ # url: https://qiita.com/oki_mebarun/ ############################################ import streamlit as st impo...
from collections import OrderedDict from django.db.models import F from finote_api.models import * from myapi.settings import TMDB_APIKEY import requests import datetime import time class MovieUserCount(object): def __init__(self): self.cnt = {} @staticmethod def merge_dict4(d1, d2): retu...
# coding:utf8 from __future__ import unicode_literals, division, print_function import importlib import logging import sys import tornado.escape from tornado.ioloop import IOLoop # from tornado.options import define, options from tornado.web import RequestHandler, Application import conf import url from manager impo...
""" _| _| _| _| _| _| @Time : 2020.11.18 18:16 _| _| _| _| _| _| @Auth : <NAME> _| _| _| _| _| @File : fft _| _| _| _| _| _| @IDE : PyCharm _| _| _| _| _| @CODING : utf-8 """ import numpy as np...
#!/usr/bin/env python import errno import os import shutil import subprocess from typing import List, Tuple def cleanup(): cwd = os.getcwd() print('cleanup paths in %s' % cwd) cleanup_paths = [] rename_paths: List[Tuple[str, str]] = [] # Tuples of old -> new path symlinks = [] dockerfiles =...
import mono.player as pl import mono.board as br # reading csvs def test_read_fields(): fields = br._read_fields() assert len(fields) == 40 assert fields[10].category == 'jail' assert fields[15].owner == None assert fields[16].colour == 'orange' def test_read_cards(): chance = br._read_chanc...
# coding: utf-8 import torch torch.manual_seed(1234) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False import numpy as np np.random.seed(1234) import random random.seed(1234) import argparse import time import math import os import torchtext import torch.nn as nn import yaml import pick...
""" The MIT License (MIT) Copyright (c) 2015 <NAME> (AKA Gato) 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, m...
# -*- coding: utf-8 -*- # @Time : 20-6-9 上午10:20 # @Author : zhuying # @Company : Minivision # @File : anti_spoof_predict.py # @Software : PyCharm import os import cv2 import math import torch import numpy as np import torch.nn.functional as F from src.model_lib.RepVGGNet import RepVggFTNet from src.model_lib.MiniFAS...
# import torch # import numpy as np def torch_nms(bboxes, scores, classes=None, thresh=.5): """ Non maximum suppression implemented with pytorch tensors CURRENTLY NOT WORKING Args: bboxes (Tensor): Bounding boxes of one image in the format (x1, y1, x2, y2) scores (Tensor): Scores of ...
# -*- coding: utf-8 -*- # Copyright (C) 2010-2015 <NAME> All rights reserved # Langstrasse 4, A--2244 Spannberg, Austria. <EMAIL> # **************************************************************************** # This module is part of the package GTW. # # This module is licensed under the terms of the BSD 3-Clause Licen...
import sys import os import argparse import json import pandas as pd from tree_response import * parser = argparse.ArgumentParser() parser.add_argument('c45_output', help= 'JSON file with the C4.5 output.') parser.add_argument('configuration', help= 'Configuration file of the request.') parser.add_argument('--summary'...
import os import rsa import pickle import struct import multiprocessing from Cryptodome.Cipher import AES from Cryptodome.Hash import SHA256 from Cryptodome.Random import get_random_bytes from diffiehellman import DiffieHellman from secretsharing import SecretSharer class SIG: """Generates public and private key...
from Scripts.Data.AcousticData import PureAcousticData from Scripts.Models.DataParsers.AcousticParser import AcousticDataParser, AcousticLabelParser from Scripts.utils.others import make_AuDataObjs_list from Scripts.utils.tools import format_dict2file from Scripts.Models.AcousticModel import AcousticModel import j...
from whisk.project import Project import whisk.git as git from whisk.cd import cd from whisk.cli.log_tree import PARENT_TREE_NODE_PREFIX, CHILD_TREE_NODE_PREFIX import os import subprocess from pathlib import Path import logging import sys from subprocess import PIPE logger = logging.getLogger(__name__) NOTEBOOK_EXAM...
#!/usr/bin/env python3 """ Copyright 2020 Johns Hopkins University (Author: <NAME>) Copyright 2020 ARL (Author: <NAME>) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) Prepare rats_sad data for training a speech activity detection system. Input comes from the annotations provided with the corpus. Output ...
import numpy as np import matplotlib.pyplot as plt from rllab.misc.overrides import overrides from rllab.core.serializable import Serializable from rllab.spaces.box import Box from rllab.envs.base import Env from rllab.misc import logger class MultiGoalEnv(Env, Serializable): """ Move a 2D point mass to one ...
#!/usr/bin/env python3 # Copyright 2017 The Fontbakery Authors # Copyright 2017 The Google Font Tools 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/lice...
# greaseweazle/image/kryoflux.py # # Written & released by <NAME> <<EMAIL>> # # This is free and unencumbered software released into the public domain. # See the file COPYING for more details, or visit <http://unlicense.org>. import struct, re, math, os import itertools as it from greaseweazle import error from greas...
import ray import sys from ray import tune from ray.rllib.agents.registry import get_agent_class from ray.rllib.agents.ppo.ppo_policy_graph import PPOPolicyGraph from ray.rllib.models import ModelCatalog from ray.tune import run_experiments from ray.tune.registry import register_env import tensorflow as tf from social_...
import sys import weakref from sentry_sdk._compat import reraise from sentry_sdk.hub import Hub from sentry_sdk.integrations import Integration, DidNotEnable from sentry_sdk.integrations.logging import ignore_logger from sentry_sdk.integrations._wsgi_common import ( _filter_headers, request_body_within_bounds,...
""" This data utils file for celeba is from https://github.com/sayantanauddy/vae_lightning """ from functools import partial import pandas as pd import os import PIL import glob import torch from torch.utils.data import Dataset, DataLoader, random_split from torchvision import transforms, utils, io from torchvision.d...
from ..renderer import opengl_utils import numpy as np from ..pysixd import transform from sklearn.neighbors import NearestNeighbors def rgbd_to_point_cloud(K, depth): vs, us = depth.nonzero() zs = depth[vs, us] xs = ((us - K[0, 2]) * zs) / float(K[0, 0]) ys = ((vs - K[1, 2]) * zs) / float(K[1, 1]) ...
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
import threading import norfair import numpy as np import math import requests import json from datetime import datetime class Monitor_object(): def __init__(self, id, class_name, position, timestamp): self.life = 10 self.id = id self.class_name = class_name self.positions = [] ...
# Copyright 2020 Canonical Ltd # Copyright 2016-2019 Open Source Robotics Foundation, 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 #...
# Copyright (c) 2020 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 appli...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Nov 4, 2020 @author: Enx """ #%% Importing and Variable fixing from well_plate_project.config import data_dir, reportings_dir # Dataset paths raw_data_dir = data_dir / 'raw' interm_data_dir = raw_data = data_dir / 'intermediate' describe_data_dir = repor...
import rospy import enum import time import numpy as np from control_node import HiwinRobotInterface from collision_avoidance.srv import collision_avoid, collision_avoidRequest pic_pos = [ [5, 0.5, -20, -180, 0, 0], [10, 0.5, -20, -180, 0, 0], [15, 0.5, -20, -180, 0, 0], [20, 0.5, -20, -180, 0, 0], [25, 0.5, -20...
import sys from heapq import heapify, heappop class V(object): def __init__(self, value, weight=sys.maxsize, parent=None): self.value = value self.weight = weight self.parent = parent self.vertices = [] def __str__(self): return "({V}, {W}, {P})".format(V=self.value, ...
"""Routines that implement processing data & getting models. This file includes various routines for processing & acquiring models, for later use in the code. The table data preprocessing is straightforward. We first applying scaling to the data and fit a random forest classifier. The processing of the image data is ...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. from copy import deepcopy from typing import Iterable, List, Optional, Iterator, Tuple, Mapping import heapq import copy import torch from torch import Tensor, nn from overrides import overrides from archai.nas.model_desc import C...
import atexit import logging import signal import subprocess import time from functools import partial from threading import Timer, Thread from typing import Iterable, Optional, Sequence, Union ''' This is from https://github.com/elifesciences/sciencebeam-parser https://github.com/elifesciences/sciencebeam-parser/blob...
import ast from os import walk class ParsingError(Exception): def __init__(self, errors, message): super().__init__(message) self.errors = errors class OdfParser: def __init__(self, root_path): self.root_path = root_path self.cached_folders = {} self.cached_odfs = {}...
import csv import re import time import collections import os def is_spam(mail): module_dir = os.path.dirname(__file__) pattern = r"^http:" spam_words = ['free','paid','discount','price','off','cheap','trade','.inc','limited','exchange','xchange','flat','latest','new','999','available','lose','win','winning','l...
import re import tempfile import subprocess import operator import collections BEGIN_DOCUMENT_REGEX = re.compile( r"#begin document \(?([^\);]*)\)?;?(?: part (\d+))?") COREF_RESULTS_REGEX = re.compile( r".*Coreference: Recall: \([0-9.]+ / [0-9.]+\) ([0-9.]+)%\tPrecision: \([0-9.]+ / [0-9.]+\) ([0-9.]+)%\tF1: (...
import time import numpy as np import carla VEHICLE_NAME = 'vehicle.lincoln.mkz2017' COLLISION_THRESHOLD = 20000 def set_sync_mode(client, sync): world = client.get_world() settings = world.get_settings() settings.synchronous_mode = sync settings.fixed_delta_seconds = 1.0 / 20.0 world.apply_...
from urllib import response from api.serializers.products import (LikeSerializer, ProductSerializer, SimpleProductVariantSerializer, ValidateAddToList, ValidateWishList, WishlistSerializer) from api.serializers.reviews import ReviewSerializer from api.utils import CustomImageProces...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from tqdm import tqdm from flashtext import KeywordProcessor import random class Annotation(): def __init__(self, TRAIN_FILE, DEV_FILE, EVAL_FILE, DICT_FILE): self.train_file = TRAIN_FILE self.dev_file = DEV_FILE self.eval_file = EVAL_FILE ...
import math import torch import torch.nn as nn import torch.nn.functional as F class ASPPModule(nn.Module): def __init__(self, inplanes, planes, kernel_size, padding, dilation, batchnorm): super(ASPPModule, self).__init__() self.atrous_conv = nn.Conv3d(inplanes, planes, kernel_size=kernel_size, ...
# Copyright 2008-2015 Nokia Networks # Copyright 2016- Robot Framework Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 ...
import binascii from neo.Prompt.Utils import parse_param from neo.Core.FunctionCode import FunctionCode from neo.Core.State.ContractState import ContractPropertyState from prompt_toolkit import prompt import json from neo.VM.ScriptBuilder import ScriptBuilder from neo.Prompt.Utils import get_arg from neocore.Cryptograp...
import sys from PyPDF2 import PdfFileWriter, PdfFileReader, PdfFileMerger from reportlab.pdfgen.canvas import Canvas from reportlab.lib.pagesizes import letter from reportlab.lib.utils import ImageReader from reportlab.lib.units import inch, cm import qrcode from artexamscan.tag.pdf import images_from_pdf def parse...
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
import numpy as np from numba import * """ CPU Kernel implementations """ @jit def conv_step_CPU(S, V, s, w, stride, th): V[V > th] = 0. for i in range(V.shape[0]): for j in range(V.shape[1]): for k in range(V.shape[2]): V[i, j, k] += np.sum(w[:, :, :, k] * s[i * stri...
# test the pre-trained model on a single video # (working on it) # <NAME> and <NAME> import os import re import cv2 import argparse import functools import subprocess import numpy as np from PIL import Image import moviepy.editor as mpy import torch.nn.parallel import torch.optim from models import TSN from transform...
import warnings import numpy as np from pandas import Categorical, DataFrame, Series from .pandas_vb_common import tm class Construction: params = ["str", "string"] param_names = ["dtype"] def setup(self, dtype): self.series_arr = tm.rands_array(nchars=10, size=10 ** 5) self.frame_arr...