text
stringlengths
3.07k
12.6k
from helpers import poseRt from frame import Frame import time import numpy as np import g2o import json LOCAL_WINDOW = 20 #LOCAL_WINDOW = None class Point(object): # A Point is a 3-D point in the world # Each Point is observed in multiple Frames def __init__(self, mapp, loc, color, tid=None): self.pt = np...
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from utils.parse_config import * from utils.utils import build_targets, to_cpu, non_max_suppression import matplotlib.pyplot as plt import matplotlib.patches as pa...
#!/usr/bin/env python3 # Copyright 2019, <NAME> <<EMAIL>>, <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause # Reads ms task measurement results from CSV files. # # If the path to the results is not given it is read from the following environment variables: # * SCHED_MSRESULTS # * SCHED_RESULTS and SCHED_HOST...
from flask import Flask, render_template, request, redirect, url_for import tensorflow as tf from keras.models import load_model from keras.backend import set_session from src.utils import image_preprocessing from src.utils import overall_class_label from src.utils import infinite_scraper # sessions and default graphs...
import torch import torch.nn as nn from torchvision import models import torch.nn.functional as F def model_parser(model, sum_mode=False, dropout_rate=0.0, bayesian=False): base_model = None if model == 'Resnet': base_model = models.resnet34(pretrained=True) network = HourglassNet(base_model, ...
"""MongoDB IO tasks.""" import logging from typing import List, Optional, Sequence from urllib.parse import urlparse import attr from icecream import ic # noqa pylint: disable=unused-import from pymongo import MongoClient from pymongo.errors import ServerSelectionTimeoutError import voluptuous as vol from dataplaybo...
from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from django.template.defaultfilters import slugify, linebreaks, date, truncatechars from wagtail.core.models import Page from wagtail.core.rich_text import RichText from migration.models import * from accounts.models im...
import os import errno import stat import logging from io import BytesIO from time import time, mktime, strptime from fuse import FuseOSError, Operations, LoggingMixIn logger = logging.getLogger('dochub_fs') def wrap_errno(func): """ @brief Transform Exceptions happening inside func into meaningful ...
import os import signal import atexit import json import time from pathlib import Path import subprocess import argparse import pprint from distutils.util import strtobool children_pid = [] @atexit.register def kill_child(): for child_pid in children_pid: os.kill(child_pid, signal.SIGTERM) cmd_parser = ...
"""Tools for working with Cryptopunk NFTs; this includes utilities for data analysis and image preparation for training machine learning models using Cryptopunks as training data. Functions: get_punk(id) pixel_to_img(pixel_str, dim) flatten(img) unflatten(img) sort_dict_by_function_of_value(d, f) ...
from __future__ import print_function import pylab as plt import numpy as np from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest, QueryDict from django.shortcuts import render_to_response, get_object_or_404, redirect, render from django.template import Context, RequestContext, loader fr...
# included from libs/mincostflow.py """ Min Cost Flow """ # derived: https://atcoder.jp/contests/practice2/submissions/16726003 from heapq import heappush, heappop class MinCostFlow(): def __init__(self, n): self.n = n self.graph = [[] for _ in range(n)] self.pos = [] def add_edge(s...
# Copyright (c) 2019 Works Applications 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 a...
import itertools import math import pprint import sys import typing import map_funcs GOOGLE_EARTH_AIRPORT_IMAGES = { 'GoogleEarth_AirportCamera_C.jpg' : { 'path': 'video_images/GoogleEarth_AirportCamera_C.jpg', 'width': 4800, 'height': 3011, # Originally measured on the 100m legend...
#!/usr/bin/env python3 # (c) 2021 <NAME> from abc import ABC, abstractmethod from enum import Enum from os import linesep from twisted.internet import reactor from twisted.internet.error import ConnectionDone from twisted.internet.protocol import Factory, Protocol from twisted.logger import Logger from twisted.protoc...
# utils for graphs of the networkx library import copy import networkx as nx from networkx.algorithms.shortest_paths import shortest_path from typing import Any, Union, Optional, Iterator, Iterable, Tuple, Dict, List, cast LEFT = 0 RIGHT = 1 def top_nodes(graph: nx.Graph, data: bool = False) -> Union[I...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # import json from pathlib import Path import pytest import cc_net import cc_net.minify as minify from cc_net import jsonql, process_wet_fil...
""" This module contains a pytorch dataset for learning peptide embeddings. In particular, each "instance" of the dataset comprises two peptide sequences, as well as the sNebula similarity between them. The sNebula distance reflects the BLOSSUM similarity transformed from 0 to 1. """ import logging logger = logging.ge...
# type: ignore # This is a small script to parse the header files from wasmtime and generate # appropriate function definitions in Python for each exported function. This # also reflects types into Python with `ctypes`. While there's at least one # other generate that does this already it seemed to not quite fit our p...
''' Name: color_segmentation.py Version: 1.0 Summary: Extract plant traits (leaf area, width, height, ) by paralell processing Author: <NAME> Author-email: <EMAIL> Created: 2018-09-29 USAGE: python3 color_kmeans_vis.py -p /home/suxingliu/plant-image-analysis/sample_test/ -i 01.jpg -m 01_seg.jpg -c 5 ''' ...
""" A module for calculating the relationship (or distance) between 2 strings. Namely: - edit_distance() - needleman_wunsch() - align() - coverage() """ from typing import Callable, Tuple, List from enum import IntEnum from operator import itemgetter from functools import lru_cache import unittest cl...
def elastic_rate( hv, hs, v, s, rho, mu, nx, dx, order, t, y, r0, r1, tau0_1, tau0_2, tauN_1, tauN_2, type_0, forcing, ): # we compute rates that will be used for Runge-Kutta time-stepping # import first_derivative_sbp_operators ...
import copy import _mecab from collections import namedtuple from typing import Generator from mecab import MeCabError from domain.mecab_domain import MecabWordFeature def delete_pattern_from_string(string, pattern, index, nofail=False): """ 문자열에서 패턴을 찾아서 *로 변환해주는 기능 """ # raise an error if index is outsid...
"""Tests for IPython.utils.path.py""" # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from contextlib import contextmanager from unittest.mock import patch import pytest from IPython.lib import latextools from IPython.testing.decorators import ( onlyif_cmds_ex...
#!/usr/bin/env python3 from flask import Flask, send_file, make_response, Response, g, request, stream_with_context from io import BytesIO import atexit import errno import os import subprocess import threading INPUT = '/dev/video0' FFMPEG = "/home/test/ffmpeg-nvenc/ffmpeg" app = Flask(__name__) @app.route('/pic') ...
"""DNS Authenticator for deSEC.""" import json import logging import time import requests import zope.interface from certbot import errors from certbot import interfaces from certbot.plugins import dns_common logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) @zope.interface.implementer(interfaces....
import random import socket import time class client: def __init__(self, name, address, socket, color): self.name = name self.address = address self.socket = socket self.color = color sep = '\n' def dice_roll(): return (str(random.randint(1, 6)) + ',' + str(random.randint(1...
import pandas as pd from tensorflow import keras, reduce_sum, ragged, function, math, nn, reduce_mean from os import environ class MaskedEmbeddingsAggregatorLayer(keras.layers.Layer): def __init__(self, agg_mode='sum', **kwargs): super(MaskedEmbeddingsAggregatorLayer, self).__init__(**kwargs) if ...
# -*- coding: utf-8 -*- """ Spyder Editor Code written by <NAME> with modifications by <NAME> and <NAME> This file produces plots comparing our first order sensitivity with BS vega. """ # %% # To run the stuff, you need the package plotly in your anaconda "conda install plotly" import plotly.graph_objs as go from...
from typing import Iterable, Optional from django import VERSION from django.db.models.base import Model from django.db.models.fields.related import ManyToManyField from django.db.models.fields.reverse_related import ManyToOneRel from django.db.models.manager import Manager from django.db.models.query import QuerySet ...
'''Functions and classes to wrap existing classes. Provides a wrapper metaclass and also a function that returns a wrapped class. The function is more flexible as a metaclass has multiple inheritence limitations. A wrapper metaclass for building wrapper objects. It is instantiated by specifying a class to be to be wra...
from typing import List, Optional, Sequence, Union from abc import abstractmethod, ABC from copy import deepcopy from sys import _getframe as get_stack from frozen_box.exception import FrozenException, FrozenKeyError, FrozenValueError QueryableItem = Union[str, int, slice] Queryable = Union[QueryableItem, Sequence[Qu...
# Copyright 2021 AI Redefined Inc. <<EMAIL>> # # 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 ...
#! /usr/bin/env -S python3 -u import os, shutil, sys, glob, traceback from easyterm import * help_msg="""This program downloads one specific NCBI assembly, executes certains operations, then cleans up data ### Input/Output: -a genome NCBI accession -o folder to download to ### Actions: -c bash command ...
r""" Super modules """ #***************************************************************************** # Copyright (C) 2015 <NAME> <tscrim at ucdavis.edu> # # Distributed under the terms of the GNU General Public License (GPL) # http://www.gnu.org/licenses/ #*******************************************...
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
#!/usr/bin/env python # coding: utf-8 # vim: set ts=4 sw=4 expandtab sts=4: # Copyright (c) 2011-2013 <NAME> & contributors # # 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 restricti...
import os import random from tqdm import tqdm from collections import defaultdict from data_genie.data_genie_config import * from data_genie.data_genie_utils import TRAINING_DATA_PATH, CACHED_KENDALL_TAU_PATH, load_obj, save_obj from data_genie.data_genie_utils import count_performance_retained, get_best_results from...
import pytest import torch from packaging.version import parse as V from torch_complex import ComplexTensor from espnet2.enh.layers.complex_utils import is_complex from espnet2.enh.separator.dc_crn_separator import DC_CRNSeparator is_torch_1_9_plus = V(torch.__version__) >= V("1.9.0") @pytest.mark.parametrize("inpu...
import os import random import argparse import multiprocessing import numpy as np import torch from torchvision import models, transforms from torch.utils.data import DataLoader, Dataset from pathlib import Path from PIL import Image from utils import Bar, config, mkdir_p, AverageMeter from datetime import datetime fro...
"""Simple Bot to reply to Telegram messages. This is built on the API wrapper, see echobot2.py to see the same example built on the telegram.ext bot framework. This program is dedicated to the public domain under the CC0 license. """ import logging import telegram import requests, json import traceback from time import...
import cv2 import numpy as np def hex_to_bgr(hx): hx = hx.lstrip('#') return tuple(int(hx[i:i + 2], 16) for i in (0, 2, 4))[::-1] class Rectangle: def __init__(self, x, y, width, height, max_height, min_db, max_db, color, thickness, reverse): self.rev = -1 if reverse else 1 self.x = x ...
import xml.etree.ElementTree as ElementTree import os class CARISObject: """A generic CARIS object with a name""" def __init__(self): """Initialize with empty name""" self.name = '' def __init__(self, name): """Initialize with a name provided""" self.name = name def ...
### based on https://github.com/kylemcdonald/Parametric-t-SNE/blob/master/Parametric%20t-SNE%20(Keras).ipynb import numpy as np from tensorflow.keras import backend as K from tensorflow.keras.losses import categorical_crossentropy from tqdm.autonotebook import tqdm import tensorflow as tf def Hbeta(D, beta): ""...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import ipdb import time # Clustering penalties class ClusterLoss(torch.nn.Module): """ Cluster loss comes from the SuBiC paper and consists of two losses. First is the Mean Entropy Loss which makes the output to be clos...
import logging from datetime import timedelta from flask import Flask, render_template, redirect, request, url_for, flash from flask_login import LoginManager, login_user, logout_user, current_user from preston.crest import Preston as CREST from preston.xmlapi import Preston as XMLAPI from auth.shared import db, evea...
#!/usr/bin/python2.6 #-*- coding: utf-8 -*- import signal import subprocess from glob import glob from os import listdir from os.path import basename, dirname label = 'CentOS_6.9_Final' def listifaces(): ethernet = [] for iface in listdir('/sys/class/net/'): if iface != 'lo': ethernet.app...
# MIT License # # Copyright (c) 2020 <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, publi...
#!/usr/bin/env python # -*- coding: utf-8 -*- import string from collections import Counter import numpy as np import theano import theano.tensor as T punctuation = set(string.punctuation) punctuation.add('\n') punctuation.add('\t') punctuation.add(u'’') punctuation.add(u'‘') punctuation.add(u'“') punctuation.add(u'”...
#!/usr/bin/env python3 #=============================================================================== # Copyright (c) 2020 <NAME> # Lab of Dr. <NAME> and Dr. <NAME> # University of Michigan #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation f...
import pandas as pd import pandas import numpy as np #provide local path testfile='../input/test.csv' data = open(testfile).readlines() sequences={} #(key, value) = (id , sequence) for i in range(1,len(data)): line=data[i] line =line.replace('"','') line = line[:-1].split(',') id = int(...
"""IntegerHeap.py Priority queues of integer keys based on van Emde Boas trees. Only the keys are stored; caller is responsible for keeping track of any data associated with the keys in a separate dictionary. We use a version of vEB trees in which all accesses to subtrees are performed indirectly through a hash table...
""" Tests the DQM Server class """ import json import os import threading import pytest import requests import qcfractal.interface as ptl from qcfractal import FractalServer, FractalSnowflake, FractalSnowflakeHandler from qcfractal.testing import ( await_true, find_open_port, pristine_loop, test_serv...
from collections import namedtuple import json, logging, socket, re, struct, time from typing import Tuple, Iterator from urllib.parse import urlparse, parse_qs from backend import Backend, Change from protocol import PacketType, recvall, PKT_CHANGE_TYPES, change_from_packet, packet_from_change, send_packet, recv_pack...
# Noysim -- Noise simulation tools for Aimsun. # Copyright (c) 2010-2011 by <NAME>, Ghent University & Griffith University. # # Basic geometry functions and classes import numpy import pylab EPSILON = 10e-12 # smallest difference for points/directions #--------------------------------------------------...
import pytest import yaml from nequip.utils import instantiate simple_default = {"b": 1, "d": 31} class SimpleExample: def __init__(self, a, b=simple_default["b"], d=simple_default["d"]): self.a = a self.b = b self.d = d nested_default = {"d": 37} class NestedExample: def __init...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Based on storm.py module from https://github.com/nathanmarz/storm/blob/master/storm-core/src/multilang/py/storm.py, and the examples from https://github.com/apache/incubator-storm/blob/master/examples/storm-starter/multilang/resources/splitsentence.py and http://storm....
from sqlalchemy import Column, Integer, String, Float, ForeignKey from sqlalchemy.engine.create import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker CONNECTION_STRING = "sqlite+pysqlite:///data/db.sqlite" engine = create_engine(CONNECTION_STRING) Sess...
import numpy as np import matplotlib.pyplot as plt import os from pyburst.grids import grid_analyser, grid_strings, grid_tools # resolution tests y_factors = {'dt': 3600, 'fluence': 1e39, 'peak': 1e38, } y_labels = {'dt': '$\Delta t$', 'rate': 'Burst rate', ...
#!/usr/bin/env python3 import torrent_parser as tp import asyncio import contextlib import pathlib import argparse import pprint import hashlib import concurrent.futures import os.path import logging import tqdm class TorrentChecker(object): def __init__(self, datadir=pathlib.Path('.'), data_file_globs=["**"], ...
import jittor as jt from jittor import nn from jittor import Module from jittor import init from jittor.contrib import concat from model.backbone import resnet50, resnet101 from model.backbone import res2net101 Backbone_List = ['resnet50', 'resnet101', 'res2net101'] class DeepLab(Module): def __init__(self, outp...
""" LCCS Level 3 Classification | Class name | Code | Numeric code | |----------------------------------|-----|-----| | Cultivated Terrestrial Vegetated | A11 | 111 | | Natural Terrestrial Vegetated | A12 | 112 | | Cultivated Aquatic Vegetated | A23 | 123 | | Natural Aquatic Vegetated | A24 | 124 | | Art...
import logging from abc import ABC, abstractmethod from file_read_backwards import FileReadBackwards import threading import os class Logger(ABC): def __init__(self,filename): self.lock = threading.Lock() self.dir = "Logs" if(not os.path.isdir(self.dir)): os.mkdir(self.dir) ...
import re import sys import os # Lists of same characters alpha_equiv = ['Α','Ά','ά','ὰ','ά','ἀ','ἁ','ἂ','ἃ','ἄ','ἅ','ἆ','ἇ','Ἀ','Ἁ','Ἂ','Ἃ','Ἄ','Ἅ','Ἆ','Ἇ','ᾶ','Ᾰ','Ᾱ','Ὰ','Ά','ᾰ','ᾱ'] #Converts to α alpha_subscripted = ['ᾀ','ᾁ','ᾂ','ᾃ','ᾄ','ᾅ','ᾆ','ᾇ','ᾈ','ᾉ','ᾊ','ᾋ','ᾌ','ᾍ','ᾎ','ᾏ','ᾲ','ᾴ','ᾷ','ᾼ','ᾳ'] #Converts to...
def get_lorawan_maximum_payload_size(dr): mac_payload_size_dic = {'0':59, '1':59, '2':59, '3':123, '4':230, '5':230, '6':230} fhdr_size = 7 #in bytes. Assuming that FOpts length is zero fport_size = 1 #in bytes frm_payload_size = mac_payload_size_dic.get(str(dr)) - fhdr_size - fport_size ret...
import common import student_code import array class bcolors: RED = "\x1b[31m" GREEN = "\x1b[32m" NORMAL = "\x1b[0m" def read_data(training_data, test_data1, gold_data1, filename): data = array.array('f') test = array.array('f') with open(filename, 'rb') as fd: data....
from bottle import request, response, HTTPResponse import os, datetime, re import json as JSON import jwt class auth: def gettoken(mypass): secret = str(os.getenv('API_SCRT', '!@ws4RT4ws212@#%')) password = str(os.getenv('API_PASS', 'password')) if mypass == password: ...
import pandas as pd import numpy as np import math import matplotlib.pyplot as plt from sklearn import feature_selection as fs from sklearn import naive_bayes from sklearn import model_selection from sklearn import metrics from sklearn import linear_model from sklearn import svm from imblearn.under_sampling import Ne...
# -*- coding: utf-8 -*- """ Created on Sun Jul 4 17:01:28 2021 @author: fahim """ from keras.models import Model from keras.layers import Input, Add, Activation, ZeroPadding2D, BatchNormalization, Conv2D, AveragePooling2D, MaxPooling2D from keras.initializers import glorot_uniform def identity_block(X, f, filters, ...
from datetime import datetime import timebomb.models as models def test_Notification(): notif = models.Notification("message") assert notif.content == "message" assert notif.read is False assert str(notif) == "message" def test_Player(): player = models.Player("name", "id") assert player....
"""An extension for workspace rules.""" load("@bazel_skylib//lib:paths.bzl", "paths") load("//:dependencies.bzl", "dependencies") def _workspace_dependencies_impl(ctx): platform = ctx.os.name if ctx.os.name != "mac os x" else "darwin" for dependency in dependencies: ctx.download( executabl...
import bybit import math import pandas as pd import time from datetime import datetime from dateutil.relativedelta import relativedelta # settings num_orders = 3 order_size = 1 order_distance = 10 sl_risk = 0.03 tp_distance = 5 api_key = "YOUR_KEY" api_secret = "YOUR_SECRET" client = bybit.bybit(test=False, api_key=...
from __future__ import absolute_import from collections import namedtuple from datetime import datetime, timedelta import pytz from casexml.apps.case.dbaccessors import get_open_case_docs_in_domain from casexml.apps.case.mock import CaseBlock from casexml.apps.case.xml import V2 import uuid from xml.etree import Elemen...
""" psatlib -- An imported library designed for PSAT running with Python scripts. Created by <NAME> (<EMAIL>) Created on: 06/11/2018 Last Modified on: 10/01/2018 """ __name__ = "psatlib" __version__ = "0.1" __author__ = "<NAME>" __author_email__ = "<EMAIL>" __copyright__ = "Copyright (c) 2018 Zhijie Nie" __d...
#!/usr/bin/env python # This software was developed in whole or in part by employees of the # Federal Government in the course of their official duties, and with # other Federal assistance. Pursuant to title 17 Section 105 of the # United States Code portions of this software authored by Federal # employees are not su...
import sys import argparse import matplotlib.pyplot as plt import numpy as np import pickle def load_obj(name): pkl_path = "" with open(pkl_path + name + ".pkl", 'rb') as f: return pickle.load(f) def load_prun_obj(name): pkl_path = "" with open(pkl_path + name + ".pkl", 'rb') as f: r...
"""The module contains functions to preprocess input datasets into usable format.""" import gc import gzip import json import logging import multiprocessing as mp import pathlib import sys from itertools import repeat import numpy as np import scipy.sparse as smat logging.basicConfig( stream=sys.stdout, format...
import json import uuid from dataclasses import dataclass from typing import Callable, Sequence, Any, Optional, Tuple, Union, List, Generic, TypeVar from serflag import SerFlag from handlers.graphql.graphql_handler import ContextProtocol from handlers.graphql.utils.string import camelcase from xenadapter.task import ge...
#!env python3 """ Introducing static object in the world. Tasks: 1. File got really long - move all classes to library file and import them here. """ import pygame from pygame import K_ESCAPE, K_LEFT, K_RIGHT, K_UP, K_DOWN, QUIT class Game(): def __init__(self): """ Set basic configura...
import rclpy import json,numpy from numpy import clip from rclpy.node import Node from std_msgs.msg import Float64MultiArray from sensor_msgs.msg import JointState from diagnostic_msgs.msg import DiagnosticStatus, KeyValue import can from tinymovr import Tinymovr from tinymovr.iface.can import CAN from tinymovr.units...
import os import sys import math # 3.1 using single array to implement 3 stacks # 1) - using 3 indexes to for each stack pointers, and 3 size to set maximum of stack # 2) - using 3 indexes, 1 begin at the first index and increase, 1 begin at the bottom and decrease, 1 at the bottom and re-balanced every time class Ar...
#!/usr/bin/python3 # author mhakala import json import re import subprocess import tempfile import os import xml.etree.cElementTree as ET import argparse import os.path import time import random from datetime import datetime from datetime import timedelta import traceback import configparser import glob def jobs_runn...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """WCS related utility functions.""" from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np from astropy.wcs import WCS from astropy.coordinates import Angle __all__ = [ 'linear_wcs_to_arrays', 'linea...
from generator.actions import Actions import random import string import struct import numpy as np import math import datetime as dt import ctypes def kaprica_mixin(self): if hasattr(self, 'xlat_seed'): return def xlat_seed(seed): def hash_string(seed): H = 0x314abc86 f...
import requests import json import os import sys import shutil from .azureblob import AzureBlob from .azuretable import AzureTable from .timeutil import get_time_offset, str_to_dt, dt_to_str from .series import Series from .constant import STATUS_SUCCESS, STATUS_FAIL from telemetry import log # To get the meta of a ...
import csv import os.path import random import numpy as np import scipy.io import torch import torchvision from torch.utils.data import Dataset # from .util import * from data.util import default_loader, read_img, augment, get_image_paths class PIPALFolder(Dataset): def __init__(self, root=None, ...
import codecs import collections import io import os import re import struct from .instruction import Instruction from .opcode import Opcodes from .registers import Registers from .section import Section from .symbol import Symbol def p32(v): return struct.pack('<I', v) def unescape_str_to_bytes(x): return c...
import os import ipaddress import numpy as np import pandas as pd import datetime import boto3 import gzip import json from signal_processing import signalProcess BUCKET_NAME = os.environ.get("BUCKET_NAME", None) VPC_FLOW_LOGS_PATH = os.environ.get("VPC_FLOW_LOGS_PATH", None) FINDINGS_PATH = os.environ.get("FINDINGS_...
#!/usr/bin/env python3 import sys import ujson as json import json as json_orig import traceback import re import argparse import os.path import operator import requests from threading import Thread from queue import Queue from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib...
#!/usr/bin/env python3 """This python program deploys the files needed by the Hillview service on the machines specified in the configuration file.""" # pylint: disable=invalid-name from argparse import ArgumentParser import tempfile import os.path from hillviewCommon import ClusterConfiguration, get_config, get_l...
# -*- coding: utf-8 -*- """ Created on Wed Dec 4 13:54:27 2019 @author: eric.qian """ from collections import Counter from itertools import combinations # Numeric hand rankings, higher integer value is stronger hand HAND_RANKINGS = {0: 'High Card', 1: 'One Pair', 2: 'T...
from datetime import datetime import traceback import boto3 from botocore.exceptions import ClientError from ...config import config from ...log import log class Submitter(): def __init__(self, event): self.event = event def find_instance(self, instance_id, mac_address): # pylint: disable=R0201 ...
import logging from flask import Response, make_response, request from microraiden import HTTPHeaders as header from flask_restful.utils import unpack from microraiden.channel_manager import ( ChannelManager, ) from microraiden.exceptions import ( NoOpenChannel, InvalidBalanceProof, InvalidBalanceAmoun...
# -*- coding: UTF-8 -*- """ split_by_area =========== Script : split_by_area.py Author : <EMAIL> Modified: 2018-08-27 Purpose : tools for working with numpy arrays Notes: ----- The xs and ys form pairs with the first and last points being identical The pairs are constructed using n-1 to ensur...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import numpy.random as rand import numpy as np import pandas as pd import random import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.animation import FuncAnimation from Particle import Particle #Initialization of the plots fig = plt.figure(figsize=(20,10)) axes = [None...
import numpy as np from models import * from datasets import * from util import parse_funct_arguments import pickle import itertools def mse(y_true, y_mdl): return np.mean((y_true - y_mdl)**2) def train(mdl, dset): # Get train u_train, y_train = dset.get_train() # Fit X_train, z_train = construc...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import shutil import argparse import subprocess import numpy as np import contextlib import onnx from cvi_toolkit.utils.mlir_shell import * from cvi_toolkit.utils.intermediate_file import IntermediateFile @contextlib.contextmanager def pushd(new_dir): previous...
from flask import Flask, render_template, request, redirect, url_for, Markup, \ flash # Imports Flask and all required modules import databasemanager # Provides the functionality to load stuff from the database app = Flask(__name__) import errormanager # Enum for types of errors # DECLARE datamanager as...
from cryptography.fernet import Fernet import os import discord import aiohttp import secrets from urllib.parse import quote from dotenv import load_dotenv load_dotenv() class OAuth: def __init__(self): # User Provided Data self.client_id = os.getenv("CID") self.client_secret = os.getenv("C...