text
stringlengths
2
999k
# Copyright 2019-present Kensho Technologies, LLC. from copy import copy from graphql.language.ast import ( ArgumentNode, DirectiveNode, DocumentNode, FieldNode, InlineFragmentNode, NameNode, OperationDefinitionNode, SelectionSetNode, StringValueNode, ) from graphql.validation impor...
import os import posixpath from enum import Enum from pystac.errors import RequiredPropertyMissing from typing import Any, Callable, Dict, List, Optional, TypeVar, Union, cast from urllib.parse import urljoin, urlparse, urlunparse, ParseResult as URLParseResult from datetime import datetime, timezone import dateutil.pa...
import os from flask import Flask, request, redirect, url_for, send_from_directory from werkzeug.utils import secure_filename UPLOAD_FOLDER = './Upload' app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER @app.route("/", methods=['GET', 'POST']) def index(): if request.method == 'POST': ...
# -*- coding: utf-8 -*- from unittest.mock import MagicMock from django.http import Http404 from django.core.exceptions import PermissionDenied from django.test import TestCase from djangorestframework_camel_case.render import CamelCaseJSONRenderer from rest_framework import views, serializers from drftoolbox import...
from os import path from flask import Flask, render_template, send_from_directory, jsonify from flask_webpack import Webpack from version import __version__ import fabfile import fabric import time here = path.abspath(path.dirname(__file__)) app = Flask(__name__) webpack = Webpack() app.config["WEBPACK_MANIFEST_PATH...
peso = float(input("Digite seu peso em kg: ")) altura = float(input("Digite sua altura em metros: ")) imc = float(peso/(altura*altura)) print(imc)
import math from src.shared.geometry import Coord, Distance, Rect from src.shared.ident import encodeUnitId, parseUnitId from src.shared.message_infrastructure import defineMessageType, \ ArgumentSpecification, InvalidMessageError from src.shared.unit_set import UnitSet ##########################################...
# Link: https://leetcode.com/problems/set-matrix-zeroes/ # Approach 1: # Time: O(m * n) # Space: O(m + n) # Maintain two arrays, to track which rows and cols are to be set zero. # Then, iterate through the matrix and find out which rows and cols are to be set zero. # Finally, set them zero. # def set_zeros(matrix...
from torch.nn import Embedding import pytest from fixtures import * from perceiver_pytorch.modalities import InputModalityWithEmbedding from perceiver_pytorch.multi_modality_with_text_perceiver import MultiModalityWithTextPerceiver def test_embedding_for_layer(text_inputs): text_modality = InputModalityWithEmbed...
""" Closuers Free variables and closures Remember: Functions defined inside another function can access the outer (nonLocal) variables """ def outer(): x = 'python' / this x refers to the one in outer's scope', this nonlocal variable x is called a free varia...
"""Collection of Tools.""" import numpy as np import random import os def get_label_index(Y, bbox): x1, x2, y1, y2, z1, z2 = bbox Y_cropped = Y[x1:x2, y1:y2, z1:z2] labels = range(int(np.max(Y_cropped)) + 1) label_index = {} for label in labels: label_index[label] = np.argwhere(Y_cropped == label) ret...
''' Given a initial number x and two operations which are given below: Multiply number by 2. Subtract 1 from the number. The task is to find out minimum number of operation required to convert number x into y using only above two operations. We can apply these operations any number of times. Constraints: 1 <...
""" --- Day 25: Combo Breaker --- You finally reach the check-in desk. Unfortunately, their registration systems are currently offline, and they cannot check you in. Noticing the look on your face, they quickly add that tech support is already on the way! They even created all the room keys this morning; you can take ...
from copy import deepcopy from ding.entry import serial_pipeline from easydict import EasyDict space_invaders_c51_config = dict( env=dict( collector_env_num=8, evaluator_env_num=8, n_evaluator_episode=8, stop_value=10000000000, env_id='SpaceInvadersNoFrameskip-v4', f...
import atexit import json import os import shutil import signal import sys import threading import time from argparse import ArgumentParser from operator import attrgetter from tempfile import mkstemp, mkdtemp from zipfile import ZipFile, ZIP_DEFLATED try: # noinspection PyCompatibility from collections.abc im...
from __future__ import print_function import mahotas from pylab import gray, imshow, show import numpy as np luispedro = mahotas.imread('./data/luispedro.jpg') luispedro = luispedro.max(2) T = mahotas.otsu(luispedro) lpbin = (luispedro > T) eye = lpbin[112:180,100:190] gray() imshow(eye) show() imshow(~mahotas.morph.c...
from .tools import tools from .sanook import sanook from .bbc import bbc from .pptv import pptv from .dailynews import dailyNews from .komchadluek import komchadluek from .oryor import oryor from .sure_oryor import sureOryor from .matichon import matichon from .thansettakij import thanSettakij from .thairath import tha...
from django.utils.functional import cached_property ''' Map of allowed file extensions -> format key Lower case entries, and variations in spelling e.g. 'jpg'/'jpeg' ''' # This needs to be a union of the filehandling of the possible # libraries, largely Pillow Wand, OpenCV # Pillow # django.core.validators.ge...
from __future__ import print_function from orphics import maps,io,cosmology from pixell import enmap import numpy as np import os,sys from soapack import interfaces as sints def get_coadd(imaps,wts,axis): # sum(w*m)/sum(w) twt = np.sum(wts,axis=axis) retmap = np.sum(wts*imaps,axis=axis)/twt retmap[~np....
import pandas as pd import numpy as np import jellyfish def create_heats(df, event, num_heats): counter = 0 for row_num, registration_status in enumerate(df[event]): if registration_status != '0': df.loc[row_num, event] = counter % num_heats + 1 counter += 1 allEventsDict = {"...
#! /usr/bin/env python # Copyright (c) 2019 Uber Technologies, 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 a...
#!/usr/bin/env python import shlex import string import subprocess import sys from contextlib import contextmanager from csv import QUOTE_NONE from distutils.version import LooseVersion from errno import ENOENT from functools import wraps from glob import iglob from io import BytesIO from os import environ, extsep, re...
""" WSGI config for awesome_web 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 os.environ.setdefault("DJANGO_...
# utility functions for encoding and decoding messages # created by Felix Holz, 2018-07-11 import math # maximum number of characters per packet MAX_HEX_CHARS = 10 # encode a string to the hexadecimal string used by the protocol # msg: string to encode # return: string array of hexadecimal strings. each strin...
import datetime import hashlib import logging import os import smtplib from email.headerregistry import Address from email.parser import Parser from email.policy import default from email.utils import formataddr, parseaddr from typing import Any, Dict, List, Mapping, Optional, Tuple import backoff import orjson from d...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.FileItem import FileItem from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.AlipayOfflineMarketProductBatchqueryModel import AlipayOfflineMarketProductBatchqueryModel class AlipayOfflineMarketProductBatchquer...
import discord import colorsys import random def error(text): return "\N{NO ENTRY SIGN} {}".format(text) def warning(text): return "\N{WARNING SIGN} {}".format(text) def info(text): return "\N{INFORMATION SOURCE} {}".format(text) def question(text): return "\N{BLACK QUESTION MARK ORNAMENT} {}".forma...
import unittest from dataclasses import dataclass from typing import List, Optional, Tuple import io from clvm_tools import binutils from pytest import raises from hddcoin.protocols.wallet_protocol import RespondRemovals from hddcoin.types.blockchain_format.coin import Coin from hddcoin.types.blockchain_format.progra...
# https://www.rosettacommons.org/docs/latest/rosetta_basics/scoring/score-types term_meanings = { "fa_atr": "Lennard-Jones attractive between atoms in different residues (r^6 term, London dispersion forces).", "fa_rep": "Lennard-Jones repulsive between atoms in different residues (r^12 term, Pauli repulsion fo...
import functools import mimetypes import pathlib import secrets import flask import flask_caching from google.appengine.api import app_identity from google.appengine.api import images from google.appengine.api import wrap_wsgi_app from google.cloud import storage IMAGE_EXTENSIONS = ('.jpg', '.gif', '.png') app = fl...
""" # GAS STATION There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the...
# The MIT License # Copyright (c) 2021- Nordic Institute for Interoperability Solutions (NIIS) # Copyright (c) 2017-2020 Estonian Information System Authority (RIA) # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"...
# -*- coding: utf-8 -*- """ Created on Thu Aug 27 15:45:56 2020 @author: ZongSing_NB Main reference: http://www.ejournal.org.cn/EN/10.3969/j.issn.0372-2112.2019.10.020 """ import numpy as np import matplotlib.pyplot as plt class EGolden_SWOA(): def __init__(self, fitness, D=30, P=20, G=500, ub=1, lb=0, ...
class triangle2(Exception): def triangle2(number): first = 0 count = 0 n0 = number for j in range(number): for x in range(count - 1): if first == 0: print(" ", end='') first == 1 print(" ", end=...
class Reader: async def readline(self): print('readline') def __aiter__(self): return self async def __anext__(self): val = await self.readline() if val == b'': raise StopAsyncIteration return val async for a in Reader(): print(a) else: print('else')
# -*- Mode: Python -*- import coro import coro.backdoor import coro.ssl from coro.http.spdy import spdy_client from coro.http.protocol import header_set W = coro.write_stderr ctx = coro.ssl.new_ctx ( # cert=coro.ssl.x509 (open ('cert/server.crt').read()), # key=coro.ssl.pkey (open ('cert/server.key').read()...
from attrdict import AttrDict global_obs_camera_config = AttrDict(dict( image_obs_resolution=128, eye_positions=[(0.0, 0.0, 1.6), (-0.8, -0.6, 1.4), (0.8, -1.0, 0.5)], eye_targets=[(0.0, 0.0, 1.0), (0.0, 0.0, 0.4), (0.0, 0.0, 0.4)], eye_ups=[(0, 1, 0), (0, 0, 1), (0, 0, 1)], fov=80, near=0.001...
#!/usr/bin/env python # -*- coding:utf-8 -*- import utils def run(string, entities): """Leon says what's the meaning of life""" return utils.output('end', 'meaning_of_life', utils.translate('meaning_of_life'))
import logging import logging.config import json import csv from os import write from sqlalchemy import engine import psycopg2 from config import * from decouple import config logging.config.fileConfig(logs.get('file_config')) logger = logging.getLogger('root') #def get_columns_from_csv_file(): # """ # Fu...
from flask import jsonify, json from flask_restful import Resource from injector import inject from webargs import fields from webargs.flaskparser import use_kwargs from backend_application.service import HealthIndicatorService class HealthIndicator(Resource): @inject def __init__(self, service: HealthIndica...
from __future__ import division , print_function """WIDER Face Dataset Classes author: swordli """ #from .config import HOME import os.path as osp import sys import torch import torch.utils.data as data import cv2 import numpy as np sys.path.append("/f/home/jianli/code/s3fd.180716/") #from utils.augmentations import SS...
# =============================================================================== # Copyright 2019 ross # # 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/LICE...
# 2020 # The Raven-Storm Toolkit was programmed and developed by Taguar258. # The Raven-Storm Toolkit is published under the MIT Licence. # The Raven-Storm Toolkit is based on the CLIF-Framework. # The CLIF-Framework is programmed and developed by Taguar258. # The CLIF-Framework is published under the MIT Licence. fro...
from __future__ import absolute_import import numpy as np from .Node import Op from .._base import DNNL_LIB from ..cpu_links import transpose as cpu_transpose from ..gpu_links import matrix_transpose_simple from .. import ndarray class TransposeOp(Op): def __init__(self, node_A, perm=None, ctx=None): supe...
import pyexasol import _config as config C = pyexasol.connect(dsn=config.dsn, user=config.user, password=config.password, schema=config.schema) C.execute("ALTER SESSION SET QUERY_CACHE = 'OFF'") st = C.execute("SELECT * FROM {table_name!i}", {'table_name': config.table_name}) st.fetchall()
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from rest_framework import serializers from goods.models import SKU class CartSerializer(serializers.Serializer): """添加商品到购物车序列化器""" sku_id = serializers.IntegerField(label="sku_id", min_value=1) count = serializers.IntegerField(label="数量", min_value=1) selected = serializers.BooleanField(label="是否勾选...
import os from setuptools import setup # This file is a template, and will be rendered before executed. # So the double curly brackets will become single after rendering, and # when executed, this will work as expected content = 'env = {{}}\n'.format(repr(dict(os.environ))) # noqa W291 see above comment with open('a...
from acrobotics.link import Link, LinkKinematics, DHLink, JointType import numpy as np import casadi as ca import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import from acrobotics.geometry import Scene from acrobotics.shapes import Box from numpy.testing import assert_almost...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from PySide2.QtCore import QObject, Slot, Signal from PySide2.QtQml import QQmlApplicationEngine class CaptchaDialog(QObject): showWindowCaptcha = Signal(str) def __init__(self, parent, log=None): super(CaptchaDialog, self).__init__() ...
# Copyright DataStax, 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 applicable law or agreed to in writing, softwa...
from __future__ import division from contextlib import contextmanager import numpy as np from numba import cuda, config from numba.cuda.testing import unittest, skip_on_cudasim from numba.tests.support import captured_stderr @skip_on_cudasim('not supported on CUDASIM') class TestDeallocation(unittest.TestCase): ...
from pathlib import Path import numpy as np import rasterio import geopandas as gpd from joblib import Parallel, delayed data_location = \ Path("/g/data/ge3/covariates/national_albers_filled_new/albers_cropped/") # Read points from shapefile shapefile_location = Path("/g/data/ge3/aem_sections/AEM_covariates/") ...
from __future__ import annotations from typing import Iterator, Type from ._cdata import CData from ._ffi import ffi, lib from .dcp_profile import DCPProfile __all__ = ["Input"] class Input: def __init__(self, dcp_input: CData): self._dcp_input = dcp_input if self._dcp_input == ffi.NULL: ...
import math import cv2 import numpy as np def rotateImage(input_img, angle): """ Rotate the input_img by angle degrees, Rotate center is image center. :param input_img:np.array, the image to be rotated :param angle:float, the counterclockwise rotate angle :return:np.array, the rotated image """...
import azure.cosmos.documents as documents import azure.cosmos.cosmos_client as cosmos_client import azure.cosmos.errors as errors import requests import traceback import urllib3 from requests.utils import DEFAULT_CA_BUNDLE_PATH as CaCertPath import samples.Shared.config as cfg HOST = cfg.settings['host'] MASTER_KEY...
# Generated by Django 2.1.13 on 2019-10-19 14:10 import core.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0004_recipe'), ] operations = [ migrations.AddField( model_name='recipe', name='image', ...
"""Application Models.""" from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema from .OAuthRequestSchemaOauth2 import OAuthRequestSchemaOauth2 from .OAuthRequestSchemaProfile import OAuthRequestSchemaProfile class OAuthReque...
from pocketutils.plotting.color_schemes import FancyCmaps from sauronlab.core.core_imports import * from sauronlab.viz import CakeComponent from sauronlab.viz._internal_viz import * @abcd.auto_eq() @abcd.auto_repr_str() class ImportancePlotter(CakeComponent, KvrcPlotting): """ Plots weight (often importance)...
#!/usr/bin/env python #-*-*- encoding: utf-8 -*-*- weblab_xilinx_experiment_xilinx_device = 'FPGA' weblab_xilinx_experiment_port_number = 1 # This should be something like this: # import os as _os # xilinx_home = _os.getenv('XILINX_HOME') # if xilinx_home == None: # if _os.name == 'nt': # xilinx_home = r'C:...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
from enum import Enum class TargetPython(Enum): python3 = 2 # recipes that currently break the build # a recipe could be broken for a target Python and not for the other, # hence we're maintaining one list per Python target BROKEN_RECIPES_PYTHON3 = set([ 'brokenrecipe', # enum34 is not compatible with P...
from random import * #THIS IS A STUDENT BOT THAT DID REASONABLY WELL IN THE CLASS TOURNAMENT BUT DIDN'T PLACE IN THE TOP 3 def getMove(myScore, mySnowballs, myDucksUsed, myMovesSoFar, oppScore, oppSnowballs, oppDucksUsed, oppMovesSoFar): #if I have no more snowballs, do this... if mySnowballs == 0: ...
"""Standard location_provider class(es) for creating DataSet locations.""" from datetime import datetime import re import string from qcodes import config class SafeFormatter(string.Formatter): """Modified string formatter that doesn't complain about missing keys.""" def get_value(self, key, args, kwargs): ...
''' 地址(行政处罚):http://www.cbirc.gov.cn/branch/beijing/view/pages/common/ItemList.html?itemPId=1851&itemId=1855&itemUrl=ItemListRightList.html&itemName=%E8%A1%8C%E6%94%BF%E5%A4%84%E7%BD%9A 这个要用到selenium和chromedriver,下载驱动用这个网址: https://sites.google.com/a/chromium.org/chromedriver/downloads 注意驱动版本和chrome版本对应 chrome版本查询: 打开c...
""" SAN.T2V.learning ~~~ Unsupervised - Entropy or Bayesian network: inputs are tons of documents without speech. Outputs are TERMS which usually occur together. Training is based on the time of occurring of terms. :copyright: 2017 by Nhut Hai Huynh. :license: MIT, see LICENSE for more details. """
""" Module: 'utimeq' on esp8266 v1.11 """ # MCU: (sysname='esp8266', nodename='esp8266', release='2.2.0-dev(9422289)', version='v1.11-8-g48dcbbe60 on 2019-05-29', machine='ESP module with ESP8266') # Stubber: 1.2.0 class utimeq: '' def peektime(): pass def pop(): pass def push(): ...
import requests from requests.api import request from .entities import Account class AuthorizationException(Exception): pass class ForbiddenException(Exception): pass class MonzoClient: BASE_URL = 'https://api.monzo.com' def __init__(self, access_token): self._auth_header = {'authorizat...
from .base import InvalidInput from goldstone.lib.errors import Error from .cli import ( Command, Context, Run, RunningConfigCommand, GlobalShowCommand, ModelExists, TechSupportCommand, ShowCommand, ConfigCommand, ) from .root import Root from .util import dig_dict, human_ber, obj...
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
# 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 json import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class Origin...
import rlkit.util.hyperparameter as hyp from multiworld.envs.mujoco.cameras import sawyer_init_camera_zoomed_in, sawyer_pusher_camera_upright_v2 from rlkit.launchers.launcher_util import run_experiment import rlkit.torch.vae.vae_schedules as vae_schedules from rlkit.torch.vae.conv_vae import imsize48_default_architectu...
"""Type definitions for the airline_demo.""" from collections import namedtuple import sqlalchemy from dagster import as_dagster_type from dagster.core.types.runtime.runtime_type import Stringish AirlineDemoResources = namedtuple( 'AirlineDemoResources', ('spark', 's3', 'db_url', 'db_engine', 'db_dialect', ...
# -*- coding: utf-8 -*- from django import template from django.core.paginator import EmptyPage from classytags.core import Options, Tag from classytags.arguments import MultiKeywordArgument, Argument from classytags.helpers import InclusionTag from publication_backbone.utils.paginator import Paginator, OffsetNotAnIn...
from __future__ import absolute_import, division, print_function, unicode_literals import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers print(tf.__version__) dataset_path = keras.utils.get_file("auto-mpg.dat...
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish...
""" test_util ~~~~~~~~~~~~~~~ Tests util functions. :copyright: Copyright 2007-2020 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. """ import os import tempfile from unittest.mock import patch import pytest import sphinx from sphinx.errors import ExtensionError, Pycode...
import json from collections import namedtuple from datetime import datetime from pathlib import Path from zipfile import ZipFile import h5py import numpy as np from scipy.signal import convolve2d from torch.utils.data import Dataset from .exceptions import InconsistentDataException, DoesNotExistException from .trans...
# coding: utf-8 import re from collections import Counter def word_count(txt): word_pattern = r'[a-zA-Z-]+' words = re.findall(word_pattern, txt) return Counter(words).items() if __name__ == '__main__': txt = open('test.txt', 'r').read().lower() print word_count(txt)
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
from django.contrib.auth.models import User from django import forms import re class RegistrationForm(forms.Form): first_name = forms.CharField( label='Enter Your First Name', widget=forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Your ...
from pytest_mock import MockFixture from tests.resources import get_test_image from white_brush.enhance import enhance from white_brush.entities.color_configuration import ColorConfiguration from white_brush.services import enhance_service class TestEnhance: def test_enhancing_a_single_image_no_color_config(self...
from __future__ import absolute_import import six # #START_LICENSE########################################################### # # # This file is part of the Environment for Tree Exploration program # (ETE). http://etetoolkit.org # # ETE is free software: you can redistribute it and/or modify it # under the terms of th...
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
""" ASGI config for sociallogin project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/ """ import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_S...
import pytest import sys import os import shutil import flopy import pymake from ci_framework import ( base_test_dir, FlopyTestSetup, download_mf6_examples, ) exe_name = "mf6" v = flopy.which(exe_name) run = True if v is None: run = False mf6path = download_mf6_examples() exclude_models = ("lnf",) ex...
from __future__ import unicode_literals import io import os import subprocess import time import re from .common import AudioConversionError, PostProcessor from ..utils import ( encodeArgument, encodeFilename, get_exe_version, is_outdated_version, PostProcessingError, prepend_extension, ...
# Copyright (c) 2010 - 2020, Nordic Semiconductor ASA # 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 o...
def selection_sort(lst): for i in range(len(lst) - 1): for j in range(i+1, len(lst)): if lst[i] > lst[j]: lst[i], lst[j] = lst[j], lst[i] return lst
#!/usr/bin/env python # -*- coding: utf-8 -*- # Triangle Project Code. # Triangle analyzes the lengths of the sides of a triangle # (represented by a, b and c) and returns the type of triangle. # # It returns: # 'equilateral' if all sides are equal # 'isosceles' if exactly 2 sides are equal # 'scalene' ...
import numpy as np from qtrader.utils.numpy import eps def _mu_p(w: np.ndarray, r: np.ndarray) -> float: """Portfolio Returns.""" return np.dot(w.T, r) def _sigma_p(w: np.ndarray, Sigma: np.ndarray) -> float: """Portoflio Variance""" return np.dot(np.dot(w.T, Sigma), w) def _trans_costs(w: np.nda...
""" The MIT License (MIT) Copyright (c) 2015-present Rapptz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merg...
"""Variational autoencoder module class.""" from typing import Tuple import torch.nn as nn from torch import Tensor from utils import init_weights from vae.models.base import Decoder, Encoder, VAEConfig, VAEModel class _Encoder(Encoder): def __init__(self, z_dim: int, num_features: int) -> None: super(_...
from __future__ import annotations import logging import time from dataclasses import replace from secrets import token_bytes from typing import Any, Dict, List, Optional, Set from blspy import AugSchemeMPL, G2Element from littlelambocoin.consensus.cost_calculator import calculate_cost_of_program, NPCResult from lit...
import mysql.connector as mysqlConnector from tkinter import * import tkinter.messagebox from datetime import date from datetime import datetime from datetime import timedelta from admin_panel import admin_panel from report_panel import report_panel from add_admin import add_admin from add_student import add_student fr...
import json import click from tabulate import tabulate from alertaclient.models.alert import Alert from alertaclient.utils import DateTime, build_query COLOR_MAP = { 'critical': {'fg': 'red'}, 'major': {'fg': 'magenta'}, 'minor': {'fg': 'yellow'}, 'warning': {'fg': 'blue'}, 'normal': {'fg': 'gree...
import os import glob import sys sys.path.append('C:\\3DUnetCNN-master\\') from unet3d.data import write_data_to_file, open_data_file from unet3d.generator import get_training_and_validation_generators from unet3d.model import isensee2017_model from unet3d.training import load_old_model, train_model config = dict()...
# Copyright 2019 The Cirq Developers # # 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/LICENSE-2.0 # # Unless required by applicable law or agreed to in ...
import sqlite3 import click from flask import current_app, g from flask.cli import with_appcontext def get_db(): if 'db' not in g: g.db = sqlite3.connect( 'sqlite3_db.db',#current_app.config['DATABASE'], detect_types = sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sq...