text stringlengths 3.07k 12.6k |
|---|
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 5 21:14:36 2018 [V1]
Edited on 21/10/9102 to reformulate the code in Pytorch style. [V2]
@author1: <NAME>
@author2: <NAME>
"""
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
import pdb
import datetime
"[ATTENTION] There are total 5 spaces ... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Variant of the resnet module that takes cfg as an argument.
Example usage. Strings may be specified in the config file.
model = ResNet(
"StemWithFixedBatchNorm",
"BottleneckWithFixedBatchNorm",
"ResNet50StagesTo4",
... |
#########################################################################
# Dicomifier - Copyright (C) Universite de Strasbourg
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for... |
#!/usr/bin/env python
#
# 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,
# distribute, subl... |
import sys
import os
from multiprocessing import Pool
import string
import random
import shelve
import numpy as np
import scipy.sparse as sparse
import pickle as pickle
from collections import defaultdict, namedtuple
import xml.etree.ElementTree as ET
from Parsing import *
import re
def noRepresent(w):
r... |
'''
***********************************************************
This script setups the vertical and spectral grids.
***********************************************************
'''
from __future__ import division, print_function, absolute_import
import numpy as np
from . import VerticalStructure
from . import Thermodyna... |
# Copyright 2014 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 agr... |
# coding: utf-8
#
#
#
#
import os
import time
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import soundfile as sf
from joblib import Parallel, delayed
from model_utils.utils import PESQ, STOI, SDR
from model_utils.utils import AudioReBuild, AverageMeter
from model_utils.model import FullyCNNSEModel,... |
from bs4 import BeautifulSoup
import requests
import argparse
def geo_match(latitude, longitude, search_radius='1000'):
"""
Takes in a certain latitude and longitude coordinate and returns the nearest stationary NOAA buoy available on
the National Data Buoy Center website. Latitude and longitude should be... |
import numpy as np
class FieldArray(object):
"""``FieldArray`` is the collection of ``Instance``s of the same field.
It is the basic element of ``DataSet`` class.
:param str name: the name of the FieldArray
:param list content: a list of int, float, str or np.ndarray, or a list of list of one, or a n... |
#!/usr/bin/python2
import os
import sys
from PyQt4 import QtCore, QtGui, uic
from PyQt4.QtGui import QPixmap, QFileDialog
import pickle
import cv2 as cv
import exec_thread
fileDir = os.path.dirname(os.path.realpath(__file__))
os.system("export PATH=/home/ivan/torch/install/bin:$PATH")
PROBABILITY_THRESHOLD = 0.8
fif... |
from datetime import timedelta
import re
from math import floor
from ebu_tt_live.strings import ERR_TIME_NEGATIVE, \
ERR_TIME_FRAMES_OUT_OF_RANGE, \
ERR_TIME_FRAME_IS_DROPPED
from ebu_tt_live.errors import TimeNegativeError, TimeFormatError
class ISMPTEtoTimedeltaConverter(object):
def __init__(self):
... |
import multiprocessing as mp
import numpy as np
import pickle
import datetime
import head_to_head
import sys
def write_stdout():
sys.stdout = open(str(datetime.datetime.today()) + ".log", "w")
def write_stderr():
sys.stderr = open(str(datetime.datetime.today()) + ".err", "w")
# cofigurations
RANK = 10
SAMP... |
import json
import uuid
import itertools
import time
import logging
logging.basicConfig(level=logging.WARNING) # set from WARNING to INFO for more output
MAX_VALUES_PER_INSERT = 1000
def insertUnitValues(sql, unit):
if unit and "label" in unit:
id_of_new_unit = str(uuid.uuid4())
label ... |
import sys
import requests
import pycurl
import pprint
import json
import time
import autoscaler.network.setup_topology as setup_topo
import autoscaler.util as util
import autoscaler.conf.engine_config as eng
import autoscaler.network.network_util as net_util
def ovsdb_request(switch_dpid, switch_ip):
ovsdb_data ... |
#!/usr/bin/env python3
import kubernetes
from kubernetes.client.rest import ApiException
import threading
import logging
import os
FORMAT = "%(levelname)s: %(asctime)s [%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(format=FORMAT)
log = logging.getLogger(__name__)
log.setLevel(logging... |
# common functions used across xyz, adj and apu pynadjust modules
import datetime
import shapefile
import os
def write_prj(file_name, ref_frame=None):
"""
Function to write shape projection files. GDA94 and GDA2020 reference frames are supported. Nothing is written
for other reference frames.
:param ... |
import tilepack.outputter
import requests
import zipfile
import argparse
import os
import multiprocessing
import time
import random
import traceback
import mercantile
import logging
import csv
import gzip
sess = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=200)
sess.mou... |
__author__ = "MetaCarta"
__copyright__ = "Copyright (c) 2006-2008 MetaCarta"
__license__ = "Clear BSD"
__version__ = "$Id: DBM.py 444 2008-03-19 01:35:35Z brentp $"
from FeatureServer.DataSource import DataSource
from FeatureServer.DataSource import Lock
from FeatureServer.Service.Action import Action
import anydbm
... |
import numpy as np
import pandas as pd
import itertools
def build_deck():
numbers=list(range(2,15))
suits = ['H','S','C','D']
deck = []
for i in numbers:
for s in suits:
card = s+str(i)
deck.append(card)
return deck
def combinations(arr, n):
arr = np.asarray(arr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Assumptions:
- ok to break execution if any of product fetching fails (all or nothing)
- ok to add extra logging to Stderr
- ok to skip nice help and options (otherwise would use http://click.pocoo.org/)
- ok with Very basic tests
- ok with python>=3.4
"""
import re
imp... |
import tensorflow.python.keras.layers as kl
import tensorflow.python.keras.regularizers as kr
from functools import reduce, wraps
def resblock_body(x, num_filters, num_blocks):
'''A series of resblocks starting with a downsampling Convolution2D'''
# Darknet uses left and top padding instead of 'same' mode
... |
# Copyright (c) 2022 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... |
"""
Invoice resource, it includes the class Resource, a request
class to create the resource and a class to represent an
Invoice Item.
"""
import datetime as dt
from typing import ClassVar, Dict, List, Optional, Union, cast
from pydantic import BaseModel
from pydantic.dataclasses import dataclass
from ..types impor... |
"""Code for reading the haplotyping table information.
This contains the informative positions for haplotyping of calls.
"""
import os
import shlex
import subprocess
import tempfile
import typing
import attr
import json
from logzero import logger
from .blast import BlastMatch
from .common import call_variants, norm... |
"""Parser for BLE advertisements used by Passive BLE monitor integration."""
import logging
import subprocess
from .atc import parse_atc
from .brifit import parse_brifit
from .govee import parse_govee
from .kegtron import parse_kegtron
from .miscale import parse_miscale
from .inode import parse_inode
from .xiaomi impo... |
from torch import nn
from einops import rearrange
from tsl.utils.parser_utils import ArgParser
from tsl.nn.blocks.encoders import ConditionalBlock
from tsl.nn.blocks.encoders.rnn import RNN
from tsl.nn.blocks.decoders.mlp_decoder import MLPDecoder
class RNNModel(nn.Module):
r"""
Simple RNN for multi-step f... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class VGG16(nn.Module):
def __init__(self):
super(VGG16, self).__init__()
self.layers = self._make_layers()
def forward(self, x):
y = self.layers(x)
return y
... |
#-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2011 EOX I... |
# -*- coding: UTF-8 -*-
"""
..
---------------------------------------------------------------------
___ __ __ __ ___
/ | \ | \ | \ / the automatic
\__ |__/ |__/ |___| \__ annotation and
\ | | | | \ ... |
#
# author: <NAME>
#
# Copyright 2010 University of Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import numpy as np
### VISUALIZE HIERARCHICAL HISTOGRAMS AND CUTS
# generte tree structures for visualization
def find_cuts(list_of_mp_trees):
"""
This function is used to generate input for function in flowMP_visualize.print_cuts_on_hist.
"""
if len(list_of_mp_trees) == 0:
return None
mp_... |
# Copyright (c) 2021 <NAME>. All rights reserved.
import asyncio
import ssl
import logging
from typing import Optional
from urllib3 import connection
from urllib3.util import url
import websockets.legacy.client as websockets
from websockets.typing import Data
from remoteweb import (
app,
crypto,
exception... |
#!/usr/bin/env python
# coding: utf-8
# In[25]:
#!/usr/bin/env python
#Imports for helper functions
from sklearn.preprocessing import MinMaxScaler
from sklearn import svm
import pandas as pd
import numpy as np
from io import StringIO
import sys
import ast
import json
import PySimpleGUI as sg
f... |
import os, json
import random
import numpy as np
from mrcnn import model as modellib, utils, visualize
from PIL import Image, ImageDraw
from samples.coco import coco
import skimage
# Pocet tried v datasete
NUM_CLASSES = 1
# Relativna cesta k .h5 suboru s vahami
WEIGHTS_FILE = None
# Relativna cesta k JSON anotaciam ... |
import numpy as np
from baselines.common.runners import AbstractEnvRunner
class Runner(AbstractEnvRunner):
"""
We use this object to make a mini batch of experiences
__init__:
- Initialize the runner
run():
- Make a mini batch
"""
def __init__(self, *, env, model, nsteps, gamma, gamma_... |
import json
import os
import re
import time
import uuid
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from common.utils.util_date import time_stamp_to_date
from common.utils.util_store_path import file_store_path... |
# ============== SemEval-2015 Task 1 ==============
# Paraphrase and Semantic Similarity in Twitter
# ===================================================
#
# Author: <NAME> (UPenn <EMAIL>)
#
# This is the unofficial evaluation script.
# We may change or add some metrics (e.g. area under P/R curve) for the final eval... |
import numpy as np
from .. import evaluate as ev
class Null(object):
def __init__(self, *args, **kwargs):
self.default_cache = 'feature-cache'
def __call__(self, g, n1, n2=None):
return self.compute_features(g, n1, n2)
def write_fm(self, json_fm={}):
return json_fm
def compu... |
from easymunk import Vec2d, Arbiter, Body, Vec2d, ShapeFilter, pyxel as phys
import pyxel
import random
FPS = 30
WIDTH, HEIGHT = 256, 196
SCREEN = Vec2d(WIDTH, HEIGHT)
class Particles:
def __init__(self, space):
self.particles = []
self.space = space
def draw(self, camera=pyxel):
for... |
import math
from typing import Text, List, Mapping, Optional, Union
import tensorflow as tf
from .moving_grid_attn_node import MovingGridAttnNode
from .. import InfoNode, TargetResponsiveNode
from ...utils import types as ts
from ...utils import keys
class SoftMovingGridAttnNode(MovingGridAttnNode):
"""Differen... |
# MIT License
# Copyright (c) 2020 ffreemt
# 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, publis... |
# Copyright (c) Gorilla-Lab. All rights reserved.
import os
import paramiko
import argparse
default_mlx_path = os.path.join(os.path.dirname(__file__),
"2_simplify_mesh.mlx")
load_file = "mesh_gt.ply"
save_file = "mesh_gt_simplified.ply"
class Transfer:
def __init__(self, server_ip... |
'''Train CIFAR10 with PyTorch.'''
from __future__ import print_function
# from torch.utils.tensorboard import SummaryWriter
from torch.autograd import Variable
from cutout import Cutout
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import torch.backends.cudnn as cudnn
from sam import... |
import json
from collections import defaultdict
from dataclasses import dataclass, field
from functools import total_ordering
from pathlib import Path
from re import compile, search
from typing import Any, DefaultDict, List
from urllib.request import urlretrieve
from bs4 import BeautifulSoup as Soup
out_dir = Path("/... |
from abc import ABC, abstractmethod
from functools import cached_property
from typing import Tuple, Optional, List, Callable
import ConfigSpace as CS
import numpy as np
import ConfigSpace.hyperparameters as CSH
from matplotlib import pyplot as plt
from pyPDP.algorithms import Algorithm
from pyPDP.algorithms.ice impor... |
import os
from envs.simulation.robot import SimRobot
from models.stage1 import Seg
from models import YoungNet, State, SelectNet
import utils
import cv2
import numpy as np
import torch
from envs.data import Data as TextData
import random
from itertools import count
from envs.data import Instruction
import torch.nn.func... |
"""
reads irs 990 forms
writes three files
- section_a.csv: employee data in section a (part ii)
- schedule_j.csv: employee data in schedule j (part ii)
- version_summary.csv: schema version of the form
"""
import requests
from parse_utils.page_parser import ItemExtractor
from lxml import html
import sys
import json
i... |
from collections import Counter
import sys
import json
from multiprocessing import Process
from time import sleep
import os
import logging
from flask import Flask, g, request, jsonify, send_from_directory, abort
from models import get_database, create_tables
from models import Bite, Apple
from models import STATUS_PROC... |
# -*- coding: utf-8 -*-
from django.utils.safestring import mark_safe
from django.db import models
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.contrib.auth.models import AbstractBaseUs... |
"""
资源调度,job sechdule、nni SLI/SLO
1. 中等规模(1500pod,100node)下jobmanager调度多用户任务的可靠性
2. 批量用户在线的负载情况下任务调度的sechdule过程的响应效率
"""
import locust.stats
locust.stats.CONSOLE_STATS_INTERVAL_SEC = 3
from locust import TaskSet, task, between, User
from locust.contrib.fasthttp import FastHttpUser
from locust import events
import ... |
import itertools
import math
from typing import Tuple, TypeVar
import einops
import torch
from torch import Tensor
from transformers.models.gpt2.modeling_gpt2 import GPT2Attention
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoSelfAttention
from transformers.models.gptj.modeling_gptj import GPTJAttenti... |
"""Advent of Code 2015: Day 21"""
from __future__ import annotations
from dataclasses import dataclass, field
from itertools import combinations
from typing import Callable, Dict, Generator, List, Optional, Protocol
PLAYER_STATS = {
"name": "Player",
"max_hitpoints": 50,
}
BOSS_STATS = {
"name": "<NAME>"... |
import pandas as pd
import numpy as np
import os
import itertools
import torch
from torch import nn
import torch.nn.functional as F
from tqdm import tqdm_notebook
import multiprocessing
from .resnet2 import ResNet_G
from .icnn import View
from PIL import Image
from .inception import InceptionV3
from tqdm import tq... |
import os
import yaml
from pathlib import Path
from typing import Optional
from discord import Embed
from discord.ext.commands import Cog, Context, group
from discord.guild import Guild
from incarn.bot import IncarnBot
class HomeRules(Cog):
"""Commands for managing server's homerules."""
@group(name="homer... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import math
r"""
This class has been developed to accomodate various spatial convolution graph algorithms
Initial Graph convolution network, Graph Attention network and GraphSage has been implemented
User ... |
from types import SimpleNamespace
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
import ipywidgets as widgets
from . import consumer_old as consumer
###########
# figure #
###########
def _figure(par,p1,p2,I,alpha,beta,gamma):
par.p1 = p1
par.p2 = p2
par.I = I
par.alp... |
import re
from . import registry, version
from .base import _DomainObject
from .exceptions import DuplicateRegistrationError
from .properties import (
ListProperty, ObjectReferenceProperty, ReferenceProperty, _validate_type,
)
from .utils import PREFIX_21_REGEX
def _validate_ref_props(props_map, is_observable20=... |
""" Controller test module """
from unittest import mock
import pytest
from constants import FEVersions
from controller import (
handler,
combo_box_handler,
browse_handler,
RandomizerHandler,
_get_filters,
)
from rom_editors.stat_editor import InvalidConfigError
from versions import VERSION_LOCAT... |
"""This module contains the general information for EquipmentNvmeDef ManagedObject."""
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class EquipmentNvmeDefConsts:
INT_ID_NONE = "none"
M_SWITCH_SAS_MIXING_SUPPORTED_FALSE = "false"
M... |
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import openpyxl
import os
import pathlib
import spacy
from itertools import chain
import argparse
import pandas as pd
import numpy as np
from commo... |
#
# (C) Copyright 2000- NOAA.
#
# (C) Copyright 2000- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of ... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# Copyright (c) 2016, Battelle Memorial Institute
# 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. Redistri... |
import pandas as pd
import random
import numpy as np
from sklearn.preprocessing import LabelEncoder
import seaborn as sns
import matplotlib.pyplot as plt
import pickle
from preprocess import process_csv_file
# function to classify datetime to weekday/weekend
def is_weekend(transaction_date):
"""computes if date ... |
"""
Load data to big query from mysql in batch mode (all data from a date)
or streaming (load data from a date, wait, and load new data).
* loader.py Date .- Load data from mysql to big query from a day
* loader.py Date online .- Load in streamind mode.
* loader.py Date --until_yestarday .- Load all data from
... |
class expando:
pass
class TSSim:
def __init__(self, mult, series, Pmax=None, sign=1, phase=0):
self.mult = mult
self.series = series
self.sign = sign
if Pmax == None:
self.Pmax = 1e100
self.calc_val(0)
def calc_val(self, t):
self.cur_t = t
... |
#!/usr/bin/env python3
'''
lib/task/pool.py
Task pool abstraction. Replacement for `concurrent.futures`.
Defines a task pool class that can be used to run tasks asynchronously.
Most of this logic was taken from pythonfutures:
https://github.com/agronholm/pythonfutures
https://git.io/vdCQ2
'''
from concurrent.future... |
from snorkel.labeling import labeling_function
import numpy as np
from .utils import *
from ..classification import *
"""
:param x: a DataFrame containing all the fields of the input DataFrame for two ethical alternatives
:returns: whether or not to intervene (0 or 1); -1 to abstain
"""
# don't intervene
SAVE_NOINT = ... |
import os
from .common import get_user_client, validate_cluster, \
random_test_name, AWS_SSH_KEY_NAME
import pytest
EKS_ACCESS_KEY = os.environ.get('RANCHER_EKS_ACCESS_KEY', "")
EKS_SECRET_KEY = os.environ.get('RANCHER_EKS_SECRET_KEY', "")
EKS_REGION = os.environ.get('RANCHER_EKS_REGION', "us-east-2")
EKS_K8S_VERS... |
import os, shutil, glob, random, time
def newdir(out_dir):
if os.path.exists(out_dir): shutil.rmtree(out_dir)
os.makedirs(out_dir)
def copy_files_to(files, dst, overwrite=False):
if not os.path.exists(dst):
os.makedirs(dst)
for i, f in enumerate(files):
fn = os.path.basename(f)
f2 = dst + '/' + fn
if os... |
import email
import email.utils
from django.template.loader import get_template
from django.template import Context
from django.core.mail import EmailMessage, send_mail
from detention_notifier.models import Detention, DetentionMailer, DetentionCC, DetentionTo
from academics.models import AcademicYear, Enrollment, Stu... |
from lzwcompressor import LZWCompressor
from name_generator import connect_db, close_db
from headstega import dictionary as coverdictionary
import random
def check_alphabet_lower(s):
if len(s) > 1:
return False
if ord(s) < 97 or ord(s) > 122:
return False
return True
def query_database_name(cnx, s):
cursor ... |
# coding=utf-8
# Copyright 2021 The Deadunits 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 applicable law... |
from posixpath import dirname
from matplotlib.pyplot import plot
import numpy as np
from eit_model.model import EITModel
from eit_model.solver_abc import Solver,RecParams
from typing import Any
from eit_model.data import EITData, EITImage, build_EITImage
from eit_ai.train_utils.workspace import AiWorkspace
from eit_ai.... |
import numpy as np
import torch
from torch import nn, Tensor
from typing import Tuple
from .vcg import to_vcg, to_ecg
class _Augmentation(nn.Module):
def __init__(self, no_op: bool) -> None:
super().__init__()
self._no_op = no_op
class _RandomVCGAugmentation(_Augmentation):
def __init__(self, no_op: bool)... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from phonebook.forms import LoginForm, ContactForm, SearchForm
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from phonebook.model... |
# -*- coding: utf-8 -*-
import time
import os
import csv
from datetime import datetime,timedelta
import tkinter as tk
from tkinter import messagebox as msg
from date_utils import *
from topkeywords_stream import fetchStreamTopKeywords
from topkeywords_deal import fetchDealTopKeywords
class Timer(tk.Tk):
def __init... |
# coding=utf-8
# @Author : zhzhx2008
# @Time : 18-10-8
import os
import warnings
import jieba
import numpy as np
from lightgbm import LGBMClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import GradientBoostingClassifier
from skle... |
import csv
from sqlalchemy.sql.elements import True_
from sqlalchemy.sql.expression import select, and_
from .util import vector_greater_than, uncompressed
import warnings
import time
from oreader.readers import DataSourceError
from sqlalchemy.sql.sqltypes import String, Text
import traceback
from six import next, Iter... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# This code describes how TensoLayerX uses TensorBoard to monitor training.
# TensorLayerX uses tensorboardX to monitor the training situation, so it is necessary to install tensorboardX, The version of tensorboardX installed needs to match with TensorFlow.
# tensorboardX repo... |
from __future__ import absolute_import
import datetime
import logging
import os
import re
import sys
from flask import Flask, json
from flask_cors import CORS # debdeps: python3-flask-cors
# python3-flask-cors has unnecessary dependencies :-/
from ooniapi.rate_limit_quotas import FlaskLimiter
try:
from system... |
import os
from time import time
import numpy as np
from math import ceil
from scipy.ndimage.morphology import binary_dilation, binary_erosion
from sklearn.mixture import GaussianMixture
import sys
sys.path.append('/workspace/trustworthy-ai-fetal-brain-segmentation')
from src.utils.definitions import *
def merge_deep_... |
import tensorflow as tf
import numpy as np
from collections import defaultdict
from functools import partial
class NN:
def __init__(self, input, output):
init = tf.contrib.layers.xavier_initializer
self.hidden_1 = tf.layers.Dense(units=32, activation=tf.nn.relu, bias_initializer=init())
sel... |
# Copyright 2018-2019 QuantumBlack Visual Analytics 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/LICENSE-2.0
#
# THE SOFTWARE IS PROVIDED "AS IS"... |
# Borrowed from: https://github.com/yjxiong/tsn-pytorch/blob/master/transforms.py
import torchvision
import random
from PIL import Image
import numbers
import torch
import torchvision.transforms.functional as F
class GroupResize(object):
def __init__(self, size, interpolation=Image.BILINEAR):
self.worker ... |
import uuid
import jsonobject
from jsonobject.exceptions import BadValueError
from memoized import memoized
from casexml.apps.case.mock import CaseBlock, IndexAttrs
from corehq.apps.hqcase.utils import CASEBLOCK_CHUNKSIZE, submit_case_blocks
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
fro... |
#!/usr/bin/env python3
# iLert Zabbix Plugin
#
# Copyright (c) 2020, iLert GmbH. <<EMAIL>>
# All rights reserved.
# see https://docs.ilert.com/integrations/zabbix for setup instructions
import fcntl
import json
import os
import syslog
import uuid
PLUGIN_VERSION = "1.0"
CONFIG = {
'tmp_dir': '/tmp/ilert_zabbix... |
# Calculate Peak Acceleration
# Making peak acceleration stuff
import asyncio
import sys
import struct
import array
import math
from SeismogramTasks import Rotate_2D_TimeSeries,VectorMagnitude,Rotate_3D_TimeSeries
from datetime import datetime, timedelta
import json
# note: each element of x,y,z makes one vector!
arra... |
# <NAME>
# 2020_03_21
# %tensorflow_version 2.x
# %tensorflow_version 2.x
import tensorflow as tf
import numpy as np
class MultiNN(object):
def __init__(self, input_dimension):
"""
Initialize multi-layer neural network
:param input_dimension: The number of dimensions for each... |
"""
Read athena zprof file using pandas and xarray
"""
from __future__ import print_function
import os
import os.path as osp
import glob
import numpy as np
import pandas as pd
import xarray as xr
def read_zprof_all(dirname, problem_id, phase='whole', savdir=None,
force_override=False):
"""Func... |
"""
Simplicial Complexes for manim
"""
from manimlib.imports import *
import numpy as np
class SimplicialFiltration(VGroup):
def __init__(
self,
points,
simplices,
times,
tri_opacity=0.2,
**kwargs
):
super().__init__(**kwargs)
self.current_time = -np.inf
self.pts = points
self.tri_opacity=tri_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from caffe2.python import core
from functools import partial
from hypothesis import given
import caffe2.python.hypothesis_test_util as hu
import numpy as np
def split(da... |
import pytest
import numpy as np
import plotly.graph_objects as plt
from gilp._graphic import (Figure, num_format, linear_string, equation_string,
label)
# The following functions are not tested since they create visual objects:
# table, vector, scatter, line, equation, and polygon
@pytes... |
from osgeo import gdal
from ..helper import generate_output_file_tif, create_zip_shapefiles
import logging
import time
import warnings
import os
import secrets
import shutil
import subprocess
import pathlib
from pprint import pprint
import numpy as np
from .my_calculation_module_directory.input_data_function import P... |
from tsp import tsp_lower_bound, tsp_upper_bound
class Kante:
distanz = None
pfad = []
def __init__(self, distanz, pfad):
self.distanz = distanz
self.pfad = pfad
def __repr__(self):
return str(self.distanz)
class Paket:
zielknoten = None
gewicht = None
own_id=None
'''immutable'''
def __init__(self, ... |
from typing import Dict
from wordcloud import WordCloud
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import random
import re
import logging
import matplotlib.pyplot as plt
import sys
sys.path.append('RiksdagenPythonAPI/')
import riksdagen
def transform_format(val):
if val == 0:
return ... |
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import get_object_or_404, render
from django.urls import reverse, reverse_lazy
from django.views import generic
from .models import Experiment, ExperimentCalc
from . import graphs, expcalcs, forms
class IndexView(generic.FormView):
... |
from spacy import displacy
import re
# Document level classes
class entClass(object):
''' Entity class for myDoc classes, similarly to spacy, it contains the string, the offsets and the label for one entity
'''
def __init__(self, word, start, end, label, nested = -1, idx = -1, level = -1):
se... |
from typing import Callable
import torch
from torch.nn.modules.loss import _Loss
# from torch.types import Number
from ..raster.composite import softor
from ..raster.disttrans import line_edt2
from ..raster.raster import nearest_neighbour, compute_nearest_neighbour_sigma_bres
class Chamfer(_Loss):
"""Compute th... |
from typing import List
import numpy as np
import pandas as pd
from numpy import ndarray as Array
from matplotlib import pyplot as pp
from .error_functions import MSE
from .activation_functions import softmax, sigmoid, sigmoid_derivative
class Layer:
"""
Layer abstraction used internally by MultilayerPerce... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.