content
stringlengths
5
1.05M
from math import cos, pi, sqrt INITIAL_X = 0 # meters INITIAL_Y = 5 # meters INITIAL_THETA = 0 # degrees LANDMARK_1_LOCATION = [6, 4] LANDMARK_2_LOCATION = [-7, 8] LANDMARK_3_LOCATION = [6, -4] LANDMARKS = [LANDMARK_1_LOCATION, LANDMARK_2_LOCATION, LANDMARK_3_LOCATION] STD_DEV_LOCATION_RANGE = 0.1 STD_DEV_LOCATION_BE...
from requests_html import HTML from spells.forum import Spell from unittest.mock import patch from unittest.mock import MagicMock from utils.utils import load_html from utils.dummy import DummyResponse class DummyItem: def __init__(self, html): self._html = html @property def html(self): r...
# 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...
import sys import os, os.path import subprocess import numpy if __name__ == "__main__": formula = sys.argv[1] kind = sys.argv[2] program = "bsub" params = ["-n", "4", "-W", "04:00", "-R", "\"rusage[mem=4096]\""] run_string = "\"mpirun -n 4 gpaw-python run_doping.py {0} {1} {2:.2f}\"" for fermi_...
from __future__ import division import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.naive_bayes import MultinomialNB pd.options.mode.chained_assignment = None from sklearn.metrics import confusion_matrix from sklearn.cross_validation import c...
from typing import Iterable, Iterator, Sequence, List, Mapping, Dict def f1() -> Iterable[int]: pass def f2() -> Iterator[int]: pass def f3() -> Sequence[int]: pass def f4() -> List[int]: pass def f5() -> Mapping[str, int]: pass def f6() -> Dict[str, int]: pass for x in f1(): p...
import pandas as pd from .medscore import UserMacros from .models import Food from .views import FOOD_BEV, NUTR CAL_FROM_G_PRO = 4 CAL_FROM_G_CHO = 4 CAL_FROM_G_FAT = 9 def getFoodMacros(foods): ## Get the foods that the user ate for the day serve_field = Food._meta.get_field('servings') name_field = Foo...
from dark_chess_app import login from flask_login import UserMixin # Note that this is a temporary solution to storing user sessions. # it has the distinct disadvatage that it cannot be shared by # multiple processes/servers. Sooner rather than later this should # probably be refactored to make use of redis or somethi...
from .phat import InkyPHAT, InkyPHAT_SSD1608 # noqa: F401 from .what import InkyWHAT # noqa: F401 from . import eeprom def auto(i2c_bus=None): _eeprom = eeprom.read_eeprom(i2c_bus=i2c_bus) if _eeprom is None: raise RuntimeError("No EEPROM detected! You must manually initialise you...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf.urls import url from clock.exports.views import ExportMonth, ExportMonthAPI, ExportContractMonthAPI, ExportNuke urlpatterns = [ # Export URLs url(r'^(?P<year>[0-9]{4})/(?P<month>[0-9]+)/contract/(?P<pk>\d+)/$', ExportMonth.as_vi...
import spotipy from pprint import pprint def main(): spotify = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth()) me = spotify.me() pprint(me) if __name__ == "__main__": main()
from datasets import load_dataset, load_metric import numpy as np dataset = load_dataset("glue", "sst2") datasetTrain = np.asarray(dataset["train"]) print(type(datasetTrain)) # print(datasetTrain) import data_utils import torch from torch.utils.data import Dataset print(type(Dataset)) print(Dataset) class SST2Datase...
from os import kill import numpy as np from void_mesh import * from functions import * d1 = 1 d2 = 1 p = 6 m = 6 R = 0.2 element_type = 'D2QU4N' defValue = 0.1 #Deformation Value NL, EL = void_mesh(d1, d2, p, m, R, element_type) BC_flag = 'extension' ENL, DOFs, DOCs = assign_BCs(NL, BC_flag, defValue) K = ...
from mltoolkit.mldp.steps.preprocessors import BasePreProcessor from mltoolkit.mlutils.helpers.paths_and_files import get_file_paths from numpy import random class GroupFileShuffler(BasePreProcessor): """Reads the paths of group CSV files, shuffles them, and passes along.""" def __init__(self, **kwargs): ...
#!/usr/bin/env python3 import aiohttp import logging from urllib.parse import quote class Session: def __init__(self, url_builder, headers, user = None, password = None, verify_ssl_certs = True): self.logger = logging.getLogger(__name__) self.url_builder = url_builder self.headers = heade...
"""server""" # -*- coding:utf-8 -*-
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-07-05 15:57 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import summer.validators import uuid class Migration(migrations.Migration): initial = True ...
import json import yaml from .batch_cli_utils import get_batch_if_exists def init_parser(parser): parser.add_argument('batch_id', type=int, help="ID number of the desired batch") parser.add_argument('-o', type=str, default='yaml', help="Specify output format", choices=["yaml", "json"]...
""" Library for predicates during queries. """ import abc import db.rtype as rtype # General superclass for all predicates class Predicate(rtype.RType): @abc.abstractmethod def before_query(self): """ Function to run at the beginning of a query chain. Useful for aggregations that have things to res...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. import logging import multiprocessing import os import unittest import warnings import numpy as np from monty.serialization import loadfn from pymatgen import SETTINGS from pymatgen.analysis.pourbaix_diagram...
######################################################################################################## ## pyFAST - Fingerprint and Similarity Thresholding in python ## ## Karianne Bergen ## 11/14/2016 ## ## (see Yoon et. al. 2015, Sci. Adv. for algorithm details) ## ###################################################...
import logging import random from .Genericgeneration import Generation class Classify(Generation): """ Classification class for classifying and categorizing number guess. Attributes: n(integer) - number of attempts """ def __init__(self, n): super().__init__(n) def guess_number(self): ...
curso = 'Programacao em Python Essencial' def funcao2(): return curso
from datetime import datetime from flask import g, has_request_context, request, abort from gatekeeping.db import get_db from gatekeeping.api.audit import create_audit_log from gatekeeping.api.user import get_users_with_password_reset_tokens from gatekeeping.keys import mail from gatekeeping.api.submission import (get_...
print('----------------') print('CAIXA ELETRÔNICO') print('----------------') cd = x = 1 sc = 0 print('\n\033[4;33mNotas disponíveis: [R$50,00] [R$20,00] [R$10,00] [R$1,00]\033[m') v = int(input('\nDigite o valor inteiro que você deseja sacar: R$')) while True: cd = v // x % 10 if cd == 0: break el...
import streamlit as st import os from werkzeug.utils import secure_filename import logging from pathlib import Path import ocrmypdf import zipfile logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) ALLOWED_EXTENSIONS = set(['pdf']) CWD = Path(os.getcwd()) UPLOAD_DIRECTORY = CWD / "results...
import unittest from katas.kyu_6.which_are_in import in_array class InArrayTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(in_array( ['live', 'arp', 'strong'], ['lively', 'alive', 'harp', 'sharp', 'armstrong']), ['arp', 'live', 'strong'])
import os import tempfile import pyblish.api from pype.vendor import clique import pype.api class ExtractReviewSP(pyblish.api.InstancePlugin): """Extracting Review mov file for Ftrack Compulsory attribute of representation is tags list with "review", otherwise the representation is ignored. All new...
# Advent of Code 2020 # Day 19 # Author: irobin591 import os import doctest import re with open(os.path.join(os.path.dirname(__file__), "input.txt"), 'r') as input_file: input_data = input_file.read().strip().split('\n') # Prep Input # input_data = list(map(int, input_data.strip().split('\n'))) re_rule_int = re...
'''A Pure Python DB-API 2.0 compliant interface to ThinkSQL. Copyright © 2000-2012 Greg Gaughan http://www.thinksql.co.uk ''' from string import split,replace import struct import cStringIO import warnings import socket import datetime try: from fixedpoint import FixedPoint h...
#!/usr/bin/env python3 # MEMO #date -r 1584214882 #date -j -f "%Y %j %H %M %S" "2020 12 15 00 00 00" "+%s" import copy import datetime from decimal import Decimal import json import os import subprocess import sys import time import traceback os.system('clear') first_time = True # # order_type: buy/sell # # key: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from contextlib import redirect_stdout # since 3.4 from contextlib import contextmanager from io import StringIO import sys def f1(): s = StringIO() with redirect_stdout(s): print(42) print('='*20) print(s.getvalue(), end='') print('='*20) ...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
import asyncio import logging import pyez ZMQ_REQ_PORT = 9999 WORKER_PORT = 9998 LIVELINESS = 3000 SERVER_DURATION = 2000 def assert_eq(exp, act): if exp != act: raise AssertionError( "expected {}, actual: {}".format(exp, act)) return def new_con(): return pyez.WorkerConnection( ...
import os from pathlib import Path import torch from torch import optim import torch.nn as nn from tqdm import tqdm_notebook as tqdm from .dataset import generate_batches, CBOWDataset from .utils import set_seed_everywhere, handle_dirs, compute_accuracy from .classifier import CBOWClassifier from .utils import make_...
#!/usr/bin/python # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distribut...
bl_info = { "name": "Add heightmap", "author": "Spencer Alves", "version": (1, 0), "blender": (2, 75, 0), "location": "File > Import > Import heightmap", "description": "Generates a mesh from a heightmap image", "warning": "", "wiki_url": "", "category": "Add Mesh", } import bp...
#!/usr/bin/env python # Copyright (c) 2013-2018, Rethink Robotics 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 ...
import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils from h2o.estimators.glm import H2OGeneralizedLinearEstimator ''' Copied example from Honza to fix bug in 2D pdp. Basically, when no figure is plotted, this bug will thrown an error. Hence, this code just needs to run to completion. No a...
import cv2 def save_image(image, folder, now): """ Save an image using OpenCV and then resaves it using PIL for better compression """ filename = '%s/%s.jpg' filepath = filename % (folder, now) cv2.imwrite(filepath, image, [cv2.cv.CV_IMWRITE_JPEG_QUALITY, 80]) # Resave it with pillow ...
import numpy as np from mcts import MCTS class Player: def set_player_ind(self, player_ind): self.player = player_ind def get_action(self, board, temp=1e-3, return_prob=False): pass class MCTSPlayer(Player): """ 基于蒙特卡洛树的电脑玩家 """ def __init__(self, policy_value_function, c_p...
import sys import logging import os from lark import Lark __location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) def run_parser(script, target, debug): if (debug == True): logging.getLogger().setLevel(logging.DEBUG) logging.info("AZ Script Compiler v 0.1") logging...
from includes import * ''' python -m RLTest --test tests_dag_basic.py --module path/to/redisai.so ''' def test_dag_load(env): con = get_connection(env, '{1}') ret = con.execute_command( "AI.TENSORSET persisted_tensor_1{1} FLOAT 1 2 VALUES 5 10") env.assertEqual(ret, b'OK') command = "AI.DAGEX...
import argparse import glob import io import os import re import ssl from time import sleep import zipfile from selenium import webdriver # from selenium.webdriver.common.keys import Keys from webdriver_manager.chrome import ChromeDriverManager import requests from lxml import etree from scour import scour # Scour r...
""" Complete the preOrder function in your editor below, which has parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. """ def traverse_in_order_recursive(root): if root: traverse_in_order_recursive(root.left) ...
from flask import Flask, render_template, request, session, redirect, url_for import pymysql app = Flask(__name__) app.secret_key = '!hv@cRsh0nU' class Merchant: name = "" username = "" password = "" organisation = "" abn = None def __init__(self, name, usrnm, passwd, abn, org): self...
from django.views import View from django.http.response import JsonResponse class HealthCheck(View): def get(self, *args, **kwargs): return JsonResponse(data='Service is up', status=200, safe=False)
from tests.db.data_fixtures import *
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.condenser_equipment_and_heat_exchangers import CoolingTowerTwoSpeed log = logging.getLogger(__name__) class TestCoolingTowerTwoSpeed(unittest.TestCase): def setUp(self): ...
# Copyright 2019 Arie Bregman # # 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 agree...
#! /usr/bin/env python import numpy as np def sparseFrobeniusNorm(X): """ Compute a the Frobenius norm of the observed entries of a sparse matrix. Args: X: a sparse matrix Returns: The square root of the sum of the squares of the observed entries. """ tmp = X.multi...
import gin import tensorflow as tf @gin.configurable class MultiPolicy: def __init__(self, act_spec, logits): self.logits = logits self.inputs = [tf.placeholder(s.dtype, [None, *s.shape]) for s in act_spec] self.dists = [self.make_dist(s, l) for s, l in zip(act_spec.spaces, logits)] ...
from flask import session, flash, redirect, current_app from flask import Blueprint, session, redirect, url_for, render_template #request, , , jsonify auth_routes = Blueprint("auth_routes", __name__) # signup route only for email password auth (not implemented) #@auth_routes.route("/signup") #def signup(): # prin...
# © 2020 지성. all rights reserved. # <[email protected]> # Apache License 2.0 from .base import * from .naive import * from .pg import * from .predict import *
orig = 'abcdefghijklmnopqrstuvwxyz' new = ['@', '8', '(', '|)', '3', '#', '6', '[-]', '|', '_|', '|<', '1', '[]\/[]', '[]\[]', '0', '|D', '(,)', '|Z', '$', '\'][\'', '|_|', '\/', '\/\/', '}{', '`/', '2'] line = raw_input().lower() trans = '' for ch in line: try: trans += new[orig.index(ch)] except:...
from typing import Dict import torch from torchtyping import TensorType from typing import Dict, Optional from tqdm import tqdm from typeguard import typechecked """ # PCA rationale: # check for the constraints , if small, do nothing # if needed, project the result onto the constraints using the proje...
from models.cbamresnet import * from models.pnasnet import * from models.seresnext import * from models.inceptionresnetv2 import * from models.xception import * __all__ = ['get_model'] _models = { 'cbam_resnet50': cbam_resnet50, 'pnasnet5large': pnasnet5large, 'seresnext50_32x4d': seres...
#!/usr/bin/env python from __future__ import print_function from distutils.core import setup from distutils import sysconfig from os.path import join as pjoin, split as psplit import sys import platform setup(name='FEniCSopt', version='0.2', description = "FEniCS optimization package", author = "Petr...
# -*- coding: utf-8 -*- # @Brief: 配置文件 input_shape = (320, 320, 3) num_classes = 21 epochs = 50 batch_size = 4 lr = 0.0001 train_txt_path = "/Users/linzhihui/Desktop/Data/VOC2012/ImageSets/SegmentationAug/train.txt" val_txt_path = "/Users/linzhihui/Desktop/Data/VOC2012/ImageSets/SegmentationAug/val.txt" trainval_txt...
"""Support for hunterdouglass_powerview sensors.""" from aiopvapi.resources.shade import BaseShade, factory as PvShade from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import PERC...
# Code generated by lark_sdk_gen. DO NOT EDIT. from pylark.lark_request import RawRequestReq, _new_method_option from pylark import lark_type, lark_type_sheet, lark_type_approval import attr import typing import io @attr.s class DeleteDepartmentReq(object): department_id_type: lark_type.DepartmentIDType = attr.i...
import re import os import copy import torch import torch.nn as nn import torch.nn.functional as F import torch.distributed as dist import numpy as np from torchvision.models.densenet import model_urls, _DenseLayer, _DenseBlock, _Transition from torchvision.models.utils import load_state_dict_from_url from collections ...
from numpy import maximum from numpy import zeros from gwlfe.BMPs.AgAnimal.NFEN import NFEN from gwlfe.BMPs.AgAnimal.NFEN import NFEN_f from gwlfe.BMPs.Stream.NSTAB import NSTAB from gwlfe.BMPs.Stream.NSTAB import NSTAB_f from gwlfe.BMPs.Stream.NURBBANK import NURBBANK from gwlfe.BMPs.Stream.NURBBANK import NURBBANK_f...
class Solution: def maxSubArray(self, nums: List[int]) -> int: # ans = -float('inf') # sum_ = -float('inf') # for index, element in enumerate(nums): # sum_ = max(sum_ + element, element) # ans = max(ans, sum_) # ...
# -*- coding: utf-8 -*- # # Copyright (c) 2017 - 2019, doudoudzj # Copyright (c) 2012, VPSMate development team # All rights reserved. # # InPanel is distributed under the terms of the (new) BSD License. # The full license can be found in 'LICENSE'. '''Module for Service Management.''' import glob import ...
# coding: utf-8 from __future__ import annotations from datetime import date, datetime # noqa: F401 import re # noqa: F401 from typing import Any, Dict, List, Optional, Union, Literal # noqa: F401 from pydantic import AnyUrl, BaseModel, EmailStr, validator, Field, Extra # noqa: F401 from aries_cloudcontroller.m...
from utils.aioLogger import aioLogger import pandas as pd from typing import List, Tuple, Union from config.aioConfig import heightWeightConfig class heightWeightTimeVerifier: """this class verify the time info""" def __init__(self, sorted_dfs: List[pd.DataFrame]): self.sorted_dfs = sorted_...
from ezcode.list.linked_list import SinglyLinkedList from ezcode.list.stack import Stack, MinStack, MaxStack from ezcode.list.queue import Queue, MonotonicQueue from ezcode.list.lru_cache import LRUCache from fixture.utils import equal_list class Node: def __init__(self, v=None, n=None): self.v = v ...
from email.mime import text import random from configparser import SafeConfigParser import email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import sys import os current_dir = os.path.dirname(os.path....
""" * * Copyright (c) 2017 Cisco Systems, 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: * * Redistributions of source code must retain the above copyright * notice, this lis...
from edutls.record import ContentType from edutls.types import UInt8Enum, UInt16Enum, Protocol class AlertLevel(UInt8Enum): warning = 1, fatal = 2 class AlertDescription(UInt8Enum): close_notify = 0, unexpected_message = 10, bad_record_mac = 20, record_overflow = 22, handshake_failure = ...
import dash_core_components as dcc from dash.dependencies import Input, Output, State from urllib.parse import parse_qs, urlparse from app.models import ElementTemplate def layout(): return dcc.Dropdown(id = "elementTemplateDropdown", placeholder = "Select Element Template", multi = False, value = -1) def options...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' @AUTHOR:Joselyn Zhao @CONTACT:[email protected] @HOME_PAGE:joselynzhao.top @SOFTWERE:PyCharm @FILE:qie.py @TIME:2020/4/18 20:55 @DES: 命名切片 ''' items = [0,1,2,3,4,5,6] a = slice(2,4) print(items[2:4]) print(items[a]) items[a] = [10,11] #局部替换 print(items) print(a.start...
# Write code using find() and string slicing to extract the number at the end of the line below. Convert the extracted value to a floating point number and print it out. # Desired Output # 0.8475 text = "X-DSPAM-Confidence: 0.8475"; pos = text.find(" ") number = text[pos:] number = number.strip() num = fl...
import pathlib import importlib from typing import Any, AsyncIterator, Tuple from dffml import ( config, field, entrypoint, SimpleModel, ModelNotTrained, Feature, Features, Sources, Record, SourcesContext, ) @config class DAAL4PyLRModelConfig: predict: Feature = field("La...
#+ # Copyright 2015 iXsystems, Inc. # All rights reserved # # Redistribution and use in source and binary forms, with or without # modification, are permitted providing that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and t...
import numpy as np import sklearn.model_selection class _TemporalDataset: def __init__(self, data): self.X = np.array(data) class TemporalDatasetTrain(_TemporalDataset): def __init__(self, data, ground_truth=None): super(TemporalDatasetTrain, self).__init__(data) self.ground_truth = ...
import os, sys import time from tqdm import tqdm import argparse def get_parser(): parser = argparse.ArgumentParser(description="PAIB") group = parser.add_mutually_exclusive_group(required=False) group.add_argument( "-pg", "--passgen", action="store_true", help="Generate pa...
# set up logging import logging, os from datetime import datetime, timedelta logging.basicConfig(level=os.environ.get("LOGLEVEL","INFO")) log = logging.getLogger(__name__) import rasterio import numpy as np from datetime import datetime from multiprocessing import Pool from .util import * from .const import * def _...
class Solution(object): def containsNearbyDuplicate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ if len(nums) <= 1: return False if k == 0: return False p1, p2 = 0, 1 numSet = set() num...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Lazily-evaluated property pattern in Python. https://en.wikipedia.org/wiki/Lazy_evaluation *References: bottle https://github.com/bottlepy/bottle/blob/cafc15419cbb4a6cb748e6ecdccf92893bb25ce5/bottle.py#L270 django https://github.com/django/django/blob/ffd18732f3ee9e6...
# -*- coding: utf-8 -*- from aserializer.utils.parsers import Parser class MetaOptions(object): def __init__(self, meta): self.fields = getattr(meta, 'fields', []) self.exclude = getattr(meta, 'exclude', []) class SerializerMetaOptions(MetaOptions): def __init__(self, meta): supe...
import sys userpassinfo = ('51reboot', '123456') class Auth(object): def login(self, username, password): if username == userpassinfo[0] and password == userpassinfo[1]: return "login succ.", True else: return "login faild.", False def logout(self): sys.exit(0...
from django.urls import include, path from .views import ( TraderRegisterView, FarmerRegisterView, UserLoginView, UserLogoutView, ValidateOTP, ValidatePhoneNumberSendOTP, ) urlpatterns = [ path("send/otp/", ValidatePhoneNumberSendOTP.as_view(), name="send_otp"), path("verify/otp/", Vali...
#!/usr/bin/env python """ Reads the example file to a dict This file shows, how to read the data into a dict, that can be used as any other Python dict. Also it shows how to read the attributes available in the file and in a dataset. """ from structure_definitions import * __author__ = "Johannes Hiller" __...
from .gat import GAT from .sp_gat import SpGAT
from pprint import pprint from bubbl2struct import b2s # Load the simple diagram from the diagras folder converter = b2s('diagrams/simple_diagram.html') # Load as JSON json = converter.as_json() print 'Converted to json format: ' pprint(json) # Load as adjacency adj, nodes, edges = converter.as_adj() print 'Conve...
"""Python script to create GnuPlot plots.""" from subprocess import Popen, PIPE # A few constants shared across all plots FONTSIZE = "15" TERMINAL = "postscript eps color solid" LINEWIDTH = "3" OUTPUT_PREFIX = "output/" # The following is the template all GnuPlot script files share. It contains # placeholders for a n...
#!/usr/bin/env python # Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. # Utility script to make it easier to update what golem builds. import gradle import s...
import numpy as np import pandas as pd import copy class Correlationer: def __init__(self, method="pearson", critical=0.7, movingAverageWindow=2, movingWeightMax=2): self._method = method self._critical = critical self._movingAverageWindow = movingAverageWindow self._movingWeightMax...
# 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: def findLeaves(self, root: TreeNode) -> List[List[int]]: heights = {} self.getHeight(root, h...
import tensorflow as tf from keras import optimizers from keras.layers import Conv2D, MaxPooling2D, Dropout, Dense, Flatten, Activation, BatchNormalization from keras.models import Sequential from keras_layers import ConvGHD, FCGHD, CustomRelu def categorical_crossentropy(y_true, y_pred): return tf.nn.softmax_cr...
"""Internal Accretion constants.""" ARTIFACTS_PREFIX = "accretion/artifacts/" ARTIFACT_MANIFESTS_PREFIX = "accretion/manifests/" SOURCE_PREFIX = "accretion/source/" LAYER_MANIFESTS_PREFIX = "accretion/layers/"
from django.shortcuts import render, get_object_or_404 from django.urls import reverse_lazy from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, CreateView, DeleteView from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.conf import...
# -*- coding: utf-8 -*- # @Time : 2020/7/13 0:38 # @Author : Zhongyi Hua # @FileName: check.py # @Usage: # @Note: # @E-mail: [email protected] """ 把各个部分的check任务全部拆出来,这样方便反复使用 1. 保守基因情况 2. un normal name 3. 重复区域 4. renumber 5. cds check """ import gffutils import portion as pt import pandas as pd from Bio import Se...
"""Support for Roku binary sensors.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from rokuecp.models import Device as RokuDevice from homeassistant.components.binary_sensor import ( BinarySensorEntity, BinarySensorEntityDescription, ) from homea...
"""Definition for aiosql compatible adapters. Adapters here aren't "real" adapters, that can execute queries but just dummy classes with compatible interface. """ # this drivers won't and shouldn't be used as real drivers. # they are required only for queries building. class EdgeQLAsyncAdapter: """Dummy adapte...
from socket import socket, AF_INET, SOCK_DGRAM, timeout import binascii import json import os from math import ceil FILE_PATH = 'client_storage/innopolis.jpg' CLIENT_PORT = 12345 SERVER_PORT = 12346 SERVER_ADDR = 'localhost' CLIENT_BUF_SIZE = 2048 SERVER_BUF_SIZE = -1 # We don't know yet def get_crc_checksum(file_c...
#!/usr/bin/env python3 # Copyright (C) Alibaba Group Holding Limited. from models.module_zoo.branches.r2plus1d_branch import R2Plus1DBranch from models.module_zoo.branches.r2d3d_branch import R2D3DBranch from models.module_zoo.branches.csn_branch import CSNBranch from models.module_zoo.branches.slowfast_branch import...
# -*- coding: utf-8 -*- import json import uuid from typing import List, Dict, Tuple, Iterable from requests import Response from TM1py.Exceptions.Exceptions import TM1pyRestException from TM1py.Objects.Process import Process from TM1py.Services.ObjectService import ObjectService from TM1py.Services.RestService impo...