text
stringlengths
1
927k
# -*- coding: utf-8 -*- from __future__ import unicode_literals """ Holds all the information relevant to the client (addresses for instance) """ from six import with_metaclass from django.db import models from django.template.loader import select_template from django.utils.translation import ugettext_lazy as _ from ...
""" Test slider callbacks """ import vcs.vtk_ui from vtk_ui_test import vtk_ui_test from decimal import Decimal class test_vtk_ui_slider_callbacks(vtk_ui_test): def do_test(self): self.win.SetSize(100, 100) slider = vcs.vtk_ui.Slider(self.inter, point1=(.1, .5), point2=(.9, .5), end=self.end_callba...
""" Copyright (C) 2018-2020 Intel Corporation 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 i...
from .enumerator import Enumerator from .line_skeleton import LineSkeletonEnumerator, LineSkeletonIterator
import torch import numpy as np import os from datetime import datetime import glob import matplotlib.pyplot as plt plt.switch_backend('agg') from collections import deque from torchvision import transforms def save_checkpoint(state, is_best=0, gap=1, filename='models/checkpoint.pth.tar', keep_all=False): torch.s...
import cProfile import logging import os import pstats import sys import warnings from datetime import datetime import numpy as np import pandas as pd import pandas.api.types as pdtypes from future import standard_library from .base_backend import ComputationalBackend from .feature_tree import FeatureTree from featu...
from typing import Optional # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: # recursive solution # Depth-first search going right, then left def invertTre...
import os import signal import sys import threading import time import traceback from datetime import datetime from win32com.client import constants from win32com.client.gencache import EnsureDispatch def getdocsfolder(): # Gets local user document folder and appends 'Autosaves' oshell = EnsureDispatch("Wscr...
# -*- coding:utf-8 -*- # pylint: disable=no-member import csv import numpy as np from scipy.sparse.linalg import eigs from .metrics import mean_absolute_error, mean_squared_error, masked_mape_np def search_data(sequence_length, num_of_batches, label_start_idx, num_for_predict, units, points_per_hour...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
from pathlib import Path from dynamic_yaml import load with (Path(__file__).parent / 'config.yaml').open() as f: CONFIG = load(f)
#!/bin/python3 import math import os import random import re import sys from functools import cache import time from bisect import bisect,insort @cache def get_sub_sum(temp_sum,removed,added,modulo): return (temp_sum-removed+added)%modulo def maximumSum_iter_2(a, m, a_sum): if len(a) == 0: return 0 if le...
from django.contrib import admin from .models import Category, Recipe, Ingredient, RecipeVote @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ( "id", "name", "owner", "description", ) search_fields = ( "name", "owner" ) ...
# -*- coding: utf-8 -*- """ 用数组实现队列queue:用数组实现的队列是顺序队列,主要操作有入队和出队操作。 """ from typing import Optional class DynamicQueue: """ 算法步骤: 1.入队列 (1)判断尾指针大小是否位等于队列存储容量 是 (1.2)判断头指针是否位于队列开头, 是,队列已满,无法插入 否,队列未满,将队列进行前部搬移 a.数据整段往前重新复制搬移 b.将尾...
# Copyright 2015, Ansible, Inc. # Luke Sneeringer <lsneeringer@ansible.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 requi...
""" 一个制作替换头像背景颜色的小工具(可以自制证件照~) resetbg.py img_file color[blue|red|white] """ import sys import removebg from removebg import RemoveBg from PIL import Image class Color(object): BLUE = (30, 144, 255) RED = (255, 48, 48) WHITE = (255, 255, 255) @staticmethod def getColor(color): return { ...
# Description: Dictionaries in Python # Note # 1. A dictionary is an UNORDERED key: value pairs, with the requirement that the keys are unique within a dictionary. # 2. Dictionary in other languages are also called "associative memories", "associative arrays", "hash map" etc. # 3. Dictionary Keys # - Dictionaries a...
from logging import disable import os import signal import asyncio import uuid import aiohttp import functools from typing import List, Optional from fastapi import FastAPI import websockets from opal_common.logger import logger, configure_logs from opal_common.middleware import configure_middleware from opal_common....
from ..common.opinions.opinion import Opinion class RuSentRelOpinion(Opinion): def __init__(self, value_source, value_target, sentiment): assert(',' not in value_source) assert(',' not in value_target) super(RuSentRelOpinion, self).__init__(source_value=value_source, ...
import abc from typing import Union from ..master.master import Master, _Shards from ..master.client import MasterClient from ..shard.client import ShardClient from ..core.client import ClientError from ..core.typing import Key, Doc, Hash class AbstractResult(abc.ABC): @abc.abstractmethod def result(self) ->...
import asyncio import aiohttp import requests from top_articles.models import Story from django.core.exceptions import ObjectDoesNotExist def check_db_story_ids(articlesID_list): new_articleID_list = [] for id in articlesID_list: try: Story.objects.get(id=id) except ObjectDoesNotExi...
import numpy as np import cv2 import tensorflow.keras as keras from tensorflow.keras.preprocessing import image import numpy as np # ------------------------------------------------------------------- # Load models # ------------------------------------------------------------------- # Load the trained model mask_net...
input0 = """button_clicked cycle_complete button_clicked button_clicked button_clicked button_clicked button_clicked cycle_complete""" input1 = """button_clicked cycle_complete button_clicked block_detected button_clicked cycle_complete button_clicked block_cleared button_clicked cycle_complete""" class GarageDoor(ob...
# Copyright 2020-present, Netherlands Institute for Sound and Vision (Nanne van Noord) # # 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 # #...
from typing import Callable from typing import List from typing import Optional from typing import Sequence from typing import Union import warnings from optuna.distributions import CategoricalDistribution from optuna.distributions import LogUniformDistribution from optuna.study import Study from optuna.trial import F...
""" Kubernetes CIS rules verification. This module verifies correctness of retrieved findings by manipulating audit and remediation actions """ from datetime import datetime import pytest import time from commonlib.utils import get_evaluation from product.tests.tests.process.process_test_cases import * @pytest.mark...
#!/usr/bin/env python from setuptools import setup, find_packages packages = [package for package in find_packages() if package.startswith('neotiles')] version = '0.4.0' install_requires = [ 'wrapt', ] setup_requires = [ 'pytest-runner' ] tests_require = [ 'pytest', 'pytest-cov', ...
from flask import Flask, flash, render_template, request, session, redirect, url_for import flask_login from sqlalchemy import create_engine, Column, Integer, String, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session, sessionmaker from flask_session import Session fro...
''' Created on Oct 13, 2017 @author: svanhmic ''' from pyspark.ml.param.shared import HasInputCol, HasOutputCol from pyspark.ml import Transformer from pyspark.sql import functions as F from pyspark import keyword_only from pyspark.ml.param import Params, Param, TypeConverters class CastInPipeline(Transformer, HasIn...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import json import logging import numpy as np import os import yaml from ray.tune.log_sync import get_syncer from ray.tune.result import NODE_IP, TRAINING_ITERATION, TIME_TOTAL_S, \ TIMESTEPS_TO...
import os from flask import Flask, render_template, abort, request, jsonify # from model import get_cluster, get_cluster_list, types, recover_doc_online from model import Model, types # from setting import repo, port, repositories, upload_folder, import_endpoint import setting from setting import url_prefix import grou...
# from opennre.dataset.converters.converter_semeval2010 import ConverterSemEval2010 # def test_should_return_correct_spacy_sdp_when_doing_sdp_preprocessing_first_example(): # p = ConverterSemEval2010("spacy", "general") # assert p.tokenize("the most common ENTITYSTART audits ENTITYEND were about ENTITYOTHE...
# Copyright 2019 The TensorFlow 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 applica...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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, overload from . import ...
#ArcGIS Server 10.1 service editor #view your service properties at: http://[your server URL]/arcgis/admin/services/ #put a ?f=json at the end of a service name to see the json properties - #the JSON is what is being edited here #Loops through the services in a particular folder and edits the #listSupportedCRS property...
import h5py import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from signals.aux_functions import gaussian_bump import nexa.loading as load from visualization.sensors import visualize_SLM_hdf5 from visualization.sensors import visualize_STDM_hdf5 from visualization.sensor_clusteri...
############################################################################### # PyDial: Multi-domain Statistical Spoken Dialogue System Software ############################################################################### # # Copyright 2015 - 2017 # Cambridge University Engineering Department Dialogue Systems Grou...
from ObjectCollection import * import TclCommand class TclCommandIsolate(TclCommand.TclCommandSignaled): """ Tcl shell command to Creates isolation routing geometry for the given Gerber. example: set_sys units MM new open_gerber tests/gerber_files/simple1.gbr -outname margin ...
# Generated by Django 3.0.3 on 2020-08-19 23:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('predictor', '0002_review'), ] operations = [ migrations.AlterField( model_name='review', name='dokumen_relevan', ...
""" WSGI config for mis project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application if os.getenv("DJANGO_MODE").lower() !...
import numpy as np def accuracy(output, target, topk=(1,)): """Computes the accuracy@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] ...
import sys from time import * import serial import serial.tools.list_ports as serial_tools from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5 import QtCore, QtGui, QtWidgets import pista as base #---------------------------- VARIAVEIS GLOBAIS global tempo_sensor tempo_sensor = { 'contador_do_timer' :...
from panda3d.core import Point3, VBase3, Vec3, Vec4 from toontown.betaevent.DistributedEvent import DistributedEvent from toontown.betaevent import CogTV from toontown.hood import ZoneUtil from direct.fsm import ClassicFSM, State from direct.interval.IntervalGlobal import * from toontown.toon import Toon, ToonDNA from...
# -*- coding: utf-8 -*- """Click commands.""" import os from glob import glob from subprocess import call import click from flask import current_app from flask.cli import with_appcontext from werkzeug.exceptions import MethodNotAllowed, NotFound HERE = os.path.abspath(os.path.dirname(__file__)) PROJECT_ROOT = os.path...
import json from datetime import date, time from urllib.parse import parse_qs import pytest from freezegun import freeze_time from tests.utils import file_response, read_test_file_content from city_scrapers.constants import CITY_COUNCIL from city_scrapers.spiders.chi_citycouncil import ChiCityCouncilSpider INITIAL_R...
from minidoc import minidoc from minidoc import tst import argparse from efdir import fs parser = argparse.ArgumentParser() parser.add_argument('-tst','--test_file', default="code.tst.py",help=".tst.py file name") parser.add_argument('-codec','--codec', default="utf-8",help=".tst.py file codec") parser.add_argument('-...
import streamlit as st import json import requests import matplotlib.pyplot as plt import numpy as np URI = 'http://neural-net-viz-flask.herokuapp.com' st.title('Nural Network Visualizer') st.sidebar.markdown('## Input Image') if st.button('Get Random Prediction'): response = requests.post(URI, data={}) resp...
# Generated by Django 2.2 on 2019-06-08 10:37 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('shop', '0002_auto_20190608_1135'), ] operations = [ migrations.RenameModel( old_name='Smart_Watch', new_name='Smart_Watche', ...
from os import path from unittest import TestSuite, TestLoader, TextTestRunner import sys if __name__ == "__main__": # Because the project is structured differently than # any tooling expects, we need to modify the python # path during runtime (or before) to get it to # properly import plugins and othe...
import uuid from django.contrib.auth import get_user_model from django.db import models # Create your models here. from django.urls import reverse class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=250) author = model...
# -*- coding: utf-8 -*- # Copyright (c) 2020, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from coremltools.converters.mil.mil.passes.pass_registry import register_pas...
#!/usr/bin/env python3 import testUtils import argparse import signal from collections import namedtuple import os import shutil ############################################################### # Test for validating consensus based block production. We introduce malicious producers which # reject all transactions. #...
# -*- coding: utf-8 -*- """ Testing class for survey endpoints of the Castor EDC API Wrapper. Link: https://data.castoredc.com/api#/survey @author: R.C.A. van Linschoten https://orcid.org/0000-0003-3052-596X """ import pytest from exceptions.exceptions import CastorException from tests.test_api_endpoints.data_models ...
import os import torch class Dictionary(object): """Build word2idx and idx2word from Corpus(train/val/test)""" def __init__(self): self.word2idx = {} # word: index self.idx2word = [] # position(index): word def add_word(self, word): """Create/Update word2idx and idx2word""" ...
#!/usr/bin/env python import logging import bx.align.maf import cStringIO import os import io import ete2 from flask import Flask, request, send_file LOGFORMAT = '%(asctime)-15s %(name)s %(levelname)s %(message)s' logging.basicConfig(format=LOGFORMAT, level=logging.INFO) logger = logging.getLogger(__name__) ENVSETTIN...
from setuptools import setup, find_packages config = { 'description':'fingerid-package', 'author':'Huibin Shen', 'url':'project https://github.com/icdishb/fingerid', 'author_email':'huibin.shen@aalto.fi', 'version':'1.4', 'install_requires':['nose'], 'packages':find_packages(), 'name':'...
lost_fights = int(input()) helmet_price = float(input()) sword_price = float(input()) shield_price = float(input()) armor_price = float(input()) sum = 0 shield_breaks = 0 for i in range (1, lost_fights + 1): if i % 2 == 0: sum += helmet_price if i % 3 == 0: sum += sword_price if i % 2 ...
# -*- coding: future_fstrings -*- # # Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, # Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, # Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, # Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Di...
# coding: utf-8 """ Quay Frontend This API allows you to perform many of the operations required to work with Quay repositories, users, and organizations. You can find out more at <a href=\"https://quay.io\">Quay</a>. # noqa: E501 OpenAPI spec version: v1 Contact: support@quay.io Generated by: h...
import os import sys import time import numpy from numpy import zeros from numpy.random import randn from scipy.linalg import blas def run_ssyrk(N, l): A = randn(N, N).astype('float32', order='F') C = zeros((N, N), dtype='float32', order='F') start = time.time() for i in range(0, l): blas.ss...
# configuration file for interface "http_1" # this file exists as a reference for configuring HTTP interfaces # # copy this file to your own cage, possibly renaming into # config_interface_YOUR_INTERFACE_NAME.py, then modify the copy config = dict \ ( protocol = "http", # meta listener_address =...
# Copyright 2017 The TensorFlow 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 applica...
from builtins import object import os import cv2 import numpy as np import tensorflow as tf from hailo_model_zoo.core.datasets import dataset_factory from hailo_model_zoo.utils.video_utils import VideoCapture def _open_image_file(img_path): image = tf.io.read_file(img_path) image = tf.cast(tf.image.decode_jp...
from rest_framework import permissions class UpdateOwnProfile(permissions.BasePermission): """Allow user to edit their own profile""" def has_object_permission(self, request, view, obj): """Check user is trying to edit their own profile""" if request.method in permissions.SAFE_METHODS: ...
from copy import deepcopy from typing import NamedTuple, Optional import constants as c def main(): """ Runs a game of tic-tac-toe. Asks players "X" and "O" to alternate choosing squares of the tic-tac-toe board to fill in. After each turn, will check the board to see if there is a winner. If all squ...
#!/usr/bin/env python2 import argparse import json import os from patrace import ( InputFile, OutputFile, Call, CreateInt32Value, ) class Arg: def __init__(self, type, name, value): self.type = type self.name = name self.value = value def get(self): arg = self....
salário = float(input('Digite o valor do seu salário: R$')) if salário <= 1250: novo = salário + (salário * 15 / 100) else: novo = salário + (salário * 10 / 100) print('Quem ganhava R$ {:.2f} passou a ganhar R$ {:.2f}'.format(salário, novo))
# coding: utf-8 """ axxell-api No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); ...
import unittest import tkinter from tkinter import ttk from test.support import requires import sys from tkinter.test.test_ttk.test_functions import MockTclObj from tkinter.test.support import (AbstractTkTest, tcl_version, get_tk_patchlevel, simulate_mouse_click) from tkinter.test.wid...
#!/usr/bin/python # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ import os import re import sys import urllib """Logpuzzle exercise Given an apache logfile, ...
from django import forms from .models import Transactions, GroupMembers,Group class Bill_CreateForm(forms.ModelForm): def __init__(self, user_list, *args, **kwargs): super(Bill_CreateForm, self).__init__(*args, **kwargs) self.fields['share_with'] = forms.MultipleChoiceField(widget=form...
#!/usr/bin/env python # Copyright (c) 2013-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from __future__ import division,print_function,unicode_literals import biplist from ds_store import DSStore...
from sklearn import linear_model from ml.regression.base import Regression class LogisticRegression(Regression): def __init__(self): Regression.__init__(self) self._name = "Logistic" self._model = linear_model.LogisticRegression(C=1e5) def predict_proba(self, data): return se...
import numpy as np PROBS_CONTACTS = np.array([4.0, 2.0, 4.0, 2.0]) PROBS_CONTACTS /= np.sum(PROBS_CONTACTS) RULE_CONTACTS = [ # [0.5, 1.0] -> 4 { 'num_contacts': 1, 'translations': [[0.5, 1.0], [-0.5, 1.0], [0.5, -1.0], [-0.5, -1.0]], 'direction': 0 }, # [0.5, 0.0] -> 2 { ...
from lithopscloud.modules.gen2.endpoint import EndpointConfig from typing import Any, Dict from lithopscloud.modules.utils import get_region_by_endpoint class RayEndpointConfig(EndpointConfig): def __init__(self, base_config: Dict[str, Any]) -> None: super().__init__(base_config) base_endpoin...
from __future__ import absolute_import, division, print_function __metaclass__ = type import math from ansible.module_utils.facts.hardware import linux from ansible.module_utils.facts.utils import get_mount_size def get_mount_info(module): lh = linux.LinuxHardware(module) bind_mounts = lh._find_bind_mounts()...
# ------------------------------ # 230. Kth Smallest Element in a BST # # Description: # Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. # Note: # You may assume k is always valid, 1 ≤ k ≤ BST's total elements. # # Example 1: # Input: root = [3,1,4,null,2], k = 1 # ...
print('exe-004 comandos primitivos') print('Tipos primitivos de comandos -int = inteiro- floot') num1=int(input('Digite um número ')) num2=int(input('Digite outro número ')) soma=num1+num2 fim = 'The End' #print('A soma de',num1, 'e',num2, 'é',soma) print('A soma entre {} e {} vale {}'.format(num1, num2, soma)) prin...
from rest_framework import viewsets from rest_framework import mixins from apps.endpoints.models import Endpoint from apps.endpoints.serializers import EndpointSerializer from apps.endpoints.models import MLAlgorithm from apps.endpoints.serializers import MLAlgorithmSerializer from apps.endpoints.models import MLAlg...
#encoding=utf-8 #Данный пример определяет тип модуля реле или силового ключа подключённого к шине I2C. from pyiArduinoI2Crelay import * # Подключаем библиотеку для работы с реле pwrfet = pyiArduinoI2Crelay() # Объявляем объект pwrfet ...
''' Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual operação ele deseja realizar. O resultado da operação deve ser acompanhado de uma frase que diga se o número é: par ou ímpar; positivo ou negativo; inteiro ou decimal. ''' numero1 = float(input("Digite o número 1: ")) numero2 = float(input("...
import onnx from typing import Iterable def print_tensor_data(initializer: onnx.TensorProto) -> None: if initializer.data_type == onnx.TensorProto.DataType.FLOAT: print(initializer.float_data) elif initializer.data_type == onnx.TensorProto.DataType.INT32: print(initializer.int32_data) eli...
import random import time from functools import partial from itertools import product from blessings import Terminal term = Terminal() WINDOW_WIDTH = term.width // 2 WINDOW_HEIGHT = term.height - 1 WOLF = 'W' RABBIT = 'R' EMPTY = ' ' RABBIT_SURVIVAL = 60 WOLF_SURVIVAL = 80 WOLF_BREED = 80 def random_animal(): ...
""" rename_all.py Usage: $ poetry install $ poetry run python rename_all.py """ from typing import Optional from serde import serde from serde.json import from_json, to_json @serde(rename_all='pascalcase') class Foo: name: str no: Optional[int] = None def main(): f = Foo('Pikachu') print(...
from sanic import Sanic from sanic import response app = Sanic(__name__) @app.route('/') def handle_request(request): return response.redirect('/redirect') @app.route('/redirect') async def test(request): return response.json({"Redirected": True}) if __name__ == '__main__': app.run(host="0.0.0.0"...
import json from urllib.parse import urlencode import pytest from aiohttp import FormData from graphql.execution.executors.asyncio import AsyncioExecutor from graphql.execution.executors.sync import SyncExecutor from aiohttp_graphql import GraphQLView from .schema import Schema, AsyncSchema # pylint: disable=inva...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="autoth-qiuqiangkong", # Replace with your own username version="0.0.3", author="Qiuqiang Kong", author_email="qiuqiangkong@gmail.com", description="Automatic threshold optimization", l...
import numpy as np import condition def solve_matrix(p, Ap, Ae, Aw, An, As, bb, m, n): md = 101 nd = 101 p_old = np.zeros((md, nd)) ''' SOR algorithm ''' iter_max = 300 # SOR max iteration steps relax_factor = 1.8 # SOR relaxation factor for iter_i in range(1, iter_max): erro...
#!/usr/bin/env python """Add Physical Linux Servers to File-based Protection Job Using Python""" ### usage: ./protectLinux.py -v mycluster \ # -u myuser \ # -d mydomain.net \ # -j 'My Backup Job' \ # -s myserver...
def list_sum_recursive(input_list): # Base Case if not input_list: return 0 # Recursive case # Decompose the original problem into simpler instances of the same problem # by making use of the fact that the input is a recursive data structure # and can be defined in terms of a smaller ver...
# Copyright (c) 2021, DjaoDjin inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and t...
''' @author: Roman Briskine, University of Minnesota ''' import os.path; import re; F_VARIANT = 1; F_CLASS = 2; F_POS = 3; F_REF_ALLELE = 4; F_VAR_ALLELE = 5; F_EXON = 9; F_ACC_OFFSET = 13; class PhasedHaplotypeParser(): def __init__(self, accessionN = 3, accessionColN = 7, delim = '\t'): self.accessionN = acces...
"""Fairness metrics. This module gathers various metrics to assess fairness of a machine learning pipeline. TODO: Implement: * duplicated rows with different protected attributes and classes, * sample size disparity (for data and features), * disparate impact, and * disparate treatment. """ # Author:...
""" Created on 14/11/2012 @author: victor """ import pyRMSD.RMSDCalculator import time import numpy import sys #With OpenMP and amber_5k.pdb it took: 2.5554060936 [ 0.0 ] if __name__ == '__main__': coordsets = numpy.load("data/amber_30k.npy") number_of_conformations = coordsets.shape[0] number_of_atoms ...
from unittest.mock import patch from django.test import TestCase from django.contrib.auth import get_user_model from core import models def sample_user(email='test@stuffedpenguinstudio.com', password='testpass'): """Create sample user""" return get_user_model().objects.create_user(email, password) class Mo...
import numpy as np # from gym import spaces from bc_gym_planning_env.envs.base import spaces from collections import OrderedDict from . import VecEnv class DummyVecEnv(VecEnv): def __init__(self, env_fns): self.envs = [fn() for fn in env_fns] env = self.envs[0] VecEnv.__init__(self, len(env...
import dateutil.parser import datetime import time import re import requests from bs4 import BeautifulSoup from comment import Comment from difflib import SequenceMatcher from handlers.AbstractBaseHandler import AbstractBaseHandler, HandlerError from newspaper import Article from nltk.util import ngrams import codecs...
import click from dexp.cli.defaults import _default_workers_backend from dexp.video.overlay import add_overlays_image_sequence @click.command() @click.argument("input_path", type=str) @click.option("--output_path", "-o", type=str, default=None, help="Output folder for overlayed frames.") @click.option("--scalebar/--...
#!/usr/bin/env python3 # # Match SI GBIF records without coordinates to other GBIF records for the species/genus # import psycopg2, os, logging, sys, locale, psycopg2.extras import pandas as pd from time import localtime, strftime from fuzzywuzzy import fuzz import pycountry #Import settings import settings #Set loc...
import asyncio import json import logging import time from pathlib import Path from typing import Any, Callable, Dict, List, Optional, Tuple import traceback import aiohttp from blspy import AugSchemeMPL, G1Element, G2Element, PrivateKey import inan.server.ws_connection as ws # lgtm [py/import-and-import-from] from ...