text stringlengths 3.07k 22.1k |
|---|
import pytest
from bs4 import BeautifulSoup
import cocrawler.facet as facet
from cocrawler.urls import URL
def test_double_entries():
t = '''
<meta name="robots" content="noarchive" />
<meta name="robots" content="index, follow" />
<meta http-equiv="content-type" content="text/html; charset=utf-8">
... |
import pygame
import math
from queue import PriorityQueue
WIDTH = HEIGHT = 800 #400 is another option
win = pygame.display.set_mode((WIDTH,HEIGHT))
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
GREY = (128, 128, 128)
BLACK = (0,0,0)
WHITE = (255,255,255)
PURPLE = (128, 0, 128)
ORANGE = (250, 165, 0)
TU... |
import collections
from typing import List
# 自带函数
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
stat = collections.Counter(nums)
return [t[0] for t in stat.most_common(k)]
# 堆
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
... |
import colorama
import os
import time
import uuid
from colorama import Fore, Back, Style
import hashlib, bcrypt
import sys
wi = Fore.WHITE
print(Fore.CYAN + '''
█████ █████ █████
░░███ ░░███ ░░███
░███ ░███ ██████ █████ ... |
import datetime
import logging
import re
import psycopg2
from typing import Optional
import telegram.error
from telegram import Update, messageentity, ReplyKeyboardMarkup, ReplyKeyboardRemove
from telegram.ext import (
ConversationHandler,
CallbackContext
)
import data
from doesntCare import DoesntCare
from m... |
from collections import defaultdict
import numpy
from OpenGL.GL import *
from btypes.big_endian import *
import gx
from j3d.opengl import *
import logging
logger = logging.getLogger(__name__)
class Header(Struct):
magic = ByteString(4)
section_size = uint32
attribute_format_offset = uint32
position_o... |
"""Training hooks/callbacks.
Adapted from
https://github.com/facebookresearch/detectron2
"""
import datetime
import logging
import os
import tempfile
import time
from collections import Counter
import torch
from fvcore.common.checkpoint import PeriodicCheckpointer as _PeriodicCheckpointer
from fvcore.common.timer im... |
"""Tools for studying Zernike sky approximations
"""
from os import path
from argparse import ArgumentParser
from collections import OrderedDict
from collections import namedtuple
import logging
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import pandas as pd
from astropy.coordinates im... |
# j'importe les modules que je vais utiliser par la suite
import datetime
import typing # typing contient des objets pour indiquer à l'éditeur de texte/code quels sont les types de variable
import requests # requests est un module qui doit être téléchargé avec pip
class WeatherAppError(Exception): # je créer un o... |
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
import re
''' These are values that would be inconvenient to change at the command line '''
# The entire Cpf1(Cas12)-Repeat sequence. Terminates right before the SWSWSWS
cas12RepeatSequence = "ACAATTTCTACTGTTGTAGAT"
# This is the CRISPR-gate Promo... |
import collections
import mimetypes
import re
import tempfile
import uuid
import requests
import encapsia_api
class Base:
def __init__(self, url, token, version="v1"):
"""Initialize with server URL (e.g. https://myserver.encapsia.com)."""
if not url.startswith("http"):
url = f"https:... |
import math
import logging
import time
from datetime import timedelta
# If you pass the word, it'll tell you if this word can be used in the current sentence
def isSentenceAllowed(originalStringLength, sentence, args):
global theOrgStringHash
sNew = sentence.replace(" ", "")
if len(sNew) > originalStringL... |
import json
import os
import sys
import time
from datetime import datetime
from time import gmtime, strftime
from urllib.parse import parse_qs, urlparse
import boto3
import numpy as np
import requests
from chalice import Chalice
# Global Varibale from model
content_type = "application/json"
accept = "Accept"
min_serv... |
from constants import Const
from category_extraction.BinCategoryExtractor import BinCategoryExtractor
from ote.CrfOpinionTargetExtractor import CRFOpinionTargetExtractor
from ote.OpinionTargetFeatureExtractor import extract_features
from sentiment_polarity.SentimentPolarityClassifier import CNNSentimentPolarityClassifi... |
import datetime
from time import mktime
from typing import List, Tuple
import math
from py_yr.config.settings import LANGUAGE, FORECAST_TYPE_STANDARD, FORECAST_TYPE_HOURLY
from django.utils.translation import ugettext as _
from py_yr.yr import Yr
from api.models import Credit, Time, WindSpeed, WindDirection, Temperatu... |
from enum import Enum
import json
import logging
from typing import List, Optional, Union
from uuid import uuid4
import channels.layers
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from django.db import connections
from datetime import datetime
from pydantic.main impo... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 10 18:42:00 2021
@author: zongsing.huang
"""
# =============================================================================
# x in {0, 1}
# 最大化問題的最佳適應值為-D;最小化問題的最佳適應值為0
# =============================================================================
import n... |
#
#------------------------------------------------------------------------------
# Copyright (c) 2013-2014, <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.a... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import arcsim
import gc
import time
import json
import sys
import gc
import numpy as np
import os
from datetime import datetime
import cv2
import matplotlib.image as mpimg
import pytorch3d
from pytorch3d.structures import Meshes, Pointclouds
from pyto... |
# NOT MY CODE, HERE FOR REFERENCE
# Pretty sure this is crap.
import time
import smbus
import datetime
import math
# I2C address vary on the device
# Default are the Adafruit LSM9DS0
MAG_ADDRESS = 0x1D
ACC_ADDRESS = 0x1D
GYR_ADDRESS = 0x6B
#LSM9DS0 gyrometer registers
WHO_AM_I_G = 0x0F
CTRL_REG1_G = 0x20
CTRL_RE... |
# Automatically adapted for numpy.oldnumeric Aug 01, 2007 by
# Further modified to be pure new numpy June 24th 2008
"""
CDMS CoordinateAxis objects
"""
import sys
from . import cdmsNode
import cdtime
import copy
import numpy
# import internattr
from .cdmsobj import CdmsObj
from .axis import TransientAxis
from .error i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from aldryn_apphooks_config.admin import BaseAppHookConfig, ModelAppHookConfig
from aldryn_translation_tools.admin import AllTranslationsMixin
from cms.admin.placeholderadmin import FrontendEditableAdminMixin
from cms.admin.placeholderadmin import Placeho... |
"""ColoredMNIST Dataset."""
from enum import Enum
from pathlib import Path
from typing import ClassVar, Dict, List, Optional, Tuple, Union, cast
from PIL import Image
import numpy as np
import numpy.typing as npt
from ranzen.decorators import implements, parsable
from ranzen.misc import str_to_enum
import torch
from t... |
from __future__ import print_function
import os
from skimage.transform import resize
from skimage.io import imsave
import numpy as np
from keras.models import Model
from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose
from keras.optimizers import Adam
from keras.callbacks import ModelChec... |
"""Deep Q learning graph
The functions in this file can are used to create the following functions:
======= act ========
Function to chose an action given an observation
Parameters
----------
observation: object
Observation that can be feed into the output of make_obs_ph
stochastic: bool... |
from .base import LegistarScraper
from lxml.etree import tostring
class LegistarBillScraper(LegistarScraper):
def legislation(self, search_text='', created_after=None,
created_before=None, num_pages=None) :
for page in self.searchLegislation(search_text, created_after,
... |
import tensorflow as tf
class LSTMNBase(object):
'''Base class implementing the constructor and the generic soft attention reweighting.
Args:
num_units (int): Number of units in the hidden LSTMN layer
scope (Optional[tf VariableScope]): Scope that all operations will be prefixed with.
Att... |
# TODO Sep 08 version
"""This module contains simple helper functions """
from __future__ import print_function
import torch
import numpy as np
from PIL import Image
import os
import math
def tensor2im(input_image, imtype=np.uint16):
""""Converts a Tensor array into a numpy image array.
Parameters:
i... |
"""Objects for interfacing with SQL databases."""
from hsdbi import base
from hsdbi import errors
import importlib
import sqlalchemy as sa
from sqlalchemy import orm as saorm
from sqlalchemy import func
from sqlalchemy.dialects import mysql
# Static Functions
def create_sql_session(connection_string):
"""Create... |
# flake8: noqa
from __future__ import division
import numpy as np
import torch
from torch.distributions import Categorical, constraints
from torch.distributions.normal import Normal
from torch.distributions.transformed_distribution import TransformedDistribution
from torch.distributions.transforms import StickBreaking... |
#!/bin/false
"""This script performs these steps:
#1. retrieve author, title info from sqlite db
#2. form CQL query
#3. send query to Proquest API
#4. retrieve results
#5. import results to tmp table in db
#6. update pq_gateway table from tmp_pq_gateway
"""
import logging
import logging.handlers
import optparse
import ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 18 13:42:33 2018
@author: yoelr
"""
from . import compounds as cmps
from ._exceptions import UndefinedCompound
import numpy as np
inf = np.inf
__all__ = ('Species', 'WorkingSpecies')
# TODO: Fix how Dortmund groups are selected in thermo.Chemical. Glycerol defaults to ... |
"""The filters implementation.
Provide filters for querying close approaches and limit the generated
results.
The `create_filters` function produces a collection of objects that is used by
the `query` method to generate a stream of `CloseApproach` objects that match
all of the desired criteria. The arguments to `crea... |
import logging
import json
import requests
import voluptuous as vol
from datetime import datetime, timedelta
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME
from homeassistant.helpers.entity import Entit... |
import torch
import torchvision.utils as vutils
import h5py
import numpy as np
import pickle
from skimage import exposure
N = 15 # default maximum number of sections to show
min_batch = 3
def prepare_data(volume, label, output, input_label=None, color_data=None):
volume = exposure.rescale_intensity(volume.numpy(),... |
# coding=utf-8
from __future__ import print_function, division
import os
from teletype import codes, io
__all__ = [
"SelectOne",
"SelectApproval",
"SelectMany",
"ProgressBar",
"ChoiceHelper",
]
class SelectOne(object):
""" Allows the user to make a single selection
- Use arrow keys or... |
from __future__ import unicode_literals
import discord
from discord import Member
from typing import Optional
from discord.ext import commands
from discord.ext.commands import Cog, Greedy
from discord.utils import get
from discord_slash import cog_ext, SlashContext, SlashCommand
import discord_slash
from discord_slash.... |
import json
import logging
import os
import sys
from distutils.util import strtobool
from typing import Any, Callable, Iterator, List, Optional, TypeVar, Union
import requests
from flask import Flask, Response, abort, jsonify, request, stream_with_context
from plz.controller import configuration
from plz.controller.a... |
"""Copula Based Outlier Detector (COPOD)"""
# Author: <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
# License: BSD 2 clause
from __future__ import division, print_function
import warnings
import matplotlib.pyplot as plt
import numpy as np
from joblib import Parallel, delayed
from scipy.stats import skew
from sklearn.ut... |
"""
file: cas_manager.py
authors: <NAME> <<EMAIL>>
date: Jan. 2014
description: This module contains the CAS_manager class, which is a thread that continously checks if there
is work that needs to be done. Also contains supporting classes of Worker and ThreadPool used by
the CAS_Manager.
"""
from analyzer.analy... |
import keras
from keras.layers import Input, Dense, Activation, Reshape, Dropout
from keras.models import Model
import numpy as np
import os
import csv
import random
from keras.utils import multi_gpu_model
from keras.models import load_model
from sklearn.model_selection import train_test_split
import pickle
import rand... |
"""
Assigns negative log-likelihoods to each trace in a set of trajectories.
"""
import argparse
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
import sys
sys.path.append('../')
from load_paths import load_box_paths
import matplotlib as mpl
import matplotlib.dates a... |
"""
ZoneUtil
Get various information from a zone ID.
"""
from toontown.toonbase.ToontownGlobals import *
from direct.directnotify import DirectNotifyGlobal
zoneUtilNotify = DirectNotifyGlobal.directNotify.newCategory("ZoneUtil")
tutorialDict = None
def isGoofySpeedwayZone(zoneId):
return (zoneI... |
#!/usr/bin/python
# encoding: utf-8
# -*- encoding: utf-8 -*-
import torch
import torch.nn as nn
from torch.autograd import Variable
import collections
from PIL import Image, ImageFilter
import math
import random
import numpy as np
import cv2
#with open('./data/char_std_5990.txt') as f:
with open('./data/new_complex... |
"""keyword.py
Classes to define and read conveniently individual keywords of an input file
"""
import re
import sys
import inspect
import numpy as np
from muspinsim.constants import MU_GAMMA
from muspinsim.input.larkeval import LarkExpression, lark_tokenize
from muspinsim.input.variables import FittingVariable
from ... |
"""
DMCI : Api Test
=================
Copyright 2021 MET Norway
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... |
"Unit tests of larry's indexing by label method, lix"
from nose.tools import assert_raises
import numpy as np
from numpy.testing import assert_equal
import la
from la import larry
from la.util.misc import isscalar
from la.util.testing import assert_larry_equal as ale
S = slice
N = None
si = [
((2,3,4) , ([0... |
import time
import yaml
import json
from os import listdir
def output_test(out, test_name, lines):
out.write('- (void)test%s\n' % test_name)
out.write('{\n')
out.write('\n'.join(lines))
out.write('\n')
out.write('}\n\n')
def parse_class(out, className, classTests):
total = 0
init_name = ... |
"""
Adapted from:
https://learn.adafruit.com/adafruit-mini-pitft-135x240-color-tft-add-on-for-raspberry-pi/python-usage#displaying-system-information-3042505-43
Some more fonts:
http://www.dafont.com/bitmap.php
"""
import adafruit_rgb_display.ili9341 as ili9341
import board
import digitalio
from PIL import Image, Ima... |
__all__ = [
'MigrationPolicy',
'Migration',
'MigrationsGraph'
]
from typing import Dict, List
from mongoengine_migrate.exceptions import MigrationGraphError
from mongoengine_migrate.utils import Slotinit
from enum import Enum
class MigrationPolicy(Enum):
"""Policy which determines how much the migra... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import os
import compas
from compas.geometry import centroid_points
from compas.viewers.viewer import Viewer
from compas.viewers.core.drawing import xdraw_polygons
from compas.viewers.core.drawing import xdr... |
import sys, random, os
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QToolBar, QLabel, QComboBox, QSpinBox, QVBoxLayout, \
QHBoxLayout, QGridLayout, QAction, QToolButton, QColorDialog, QSplitter, QLineEdit, QTextEdit, QLayout
from PyQt5.QtGui import QPainter, QColor, QFont, QPalette, QPixmap, QPen... |
# Licensed under an MIT open source license - see LICENSE
'''
Make the pipe comparison plot for paper.
'''
import numpy as np
import matplotlib.pyplot as p
from astropy.io import fits as fits
from astropy.table import Table
from scipy.ndimage import zoom
from matplotlib.collections import Collection
from matplotlib.a... |
#!/bin/env python3
import RNA
import RNAblueprint as rbp
from utils.pseudoknots import pKiss
import argparse
import math
from Bio import SeqIO, Seq
from concurrent.futures import as_completed, ProcessPoolExecutor
from tqdm import tqdm
TARGET_GISSD = "...(((((((..((....)).)))))))...((((((....((((((...((...((((((....)... |
import torch
from torch import nn
from torch.nn import init
import torch.nn.functional as F
import math
from torch.autograd import Variable
import numpy as np
from torch.nn.quantized import FloatFunctional
#from .deeplab_resnet import resnet50_locate
config_resnet = {'convert': [[64,256,512,1024,2048],[128,256,256,51... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
from random import randint
from markupsafe import escape
from pymongo import ASCENDING
from flask import Blueprint, render_template, session, url_for,redirect,flash,request,abort
from functools import wraps
from bson.objectid import ObjectId
import json
from datetime import datetime, timedelta
from app.users.forms impo... |
# Copyright (c) 2019 Georgia Tech Robot Learning Lab
# Licensed under the MIT License.
from abc import ABC, abstractmethod
import numpy as np
import copy
from rl.core.online_learners.online_learner import OnlineLearner
from rl.core.online_learners.base_algorithms import MirrorDescent, Adam, BaseAlgorithm
from rl.core.... |
import os
import tqdm
import json
import pymongo
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from collections import defaultdict
class create_author_db():
def __init__(self,
id_variable,
entity_variable,
... |
import os
# os.environ["CUDA_VISIBLE_DEVICES"]="";
import h5py
import numpy as np
import time
import tensorflow as tf
from tensorflow import keras
import tensorflow.keras.layers as L
import tensorflow.keras.backend as K
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.per_p... |
import numpy as np
from scipy.optimize import curve_fit
import math
import json
__author__ = "<NAME>"
# Module with an assortment of functions see
# individual function comments for description
# calc and return unit vector of two pts, pts must numpy format
def unit_vector(pt1, pt2):
line = pt2 - pt1
retur... |
import torch
import torch.nn.functional as F
import torch.nn as nn
import math
from config import cfg
import torch.nn.init as init
def xavier(param):
init.xavier_uniform_(param)
def adjust_learning_rate(optimizer, gamma, step, decay_step, base_lr):
"""Sets the learning rate to the initial LR deca... |
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2021 <NAME> <<EMAIL>>
#
# SPDX-License-Identifier: MIT
import threading
from typing import List
import yaml
import json
from lib.composegenerator.v0.generate import createComposeConfigFromV0
from lib.composegenerator.v1.generate import createComposeConfigFromV1
from li... |
from channels.generic.websocket import AsyncJsonWebsocketConsumer, WebsocketConsumer
from .global_member import GlobalMember
from .serializers import PlayerBoardDetailSerializer, LiveGameRoomSerializer
from .utils import ClientError, get_room_or_error, user_count
from django.conf import settings
import requests
import... |
#!/usr/bin/env python
"""
Homogeneous Transformation Matrices
"""
import math
import numpy as np
# Local modules
import trifinger_mujoco.utils as tfu
def are_equal(T1, T2, rtol=1e-5, atol=1e-8):
"""
Returns True if two homogeneous transformation are equal within a tolerance.
Parameters
----------
... |
import os
import torch
import torch.nn.functional as F
from transformers import GPT2LMHeadModel, GPT2Tokenizer
from story.utils import cut_trailing_sentence, remove_profanity, logger
# warnings.filterwarnings("ignore")
MODEL_CLASSES = {
"gpt2": (GPT2LMHeadModel, GPT2Tokenizer),
}
def top_k_top_p_filtering(logit... |
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from transformers import AutoTokenizer
import torch
import util
def get_tokenizer():
"Need to add a few special tokens to the default longformer checkpoint."
tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-large-4096")... |
"""
@file
@brief Implements a class able to compute the predictions
from on an :epkg:`ONNX` model.
"""
from onnx import helper, shape_inference
from .onnx2py_helper import guess_proto_dtype
from .optim import onnx_remove_node_unused
def enumerate_model_node_outputs(model, add_node=False, order=False):
"""
Enu... |
# Copyright 2019 PerfKitBenchmarker 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... |
"""
Experiment to find order in synthetic data using an Evolution Strategy
"""
import numpy as np
import random
import pickle
import argparse
import os
from copy import copy
# Argument parser
parser = argparse.ArgumentParser()
parser.add_argument('--dir', type=str, required=True,
help="Base directory for experime... |
# converting numbers (number to different base number)
# encoding characters (char to number)
# decoding characters (number to char)
class ConvertingArrays(object):
"""dynamically set up a method to call conversions for arrays"""
def __init__(self):
super().__init__()
@staticmethod
def array... |
# Copyright 2017, IBM US, 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 to in writing... |
import pytest
from sidekick import Record, Maybe, Nothing, Union, Case, to_maybe, Ok, Err
from sidekick.types.union import SingletonMeta, SingletonMixin
UnionMeta = type(Union)
class TestCreateUnionType:
def test_case_constructor(self):
assert issubclass(Case("foo"), Record)
assert issubclass(Ca... |
import glob
import math
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
from pathlib import Path
import cv2
import numpy
import sys
# sys.path.append('.')
from kaggle_ndsb2017 import helpers
from kaggle_ndsb2017 import settings
from kaggle_ndsb2017 import step2_train_nodule_detector
from kaggle_ndsb2017.step1_pr... |
import numpy as np
import scipy as sp
import scipy.special
import numba
from function_generator import FunctionGenerator
@numba.njit
def __Iv(x, v, tol=1e-15, maxiter=1000):
"""
For large real x, we can write:
Iv(x) = e^x/sqrt(2*pi*x)*__Iv(x)
Where __Iv(x) is a power series in 1/x
I've tetsed v=0,... |
#!/usr/bin/env python
# coding: utf-8
# # Take Home Test Instructions
#
# You are being provided with a single compressed csv file with the following fields :
#
# - browser : the browser the campaign was provided on
# - visiting_time : the amount of time on the campaign site
# - total_amount_due : their account bala... |
__copyright__ = "Copyright (C) 2019 <NAME>"
__license__ = """
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, modif... |
import os
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from torchvision.utils import make_grid, save_image
from modules.RFRNet import RFRNet, VGG16FeatureExtractor
from utils.io import load_ckpt, save_ckpt
GOT_AMP = False
try:
print(... |
# Author: <EMAIL> (Any bug report is welcome)
# Time Created: Aug 2016
# Time Last Updated: Oct 2016
# Addr: Shenzhen, China
# Description: apply pk model to pubchem dataset, to screen potential active substrate(drugs)
from __future__ import absolute_import
from __future__ import division
from __future__ import print_... |
"""
Dialog classes.
"""
from __future__ import annotations
# standard libraries
import gettext
import time
import typing
# third party libraries
# none
# local libraries
from nion.ui import Window
from nion.ui import UserInterface
from nion.utils import Geometry
from nion.utils import Model
if typing.TYPE_CHEC... |
from flask import Flask
import pytest
from app.factory import create_app
from flask_sqlalchemy import SQLAlchemy
from app.app_config import DB_URL_TEST, SECRET_KEY
from app.db import db_config, _db
from app.celery_utils import make_celery
from celery import Celery
from utils import get_env_var
from app.utils import se... |
from collections import deque
from typing import Tuple
import cv2
import numpy as np
from . import poly, image, warp
class LaneDetector(object):
def __init__(self, minpix_poly:int=200, history:int=5):
self.minpix_poly = minpix_poly
self.history = history
self.reset()
def reset... |
"""
Python library for the VEML6030 sensor.
"""
from enum import IntEnum, IntFlag
ADDRESS = [0x48, 0x10]
SETTING_REG = 0x00
H_THRESH_REG = 0x01
L_THRESH_REG = 0x02
POWER_SAVE_REG = 0x03
AMBIENT_LIGHT_DATA_REG = 0x04
WHITE_LIGHT_DATA_REG = 0x05
INTERRUPT_REG = 0x06
class Gain(IntEnum):
x1 = 0b00 # 1x Gain
... |
from castile.builtins import BUILTINS
from castile.context import ScopedContext
from castile.types import (
Integer, String, Void, Boolean, Function, Union, Struct
)
class CastileTypeError(ValueError):
pass
class StructDefinition(object):
def __init__(self, name, field_names, content_types):
sel... |
#
# Copyright 2017 Mastercard
#
# 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,... |
import pandas as pd
import numpy as np
import time
import rdkit.Chem as Chem
import rdkit.Chem.AllChem as AllChem
from rdkit import DataStructs
from rdchiral.main import rdchiralReactants
from collections import defaultdict
import os
from joblib import Parallel, delayed
# Set up fingerprinting of molecules
getfp = lam... |
from __future__ import division
from math import radians, sin, cos
import util
class Triangle(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def box(self):
ax, ay, az = self.a
bx, by, bz = self.b
cx, cy, cz = self.c
x1 = min(min... |
"""
Deploy tasks
"""
from __future__ import with_statement
import os
from fabric.colors import red, green, yellow
from fabric.api import *
from fabric.contrib.console import confirm
from py_mina.config import fetch, ensure, set, check_config
from py_mina.state import state
from py_mina.echo import *
from py_mina.subta... |
#!/usr/bin/env python
# std-lib
import time
import unittest
import re
import random
from string import ascii_letters
# test harness
from unit_test_setup import generate_uuid
# test-harness
from setup_redis import (
hbom,
clear_redis_testdata,
default_redis_connection,
skip_if_redis_disabled,
)
clas... |
# -*- coding: utf-8 -*-
"""
Title
==============
Description.
"""
# import standard libraries
import os
import ctypes
# import third-party libraries
from sympy import symbols
import numpy as np
from multiprocessing import Pool, cpu_count, Array
import matplotlib.pyplot as plt
from colour import LUT3D, XYZ_to_RGB, L... |
import os
import numpy as np
import cv2
from collections import defaultdict
import hashlib
import glob
import configparser
from sixd_toolkit.params import dataset_params
from sixd_toolkit.pysixd import inout
from auto_pose.ae.pysixd_stuff import view_sampler
from auto_pose.ae import utils as u
import glob
def get_g... |
""" This file extracts the required information of a given file selecting only those
attributes important from the viewpoint of a malware researcher,using the PE library """
import pefile
import os
import array
import math
import csv, json
def get_entropy(data):
""" learn Entropy calculated across various sections ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 30 12:05:47 2020
@author: peter
"""
# a script to analyse the steps data.
import numpy as np
import pandas as pd
from pathlib import Path
import tifffile
import scipy.stats
import matplotlib.pyplot as plt
import scipy.ndimage as ndimage
import can... |
"""
Conversion utilities.
"""
# Author: <NAME>, <NAME>, <NAME>
# License: simplified BSD
import numpy as np
from sklearn.externals.joblib import Memory
from .cache_mixin import cache
from .niimg import (_safe_get_data, load_niimg, new_img_like,
short_repr)
from .compat import _basestring
def _c... |
import numpy as np
import cv2
from time import time
import sys
from cameras import cam2mat as cameraMatrix0
from cameras import cam2dcoef as distCoeffs0
from cameras import cam3mat as cameraMatrix1
from cameras import cam3dcoef as distCoeffs1
cameraMatrix0 = np.array(cameraMatrix0)
distCoeffs0 = np.array(distCoeffs0... |
#!/usr/bin/env python3
import datetime
import gzip
import os
import subprocess
import sys
import tempfile
from glob import glob
from pathlib import Path
import align as align
import mapping
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.SeqUtils import GC
from simplesam impo... |
import os
import time
import pytz
from datetime import datetime
from collections import OrderedDict
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.cuda.amp as amp
import tqdm
from setproctitle import setproctitle
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from... |
"""
Creates a HRNet Model as defined in:
<NAME>, <NAME>, <NAME> and <NAME>. (2019 CVPR).
Deep High-Resolution Representation Learning for Human Pose Estimation.
Copyright (c) <NAME>, 2019
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import lib.ops as ops
from lib.layers import BasicBlock, Bot... |
"""
Programmer: <NAME>
Purpose: Code for doing experiments on covers 1000 dataset
"""
import numpy as np
import sys
import os
import glob
import scipy.io as sio
import subprocess
import time
from sys import exit, argv
from multiprocessing import Pool as PPool
from CSMSSMTools import *
from BlockWindowFeatures import *
... |
"""Ancilarry."""
from typing import Any
from typing import List
from typing import Tuple
import geopandas as gpd
import requests
from dataretrieval import nwis
from shapely.geometry import LineString
from shapely.geometry import Point
from shapely.geometry import Polygon
from nldi_xstool.ExtADCPBathy import ExtADCPBa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.