text
stringlengths
3.07k
12.6k
"""GitHub Module""" import json import requests from django.contrib.auth.models import User #from readux import __version__ __version__ = "2.0.0" class GithubApiException(Exception): """custom exception""" pass class GithubAccountNotFound(GithubApiException): """custom exception""" pass class Gith...
""" Copyright (c) 2015 SONATA-NFV 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 agreed to...
import pandas as pd import numpy as np def update_judges_table(): """ This function pulls information from multiple url's to create a table populated with information on all immigration judges. This table is saved in the current directory as 'judges_courts.csv'. """ def get_courts(data): ...
"""Display the "About Porcupine" button in the "Help" menu.""" from __future__ import annotations import functools import itertools import os import pathlib import re import subprocess import sys import tkinter import webbrowser from tkinter import ttk from typing import Any, List, Match, Union from porcupine import ...
from mpi4py import MPI import unittest import numpy as np import sys import pycorgi.twoD as pycorgi #sys.path.append('../lib') class Params: mins = None maxs = None lens = None class Initialization(unittest.TestCase): Nx = 10 Ny = 20 xmin = 0.0 xmax = 1.0 ymin = 2.0 ymax = 3....
from datetime import datetime, timedelta from functools import lru_cache, partial from typing import Any, ByteString, Dict, Text, Tuple, Optional, ClassVar, List from urllib.parse import urljoin, urlparse, urlunparse import attr from bs4 import BeautifulSoup, Tag from requests import Session from baseball_utils.savan...
# Copyright 2012 Viewfinder Inc. All Rights Reserved. """Handlers for viewing counters generated by logs analysis. """ __author__ = '<EMAIL> (<NAME>)' import json import os import re import time import logging from collections import Counter, defaultdict from functools import partial from tornado import auth, gen, t...
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe, random, erpnext from datetime import timedelta from frappe.utils.make_random import how_many from frappe.desk import query_report from e...
import argparse import numpy as np import torch import torch.backends.cudnn as cudnn import torch.optim as optim import torchvision import torchvision.transforms as transforms from torch.nn import CrossEntropyLoss from torch.utils.data import DataLoader from tqdm import tqdm from models.resnet_cifar10 import ResNet18...
import pickle import pdb import random import unittest from pathlib import Path from typing import Any, Tuple import dask import numpy as np from gtsam import Cal3Bundler, Pose3 from scipy.spatial.transform import Rotation from gtsfm.common.keypoints import Keypoints from gtsfm.frontend.verifier.degensac import Degen...
# ---------------------------------------------------------------------------- # meh # Copyright (c) 2021 TreeCaptcha # # 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, in...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
#!/usr/bin/env python3 # Copyright 2022 Xiaomi Corporation (Author: <NAME>) # # See ../../../../LICENSE for clarification regarding multiple 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 Licen...
import logging import json import typing import azure.functions as func from requests.exceptions import HTTPError from shared_code.services.workbench_service import get_rca_task, get_workbench_detail from shared_code import utils, configurations, transform_utils from shared_code.exceptions import GeneralException fro...
import asyncio import json import logging import os import yaml from collections import ChainMap from pathlib import Path from . import discovery from . import knowledge from . import utils log = logging.getLogger("disco") _marker = object() class Rule: op = all def __init__(self, deps, command, op=None, ...
#!/usr/bin/python from lennoxs30api.s30exception import S30Exception from lennoxs30api import lennox_system, lennox_zone, s30api_async import time import logging import sys import asyncio ###### ENIVRONMENT SETUP ##################### LOG_PATH = "/home/pete" # Directoy to stash the log file in # EMAIL_ADDRESS = "<...
import boto3 import uuid import datetime import time from botocore.exceptions import ClientError rekognition = boto3.client('rekognition') client = boto3.client('sns') main_images_bucket_name = "team30ws-mediarepofinal" resized_images_bucket_name = "team30ws-mediarepofinalresized" # The sender for the email SENDER ...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # Name: correlate.py # Purpose: Stream analyzer designed to correlate and graph two properties # # Authors: <NAME> # # Copyright: Copyright © 2009-2010 <NAME> and the music21 Project # License: ...
import os, time, subprocess, random from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriv...
import os import csv import uuid import tqdm import pickle import langdetect from langdetect import detect from . import encoding class DataDescription(object): """ Describes a fields in a CSV """ def __init__(self, header_index:int=0, header_keys_special:dict={}) -> None: """__init__ ...
""" -------------------------------------------------------------------- Title: lodcloud_search_api Author: <NAME> URL: https://github.com/AntonioGiulio/lod_cloud_search_engine Description: This module is capable of performing various types of queries on the JSON file offered by lod cloud. It turns out to b...
from collections import deque from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import Dense from tensorflow.python.keras.optimizers import Adam from time import sleep import numpy as np import random import gym class DQNAgent: """Class providing DQN algorithm based on kera...
import ckan.plugins as plugins import ckan.plugins.toolkit as toolkit import validators from datetime import datetime import json import helpers from ckan.logic import NotFound from ckan.lib.plugins import DefaultTranslation from logic import action import logging from pylons import config log = logging.getLogger(__n...
# Copyright 2014-2020 The PySCF Developers. 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 appl...
import logging import numpy as np import torch from torch import nn from torch.serialization import load from tqdm import tqdm from torch import optim from torch.nn import functional as F from torch.utils.data import DataLoader from utils.inc_net import IncrementalNet from models.base import BaseLearner from utils.tool...
import os import subprocess from pathlib import Path import standard.experiments as experiments import standard.experiment_controls as experiment_controls import standard.experiment_metas as experiment_metas import tools import settings use_torch = settings.use_torch def local_train(config, path=None, **kwargs): ...
# -*- coding: utf-8 -*- from django.contrib import admin from gestion.forms import LotesAdminForm from gestion.models import SeriesLotes, DetAnaliticas, Procedencia, CabAnaliticas, Lotes, DetLotes, OrdenProduccion from maestros.models import Terceros from produccion.models import DetProcesos from utils import * clas...
from blinky.cli import pass_environment import os import click from PIL import Image, ImageDraw, ImageFont import time import requests @pass_environment def binance(ctx, symbol): try: response = requests.get(f'https://api.binance.us/api/v3/ticker/24hr?symbol={symbol}') ctx.json_data = response.json...
from django.contrib import admin from django.contrib.admin import SimpleListFilter from django.db import models from django.utils.translation import ugettext_lazy as _ from powerdns.forms import ( CryptoKeyForm, DomainForm, DomainMetadataForm, RecordForm, RecordRequestForm, ) from powerdns.models i...
#!/usr/bin/env python #This is a script that calculates collocates for a specific keyword by computing how often each word collocates with the keyword across a text corpus. A measure of the strength of association between the keyword and its collocates (MI) is calculated, and the results are saved as a single file con...
#! /usr/bin/python3 import sys import os import subprocess import time import pathlib import shutil import delectable import dlct def process_targets_folder(singularity_image_path, leaf_script_path, mount_folder_path, targets_folder_path, model_folder_path, n_submitted) : # Go training ...
import torch from einops import rearrange from torch.nn.utils.rnn import PackedSequence import padertorch as pt from padertorch.modules import fully_connected_stack from padertorch.modules.normalization import Normalization from padertorch.modules.recurrent import StatefulLSTM from padertorch.ops import pack_sequence,...
# encoding: utf-8 """ @author: BrikerMan @contact: <EMAIL> @blog: https://eliyar.biz @version: 1.0 @license: Apache Licence @file: helpers.py @time: 2019-05-17 11:37 """ import json import os import pathlib import pydoc import random import time from typing import List, Optional, Dict, Union import tensorflow as tf ...
import bpy import bmesh import numpy as np from mathutils import Vector def find_first_view3d(): '''Helper function to find first space view 3d and associated window region. The three returned objects are useful for setting up offscreen rendering in Blender. Returns ------- area: object ...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
##################################### # WARNING! # This was designed with little experience in appropriate patterns. # This is ABSOLUTELY NON RESTful. # Please never use any of this App methods except from within Slave App. # Planned for redesign! ##################################### import logging logger = logging.g...
# Copyright (c) 2008, <NAME>. All rights reserved. # # 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...
from collections import defaultdict from typing import ( Callable, Dict, Generator, Iterable, List, Optional, Set, Union, ) from scmrepo.git import Git from dvc.exceptions import InvalidArgumentError from dvc.repo.experiments.exceptions import AmbiguousExpRefInfo from .base import ( ...
import os import sys from setuptools import setup import numpy as np import numpy.distutils from numpy.distutils.command.build_ext import build_ext from numpy.distutils.command.build_src import build_src from numpy.distutils.command.build import build import numpy.distutils.core from subprocess import call # Path ...
import math import logging import numpy as np import torch from torch import nn import torch.utils.data from torch.nn import functional as F from torch.autograd import Variable def normalize(x): x_norm = torch.norm(x, p=2, dim=1).unsqueeze(1).expand_as(x) x_normalized = x.div(x_norm + 0.00001) return x_n...
import asyncio import asyncpg import random from fixtures.zenith_fixtures import WalAcceptor, WalAcceptorFactory, ZenithPageserver, PostgresFactory, Postgres from typing import List from fixtures.utils import debug_print pytest_plugins = ("fixtures.zenith_fixtures") class BankClient(object): def __init__(self, ...
from .extensions import db from datetime import datetime from werkzeug.security import check_password_hash,generate_password_hash from flask_login import UserMixin from app.search import add_to_index,query_index,remove_from_index class User(db.Model,UserMixin): id = db.Column(db.Integer,primary_key=True) ...
import argparse import json import logging import random import re from datetime import datetime from os import listdir from os.path import join import numpy as np import pandas as pd import torch from torch.utils.data import DataLoader from datasets.shapenet import ShapeNetDataset from metrics.jsd import jsd_between...
"""Training module.""" import logging import numpy as np import os import torch from collections import defaultdict from sklearn.metrics import roc_auc_score from timeit import default_timer from tqdm import trange from flexehr.utils.modelIO import save_model from utils.helpers import array class T...
# Astral solar angles parse import datetime as dt from astral import Astral, Location import pytz import timezonefinder import pymongo from pymongo import MongoClient # from razon_parse import get_cos_factors import math import pandas as pd from angle_to_position import * class AstralPositions: def __init__(self...
""" This module implement the ServiceProxy class. This class is used to provide a local proxy to a remote service for a ZeroRobot. When a service or robot ask the creation of a service to another robot, a proxy class is created locally so the robot see the service as if it as local to him while in reality the service ...
import numpy as np import argparse import imutils import cv2 from scipy.spatial import distance as dist from imutils import perspective from imutils import contours # Variables for each extruder TRUE_DIST = [2, 4, 6, 8, 10, 12, 14] REF_CENTER_COORDINATE = [] PROJECTED_COORDINATES = [] COLORS = ( (0, 0, 255), ...
#coding=utf8 from uliweb.core.taglibs import parse, Loader, parse_xml tags = {'panel': """<div {%=to_attrs(_attrs, {'class':'panel'})%}> <div class="panel-head"> <h3>{%<< xml(head)%}</h3> {% if defined('button'):%} {%<< xml_full('button', button)%} {%pass%} </div> </div>""", 'button': "...
#!/usr/bin/python3 # # https://github.com/eLvErDe/check-open-fds # # This is free and unencumbered software released into the public domain. # # Anyone is free to copy, modify, publish, use, compile, sell, or # distribute this software, either in source code form or as a compiled # binary, for any purpose, commercial o...
import copy import random import numpy as np import torch from .. import ModelWrapper class GCNMixModelWrapper(ModelWrapper): """ GCNMixModelWrapper calls `forward_aux` in model `forward_aux` is similar to `forward` but ignores `spmm` operation. """ @staticmethod def add_args(parser): ...
# Copyright 2020 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import textwrap from abc import abstractmethod from dataclasses import dataclass from typing import List, Tuple, cast from pants.core.util_rules.archive import ExtractedDigest, MaybeExtra...
""" MIT License Copyright (c) 2021 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
import tkinter from tkinter import * import os import ctypes from tkinter import ttk from tkinter.messagebox import showinfo import windnd from tkinter import filedialog import time from win32.win32api import GetSystemMetrics import subprocess st=subprocess.STARTUPINFO() st.dwFlags=subprocess.STARTF_USESHOWWINDOW st.w...
# Copyright (c) 2021 The Distrobuild Authors # # 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,...
#!/bin/env python3 ##Modual Imports####### from math import * import pygame from time import * from random import * ####################### class GUI(): def __init__(): ### Pygame Setup####### wd=1200 ht=600 pygame.init() win = pygame.display.set_mode((wd,ht)...
#!/usr/bin/env python #encode=utf-8 #vim: tabstop=4 shiftwidth=4 softtabstop=4 #Created on 2013-8-17 #Copyright 2013 nuoqingyun xuqifeng import sys import time from datetime import datetime, timedelta from glance import log as logging LOG = logging.getLogger(__name__) # Somes libs depends of OS is_B...
"""Get the main loaded data""" from pathlib import Path from PySide6.QtStateMachine import QState, QAbstractState, QStateMachine, QFinalState, QKeyEventTransition from abc import abstractmethod, abstractproperty, ABC, ABCMeta import traceback, sys, enum from isu.ui import UiLoad from enum import Enum, auto, unique, ...
""" File Name: Serializers Purpose: Serializers for translating database data before sending it over the API. Comments: """ from django.db.models import Sum from rest_framework import serializers from rest_framework.fields import empty from api.models import BugReport, FeedbackForm from api.models import Student, Ment...
from __future__ import absolute_import import json import subprocess import sys import textwrap from detect_secrets import VERSION from detect_secrets.core.baseline import get_secrets_not_in_baseline from detect_secrets.core.baseline import update_baseline_with_removed_secrets from detect_secrets.core.log import get_...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np from pylfi.utils import check_1D_data, check_number_of_entries, iqr from scipy import optimize, special def histogram(data, bins=10, density=True, **kwargs): """ """ bins = calculate_bins(data, bins=bins) return np.histogram(data, bins...
""" Code for performing the case study for the risk quantification paper. Creation date: 2021 02 03 Author(s): <NAME> Modifications: """ import os from typing import Callable, List, NamedTuple import numpy as np import pandas as pd from tqdm import tqdm from simulation import SimulationString, KDE, kde_from_file #...
import numpy as np import multiprocessing import time from approx import compute_exact_grid_logpf, bound_logpf, bound_logpf_trw def generate_model(height, width, min_field, max_field, min_interaction, max_interaction, seed): np.random.seed(seed) magnetic_fields = min_field + np.random.rand(height, w...
import pickle, shutil, os, re, json from grtoolkit.Decorators import try_pass from grtoolkit.File import directoryLastValue class Pickle: def __init__(self, fileName): self.file = fileName self.contents = None def load(self): with open(self.file, 'rb') as file: self.content...
import math import random import matplotlib.pyplot as plt import numpy as np import gym import os import json from policy_gradient.ppo.ppo import PPO from EnvLib.GeomEnv1 import * show_animation = True mark_size = 4 line_size = 2 class Transformation(): def __init__(self): self.diff_x = 0 self.d...
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
from collections import namedtuple import os import posixpath import re import sys import urllib.parse from .exceptions import UnsupportedProtocolError from .lib import yellow, toabs ExtractedPath = namedtuple('ExtractedPath', ('format', 'protocol', 'bucket', 'path', 'host') ) ALLOWED_PROTOCOLS = [ 'gs', 'file', ...
#!/usr/bin/python # -*- coding: utf8 -*- from pprint import pprint from s3_utils import * from sqs_utils import * from urllib import unquote_plus import random # 0. Job job_info = { 'src_type': 's3_inventory', 'inventory_bucket': 'leo-bjs-inventory-bucket', 'inventory_manifest_dir': 'leodatacenter/leodata...
#coding:utf-8 import requests import json from bs4 import BeautifulSoup from lxml import etree import re import time import os # header cookies = '' header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36', 'Connection': 'keep-aliv...
import os from os import path import sys import tempfile import difflib import signal if os.name == 'posix' and sys.version_info[0] < 3: import subprocess32 as subprocess else: import subprocess def from_file(corr,inp,folder,file_check,fault,limit,time): inp_temp=tempfile.TemporaryFile(dir=folder) (head,tail)...
from nitorch import spatial, io from nitorch.core import py, utils import torch import os def _crop_to_param(aff0, aff, shape): dim = aff0.shape[-1] - 1 shape = shape[:dim] layout0 = spatial.affine_to_layout(aff0) layout = spatial.affine_to_layout(aff) if (layout0 != layout).any(): raise V...
import os import pytest from click.testing import CliRunner from ncpi_fhir_utility import loader, cli, app from conftest import ( PROFILE_DIR, EXAMPLE_DIR, EXTENSION_DIR, INVALID_RESOURCES, TEST_SITE_ROOT, copy_resources_into_ig, ) VALID_PROFILE_DIR = os.path.join(PROFILE_DIR, "valid") VALID_...
from baconian.common.plotter import Plotter import pandas as pd from baconian.common.files import * from collections import OrderedDict from typing import Union class SingleExpLogDataLoader(object): def __init__(self, exp_root_dir: str): self._root_dir = exp_root_dir check_file(path=os.path.join(e...
import argparse import os import pickle from collections import OrderedDict from torch.utils import data from utils.helpfunc import get_data_root import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from matplotlib import pyplot as plt from torch.utils.data import DataLoader from tqdm...
from __future__ import print_function import copy import numpy as np import math class ColorMap(object): def __init__(self, name): self.name = name def get_color(self, x): pass def convert_to_intensity(self, x): x = np.fabs(x) mask = x > 1.0 x[mask] = 1.0 ...
# $ pythran -DUSE_XSIMD -fopenmp -march=native speedup.py import numpy as np #pythran export sort(float[]) def sort(scores): return np.sort(scores)[::-1] #pythran export complement(str) def complement(seq): seq = list(seq.replace('A', 't').replace('T', 'a').replace('C', 'g').replace('G', 'c').upper()) ...
import numpy as np import itertools from scipy.special import gammaln class bayesian_hclust_cpp(): """ Bayesian Hierarchical Clustering with critical function using c++ optimized """ def __init__(self, model, alpha): """ Parameters: ------------ model: class ...
#/*********************************************************************** # * Licensed Materials - Property of IBM # * # * IBM SPSS Products: Statistics Common # * # * (C) Copyright IBM Corp. 1989, 2020 # * # * US Government Users Restricted Rights - Use, duplication or disclosure # * restricted by GSA ADP Sch...
# Copyright 2017 Google Inc. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # #...
#! /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/L...
"""SciKit Sequitur Core Python code adapted from a Javascript version written by <NAME>. """ class Symbol: """Symbol Initializes a new symbol. If it is non-terminal, increments the reference count of the corresponding rule. Tightly coupled with Rule. Not designed for extensibility. """ # ...
import random import torch import numpy as np from tqdm import tqdm import mmcv from mmdet.core.bbox import bbox_overlaps def np_iof(bboxes, canvas): return bbox_overlaps( torch.FloatTensor(bboxes), torch.FloatTensor(canvas), 'iof', ).numpy().reshape(-1) def iter_empty_crops(w, h, s...
import os import numpy as np from datetime import datetime as dt, timedelta import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify os.chdir(os.path.dirname(os.path.abspath(__file__))) ###########...
#!/usr/bin/env python from __future__ import print_function import argparse import cProfile import pstats import random import numpy as np from examples.continuous_tamp.constraint_solver import cfree_motion_fn, get_optimize_fn from examples.continuous_tamp.primitives import get_pose_gen, collision_test, distance_fn,...
import argparse from inspect import getmodule, getmembers, isfunction import os from pathlib import Path import platform import subprocess import sys import numpy as np import niaarm from niaarm import NiaARM, Dataset, get_rules from niapy.util.factory import get_algorithm from niapy.util import distances, repair from...
import rlp import uuid from gear.utils.singleton import Singleton from gear.utils.types import ( encode_number, encode_hex ) from gear.utils.compat import ( thor_block_convert_to_eth_block, thor_receipt_convert_to_eth_receipt, thor_tx_convert_to_eth_tx, thor_log_convert_to_eth_log, thor_stor...
# transform train/test data import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessing import LabelEncoder from sklearn import metrics import numpy as np from sklearn.preprocessing import StandardScaler def eda(df): # Exploratory data analysis # Target variable analysis plt.hist(df['Su...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import deque from io import StringIO from math import ceil import os import threading import unittest from hwt.simulator.simTestCase import SimTestCase from hwtLib.examples.axi.debugbusmonitor import DebugBusMonitorExampleAxi from hwtLib.tools.debug_bus_...
#!/usr/bin/env python3 # # Copyright 2020 Google LLC # # 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 ...
from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset from torch.optim.lr_scheduler import StepLR import numpy as np class Spline(Dataset): def __init__(self, fname): self.spl...
import os import csv import cv2 import math import numpy as np from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from tensorflow import keras def steering_angle(angle, wheel_base = 2.0, axle_track = 1.6): # vehicle parameters are roughly setted here if angle != 0: radi...
# -*- coding: utf-8 -*- # @Author : <NAME> # @Email : <EMAIL> # @Created Date : 2021-02-24 13:58:46 # @Last Modified : 2021-03-05 18:14:17 # @Description : import tensorflow as tf from .nets.efficientnet import EfficientNetB0, EfficientNetB1, EfficientNetB2, EfficientNetB3 from .nets.efficientnet im...
# Using PyTorch 1.4 import numpy as np import pyarrow.parquet as pq import pandas as pd import random import torch import fire import logging import os import csv from torch.utils.data import Dataset, DataLoader from transformers import GPT2Tokenizer, GPT2LMHeadModel, AdamW, get_linear_schedule_with_warmup from tqdm ...
#!/usr/bin/env python3 """Library for Network Switch Classes.""" # Copyright 2019 IBM Corp. # # 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...
__author__ = ["<NAME>"] __copyright__ = "Copyright 2020, National Renewable Energy Laboratory" __maintainer__ = "<NAME>" __email__ = ["<EMAIL>"] import re import time from copy import deepcopy from random import sample from itertools import product import yaml import numpy as np import pandas as pd import statsmodel...
from collections import OrderedDict, namedtuple from copy import copy """Adaptive replacement cache implementation based upon OrderedDict see https://en.wikipedia.org/wiki/Adaptive_replacement_cache Every cached element is represented as a list (mutable tuple) of three elements: IDX (int): 0th, index of an el...
"""Parsing and validation for Device/Service XML. Provides a light wrapper around the generated device & service parsers. The wrappers check for required fields and values. Default values are also provided for optional fields. Clients of this module can expect that all fields of the dataclass instances are fully popul...
#! /usr/bin/env python import cv2 import numpy as np from vgg19 import VGG_19 import keras.backend as K def load_img(path): transpose_shape = (2, 0, 1) img_shape = (224, 224) img = cv2.imread(path, cv2.IMREAD_COLOR) img = cv2.resize(img, img_shape).astype(np.float32) img = img.transpose(transpose_...
#!/usr/bin/env python3 import logging import datetime import re import sys # The arrow library is used to handle datetimes import arrow # The request library is used to fetch content through HTTP import requests # please try to write PEP8 compliant code (use a linter). One of PEP8's # requirement is to limit your lin...
""" Based on original haml-watcher.py by <NAME> (<EMAIL>) Watches a folder for files with the given extensions and calls the HamlPy compiler if the modified time has changed since the last check. """ import argparse import codecs import os import os.path import sys import time from time import strftime from hamlpy i...
#!/usr/bin/env python3.3 from time import time import json import re from multiprocessing.pool import ThreadPool from time import time, sleep import requests from websocket import create_connection, WebSocketTimeoutException from colorama import Fore LIVEANY_URL = 'http://172.16.58.3:6007/socket.io/' WS_URL = 'ws://...