text
stringlengths
3.07k
12.6k
import tensorflow as tf import numpy as np import createBasisWeights as cbw def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') #copied from https://www.tensorflow.org/get_started/mnist/pros #To keep our code cleaner, let's also abstract th...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api, _ from odoo.exceptions import UserError from odoo.addons import decimal_precision as dp class SaleOrder(models.Model): _inherit = 'sale.order' carrier_id = fields.Many2one...
# encoding: utf-8 import os import bson import logging import pymongo from modularodm import fields, Q from modularodm import exceptions as modm_errors from modularodm.storage.base import KeyExistsException from framework.auth import Auth from framework.mongo import StoredObject from framework.analytics import get_...
# Copyright 2021 The Petuum 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 applicable...
# # A wrapper script that trains the SELDnet. The training stops when the SELD error (check paper) stops improving. # import os import sys import numpy as np import matplotlib.pyplot as plot import cls_feature_class import cls_data_generator from metrics import evaluation_metrics import keras_model from keras.models i...
#!/usr/bin/env python ''' ShellOut.py call an external program passing the active layer as a temp file. Windows Only(?) Author: <NAME> Version: 0.7 fixed file save bug where all files were png regardless of extension 0.6 modified to allow for a returned layer that is a different size than the saved ...
from django.contrib import messages from django.contrib.auth import logout, update_session_auth_hash from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordChangeForm from django.contrib.auth.mixins import LoginRequiredMixin from django.db import Error from django.shortc...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2010,2011,2012,2013,2014,2015,2016 Contributor # # 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...
from tqdm import tqdm import gym import numpy as np from gym import spaces from stable_baselines3 import PPO, A2C, DQN from stable_baselines3.common.evaluation import evaluate_policy from pettingzoo.mpe import simple_adversary_v2 from policies import static_policy, random_policy, follow, follow_non_goal_landmark_policy...
# Import libraries import pandas as pd import numpy as np import math import time import sys import pickle from gensim.models.doc2vec import Doc2Vec, TaggedDocument from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, precision_recall_curve, auc, matthews_corrcoef from sklearn...
#!/usr/bin/env python # Copyright (c) 2013, Oregon State University # 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 # no...
import os import torch import argparse import numpy as np from PIL import Image from tqdm import tqdm from torch.utils.data import DataLoader import logging from torch.autograd import Variable from torchvision import transforms logger = logging.getLogger(__name__) class HUMANPARSING(object): """ HUMANPARSI...
# Copyright (c) 2013 by California Institute of Technology # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this...
# Copyright 2017 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 ...
# -*- coding: utf-8 -*- """ Created on Sun Jul 21 10:04:57 2019 @author: Dominic """ from ..finutils.FinGlobalVariables import gDaysInYear from ..finutils.FinError import FinError from ..products.FinOptionTypes import FinOptionTypes import numpy as np from numba import njit, jit, float64, int64 bump = 1e-4 #####...
import json import sched import time from typing import Tuple from uk_covid19 import Cov19API covid19scheduler = sched.scheduler(time.time, time.sleep) def parse_csv_data(csv_filename: str) -> list: """ parse_csv_data extracts data from a csv file and formats it as a list of strings with eac...
# -*- coding: utf-8 -*- #------------------------------------------------------------------------- # drawElements Quality Program utilities # -------------------------------------- # # Copyright 2015 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use t...
from unittest.mock import Mock import pytest from plenum.common.constants import COMMIT, NEW_VIEW from plenum.common.messages.internal_messages import MissingMessage, ViewChangeStarted from plenum.common.messages.node_messages import MessageReq, MessageRep, Commit, ViewChange, ViewChangeAck, NewView from plenum.commo...
#!/usr/bin/env python3 # day_11.py # By <NAME>, 2018. import aocd class SummedAreaTable: """ Given a table, create a summed-area table for that table. A summed-area table is a table where entry (x,y) contains the sum of table[i][j] for 0 <= i <= x and 0 <= j <= y. This allows us to calculate the sum...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Copyright 2021 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import json import os import re import shutil import sys from collections import Counter from pprint import pprint import requests from requests_ftp.ftp import FTPSession from rfc6266 import parse_requests_response from translitua i...
#!/usr/bin/env python # Copyright (c) 2018 Intel Labs. # authors: <NAME> (<EMAIL>) # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """ Module with auxiliary functions. """ import math import numpy as np import carla def draw_waypoi...
# -*- coding: utf-8 -*- """ Created on Sat Apr 23 11:57:14 2016 @author: eman """ import numpy as np from scipy.sparse import csr_matrix, csc_matrix, spdiags, diags from sklearn.utils.graph import graph_laplacian from utils.nearestneighbor_solver import knn_scikit, knn_annoy from utils.knn_solvers import KnnSolver # ...
#!/usr/bin/env python3 from progress.bar import Bar, ChargingBar import os, time, random import numpy as np import matplotlib.pyplot as plt from numpy.random import normal, uniform from numpy import pi from step import simulador C = 10 ** -3 def random_position(Ym, perturbations, Ysd=None, normal_=True, dist=None): ...
# Copyright © 2020 Arm Ltd. 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 agre...
import bpy import json import os import subprocess from bpy.props import BoolProperty, EnumProperty, PointerProperty, StringProperty from bpy_extras.io_utils import ImportHelper from .viewlayers_load import load_view_layers from .viewlayers_save import search_view_layers from .util import * # -------------------------...
import pandas as pd import numpy as np import scipy as sp import os import exa import exatomic from exatomic import qe from neighbors_input import * from exatomic.algorithms import neighbors from exatomic.algorithms.neighbors import periodic_nearest_neighbors_by_atom # Only valid for simple cubic periodic c...
# -*- coding: utf-8 -*- # # Copyright (c) 2013 <NAME>. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, m...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 23 11:08:54 2017 @author: shenda """ from collections import Counter import numpy as np import pandas as pd import MyEval import ReadData import dill from sklearn.model_selection import KFold from sklearn.model_selection import StratifiedKFold from...
""" Image classification, Keras and SymJAX ====================================== example of image classification with deep networks using Keras and SymJAX """ import symjax.tensor as T from symjax import nn import symjax import numpy as np import matplotlib.pyplot as plt import sys sys.setrecursionlimit(3500) def ...
from django import forms from django.core.exceptions import ValidationError from django.utils.formats import date_format from django.utils.translation import gettext_lazy as _ from django_scopes.forms import SafeModelChoiceField from i18nfield.forms import I18nFormField, I18nTextarea, I18nTextInput from pretix.base.ema...
#!/usr/bin/env python # this should generally receive motor msg which is currently just left or right based on 3 or 4 respectively # or stop at 0. 1 and 2 are forward and backwards for initialisation - the purpose of this was initially to allow # test of the setup without any actual arduino hardware and that should be...
from typing import List import itertools import random import datetime import sqlite3 def add_users(connection: sqlite3.Connection) -> List[int]: """Create table `users` with fields: `id`, `name`, `age`, and fill it with random values """ cursor = connection.cursor() # clear table if exists ...
import re import requests from bs4 import BeautifulSoup from .leagues import URLS as LEAGUES_URLS BASE_URL = 'http://www.sportslogos.net/' class DownloadError(Exception): pass class HtmlParserError(Exception): pass class Downloader(object): def __init__(self, sport, league, team_name): for...
__all__ = ['L2Softmax', 'ArcLoss', 'AMSoftmax', 'CircleLossFC'] from torch import nn from torch.nn import functional as F import torch import math class NormLinear(nn.Module): def __init__(self, in_features, classes, weight_norm=False, feature_norm=False): super(NormLinear, self).__init__() self....
#! /usr/local/bin/python3 import sh import sys import os def print_error_and_continue(error, custom_message): print(custom_message) print("Full command: " + str(error.full_cmd)) print("Stderr: " + str(error.stderr)) print("Exit code: " + str(error.exit_code)) print("Proceeding with script executi...
#!/usr/bin/env python #-*- coding: utf-8 -*- import sys import re import os import argparse import pandas as pd import numpy as np import glob import random import datetime import subprocess import shutil def status_message(msg): print(msg) sys.stdout.flush() def run_cmd(cmd, msg=None): status_message(cmd...
import numpy as np import networks.yolov2.params as params def lastlayer2detection(lastlayer , thresh = 0.5): ''' Parameter lastlayer : dtype : np.array shape : (batch_size , H , W , num_anchors , (5(x , y , w , h , prob) + num_clss)) Return detection : ...
''' Description: This tool creates unique IDs for each segment and builds the To_Node, From_Node, and NextDownID columns to traverse the network Required Arguments: streams = stream network wbd8 = HUC8 boundary dataset hydro_id = name of ID column (string) ''' import sys...
from matplotlib.collections import LineCollection import matplotlib.colors as mpl_colors import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import os import scipy.io import seaborn.apionly as sns from mantis import sdp_km_burer_monteiro, cop...
#!/usr/bin/env python # # This software is distributed with the MIT license: # https://github.com/gkiar/clowdr/blob/master/LICENSE # # clowdr/share/server.py # Created by <NAME> on 2018-03-01. # Email: <EMAIL> from flask import Flask, render_template, redirect import os.path as op import datetime import tempfile impor...
import torch import numpy as np from torch import nn, Tensor from torch.nn import functional as F from torch import distributed as dist class DINOLoss(nn.Module): def __init__(self, out_dim, ncrops, warmup_teacher_temp, teacher_temp, warmup_teacher_epochs, nepochs, student_temp=0.1, center_momentum=0.9): ...
import threading import uuid import wsgiref.util from oauthlib.oauth2 import MobileApplicationClient,OAuth2Error from wsgiref.simple_server import make_server class ImplicitGrantManager: def __init__(self,cid,oauthPageUrl,receivePort): """ Args: cid (string): The client id from Authorization provider oau...
from collections import OrderedDict import torch from torch import nn from project.datasets import tokens_to_ids, vocab_size, BOS, EOS, UNK, PAD import torchvision models_ = { "resnet50": { "model": torchvision.models.resnet50, "features_out": 2048, "pooling": True, "remove_last":...
import re import random import string from . import db, APP_URL from .models import URL_DB from flask import Blueprint, render_template, request, redirect, flash, abort, jsonify URL_REGEX = ( "((http|https)://)(www.)?" + "[a-zA-Z0-9@:%._\\+~#?&//=]" + "{2,256}\\.[a-z]" + ...
from google.cloud import language_v1 import emoji import yaml import re from google.oauth2 import service_account def process_yaml(path): """[summary] :param path: [description] :type path: [type] :return: [description] :rtype: [type] """ with open(path) as file: return yaml.sa...
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of Androwarn. # # Copyright (C) 2012, <NAME> <<EMAIL>> # All rights reserved. # # Androwarn is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
# #------------------------------------------------------------------------------ # Copyright (c) 2013-2014, <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.or...
from srcT.Symbolic import AbstractToken import traceback from srcT.Common import ConfigFile as CF, Helper as H import collections, sys from clang.cindex import * class SymbTable: def __init__(self): self.dictBlockVarType = {} # Spelling -> Type mapping (for user-defined vars/funcs): In case Clang-goofUps...
# # Copyright (c) 2015-2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import os.path from nfv_common import config from nfv_common import debug from nfv_common import timers from nfv_common.helpers import coroutine from nfv_common.helpers import local_uptime_in_secs from nfv_common.helpers im...
#!/usr/bin/env python import rospy import socket import select import traceback from threading import Thread from collections import deque from std_msgs.msg import String, Header, Bool, Float32MultiArray from riptide_msgs.msg import Depth, PwmStamped, StatusLight, SwitchState IP_ADDR = '192.168.1.42' copro = None con...
from pathlib import Path import numpy as np import pandas as pd from src.available_datasets import train_datasets, val_datasets def get_scores_dataset_x_configs(dataset_dir): paths_list = sorted(dataset_dir.glob("*")) all_config_paths = [path for path in paths_list if not path.is_file()] n_repeat = len(...
"""Handles migration of historical statistics CSV files to the database.""" import csv import logging import sys import time from contextlib import contextmanager from datetime import datetime, timedelta from .db import engine, sesh, _set_db_readonly, _set_db_writable from .dbinfo import DbInfo, get_dbinfo from .accou...
""" A forked version of the Python :py:mod:`dataclasses` module. Create a dataclass with the decorator ``@sp.dataclass`` as follows:: import scalarstop as sp @sp.dataclass class Hyperparams(sp.HyperparamsType): val1: int val2: str The Python :py:mod:`dataclasses` module uses singletons ...
import sys import types import py from py.builtin import set, frozenset, reversed, sorted def test_enumerate(): l = [0,1,2] for i,x in enumerate(l): assert i == x def test_any(): assert not py.builtin.any([0,False, None]) assert py.builtin.any([0,False, None,1]) def test_all(): assert not...
import os from pytz import timezone from datetime import datetime import requests.exceptions from helpers import log from .sudo_query_helpers import query, update from .kalliope_adapter import construct_kalliope_poststuk_in from .kalliope_adapter import open_kalliope_api_session from .kalliope_adapter import post_kal...
# Copyright 2018 Fujitsu. # # 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...
import boto3 import json import os import yaml from collections import MutableMapping import logging import re from click._compat import open_stream import click import botocore import sys logger = logging.getLogger() logger.setLevel(getattr(logging, os.getenv('LOG_LEVEL', 'INFO'))) handler = logging.StreamHandler(sys....
import os import tarfile import requests from PIL import Image import numpy as np from keras.utils import np_utils from sklearn.model_selection import train_test_split def get_root(): home = os.path.expanduser('~') return os.path.join(home, '.mps/mpsc20190813') def create_root(): if not os.path.exists(g...
# Image Style Transfer Using Convolutional Neural Network # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++= # importing the required libraries import tensorflow as tf import numpy as np import os # Defining the required variables ROOT = os.getcwd() # project directory CONTENT_IMAGE = ROOT +...
from test.support import verbose, import_module, reap_children import_module('termios') import errno import pty import os import sys import select import signal import socket import unittest TEST_STRING_1 = b'I wish to buy a fish license.\n' TEST_STRING_2 = b'For my pet fish, Eric.\n' if verbose: def debug(msg): ...
"""Defines NastranMaker, an intelligent bulk data replacer for Nastran files.""" import re from nastran_util import stringify class NastranMaker(object): """A object that performs specified replacements conforming to the Nastran format. The goal of NastranMaker is to output a Nastran file with a set o...
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2019 <NAME> <<EMAIL>> # # 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 # ...
# ---------------------------------------------------------------------------- # Copyright (c) 2018-2021, QIIME 2 development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
from bottle import Bottle, template, static_file, request, response, redirect import bottle_session import bottle_sqlite import hashlib from datetime import datetime from markdown import markdown from beaker.middleware import SessionMiddleware from cork import Cork from cork.backends import SQLiteBackend import bottle ...
import os import sys import json import itertools import operator import matplotlib.pyplot as plt def create_folder(name): try: os.mkdir(name) except: pass def delete_file(name): try: os.remove(name) except: pass def plot_cumulative_sequence(data, property, attribute...
import os from datetime import datetime import keras import pandas as pd from definitions import ROOT_DIR from stable_baselines_model_based_rl.dynamic_model_trainer import (model_builder, prepare_data, verifier) from stable_baselines_model_based_rl.ut...
import torch import torch.nn as nn import torch.nn.functional as F import torchvision.models as models import timm from transformers import BertModel, BertTokenizer, BertConfig import os import json import custom_models as cm torch.hub._validate_not_a_forked_repo = lambda a, b, c: True torch_version = torch.__version...
# ESC180 Project 1 # gamify.py # Oct 14, 2021 # Done in collaboration by: # Ma, <NAME> (macarl1) and # <NAME> (xushenxi) # NOTE: VERSION 2 - FINAL SUBMISSION (UNLESS UPDATED) def initialize(): '''Initializes the global variables needed for the simulation. Note: this function is incomplete, and you may want t...
import numpy as np from scipy.sparse import csr_matrix class AliasArray(np.ndarray): """An ndarray with a mapping of values to user-friendly names -- see example This ndarray subclass enables comparing sub_id and hop_id arrays directly with their friendly string identifiers. The mapping parameter transla...
import discord from discord import webhook from discord_webhook import DiscordWebhook, DiscordEmbed from copy import deepcopy from time import sleep #from svg.path import Path, Line, Arc, CubicBezier, QuadraticBezier, Close, parse_path #from svgpathtools import Path, Line, QuadraticBezier, CubicBezier, Arc from discord...
import numpy as np import torch from torch import nn from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from config import device, im_size, grad_clip, print_freq, num_workers from data_gen import DIMDataset from models.deeplab import DeepLab from test import test from utils import parse_args, save...
import numpy as np import torch def rand_bbox_2d(size, lam): # lam is a vector B = size[0] assert B == lam.shape[0] W = size[2] H = size[3] cut_rat = np.sqrt(1. - lam) cut_w = (W * cut_rat).astype(np.int) cut_h = (H * cut_rat).astype(np.int) # uniform cx = np.random.randint(0, ...
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2020, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOC...
#============================================================================= # # Color Management # #============================================================================= """ Color Management ================ This system intends to equally support many different color representation schemes. There are many...
# -*- coding: utf-8 -*- # %% IMPORTS # Built-in imports from os import path # Package imports import astropy.units as apu import matplotlib.pyplot as plt import pytest # e13Tools imports from e13tools.core import InputError from e13tools.pyplot import ( apu2tex, center_spines, draw_textline, f2tex, q2tex) # Sav...
import copy import numpy as np from image_processing import image_proc from kuzushiji_data import visualization as vis class TranslateAugmentation_9case: def __init__(self, image_size_hw, width_shift_range=0.1, height_shift_range=0.1): self.IMAGE_SIZE_HW = image_size_hw self.WIDTH_SHIFT_R...
# DNA and RNA version 2 from typing import NoReturn, overload import colorama as _colorama from abc import ABCMeta, abstractmethod # *Custom error class UnknownBase(Exception): pass class UnknownPrime(Exception): pass # *Low level utility # Check if sequence is valid def _is_sequence_valid(sequence: str,...
import os from pathlib import Path from typing import Any import matplotlib.pyplot as plt import cv2 import numpy as np import gym from dataclasses import dataclass """ env.reset() -> obs env.step(action: int) -> obs: ndarray, reward: float, done: bool, info: Dict env.render """ games = () def make_env(game, width...
import random from Ship import ship from math import floor from Roll_Table import RollTable class MaelstromQuadrant: possible_encounters = ['Debris Cloud', 'Increasing Need', 'Smooth Sailing', 'Escape Capsule'] encounter_weights = [1, 1, 1, 1] weighted_encounter_table = None sector = 0 quadrant =...
# This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. from tempfile import TemporaryFile from os.path import join import biotite.sequence as seq import biotite.sequence.io.gff as gff import biotite.sequence.io.genbank ...
#! /usr/bin/enc python # -*- coding: utf-8 -*- # author: <NAME> # email: <EMAIL> """ 分布式架构 """ import copy from datetime import datetime from multiprocessing import set_start_method import torch.multiprocessing as torch_mp import multiprocessing as mp import queue from time import sleep import os from Networks imp...
import functools import inspect from pydoc import Helper import requests import json import urllib.parse import logging import csv import os from typing import Optional, Callable, Type, Union DEFAULT_README_PATH: str = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'README.md')) class Companie...
import requests import json import os # LAB EXERCISE 09 # SETUP CODE ENDPOINT = 'https://swapi.py4e.com/api' def get_swapi_resource(url, params=None, timeout=10): """Returns a response object decoded into a dictionary. If query string < params > are provided the response object body is returned in the form o...
import numpy as np import math import scipy import scipy.optimize import scipy.fftpack from BayesPSD import lightcurve def add_ps(psall, method='avg'): pssum = np.zeros(len(psall[0].ps)) for x in psall: pssum = pssum + x.ps if method.lower() in ['average', 'avg', 'mean']: pssum = pssum/...
import torch import matplotlib.pyplot as plt import glob import gzip import json import os import re import models as module_arch from datetime import datetime from parse_config import ConfigParser from pathlib import Path # Load a trained model using its best weights unless otherwise specified def load_model_config(...
import json import requests from events.handlers.base import EventHandler from django.conf import settings class ChatMessageHandler(EventHandler): """Take care of all events and push event for class chat messages""" event_types = ["chat_message", ] def handle(self): # It's already been added to ...
# Copyright (c) 2013 Mirantis 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 writ...
""" Users can detect bias in a model by seeing which concepts certain vectors are closer to. This is a particularly useful tool when users are looking at semantic vectors and would like to check if certain words are leaning particularly towards any specific category. An example of analysing gender bias inside Google's...
#!/usr/bin/env python3 # Copyright (c) 2021 Arm Limited. # # SPDX-License-Identifier: MIT # # 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 t...
#python3 Steven 08/25/2020 import matplotlib.pyplot as plt import numpy as np import random import matplotlib.patches as patches gStyles=['Line','Diag Line','Rectangle','Circle'] def plotXY(x,y,color='k'): plt.plot(x,y,color=color) def plotXYColor(x,y): plt.plot(x,y) def DrawPolygonByPt(pt1,pt2,pt3,pt4): ...
#!/usr/bin/env python # # 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.0OA # # Authors: # - <NAME>, <<EMAIL>>, 2021 """ performance test to insert ...
import wx class FormObj: pass class PersonPanel(wx.Panel): people_data = [] update_label = ["Save", "Update"] edit_mode=False def __init__(self, parent, event_handler, tab_title, person_controller): super().__init__(parent, wx.ID_ANY) self.top_parent = wx.GetApp().TopWindow ...
# coding: utf-8 # 2021/5/29 @ tongshiwei from EduNLP import logger import multiprocessing import gensim from gensim.models import word2vec from gensim.models.doc2vec import TaggedDocument from gensim.models.callbacks import CallbackAny2Vec from EduNLP.SIF.sif import sif4sci from EduNLP.Vector import D2V, BowLoader from...
#importing necessary library import RPi.GPIO as GPIO import threading import time import random import os from time import sleep # green, White, Yellow, RED LIGHTS = [13, 26, 19, 6] #in BCM mode #GPIO Pin for button Press #Corresponding button FOr Led As Above BUTTONS = [17, 22, 27, 4] #in BCM mode # values you ...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. from torch import nn from .base_backbone import BackboneCNN from ..builder import BACKBONES def _make_divisible(v, divisor, min_value=None): """ This function is taken from the original tf repo. It ensures that...
from server import Server import asyncio import logging import cbor2 import defines from messages.request import Request from messages.option import Option from messages.numbers import NON, Code from resources.resource import Resource logger = logging.getLogger() logger.addHandler(logging.StreamHandler()) logger.setL...
#!/usr/bin/python # -*- coding: utf8 -*- import numpy as np import math import cv2 as cv from matplotlib import pyplot as plt from lib_levels import ImageLevels ratio = 3 kernel_size = 3 low_threshold = 20.0 def calcRect(contours): r = cv.boundingRect(contours[0]) rect = list(r) for cnt in contours[1:]: ...
""" Implementation of Dijkstra shortest path algorithm in python. See https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm. """ import sys import math from collections import defaultdict, namedtuple import random from heapq import heappush, heappop from matplotlib import pyplot as plt Node = namedtuple('Node', ['x', ...
"""Generic util functions.""" import torch as th from torch.nn import functional as F from tqdm import tqdm from collections import OrderedDict from functools import partial # from datetime import datetime def printmd(s): from IPython.display import Markdown, display display(Markdown(s)) def get_device(no...