text
stringlengths
3.07k
22.1k
import base64 import dateutil.parser from django.db import models from django.db.models import Q from django.utils import simplejson from zumanji.github import github RESULT_CHOICES = tuple((k, k) for k in ( 'success', 'failed', 'skipped', 'deprecated', )) class GzippedJSONField(models.TextField): ...
from datacube import Datacube from datacube.api.query import query_group_by import numpy as np from types import SimpleNamespace import pytest from pathlib import Path from datacube.testutils import ( mk_sample_dataset, mk_test_image, gen_tiff_dataset, ) from datacube.testutils.io import write_gtiff, rio_s...
# -*- coding: utf-8 -*- import numpy.random as random import pandas as pd import numpy as np from numpy.random import randint #============================================================================# #==============================BUILDING BLOCKS===============================# #====================...
from sklearn import datasets import pandas as pd import numpy as np import time from dagster import execute_pipeline, pipeline, solid from dagster import ( Bool, Field, Output, OutputDefinition, PythonObjectDagsterType, execute_pipeline, pipeline, solid, String, Selector, En...
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright (c) 2020 by <NAME>. ~ # :license: Apache2, see LICENSE for more details. ~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Sampl...
import datetime import shutil from abc import ABC import pandas as pd from klgists.files import remake_dirs from klgists.misc.colored_notifications import notify_user, success_to_user from valarpy.Valar import Valar from sauronx import ( looks_like_submission_hash, plain_timestamp_started, plain_timestamp...
from os import listdir from os.path import isfile, join import numpy as np import pandas as pd import tensorflow as tf from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.models import Model from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Concatenate, Input def make_Res...
#!/usr/bin/env python3 # Copyright (c) 2019-2020, Arm Limited. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause # ''' The functions here perform straight-forward line-by-line comparisons of regression TF-Fuzz regression tests. These are not sufficient to address cases where the PSA calls are randomized....
#!/usr/bin/env python import PIL import PIL.Image import PIL.ImageDraw import PIL.ImageFont import numpy as np import nibabel as nib from future.utils import viewitems import argparse def main(): parser = argparse.ArgumentParser( description=""" Takes a t1 and a mask file, produces a ...
import asyncio import base64 import json import logging import re import shlex import uuid from dataclasses import dataclass, field from pathlib import Path from typing import Any, AsyncIterator, Dict, Optional, Sequence, Tuple import click import neuro_sdk as neuro_api from neuro_sdk.url_utils import normalize_storag...
import os import yaml import re from fs_helpers import * from wwrando_paths import ASM_PATH from wwlib.rel import REL, RELSection, RELRelocation, RELRelocationType ORIGINAL_FREE_SPACE_RAM_ADDRESS = 0x803FCFA8 ORIGINAL_DOL_SIZE = 0x3A52C0 def split_pointer_into_high_and_low_half_for_hardcoding(pointer): high_halfw...
from __future__ import unicode_literals from itertools import groupby from django.contrib.postgres.fields import JSONField from django.db import models from witio import splitwise from witio import stringops import re import json class RegisteredUser(models.Model): class Meta: verbose_name = 'Registe...
""" Train a policy network on CartPole-v0 using deep deterministic policy gradient (DDPG) """ from __future__ import division, print_function from collections import deque from keras.models import Model from keras.layers import Dense, Input, Add, BatchNormalization, Activation, Lambda from keras.optimizers import Ada...
""" Displaying eigenmodes of vibration using ``warp_by_vector`` ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This example applies the ``warp_by_vector`` filter to a cube whose eigenmodes have been computed using the Ritz method, as outlined in Visscher, <NAME>., <NAME>, <NAME>, et <NAME>. "On the normal...
import numpy as np import os import cv2 import math import imageio from tqdm import tqdm from PIL import Image from functional.motion import normalize_motion_inv, trans_motion_inv from functional.utils import ensure_dir def interpolate_color(color1, color2, alpha): color_i = alpha * np.array(color1) + (1 - alpha) ...
#Run with L371 False and then again with True from qiskit import QuantumRegister, ClassicalRegister from qiskit import QuantumCircuit import numpy as np import math from qiskit.circuit.library.standard_gates import RYGate import os os.environ['KMP_DUPLICATE_LIB_OK']='True' ### Parameters ### events = 2000 # 100000...
# Copyright (C) 2006-2010 Canonical Ltd # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distribute...
#!/usr/bin/env python3.7 print("Loading Python modules for car_control. Please be patient.") import rcpy, datetime, time, math #import pygame from rcpy.servo import servo1 from rcpy.servo import servo3 #from rcpy.button import modeAI, pauseAI from rcpy.button import mode, pause from rcpy import button from rcpy.led imp...
""" Created by <NAME> on January 14, 2020 This is an implementation of the paper IMITATION LEARNING FROM VISUAL DATA WITH MULTIPLE INTENTIONS Tamar et. al. """ import torch import torch.nn as nn # from torch.distributions import RelaxedOneHotCategorical import numpy as np from torch.autograd import Variable # from uti...
import networkx as nx import numpy as np import math import subprocess import socket import os import re import sys import threading import time import matplotlib.pyplot as plt from functools import wraps from pathlib import Path import errno HOME = f'{str(Path.home())}/regtest' print(HOME) # Decorator that adds iden...
import logging from collections import OrderedDict, defaultdict from wazimap.models.data import DataNotFound from wazimap.data.utils import ( collapse_categories, calculate_median, calculate_median_stat, group_remainder, get_stat_data, percent, current_context, dataset_context, merg...
""" Commonly used utils: evaluation metrics e.g. similarity, AUC, AP@k, MAP@k graph related operation testing data generator file I/O visualization etc... by <NAME> """ import time import numpy as np from scipy import sparse import pickle import networkx as nx # -----------------------------------------------------...
import os import sys import time import h5py import hdf5plugin from blimpy import utils def write_to_hdf5(wf, filename_out, f_scrunch=None, *args, **kwargs): """ Copy the header and the selected data matrix subset from the input file to the output HDF5 file. Check the heavy flag to decide how to write the...
# @author <NAME> # @license MIT # @see github.com/michaelhogg/sublime-file-infobar import datetime # docs.python.org/2.6/library/datetime.html import os # docs.python.org/2.6/library/os.html import sublime # sublimetext.com/docs/2/api_reference.html#sublime import sublime_plugin # sublimetext.c...
from numpy import hstack, vstack, atleast_1d, cumsum, asarray, zeros, ndarray,\ prod, ones, copy, nan, flatnonzero, array_equal, asanyarray#, int64 from nonOptMisc import scipyInstalled, Hstack, Vstack, Find, \ isspmatrix, SparseMatrixConstructor, DenseMatrixConstructor import numpy as np #from oologfcn import OpenOpt...
import gzip import os import re import sys class MolBlcokElements: MolName = "MolName" Software = "Software" NumOfAtoms = "NumOfAtoms" MolMiscNumbers = "MolMiscNumbers" #TODO MiscNumbers = "MiscNumbers" # TODO NumOfBonds = "NumOfBonds" Atoms = "Atoms" Bonds = "Bonds" Properties = "Properties" Version = "Vers...
from posixpath import splitext import torch from torch.utils.data import Dataset import torchvision import os import glob import copy import six import numpy as np import fmr_mesh as mesh import fmr_transforms as transforms from register_util import angle_of_R from im2mesh.data.transforms import gen_randrot, apply_tr...
# create maps from sqlays import export_sql, import_sql from iscays import isc_xlsx from mpl_toolkits.basemap import Basemap from mpl_toolkits.basemap import maskoceans # brew install geos # pip3 install https://github.com/matplotlib/basemap/archive/master.zip # for DIVA tools # https://github.com/gher-ulg/DivaPythonTo...
""" Tool used for plotting various things throughout the project. Helpful for navigating the BMTK h5 structuring. """ import matplotlib.pyplot as plt import numpy as np import h5py import scipy.signal as s def get_key(group, index=0): """From the list of the keys of the given group, returns the key at the giv...
#!/usr/bin/env python # ENCODE DCC filter wrapper # Author: <NAME> (<EMAIL>) import sys import os import argparse from encode_lib_common import ( copy_f_to_dir, log, ls_l, mkdir_p, rm_f, run_shell_cmd, strip_ext, strip_ext_bam) from encode_lib_genomic import ( locate_picard, remove_chrs_from_bam, samstat,...
# 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 in...
"""This module contains WebServer class TODO DOC """ import os import sys import asyncio import logging from aiohttp import web from aiohttp import WSCloseCode import aiohttp_jinja2 import jinja2 import json import weakref import trunklucator.const.msg as const_msg import trunklucator.protocol.dto as dto logger ...
from argparse import ArgumentParser import numpy as np import librosa import pickle import os from loader import setup_ada_training_data, setup_ada_testing_data from utils import save_pkl, load_pkl def parse_arguments(): parser = ArgumentParser() parser.add_argument("--seed", type=int, default=42, ...
from flask import Flask, render_template, request,url_for,redirect import numpy as np import pickle import os import glob import re import sys #from tensorflow.keras.applications.imagenet_utils import preprocess_input, decode_predictions #from tensorflow.keras.models import load_model #from tensorflow.keras....
import csv import gzip import os import click import pandas as pd import numpy as np import requests from .transcoding.names.eurostat import col, var from .transcoding.metadata import dtype from .utils import download_and_parse_gzip_csv eurostat_gz_url = ( "https://ec.europa.eu/eurostat/estat-navtree-portlet-pro...
#!/usr/bin/env python # coding: utf-8 # In[18]: import glfw from OpenGL.GL import * import OpenGL.GL.shaders import numpy as np import sys import math import transformations as tr import basic_shapes as bs import scene_graph as sg import easy_shaders as es # A class to store the application control class Controll...
"""Bindings for the Barnes Hut TSNE algorithm with fast nearest neighbors Refs: References [1] <NAME>, L.J.P.; Hinton, G.E. Visualizing High-Dimensional Data Using t-SNE. Journal of Machine Learning Research 9:2579-2605, 2008. [2] <NAME>, L.J.P. t-Distributed Stochastic Neighbor Embedding http://homepage.tudelft.nl/19...
import os import sys import cv2 import glob import time import uuid import random import numpy as np from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * class Gui(QMainWindow): cancelelapse = pyqtSignal() cancelecal = pyqtSignal() timelapsing = False def __init__(...
# see "License Acknowledgement" for accrediton to original source code # adapted from florian, who extended from the SciPy 2015 Vispy talk opening example # https://github.com/flothesof/LiveFFTPitchTracker ### NOTES ### import sys import threading import atexit import pyaudio import numpy as np import matplotlib matp...
from __future__ import division import ctypes import numpy as np import os import signal import sys import time import logging import copy import sbndprmdaq.digitizer.atsapi as ats class ATS310Exception(Exception): """ Exception class for ATS310. """ def __init__(self, logger, message): ''' ...
# @Author: guanwanxian # @Date: 1970-01-01T08:00:00+08:00 # @Email: <EMAIL> # @Last modified by: guanwanxian # @Last modified time: 2017-03-26T19:39:24+08:00 from .Transformations import superimposition_matrix import numpy as np class Point3D(): """ 3D Object Class """ def __init__(self, x, y, z): ...
import os from random import shuffle, seed from rdkit import Chem import pandas as pd from tqdm import tqdm from PyFingerprint.All_Fingerprint import get_fingerprint import torch from SubGNN import config from . import config_prepare_dataset as pdconfig # allowable node and edge features allowable_features = { ...
""" Module to define `Slits` classes. The SLAC EPICS motor record contains an extra set of records to abstract four axes into a Slits object. This allows an operator to manipulate the center and width in two dimensions of a small aperture. The classes below allow both individual parameters of the aperture and the Slit...
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
import json try: from urllib.parse import urlparse except ImportError: # Fall back to Python 2 from urlparse import urlparse import logging from .exceptions import MsalServiceError logger = logging.getLogger(__name__) # Endpoints were copied from here # https://docs.microsoft.com/en-us/azure/active-directo...
import json import logging from django.contrib import auth, messages from django.contrib.auth.decorators import login_required from django.db import transaction from django.http import HttpResponseForbidden from django.shortcuts import get_object_or_404, redirect from django.template.response import TemplateResponse f...
""" Tests for finder. """ from django.template.response import TemplateResponse from django.test import RequestFactory from mock import Mock, patch from tests import case class FinderDecoratorTest(case.DBTestCase): """Tests for the finder view decorator.""" @property def finder(self): """The d...
#!/usr/bin/env python # coding=utf-8 from __future__ import absolute_import from __future__ import print_function, division import errno import os import random from datetime import datetime import numpy as np def PrintWithTime(string=None): if string is None: print("{0}".format(datetime.now().strftime(...
import os from collections import namedtuple from functools import partial from logging import Logger from typing import Any, Dict, List, Optional, Type, TypeVar, Union import requests from flask_injector import request from injector import inject from werkzeug.exceptions import NotFound from husky_directory.app_conf...
# -*- coding: utf-8 -*- # This file is part of the pyMOR project (http://www.pymor.org). # Copyright Holders: <NAME>, <NAME>, <NAME> # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) # This file was originally based upon sphinxcontrib-napoleon # Copyright 2013 <NAME> from collections impor...
import argparse from configparser import ConfigParser import json import os import re import sys from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Union import urllib.parse import requests from . import git from . import publishthing # noqa from .ut...
# -*- coding: utf-8 -*- """ Functions for degeneration of a brain object """ import random import networkx as nx import numpy as np from maybrain import constants as ct def random_degenerate(brain, weight_loss=0.1, edges_removed_limit=1, thresh_limit=None, pc_limit=None, weight_loss_limit=Non...
import pickle import logging import os import sys import torch import numpy as np import utils def save_checkpoint(name, path, model, optim, log): if os.path.exists(path) == False: os.makedirs(path) torch.save({ 'model_state_dict': model.state_dict(), 'optim_state_dict': optim.state_...
# Copyright 2017 <NAME>.P. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software...
from mat import Mat from vec import Vec import math ## Task 1 def identity(labels = {'x','y','u'}): ''' In case you have never seen this notation for a parameter before, it defines the default value of labels to be {'x','y','u'}. You should write your procedure as if it were defined 'def identity...
import os import pathlib from dataclasses import dataclass from typing import Union, Optional, Dict import numpy as np import pandas as pd import xarray as xr class CommonDataMethods: def __init__(self): self.data = None @staticmethod def default_path_and_name(path, name='subsurface_data.nc', ):...
import tempfile from typing import Callable from typing import Generator from typing import TYPE_CHECKING import numpy as np import pytest import tensorflow as tf import tensorflow_hub as hub import bentoml from tests.utils.helpers import assert_have_file_extension if TYPE_CHECKING: from bentoml._internal.extern...
import os import json from tornado.gen import coroutine from tornado.websocket import websocket_connect from user import UserConst class ChalConst: STATE_AC = 1 STATE_WA = 2 STATE_RE = 3 STATE_TLE = 4 STATE_MLE = 5 STATE_CE = 6 STATE_ERR = 7 STATE_JUDGE = 100 STATE_STR = { ...
import sys import os import torch import random import math from sklearn.utils import shuffle from sklearn.metrics import f1_score import torch.nn as nn import numpy as np def evaluate(dataCenter, ds, graphSage, classification, device, max_vali_f1, name, cur_epoch): test_nodes = getattr(dataCenter, ds+'_test') val...
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from direct.distributed.MsgTypes import * from otp.ai.MagicWordGlobal import * from otp.otpbase import OTPGlobals from datetime import datetime from direct.distributed.PyDatagram import PyDatagram i...
"""Conway's Game of Life problems""" from problems import Problem, register, get_problems from typing import List @register class Oscillators(Problem): """Oscillators (including some unsolved, open problems) Find a pattern in [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) ...
import os import numpy as np import time import sys import paddle import paddle.fluid as fluid from resnet import TSN_ResNet import reader import argparse import functools from paddle.fluid.framework import Parameter from utility import add_arguments, print_arguments parser = argparse.ArgumentParser(description=__doc...
#!/usr/bin/env python3 import serial import binascii import argparse PORT_RELAY1 = "/dev/ttyRELAY1" BAUDRATE_RELAY1 = 115200 PORT_RELAY2 = "/dev/ttyRELAY2" BAUDRATE_RELAY2 = 115200 TIMEOUT = 1 def addcrc(data): crc_table=[ 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, 0...
# coding=utf-8 import random __author__ = "HibernantBear" class GeneticAlgorithm(object): """ 遗传算法 """ def __init__(self): self.individuals = [] # 个体的集合 self.individual_number = 0 self.best_individual_ever = None # 史上最好的个体 self.cross_func = self._default_cross_func ...
# Web app packages import streamlit as st import boto3 import joblib # Data science packages import numpy as np import pandas as pd from sklearn.cluster import KMeans from random import shuffle # Sidebar panel st.sidebar.markdown( ''' # BetterReads *Curated crowdsourcing of book reviews* --- ...
# coding=utf-8 """ Using OpenMesh to compute normals for lighting effects. """ import glfw from OpenGL.GL import * import numpy as np import sys import os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import openmesh import grafica.transformations as tr import grafica.basic_shapes ...
# -*- coding: utf-8 -*- """HighRes3DNet implemented in TensorFlow. Implementation is influenced by [NiftyNet](http://www.niftynet.io/). Reference --------- <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>. (2017) On the Compactness, Efficiency, and Representation of 3D Convolutional Networks: Brain Parcellation as...
# Copyright 2020 The Trieste Contributors # # 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 torch import torch.nn as nn from torch.utils.data import DataLoader from torch.utils.data import Dataset from tqdm import tqdm, trange from torch.optim import Adam from tensorboardX import SummaryWriter import pandas as pd from collections import OrderedDict, Counter import os, re from models import RNN, CNN d...
import functools import numpy as np import torch from inspect import getfullargspec def array_converter(to_torch=True, apply_to=tuple(), template_arg_name_=None, recover=True): """Wrapper function for data-type agnostic processing. First converts in...
""" Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distri...
""" This module contains the basic components of dataflow, including Example, Feature, MiniBatch and DataFlow classes. """ import abc import collections import json import random from typing import Dict import numpy as np from relogic.logickit.base import utils class Example(object, metaclass=abc.ABCMeta): """B...
#!/usr/bin/env python3 # # Access Sentinel-6 MF Data using a script # This script shows a simple way to maintain a local time series of Sentinel-6 # data using the # [CMR Search API] # (https://cmr.earthdata.nasa.gov/search/site/docs/search/api.html). # It downloads granules the ingested since # the previous run to ...
from rest_framework import serializers from rest_framework.serializers import SerializerMethodField from .models import User,Profile,InviteOnly from django.contrib import auth from rest_framework.exceptions import AuthenticationFailed,ValidationError from django.contrib.auth.tokens import PasswordResetTokenGenerator fr...
#import modules from sqlite3.dbapi2 import PARSE_COLNAMES from main import * import bcrypt from tkinter import * from datetime import datetime import json import sqlite3 from sqlite3 import Error def create_bcrypt_hash(password): # convert the string to bytes password_bytes = password.encode() # generate ...
# MPR121 capacitive touch breakout driver. Port of Raspberry Pi/BeagleBone Black # code from: https://github.com/adafruit/Adafruit_Python_MPR121/ # Author: <NAME> # License: MIT License (https://opensource.org/licenses/MIT) """ `adafruit_mpr121` ==================================================== CircuitPython driv...
''' This is a pasted boiler plate for reference. It is best to use an IDE like PyCharm or VSCode to edit these documents. I added them to our project as boiler plates so that I would have offline access to study them. ''' # Edit made to orginal Adafruit Driver to enable it to use the SMBus module # instead of Adafrui...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from cbalancer import app from flask import render_template, request from datetime import datetime from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database import psycopg2 import pandas as pd from model import * from bokeh.plot...
import utility from dag.priorityset import PrioritySet import lmdb import struct import sqlite3 import math import res.pinyin_data kLMDB = 'LMDB' kRAWDATA = 'RAWDATA' kGB18030 = 'gb18030' Database_Type = kLMDB LMDB_FILE = './result_files/transition.mdb' PY_DATABASE = './result_files/emission.db' GRAM1FILE = './result...
''' This code reads a checkpoint file and reads from the test dataset to plot ''' import sys import torch import matplotlib.pyplot as plt from labellines import labelLines import os.path as osp import glob from MultiLayerLinear import MultiLayerLinear from gnn_model import GnnModel from train_gnn import get_lr im...
from compiler.ast import * import copy import pickle import logging import os logger = logging.getLogger('ExprManip.Differentiation') import AST from AST import strip_parse import Simplify import Substitution _ZERO = Const(0) _ONE = Const(1) # Record the version of the Differentiation.py file we loaded. __version_lo...
# source: https://github.com/rionbr/CANA/pull/5/files import os, re from itertools import product def CC_bool_expr2cnet(expression_all_file, external_node_file, outputfile): '''Convert ONE network in Cell Collective Boolean expression format to a cnet file. Args: expression_all_file (string) : the loc...
import struct import socket from os import urandom from string import printable OPCODE_CONTINUATION = 0x0 OPCODE_TEXT = 0x1 OPCODE_BINARY = 0x2 OPCODE_CLOSE = 0x8 OPCODE_PING = 0x9 OPCODE_PONG = 0xA CLOSE_NORMAL = 1000 CLOSE_GOING_AWAY = 1001 CLOSE_PROTOCOL_ERROR = 1002 CLOSE_NOACCEPT_DTYPE = 1003 CLOSE_INVALID_DATA...
import h5py import numpy as np import pandas as pd import random from tqdm import tqdm from sklearn.preprocessing import Imputer, Normalizer def load_data(data_path, split=None, label=None, protein_name_list=None, sample_size=None, features_list=None, mode=None): input_fo = h5py.File(data_path, 'r') if spli...
# Copyright 2017. <NAME>. 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 list of conditions and the following # dis...
# Copyright 2019 Canonical 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 agreed to in writing, s...
from tkinter import * import time import threading def wait_func(timer=1): time.sleep(timer) global dist def run(list2=['A','B','C', 'D','E'], dist=[[0, 74, 4109, 3047, 2266],[74, 0, 4069, 2999, 2213],[4109, 4069, 0, 1172, 1972], [3047, 2999, 1172, 0, 816],[2266, 2213, 1972, 816, 0]],cities=[0,1,2,3,4,5,6]): ...
import csv from io import StringIO from enum import Enum def load_csv(input_file, col_act, col_pred, col_weight=None, delimiter=",", quotechar="\"", header=True): """ Loads the actual, predicted and weight (if present) values from the CSV file as column lists. :param input_file: the CSV file to load actu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import scipy.stats from .base import BaseChromosome, BaseGene from .gene import * from .utils import * class ArrayChromosome(np.ndarray, BaseChromosome): element_class = BaseGene def __new__(cls, array, gene=None): if gene is None: ...
#!/usr/bin/env python3 """ Toolkit to manage Fritz Internet Router to parse it's device logs and send notifications via Gmail. You can use something else to send the Gmail notification. """ # Import modules import os import pathlib as pl import sys import notifiers import classes import dotenv import fritzconnection ...
from subprocess import Popen, PIPE, TimeoutExpired import importlib import importlib.machinery import time import datetime import signal import os.path import os import inspect import re import logging import logging.handlers try: import serial has_serial=True except ImportError: has_serial=False import thr...
# Copyright 2021, 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 or agreed to in writing...
from os import path import h5py import torch from torch import nn from torch import cuda from collections import Counter import numpy as np from preprocess.preprocess import * def complete_opt(opt): if 'base' in opt.bert_type: opt.hidden_size = 768 elif 'large' in opt.bert_type: opt.hidden_size = 1024 if hasat...
# Project: hardInfo # Author: <NAME> # Date Started: March 18, 2022 # Copyright: (c) Copyright 2022 <NAME> # Module: model/LsUsb.py # Date Started: March 23, 2022 # Purpose: Store and provide API for Linux lsusb command. # Development: # Arguments to include ...
from overrides import overrides import torch import torch.nn as nn import torch.nn.functional as F from claf.decorator import register from claf.model.base import ModelWithTokenEmbedder from claf.model.reading_comprehension.mixin import SQuADv1 from claf.modules import attention, initializer from claf.modules import f...
"""Contains the models that will be used to define our database tables. """ from flask import Markup from app import db, whooshee, login from datetime import datetime from slugify import slugify from markdown import markdown from markdown.extensions.codehilite import CodeHiliteExtension from markdown.extensions.extra i...
""" The main module of symmetric. """ import sys import json import bisect import flask import symmetric.logging import symmetric.constants import symmetric.endpoints import symmetric.helpers import symmetric.errors import symmetric.openapi.utils import symmetric.openapi.docs class _SymmetricSingleton(type): "...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from photo.models import Photo from photo.models import Images import json import os from django.conf import settings from djan...
from types import FunctionType import warnings import numpy as np from astropy.units import Quantity, rad from astropy.table import Table __all__ = ['ppv_catalog', 'pp_catalog'] def _qsplit(q): """Split a potential astropy Quantity into unit/quantity""" if isinstance(1 * q, Quantity): return q.unit,...
# -*- coding: utf8 -*- # 输入:微博热门 from __future__ import unicode_literals import re import requests import sys from bs4 import BeautifulSoup reload(sys) sys.setdefaultencoding('utf8') WORDS = ["WEIBORESOU"] SLUG = "weibo_resou" user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = {'User-Agent': user_...