text
stringlengths
3.07k
12.6k
"""Marshmallow (sorry, no Pydantic) validation config schemas.""" from marshmallow import ( INCLUDE, Schema, fields as f, validate as v, validates_schema, ) from hikcamerabot.config.schemas.validators import int_min_1, non_empty_str from hikcamerabot.constants import ( CMD_CAM_ID_REGEX, FF...
from __future__ import annotations import asyncio import collections from collections import defaultdict from contextlib import suppress from operator import attrgetter from typing import TYPE_CHECKING, DefaultDict, Deque, List, NamedTuple, Optional, Union import cachingutils.redis from bs4 import BeautifulSoup from...
################################################################################ # COPYRIGHT(c) 2018 STMicroelectronics # # # # Redistribution and use in source and binary forms, with or without ...
#! /usr/bin/env python3 """ This module defines functions to generate content for the site. It does not seem very elegant to generate the whole html "content" part with functions, so I will try to re-implement these funcions as bottle templates, and probably get rid of this file. """ import datetime from urllib.parse ...
import tensorflow as tf from typing import List, Tuple, Generator import logging from abc import ABC, abstractmethod logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) WIDTH = 224 HEIGHT = 224 NUM_CHANNELS = 3 class BaseLoader(ABC): def __init__(self, batch_size: int, prefetch_size: i...
import os import os.path as op import sys from typing import List from watchdog.events import FileSystemEvent from foremon.config import * from foremon.display import * from foremon.monitor import Monitor from foremon.task import ForemonTask, ScriptTask from foremon.util import guess_and_update_scripts, relative_if_c...
# Seleinum script to scrape station address (gu, dong) from urllib.request import urlopen from lxml import etree import urllib from retrying import retry import math import pandas as pd # Scrape station addresses from 나무위키 using lxml def scrape_address(): def find_gu_dong(station): base_url = 'https://na...
""" PDF Export logic for test reports via ReportLab. """ import os import uuid import warnings try: from urllib import pathname2url # Python 2.x except: from urllib.request import pathname2url # Python 3.x from schema import Schema, Or try: from reportlab.platypus import SimpleDocTemplate except Exc...
import machine import utime import random import _thread import sh1106 import micropython # Since there's multiple things that are logically grouped together, lets logically group them together. class SimonIO: def __init__(self, name, ledPin, buttonPin, buzzerFreq): self.name = name self.led = mach...
import socket import logging import sys import os import numpy as np import io from PIL import Image from termcolor import colored from datetime import datetime import shutil import math import tensorflow as tf import torch from torch.optim.lr_scheduler import _LRScheduler class CosineDecayLR(_LRScheduler): def __i...
import sys import time from multiprocessing import TimeoutError import pytest from orion.executor.base import AsyncException, ExecutorClosed, executor_factory from orion.executor.dask_backend import Dask from orion.executor.multiprocess_backend import PoolExecutor from orion.executor.single_backend import SingleExecu...
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # Reference: https://github.com/facebookresearch/music-translation/blob/master/src/wavenet.py import torch import torch.n...
# noqa: D100 # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup ------------------------------------------------------------------------ # I...
# Copyright 2018 The Feast 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
import re from marshmallow import fields, Schema, validate from marshmallow.utils import get_value, missing from six import iteritems, itervalues from .collection import ListDescriptor from .deletion import CASCADE, CLEAR, PROTECT from .exceptions import ImproperlyConfigured, ValidationError from .relationships impor...
import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.patches import Ellipse from sklearn.decomposition import PCA from sklearn.linear_model import LinearRegression plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] def drop_constant_column(df): return df.loc[:, (df != df.iloc...
#!/usr/bin/env python3 """Module containing the FixBackbone class and the command line interface.""" import argparse from biobb_common.generic.biobb_object import BiobbObject from biobb_common.configuration import settings from biobb_common.tools import file_utils as fu from biobb_common.tools.file_utils import launch...
import numpy as np import torch import base64 import torch.nn as nn from tqdm import tqdm from sklearn.metrics import f1_score from torch.utils.data import Dataset if torch.cuda.is_available(): device = torch.device("cuda:0") else: device = torch.device("cpu") class CdmcDataset(Dataset): def __init__(se...
import time import datetime import numpy as np import pandas as pd class elect_use_cost_tou: def __init__(self, rates): ''' 'use' is a Pandas DataFrame object. Must use column names "datetime" and "Value" rates is an instance of the class elect_rates ''' self.rates...
# Developed by <NAME>, <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 # # https://github.com/jtwwang/hanabi/blob/master/LICENSE # # Unless required by applicable law or agre...
from monopoly.consumers.message import build_roll_res_msg, build_game_end_msg, build_buy_land_msg, build_construct_msg, \ build_cancel_decision_msg, build_chat_msg from monopoly.consumers.util import games, rooms, decisions, readys from monopoly.core.game import Game from monopoly.core.land import LandType, Land, B...
#!/usr/bin/env python3 # encoding: utf-8 # @Time : 2018/9/28 下午12:13 # @Author : yuchangqian # @Contact : <EMAIL> # @File : init_func.py.py import math import torch import torch.nn as nn from seg_opr.conv_2_5d import Conv2_5D_depth, Conv2_5D_disp def __init_weight(feature, conv_init, norm_layer, bn_eps, bn_mom...
#!/usr/bin/python #----------------------------------------------------------------------------------------------------------------------------------------- # Script Description: # Functions to correct a trace for shear wave splitting back to original signal, pre anisotropic effects. # Input variables: # tr_N - The...
from .bounding_box import BoundingBox from .utils import * from typing import Callable, Iterator, Mapping, Sequence from os import PathLike from pathlib import Path from rich.table import Table from rich import print as rprint class Annotation: """ Bounding box annotations for one image. """ def __...
# standard library import datetime # 3rd party libraries # project libraries import core import translation class Policies(core.CoreDict): def __init__(self, manager=None): core.CoreDict.__init__(self) self.manager = manager self.log = self.manager.log if self.manager else None def get(self): ""...
import numpy as np from cv2 import cv2 import random import huffman import collections def zigzag(input): horizontal = 0 vertical = 0 vertical_max = input.shape[0] horizontal_max = input.shape[1] i = 0 output = np.zeros((vertical_max * horizontal_max)) while ((vertical ...
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz 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, merg...
import numpy as np import os import sys import tensorflow as tf import cv2 import imutils import time from sklearn.metrics import pairwise from imutils.video import FPS # sys.path.append('../../research') from utils import ops as utils_ops from utils import label_map_util from utils import visualization_utils as vis...
import math import torch.nn as nn __all__ = ['PreResNet', 'PreBasicBlock'] # ---------------------------Small Data Sets Like CIFAR-10 or CIFAR-100---------------------------- def conv1x1(in_plane, out_plane, stride=1): """ 1x1 convolutional layer """ return nn.Conv2d(in_plane, out_plan...
try: from setuptools import setup except ImportError: from distutils.core import setup from distutils.command.build_py import build_py import glob import os import platform import subprocess from pathlib import Path from shutil import copyfile import sys class FetchDependencies(build_py): """ A command...
# Copyright (c) 2020-2021 The MMSegmentation Authors # SPDX-License-Identifier: Apache-2.0 # # Copyright (C) 2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # import random import warnings import numpy as np import torch from mmcv.runner import HOOKS, build_optimizer, build_runner from mmcv.utils import ...
import seaborn as sns from matplotlib import pyplot as plt import math import warnings def plotter(f): def plotter_function(*args, figsize=(12, 12), title=None, title_y=1.03, tight_layout=True, **kwargs): plt.figure(figsize=figsize, tight_layout=tight_layout) f(*args, **kwargs) figure = plt.gc...
import os from statistics import mean import requests from dotenv import load_dotenv from terminaltables import AsciiTable def predict_salary(salary_from, salary_to): if salary_from and salary_to: expected_salary = mean([salary_from, salary_to]) elif salary_from and not salary_to: expected_sa...
import numpy as np from numpy.testing.utils import assert_equal from nose import with_setup from nose.plugins.attrib import attr from brian2 import * from brian2.devices.device import restore_device @attr('codegen-independent') def test_timedarray_direct_use(): ta = TimedArray(np.linspace(0, 10, 11), 1*ms) as...
from functools import partial import numpy as np import chainer import chainer.functions as F import chainer.links as L import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from common.utils import backward_var_iter_nodup def add(a,b): return a+b def named(name, var): ...
# fat.py; ad-hoc fat16 reader # by <NAME> <<EMAIL>> # # references: # http://en.wikipedia.org/wiki/File_Allocation_Table # http://www.ecma-international.org/publications/standards/Ecma-107.htm # # example: # with open("/dev/sdc1") as file: # fs = FatFs(file) # for rootdir in fs: # pr...
"""Does object detection and segmentation on images.""" import os import threading import cv2 import numpy as np import tensorflow.compat.v1 as tf from google.protobuf import text_format tf.disable_eager_execution() import util_io from object_detection.builders import image_resizer_builder from object_detection.infe...
# # Copyright (C) 2008 The Android Open Source Project # # 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 la...
import cv2 import numpy as np import time from threading import Thread try: import pygame from pygame.locals import K_BACKSPACE from pygame.locals import K_COMMA from pygame.locals import K_DOWN from pygame.locals import K_ESCAPE from pygame.locals import K_F1 from pygame.locals import K_LE...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Script for plotting 1D DG FEM data stored in VTK files """ import glob import matplotlib matplotlib.use('Qt5Agg') import matplotlib.pyplot as plt import argparse from os.path import join as pjoin import os import sys from glob import glob from sfepy.discrete.dg.dg_1D...
from abc import ABCMeta, abstractmethod, abstractproperty from operator import itemgetter from .experiment import Experiment, DefaultExperiment from .ops.random import Sample, FastSample, RandomInteger from .assignment import Assignment # decorator for methods that assume assignments have been made def requires_exp...
import base64 from datetime import datetime from datetime import timedelta import json import logging import os import random import time import urllib2 import creds from models import Session from models import User from api.error import BTError import api.error as error import api.phone as phone #import api.apple_a...
import os import uuid import logging import predix.admin.cf.api import predix.admin.cf.orgs import predix.admin.cf.apps import predix.admin.cf.services def create_temp_space(): """ Create a new temporary cloud foundry space for a project. """ # Truncating uuid to just take final 12 characters sin...
# -*- coding: utf-8 -*- """ All possible ply lamination parameters """ __version__ = '1.0' __author__ = '<NAME>' import sys import numpy as np sys.path.append(r'C:\BELLA') from src.CLA.lampam_functions import calc_delta_lampam_mp_3 from src.CLA.lampam_functions import calc_delta_lampam def calc_delta_l...
import hsm class test_hsm(hsm.Statemachine): ''' This is a sample Statemachine as in figure 6.2 on page 170 in 'Practical Statecharts in C/C++', ISBN 1-57820-110-1. ''' def __init__(self): super().__init__() self.foo = False def state_0(self, objSignal): 'This is State "0"!' if objSign...
# Copyright 2016 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...
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Natural language API. .. info: Acknowledgments go to `z0mbiehunt3r <https://twitter.com/z0mbiehunt3r>`_ for his ideas and help. `Check out his blog <http://blog.alejandronolla.com/2013/05/15/detecting-text-language-with-python-and-nltk/>`_ to know where this modu...
from email.message import EmailMessage from django.conf.global_settings import DEFAULT_FROM_EMAIL from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserCreationForm from django.db.models import Q from django.http import Http404, HttpResponse from django.shortcuts import re...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. """ Userbot module containing userid, chatid and log commands""" from asyncio import sleep from userbot import BOTLOG, ...
import os import json from argparse import Namespace import onmt from onmt.utils.logging import init_logger from onmt.utils.misc import split_corpus from onmt.translate.translator import build_translator from onmt.translate.translator import Translator import onmt.opts as opts from onmt.utils.parse import ArgumentPars...
import json from http import HTTPStatus from logging import getLogger from pyhap.accessory import Accessories from pyhap.config import ( ControllerPermission, HAPStatusCode, ) from pyhap.http_server import ( Request, Response, encrypted, ) from pyhap.pair import ( add_pairing, exchange, ...
import os import argparse import time from multiprocessing import cpu_count, Pool import gzip import traceback import chainer import numpy as np from scipy.misc import imresize import gym import imageio from lib.utils import log, mkdir, pre_process_image_tensor, post_process_image_tensor from lib.constants import DO...
# Copyright 2015-2016 Yelp 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 writin...
from __future__ import annotations import datetime import zoneinfo from typing import Any, Generic, Optional, TYPE_CHECKING, TypeVar import aiohttp import parsedatetime import discord from discord.ext import commands from jishaku.codeblocks import codeblock_converter, Codeblock from jishaku.modules import Extensio...
import time import math import torch.autograd import torch.nn as nn import dcp.utils as utils class View(nn.Module): """ Reshape data from 4 dimension to 2 dimension """ def forward(self, x): assert x.dim() == 2 or x.dim() == 4, "invalid dimension of input {:d}".format(x.dim(...
import requests, requests.utils import time, re import pdb class PyMsCognitiveException(Exception): pass class PyMsCognitiveSearch(object): """ Shell class for the individual searches """ def __init__(self, api_key, query, query_url, safe=False): self.api_key = api_key self.safe = ...
# Copyright 2012 Nebula, Inc. # Copyright 2013 IBM Corp. # # 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...
"""Ground motion selection functionality for simulations based on the following papers: - Bradley, <NAME>. "A generalized conditional intensity measure approach and holistic ground‐motion selection." Earthquake Engineering & Structural Dynamics 39.12 (2010): 1321-1342. - Bradley, <NAME>. "A ground motion selection algo...
import os import datetime import numpy as np import gym import tensorflow as tf from tensorflow.keras.models import Sequential, clone_model from tensorflow.keras.layers import Dense from tensorflow.keras.optimizers import Adam from tensorflow.summary import create_file_writer from cpprb import ReplayBuffer, Priori...
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
import torch import torch.nn as nn import torchvision.transforms as T from models import SequentialFlow, Flow, CouplingLayer, ActNormImage from utils import get_mask SCALE_L2_REG_COEFF = 5e-5 MAX_GRAD_NORM = 100. class RealNVP(): def __init__(self, image_shape, hidden_channels, num_resnet, lr, device): a...
import hmac import hashlib import base64 import json import jwt import requests import uuid import datetime import pkg_resources from pkg_resources import DistributionNotFound from types import ModuleType from .constants import URL, HTTP_STATUS_CODE, ERROR_CODE from . import resources from .errors import ServerErr...
""" This package holds communication aspects """ import binascii import json import logging import socket import traceback from abc import abstractmethod from binascii import unhexlify from threading import Thread from pylgbst.messages import MsgHubAction from pylgbst.utilities import str2hex log = logging.getLogger(...
import math import torch from torch.nn import Parameter import torch.nn.functional as F import torch.optim as optim from sklearn.linear_model import LogisticRegression from torch_geometric.nn import GCNConv from deeprobust.graph import utils from copy import deepcopy def uniform(size, tensor): if tensor is not...
import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import griddata #from matplotlib.mlab import griddata import scipy.special as spc np.cosd = lambda x : np.cos( np.deg2rad(x) ) np.acosd = lambda x : np.arccos( np.deg2rad(x) ) np.sind = lambda x : np.sin( np.deg2rad(x) ) np.asind = lambda x : n...
import time import os import re import sys import click from examples.NIPS.ActivityDetection.prob_ec_testing import test from examples.NIPS.MNIST.mnist import MNIST_Net, test_MNIST from examples.NIPS.MNIST.mnist import neural_predicate as default_neural_predicate sys.path.append('../../../') from train import train...
# Copyright (c) 2017 Cable Television Laboratories, Inc. ("CableLabs") # and others. 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://w...
import keras import cv2 import numpy as np import argparse from glob import glob import matplotlib.pyplot as plt # GPU config import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf from keras import backend as K config = tf.ConfigProto() config.gpu_options.allow_growth = True config.gpu_options.vis...
import configuration import data import discord import re intents = discord.Intents.default() intents.members = True client = discord.Client(intents=intents) database = data.Client() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(me...
# -*- coding: utf-8 -*- # 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, softw...
#The MIT License (MIT) #Copyright (c) 2014 Microsoft Corporation #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, modi...
# Copyright (c) 2018, The Regents of the University of California # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, thi...
import numpy as np from joblib import Parallel, delayed from .multi_sample_split import aggregate_medians, aggregate_quantiles from .clustered_inference import clustered_inference def _ensembling(list_beta_hat, list_pval, list_pval_corr, list_one_minus_pval, list_one_minus_pval_corr, method='quantile...
import os import torch from tqdm import tqdm import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import classification_report, confusion_matrix import itertools def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): if normalize: cm = cm....
# -*- coding: utf-8 -*- from time import time from datetime import timedelta import logging from argparse import ArgumentParser from struct import unpack import zmq from zmq.eventloop.ioloop import IOLoop from zmq.eventloop.zmqstream import ZMQStream from distributed_frontera.settings import Settings from socket_con...
#!/usr/bin/python import gringo import urwid import sys class Plan: def __init__(self, field, stone, target, move): mx = min([x for (x, y) in field]) my = min([y for (x, y) in field]) self.width = max([x for (x, y) in field]) - mx + 1 self.height = max([y for...
# -*- coding: utf-8 -*- # from __future__ import print_function import numpy import pytest import sympy import orthopy import quadpy from quadpy.quadrilateral import Product from helpers import check_degree_ortho def _integrate_exact(f, quadrilateral): xi = sympy.DeferredVector("xi") pxi = ( quadri...
import torchvision import os import utils.DataTools as dt aug_train = torchvision.transforms.Compose([ torchvision.transforms.Resize(256), torchvision.transforms.RandomCrop(224), torchvision.transforms.RandomHorizontalFlip(), torchvision.transforms.ToTensor(), torchvision.transforms.Normal...
from django import http from django.contrib.auth import mixins from django.contrib.auth import views as auth_views from django.views import generic from main import forms, error_codes, dal, models from main import statics from datetime import datetime from django.urls import resolve # Create your views here. # 用户登录 c...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2020-2021 Alibaba Group Holding Limited. # # 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/LI...
# -*- coding: utf-8 -*- # MIT license # # Copyright (c) 2020-2021 <NAME> # Copyright (c) 2020-2021 Instituto Nacional de Tecnología Industrial # # 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 Softwa...
from __future__ import unicode_literals from datetime import datetime from typing import Callable from django.contrib.auth import get_user_model from django.db import models from django.db.models.manager import BaseManager from django.urls import reverse, reverse_lazy from django.utils import timezone from positions ...
# This implements the "diagnose-nsstring" command, usually installed in the debug session like # command script import lldb.diagnose # it is used when NSString summary formatter fails to replicate the logic that went into LLDB making the # decisions it did and providing some useful context information that can # be ...
# -*- coding: utf-8 -*- import bs #Created By MythB # http://github.com/MythB from bsSpaz import * import bsSpaz import bsUtils import random import bsInternal import MythBAdminList as mbal class PermissionEffect(object): def __init__(self,position = (0,1,0),owner = None,prefix ...
# -*- coding: utf-8 -*- """BadgrLite module for automating Badr awards (assertions)""" # pylint: disable=R1710 # pylint: disable=R1710 import json import os import requests from requests.models import Response from badgr_lite import exceptions from .helpers import pythonic, to_datetime class Badge: """Python...
from typing import Optional, List, Union, Set, Dict, Sequence, Any, Tuple from numbers import Real import itertools import numbers import sympy import numpy as np from qupulse.utils.sympy import IndexedBroadcast from qupulse.utils.types import ChannelID from qupulse.expressions import Expression, ExpressionScalar fro...
from collections import OrderedDict import numpy as np import megengine.functional as F import megengine.module as M from megengine import Tensor from megengine.core._imperative_rt.core2 import apply from megengine.core.ops import builtin from megengine.module import Module from megengine.traced_module import TracedM...
# Copyright 2018 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from google.appengine.ext import ndb from gae_libs import dashboard_util from gae_libs.handlers.base_handler import BaseHandler from gae_libs.handlers.base_...
from __future__ import print_function import h5py import sys import numpy as np class NanoporeModel(object): def __init__(self, fast5File): self.fastFive = h5py.File(fast5File, "r") self.stay_prob = 0 self.skip_prob_bins = [] self.model_name = '' self.model = None def ...
import tweepy import pandas as pd from langdetect import detect from .sentiment import analyse_per_language from .datahandler import DataHandler import gc class GlobalStreamListener(tweepy.StreamListener): """ Twitter listener. collects tweets and stores it to a data-handler """ def __init__(self, lan...
#!/usr/bin/env python3 ''' Author: AGDC Services Website: AGDCservices.com Date: 20210501 This is a Command and Control(C2) server simulator for TCP traffic Usage: - Fill in the variables at the top of main - write your custom C2 code in the "Start of C2 Simulation Code" section in main a...
# coding: utf8 # Author: <NAME> # Date: 03/2013 from unittest import TestCase TestCase.maxDiff = None """ Base class for Nikola test cases """ __all__ = ["BaseTestCase", "cd", "LocaleSupportInTesting"] import os import sys from contextlib import contextmanager import locale import unittest import logbook imp...
#!/usr/bin/python3 -B import platform from collections import OrderedDict from subprocess import Popen, PIPE, TimeoutExpired # get OS related information def platform_info(): distro = platform.linux_distribution() return(distro) # get DGX platform related information def dgx_info(): dgx = {} with ope...
import numpy as np import cv2 import torch import torchvision.transforms as transforms def skew(x): return np.array([[0, -x[2], x[1]], [x[2], 0, -x[0]], [-x[1], x[0], 0]]) def compute_fundamental_from_poses(K_src, K_dst, T_src, T_dst): T_src2dst = T_dst.dot(np.linalg.inv(T_src)) R = T_src2dst[:3, :3] ...
import logging import os from typing import Any, Dict, List, Optional, Tuple import joblib import numpy as np import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import scipy.sparse as ss from gleams.feature import encoder, spectrum from gleams.ms_io import ms_io logger = logging.getLogger('gleams...
# Module for caculate view and scene graph similarity scores \in (0,1) import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Wedge from termcolor import colored from matplotlib.collections import PatchCollection from numpy import matlib as mb from lib.params import * # color map and setting...
"""CAS login/logout replacement views""" import sys import types from six.moves import urllib_parse from django.conf import settings from django.http import HttpResponseRedirect from django.core.exceptions import PermissionDenied from django.http import HttpResponse from django.utils import timezone from django.vi...
from sumpy.annotators._annotator_base import _AnnotatorBase from sumpy.annotators import SentenceTokenizerMixin, WordTokenizerMixin from sumpy.document import Summary from abc import ABCMeta, abstractmethod import pandas as pd import numpy as np import networkx as nx class _SystemBase(object): """Abstract base cla...
#!/usr/bin/env python3 import zmq import os import subprocess import time import io from numpy import * # genfromtxt, array import sys sys.path.append('../src/master') import control_pb2 FMUS_DIR = '../build/umit-fmus' if not 'FMUS_DIR' in os.environ else os.environ['FMUS_DIR'] fmu = os.path.join(FMUS_DIR, 'tests/type...