content
stringlengths
5
1.05M
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Collection of decorators to help optimize Python functions and classes by caching return values. Return values are (by default) keyed off of the functio...
#!/usr/bin/env python import os, random, string, logging import webapp2 from google.appengine.api.app_identity import app_identity from www import models from www import routing # patch json module import json, datetime def defaultEncoder(self, obj): if not obj: return None if isinstance(obj, datetime.datetime)...
q=[int(input()) for _ in range(5)] print(-q[0]*q[2]+q[3]+q[1]*q[4] if q[0]<0 else (q[1]-q[0])*q[4])
from django.urls import reverse from service_catalog.models import RequestState, Request, Instance from tests.test_service_catalog.base_test_request import BaseTestRequest AUTHORIZED_STATES = [RequestState.SUBMITTED, RequestState.ACCEPTED, RequestState.FAILED] class TestApiRequestAccept(BaseTestRequest): def s...
import yaml import caffe from multiprocessing import Process, Queue from sbir_util.batch_manager import MemoryBlockManager from image_proc import Transformer from sample_util import * class TripletSamplingLayer(caffe.Layer): def setup(self, bottom, top): """Setup the TripletSamplingLayer.""" ...
from invoke import task CI_NAME = 'compose' PIPELINE_NAME = 'main' @task def ci_server(c): c.run('docker-compose up -d') @task(ci_server) def concourse_login(c): c.run(f'fly login -t {CI_NAME} -u test -p test -c http://localhost:8080') @task(concourse_login) def set_pipelines(c): c.run(f'fly -t {CI_...
from django.db import models # 经纪公司 class ManagementCompany(models.Model): id = models.AutoField(primary_key=True) # 数据库 自增ID create_time = models.DateTimeField(auto_now_add=True) ...
# Made by Mr. Have fun! # Version 0.3 by DrLecter import sys from ru.catssoftware.gameserver.model.quest import State from ru.catssoftware.gameserver.model.quest import QuestState from ru.catssoftware.gameserver.model.quest.jython import QuestJython as JQuest qn = "213_TrialOfSeeker" DUFNERS_LETTER_ID, TERYS_ORDER1_...
#!/usr/bin/env python import errno import json import ntpath import os import requests import shutil import stat import StringIO from subprocess import call import sys import time import urllib2 import zipfile sys.path.append(os.path.abspath('/home/pi/telemetry/')) from config import couchdb_baseurl, wxoutside_domai...
#!/usr/bin/env python import sys import subprocess as sp import json msg = ''' A simple script which uses minhash to find distances between a sample and hmp sites Arguments are rudimentary and positional: <cmd> [hmp site minhash] [sample minhash] Output is a JSON string to stdout and in the following form:...
""" Used for screening anomolies in demand data Copied and modified from https://github.com/truggles/EIA_Cleaned_Hourly_Electricity_Demand_Code/blob/master/step2_anomaly_screening.ipynb """ import pandas as pd import numpy as np import os from datetime import datetime def add_rolling_dem(df, short_hour_window, value...
from __future__ import print_function import sys from tox.session import prepare as tox_prepare from detox import __version__ from detox.proc import Detox def main(args=None): args = sys.argv[1:] if args is None else args if args and args[0] == "--version": print("detox {} running as plugin in tox:...
#encoding=utf8 # 作者:挖数 # 链接:https://www.zhihu.com/question/28975391/answer/100796070 # 来源:知乎 # 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 import requests import urllib2 import re import random from time import sleep def main(): url='https://www.zhihu.com/question/31106546' set_headers = {'Host':'https://www.zhihu.com...
__author__='Josh Fass' ''' contains all metric learning algorithms under consideration''' from msmbuilder.decomposition import tICA class MetricLearner(): ''' abstract class representing a metric learning algorithm that can either embed an object into a vector space compute the distance''' def __ini...
from keystoneauth1 import loading from keystoneauth1 import session from novaclient import client """ load from env auth_url=os.environ["OS_AUTH_URL"], username=os.environ["OS_USERNAME"], password=os.environ["OS_PASSWORD"], user_domain_id=os.environ["OS_USER_DOMAIN_ID"], project_...
""" Utility functions to fit and apply coordinates transformation from PTL (petal local) to FP (focal plane ~ CS5) """ import numpy as np #from desimeter.log import get_logger from desimeter.io import load_petal_alignement from desimeter.transform import rszn_lookups petal_alignment_dict = None # rotation matrices ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import emoticonvis.apps.enhance.fields from django.conf import settings import emoticonvis.apps.base.models class Migration(migrations.Migration): dependencies = [ ('corpus', '0001_initial'), ...
import os import sys import click import cv2 import numpy as np from tqdm import tqdm from utils.image import resize_image sys.path.append(os.getcwd()) from utils.prepare.utils import orderConvex, shrink_poly @click.command() @click.option('--input', '-i', default='mlt_selected') @click.option('--output', '-o', def...
# -*- coding: utf-8 -*- """version file.""" __version__ = '1.3.2' import os import sys import time import subprocess as sp import webbrowser def get_tshark_status(): """Errors and quits if tshark is not installed. On Windows, tshark may not be recognized by cmd even if Wireshark is installed. On Windows...
import os import sys import shutil def dir_name(dir_path): """ 转换零时文件夹、输入文件夹路径 :param dir_path: 主目录路径 :return:[tmp_dir, input_dir, res_dir] """ tmp_dir = dir_path + "tmp\\" input_dir = dir_path + "input\\" res_dir = dir_path + "result\\" return tmp_dir, input_dir, res...
"""Command line functions for training language models""" from __future__ import annotations import os from typing import TYPE_CHECKING, List, Optional from montreal_forced_aligner.command_line.utils import validate_model_arg from montreal_forced_aligner.exceptions import ArgumentError from montreal_forced_aligner.la...
from fastapi import FastAPI from .routes import urls app = FastAPI(title="URL Shortener", version="1.0.0", docs_url="/docs") app.include_router(urls.router)
#!/usr/bin/env python3 import requests # This example shows how a file can be uploaded using # The Python Requests module url = "http://localhost/upload/" with open('/usr/share/apache2/icons/icon.sheet.png', 'rb') as opened: r = requests.post(url, files={'file': opened})
import graphene import bcrypt from datetime import datetime from bson.objectid import ObjectId from ..database import RegistrationModel from mongoengine import DoesNotExist class Registration: def __init__(self, registration=None, id=None, identifier=None, registration_date=None): if registration != None:...
# -*- coding:utf-8 -*- """ This is a Django_ integration of Select2_. The app includes Select2 driven Django Widgets and Form Fields. .. _Django: https://www.djangoproject.com/ .. _Select2: http://ivaynberg.github.com/select2/ Widgets ------- These components are responsible for rendering the necessary JavaScript a...
import os as _os import re as _re import discord import shutil class Cours(): def __init__(self): self.donnees = {} self.path_main = _os.path.dirname(_os.path.realpath(__file__)) async def save(self, matiere, nom, list_fic): path_matiere = "_".join(matiere.upper().split("-")) ...
import numpy as np import torch import os from torch.utils.data import Dataset #import pandas as pd #from torchvision import transforms, utils #import struct #import cv2 # dt = 30, step = 3 #自定义数据加载类 class DVSGesture(Dataset): def __init__(self, path, train, step, dt): super(DVSGesture, self).__...
""" Compares trajectories between learned and ground truth environment """ import argparse import gym import matplotlib.pyplot as plt import sys sys.path.append('./') # TODO Hacky, remove by reorganizing the python folder structure. from environments.learned_pendulum import LearnedPendulumEnv from utils.plot_utils i...
# coding=UTF-8 import binascii import os import sys import tempfile import textwrap import time from pytest import raises, mark import duct from duct import cmd, StatusError try: from pathlib import Path has_pathlib = True except ImportError: has_pathlib = False NEWLINE = os.linesep.encode() # Windows...
import pygame import numpy as np from time import sleep SCREEN_WIDTH = 480 SCREEN_HEIGHT = 600 BIG_LINE_WIDTH = 4 # BIG_LINE_COLOR = (33, 109, 148) BIG_LINE_OFFSET = 0 SMALL_LINE_WIDTH = 2 # SMALL_LINE_COLOR = (3, 29, 66) SMALL_LINE_OFFSET = 6 GRID_COLOR_SOLVING = (3, 29, 66) GRID_COLOR_SOLVED = (20, 227, 62) GRID...
#!/usr/bin/env python ''' `apply_if_or_else` tests for `opyttional` package. ''' from nanto import isanan value_battery_without_nan = [ 0, 1, 0.0, 1.0, float('inf'), None, False, True, '', 'None', 'hello', [], [None], ['greetings'], [[]], ] def test_with_...
print min(((i*j*(i+1)*(j+1)/4,i*j) for i in xrange(10000) for j in xrange(100)), key = lambda x:abs(x[0] - 2 * 10 ** 6))
import sys import argparse from nsvision import classifier description = """ This script renames the files in the folder. Rename format is as follow- {fix_name}_{number}.{extension} There will be a fix or common name for all the files in the folder followed by a unique number and with the orignal file extension. The f...
#!/usr/bin/env python3 import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy import stats from math import sqrt from matplotlib import cm # matplotlib settings for LaTeX plt.rc('text', **{'usetex': True}) plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': 12})...
""" History: - 2014-08-05: Updated by mlr because it was not working, however, in middle of update, site appeared to change. At first there were about five columns in the table and scraper was failing. Soon, there were seven and the scraper started working without my fixing it. Very odd. """ from...
from jmeter_api.basics.thread_group.elements import BasicThreadGroup, ThreadGroupAction import xmltodict import pytest def test_basic_thread_group_parameter_num_threads_type_check(): with pytest.raises(TypeError, match=r".*must be int.*"): BasicThreadGroup(num_threads='qweasd') def test_basic_thread_gro...
import os import shutil import sys import gym_vecenv import gym def check_logdir(log_dir): # raise warning if log directory already exists if os.path.exists(log_dir): print('\nLog directory exists already! Enter') ch = input('c (rename the existing directory with _old and continue)\ns (stop)!...
# -*- coding: utf-8 -*- import scrapy class Item(scrapy.Item): country = scrapy.Field() title = scrapy.Field() date = scrapy.Field() body = scrapy.Field() link = scrapy.Field() class AlbaniaSpider(scrapy.Spider): name = "albania" allowed_domains = ["dogana.gov.al"] start_urls = ( ...
import asyncio import concurrent import logging import sys from announcer import Announcer from states import State MIN_PLAYERS = 2 FINAL_GUESS_DOUBT = "doubt" FINAL_GUESS_FIT = "fit" class DudoStateMachine(Announcer): def __init__(self, sender): Announcer.__init__(self, sender) self.logger = lo...
from __future__ import annotations from dataclasses import dataclass from enum import Enum, unique from pylox.lox_types import LoxType @unique class TokenType(Enum): LEFT_PAREN = "(" RIGHT_PAREN = ")" LEFT_BRACE = "{" RIGHT_BRACE = "}" COMMA = "," DOT = "." SEMICOLON = ";" PLUS = "+...
#!/usr/bin/env python import os import sys import argparse from argparse import RawTextHelpFormatter import time import matplotlib.pyplot as plt import numpy as np from functools import reduce import torch import torch.nn as nn from torch.optim import Adam import torch.distributed as dist from torch.backends import c...
#!/usr/bin/env python #encoding=utf-8 ''' @Time : 2020/10/25 22:28:30 @Author : zhiyang.zzy @Contact : zhiyangchou@gmail.com @Desc : 训练相似度模型 1. siamese network,分别使用 cosine、曼哈顿距离 2. triplet loss ''' # here put the import lib from model.bert_classifier import BertClassifier import os import time from num...
import csv import json import codecs import os.path from optparse import OptionParser import sources def main(): usage = "%prog metadata.csv metadata.json" parser = OptionParser(usage=usage) (options, args) = parser.parse_args() output = args[1] metadata = {} SOURCES = sources.SOURCES s...
""" Revision ID: 0367_add_reach Revises: 0366_letter_rates_2022 Create Date: 2022-03-24 16:00:00 """ import itertools import uuid from datetime import datetime from alembic import op from sqlalchemy.sql import text from app.models import LetterRate revision = '0367_add_reach' down_revision = '0366_letter_rates_20...
# Goal: compare different implementation to see which one is faster import torch import matplotlib.pyplot as plt import numpy as np import neighbors import time from scipy.spatial import cKDTree def compute_batch_radius_with_scipy(x, y, batch_x, batch_y, radius): x_ = torch.cat([x, 2 * radius * batch_x.view(-1,...
from setuptools import setup, find_packages from torch.utils.cpp_extension import BuildExtension, CUDAExtension import os EXT_SRCS = [ 'csrc/mish_cuda.cpp', 'csrc/mish_cpu.cpp', 'csrc/mish_kernel.cu', ] setup( name='mish_cuda', version='0.0.3', packages=find_packages('src'), package_dir={''...
import unittest from unittest import TestCase, mock class test_soca(TestCase): pass if __name__ == '__main__': unittest.main()
""" This sub-module includes all of the interaction with dynamo """ import logging from collections import defaultdict from .. import opts LOG = logging.getLogger(__name__) # This is the old version of connecting to dynamo if opts.V1: LOG.warning('Using v1 of dynamo interface') from .v1 import inventory ...
#!/usr/bin/python import pika import logging import argparse LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' '-35s %(lineno) -5d: %(message)s') LOGGER = logging.getLogger(__name__) class Consumer: def __init__(self, url, gatewayId, exchange, queue): self._url = url ...
#!/usr/bin/env python """DESC: This module Contains the train and prepare data operations within special algorithm.""" from __future__ import division, print_function from xt.algorithm.algorithm import Algorithm from xt.algorithm.algorithm import AGENT_PREFIX, MODEL_PREFIX __ALL__ = [ "Algorithm", "alg_build...
import datasets from raft_baselines.classifiers import NaiveBayesClassifier train = datasets.load_dataset( "ought/raft", "neruips_impact_statement_risks", split="train" ) classifier = NaiveBayesClassifier(train) print(classifier.classify({"Paper title": "CNN research", "Impact statement": "test2"}))
#!/bin/python3 """Clusters a graph""" import networkx as nx import community as lv import cli def main(): input_file, output_file = cli.get_file_conversion_arguments('input.gml', 'clustering_file') graph = nx.read_gml(input_file) partition = lv.best_partition(graph) with open(output_file, "w") as fil...
# unit tests for rates from pynucastro.nucleus import Nucleus from pytest import approx class TestNucleus: @classmethod def setup_class(cls): """ this is run once for each class before any tests """ pass @classmethod def teardown_class(cls): """ this is run once for each clas...
#!/usr/bin/python import RNA ##install viennaRNA python binding first ##for each gene, grab 3' most 100nt for folding genename="RN7SL1" ##grabing gene info and sequence import httplib2 import json try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse headers = { 'Accept': 'appl...
# MK Jul 2016 import logging.config logging.config.fileConfig('logging.conf') logger = logging.getLogger('runner') import os import ConfigParser import subprocess from db.Apps import Apps from db.CodeAnalysis import CodeAnalysis from db.Drozer import Drozer # initialize configuration parser config = ConfigParser.R...
from typing import List class Solution: def maxArea(self, height: List[int]) -> int: i, j = 0, len(height) - 1 ans = (j - i) * min(height[i], height[j]) while i < j: if height[i] < height[j]: i += 1 else: j -= 1 ans = max(...
# -*- coding: utf-8 -*- from setuptools import setup setup( name='ninepatch', version='0.1.19', author='Thomas Schüßler', author_email='vindolin@gmail.com', packages=['ninepatch'], scripts=['bin/ninepatch', 'bin/ninepatch_viewer'], url='https://github.com/vindolin/ninepatch', license=op...
""" This script provides an example to wrap UER-py for ChID (a multiple choice dataset). """ import sys import os import argparse import json import random import torch uer_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) sys.path.append(uer_dir) from uer.layers import * from uer.encoders import *...
from distutils.core import setup setup( name = 'csv2latex', packages = ['csv2latex'], version = '0.11', description = 'Simple script in python to convert CSV files to LaTeX table', long_description="Simple script in python to convert CSV files to LaTeX table", author = 'Sepand Haghighi & Nima Mohammadi', ...
"""Kerasの各種モデル。""" # pylint: skip-file from . import darknet53 from . import xception
import unittest from oeqa.oetest import oeRuntimeTest from oeqa.utils.decorators import * class DfTest(oeRuntimeTest): @skipUnlessPassed("test_ssh") def test_df(self): (status,output) = self.target.run("df / | sed -n '2p' | awk '{print $4}'") self.assertTrue(int(output)>5120, msg="Not enough ...
import demistomock as demisto # noqa: F401 from CommonServerPython import * # noqa: F401 def main(): outputs: Dict[str, Any] = {} readable_output = '' err = None args = demisto.args() pwd_generation_script = args.get("pwdGenerationScript") username = args.get("sAMAccountName") user_emai...
from model import * # Helper def lenVector(x, y): return sqrt(x * x + y * y) def normalizeVector(x, y): l = sqrt(x * x + y * y) if l == 0: l = 0.001 return (x / l, y / l) def partition(pred, data): yes, no = [], [] for d in data: (yes if pred(d) else no).append(d) retu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Feb 13 22:07:00 2021 @author: ali """ import angr,claripy class _memmove_vul(angr.SimProcedure): def run(self,dst_addr, src_addr ,limit): strlen = angr.SIM_PROCEDURES['libc']['strlen'] memcpy = angr.SIM_PROCEDURES['libc']['memcp...
# empty settings file. just to have one
# Copyright (c) 2010 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'android_java', 'type' : 'none', 'variables': { 'jar_path': '<(android_sdk)/android.jar', ...
import py class TestJitTraceInteraction(object): def test_trace_while_blackholing(self): import sys l = [] printed = [] def trace(frame, event, arg): l.append((frame.f_code.co_name, event)) return trace def g(i, x): if i > x - 10: ...
#!/usr/bin/env python """A generic serializer for python dictionaries.""" import collections from grr.lib import rdfvalue from grr.lib import utils from grr.lib.rdfvalues import structs as rdf_structs from grr.proto import jobs_pb2 class KeyValue(rdf_structs.RDFProtoStruct): protobuf = jobs_pb2.KeyValue class ...
import FWCore.ParameterSet.Config as cms from Configuration.StandardSequences.Eras import eras process = cms.Process('RECOgpu', eras.Run2_2018) # import of standard configurations process.load('Configuration.StandardSequences.Services_cff') process.load('FWCore.MessageService.MessageLogger_cfi') process.load('Hetero...
from datetime import datetime, timedelta from typing import Union from jose import jwt from passlib.context import CryptContext from sqlalchemy.orm.session import Session from configurations.constants.security import ( ACCESS_TOKEN_EXPIRE_MINUTES, ALGORITHM, SECRET_KEY ) from configurations.messages.err...
from typing_extensions import Literal from rclonepy.ifaces.cmds_iface import RcloneCmd from rclonepy.ifaces.shell_actor_iface import ShellActorIface def _CMD_NAME_(actor: ShellActorIface, source: str, flags=None, **kw) -> str: """ _DOCS_TEXT_ """ ucmd = RcloneCmdItem(source=source, flags=flags) re...
"""API Handler Class""" # standard library import gzip import os import shutil from logging.handlers import RotatingFileHandler from typing import Optional class RotatingFileHandlerCustom(RotatingFileHandler): """Logger handler for ThreatConnect Exchange File logging.""" def __init__( self, f...
_base_ = ['pix2pix_moe_linear.py'] dataroot = 'data/paired/moe_pidinet_2' data = dict(train=dict(dataroot=dataroot)) # runtime settings exp_name = 'pix2pix_moe_pidinet_2' work_dir = f'./work_dirs/experiments/{exp_name}'
"""Details a visit in the past""" import rows.model.object import rows.model.carer import rows.model.visit import rows.util.parse class PastVisit(rows.model.object.DatabaseObject): # pylint: disable=too-many-instance-attributes """Details a visit in the past""" VISIT = 'visit' CARER = 'carer' CANC...
import unittest import RMF import subprocess class Tests(unittest.TestCase): def test_help(self): """Test rmf3_dump --help""" p = subprocess.Popen(['rmf3_dump', '--help'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PI...
import os import vtk, qt, ctk, slicer, logging # # Abstract class of python scripted subject hierarchy plugins # class AbstractScriptedSubjectHierarchyPlugin(object): """ Abstract scripted subject hierarchy plugin for python scripted plugins USAGE: Instantiate scripted subject hierarchy plugin adaptor class ...
from alarm.page.ding_talk import DingTalk from backstage_data_migrate.config import ROBOT_TOKEN from cookie.model.data import Data from cookie.page.hupun_login_third import HupunLoginThird from pyspider.libs.base_crawl import * class HupunLoginEntry(BaseCrawl): """ hupun 的 cookie 获取的入口地址的第 2 个链接 """ ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Mar 26 12:13:01 2017 @author: sebastian """ import numpy as np import matplotlib.pyplot as plt def logistic_function(w, x): # TODO implement the logistic function return np.dot(w.transpose(), x.transpose()) # change this line # To make it ea...
# Generated by Django 3.0.8 on 2020-07-21 20:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("api", "0084_merge_20200611_1311"), ("api", "0084_task_reviewers"), ] operations = []
from flask import Flask, request from flask_cors import CORS from naoqi import ALProxy import math def move(Stepsinput): motion = ALProxy("ALMotion", "172.20.10.9", 9559) motion.setStiffnesses("Body", 1.0) motion.moveInit() motion.moveTo(float(Stepsinput), 0, 0) print (Stepsinput) return def talk(text): tts ...
import re from collections import defaultdict, namedtuple from dataclasses import dataclass from itertools import product from math import prod from typing import List, Dict, Any, Tuple import aocd from . import aoc_year from loguru import logger aoc_day = 8 def unescape(raw: str): parsed = [] i = 0 whil...
from .__version__ import __application_name__, __author__, __version__, __author_email__, __url__, __title__, __download_url__, __description__ from .tobool import to_bool
from __future__ import print_function import threading from state import GetState, PrintState, RestoreState import multiprocessing import numpy import random import sys, pprint import os import globals import colorama import rTree from timer import globalTimer, DURATION from dataStructures import rL_APE, rL...
import os from pyfakefs import fake_filesystem_unittest from mock import patch from shellfoundry.utilities.config_reader import Configuration, CloudShellConfigReader, ShellFoundryConfig class TestConfigReader(fake_filesystem_unittest.TestCase): def setUp(self): self.setUpPyfakefs() def test_read_con...
""" Order fill logic. Feels good but could use a through code review. """ from ..orders import Order from ..accounts import Account from ..assets import Option from ..positions import Position from ..adapters.quotes import QuoteAdapter from ..estimators import Estimator from math import copysign from .maintena...
import torch import torch.nn as nn import torch.nn.functional as F class GLU(nn.Module): r""" Overview: Gating Linear Unit. This class does a thing like this: .. code::python # Inputs: input, context, output_size # The gate value is a learnt function of the in...
from aoc21.p09 import parse_input, sum_risk_levels, top_3_basin_sizes_multiplied def test_example(): data = """ 2199943210 3987894921 9856789892 8767896789 9899965678 """.strip().splitlines() heightmap = parse_input(data) assert sum_risk_levels(heightmap) == 15 assert top_3_basin_sizes_multiplied(heig...
import poly import sample a=[-1,0,1] b=[1,2,-1] q=8192 n=3 out=poly.rq_mul(a,b,q,n) print(out) print(sample.arr_to_str_integer(b)) print(sample.arr_to_str_ternary(a))
# System import argparse # Math import numpy as np import math # Visualize import progressbar # Pytorch import torch import torch.nn as nn from torch.utils.data import DataLoader # Custom from loader import * from libs.projections import bin2Sphere from utils import getAngle def evaluate(module): lista = [] listb = ...
from Combinatorics import choose def neg_binomial_eq(r,p,k): return choose(k+r-1,k)*(1-p)**r*p**k class NegativeBinomialDist: def __init__(self,r,p): assert r > 0 assert p > 0 and p < 1 self.p = p self.r = r self.mean = p*r/(1-p) self.var = (p*r)/(1-p)**2...
import autoarray as aa import numpy as np import pytest from autoarray.mock.mock import MockFit class TestFitImaging: def test__image_and_model_are_identical__no_masking__check_values_are_correct(self): mask = aa.Mask2D.manual( mask=[[False, False], [False, False]], sub_size=1, ...
from typing import Dict, Iterator, List import torch import torch.nn as nn from torch.autograd import Variable from allennlp.modules.text_field_embedders import TextFieldEmbedder from allennlp.modules.matrix_attention.cosine_matrix_attention import CosineMatrixAttention class KNRM(nn.Modul...
import KratosMultiphysics import KratosMultiphysics.KratosUnittest as UnitTest import KratosMultiphysics.ChimeraApplication from KratosMultiphysics.ChimeraApplication.fluid_chimera_analysis import FluidChimeraAnalysis class ChimeraAnalysisBaseTest(UnitTest.TestCase): def setUp(self): # Set to true to get ...
from .dann import DANN from .deep_jdot import DeepJDOT # from .jdot import JDOT
#coding: utf-8 """ Reverse a string - Enter a string and the program will reverse the string and print out. """ if __name__ == '__main__': # Prompt to the user for the string string = raw_input("Please, ingress a string to invert: ") # Invert the string using slice syntax [begin:end:step] reversed_st...
# Dictionaries Example students = { 'Akash': '0001', 'Binoy': '0002', 'Cheteshwar': '0003', 'Durga': '0004', 'Vinay': '0005', 'Yash': '0006' } print(students) # Add Student to Dictionary students['Yashica'] = '0007' print("Dictionary --> When new student is added") print(students) # Delete ...
# -*- coding: utf-8 -*- import numpy as np import pandas as pd from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler, MinMaxScaler from dramkit.gentools import con_count, isnull class ExternalStd(object): '''极端值处理,标准差倍数法''' def __init__(self, nstd=3, cols=None): ra...
# Copyright 2021 Universität Tübingen, DKFZ and EMBL for the German Human Genome-Phenome Archive (GHGA) # # 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 # # https://www.apache.org/licenses...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @created: 25.11.19 @author: felix """ from typing import Mapping, Optional class PermaDict(dict): silent: bool def __init__(self, seq=None, **kwargs): self.silent = kwargs.pop('silent', False) seq = seq if seq is not None else {} supe...
#!/usr/bin/env python from flask import Flask, jsonify, request, render_template, abort, redirect, url_for from textblob import TextBlob from textblob.utils import strip_punc import emote import os from werkzeug.utils import secure_filename from flask import send_from_directory UPLOAD_FOLDER = '/' ALLOWED_EXTENSIONS =...