content
stringlengths
5
1.05M
#!/usr/bin/env python # coding=utf-8 """ verify typehints match expected objects no method found to directly check object instances against non-trivial typehints. isinstance(«object», «typehint») fails with `TypeError: isinstance() argument 2 cannot be a parameterized generic` Some tools exist to parse typehint det...
import pygame, sys from pygame.locals import * from sys import exit class Player(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.Surface([30,30]) self.image.fill([255,0,0]) self.rect = self.image.get_rect() def move_player(self...
# coding: utf-8 """ Arduino IoT Cloud API Provides a set of endpoints to manage Arduino IoT Cloud **Devices**, **Things**, **Properties** and **Timeseries**. This API can be called just with any HTTP Client, or using one of these clients: * [Javascript NPM package](https://www.npmjs.com/package/@arduino/ard...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ /* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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 * * h...
import re from datetime import datetime import pytest from pydantic import ValidationError from node.blockchain.facade import BlockchainFacade from node.blockchain.inner_models import ( AccountState, BlockMessage, BlockMessageUpdate, CoinTransferBlockMessage, CoinTransferSignedChangeRequest ) from node.blockchain...
""" xbox360-arduino-flasher --Ian Ling (https://iancaling.com) Dumps xbox360 NAND via an Arduino """ import serial import struct from math import floor from sys import argv, exit from time import time # globals SERIAL_DEVICE = "/dev/ttyACM0" BAUD_RATE = 115200 DUMP_COMMAND = b"d" FLASH_COMMAND = b"f" FLASH_CONFIG_C...
from setuptools import setup with open("README.md","r") as fh: long_description=fh.read() setup( name='hithere', version='0.0.1', description="Say hi !!", py_modules=["hithere"], package_dir={'':'src'}, long_description=long_description, long_description_content_type="text/markdown", ...
#!/usr/bin/env python ########################################################################################## # Developer: Icaro Alzuru Project: HuMaIN (http://humain.acis.ufl.edu) # Description: # Compares the text files of two directories using the Damerau-Levenshtein similarity. # #####################...
#! /usr/bin/env python ############################################################################ # Copyright (c) 2009 Dr. Peter Bunting, Aberystwyth University # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to ...
from django.shortcuts import render #from arches.app.models.system_settings import settings def index(request): return render(request, 'index.htm')
"""Extension of utilities.py to provide functions required to check the version information of enrichr and determine if it needs to be updated. Classes: Enrichr: Extends the SrcClass class and provides the static variables and enrichr specific functions required to perform a check on enrichr. Functions: ...
#Author: Jayendra Matarage #Title: Distance Finder #Date : 31, Jan, 2019 from Getdata import Getdata from distance import Distance getdata = Getdata() distanceCal = Distance() def main(): print("---------------------------------") print("|\t\tDISTANCE FINDER\t\t|") print("-------------------------------...
class LTEMol(): def __init__(): pass def tex(): pass def Tbkg(): pass
""" # Copyright 2022 Red Hat # # 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 agr...
# -*- coding: utf-8 -*- # Copyright (c) 2011, Sebastian Wiesner <lunaryorn@gmail.com> # 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 copy...
'''Display a sum problems with a function returning a string, not printing directly. ''' def sumProblemString(x, y): sum = x + y return 'The sum of {} and {} is {}.'.format(x, y, sum) def main(): print(sumProblemString(2, 3)) print(sumProblemString(1234567890123, 535790269358)) a = int(input("Ente...
import os import cv2 import numpy as np import time def find_orientation(image, template): img_rgb = image if len(img_rgb.shape) == 3: img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) else: img_gray = image #w, h = template.shape[::-1] res = cv2.matchTemplate(img_gray,templa...
""" Train an agent using Proximal Policy Optimization from OpenAI Baselines """ import argparse import sys import retro import os import numpy as np import gym import tensorflow as tf from baselines.common.vec_env import SubprocVecEnv from baselines.common.vec_env.vec_video_recorder import VecVideoRecorder from ppo2 ...
import numpy as np import pandas as pd import os from os.path import exists, join from tensorflow.keras.layers import Input, Dense, Dropout, GaussianNoise from tensorflow.keras.models import Model from tensorflow.keras.regularizers import l2 from tensorflow.keras.optimizers import Adam, SGD import xarray as xr class ...
import logging import pickle # get a usable pickle disassembler if pickle.HIGHEST_PROTOCOL >= 5: from pickletools import dis as pickle_dis else: try: from pickle5.pickletools import dis as pickle_dis except ImportError: pass from lenskit.algorithms import als from lenskit import util impo...
""" @author: Maziar Raissi """ import sys sys.path.insert(0, "../../Utilities/") import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import scipy.io from scipy.interpolate import griddata from pyDOE import lhs from plotting import newfig, savefig from mpl_toolkits.mplot3d import Axes3D import ...
import math import os import uuid import cv2 import numpy as np import tensorflow as tf import tensorflow_hub as tfhub from tensorflow.keras.utils import get_file def produce_embeddings(model, input_frames, input_words): frames = tf.cast(input_frames, dtype=tf.float32) frames = tf.constant(frames) video_...
from __future__ import absolute_import, division, print_function, unicode_literals from six import python_2_unicode_compatible from canvasapi.bookmark import Bookmark from canvasapi.paginated_list import PaginatedList from canvasapi.user import User from canvasapi.util import combine_kwargs, obj_or_id @python_2_uni...
""" This example creates a center column study reactor using a parametric reactor. Adds some TF coils to the reactor. By default the script saves stp, stl, html and svg files. """ import paramak def make_center_column_study_reactor( outputs=[ 'stp', 'neutronics', 'svg', 'stl', ...
# -*- coding: utf-8 -*- """ Created on Tue Sep 18 14:21:09 2018 @author: Basil """ # -*- coding: utf-8 -*- """ Created on Sat Jul 14 19:33:08 2018 @author: Basil """ #from numpy import * import gc import numpy import time from joblib import Parallel, delayed def GetIntensityDependence(zs, useRunningTime = Fal...
# Sprobuj wykonac w shellu: # locals() # globals() # import a01_funkcje # locals() # globals() """ Opis modulu """ a = 1 b = 2 def test1(arg1): """To jest pierwsza linia opisu A to sa kolejne I jeszcze I jeszcze. """ a = arg1 print('test1: LOCALS :', locals()) print('test1: GLOBALS ...
import numpy as np class BayesNet(object): ''' Define a Bayesian Network class ''' def __init__(self): self.nodes = None class Node(object): def __init__(self, table, state): self.table = table self.state = state if __name__ == "__main__": pass
import os import sys import numpy as np import rootpath import xml.etree.ElementTree as ET from collections import namedtuple try: sys.path.append(os.path.join(rootpath.detect())) import setup from argU.preprocessing.texts import clean_to_nl from argU.preprocessing.texts import clean_to_train from ...
import sgtk from sgtk.platform.qt import QtCore, QtGui import cPickle from ..ui.my_time_form import Ui_MyTimeForm logger = sgtk.platform.get_logger(__name__) class MyTimeTree(QtGui.QListView): ''' a listView whose items can be moved ''' def __init__(self, parent=None): QtGui.QListView.__ini...
"""Leetcode 4. Median of Two Sorted Arrays Hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). You may assume nums1 and nums2 cannot be both empty. Example 1: nums1 = [1, 3] nums2 = [2] The ...
# Copyright (C) 2020 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """Object mapper modal.""" from lib import base from lib.page.modal import search_modal_elements class ObjectMapper(base.WithBrowser): """Object mapper modal.""" # pylint: disable=too-few-public-methods...
from django.core.mail import send_mail, EmailMessage, send_mass_mail, EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags FROM_EMAIL = 'no-reply@massenergize.org' def send_massenergize_email(subject, msg, to): ok = send_mail( subject, msg, ...
""" Test autoencoder sparse activation cost. """ from pylearn2.config import yaml_parse def test_sparse_activation(): """Test autoencoder sparse activation cost.""" trainer = yaml_parse.load(test_yaml) trainer.main_loop() test_yaml = """ !obj:pylearn2.train.Train { dataset: &train !obj:pylear...
#!/usr/bin/env python2 # CVE-2018-10933 Scanner by Leap Security (@LeapSecurity) https://leapsecurity.io import socket, argparse, sys, os, paramiko, ipaddress from six import text_type VERSION = "1.0.4" class colors(object): blue = "\033[1;34m" normal = "\033[0;00m" red = "\033[1;31m" yellow = "\033...
# Generated by Django 3.0.3 on 2020-02-18 15:01 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('console', '0006_auto_20200218_1601'), ] operations = [ migrations.AlterField( model_name='timeentry', ...
import cv2 import threading #from tf_pose_estimation.run_v3 import PoseEstimator class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() self.stopped = False #self.estimator = PoseEstimator() #def _configure...
""" Database Initialize and create connection control flow for database. Datase parameters must be set in config.py or directly in app.py """ from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session from contextlib import contextmanager from models import * import click fr...
import sys import json import urllib.request import time print( "usage python .\\6removeoldscrape.py data.json outfile.json" ) url_start = "http://store.steampowered.com/api/appdetails?appids=" with open(sys.argv[1], 'r') as json_data: data = json.load(json_data) for item in list(data): appid = data[item]["...
from stat import S_IFDIR, S_IFLNK, S_IFREG from typing import Dict, Iterable import aiohttp from io import BytesIO import os from .types import * from .core import * from . import types_conv class BaseFile(Node): def __init__(self, mode: int = 0o444) -> None: self.mode = mode & 0o777 async def getat...
import re texto =''' ===t1 <h1>{{v1}}</h1> {{L1,T2}} ===T2 viva o Salgueiros ''' def compilaTemplates(txt): texto_Separado = re.split(r'===',texto) #Deitar fora o primeiro bocado do split pois e inutil texto_Separado.pop(0) for t in texto_Separado: t = re.sub(r'(\w+)(.+)',r"def \1(d): r...
""" Collection of PyTorch general functions, wrapped to fit Ivy syntax and signature. """ # global import ivy import numpy as np torch_scatter = None import math as _math import torch as torch from operator import mul from torch.types import Number from functools import reduce as _reduce from typing import List, Dict,...
# Copyright (c) Facebook, Inc. and its affiliates. import torch import torch.nn as nn import torch.nn.functional as F import random class DecoderStep(nn.Module): def __init__(self, input_dim, output_dim, hidden_dim, lstm=None): super(DecoderStep, self).__init__() self.lstm = ( nn.LSTM...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # vim: set et sw=4 ts=4 sts=4 ff=unix fenc=utf8: # Author: Binux<i@binux.me> # http://binux.me # Created on 2014-02-22 14:00:05 import os import copy import time import unittest2 as unittest import logging.config logging.config.fileConfig("pyspider/logging.conf")...
import logging from concurrent.futures.thread import ThreadPoolExecutor from smtplib import SMTPAuthenticationError from crispy_forms.helper import FormHelper from crispy_forms.layout import HTML, Button, ButtonHolder, Column, Div, Field, Layout, Row, Submit from django import forms from django.contrib.auth import get...
# Copyright 2008-2015 Nokia Solutions and Networks # # 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 l...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' docker-parse is a useful command to get docker-run commands or docker-compose configurations from running containers ''' from __future__ import absolute_import from __future__ import print_function import sys import pipes import getopt import yaml import docker __ve...
from django.urls import path from charaViewer.viewer.views import (top_view, login_view) urlpatterns = [ path('', top_view, name="viewer_top"), path('login', login_view, name="viewer_login"), ]
import os import pandas as pd from copy import deepcopy from itertools import product from indra.sources import signor from collections import defaultdict from indra.statements import Activation, Inhibition from causal_precedence_training import locations def get_relevant_signor_statements(): """Get Inhibition a...
# -*- coding: utf-8 -*- #BEGIN_HEADER import os import sys import shutil import hashlib import subprocess import traceback import uuid import logging import pprint import json import tempfile import re from datetime import datetime from AssemblyUtil.AssemblyUtilClient import AssemblyUtil from pprint import pprint, pfor...
# This file allows you to programmatically create blocks in PiWorld. # Please use this wisely. Test on your own server first. Do not abuse it. import socket import sys import time DEFAULT_HOST = '127.0.0.1' DEFAULT_PORT = 4080 EMPTY = 0 GRASS = 1 SAND = 2 STONE = 3 BRICK = 4 WOOD = 5 CEMENT = 6 DIRT = 7 PLANK = 8 SN...
""" Tracing Context Injection. @author: Hao Song (songhao@vmware.com) """ import opentracing # pylint: disable=protected-access def inject_as_headers(tracer, span, request): """Inject tracing context into header.""" text_carrier = {} tracer._tracer.inject(span.context, opentracing.Format.TEXT_MAP, ...
import logging import re import socket from http.client import HTTPMessage from .proxy2 import ProxyRequestHandler from .request import Request, Response from .utils import is_list_alike log = logging.getLogger(__name__) class CaptureMixin: """Mixin that handles the capturing of requests and responses.""" ...
''' Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path. In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. Note that the returned canonical path must always begin with a ...
import datetime from io import StringIO import concurrent.futures import os import sys import pandas as pd import requests sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from top_counties import most_infected def days_between(start_date: datetime.date, end_date: datetime.date) -> list: """retur...
import json import operator def filter_dict(input_dict): output_dict = dict() for tmp_verb in input_dict: sorted_x = sorted(input_dict[tmp_verb].items(), key=operator.itemgetter(1)) output_dict[tmp_verb] = sorted_x[:5] return output_dict with open('verb_nsubj_amod_dict.json', 'r') as nsu...
import numpy as np import tensorflow as tf import sys import time from sklearn.metrics import f1_score import random class hisan(object): ''' hierarchical self-attention network parameters: - embedding_matrix: numpy array numpy array of word embeddings each row should represent a...
import numpy as np import tensorflow as tf import torch from torch.nn import functional as F def createCircularMask(h, w, center=None, radius=None): if center is None: # use the middle of the image center = [int(w / 2), int(h / 2)] if radius is None: # use the smallest distance between the center a...
#### # This script demonstrates how to use the Tableau Server API # to publish a workbook to a Tableau server. It will publish # a specified workbook to the 'default' project of the given server. # # Note: The REST API publish process cannot automatically include # extracts or other resources that the workbook uses. Th...
""" Unix functions wrapped in Python """ import os import random import shutil import socket import time from seisflows.tools.tools import iterable def cat(src, *dst): """ Concatenate files and print on standard output """ with open(src, 'r') as f: contents = f.read() if not dst: ...
import numpy as np import tensorflow as tf def split_reim(array): """Split a complex valued matrix into its real and imaginary parts. Args: array(complex): An array of shape (batch_size, N, N) or (batch_size, N, N, 1) Returns: split_array(float): An array of shape (batch_size, N, N, 2) conta...
#!/usr/bin/env python import os import string import sys sys.path.insert(0, "../../../util/python") import Util fn_in = None fn_out = None class ReadCnt: def __init__(self, r, fp, tp): self.reads = r self.bf_fp = fp self.bf_tp = tp self.bf_n = r - fp - tp self.reads_miss = r - tp def __str__(self): r...
"""Main. The main script that is called to run everything else. Author: Yvan Satyawan <y_satyawan@hotmail.com> """ from platform import system from trainer import Trainer from utils.slacker import Slacker from os import getcwd from os.path import join import warnings import traceback try: import curses exc...
class PriceInfo(object): def __init__(self, curr_trend, trend_today, trend_30, trend_90, trend_180, osbuddy_price): self.curr_trend = curr_trend self.trend_today = trend_today self.trend_30 = trend_30 self.trend_90 = trend_90 self.trend_180 = trend_180 self.osbuddy_price = osbuddy_price def price(self)...
# Copyright 2015 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. # Runs the Microsoft Message Compiler (mc.exe). This Python adapter is for the # GN build, which can only run Python and not native binaries. # # Usage: mess...
# -*- coding: utf-8 -*- """ Created on Sat Jul 6 16:02:49 2019 @author: KuroAzai """ import Calculator def LessThanSix(calc,ops): print(calc[1]) if calc[1] == ops[0]: result = Calculator.Addition(calc[0],calc[2]) print("Add" , result) elif calc[1] == ops[1]: result...
from sql_helper import MySqlHelper class Admin(object): def __init__(self): self.__helper = MySqlHelper() def get_table_servers(self):#查询servers表 sql="select * from servers" params = None return self.__helper.Get_Dict(sql,params) def get_table_users(self):#查询users表 s...
matriz = [list(linea)[-1] for linea in open("Laberinto.txt").readlines()] class Nodo(): def __init__(self,valor,posicion,hijos=[]): self.valor=valor self.posicion = posicion self.hijos=hijos def agregarHijo(self,hijo): self.hijos.append(hijo) def setPosicion(self,p...
from .models import PartClass def full_part_number_to_broken_part(part_number): part_class = PartClass.objects.filter(code=part_number[:3])[0] part_item = part_number[4:8] part_variation = part_number[9:] civ = { 'class': part_class, 'item': part_item, 'variation': part_variat...
#!/usr/bin/env python # Copyright 2012 Laboratory for Advanced Computing at the University of Chicago # # This file is part of UDR. # # 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 ...
# Copyright (c) OpenMMLab. All rights reserved. from typing import Sequence import torch from mmdeploy.codebase.mmdet import (get_post_processing_params, multiclass_nms, pad_with_value_if_necessary) from mmdeploy.core import FUNCTION_REWRITER f...
import torch from tests import utils class GatherModule(torch.nn.Module): def __init__(self, dimension): super(GatherModule, self).__init__() self.dimension = dimension def forward(self, tensor, index): return torch.gather(tensor, self.dimension, index) class TestGather(utils.TorchG...
# coding: utf-8 from .link import Link from .statistics import ImportStatistics
import math """ 今天看了一篇Python的文章,才发现还有这种写法,这基本上和Swift没什么区别了 """ def swiftStyle(): """ 一个Swift风格的函数表达式 """ a: str = "aa" b: int = 1 # 虽然a被定义成了str类型,但是这里还是可以对a赋值2,并且不会报错,print也没什么异常 a = 2 print(a) isinstance(a, int) # 参数和返回标注了类型,那么接下来调用时就能进行提示 def example(a: str) -> str: ret...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'exampleWatchlist.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! # This code is to be used as a reference for the code for generating the watchlist # window when a user loads their...
import json import unittest from json import JSONDecodeError from unittest.mock import patch, Mock from spresso.model.base import Composition, User, JsonSchema, Origin from spresso.utils.base import get_url class CompositionTestCase(unittest.TestCase): def test_init(self): c = Composition() self....
import ftplib import glob import subprocess as sp import csv import numpy as np import netCDF4 as nc4 import pygrib as pg import matplotlib.pyplot as plt plt.switch_backend('agg') import datetime import scipy import os import sys from mpl_toolkits.basemap import Basemap from matplotlib.patches import Polygon from matp...
from sys import exit try: from cap1xxx import Cap1166, PID_CAP1166 except ImportError: exit("This library requires the cap1xxx module\nInstall with: sudo pip install cap1xxx") I2C_ADDR = 0x2c UP = 1 DOWN = 2 LEFT = 3 RIGHT = 5 BUTTON = 4 CANCEL = 0 _cap1166 = Cap1166(i2c_addr=I2C_ADDR) _cap1166._write_byte...
#!/usr/bin/env python3 import numpy as np import matplotlib # Force matplotlib to not use any X Windows backend (must be called befor importing pyplot) matplotlib.use('Agg') import matplotlib.pyplot as plt def plotDataPoints(X, idx, K, i): #PLOTDATAPOINTS plots data points in X, coloring them so that those with ...
import typing as t import logging from typing import TYPE_CHECKING logger = logging.getLogger("bentoml.tests") if TYPE_CHECKING: from aiohttp.typedefs import LooseHeaders from starlette.datastructures import Headers from starlette.datastructures import FormData async def parse_multipart_form(headers: "...
from argparse import ArgumentParser from . import __version__ parser = ArgumentParser( prog="sqlite3_shell", description="Python SQLite3 shell" ) parser.add_argument( "--version", action="version", version=f"sqlite3-shell {__version__}" ) parser.add_argument( "database", default=":memory:", nargs="?", help="dat...
#!/usr/bin/env python # -*- coding: utf-8 -*- import dash_core_components as dcc import dash_html_components as html from utilities.models import * from honeycomb import * @db_session def load_statistics(statistic): """This function takes a string as parameter and returns a certain value, which is then displaye...
# -*- coding: utf-8 -*- import pandas as pd from zvt.api.data_type import Region, Provider, EntityType from zvt.domain import Stock, StockDetail from zvt.recorders.consts import YAHOO_STOCK_LIST_HEADER from zvt.contract.recorder import RecorderForEntities from zvt.contract.api import df_to_db from zvt.networking.reque...
#!/usr/bin/env python import tamasis as tm import csh import csh.score import numpy as np import lo import scipy.sparse.linalg as spl # data pacs = tm.PacsObservation(filename=tm.tamasis_dir+'tests/frames_blue.fits', fine_sampling_factor=1, keep_bad_detectors=True) tod = pacs.get_tod() # comp...
import matplotlib.gridspec import matplotlib.pyplot as plt import numpy as np from predicu.data import CUM_COLUMNS from predicu.plot import COLUMN_TO_HUMAN_READABLE data_source = ["bedcounts"] def plot(data): n_rows = (len(CUM_COLUMNS) + len(CUM_COLUMNS) % 2) // 2 fig = plt.figure(figsize=(n_rows * 5, 10)) ...
from setuptools import setup, find_packages setup(name='backstabbr_api', version='1.0.2', description='Web-scraper API and Discord Bot for the online diplomacy program Backstabbr', url='https://github.com/afkhurana/backstabbr_api', author='Arjun Khurana', author_email='afkhurana@gmail.com', license='MIT', ...
""" 今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有这些顾客都会在那一分钟结束后离开。 在某些时候,书店老板会生气。 如果书店老板在第 i 分钟生气,那么 grumpy[i] = 1,否则 grumpy[i] = 0。 当书店老板生气时,那一分钟的顾客就会不满意,不生气则他们是满意的。 书店老板知道一个秘密技巧,能抑制自己的情绪,可以让自己连续 X 分钟不生气,但却只能使用一次。 请你返回这一天营业下来,最多有多少客户能够感到满意的数量。   示例: 输入:customers = [1,0,1,2,1,1,7,5], grumpy ...
"""The STOMP command and header name strings. """ HDR_ACCEPT_VERSION = 'accept-version' HDR_ACK = 'ack' HDR_CONTENT_LENGTH = 'content-length' HDR_CONTENT_TYPE = 'content-type' HDR_DESTINATION = 'destination' HDR_HEARTBEAT = 'heart-beat' HDR_HOST = 'host' HDR_ID = 'id' HDR_MESSAGE_ID = 'message-id' HDR_LOGI...
#!/usr/bin/env python """ convnet/prep.py Grabs the first two classes of CIFAR10 and saves them as numpy arrays Since we don't assume everyone has access to GPUs, we do this to create a dataset that can be trained in a reasonable amount of time on a CPU. """ import os import sys import numpy...
from pyrogram import filters from pyrogram.types import Message from wbb import BOT_ID, SUDOERS, USERBOT_PREFIX, app2 from wbb.core.decorators.errors import capture_err from wbb.modules.userbot import edit_or_reply from wbb.utils.dbfunctions import add_sudo, get_sudoers, remove_sudo from wbb.utils.functions import res...
import re from collections import defaultdict import math from lxml import html from lxml import etree from .book import Book from .quote import Quote from .page_loader import download_page, wait_for_delay def error_handler(where, raw): """ Обработчик ошибки при парсинге html страницы :param where: string...
# Copyright (C) 2010, 2015 Apple 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...
from gym.spaces import Dict from .simple_replay_pool import SimpleReplayPool, Field import numpy as np from flatten_dict import flatten class MultiGoalReplayPool(SimpleReplayPool): def __init__(self, extra_fields={}, *args, **kwargs): extra_fields['relab...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains library item tree view implementation """ from __future__ import print_function, division, absolute_import import logging import traceback from Qt.QtCore import Qt, Signal, QPoint, QRect, QSize, QMimeData from Qt.QtWidgets import QListView, QAb...
from keystone.backends.sqlalchemy import migration from keystone import version from keystone.manage2 import base from keystone.manage2 import common from keystone.logic.types import fault @common.arg('--api', action='store_true', default=False, help='only print the API version') @common.arg('--implementation...
"""Unit test package for htping."""
from selenium import webdriver import time import csv from csv import reader from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC browser = webdriver.Chrome("/usr/bin/chromedriver") browser.get("http://loc...
from __future__ import unicode_literals import logging import typing from copy import deepcopy from django.core.exceptions import ( NON_FIELD_ERRORS, ObjectDoesNotExist, ValidationError, ) from django.db import models from django.db.models import Q, UniqueConstraint from django.utils.encoding import pytho...
from __future__ import division import numpy as np from warnings import warn import torch # Fixed MRI Simulator def get_precomputed_matrices(batch_size, alphas, T): cosa2 = torch.cos(alphas/2.)**2 sina2 = torch.sin(alphas/2.)**2 cosa = torch.cos(alphas) sina = torch.sin(alphas) RR = torch.zeros...
from pathlib import Path import numpy as np from torch import nn import torch from torch.nn import functional as F import pytorch_lightning as pl from pytorch_lightning.trainer import Trainer from sklearn.model_selection import train_test_split from torch.utils import data from dataset import SplitDataset from argparse...
from typing import Union, Dict import pygame from pygame_gui.core.interfaces import IContainerLikeInterface, IUIManagerInterface from pygame_gui.core import UIElement from pygame_gui.core.drawable_shapes import RectDrawableShape, RoundedRectangleShape class UIWorldSpaceHealthBar(UIElement): """ A UI that wi...