content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library', '0032_auto_20170502_0132'), ] operations = [ migrations.AddField( model_name='casebrief', ...
import sys, os # need a different name import random as rnd import pprint pp = pprint.pprint import pdb kwdbg = 0 W, H = 542, 1050 fullwidth = int(W-20) tilewidth = int((fullwidth-10) / 2.0) # check for Nodebox NB = True try: _ctx except(NameError): NB = False if NB: size(W, H) pb = ximport("phot...
import typing as t SchemeType = t.Literal["RA", "CA", "MA", "PA", ""] NodeType = t.Literal["RA", "CA", "MA", "PA", "", "I", "TA", "YA", "L"] DATE_FORMAT = "YYYY-MM-DD HH:mm:ss" class Node(t.TypedDict): nodeID: str text: str type: NodeType timestamp: str class Edge(t.TypedDict): edgeID: str ...
""" A pair of production base environments. """ def update_envs_production(env_dir_name, env_yml_path, env_path_a="/prj/ids/ids-conda/envs_ping", env_path_b="/prj/ids/ids-conda/envs_pong", prod_env_path_link="/prj/ids/ids-conda/envs_prod...
import RPi.GPIO as GPIO import time from enum import Enum class StickType(Enum): Center = 7 Front = 8 Right = 9 Left = 10 Back = 11 class Joystick: def __init__(self): self.callback = None for pin in StickType: GPIO.setup(pin.value, GPIO.IN, GPIO.PUD_UP) ...
# SPDX-FileCopyrightText: 2021 Carnegie Mellon University # # SPDX-License-Identifier: Apache-2.0 import os import psycopg2 # connect to the testdb database try: host_addr = "127.0.0.1" pw = os.getenv("LIVEMAP_DB_PASSWORD") conn = psycopg2.connect( database="livemap_db", user="osm", ...
########################################## # check ancestry of the unknown # sequence by comparing with # known sequences ########################################## f=open("asia","r") asia=f.readline() f.close() f=open("africa","r") africa=f.readline() f.close() f=open("south-america","r") south=f.readline()...
from http.client import HTTPConnection, HTTPSConnection from http.cookies import SimpleCookie from json import loads as json_loads from urllib.parse import urlencode, urljoin, urlsplit from wheezy.core.collections import attrdict, defaultdict from wheezy.core.gzip import decompress class HTTPClient(object): """H...
import cv2, mediapipe as mp class PoseTrack: def __init__(self, static_image_mode=False, upper_body_only=False, smooth_landmarks=True, min_detection_confidence=0.5, min_tracking_confidence=0.5 ): ...
import math def solution(A, B): maxA = max(A) fib = [1] * (maxA + 1) for i in range(2, maxA + 1): fib[i] = fib[i - 1] + fib[i - 2] n = len(A) answers = [0] * n for i in range(n): answers[i] = fib[A[i]] % int(math.pow(2, B[i])) return answers
import os import torch from utils.utils import get_logger, is_logging_process import wandb def test_model(cfg, model, test_loader, writer): logger = get_logger(cfg, os.path.basename(__file__)) model.net.eval() total_test_loss = 0 test_loop_len = 0 with torch.no_grad(): example_images = [...
import os as _os import sys as _sys import dash as _dash from .version import __version__ _current_path = _os.path.dirname(_os.path.abspath(__file__)) _components = _dash.development.component_loader.load_components( _os.path.join(_current_path, 'metadata.json'), 'dash_core_components' ) _this_module = _sys....
name = input("Enter your name : ") print(name) name = "max" print(name) length = len(name) print(length) # Variables rules """ 1. only a-z, A-Z, 0-9, _ are allowed 2. Do not start with number 3. No other special characters 4. No use of reserved words 5. case sensitive """
"""Schema for the API endpoints.""" from marshmallow import Schema, fields class PresentationSchema(Schema): """Schema for the presetntation.""" participant_id = fields.Int() role = fields.Str() order = fields.Int() class NewPanelSchema(Schema): """Schema for the panel.""" name = fields.St...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : .ycm_extra_osx_conf.py # License: MIT/X11 # Author : Dries Pauwels <2mjolk@gmail.com> # Date : do 13 sep 2018 10:24 import os import ycm_core # These are the compilation flags that will be used in case there's no # compilation database set (by default, one is ...
import tkinter as tk def say(): m.config(text="WELCOME " + e.get()) root = tk.Tk() root.title('Strawberry Cake') root.config(bg='#0394fc') m = tk.Label(root, text='WELCOME!', bg='#0394fc', fg='orange', font=('Comic Sans MS', 20)) m.pack() e =tk.Entry(root, bg='#0394fc', fg='orange', font=('times', 20)) e.pa...
"""Denon HEOS Media Player.""" from __future__ import annotations import asyncio from datetime import timedelta import logging from pyheos import Heos, HeosError, const as heos_const import voluptuous as vol from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.const import CONF_HOST...
import datetime from footynews.aggregator import exceptions from footynews.aggregator.base import (Aggregator, Article, InvalidArticle, make_soup) from footynews.aggregator.utils import code_to_month class FourFourTwo(Aggregator): base_url = 'http://www.fourfourtwo.com/fea...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', ...
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ # if len less then two if len(s) < 2: return s self.res = "" # loop true each letter nd run helper function for i in range(len(s)): # for o...
from os.path import isfile from Message import Message from api import send_message from command.Command import Command class Remind(Command): def __init__(self): super().__init__() self.help = "/remind — напомнить сообщение\n" self.full_help = "/remind [ключ] — напомнить сообщение по клю...
import sys import numpy as np from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QComboBox, QLineEdit, QListWidget from PyQt5.QtCore import pyqtSignal class GuessTransition(QWidget): '''Pop-up Widget to select ions''' # Exporting signals send_z_cal = pyqtSignal(list) # Initialization - Widget main layout ...
''' Copyright 2020 CITA 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, software distribute...
from passlib.hash import pbkdf2_sha256 import time import json from citybuilder import core from random import randrange class Unit: def __init__(self, key, level): self.type = key self.level = level class Job: def __init__(self, player, product): self.player = player self.pr...
# -*- coding: utf-8 -*- from statsmodels.compat.python import lzip import numpy as np from . import kernels #TODO: should this be a function? class KDE(object): """ Kernel Density Estimator Parameters ---------- x : array_like N-dimensional array from which the density is to be estimated ...
""" Based on rllab's logger. https://github.com/rll/rllab """ import csv import datetime import errno import joblib import json import os import os.path as osp import pickle import sys import torch from collections import OrderedDict from contextlib import contextmanager from enum import Enum import dateutil.tz impor...
import numpy as np from PyQt5 import QtWidgets def save_fig(fig): fname = QtWidgets.QFileDialog.getSaveFileName(caption='Save current figure', filter='Image (*.png)') if fname[0]: fig.savefig(fname[0], bbox_inches='tight')
from . import nn, rl, util, RaggedArray, ContinuousSpace, FiniteSpace, optim, thutil import policyopt import numpy as np import theano.tensor as T from scipy.spatial.distance import cosine from contextlib import contextmanager import theano; from theano import tensor from scipy.optimize import fmin_l_bfgs_b import pi...
DOXYFILE = 'Doxyfile-mcss' MAIN_PROJECT_URL = '../index.html' SHOW_UNDOCUMENTED = True LINKS_NAVBAR1 = [ ('Pages', 'pages', []), # ('Namespaces', 'namespaces', []), ('Classes', 'annotated', []), ('Files', 'files', []) ] LINKS_NAVBAR2 = [ ('<a href=\"../python/index.html\">Python</a>', []), ('<...
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint: disable=missing-docstring,import-error,wrong-import-order import cv2 import numpy as np from common.camera import Camera def main(): def callback(frame, _): edges = cv2.Canny(frame, 100, 200) cv2.imshow('frame', np.vstack((frame, edges))) with Came...
## Lexer # # @filename Lexer.py # @author Ben Mariano # @date 5/9/2017 # # @brief Custom language lexer/tokenizer. from Token import Token # Token Types (LPAREN, RPAREN, COMMA, LBRACK, RBRACK, LCURLY, RCURLY, SEMI, EQUALS, LESSTHAN, GREATERTHAN, LESSEQUAL, GREATEREQUAL, AND, OR, COLON, ID, INTEGER, CAUSES, DOT, Q...
from __future__ import absolute_import import jax from jax import numpy as jnp def cuda(): try: return jax.devices("gpu")[0] except: return None def is_cuda_available(): from jax.lib import xla_bridge return 'gpu' in str(xla_bridge.get_backend().platform) def array_equal(a, b): i...
import enum class ActivationType(enum.Enum): """ The activation types are used to link a specific precursor mass with an activation type. There are 26 possible mode values, including some reserved values. """ CollisionInducedDissociation = 0 MultiPhotonDissociation = 1 ElectronCaptureDisso...
""" !/usr/bin/python3.7 -*- coding: UTF-8 -*- Author: https://github.com/Guanyan1996 ┌─┐ ┌─┐ ┌──┘ ┴───────┘ ┴──┐ │ │ │ ─── │ │ ─┬┘ └┬─ │ │ │ │ ─┴─ │ │ │ └───┐ ┌───┘ ...
from config import * from keyboard import * from functions import * def start_seller(user): """ This is the handler to start seller options """ keyboard = seller_menu() user = get_user(msg=user) bot.send_message( user.id, emoji.emojize( ":robot: What would you...
import os import slack import requests import datetime import yaml from GoogleAPI import Create_Service from googleapiclient.http import MediaFileUpload from slackeventsapi import SlackEventAdapter from pathlib import Path from dotenv import load_dotenv from flask import Flask, request, Response """ Load environment ...
# Link urls to views from django.urls import path from . import views # App name app_name = 'dashboard' # Routes urlpatterns = [ path('', views.index, name='index'), path('detail', views.detail, name='detail'), path('history', views.history, name='history'), path('get_newest_readings/<str:racks>/<str...
from django.apps import AppConfig from tulius.websockets import runserver class WebsocketsConfig(AppConfig): name = 'tulius.websockets' label = 'websockets' verbose_name = 'websockets' def ready(self): runserver.patch()
# -*- coding: utf-8 -*- """ NG PyTest Salt Plugin """ # pragma: no cover import os import re import sys from saltfactories._version import get_versions # Store the version attribute __version__ = get_versions()["version"] del get_versions # Define __version_info__ attribute VERSION_INFO_REGEX = re.compile( r"(?...
""" Cisco_IOS_XR_fretta_bcm_dpa_npu_stats_oper This module contains a collection of YANG definitions for Cisco IOS\-XR fretta\-bcm\-dpa\-npu\-stats package operational data. This module contains definitions for the following management objects\: dpa\: Stats Data Copyright (c) 2013\-2018 by Cisco Systems, Inc. All...
from .lenet import LeNet from .mnf_feed_forward import MNFFeedForward from .mnf_lenet import MNFLeNet
import os import inspect import importlib import torch import random import numpy as np import pandas as pd import tensorflow as tf import easyPheno.model def get_list_of_implemented_models() -> list: """ Create a list of all implemented models based on files existing in 'model' subdirectory of the repositor...
import itertools def containsAny(seq, aset): for item in itertools.ifilter(aset.__contains__, seq): return True return False
from im2mesh.onet.models import decoder from im2mesh.utils import visualize as vis from im2mesh.training import BaseTrainer import torch from torch import nn from torch.nn import functional as F from torch import distributions as dist from torch.optim import Adam from im2mesh.common import ( compute_iou, make_3d_g...
"""Decorator to disable runtime type-checking for a function.""" from typing import TYPE_CHECKING from typing import TypeVar if TYPE_CHECKING: # pragma: no cover F = TypeVar("F") def typeguard_ignore(f: F) -> F: """This decorator is a noop during static type-checking.""" return f else: ...
import os import pytest from falcon import testing path = os.path.abspath(__file__) dir_path = os.path.dirname(os.path.dirname(path)) os.chdir(dir_path) from api import api # noqa: E402 from lib.token import create_token # noqa: E402 @pytest.fixture() def client(): return testing.TestClient(api()) def test...
from rest_framework import routers from app import views router = routers.DefaultRouter() router.register(r'day-stats', views.DayStatsViewset, basename='day-stats')
from openpnm.algorithms import TransientReactiveTransport, AdvectionDiffusion from openpnm.utils import logging, Docorator, GenericSettings docstr = Docorator() logger = logging.getLogger(__name__) @docstr.dedent class TransientAdvectionDiffusionSettings(GenericSettings): r""" Parameters ---------- %(...
"""Example of Timer and Compare APIs: $ python -m examples.sparse.compare """ import pickle import sys import time import torch import torch.utils.benchmark as benchmark_utils class FauxTorch(object): """Emulate different versions of pytorch. In normal circumstances this would be done with multiple proces...
#!/usr/bin/python3 import os.path import sys import time import torch as tr import numpy as np import random as rn import torch.utils.data as dt from sklearn.metrics import precision_recall_curve, auc from src.fold_dataset import FoldDataset from src.model import mirDNN from src.parameters import ParameterParser from s...
import json data = input() consulta = input().replace(" ", '').upper() dictt = json.loads(data) consEx = "" contador = 0 for i in consulta: if i in dictt: consEx += i + " " contador += dictt.get(i) print(contador) print(consEx)
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-05-29 18:22 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove...
import tornado.httpserver import tornado.ioloop import tornado.web import tornado.websocket import tornado.gen from tornado.options import define, options import multiprocessing import serialworker import json define("port", default=8080, help="run on the given port", type=int) clients = [] input_queue = multiproces...
from tuyaha.devices.base import TuyaDevice # The minimum brightness value set in the API that does not turn off the light MIN_BRIGHTNESS = 10.3 # the default range used to return brightness BRIGHTNESS_STD_RANGE = (1, 255) # the default range used to set color temperature COLTEMP_SET_RANGE = (1000, 10000) # the defa...
# PurePNG setup.py # This is the setup.py script used by distutils. # You can install the png module into your Python distribution with: # python setup.py install # You can also do other standard distutil type things, but you can refer # to the distutil documentation for that. # This script is also imported as a modu...
# parse log files and generate an excel file import re import sys, getopt import pandas as pd import xlsxwriter rx_dict = { 'File': re.compile(r'File: (?P<file>.*) , Top Module: (?P<top_module>.*)'), 'Faults': re.compile(r'Found (?P<fault_sites>.*) fault sites in (?P<gates>.*) gates and (?P<ports>.*) ports.'...
"""Common configure functions for interface""" # Python import logging # Unicon from unicon.core.errors import SubCommandFailure # Steps from pyats.aetest.steps import Steps log = logging.getLogger(__name__) def configure_policy_map(device, policy_name, class_map_list ): """ Configures po...
import vcf import re import sys if (len(sys.argv)<2): sys.exit("[USAGE] python correct_ambiguous_bases.py in.vcf.gz out.vcf") infile=sys.argv[1] outfile=sys.argv[2] vcf_reader = vcf.Reader(filename=infile) vcf_writer = vcf.Writer(open(outfile, 'w'), vcf_reader) #number of ambiguous bases in the REF/ALT column n...
import json import os import time from typing import cast, Dict, Optional import boto3 from sebs.cache import Cache from sebs.faas.config import Config, Credentials, Resources from sebs.aws.function import LambdaFunction from sebs.utils import LoggingHandlers class AWSCredentials(Credentials): _access_key: st...
class User(object): """ User """ _id = None _first_name = None _last_name = None _email = None _uuid = None _password = None def __init__(self, id = "", first_name = "", last_name = "", email = "", uuid = "", password = ""): """ Constructor :param id: ...
from model.genre import Genre from schema.genre import GenreSchema class GenreService: @staticmethod def get_movie_genres_all() -> dict: return GenreSchema(many=True).dump( Genre.query.all() )
# -*- coding: utf-8 -*- # # Copyright 2019 SoloKeys Developers # # Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or # http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or # http://opensource.org/licenses/MIT>, at your option. This file may not be # copied, modified, or distribute...
# Copyright 2013 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 mimetypes import os from compiled_file_system import SingleFile from directory_zipper import DirectoryZipper from docs_server_utils import ToUnicode ...
import numpy as np from abc import ABCMeta, abstractmethod from scipy.spatial import KDTree class AbstractPopulationGenerator(object): __metaclass__ = ABCMeta def __init__(self, population_size, **kwargs): """Create a new population generator. :param population_size: the size of the populati...
#Importa biblioteca pandas import pandas as pd #Transforma a planilha em dados data = pd.read_excel("secoes_ibge.xlsx") #Realiza leitura das colunas e coloca o padrão lower data['Secção'] = data['Secção'].str.lower() data['Divisão'] = data['Divisão'].str.lower() #Realiza leitura das colunas e remove os acentos data[...
from flask import Flask app = Flask(__name__) cmdQueueFromUIToAlarm = None currentPlayState = None playlist = None from gui import views
import argparse, firebase_admin from firebase_admin import credentials from firebase_admin import firestore def init_firestore(project_name): cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred, { 'projectId': project_name, }) db = firestore.client() doc_ref = db.col...
from mpython import * import socket mywifi=wifi() # 创建wifi对象 mywifi.connectWiFi("ssid","password") # 连接网络 # 捕获异常,如果在"try" 代码块中意外中断,则停止关闭套接字 try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 创建UDP的套接字 s.setsockopt(socket.SOL_S...
# Generated by Django 3.2.4 on 2021-06-09 11:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('geo', '0005_auto_20210609_1027'), ] operations = [ migrations.CreateModel( ...
import collections from sigame_tools.filters import ( make_typed_field_filter ) def make_get_weight(args, types): filters = tuple(generate_field_filters(args=args, types=types)) if not filters: return lambda _: 1 weights = dict() def impl(value): result = weights.get(value) ...
# -*- encoding: utf-8 -*- # Check this # Author: Alex S. Garzão <alexgarzao@gmail.com> # mandrill_service.py import logging import mandrill class MandrillService: '''Class responsible in send emails using the mandrill service. ''' def __init__(self, config): self.logger = logging.getLogger(__nam...
# https://leetcode.com/problems/unique-number-of-occurrences/ """ Problem Description Given an array of integers arr, write a function that returns true if and only if the number of occurrences of each value in the array is unique. """ # Time Complexity Space Complexity # O(n) O(n) class Solution...
# -*- coding: utf-8 -*- # # Copyright 2016 Google LLC. 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 requir...
from pathlib import Path from seaborn import color_palette import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torchvision import models, transforms, utils import copy from utils import * from PIL import Image # load the original Alexnet model model = models.v...
''' This is the main script that : 1. Parses the client API request. 2. Queries and Fetches the data from IMDb. 3. Extracts and Parses the response into JSON format which is then relayed back to the client. ''' import requests from bs4 import BeautifulSoup import re def SearchApi(title,title_t...
""" In-memory session. This file is part of the everest project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Created on Jan 8, 2013. """ from collections import MutableSequence from collections import MutableSet from everest.constants import RELATION_OPERATIONS from everest.constants ...
""" Logging Utilities Written by Patrick Coady (pat-coady.github.io) """ import numpy as np import os import shutil import glob import csv class Logger(object): """ Simple training logger: saves to file and optionally prints to stdout """ def __init__(self, logname, now): """ Args: ...
#!/usr/bin/python3 """ Create a storage object from the selected storage engine """ from os import getenv storage_t = getenv('PERI_TYPE_STORAGE') if storage_t == "db": from models.engine.db_storage import DBStorage storage = DBStorage() else: from models.engine.file_storage import FileStorage storage ...
import json import os, sys sys.path.append(os.path.join(os.path.dirname(__file__), '../../')) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SMS_18.settings") import django django.setup() from main.models import Stock import time import random with open('day1.json') as jsonfile: dictionary=json.load(jsonfile) ...
from sonos.config import local_store ACTIVE_HOUSEHOLD_FILE = "household.json" def save_active_household(household): local_store.save(ACTIVE_HOUSEHOLD_FILE, household) def get_active_household(): return local_store.load(ACTIVE_HOUSEHOLD_FILE)
#Joseph Daly def dummy(scooby): if scooby == 1: print("shaggy") else: print("velma")
''' Created on 23 mars 2014 @author: guillaume ''' import os,sys from unittest import TestCase from tests.utils.utils import utils s = sys.path.append(utils().buildPath(os.getcwd())+"/vagrant/optraj.istic.univ-rennes1.fr/src/") from interfacebdd.SiteDAO import SiteDAO from system.Site import Site from system.Position...
''' Narrow phase ray- triangle intersection ''' import numpy as np from ..constants import tol from ..util import diagonal_dot def rays_triangles_id(triangles, rays, ray_candidates=None, return_any=False): ''' Intersect a set of rays and trian...
#!/usr/bin/env python # coding=utf8 from uuid import uuid4 as uuid import pytest pymongo = pytest.importorskip("pymongo") from basic_store import BasicStore from conftest import ExtendedKeyspaceTests from minimalkv._mixins import ExtendedKeyspaceMixin from minimalkv.db.mongo import MongoStore class TestMongoDB(B...
import logging from collections import deque from importlib import import_module from lakesuperior.dictionaries.namespaces import ns_collection as nsc ''' Constants used in messaging to identify an event type. ''' RES_CREATED = '_create_' RES_DELETED = '_delete_' RES_UPDATED = '_update_' ROOT_UID = '/' ROOT_RSRC_UR...
#!/usr/bin/python import obd from influxdb import InfluxDBClient obd.debug.console = True c = obd.OBD() r = c.query(obd.commands.RPM) print r.value def get_run_time(c): r = c.query(obd.commands.RUN_TIME) return r.value def get_engine_load(c): r = c.query(obd.commands.ENGINE_LOAD) return r.value ...
# import random # jogador = int(input('Digite um número entre 0 e 5: ')) # computador = random.randint(0, 5) # print('O número escolhido pelo computador foi {}'.format(computador)) # if jogador == computador: # print('Você venceu!') # else: # print('Você perdeu!') # O programa acima foi escrito por mim e está ...
from subprocess import run from os.path import join, exists from shutil import rmtree from invoke import task from faasmtools.env import ( USABLE_CPUS, THIRD_PARTY_DIR, PROJ_ROOT, ) from faasmtools.build import ( WASM_CC, WASM_AR, WASM_LIB_INSTALL, WASM_NM, WASM_SYSROOT, ) @task(de...
class Solution(object): def convert(self, s, numRows): """ :type s: str :type numRows: int :rtype: str """ ret = [[] for _ in xrange(numRows)] row, dir = 0, 1 for s_i in s: ret[row].append(s_i) row += dir if row < 0:...
# Made By @Its_eviralBoy Keep Credits If You Are Goanna Kang This Lol # And Thanks To The Creator Of Autopic This Script Was Made from Snippets From That Script # Usage .actressdp Im Not Responsible For Any Ban caused By This import asyncio import os import random import shutil from datetime import datetime from PIL...
import torch import torch.nn.functional as F from .divergences import jensen_shannon_div, symmetric_kl_div def mse_triplet_loss(anchor, positive, negative, margin=0.5): ''' Computes the MSE triplet loss between three batches. Args: anchor: Logits Tensor of dimension (batch x classes) posi...
import os from io import BytesIO from os.path import join, getsize from pathlib import PurePosixPath import cv2 import numpy as np from PIL import Image, ExifTags def reduce_pil_image(img): """ 压缩 PIL image对象, 返回一个PIL image对象 :param max_size: :param img: PIL image对象 :return: PIL image对象 """ ...
from .msgpack_rpc import MSGPackRPC __version__ = '1.0.1' __all__ = ['MSGPackRPC']
class Solution: def maxProfitAssignment(self, difficulty, profit, worker): """ :type difficulty: List[int] :type profit: List[int] :type worker: List[int] :rtype: int """ jobs = sorted([a, b] for a, b in zip(difficulty, profit)) res = i = maxp = 0 ...
class Solution: def addStrings(self, num1: str, num2: str) -> str: m, n = len(num1), len(num2) longer, shorter = list(num1), list(num2) if m < n: longer, shorter = shorter, longer m, n = n, m i, carry = 1, 0 while n - i >= 0: sum = ord(long...
def find_next_empty(puzzle): # return (row,col) (None,None) for r in range(9): for c in range(9): if puzzle[r][c] == -1: return r, c return None, None def is_valid(puzzle, guess, row, col): row_vals = puzzle[row] if guess in row_vals: return ...
import argparse from .sniffer import TLSHandshakeSniffer def parse_args(): parser = argparse.ArgumentParser(prog="pytlssniff") parser.add_argument("-d", '--debug', dest='debug', action='store_true', help="enable debug mode") parser.add_argument("-s", '--sni', dest='sni', action='s...
#!/usr/bin/env python #coding:utf-8 # Created: 21.03.2010 # Copyright (C) 2010, Manfred Moitzi # License: MIT License __author__ = "mozman <mozman@gmx.at>" try: # Python 2.6 and earlier need the unittest2 package # try: easy_install unittest2 # or download source from: http://pypi.python.org/pypi/unittest...
import os import settings if not os.path.exists(settings.STORAGE): print('STORAGE folder not found, Creating!') os.makedirs(settings.STORAGE) print('STORAGE folder Created at ' + settings.STORAGE)
import tempfile import numpy as np import pytest import time import zarr from pathlib import Path from itertools import product from swyft.store.store import DirectoryStore, MemoryStore from swyft.store.simulator import Simulator from swyft import Prior def model(params): p = np.linspace(-1, 1, 10) a, b = par...