content
stringlengths
5
1.05M
from .pushservice import *
from copy import deepcopy from hashlib import md5 from misago.core import threadstore from .forms import get_permissions_forms def fake_post_data(target, data_dict): """ In order for form to don't fail submission, all permission fields need to receive values. This function populates data dict with defau...
from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.db import models from django.test import TestCase, TransactionTestCase from django_dynamic_fixture import G from mock import patch, MagicMock, call from activatable_model.models import BaseActivata...
class Response(object): status = None reason = None url = None content_type = None charset = None text = None meta = None def __init__(self): pass
from bokeh.models.formatters import FuncTickFormatter def configure_plot(plot): plot.toolbar.logo = None plot.xaxis.axis_label_text_font_style = "normal" plot.yaxis.axis_label_text_font_style = "normal" plot.xaxis.major_label_text_font_size = "1rem" plot.yaxis.major_label_text_font_size = "1rem" ...
# # K-line, stock datas # Klang 提供了全局的股票数据,和获取股票数据的方法 # Kdatas 是提供了单只股票的数据和计算方法 # 类似通达信这样的公式,经过计算的数据有时候需要 计算整个周期,有时候是单个周期 # 因此需要封装成 python 类来解决 # 例如: if CLOSE > OPEN, 判断的是单个周期 # 例如: EVERY (CLOSE > OPEN,N) 这时候判断的是多个周期 import numpy as np import pandas kl = None def setstock(kl1): global kl kl = kl1 """ df2 = ...
#----------------- Libraries -------------------# import os import sys from tqdm import tqdm import numpy as np import pandas as pd from sklearn.model_selection import KFold from sklearn.model_selection import train_test_split from Preprocessing import Preprocessing def kfold_decompose(data, kfold_n): """ Thi...
""" Custom validator that validates the format needed for PBRG to get the record date from a folder name. """ import re import string import wx DAY_NUMBER = 0 MONTH_NAME = 1 YEAR_NUMBER = 2 class DateValidator (wx.Validator): """ Validates input date has the next format: DD MONTH_NAME YYYY """ def...
import time from netmiko.no_enable import NoEnable from netmiko.no_config import NoConfig from netmiko.cisco.cisco_ios import CiscoIosBase class KeymileSSH(NoEnable, NoConfig, CiscoIosBase): def __init__(self, **kwargs): kwargs.setdefault("default_enter", "\r\n") return super().__init__(**kwargs)...
#!/usr/bin/env python import sys import requests import base64 from requests.auth import HTTPBasicAuth import json import configparser account_data = {} pc_data = {} #verify_git_creds verifies the given got credentials have access to the repo def verify_git_creds(repo, owner, username, password): git_repo_endpoi...
#output position of player in 25 seconds import time from mcpi.minecraft import Minecraft mc = Minecraft.create() pos1 = mc.player.getTilePos() x1=pos1.x y1=pos1.y z1=pos1.z #wait for 25 seconds time.sleep(25) #get position again pos2 =mc.player.getTilePos() x2 = pos2.x y2 = pos2.y z2 = pos2.z #calcu...
from unittest import TestCase import puzio import re class TestModule(TestCase): def test_timestamp(self): t = puzio.timestamp() patt = r'\d{8}T\d{6}' self.assertTrue(re.fullmatch(patt, t), f"timestamp {t} does not match pattern {patt}")
# coding: utf-8 """ ELEMENTS API The version of the OpenAPI document: 2 Generated by: https://openapi-generator.tech """ import pprint import re # noqa: F401 import six from elements_sdk.configuration import Configuration class FSProperties(object): """NOTE: This class is auto generated by Open...
''' Created on 16-10-2012 @author: Jacek Przemieniecki ''' from unifac.facade import Facade #@UnresolvedImport class UI(object): def __init__(self): self.facade = Facade() def parse_file(self, f): """ Opens the file from patch f and executes commands inside""" with open(f...
''' Escreva um programa que leia a velocidade de um carro. Se ele ultrapassar 80Km/h, mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada Km acima do limite. ''' # Ler a velocidade do carro. vc = int(input('Informe a velocidade do carro: ')) print('--*-'* 20) print('A velocidade re...
""" OAuth/Gmail API-based email notifier :author: alanung and Matthew Farrugia-Roberts """ import base64 import pickle import os.path from email.mime.text import MIMEText from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Re...
# codes in this file are reproduced from https://github.com/GraphNAS/GraphNAS with some changes. from torch_geometric.nn import ( GATConv, GCNConv, ChebConv, SAGEConv, GatedGraphConv, ARMAConv, SGConv, ) import torch_geometric.nn import torch from torch import nn import torch.nn.functional ...
# -*- coding: utf-8 -*- """ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is he...
# Copyright (C) 2020 FUJITSU # 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 a...
import random import torch import numpy as np from ..environment.device import DeviceTopology from ..environment.state import CircuitStateDQN from ..algorithms.simanneal import AnnealerDQN from ..hyperparams import DEVICE class DoubleDQNAgent(torch.nn.Module): def __init__(self, device: DeviceTopology): ...
import pytest @pytest.fixture def analysis_step_version_3(testapp, analysis_step, software_version): item = { 'schema_version': '3', 'version': 1, 'analysis_step': analysis_step['@id'], 'software_versions': [ software_version['@id'], ], } return item @...
from __future__ import absolute_import # Copyright 2013-2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at # # http://aws.amazon.com/apach...
from typing import Any, Generic, List, Optional, Union, cast from thirdweb.abi import TokenERC1155 from thirdweb.common.error import NotFoundException from thirdweb.common.nft import fetch_token_metadata from thirdweb.constants.currency import ZERO_ADDRESS from thirdweb.constants.role import Role, get_role_hash from th...
#this file contains functions that transform images; import tensorflow as tf import numpy as np import scipy def uniform_random(x_nat, epsilon): """Input: batch of images; type: ndarray: size: (batch, 784) Output: batch of images with uniform nois; we use clip function to be assured that numbers in matr...
""" Class definitions for the fundamental objects in the agent-based model. @author: Noah Burrell <burrelln@umich.edu> """ from scipy.stats import binom, norm, halfnorm, uniform class Student: """ A (truthfully-reporting) Student object. Attributes ---------- id : int. Unique identi...
# Copyright (C) 2012 Ion Torrent Systems, Inc. All Rights Reserved # from django.test import TestCase # from mockito import mock, when, any, verify, contains # import iondb.rundb.data.tasks # from django.contrib.auth.models import User # from iondb.rundb.tests.views.report.test_report_action import verifyMessage # impo...
''' 12. Try a string operation to perform below operation exam_st_date = (11, 12, 2014) Sample Output : The examination will start from : 11 / 12 / 2014 ''' exam_st_date = (11, 12, 2014) exam_st_date = str(exam_st_date) print(exam_st_date.replace(', ', ' / '))
# Not OK def simple(l = [0]): l[0] = 1 #$ modification=l return l # Not OK def slice(l = [0]): l[0:1] = 1 #$ modification=l return l # Not OK def list_del(l = [0]): del l[0] #$ modification=l return l # Not OK def append_op(l = []): l += [1, 2, 3] #$ modification=l return l # Not...
# coding=UTF-8 from natcap.invest.ui import model, inputs import natcap.invest.carbon class Carbon(model.InVESTModel): def __init__(self): model.InVESTModel.__init__(self, label=u'InVEST Carbon Model', target=natcap.invest.carbon.execute, ...
from django.db import models from django.contrib.auth.models import AbstractUser from djmoney.models.fields import MoneyField # Create your models here. class Greeting(models.Model): when = models.DateTimeField("date created", auto_now_add=True) class User(AbstractUser): email_notifications = models.BooleanF...
import sys from sty import fg, bg, ef, rs, RgbFg from core.game import TetrisRunner class TerminalTetrisRunner(TetrisRunner): def __init__(self, width=10, height=20): super().__init__(width, height) def delete_last_lines(self,n): CURSOR_UP_ONE = '\033[F' #'\x1b[1A' ERASE_LINE = '\033[K' #'\x1b[2K' for _ in...
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file acc...
#!python3 # -*- coding: utf-8 -*- import os, sys, time def main(): os.chdir('dist') for file in os.listdir(os.path.curdir): if 'py2.' in file: newfile = file.replace('py2.', '') os.rename(file, newfile) if __name__ == '__main__': main()
# coding=utf-8 from lib.verify import verify from plugins.BruteForce.mysql_crack import mysql_check from plugins.BruteForce.postgres_crack import postgres_check from plugins.BruteForce.ssh_crack import ssh_check class Crack(): def __init__(self): self.result = [] def pool(self, ip, ports): ...
import os import sys import telegram.ext as tg from loguru import logger from pyrogram import Client # enable logging LOGGER = logger # if version < 3.6, stop bot. if sys.version_info[0] < 3 or sys.version_info[1] < 6: LOGGER.error("You MUST have a python version of at least 3.6! Multiple features depend on this...
import unittest import os from checkov.dockerfile.runner import Runner from checkov.runner_filter import RunnerFilter class TestRunnerValid(unittest.TestCase): def test_runner_empty_dockerfile(self): current_dir = os.path.dirname(os.path.realpath(__file__)) valid_dir_path = current_dir + "/reso...
from sqlalchemy import Integer, Column, Table, Float, ForeignKey, String from db.meta import metadata Score = Table("score", metadata, Column("id", Integer(), primary_key=True), Column("user_id", Integer(), ForeignKey("user.id"), nullable=False), Column("score", Float(), primary_key=True), Column("tim...
from ober.tokens import TokenDatabase from ober.senses import SenseDatabase import struct import numpy as np import argparse import os def get_latest_clusters_version(clusters_path="data/senses/clusters"): max_version = 0 for f in os.listdir(clusters_path): if f.endswith(".clusters"): version = 0 try: v...
# -*- coding: utf-8 -*- """ Model page with tabs containing - App description - How to report issues - About contributors. """ import json import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input from dash.depende...
accuracy_requirement = 0.75 analytical_delay = True auto_delay_chain_sizing = False bank_select = "bank_select" bitcell = "bitcell_1port" bitcell_array = "bitcell_array" buf_dec = "pbuf" check_lvsdrc = False col_cap = "col_cap" col_cap_array = "col_cap_array" column_mux_array = "column_mux_array" config_file = "/home/p...
class Setup: def __init__(self, downloadInfo, **kwargs): self.downloadInfo = downloadInfo if self.downloadInfo.type.isVideo(): self.unmuteVideo = kwargs.get("unmuteVideo", True) self.updateTrack = kwargs.get("updateTrack", False) self.priority = kwargs.get("priori...
# ***************************************************************************** # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistribution...
""" Author: Matt Hanson Created: 27/08/2020 11:13 AM """ import pandas as pd import os import numpy as np from supporting_functions.conversions import convert_RH_vpa from supporting_functions.woodward_2020_params import get_woodward_mean_full_params test_dir = os.path.join(os.path.dirname(__file__), 'test_data') ...
# -*- coding: utf-8 -*- # Copyright 2018-2019 Streamlit 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 applicabl...
""" Hyper parameters related utils. For now it contains hyper parameter search tools with random search but it may evolve later. :: hp_sampler = HyperparamSearch( lr=ExpSampler(1e-6, 0.1), momentum=DecaySampler(0.5, 0.999), wd=ExpSampler(0.1, 1e-6), model=ChoiceSampler(['resnet', '...
# Version 0 # Initial config version! V0 = { "$schema": "http://json-schema.org/schema#", "type": "object", "properties": { # GitLab private token "token": { "type": "string", }, # GitLab domain (https://git.gitlab.com) "gitlab-host": { "typ...
"""Helper functions""" from itertools import product from math import isinf from typing import List import mpmath as mp import numpy as np import pandas as pd from utils.exceptions import ParameterOutOfBounds EPSILON = 1e-09 def get_q(p: float) -> float: """ :param p: Hoelder p :return: q """ ...
class cell: """ A cell for the CA problem. """ def __init__(self, rule, state): self.right = None self.left = None self.rule = rule self.state = state def situate(self): """looks around itself and calculated its situation. Returns an int from 0 to 7""" ...
from pathlib2 import Path import pathlib2 import os PROJECT_DIR = Path(__file__).resolve().parents[1] DATA_DIR = PROJECT_DIR / "data"
__title__ = 'Geo km' __description__ = 'Calculate distance and travel time between points using Google API.' __url__ = 'not available' __version__ = '2.0' __author__ = 'Shkaberda V., Zubriichuk V.' __author_email__ = 'not available' __license__ = 'MIT License' __copyright__ = 'Copyright 2021 Shkaberda Vadim, Vitaliy Zu...
from django.contrib.auth import views as auth_views from django.urls import path from .forms import CustomAuthenticationForm app_name = "accounts" login_view = auth_views.LoginView.as_view( template_name="accounts/login.html", authentication_form=CustomAuthenticationForm ) logout_view = auth_views.LogoutView...
from django.apps import AppConfig class ResourcecenterConfig(AppConfig): name = 'apps.hobbygroups' verbose_name = 'Hobby groups'
import os os.environ["TF_CPP_MIN_LOG_LEVEL"]='1' # 这是默认的显示等级,显示所有信息   os.environ["TF_CPP_MIN_LOG_LEVEL"]='2' # 只显示 warning 和 Error    os.environ["TF_CPP_MIN_LOG_LEVEL"]='3' # 只显示 Error import tensorflow as tf import numpy as np import matplotlib.pyplot as plt x_sin=np.linspace(-10,10,200) c,s=np.cos(x_sin),np.sin(x_...
# Extract values for each place. Create dictionaries for each case at each place. roman = thou[th] + hund[h] + tens[t] + ones[o]. class Solution(object): def intToRoman(self, num): """ :type num: int :rtype: str """ thousands = {'0':'', '1':'M', '2':'MM', '3':'MMM'} ...
# -*- coding: utf-8 -*- # Copyright (c) 2016 Ericsson AB # # 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 ...
from django.urls import path, include from rest_framework import routers from employee_management_backend.users.api import views router_users = routers.DefaultRouter() router_users.register("user", views.UserViewSet, "user") router_users.register("profiles", views.ProfileViewSet, "profiles") router_users.register("...
def expanded_form(num): return ' + '.join( [ str(int(i)*j) for i,j in zip( str(num)[::-1], [1,10]+[pow(10,p) for p in range(2,50)] ) ...
# Generated by Django 3.0.3 on 2020-03-12 10:17 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0017_lot_matiere_premiere2'), ] operations = [ migrations.RenameField( model_name='lot', old_name='matiere_premiere2...
import unittest import sys sys.path.append('.') from dl.lexer import DLLexer from dl.parser import DLParser from dl.ast import Integer, Variable, BinOp, RelOp, ArrayIndex, \ Assign, Print, Read, Return, If, While, Block, \ FunctionCall, Arguments, FunctionDeclaration, \ ...
UNIFI_DEFAULT_HOST = "unifi" UNIFI_DEFAULT_PORT = 443 UNIFI_DEFAULT_USERNAME = "admin" UNIFI_DEFAULT_PASSWORD = "ubnt" UNIFI_DEFAULT_SITE = "default" MQTT_DEFAULT_HOST = "localhost" MQTT_DEFAULT_PORT = 1883 MQTT_DEFAULT_NAME = "unifi" MQTT_DEFAULT_USERNAME = "mqtt" MQTT_DEFAULT_PASSWORD = "mqtt"
"""shell pip install autokeras """ import os import numpy as np import tensorflow as tf from sklearn.datasets import load_files import autokeras as ak """ ## A Simple Example The first step is to prepare your data. Here we use the [IMDB dataset](https://keras.io/datasets/#imdb-movie-reviews-sentiment-classification...
import sys from functools import reduce from operator import add from .lib import validate, Bracket def main(): print(reduce(add, map(lambda b: b.score if type(b) == Bracket else 0, map(validate, sys.stdin)))) if __name__ == '__main__': main()
import hassapi as hass import sys import yaml # # Centralizes messaging. # # Args: # # Version 2.0: # Initial Version class Notifier_Dispatch(hass.Hass): def initialize(self): self.gh_tts_google_mode = self.args.get("gh_tts_google_mode") self.gh_switch_entity = self.args.get("gh...
from typing import List class Solution: def findDiagonalOrder(self, nums: List[List[int]]) -> List[int]: m = [] for i, row in enumerate(nums): for j, v in enumerate(row): if i + j >= len(m): m.append([]) m[i+j].append(v) retur...
# -*- coding: utf8 -*- # Copyright (c) 2019 Niklas Rosenstein # # 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, mo...
# Copyright 2022 Huawei Technologies Co., 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...
from yahoo.YahooSocket import to_ydict, from_ydict, argsep import unittest, string d = {'1': 'penultimatefire','2': 'some ascii'} d2= { 1: 'penultimatefire', 2: 'some ascii'} bytes = '1\xc0\x80penultimatefire\xc0\x802\xc0\x80some ascii\xc0\x80' class YahooTestingSuite(unittest.TestCase): def testYDictConstruc...
from __future__ import division from models import * from utils.utils import * from utils.datasets import * from utils.parse_config import * import os import sys import time import datetime import argparse import torch from torch.utils.data import DataLoader from torch.utils.data import Subset from torchvision impor...
import abc import fnmatch import os from typing import List, Optional, Union import uqbar.objects import supriya def _search(pattern: str, root_path: str): search_path, pattern = os.path.split(pattern) search_path = os.path.expanduser(search_path) if not search_path: search_path = os.path.join(r...
import torch # torch.multiprocessing.set_sharing_strategy('file_system') import pandas as pd import numpy as np import sys import os import pickle import argparse # local imports import train_model import experiment_routines as experiments from subsetting_exp import subset_experiment # can add different from datase...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import pymongo from pymongo import MongoClient from nltk.stem.snowball import SnowballStemmer from collections import defaultdict, OrderedDict import math import codecs import SR_2_Twitter_users as SR2 STEMMER = SnowballStemmer("english", ignore_stopwords=True ) f_in = "g...
from django.shortcuts import render from django.views.generic.detail import DetailView from .models import Page class PageView(DetailView): model = Page def index(request): return render(request, 'pages/index.html', dict(pages=Page.objects.all()))
import statistics import time import random import multiprocessing import pytest import sys sys.path.append('..') import doctable def example_func(x, y=2): return x**y def example_sleep_func(x): time.sleep(x/100000) def test_workerpool(n=100): pool = doctable.WorkerPool(1, verbose=False) asser...
# test imports import sys #import sys as system, os, re #import re as regex #from os import path #from os import pipe as bar print sys #print system #print regex #print path #print bar
from datetime import datetime import pytest from sqlalchemy.exc import IntegrityError from finance.exceptions import AssetNotFoundException, AssetValueUnavailableException from finance.models import ( Account, Asset, AssetValue, Granularity, Portfolio, Record, RecordType, Transaction, ...
import pandas as pd import dgl import os import torch import numpy as np import scipy.sparse as sp import time from functools import partial from .. import randomwalk import stanfordnlp import re import tqdm import string class MovieLens(object): def __init__(self, directory): ''' directory: path t...
""" Simple function to get the quote for a desired market order from an orderbook. This is useful in a variety of ways and places. """ from gryphon.lib.money import Money from gryphon.lib.exchange.consts import Consts def price_quote_from_orderbook(order_book, mode, volume): if mode == Consts.BID: order...
# Copyright (c) 2022, RTE (https://www.rte-france.com) # See AUTHORS.txt # SPDX-License-Identifier: Apache-2.0 (see LICENSE.txt) # This file is part of ReLife, an open source Python library for asset # management based on reliability theory and lifetime data analysis. import pytest import numpy as np from relife.data...
from django.urls import reverse from rest_framework import status from lego.apps.quotes.models import Quote from lego.apps.users.models import AbakusGroup, User from lego.utils.test_utils import BaseAPITestCase def _get_list_url(): return reverse('api:v1:quote-list') def _get_list_approved_url(): return _g...
from evalml.pipelines.components.transformers.samplers.base_sampler import ( BaseOverSampler, ) from evalml.utils.woodwork_utils import infer_feature_types class SMOTESampler(BaseOverSampler): """SMOTE Oversampler component. Works on numerical datasets only. This component is only run during training and not ...
import os VERSION = "1.0" MODEL_NAME = os.path.basename(os.path.dirname(__file__)) DOCKERHUB_REPO = f"danieldeutsch/{MODEL_NAME}" DEFAULT_IMAGE = f"{DOCKERHUB_REPO}:{VERSION}" AUTOMATICALLY_PUBLISH = True from repro.models.liu2019.models import BertSumExt, BertSumExtAbs, TransformerAbs from repro.models.liu2019.setup...
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from fuji_server.models.base_model_ import Model #from fuji_server.models.object import Object # noqa: F401,E501 from fuji_server import util from fuji_server.models.a...
# Item Merge # Create a program that will compare two shopping lists from “Week A” and “Week B”. It will return any unique items contained on the list. ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def flatMap(arr, func=lambda x: x): return [func(j) for i in arr for j in i] def main(): getList = lambda x: input(f'{x}...
# # This file is part of pretix (Community Edition). # # Copyright (C) 2014-2020 Raphael Michel and contributors # Copyright (C) 2020-2021 rami.io GmbH and contributors # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by ...
from pathlib import Path from unittest.mock import patch from click.testing import CliRunner from tbpore.external_tools import ExternalTool from tbpore.tbpore import TMP_NAME, main_cli @patch.object(ExternalTool, ExternalTool._run_core.__name__) class TestClusterCLI: @staticmethod def get_command_line_from_...
#!/usr/bin/env python """The setup script.""" import os.path as op import warnings from setuptools import find_packages, setup def _read_md_as_rst(file): """Read Markdown file and convert it to ReStructuredText.""" from pypandoc import convert_file return convert_file(file, 'rst', format='md') def _rea...
""" Created on Jul 5, 2018 @author: lubo """ import pytest @pytest.mark.parametrize("variants", ["variants_impala", "variants_vcf"]) @pytest.mark.parametrize( "variant_type,count", [(None, 10), ("sub", 9), ("del", 1), ("sub or del", 10), ], ) def test_single_alt_allele_variant_types( variants_impl, varia...
import pickle import re from pathlib import Path from typing import List, NamedTuple, Optional import requests from ...core.mixins import PointMixin class NavaidTuple(NamedTuple): name: str type: str lat: float lon: float alt: Optional[float] frequency: Optional[float] magnetic_variatio...
import os from rafiki.utils.log import configure_logging from rafiki.admin import Admin from rafiki.admin.app import app configure_logging('admin') if __name__ == "__main__": # Run seed logic for admin at start-up admin = Admin() admin.seed() # Run Flask app app.run( host='0.0.0.0', ...
from .attributegenie import *
""" Distillation loss for the student training """ from typing import Optional import torch import torch.nn as nn import models.defaults as defaults from utils.stft_losses import MultiResolutionSTFTLoss class DistillationLoss(nn.Module): def __init__(self, student, teacher, *, infer_teacher: Optional[callabl...
from screws.freeze.base import FrozenOnly class GPD_2SF(FrozenOnly): """""" def __init__(self, dof): """""" self._dof_ = dof self._freeze_self_() def __call__(self, *args, **kwargs): """"""
import numpy as np from pySDC.core.Errors import ParameterError, ProblemError from pySDC.core.Problem import ptype from pySDC.implementations.datatype_classes.mesh import mesh # noinspection PyUnusedLocal class nonlinear_ODE_1(ptype): """ Example implementing some simple nonlinear ODE with a singul...
"""Fast CMS computation""" import os, logging, functools from functools import reduce #import blaze as bz import numpy as np import pandas as pd #from into import into from Operations.MiscUtil import Dict, dbg, AddFileSfx, MakeSeq, StatKeeper from Operations.tsvutils import DefineRulesTo_computeMeanStd, DefineRulesT...
import numpy as np import util class NeuralNetwork: # hyperameters learning_rate = 0.0001 l0, l1, l2, l3 = 0, 0, 0, 0 isShuffle = True # shuffle flag: for shuffling data while training the network isValidate = True # validation flag: for viewing validation results while tr...
def getAvaliableCows(cows, c): minEnd = float("inf") maxIndex = -1 start = False for i in range(0, len(cows)): if cows[i][0] <= c and cows[i][1] >= c: if not start: start = True # avaliable cow if cows[i][1] < minEnd: maxIndex = i minEnd = cows[i][1] else:...
class ComponentLanguage: PYTHON = "Python" R = "R" JAVA = "Java" JUPYTER = "Jupyter"
import numpy from amuse.units import units from amuse.units.quantities import is_quantity, value_in, to_quantity from amuse.datamodel import UnstructuredGrid, StructuredGrid,StructuredBaseGrid try: import matplotlib from matplotlib import tri if not hasattr(tri, "LinearTriInterpolator"): raise Exception...
from django.apps import AppConfig class MainSiteConfig(AppConfig): name = 'mainsite' verbose_name = 'Main Site'
import sys import random from utils import * from judgeManager import Judge_Manager class JudgeServerManager: def Add_Judge_Server(self, Address: str, Secret: str, Friendly_Name: str, Detail: str): db = db_connect() cursor = db.cursor() try: cursor.execute("INSERT INTO Judge_Ser...