text
stringlengths
3.07k
12.6k
import py from rpython.jit.metainterp.test import support from rpython.rlib.rsre.test.test_match import get_code from rpython.rlib.rsre import rsre_core from rpython.rtyper.lltypesystem import lltype from rpython.rtyper.annlowlevel import llstr, hlstr def entrypoint1(r, string, repeat): r = array2list(r) strin...
import json import logging import pprint from typing import Any, Dict, Tuple import flask from werkzeug.exceptions import BadRequest import placebo import util log = logging.getLogger('placebo.app') app = flask.Flask(__name__) placebo_app = placebo.Placebo() @app.route('/unlock', methods=['POST']) def unlock() -> ...
import re from unittest.mock import Mock import pytest from django import forms from geniza.corpus.forms import ( CheckboxSelectWithCount, DocumentChoiceField, DocumentMergeForm, DocumentSearchForm, FacetChoiceField, RadioSelectWithDisabled, ) from geniza.corpus.models import Document class ...
import os import sys from .ansi import sformat from .prettier import PrettyFormat from .timer import Timer from .utils import env_bool, env_true, is_literal, use_highlight __all__ = 'Debug', 'debug' MYPY = False if MYPY: from types import FrameType from typing import Any, Generator, List, Optional pformat = ...
import os import shutil import json import time import pandas as pd import Augmentor import tuner from tuner import utils from tuner import load_data from tuner import augment_data from tuner import use_hyperas from tuner import net class ClassificationDataset(object): def __init__(self, classed_dataset_dir):...
# Copyright (c) 2022 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...
# ------------------------------------------------------------------ # # Series of tests to check validity of ABM input # # - Does not check for upper numeric limits since they are rather # high # # ------------------------------------------------------------------ import utils as ut def load_data_for_checking(fna...
import random import pytest from eth_utils import to_canonical_address from networkx import Graph from raiden.storage.serialize import JSONSerializer from raiden.tests.utils import factories from raiden.transfer import state, state_change from raiden.transfer.merkle_tree import compute_layers from raiden.transfer.sta...
import logging import sys import reconcile.jenkins_plugins as jenkins_base import reconcile.openshift_base as ob import reconcile.queries as queries from reconcile import mr_client_gateway from reconcile.slack_base import init_slack from reconcile.status import ExitCodes from reconcile.utils.semver_helper import mak...
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_str from ..utils import ( clean_html, ExtractorError, int_or_none, str_or_none, try_get, url_or_none, ) class StitcherBaseIE(InfoExtractor): _VALID_URL_BASE = r'https?://(?:www\.)?stitche...
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2015 <NAME> <<EMAIL>> # # MIT Licence. See http://opensource.org/licenses/MIT # # Created on 2015-07-27 # """ Package containing password generators. This module contains the machinery for loading generators and the base class for generators. The default gene...
"""Specific tasks.""" import copy import json import logging import os import shutil import tempfile import warnings from collections import defaultdict from inspect import cleandoc from pathlib import Path import sphinx.cmd.build # pylint: disable=import-error import sphinx.locale # pylint: disable=import-error fro...
import copy import dataclasses import importlib import inspect import json import os import re import shutil from abc import abstractmethod from dataclasses import dataclass from dataclasses import field from hashlib import sha1 from typing import Any from typing import List from typing import Optional from omegaconf ...
#Author-Autodesk Inc. #Description-Apply a material to selected bodies. import adsk.core, adsk.fusion, traceback commandId = 'ApplyMaterialToSelectionCommand' commandName = 'ApplyMaterialToSelection' commandDescription = 'Apply a material to selected bodies or occurrences' app = None ui = None # global set of event...
import csv import io import json import pickle import struct import ujson from functools import partial import bson import cbor import msgpack import pandas as pd import pyarrow as pa from pyarrow import parquet as pq from bench_helper import bench_function, baseline_ratio, get_machine_info from book_pb2 import Book ...
#!/usr/bin/python3 '''This script goes along the blog post "Building powerful image classification models using very little data" from blog.keras.io. It uses data that can be downloaded at: https://www.kaggle.com/c/dogs-vs-cats/data In our setup, we: - created a data/ folder - created train/ and validation/ subfolders ...
# Copyright 2010 New Relic, 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 writ...
# -*- coding: utf-8 -*- """Distributed Task Queue""" # :copyright: (c) 2015 <NAME> and individual contributors. # All rights # reserved. # :copyright: (c) 2012-2014 GoPivotal, Inc., All rights reserved. # :copyright: (c) 2009 - 2012 <NAME> and individual contributors, # All rights reserv...
import keras import numpy as np from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.layers.normalization import BatchNormalization from keras.layers import Conv2D, Dense, Input, add, Activation, Flatten, AveragePooling2D from keras.callbacks import LearningRateSc...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 ...
"""Simple MNIST learner adapted from Hvass-Labs/TensorFlow-Tutorials: https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/19_Hyper-Parameters.ipynb Copyright 2019 TensorHub, Inc. Copyright (c) 2016-2018 by <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this softwar...
import time import joblib import numpy as np from sklearn.base import clone from .base import Explainer from .parsers import util class LOO(Explainer): """ Leave-one-out influence explainer. Retrains the model for each train example to get change in loss. Local-Influence Semantics - Inf.(x_...
from django.db import models from django.db.models import Max from random import randint, randrange DEFAULT_LENGTH = 20000 class Subs(models.Model): ''' Store subtitles information ''' movie_name = models.CharField(max_length=100) sub_language_id = models.CharField(max_length=3) sub_file_nam...
""" Newer variant on crusoeparse, with an infusion of monoidal.py. """ import re def parse(x, s): p = x() if callable(x) else x if isinstance(p, (str, unicode)): return parse_regex(p, s) if isinstance(p, list): return parse_rules(p, s) if callable(p): return p(s) raise ...
import sqlite3 from requests import get import urllib.parse as up import pandas as pd class Markit: def __init__(self): self.lookup_url = "http://dev.markitondemand.com/Api/v2/Lookup/json?" self.quote_url = "http://dev.markitondemand.com/Api/v2/Quote/json?" def company_search(self,st...
import pdb import re import operator from functools import reduce from django.contrib.staticfiles.templatetags.staticfiles import static from django.shortcuts import render, redirect, reverse from django.db.models import Q, Count, Case, When, Value, IntegerField, Sum from django.conf import settings from django.http i...
''' python3 run1.py train_policy_with_preferences MovingDotDiscreteNoFrameskip-v0 --n_envs 16 --render_episodes --load_prefs_dir runs/moving-dot_45cb953''' import logging import os from os import path as osp import sys import time from multiprocessing import Process, Queue import cloudpickle import easy_tf_log from ...
from .hyper import HyperNet from .cnn import NeuriteUNet, NeuriteEncoder from .reduction import reductions from .segmentation import DiceHead from ..base import Module from .. import check import torch class HyperU(Module): """Self-adaptive UNet""" def __init__(self, dim, in...
from django.db import models from django.db.models import Q from django.db.models.signals import post_save from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.auth.models import User from django.urls import reverse from django.dispatch import receiver from sixtyfour.forma...
#! /usr/bin/env python """ Listen to the /imu topic while the rover is not moving. This will help experimentally determine the variance of each sensor. """ from __future__ import print_function from datetime import datetime import signal import sys import os import math import numpy as np import rospy import rosnode ...
# -*- coding : utf-8-*- import copy from ..server import Base, Column, String, Text, ForeignKey, relationship, Float, FLOAT, DECIMAL from ..alignment.align import Align from ..model import Bridge, Span from ezdxf.math import Vec2, Matrix44, Vector class std_Foundations(object): pass class GeneralFoundation(Bas...
''' Description: Prototype System of PVMPATCH LastEditTime: 2021-10-21 16:44:03 ''' import os import sys import pandas as pd current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir, "..")) from multiprocessing import Pool from time import time from util.patch import * from uti...
# coding:utf-8 # --author-- binglu.wang """ yeti缓存操作集合 """ import os import re import logging import shutil import maya.cmds as cmds import zfused_api import zfused_maya.core.filefunc as filefunc import zfused_maya.core.record as record import zfused_maya.node.core.element as element import zfused_maya.node.core.ass...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import time import numpy as np import tensorflow as tf from config import Config import metrics import data_input from TranSearch import TranSearch def main(argv=None): train_data =...
import discord from discord.ext import commands import praw import random from utils.tools import * colors=[0xeb4034,0x31e2e8,0x3e32e3,0xe332dd,0xe3e332] reddit = praw.Reddit(client_id='', client_secret='', user_agent='') @commands.command() async def subreddit(...
import os import re import numpy as np import pandas as pd from IPython import embed import matplotlib as mpl #mpl.use('pdf') from matplotlib.backends.backend_pdf import PdfPages from mpl_toolkits.axes_grid1.inset_locator import inset_axes import matplotlib.pyplot as plt import seaborn as sns from qlknn.NNDB.model im...
# # Copyright (C) 2017 NEC, Corp. # # 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...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2013 The Plaso Project Authors. # Please see the AUTHORS file for details on individual authors. # # 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 L...
from django.shortcuts import render, reverse, get_object_or_404 from django.http import HttpResponseRedirect from django.contrib.auth import get_user_model from .models import Profile, PalRequest from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView, View, ListView Use...
import pytest from itertools import product from random import getrandbits from hamcrest import assert_that, equal_to, calling, raises from base58grs import ( b58encode, b58decode, b58encode_check, b58decode_check, b58encode_int, b58decode_int, BITCOIN_ALPHABET, XRP_ALPHABET) BASE45_ALPHABET = b"01234...
# This work was created by participants in the DataONE project, and is # jointly copyrighted by participating institutions in DataONE. For # more information on DataONE, see our web site at http://dataone.org. # # Copyright 2009-2019 DataONE # # Licensed under the Apache License, Version 2.0 (the "License"); # you ma...
import tequila.simulators.simulator_api from tequila.circuit import gates from tequila.circuit.compiler import compile_controlled_rotation, change_basis, compile_phase, compile_swap, \ compile_ry, compile_y, compile_ch from numpy.random import uniform, randint from numpy import pi, ...
import copy import json import pprint import numpy as np import networkx as nx from blockworld import blocks from blockworld.towers.tower import Tower from blockworld.utils.json_encoders import TowerEncoder def load(json_file): if isinstance(json_file, str): with open(json_file, 'r') as f: d...
#--------------------------------------- #Since : 2019/04/10 #Update: 2021/11/14 # -*- coding: utf-8 -*- #--------------------------------------- import numpy as np from copy import deepcopy import random import math from connect4 import Connect4 import time from parameters import Parameters class Node(): def __in...
""" http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection https://en.wikipedia.org/wiki/Factorial_number_system """ import math def apply_perm(omega,fbn): """ omega contains a list which will be permuted (scrambled) based on fbm. fbm is a list which repr...
import matplotlib import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap import numpy as np import os import pandas as pd import seaborn as sns from sklearn.metrics import confusion_matrix def CM(y, y_pred, labels, save_path=None, verbose=True): cm = confusion_matrix(y, y_pred) if verbose...
import asyncio import csv import json import tempfile from unittest.mock import patch import pytest from gen3.tools.metadata.discovery import ( output_expanded_discovery_metadata, publish_discovery_metadata, BASE_CSV_PARSER_SETTINGS, _try_parse, ) @patch("gen3.tools.metadata.discovery._metadata_file_...
import pickle from typing import Dict, Tuple, List from collections import OrderedDict import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split def load_interaction(filepath: str, max_item_list_len: int) -> Tuple: """Load interaction from raw dataset. Cr...
# Copyright (c) Facebook, Inc. and its affiliates # Copyright (c) MTRF authors import sys import numpy as np from pathlib import Path import glob import pickle import matplotlib.pyplot as plt import os import r3l import gym from r3l.r3l_envs.inhand_env.pickup import SawyerDhandInHandObjectPickupFixed from softlearning...
# -*- coding: utf-8 -*- """ Created on Tue Nov 17 10:55:27 2015 @author: Joakim The only thing that needs to be called from this library is updateCoordinatePairs, it does the rest """ import requests import sqlite3 as lite import json import time dbname = 'tietokanta_testi.data' tablename = 'Pysakki...
# Stubs for unittest # Based on http://docs.python.org/3.0/library/unittest.html # NOTE: These stubs are based on the 3.0 version API, since later versions # would require featurs not supported currently by mypy. # Only a subset of functionality is included. from typing import ( Any, Function, Iterable, U...
import numpy import pandas from tqdm import tqdm import logging import openbiolink.train_test_set_creation.ttsConfig as ttsConst from openbiolink import globalConfig as globConst, utils from openbiolink.gui.tqdmbuf import TqdmBuffer class Sampler: def __init__(self, meta_edges_dic, nodes): self.meta_edge...
import numpy as np import math from gym import error try: import mujoco_py except ImportError as e: raise error.DependencyNotInstalled("{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)".format(e)) def quaternion_to_euler(x, y, z, w):...
''' Copyright (c) 2018-2020 <NAME> <EMAIL> SPDX-License-Identifier: Apache-2.0 Change Logs: Date Author Notes 2019-06-30 <NAME> The first version ''' import sys import os sys.path.append(os.path.abspath("../../scripts")) print(sys.path) from tensorflow.keras import * ...
import json import numpy as np import pandas as pd import requests from bs4 import BeautifulSoup from iteration_utilities import flatten from define_collection_wave import folder from helpers import create_folder, cleanhtml path_mcdonalds = create_folder('1_McDonalds', folder) def parse_json(dat): fileName = p...
"""Migration for the Submitty system.""" import re import os import pwd import shutil from pathlib import Path def up(config): """ Run up migration. :param config: Object holding configuration details about Submitty :type config: migrator.config.Config """ # User 'postgres' uid and gid are n...
# SPDX-License-Identifier: MIT # (c) 2019 The TJHSST Director 4.0 Development Team & Contributors from typing import Any, Dict, List, Optional, cast import docker from docker.client import DockerClient from docker.models.services import Service from docker.types import EndpointSpec, Resources, RestartPolicy, ServiceM...
from sklearn.preprocessing import MultiLabelBinarizer import pandas as pd import numpy as np import copy features = [ 'StoreID', 'Date', 'IsOpen', 'IsHoliday', 'HasPromotions', 'NumberOfSales', 'StoreType_Hyper Market','StoreType_Shopping Center', 'StoreType_Standard Market', 'StoreType_Super Market', 'NearestComp...
# coding: UTF-8 ### GPU 指定 import os #os.environ["CUDA_VISIBLE_DEVICES"] = "4" ### import import torch device=torch.device('cuda') import sys import cv2 import numpy as np import time import torch.nn.functional as F import matplotlib.pyplot as plt import statistics from sift_flow_torch import SiftFlowTorch from t...
# coding:utf-8 import zlib from nose.tools import * from mock import * from flanker.mime.message.headers import MimeHeaders from flanker.mime.message.errors import DecodingError from cStringIO import StringIO from .... import * def headers_case_insensitivity_test(): h = MimeHeaders() h['Content-Type'] = 1 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from argparse import ArgumentParser import codecs import os import random import tempfile import numpy as np from prepare_dict import load_lexicon from compare_lexicons import compare_lexicons def create_tmp_file_name(): basedir = os.path.join(os.path.dirname(__fil...
import sys import tensorflow as tf from datetime import datetime from read_data import read_data_sets from cnn_word_model import CNNWordModel MAX_WORD_LEN = 31 ALPHABET_SIZE = 31 NUM_GENDERS = 3 EPOCHS = 50 BATCH_SIZE = 128 # -batch 128, 256, or 512 NUM_LAYERS = 3 # -layers 0, 1, 2, or 3 DRO...
# -*- coding: utf-8 -*- """ Created on Wed Feb 9 11:39:06 2022 @author: SimenLab """ import pathlib import numpy as np import pandas as pd import utilities # data_path = r"./Data/data_save/1_8dfp_ntc3_512_1.npz" def load_data(path): load_path = pathlib.Path(path) data = np.load(load_path.with_suffix('.npz'...
# 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. import copy import json import os import tempfile import zipfile class NonSerializableTraceData(Exception): """Raised when raw trace data cannot be serial...
import subprocess import os from leverage import path from leverage import conf # Get build config variables env = conf.load() # Set project name project = env.get("PROJECT", "") if project == "": raise Exception("Project is not set") # Enable MFA support? mfa_enabled = True if env.get("MFA_ENABLED", "true").lower()...
from __future__ import annotations from collections.abc import Sequence from pysmartthings import Capability, DeviceEntity from homeassistant.components.media_player import ( MediaPlayerEntity, DEVICE_CLASS_SPEAKER, ) from homeassistant.components.media_player.const import ( DOMAIN as MEDIA_PLAYER_DOMAIN,...
# Module fwpd_histogram import ctypes as ct import time from modules.example_helpers import * def enable_characterization(ADQAPI, adq_cu, adq_num, channel, enable, only_metadata): # Enable logic and release reset assert (channel < 5 and channel > 0), "Channel must be between 1-4." # Lookup base ...
"""코드 내 외부 설정/사전 XML파일을 불러올 때 사용하는 모듈 Classes: ImportXML ERBGrammarXML SettingXML """ import xml.etree.ElementTree as ET from util import DataFilter class ImportXML: """XML을 파싱하는 클래스 Funcitons: find_all_tags(tagname,[option_num,parent_tag]) export_textlist(tags_list) expo...
import csv, os import time, datetime from getUSDtoBRLexchangeRates import getCurrency from WriteDictToCSV import WriteDictToCSV ################################################################################ dataFolder = os.getcwd() + "\Data" outputFolder = os.getcwd() + "\Output" filename = ["ESTsoft Inc....
# Copyright 2015-2018 <NAME> # # This file is part of Platypus, a Python module for designing and using # evolutionary algorithms (EAs) and multiobjective evolutionary algorithms # (MOEAs). # # Platypus is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as pub...
import json import re import time from tweepy.streaming import StreamListener from html.parser import HTMLParser from unidecode import unidecode from sentiment_analyzer import sentiment, text_blob_sentiment from tweet_cleanser import prepare_tweet_json from es_datastore import write_to_es # Twitter's results just gi...
""" This code is based on the CKA demo published at https://cka-similarity.github.io/ """ import numpy as np def gram_linear(x): """Compute Gram (kernel) matrix for a linear kernel. Args: x: A num_examples x num_features matrix of features. Returns: A num_examples x num_examples Gram matrix of example...
"""Combination of glyph and BiLSTM-CRF model""" import tensorflow as tf from tensorflow.contrib.rnn import stack_bidirectional_dynamic_rnn as BiRNN from ner.optim import get_training_op def _get_transition_params(num_tags): with tf.variable_scope("crf", reuse=tf.AUTO_REUSE): transition_params = tf.get_va...
__all__ = [ "CLOEXEC", "NONBLOCK", "ACCESS", "MODIFY", "ATTRIB", "CLOSE_WRITE", "CLOSE_NOWRITE", "CLOSE", "OPEN", "MOVED_FROM", "MOVED_TO", "MOVE", "CREATE", "DELETE", "DELETE_SELF", "MOVE_SELF", "UNMOUNT", "Q_OVERFLOW", "IGNORED", "ONLYDI...
from enum import Enum from .linkedList import LinkedList from .bounds import DomainOperationResult from .constraintOperation import ConstraintOperationResult from .constraint import Constraint from .exceptions import UnsolvedException class StateOperationResult(Enum): Solved = 1 Unsatisfiable = 2 TimedOut ...
import pickle from os import listdir, makedirs from typing import List, Tuple, Union, Optional import json from os.path import join, exists, isfile, isdir from hotpot import config from hotpot.configurable import Configurable from hotpot.data_handling.data import RelevanceQuestion from hotpot.data_handling.word_vecto...
""" To get line profiling data, first install line-profiler pip install line-profiler --upgrade Then run the following two commands kernprof -l examples_gjrgarch_lineprofiler.py python -m line_profiler examples_gjrgarch_lineprofiler.py.lprof """ import numpy as np import matplotlib.pyplot as plt from n...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 9 14:55:25 2018 The double pendulum fractal image, restarting from a fresh perspective This code measures how long it takes for a double pendulum to flip @author: Michelle """ from numpy import sin, cos import numpy as np import matplotlib.pyplot ...
""" Date: Feb 20, 2020 Author: <NAME> Contents: Store persistent data from API calls Location (lat/lon) Cloud Cover Percentage External Temp """ import datetime import dotenv import json import os import pandas import pvlib.solarposition import requests import sys import controlalgorithm.user_defined_exceptions as ex...
import argparse import json import logging import os import pickle import subprocess import sys import tarfile logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) def install(package): subprocess.check_call([sys.executable, "-m", "pip", "install", package]) os.system("conda install -c sebp scik...
import logging from .a_blocker import ABlockerIO_Complex from .a_blk_pager import ABlockerIO_PosPager #=============================================== DEBUG_MODE = False #=============================================== class ABlockerIO_PageCluster(ABlockerIO_Complex): MAX_POS_COUNT = 50 def __init__(self, sch...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors. # # 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 class that wraps an ema.Cloud object and its relevant data. Uses that information to emit signals (from the enum like OPEN, CLOSE) which are then interpreted as buy/sell signals based on cloud status and current positions. Signals may or may not be followed up on based on stop/take profit levels and avail...
#!/usr/bin/env python -u '''chirpchirp.py - transmit data over audio with chirp modulation Usage: python -u chirpchirp.py (tx | rx) <fmin> <fmax> <period> [<volume>] python chirpchirp.py -h Options: -h Print this help. ''' from __future__ import print_function import codecs import functools import nu...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Run notebooks.""" import os from datetime import datetime from typing import Dict, List import papermill as pm PROJ_ROOT_DIR = os.path.abspath(os.getcwd()) raw_data_dir = os.path.join(PROJ_ROOT_DIR, "data", "raw") processed_data_dir = os.path.join(PROJ_ROOT_DIR, "...
#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- from typing import List class Solution: def minPathSum(self, grid: List[List[int]]) -> int: """状态转移方程:自顶向下 dp[m][n] = min(dp[m][n-1], dp[m-1][n]) + grid[i][j] """ def memoize(i, j): # 初始值 if i == 0 or j == 0:...
import os os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID" # see issue #152 os.environ["CUDA_VISIBLE_DEVICES"] = "0" from model import get_detect_model from common import CHARS import numpy as np import cv2 import sys import collections weights_file = 'model_weights_fc1_7.h5' WINDOW_SHAPE = (64, 128) def letter_prob...
# import matplotlib import matplotlib.pyplot as plt import pandas as pd # import numpy as np import re import time import sys import openpyxl from openpyxl import Workbook from openpyxl import load_workbook from openpyxl.chart import ( ScatterChart, Reference, Series, ) plt.rcParams['font.sans-serif'] = ['...
# dark blue for end nodes # light blue for path # dark green for currently searched nodes # light green for already searched nodes # white for empty import pygame, math, sys from a_star import * pygame.init() pygame.font.init() HEIGHT = 600 WIDTH = 600 display = pygame.display.set_mode((WIDTH, HEIGHT),...
import os import argparse import time import pickle from tqdm import tqdm import pandas as pd from multiprocessing import cpu_count #, get_context from helper_scripts.wit_url_downloader import download_wit_urls from helper_scripts.wit_clip_class import CLIP from helper_scripts.wit_dtype import DTYPE, DFLENGTH, DFLENGTH...
import requests import json from storage import make_s_msg_obj, users_storage, keyboards, state, timetable_output_mode import logging def handle(event): user_id = event['object']['message']['from_id'] r_msg = event['object']['message']['text'] # received message #s_msg = "что-то пошло не так" #keyboard...
# Base Parameters assets = asset_list('FX') # Trading Parameters horizon = 'H1' pair = 0 # Mass Imports my_data = mass_import(pair, horizon) def ma(Data, lookback, close, where): Data = adder(Data, 1) for i in range(len(Data)): try: ...
"""Testing error handling in the common test utilities. This module unit-tests the utilities we use for writing exhaustive test tools for the MLIR sparse codegen. """ from typing import Callable, List import inspect import itertools import logging import numpy as np import sys # Import MLIR related modules. from mli...
import numpy as np import os, json, torch, math from PIL import Image, ImageDraw from torchvision import transforms from torch.utils.data import Dataset # from functions import iou_v2, target2line, YolinoLoss class YolinoDataset(Dataset): def __init__(self, dataset_dir, image_transform, phase, p, k): self....
#!/usr/bin/env/ python3 """Guess a random number, or make the computer guess yours!""" __version__ = '0.2' __author__ = 'ehlodex' import random import time import os default_max_tries = int(10) default_min = random.randint(1, 100) # or int(1) default_max = random.randint(default_min+50, default_min+100) # or int(1...
import astropy.io.fits as pyfits import numpy as np import scipy.interpolate import warnings from bbbd.util.intervals import TimeInterval class NoGTI(RuntimeError): pass class LLEExposure(object): def __init__(self, lle_file, ft2_file): # Read GTIs and trigger time from FT1 with pyfits.op...
import torch from torch import nn from torch import optim from vae import * from loader import * from skempi_lib import * from torch_utils import * BATCH_SIZE = 32 LR = 1e-3 def get_loss(aa_hat, aa, x_hat, x, mu, logvar): KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) L1 = nn.L1Loss(reduction...
# -*- coding: utf-8 -*- """ Dependencies: flask, tornado """ from __future__ import absolute_import, division, print_function import tornado.wsgi import tornado.httpserver import logging import socket from ibeis.control import controller_inject from ibeis.web import apis_engine from ibeis.web import job_engine from ibe...
"""Contains all the functions from ``casioplot`` calculator module. Available functions: - :py:func:`set_pixel` - :py:func:`get_pixel` - :py:func:`draw_string` - :py:func:`clear_screen` - :py:func:`show_screen` You can also use :py:data:`casioplot_settings` to change some behavior. """ import os from typi...
import curses import dis import locale from types import CodeType from src.frame import Frame locale.setlocale(locale.LC_ALL, '') def get_repr(x): expr = repr(x) if len(expr) > 30: expr = '< {} object >'.format(type(x).__name__) return expr def write_code(scr: curses.window, code: CodeType): ...