content
stringlengths
5
1.05M
# problem name: Minimum Absolute Sum Difference # problem link: https://leetcode.com/contest/weekly-contest-235/problems/minimum-absolute-sum-difference/ # contest link: https://leetcode.com/contest/weekly-contest-235/ # time: (?) # author: reyad # other_tags: sorting # difficulty_level: beginner class Solution: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 19 18:09:17 2019. @author: mtageld """ import numpy as np from histomicstk.utils import ( convert_image_to_matrix, convert_matrix_to_image) from histomicstk.preprocessing.color_conversion import ( rgb_to_sda, sda_to_rgb) from histomicstk.pre...
# -*- coding: utf-8 -*- a = 1 def getA(): return a def modA(input_v): global a a = input_v
import numpy as np # Load matlab's file import scipy.io # Build-in K-means clustering model of sklearn lib from sklearn.cluster import KMeans from findClosestCentroids import find_closest_centroid from computeCentroidMean import compute_centroid_mean from KmeansAlgo import kmeans_algo ############### (1) Find...
import os import dask.dataframe as dd from utils.config import Config, mappings from utils.es_wrapper import ElasticWrapper def get_docs_json(index, docs_df): for _, row in docs_df.iterrows(): yield { "_index": index, "_id": row[Config.DOCID_KEY], "_source": { ...
def do_mul: a=2 b=4 print(a*b) do_mul() #aaa
"Placing Callbacks on Queues" ''' Luckily, queues support much more than just strings—any type of Python object can be placed on a queue. Perhaps the most general of these is a callable object: by placing a function or other callable object on the queue, a producer thread can tell the GUI how to handle the message in a...
# -*- coding: utf-8 -*- thislist = ["apple", "banana", "cherry"] thislist.insert(1, "orange") print(thislist)
from torch import nn import torch.nn.functional as F class BasicNet(nn.Module): def __init__(self): super(BasicNet, self).__init__() self.fc1 = nn.Linear(784, 128) self.fc2 = nn.Linear(128, 64) self.fc3 = nn.Linear(64, 10) def forward(self, x): x = F.relu(self.fc1(x)) ...
import unittest import numpy as np import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from config import OptimizationConfigEuRoC from utils import to_quaternion, to_rotation, Isometry3d from feature import Feature from msckf import CAMState class TestFeature(unittest....
def get_arg_types(pred:str): move_list=["north","south","east","west","northwest","northeast","southeast","southwest"] if pred in move_list or pred == 'get': return ['cell'] elif pred == 'cell': return ['cell'] elif pred == 'deepwater': return ['cell'] elif pred == 'at' or pr...
import pymysql import settings from dao.DAOUsuario import DAOUsuario class DAOCart: def connect(self): host = settings.MYSQL_HOST user = settings.MYSQL_USER password = settings.MYSQL_PASSWORD db = settings.MYSQL_DB return pymysql.connect(host, user, password, db) def ...
# lightning imports from pytorch_lightning import LightningModule, LightningDataModule, Callback, Trainer from pytorch_lightning.loggers import LightningLoggerBase from pytorch_lightning import seed_everything # hydra imports from omegaconf import DictConfig from hydra.utils import log import hydra # normal imports f...
import pickle import os import sys import numpy as np import pc_util import scene_util class ScannetDataset(): def __init__(self, root, npoints=8192, split='train'): self.npoints = npoints self.root = root self.split = split self.data_filename = os.path.join(self.root, 'scannet_%s.p...
from PIL import Image import os import argparse def rescale_images(directory): for img in os.listdir(directory): im = Image.open(directory+img) im_resized = im.resize((800,600), Image.ANTIALIAS) im_resized.save(directory+img) rescale_images("test/")
# -*- coding: utf-8 -*- """ Category model for Product Catalog """ from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from mptt.managers import TreeManager from mptt.models import MPTTModel from mptt.models import TreeFore...
# Slixmpp: The Slick XMPP Library # Copyright (C) 2010 Nathanael C. Fritz, Lance J.T. Stout # This file is part of Slixmpp. # See the file LICENSE for copying permission. from slixmpp.plugins.base import register_plugin from slixmpp.plugins.xep_0092 import stanza from slixmpp.plugins.xep_0092.stanza import Version fr...
from typing import Any # Common properties which can be used at any schema class CommonProperties: def __init__(self, title: str, description: str, type: str, nullable: bool, deprecated: bool, readonly: bool): self.title = title self.description = description self.type = type self.n...
import math from random import randint from numerus import is_numeric from omnicanvas import Canvas, colors from .series import Series, LineSeries, ScatterSeries class Chart: """The base class for all charts. It controls the attributes common to all charts - namely dimensions and title. :param str title: ...
CELERY_RESULT_BACKEND = "django-db"
"""DEPRECATED 2014-03-01 by cam. This csv stuff is now all done through compute engine. I'll leave this file around in case we want to know how to interact with cloud storage from app engine in the future. Note 2013-04-11 by ajb: Adding a delete file classmethod. This will be used to clean out our backup buckets wit...
from unittest import TestCase import PyObjectTree class TestNode(TestCase): def test_Node(self): pass
from sympy.multipledispatch import dispatch, Dispatcher from sympy.core import Basic, Expr, Function, Add, Mul, Pow, Dummy, Integer from sympy import Min, Max, Set, sympify, Lambda, symbols, exp, log, S from sympy.core.numbers import Infinity, NegativeInfinity from sympy.sets import (imageset, Interval, FiniteSet, Unio...
BASE_URL = "https://www.duolingo.com/stories"
from gui import * class MainFrame(MyFrame): def __init__(self,master): super().__init__(master) self.panel1 = MyPanel(self) self.panel2 = MyPanel(self,orient=tk.HORIZONTAL) self.panel3 = MyPanel(self,orient=tk.HORIZONTAL) self.label1 = MyLabel(self,"Word Similarity Checker...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/DataRequirement) on 2020-02-03. # 2020, SMART Health IT. import sys from dataclasses import dataclass, field from typing import ClassVar, Optional, List from .codeableconcept import Codeabl...
null = "null" # from BlueTest.logInit import * import BlueTest,time,random,asyncio def test(): with open(".//srcdata//test.json.postman_collection","w") as file: a = { "id": "3560d742-c3da-4ad7-32c1-222", "name": "test", "requests": [ { ...
# Write your solution here: class Person: def __init__(self, name: str): self.name = name def return_first_name(self): first_name = self.name.split(" ")[0] return first_name def return_last_name(self): last_name = self.name.split(" ")[1] return last_name...
import requests from bs4 import BeautifulSoup # Hardcode URL for testing purposes, will integrate input later url = "" # needs to be verified as valid URL try: # downloading HTML page target = requests.get(url) # initializing bs4 object soup = BeautifulSoup(target.content, 'html.pa...
#!/usr/bin/env python3 import sys import ipaddress for line in sys.stdin: line = line.rstrip("\r\n") if not line: break ip = ipaddress.IPv6Address(line) print(ip.reverse_pointer + ".\tPTR")
#!/usr/bin/python # -*- coding: utf-8 -*- """ PyCOMPSs Testbench ======================== """ # Imports from pycompss.api.task import task from pycompss.api.binary import binary @binary(binary="date") @task() def myDate(dprefix, param): pass def main(): from pycompss.api.api import compss_barrier myD...
# Copyright 2017-2021 object_database 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 applicable ...
import ipyvuetify as v import pandas as pd from ipywidgets import Output from matplotlib import pyplot as plt from component import parameter as cp class LayerFull(v.Layout): COLORS = cp.gradient(5) + ["grey"] def __init__(self, layer_name, values, aoi_names, colors): # read the layer list and fin...
import numpy as np import torch import torch.nn as nn from diff_models import diff_CSDI class CSDI_base(nn.Module): def __init__(self, target_dim, config, device): super().__init__() self.device = device self.target_dim = target_dim self.emb_time_dim = config["model"]["timeemb"] ...
import random try: from urlparse import urlsplit except ImportError: # try python3 then from urllib.parse import urlsplit class HostIterator(object): """An iterator that returns selected hosts in order. A host is guaranteed to not be selected twice unless there is only one host in the collec...
from random import randint matriz = [] cartela = [] cont = contador = 0 cont_cartela = 0 cont_cartela2 = 5 while contador < 5: num = randint(0, 100) if num not in cartela: cartela.append(num) cont = cont + 1 if cont == 5: if contador == 1: cont_cartela = 5 if cont...
class Stock_IEX: def __init__(self,key): self.key = key import requests import json from pandas.io.json import json_normalize import pandas as pd import numpy as np def get_quote(self,ticker,range = 'YTD'): """ Returns the historic daily stock prices for one ticker ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygame, sys, random, time from pygame.locals import * pygame.init() DISPLAYSURF = pygame.display.set_mode((960, 720)) pygame.display.set_caption('快乐小鸡') WHITE = (0, 0, 255) DISPLAYSURF.fill(WHITE) backdrop = pygame.image.load('images/backdrop.png') chickens = [p...
"""Main entry point.""" import json import random import sys from .culture import Culture def main(culture_key, gender=None): cultures = _get_cultures() chosen_culture = None for culture in cultures: if culture.key == culture_key: chosen_culture = culture print(chosen_culture.get...
from pymtl import * from lizard.util.rtl.interface import Interface, UseInterface from lizard.util.rtl.method import MethodSpec from lizard.util.rtl.types import canonicalize_type from lizard.util.rtl.case_mux import CaseMuxInterface, CaseMux class LookupTableInterface(Interface): def __init__(s, in_type, out_type...
from __future__ import absolute_import import functools import logging import time from datetime import timedelta from hashlib import md5 from django.db.models import Q from django.utils import timezone from sentry import options, quotas from sentry.api.event_search import convert_search_filter_to_snuba_query, Inval...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Service to monitor a set of OPC UA nodes and send commands to a socket service upon node value changes and, conversely, change node values upon socket responses. The service parameters are defined in a YAML file. """ import argparse import logging import yaml import co...
import re import json import math import time import datetime from explorer.views import homepage from explorer.settings import LOGGING import logging #from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED, FIRST_COMPLETED logging.config.dictConfig(LOGGING) logger = logging.getLogger('django.reques...
""" Quaternion - defined as (x, y, z, w) to be compatible with ROS and RealSense ROS: http://wiki.ros.org/tf2/Tutorials/Quaternions ROS uses quaternions to track and apply rotations. A quaternion has 4 components (x,y,z,w). That's right, 'w' is last (but beware: some libraries like Eigen put w as the first nu...
from bfio import BioReader, BioWriter import bioformats import javabridge as jutil import logging, traceback from pathlib import Path import os import cv2 import numpy as np logging.basicConfig(format='%(asctime)s - %(name)-8s - %(levelname)-8s - %(message)s', datefmt='%d-%b-%y %H:%M:%S') lo...
#!/usr/bin/env python3 # -*- coding: utf-8; py-indent-offset:4 -*- import sys import os import io import socket import logging import numpy as np import pandas as pd import datetime as dt import argparse from influxdb import DataFrameClient as dfclient from influxdb.exceptions import InfluxDBClientError class IQFeed...
# Generated by Django 3.1.4 on 2021-10-26 17:44 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0022_auto_20211026_2254'), ] operations = [ migrations.AlterField( model_name='addroom', ...
from rest_framework.views import APIView from rest_framework.response import Response class SimpleAPI(APIView): def get(self, request, format=None): return Response('hidden')
from compas.geometry import add_vectors from compas.geometry import cross_vectors from compas.geometry import normalize_vector from compas.geometry import scale_vector from compas.geometry import subtract_vectors from numpy import array from numpy import cos from numpy import cross from numpy import hstack f...
from __future__ import unicode_literals import frappe import erpnext from frappe import auth import random import datetime import json, ast from erpnext.accounts.utils import get_balance_on from frappe.utils import (flt, getdate, get_url, now, nowtime, get_time, today, get_datetime, add_days) ...
import numpy as np from subriemannian_qc.matrix_util import conj_transpose ''' Input validation utility functions. ''' def is_matrix(a: np.ndarray) -> bool: return len(a.shape) == 2 and a.shape[0] == a.shape[1] # Not very efficient, but gets the job done def is_unitary_matrix(a: np.ndarray) -> bool: if not...
#Non-Boolean and operator print(10 and 5) # --A1 print(0 and 12) # -- A2 print(13 and 0) # --A3 print(12 and 'python') # --A4
from stanza.research.metrics import * # TODO: define new metrics METRICS = { name: globals()[name] for name in dir() if (name not in ['np'] and not name.startswith('_')) }
from __future__ import absolute_import, print_function, division, unicode_literals import unittest import numpy as np from sklearn.datasets import load_iris, load_breast_cancer, load_boston from sklearn.linear_model import LogisticRegression, LinearRegression from sklearn.model_selection import cross_val_predict from x...
from __future__ import absolute_import, division, print_function import json import datasets _CITATION = """\ """ _DESCRIPTION = """\ """ _TRAIN_DOWNLOAD_URL = f"data/covid_info/train.json" _VAL_DOWNLOAD_URL = f"data/covid_info/val.json" class CovidDataConfig(datasets.BuilderConfig): def __init__( ...
#!/usr/bin/env python """ This script accepts Kraken/Kaiju output and a file listing all taxids, and gives a .csv file with taxid statistics """ __author__ = "Paul Donovan" __maintainer__ = "Paul Donovan" __email__ = "pauldonovandonegal@gmail.com" import sys from ete3 import NCBITaxa import argparse #Display help a...
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import tensorflow as tf from typing import Type def add_l2_regularization(optimizer_class: Type[tf.keras.optimizers.Optimizer], l2_regularization: float) -> Type[tf.keras.optimizers.Optimizer]: class L2Regularizer(optimizer_class...
import unittest from pychess.element.piecer import generate_pieces, Piece, get_piece_row_place from pychess import constant as c class TestPiecer(unittest.TestCase): def test_sort_pieces(self): import itertools pieces = sorted([ Piece(pd[0], pd[1]) for pd in itertools.pr...
# Author: Andreas Putz # Copyright (c) 2013, PythonFCST # License: TBD. r""" **************************************************************** :mod:`PythonFCST.mesh`: Mesh Generation Classes for PythonFCST **************************************************************** .. module:: PythonFCST.mesh Contents -------- Th...
import FWCore.ParameterSet.Config as cms HCALHighEnergyFilter = cms.EDFilter("HCALHighEnergyFilter", JetTag = cms.InputTag("iterativeCone5CaloJets"), JetThreshold = cms.double(20), EtaCut = cms.double(3.0) # ...
import json import os from copy import deepcopy from main import main, parse_args from utils import get_stats def load_config(path="./grid_search_config.json"): with open(path, "r") as f: return json.load(f) def run_experiments(args): res = [] for i in range(args.num_trials): print("Trial ...
#!/usr/bin/env python import click import os import codecs import shutil from bs4 import UnicodeDammit from functools import partial from multiprocessing import Pool from nlppln.utils import create_dirs, get_files, out_file_name def check_file(in_file, convert, out_dir): fo = out_file_name(out_dir, in_file) ...
from django.urls import reverse from django.views import generic as views from testing_demos.web.models import Profile class ProfileCreateView(views.CreateView): model = Profile fields = '__all__' template_name = 'profiles/create.html' def get_success_url(self): return reverse('details profi...
from django.db import models from customer.models import Customer, Department from engineer.models import Area, Engineer from django.utils import timezone from datetime import datetime, timedelta from django.db.transaction import atomic # Create your models here. #print(datetime.now()+datetime) speed_choices=((20,20),(...
# 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...
suitable_locations = land_use_residential * (dem_gent > 10) * (1 - roads_buffer_arr)
from abc import ABC, abstractmethod, abstractproperty from pytz import timezone class EngageScraper(ABC): def __init__(self, tz_string): super().__init__() self._agenda_locations = [] self._tz = timezone(tz_string) @property def agenda_locations(self): return self._agenda_l...
import numpy as np def target_transform(y: np.array, increment: float=0.01) -> np.array: """ Transform non-negative array to R using np.log :param y: np.array :param increment: float :return: """ return np.log(y + increment) def target_inverse_transform(y_trn: np.array, increment: float=...
from os.path import abspath, dirname, join from setuptools import find_packages, setup basedir = abspath(dirname(__file__)) with open(join(basedir, "README.md"), encoding="utf-8") as f: README = f.read() with open(join(basedir, "fimed", "__init__.py"), "r") as f: version_marker = "__version__ = " for li...
import os import sys import re from pathlib import Path from paraview.simple import * PATH = Path(os.getenv('HOME')) / "SPHinXsys-build"/"tests"/"user_examples"/"2d_boulder_on_slop" if sys.platform.startswith('linux'): PATH = str(PATH) + "/bin/output/" else: PATH = str(PATH) + "\\src\\output\\" ...
from colorama import init from colorama import Fore, Back, Style from menu import menu_one, menu_two, menu_three, menu_four def show_menu(): '''Display menu on terminal''' print('='*30) print('=' + ' '*12 + 'menu' + ' '*12 + '=') print('='*30) print('1. Add new record') print('2. Sh...
#!/usr/bin/env python2 # Win32 named pipe helper from __future__ import absolute_import __all__ = ["Win32Pipe"] import sys import ctypes import logging import random from ctypes import POINTER as PTR from ctypes.wintypes import (BOOL, DWORD, HANDLE, LPCWSTR, LPVOID, LPCVOID) class OVERLAPPED(ctypes.Structure): c...
#!/usr/bin/env python import argparse import os import requests import json import urllib.parse import m3u8 from pathlib import Path import re import ffmpeg import shutil class TwitterDownloader: video_player_prefix = 'https://twitter.com/i/videos/tweet/' video_api = 'https://api.twitter.com...
import os import shutil import unittest import torch import torchvision import torch.nn as nn from neural_compressor.data import DATASETS from neural_compressor.experimental.data.dataloaders.pytorch_dataloader import PyTorchDataLoader def build_fake_yaml(): fake_yaml = """ model: name: imagenet_prune ...
# Downstream: bikeshare prediction with latent representation # The model consists of a 3d cnn network that uses # historical ST data to predict next hour bike demand # as well as taking a latent feature map trained from # an autoencoder that includes multiple urban features # Treat latent representation as ordinary 3...
import os head = input("Enter beginning of file to be trimmed: ") tail = input("Enter end of file to be trimmed (Do not include file etension) : ") ext = input("Enter the file extension (.exe, .avi, .jpg, etc...): ") if ext == "": ext = ".txt" if "." not in ext: ext = "." + ext for filename in os.lis...
# A simple two state example, but with several separate decay rates and starting values, which are fitted individually import StateModeling as stm import numpy as np NumMolecules = 16 M = stm.Model() # creates a new Model instance M.addAxis("Different Molecules", NumMolecules) sigma = 0.2 true_I0 = 1200 * np.random....
Second Largest Value among N integers The program must accept N integers and print the second largest value among the N integers. Input Format: The first line denotes the value of N. Next N lines will contain the N integer values. Output Format: The first line contains the second largest integer. Boundary Conditions: ...
"""Script to plot 3-body ground state energies for the SRG run.""" import glob import json import matplotlib import matplotlib.pyplot as plt # matplotlib font configurations matplotlib.rcParams["text.latex.preamble"] = [ # i need upright \micro symbols, but you need... r"\usepackage{siunitx}", # ...this t...
import sys sys.path.append('../Nets/') from glob import glob from os.path import join from multiprocessing import Pool from scipy.ndimage.interpolation import rotate from keras.callbacks import ModelCheckpoint from tqdm import tqdm from functools import partial from Nodule import * from numpy import * PATH = { 'D...
"""Module for raceplan adapter.""" import logging from typing import Any, List, Optional class RaceplansAdapter: """Class representing an adapter for raceplans.""" @classmethod async def get_all_raceplans(cls: Any, db: Any) -> List[dict]: # pragma: no cover """Get all raceplans function.""" ...
#!/usr/bin/env python # Step 1 - Get a list of your Webex Teams Rooms with the token import requests, os from pprint import pprint token = os.getenv('WEBEX_TOKEN') headers = {'Content-Type':'application/json','Authorization':f'Bearer {token}'} get_url = 'https://webexapis.com/v1/rooms' get_response = requests.get(get_...
import time from pathlib import Path import superannotate as sa from .common import upload_project PROJECT_NAME1 = "test_get_exports1" PROJECT_FOLDER = Path("tests") / "sample_project_vector" def test_get_exports(tmpdir): tmpdir = Path(tmpdir) project = upload_project( PROJECT_FOLDER, PROJE...
__version__ = '3.15.0dev'
from abc import ABC, abstractmethod from dataclasses import dataclass from math import radians, sin, cos from math import pi as π from typing import Tuple, Union from numba import njit import numpy as np from zodipy._functions import interplanetary_temperature, blackbody_emission @dataclass class Component(ABC): ...
# -*- coding: utf-8 -*- """ Created on Thu Oct 22 15:58:28 2020 @author: Andrea """ import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import os import conda conda_file_dir = conda.__file__ conda_dir = conda_file_dir.split('lib')[0] proj_lib = os.path.join(os.path.join(conda_d...
from collections import OrderedDict import torch from torch import nn from torch.nn import functional as F class _SimpleSegmentationModel(nn.Module): __constants__ = ["aux_classifier"] def __init__(self, backbone, classifier, aux_classifier=None): super(_SimpleSegmentationModel, self).__init__() ...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import requests import aiohttp import asyncio import datetime import json from os import getenv from urllib.parse import urlparse, urlunparse from urllib3.util import Retry class DistributedApiTaskManager: def __init__(se...
import csv input_path = "../resources/normalization/resources/rawdata/CL_20210810.csv" output_path = "../resources/normalization/resources/dictionary/best_dict_CellType_20210810.txt" cui2names = {} with open(input_path) as f: rdr = csv.reader(f) for line in rdr: class_id = line[0] # only consi...
from network import * from PIL import Image import scipy.misc as misc import os class DnCNN: def __init__(self): self.clean_img = tf.placeholder(tf.float32, [None, None, None, IMG_C]) self.noised_img = tf.placeholder(tf.float32, [None, None, None, IMG_C]) self.train_phase = tf.pl...
def lex(): return raw_input().split() def input_set(size): a = map(int, lex()) assert len(a) == int(size) return set(a) def input_query(): cmd, size = lex() return cmd.strip(), input_set(size) s = input_set(raw_input()) for i in xrange(0, int(raw_input())): cmd, t = input_query() if ...
import torch import torchvision import torch.nn as nn import torch.nn.functional as F import math class Memory: def __init__(self): self.actions = [] self.states = [] self.logprobs = [] self.rewards = [] self.is_terminals = [] self.hidden = [] d...
import pytest import kleat.misc.settings as S from kleat.misc.calc_genome_offset import calc_genome_offset @pytest.mark.parametrize("ctg_clv, tail_side, skip_check_size, expected_gnm_offset", [ # [1, 'left', 0, 1], # [1, 'right', 0, 1], # [2, 'left', 0, 3], # [2, 'right', 0, 3], [1, 'left', 1...
# -*- coding: utf-8 -*- from flask import Flask, request, render_template from gevent.pywsgi import WSGIServer import numpy as np import re import requests import os app = Flask(__name__) def check(output): url = "https://image-to-text2.p.rapidapi.com/cloudVision/imageToText" querystrin...
import queue import numpy as np from scipy import optimize as op import matplotlib.pyplot as plt import sys import random import math MACHINE = 5 PER_GPU = 2 DBL_MIN = float('-Infinity') JOB_TIME = 5 COM_TIME = 0 READ_INF = 0 PTA = 10 # real # trace = [8, 8, 4, 16, 8, 16, 8, 4, 4, 4, 4, 16, 4, 4, 8, 8, 4, 4, 2, 2, 4,...
from adobject import * from pyadexceptions import InvalidObjectException, invalidResults import aduser, adcomputer, addomain, addomain, adgroup, adobject, pyadconstants, adcontainer def from_cn(common_name, search_base=None, options={}): try: q = ADObject.from_cn(common_name, search_base, options) ...
# 3.1.1.5 n = int(input('Input for n greater or equal to 100: ')) print(n >= 100) # 3.1.1.9 n1 = int(input('Enter the first number: ')) n2 = int(input('Enter the second number: ')) n3 = int(input('Enter the third number: ')) if n1 > n2 and n1 > n3: largest = n1 elif n2 > n1 and n2 > n3: largest = n2 elif n3 > ...
import numpy as np import matplotlib.pyplot as plt class NSG: def __init__(self, epsilon, alpha, delta, tasks, arms): self.epsilon = epsilon self.alpha = alpha self.beta = 1 self.delta = delta self.n = tasks self.k = arms self.Q = [([0]*self.k) for i in rang...
from string import digits, ascii_lowercase, ascii_uppercase from random import choice as rand_choice from secrets import choice as sec_choice def slug_generator(size: int = 10, char: str = digits + ascii_uppercase + ascii_lowercase) -> str: return "".join(rand_choice(char) for _ in range(size)) def otp_generato...
#!/usr/bin/env python3 from aws_cdk import core from {{cookiecutter.alexa_skill_name_slug}}_cdk.cdk_stack import AlexaCdkStack as CdkStack app = core.App() CdkStack( app, "{{cookiecutter.alexa_skill_cdk_stack_name}}", stack_name = "{{cookiecutter.alexa_skill_cdk_stack_name}}", description = "Lambda ...