content
stringlengths
5
1.05M
from django.contrib import admin from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.core.urlresolvers import reverse from django.utils.html import escape from django import forms from django.forms.models import inlineformset_factory, BaseInlineFormSet from djang...
import click def yellow(message): return click.style(message, fg="yellow", bold=True) def red(message): return click.style(message, fg="red", bold=True) def green(message): return click.style(message, fg="green", bold=True) def gray(message): return click.style(message, fg="white", bold=False) ...
# -*- coding: utf-8 -*- value1 = input() value2 = input() prod = value1+value2 print("SOMA = " + str(prod))
from datetime import date import boundaries boundaries.register('Grimsby wards', domain='Grimsby, ON', last_updated=date(2016, 1, 1), name_func=lambda f: 'Ward %s' % f.get('Ward'), id_func=boundaries.attr('Ward'), authority='Town of Grimsby', licence_url='https://niagaraopendata.ca/pages/open-...
# -*- coding: utf-8 -*- import re import glob from geotext import GeoText #ES: error tracking code for py 2 ------------- import logging import time import os #---------------------------------------------- def compileSubs(folderName,fileName,files,t_list,interviewer,interviewee,pass2,language,resampleSubtitles,remov...
""" Implementation of Cosmic RIM estimator""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf physical_devices = tf.config.experimental.list_physical_devices('GPU') print(physical_devices) assert len(physical_devices) > 0, "Not enough...
def center_align(text, max_length): to_add = max_length - len(text) pad = ' ' * (to_add//2) return ''.join([pad, text, pad])
''' Let's plot Brady's theory for our variables... ''' import sys import os import numpy as np import math import matplotlib.pyplot as plt def computeActivity(VP, TAUR, SIG): return (3.0 * VP * TAUR / SIG) tau_R = 1.0 / 3.0 sigma = 1.0 particle_Area = np.pi * ((sigma / 2.0)**2) def computeBradyMono(PHI, PE, APA...
from pathlib import Path import numpy as np import torch import soundfile as sf # load file list text file # comments are escaped using '#' # file names should be relative to path of the file list # in case each example corresponds to multiple files, this can be handled by # omitting extensions in the file list or u...
from common.database_api import DatabaseApi from common.loggable_api import Loggable from common.message_broker_api import MessageBrokerApi class BackendTasksApi(Loggable): """ This is an abstract class. It contains logic common to any backend tasks class. """ def __init__(self, service_name, descendant_cla...
from numpy.core.numeric import normalize_axis_tuple import torch import custom_transforms from path import Path class DataLoaderCreator(): def __init__(self, args): self.args = args def create(self, mode, seq_length=1): if self.args.dataset_format == 'stacked': from datasets.stacked...
import numpy as np from ..affine import power_L def basil_inner_loop(path_obj, lagrange_subseq, initial_data, # (solution, grad) pair inner_tol=1.e-5, verbose=False, initial_step=None, check_ac...
''' Calculate various quantities considered surface brightness such as: - net counts - net count Rate - net photon flux - net energy flux (two options) see further documentation parameters: evt_file - classic event fits file (e.g. 'acsif_#####_repro_evt2') if merged ('mer...
import primes import matplotlib.pyplot as plt P = primes.prange(1001) Y = [] for i in range(len(P)-1): Y.append(P[i+1]-P[i]) plt.plot(Y,'x') plt.xlabel('n') plt.ylabel('p(n)-p(n-1)') plt.show()
# (C) Copyright 2021 Hewlett Packard Enterprise Development LP. # Aruba Fabric Composer classes import requests from requests.auth import HTTPBasicAuth from requests.structures import CaseInsensitiveDict import classes.classes import urllib3 import json urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarni...
import functools import sys import types import inspect __all__ = [ 'partial_cls', 'register_partial_cls' ] def partial_cls(base_cls, name, module, fix=None, default=None): # helper function def insert_if_not_present(dict_a, dict_b): for kw,val in dict_b.items(): if kw not in d...
# create executable binary from python code, toy example # inspired by http://masnun.rocks/2016/10/01/creating-an-executable-file-using-cython/ # cython --embed -o hello_world.c hello_world.py # gcc -v -Os \ # -L /usr/local/Frameworks/Python.framework/Versions/3.7/lib/ \ # -I /usr/local/Frameworks/Python.fra...
pre = '/Users/phr/Desktop' # train_file = pre+'/Parser/files/small-bin.txt' # train_file = pre+'/Parser/files/medium.txt' dev_file = pre+'/Parser/files/small-dev.txt' train_file = pre+'/Parser/files/train.txt' # train_file = pre+'/Parser/files/dev.txt' output_dir = pre+'/Parser/output/' import os if not os.path.exists...
import os import numpy.ctypeslib as npct from ctypes import * import csv import numpy as np from contextlib import contextmanager import sys def getColumn(filename, column): results = csv.reader(open(filename), delimiter=",") # next(results, None) # skip the headers return [result[column] for result in re...
import abc import traitlets.config class EventSink(traitlets.config.LoggingConfigurable): """ A sink for JupyterLab telemetry events. Subclasses should do something useful with the event that are recieved (such as sending it to an event store or writing them to a file). """ @abc.abstractmeth...
SID = '' AUTH_TOKEN = '' FROM_NUMBER ='' TO_NUMBER = '' API_KEY='' DEVICE_NAME='BOLT'
#!/usr/bin/env python3 from pymongo import MongoClient #### # Indicate start #### print("============================") print(" Starting my_python_app ") print("============================") print('\n') #### # Main start function #### def main(): # MongoDB Connection mongo_client = MongoClient(MONGODB_U...
# -*- coding:utf8 -*- import fixpath import okpy G_ERROR_NUMBER = None def outer_exception(): return 1/0-3 def catcher_exception(n): return 1/(n-2) @okpy.ready def are_you_ready(): global G_ERROR_NUMBER G_ERROR_NUMBER = 2 @okpy.cleaner def i_am_cleaner(): global G_ERROR_NUMBER G_ERROR_NUMB...
from .quick_logger import *
#! /usr/bin/env python3 # # Copyright (C) 2018 Gaëtan Harter <gaetan.harter@fu-berlin.de> # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. # """ lazysponge Adaptation of moreutils `sponge` with ad...
from enum import IntEnum from blatann.nrf.nrf_types import * from blatann.nrf.nrf_dll_load import driver import blatann.nrf.nrf_driver_types as util class BLEEvent(object): evt_id = None def __init__(self, conn_handle): self.conn_handle = conn_handle def __str__(self): ret...
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml. import os from path_if import path_if from sanic import Sanic from sanic.response import json dir_path = os.path.dirname(os.path.realpath(__file__)) app = Sanic(__name__) app.blueprint(path_if) if __name__ == "__main__": app.run(...
"""SMTP Email connector to gmail. Sends email to organization member via gmail SMTP using config.py credentials """ import json import requests from requests.auth import HTTPBasicAuth import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText import config def getEmailAddres...
#! /usr/bin/python # -*- coding: utf-8 -*- import sys import math ayuda = f''' NOMBRE {sys.argv[0]} Aplicación python para calcular los ajustes del PLL para MCUs: dsPIC33Ep y PIC24EP SINOPSIS {sys.argv[0]} [-h|--help] {sys.argv[0]} [[-fi] <Freq_de_entrada>[k|K|M]] [-fo] <Freq_de_salida>[k|K|M]] Se requi...
from collections import defaultdict from datetime import datetime, timedelta from random import randint from re import search from time import time from . import db from .cmds import games welcomed = [] messages = defaultdict(int) def process(bot, user, message): update_records(bot, user) if user["id"] not in we...
import sys import os import berserk import chess from pathlib import Path from lichs.Game import Game from lichs.api_key import set_api def main(): try: set_api(sys.argv[1]) os._exit(0) except: try: token_file = Path(__file__).parent.absolute() / "key" token = ...
# https://www.acmicpc.net/problem/9498 a = int(input()) if (a >= 90) and (a <= 100): print("A") elif (a >= 80) and (a < 90): print("B") elif (a >= 70) and (a < 80): print("C") elif (a >= 60) and (a < 70): print("D") else: print("F")
"""Main functions to retrieve the relevant data of the article corresponding to the given arXiv identifier. Also helper function to check if arXiv identifier exists. """ import re import requests from lxml import html import src.article as article def get_year(ax_id): """Extract the year from an arXiv identifi...
""" 4차원 데이터를 2차원으로 변환한 후에 max pooling 구현 """ import numpy as np from common.util import im2col if __name__ == '__main__': np.random.seed(116) # 가상의 이미지 데이터(c,h,w) = (3,4,4) 1개를 난수로 생성 -> (1,3,4,4) x = np.random.randint(10, size=(1, 3, 4, 4)) print(x, 'shape:', x.shape) # 4차원 데이터를 2차원 ndarray로 변환...
import slam.plot as splt import slam.io as sio import slam.remeshing as srem if __name__ == '__main__': # source object files source_mesh_file = 'data/example_mesh.gii' source_texture_file = 'data/example_texture.gii' source_spherical_mesh_file = 'data/example_mesh_spherical.gii' # target object f...
''' Created on Jan 4, 2019 @author: bergr ''' import numpy as np from suitcase.nxstxm.stxm_types import scan_types, two_posner_scans from suitcase.nxstxm.device_names import * #from suitcase.nxstxm.utils import dct_get, dct_put from suitcase.nxstxm.roi_dict_defs import * # from suitcase.nxstxm.nxstxm_utils import (ma...
#!/usr/bin/env python3 import shutil, os, argparse, sys, stat sys.path.append("scripts/pyUtils") sys.path.append("scripts/setUpScripts") from utils import Utils from genFuncs import genHelper def main(): name = "TwoBit" libs = "njhcpp:v2.6.3" args = genHelper.parseNjhConfigureArgs() cmd = genHelper.mkC...
def distanceCentrality(network): n = network.GetNodes() Components = snap.TCnComV() # holds the connected components in a network snap.GetSccs(network, Components) nodeCloseness = dict() # dictionary {node: degree} for NI in network.Nodes(): NId = NI.GetId() farn...
import os import numpy import gym from gym import spaces try: import gym_minigrid from gym_minigrid.wrappers import * except: pass def make_env(env_id, seed, rank, log_dir): def _thunk(): env = gym.make(env_id) env.seed(seed + rank) # Maxime: until RL code supports dict obser...
#!/usr/bin/python from nn_f0nDuration import ANN import pandas as pd import numpy as np from sklearn.datasets import load_boston flag_arctic_duration = 0 flag_boston_prices = 1 if flag_boston_prices == 1: boston = load_boston() print 'Loaded Data successfully' X = boston.data Y = boston.t...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os, argparse, time from util import util # gestion des options en ligne de commande parser = argparse.ArgumentParser (description='MQTT metrics gateway to InfluxDB') parser.add_argument ('--broker', '-b', default='127.0.0.1', help='MQTT broker address - d...
# Generated file.
import json import asyncio import discord import os import config import requests import aiohttp # kgs room id ROOM=788560 # kgs bot account name kgs_bot = "LooselyBot" # kgs json api to read data kgs_url = "http://www.gokgs.com/json/access" # bold wrapper def bold(fn): def wrapper(user): # insert some ...
# -*- coding: utf-8 -*- """ Zurich Instruments LabOne Python API Example Demonstrate how to connect to a Zurich Instruments UHF Lock-in Amplifier and obtain output from the Input PWA and Boxcar using ziDAQServer's poll() command. """ # Copyright 2016 Zurich Instruments AG from __future__ import print_function import...
from abc import abstractmethod, ABC from torch import nn class Recomputable(ABC): @abstractmethod def recompute(self): pass def recompute(module: nn.Module): if isinstance(module, Recomputable): module.recompute()
from sklearn.feature_extraction.text import TfidfVectorizer class TermClassifier: def _tfidf(self, data=[]): """ term weighting """ vector = TfidfVectorizer() transformed = vector.fit_transform(data) return transformed.toarray()
nums = [3,41,12,9,74,15] print((len(nums))) print(max(nums)) print(min(nums)) print(sum(nums)) newsum = sum(nums)/len(nums) print("{:.4f}".format(newsum))
import os import gc from psana.psexp.tools import mode world_size = 1 if mode == 'mpi': from mpi4py import MPI world_size = MPI.COMM_WORLD.Get_size() rank = MPI.COMM_WORLD.Get_rank() # set a unique jobid (rank 0 process id) for prometheus client if rank == 0: prometheus_jobid = os...
import pytest import tensorflow as tf from tensorflow import keras import sys sys.path.append(".") from keras_cv_attention_models import attention_layers # Not included: batchnorm_with_activation, conv2d_no_bias, drop_block, hard_swish, phish, mish, layer_norm def test_add_pre_post_process_tf(): input_shape = (2...
import unittest import torch import math from model_utils_torch.ops import * from model_utils_torch.more_ops.multiple_pad import test_center_multiple_pad class TestOps(unittest.TestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.test_data_2d = torch.randn(5, 1...
import datetime from django.utils.timezone import utc from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse from django.contrib.auth.decorators import login_required from .forms import OptionForm, TitleForm from .models import Emails, Options, Titles, Voted from django.contrib...
#!/usr/bin/env python # -*- coding: utf8 -*- from __future__ import unicode_literals from ..helpers import HEADERS from base_scraper import BaseScraper import lxml.html import requests import time from unicodedata import normalize class IMDB(BaseScraper): BASE_URL = "http://www.imdb.com" SEARCH_PATH = "/find?q="...
# # #ok get the csv files to text # do it for all (use blob) #FAAACCCKKKKKKK import csv import os def nameG(a, b): #get the file's names which are going to deal with c = [] for i in range(b): if i==0: continue if i < 10: c.append(a +"tobacco_plant00"+ str(i)+"_bbox.csv"...
from django.shortcuts import render def admin_home(request): return render(request, 'admin_template/admin_home.html')
from __future__ import annotations from ..expressions import Expression class ExpressionVisitor: def __init__(self): self.visited = {} self._top_level = True def visit(self, expression): is_top_level = False if self._top_level: is_top_level = True self...
import numpy as np def merge_colinear(x, y): """Processes boundary coordinates in polyline with vertices X, Y to remove redundant colinear points. Polyline is not assumed to be open or closed. Parameters ---------- x : array_like One dimensional array of horizontal boundary coordinates. ...
from typing import Tuple import ema_workbench import LESO import json from tinydb import TinyDB import pandas as pd from LESO import AttrDict def load_ema_leso_results( run_id: int, exp_prefix: str, results_folder: str, return_db_as_df=True, exclude_solver_errors = True, ) -> Tuple[pd.DataFrame, dict, pd....
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
from tensorflow.keras.models import Sequential model3 = Sequential([ embedding_layer, Flatten(), ]) labels_to_encode = np.array([[3]]) print(model3.predict(labels_to_encode))
"""Constant values for the modules""" # system constants APP_NAME = "SelfStabilizingReconfiguration" RUN_SLEEP = 1 INTEGRATION_RUN_SLEEP = 0.05 FD_SLEEP = 0.25 FD_TIMEOUT = 5 MAX_QUEUE_SIZE = 10 # Max allowed amount of messages in send queue # FD BEAT_THRESHOLD = 30 # Threshold for liveness, beat-variable CNT_THRES...
from fastapi import APIRouter from .api.endpoints import api_router from .health.endpoints import health_router base_router = APIRouter() base_router.include_router(api_router, prefix='/api') base_router.include_router(health_router, prefix='/health')
from SBaaS_base.postgresql_orm_base import * #IS #internal_standard class internal_standard(Base): #__table__ = make_table('internal_standard') __tablename__ = 'internal_standard' is_id = Column(Integer, nullable = False); is_date = Column(DateTime, nullable = False); experimentor_id = Column(Strin...
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# coding: utf-8 """ Flat API The Flat API allows you to easily extend the abilities of the [Flat Platform](https://flat.io), with a wide range of use cases including the following: * Creating and importing new music scores using MusicXML, MIDI, Guitar Pro (GP3, GP4, GP5, GPX, GP), PowerTab, TuxGuitar and Mus...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-02-13 18:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Categor...
"""Reader for the GMSH file format.""" from __future__ import division, absolute_import __copyright__ = "Copyright (C) 2009 Xueyu Zhu, Andreas Kloeckner" __license__ = """ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software")...
# Copyright 2021 Hakan Kjellerstrand hakank@gmail.com # # 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 ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.27 on 2020-02-12 20:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0006_auto_20200212_1151'), ] operations = [ migrations.AddField( model_name='publication'...
import flask import logging from flask import Flask, send_from_directory, render_template, jsonify, url_for, request, redirect from dirToPod import RssGenerator from reverse_proxied import ReverseProxied from eyed3 import id3 from random import random from logging.handlers import RotatingFileHandler import shutil imp...
from pymongo import MongoClient from data_prep.config import mongo, neo4j from py2neo import Graph, Node, Relationship, authenticate class DBCrawl: def __init__(self): self.db = mongo['db_name'] self.host = mongo['host'] self.port = mongo['port'] self.client = MongoClient(self.hos...
import numpy as np from utils.test_env import EnvTest class LinearSchedule(object): def __init__(self, eps_begin, eps_end, nsteps): """ Args: eps_begin: initial exploration eps_end: end exploration nsteps: number of steps between the two values of eps ""...
from collections import defaultdict from ipaddress import ip_address, IPv4Address, IPv6Address from typing import Dict, Union, List from twisted.internet import defer from twisted.names import dns from twisted.python.failure import Failure from dnsagent import logger from dnsagent.resolver.base import BaseResolver fr...
#!/usr/bin/env python # -*- coding: utf-8 -*- #****************************************************************************** # # mask_all.py # --------------------------------------------------------- # Apply raster B to raster A to add 0 where raster A values are nodata or missing (but exist in raster B) # More: htt...
def findSep(self): text = self.text data = list(text) found="-1" for x in data: found=type(x) if (found != "-1"): break return found def type(i): switcher={ ' ':'space', ',':'comma', ';':'semi-colon', ':...
# -*- coding: utf-8 -*- """ Created on Sat Apr 25 18:37:11 2020 @author: autol """ #%% import numpy as np import pandas as pd df = pd.DataFrame({'a': np.random.randn(1000), 'b': np.random.randn(1000), 'N': np.random.randint(100, 1000, (1000)), ...
#!/usr/bin/python # # Copyright 2019 Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file ex...
from typing import Dict, List, Any, Optional import timm import torch import torch.nn as nn class BaseTimmModel(nn.Module): """Convolution models from timm name: `str` timm model name num_classes: `int` number of classes from_pretrained: `bool` whether to use timm pretrain...
""" Given an account name and a shard_id, make a request to the bulk stash tab API of Path of Exile http://api.pathofexile.com/public-stash-tabs If the account is not found in the payload, update the scheduler with the next invocation and shardId and return, if it is, then update the account in the database and retur...
"""Creates a table of transfer functions for a StateSpace (MIMO) model.""" import controlSBML.constants as cn import controlSBML as ctl from controlSBML.option_management.option_manager import OptionManager import control from docstring_expander.expander import Expander import matplotlib.pyplot as plt import numpy as...
# using nltk vader built in lexicon classifier because generating dataset for # classifier myself would take too long, might create custom dataset tho import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import constants financial_word_classification = { "bullish": 1, "bearish": -1, "...
from shelf.metadata.result import Result from shelf.metadata.error_code import ErrorCode import copy class Manager(object): """ Responsible for maintaining metadata integrity between multiple places. Not only should the metadata match but it also needs to be initialized with some values i...
#!/usr/bin/env python # -*- coding: utf-8 -*- #http://stackoverflow.com/questions/4629595/using-pysides-qtwebkit-under-windows-with-py2exe #http://qt-project.org/wiki/Packaging_PySide_applications_on_Windows __author__ = 'joseph' from distutils.core import setup import py2exe import sys # If run without args, bui...
import wx import vdesk import win32con import sys import movementindicator class Model(object): def __init__(self): pass def shortcut_data(self): def generate_shortcut(Modifiers, Key, Function): return { "Modifiers": Modifiers, "Key": Key, ...
# -*- coding: utf-8 -*- import unittest from equivalence.AstraRastr import RASTR from equivalence.Load import LoadFile from equivalence.actions.zeroing import Zeroing from equivalence.tables.Tables import Node from equivalence.test.model_test_RUSTab.path_model import absolute_path_to_file class TestZeroing(unittest....
""" Requires OpenCV2: https://docs.opencv.org/master/d7/d9f/tutorial_linux_install.html """ import pickle import socket import struct import numpy as np import cv2 from snr.proc_endpoint import ProcEndpoint from snr.node import Node from snr.utils import debug from snr.cv import find_plants from snr.cv.boxes import a...
#!/usr/bin/python # Probably belongs here... from flask import Flask, request, jsonify, send_from_directory from datetime import datetime import datahit from datahit import datahithtml, datahitlog import json from elasticsearch import Elasticsearch import yaml import sys app = Flask(__name__, static_url_path='') runda...
# Copyright (c) 2008 Mikael Lind # # 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, distr...
# Import Libraries import pandas as pd import numpy as np import yfinance as yf import time # Import Libraries from scipy import stats import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # Import Libraries from ta.momentum import RSIIndicator from ta.trend import SMAIndicator # impor...
import zipfile import tempfile from typing import Union import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow import keras from PIL import Image from keras.preprocessing import image import numpy as np import datetime from matplotlib import pyplot as plt from tensor...
import torch import cv2 import numpy as np from argparse import ArgumentParser from torch.utils.data.sampler import SubsetRandomSampler from models.model import Model def argument_setting(inhert=False): class Range(object): def __init__(self, start, end): self.start = start self....
""" Copyright 2015 Rackspace 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 dist...
import unittest from max_sub_array_2 import Solution from ddt import ddt, data, unpack @ddt class Tester(unittest.TestCase): def setUp(self): self.s = Solution() @data( [[1], 1], [[-2,1,-3,4,-1,2,1,-5,4], 6], [[-2,-1],-1], [[0,-1],0] ) @unpack def test(self,...
import numpy as np import matplotlib.pyplot as plt import h5py import scipy.io import math import sklearn import sklearn.datasets def init_mome(parameters): L = len(parameters) // 2 # number of layers v = {} # Initialize velocity for l in range(L): v["dW" + str(l+1)] = np.zeros((param...
import warnings from statsmodels.stats.diagnostic import ( CompareCox, CompareJ, HetGoldfeldQuandt, OLS, ResultsStore, acorr_breusch_godfrey, acorr_ljungbox, acorr_lm, breaks_cusumolsresid, breaks_hansen, compare_cox, compare_j, het_arch, het_breuschpagan, het_goldfeldquandt, het_white, linear_harvey_colli...
import hashlib import datetime # import pyecharts from django.http import HttpResponseNotFound from django.shortcuts import render, redirect, render_to_response from django.template import RequestContext from django.core.paginator import Paginator from pyecharts import Line from user.models import * from device.model...
#!/usr/bin/env python # -*- coding: utf-8 -*- ################################################################### # Author: Mu yanru # Date : 2019.2 # Email : muyanru345@163.com ################################################################### """ MDivider """ import six from dayu_widgets.label import MLabel from da...
"""Seawater-ice equilibrium functions. This module provides thermodynamic functions for seawater in equilibrium with ice (sea-ice), e.g. the enthalpy of melting. It also provides a Gibbs free energy function for sea-ice parcels, with primary variables being the total salinity (mass of salt per mass of salt, liquid, an...
from __future__ import annotations import os import re import shutil import stat import tempfile from collections.abc import Mapping from contextlib import contextmanager from pathlib import Path from typing import TYPE_CHECKING from typing import Any from typing import Callable from typing import Iterator if TYPE_...
# Variational Bayes for binary logistic regression using JJ bound and mean field Gaussian-Gamma. # Also, Laplace approx with EB for multiclass. # Written by Amazasp Shaumyan #https://github.com/AmazaspShumik/sklearn-bayes/blob/master/skbayes/linear_models/bayes_logistic.py import numpy as np from scipy.optimize import...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from pykg2vec.core.KGMeta import ModelMeta, InferenceMeta class TuckER(ModelMeta, InferenceMeta): """ `TuckER-Tensor Factorization fo...