content
stringlengths
5
1.05M
import pandas as pd from Models import User from Models import Results from files_lib import SHA256, file_to_dict from main import db, Submission def add_test_flag(): r = Results(subject_type='Forensic', task='Zad1', flag=SHA256('CTF')) db.session.add(r) r = Results(subject...
from nltk.tokenize import word_tokenize import numpy as np class windowed_data(): def __init__(self, sentences, labels, wlen, batchsize, encoder): self.sentences = sentences self.labels = labels self.wlen = wlen self.batchsize = batchsize self.encoder = encoder aut...
# import libraries from math import pi, sin import matplotlib.pyplot as plt from openmdao.core.component import Component class TubeCost(Component): def __init__(self): super(TubeCost, self).__init__() self.add_param('cmt', 1.2, desc='cost of materials', units='1/kg') self.add_param('cshi...
from dataclasses import dataclass, field from typing import Optional from bindings.gmd.character_string_property_type import CharacterStringPropertyType from bindings.gmd.md_classification_code_property_type import ( MdClassificationCodePropertyType, ) from bindings.gmd.md_constraints_type import MdConstraintsType ...
import json # Create your models here. class TrafficReport(object): """A representation of a traffic report from http://www.internettrafficreport.com/details.htm as a python object. Generically, speaking, it is a immutable wrapper around a list that only supports ReportEntry instances. """ def __...
import mock from django.contrib import admin from django.urls import reverse from cms.models import PageContent from cms.models.fields import PlaceholderRelationField from djangocms_versioning import versionables from djangocms_versioning.admin import VersionAdmin from djangocms_versioning.constants import DRAFT, PU...
import os.path import tensorflow as tf import helper import warnings from distutils.version import LooseVersion import project_tests as tests # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'),\ 'Please use TensorFlow version 1.0 or newer. You are using {}'.format( tf._...
# puzzle8a.py def main(): instrs = read_file() for i in range(len(instrs)): instrs = read_file() # Swap the "jmp" and "nop" operations for # each of the possibilities until we find # a case where an instruction is not re-executed. if instrs[i]["oper"] in ["jmp", "nop"]: ...
import unittest import src.OptimalControl.DynamicProgramming.VectorCubicSpline as cubic import numpy as np from numpy.linalg import norm class MyTestCase(unittest.TestCase): def spline_test(self, point, a0, a1, a2, a3): spline = cubic.VectorCubicSpline(a0, a1, a2, a3) points_on_spline = [] ...
import glob import os sources = glob.glob("src/*.asm") out_dir = os.getcwd() + "/bin/" if not os.path.isdir(out_dir): os.mkdir(out_dir) for src in sources: name = os.path.splitext(os.path.basename(src))[0] out = out_dir + name o = out + ".o" asm = "as -o " + o + " " + src lnk = "gcc -o " + o...
from setuptools import setup from ptulsconv import __author__, __license__, __version__ with open("README.md", "r") as fh: long_description = fh.read() setup(name='ptulsconv', version=__version__, author=__author__, description='Parse and convert Pro Tools text exports', long_description_...
class Stack(list): """docstring for Stack""" def __init__(self, n): super(Stack, self).__init__() self.n = n init_list = [0]*n self.extend(init_list) self.top = 0 def stack_empty(self): if self.top == 0: return True else: return False def push(self, x): self.top += 1 self[self.top] = x d...
from typing import Any, List, Literal, TypedDict from .FHIR_code import FHIR_code from .FHIR_dateTime import FHIR_dateTime from .FHIR_decimal import FHIR_decimal from .FHIR_Element import FHIR_Element from .FHIR_id import FHIR_id from .FHIR_Identifier import FHIR_Identifier from .FHIR_Meta import FHIR_Meta from .FHIR_...
from django.db import models from tests.example import managers as app_managers from tests.example import querysets as app_queryset class AfterSaveExampleModel(models.Model): objects = app_managers.AfterSaveExampleModelManager.from_queryset( app_queryset.AfterSaveExampleModelQuerySet )() test_te...
from __future__ import absolute_import import json import os.path from ocr4all.colors import ColorMap from pkg_resources import resource_string import numpy as np from ocr4all_pixel_classifier.lib.pc_segmentation import RectSegment from ocrd import Processor from ocrd_modelfactory import page_from_file from ocrd_mod...
#declaretion Data=[];data1=[];data2=[];x_val=[];y_val=[] data1.append("x") data2.append("y") #implementation import numpy,tabulate,matplotlib.pyplot as plt def f(x): return eval(eq) eq = input('Equation: ') n = int(input("Number of output: ")) x = numpy.zeros(n) y = numpy.zeros(n) ul = float(input...
# Import required modules import os import time # Import custom modules import file import solidity import geth import crypto import input # Definition for a ballot class Ballot: def __init__(self, title, address): # The local title of the ballot self.title = title # Address where the ba...
#!/usr/bin/env python # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to us...
# Generated by Django 3.0.8 on 2021-07-20 14:17 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0002_auto_20210720_1103'), ] operations = [ migrations.AlterField( model_name='profile', name='food_order_d...
""" Created on Oct 25, 2017 @author: Jafar Taghiyar (jtaghiyar@bccrc.ca) """ from django.conf.urls import url from . import views app_name = 'bulk' urlpatterns = [ url(r'^$', views.home_view, name='home'), url(r'^sample/(?P<pk>\d+)$', views.sample_detail, name='sample_detail'), url(r'^sample/list$', views.sample_lis...
from pyleap import * rect = Rectangle(100, 100, 200, 50, "green") rect2 = Rectangle(100, 100, 200, 50, "green") circle = Circle(200, 200, 50, "green") p = Point(point_size=10, color="red") circle.transform.scale_x = 2 # rect.transform.set_anchor_rate(1, 1) def draw(dt): window.clear() window.show_axis() ...
from setuptools import setup, find_packages import pathlib here = pathlib.Path(__file__).parent.resolve() # Get the long description from the README file long_description = (here / "README.md").read_text(encoding="utf-8") setup( # This is the name of your project. The first time you publish this # package, t...
#!/usr/bin/env python from __future__ import absolute_import, division, print_function import glob import os import shlex import subprocess import sys from multiprocessing.dummy import Pool ARGS = ['-O3', '-DNDEBUG', '-DKENLM_MAX_ORDER=6', '-std=c++11', '-Wno-unused-local-typedef', '-Wno-sign-compare'] INCL...
vault_operation = [ "update", "read", "delete" ] vault_attackers = [ "200.174.194.100", "200.174.194.101", "200.174.194.102", "200.174.194.103", "200.174.194.104" ] vault_benign = [ "", "", "", "" ] # the user that tried to login vault_benign_user = [ "auth/userpas...
SELIA_VISUALIZERS_APPS = [ 'selia_visualizers', ]
''' Created on 23.08.2017 @author: falensaa ''' import pickle import numpy as np import dynet import imsnpars.nparser.features from imsnpars.tools import utils, neural from imsnpars.nparser.graph import features as gfeatures class LblTagDict(object): def __init__(self): self.__lbl2Id = { } self...
# (c) @AbirHasan2005 import aiohttp import asyncio import datetime from pyrogram import Client from pyrogram.types import Message from core.send_msg import SendMessage, EditMessage MessagesDB = {} async def GetData(date: str): async with aiohttp.ClientSession() as session: async with session.get(f"https...
"""Maintain db function match_individual_name here.""" from alembic_utils.pg_function import PGFunction match_individual_name = PGFunction( schema="public", signature="match_individual_name(lastname IN VARCHAR, firstname IN VARCHAR)", definition=""" RETURNS int[] LANGUAGE plpgsql AS $$ ...
"""Module to deal with storing data files on disk.""" from __future__ import absolute_import import os def _root(): """Returns the directory at which all other persisted files are rooted. """ default_root = os.path.expanduser('~/gutenberg_data') return os.environ.get('GUTENBERG_DATA', default_root)...
# -*- coding: utf-8 -*- from split_settings.tools import include # Includes all python files without scope: include('*.py')
import os import torch import torchvision from google_drive_downloader import GoogleDriveDownloader as gd DIR = os.path.abspath(os.path.dirname(__file__)) def get_pretrained_model(model_type): model = eval("{}".format(model_type)) return model().get_model() class VGG16(): def __init__(self, pretrained=Tr...
from math import log2, floor,sqrt from torch import nn, cat, add, Tensor from torch.nn import init, Upsample, Conv2d, ReLU, AvgPool2d, BatchNorm2d from torch.nn.functional import interpolate class Residual_Block(nn.Module): def __init__(self): super(Residual_Block, self).__init__() self.conv1 = n...
# (c) Copyright [2016] Hewlett Packard Enterprise Development LP # # 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 r...
# -*- coding: utf-8 -*- # SPDX-License-Identifier: MIT """Generic resolver functions.""" from __future__ import absolute_import from abc import ABCMeta, abstractmethod import six from module_build_service.common.config import conf, SUPPORTED_RESOLVERS class GenericResolver(six.with_metaclass(ABCMeta)): """ ...
#!/usr/bin/env python3 # # Copyright 2021 Graviti. Licensed under MIT License. # from .. import LabelType class TestLabelType: def test_init(self): assert LabelType.CLASSIFICATION == LabelType("classification") assert LabelType.BOX2D == LabelType("box2d") assert LabelType.BOX3D == LabelTy...
from pymsbuild import * from pymsbuild.dllpack import * PACKAGE = DllPackage( "testdllpack", PyFile("__init__.py"), PyFile("mod1.py"), File("data.txt"), Package("sub", PyFile("__init__.py"), PyFile("mod2.py"), File("data.txt"), ), CSourceFile("extra.c"), CFunctio...
""" Tradfri wrapper for Onaeri API https://github.com/Lakitna/Onaeri-tradfri """ __version__ = '0.8.0' import sys import os import traceback import atexit from time import sleep, strftime from Onaeri.logger import log from Onaeri import Onaeri, settings, __version__ as onaeriVersion import control import lampdata on...
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import status from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.parsers import FormParser, MultiPartParser, JSONParser, FileUploadParser from rest_framework.permissions import IsAuthenticatedOrReadOnly fr...
from django.conf.urls import url from valentina.app.views import (welcome, chat, profile, facebook, report, create_affiliation, list_affiliations, chat_preferences, logout) urlpatterns = [ url(r'^$', welcome, name='welcome'), url(r'^chat/prefere...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest from pyisaf.validators import ( decimal, max_int_digits, max_length, min_length, non_negative, ) class TestValidators(unittest.TestCase): def test_decimal_total_digits_3_with_four_digits_returns_False(self): ...
import os import cv2 import numpy as np import tensorflow as tf import time os.environ["CUDA_VISIBLE_DEVICES"] = "0" gpus = tf.config.list_physical_devices('GPU') print("Devices: ", gpus) for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, False) img = cv2.imread("imgs/test-img.jpeg") img = cv2.cvtCo...
import platform from pathlib import Path import numpy as np import torch from spconv.pytorch import ops from spconv.pytorch.conv import (SparseConv2d, SparseConv3d, SparseConvTranspose2d, SparseConvTranspose3d, SparseInverseConv2d, SparseInverseConv3d, SubMConv2d, Sub...
def quick_sort(arr): if len(arr) < 2: return arr pivot = arr.pop() left = [] right = [] for num in arr: if num > pivot: right.append(num) else: left.append(num) return quick_sort(left) + [pivot] + quick_sort(right) arr = [1,2,2,...
from .build import Build from .comps import Comps from .variants import Variants __all__ = ['Build', 'Comps', 'Variants'] __version__ = '1.4.1'
from .canvas import Canvas3D from .mcanvas import MCanvas3D from .widget import Canvas3DFrame, Canvas3DNoteBook, Canvas3DNoteFrame from .surface import Surface, MarkText, MeshSet from .geoutil import *
#!/usr/bin/env python3 import sys import ipaddress import subprocess from settings import default_tab_color from utils import get_ip_by_host, color_text, parse_ssh_command try: import iterm2 from server_config import get_server_list except (ModuleNotFoundError, ImportError) as e: color_text.error(e) ...
"""A Compile object (see compile_rule.py): foo.css -> foo.min.css. We pass the CSS thorugh cssmin to minify it. However, we also inline images at compress-time (it doesn't technically 'compress' this file, but it does compress the overall number of network round-trips the user needs, so we'll count it). We inline 'u...
#!/usr/bin/env python import tarfile import os import subprocess import fnmatch tarsuffix = 'out.tar.gz' ##_______________________________________________________________|| def _UnTar(tars,dry_run): try: for i in tars: cwd = os.getcwd() directory = os.path.dirname(i) o...
# %% ####################################### def sqlite3get_table_names(sql_conn: sqlite3.Connection): """For a given sqlite3 database connection object, returns the table names within that database. Examples: >>> db_conn = sqlite3.connect('places.sqlite')\n >>> sqlite3get_table_names(db_conn)\...
"""Support for Meteo-France weather data.""" import datetime import logging from meteofrance.client import meteofranceClient, meteofranceError from vigilancemeteo import VigilanceMeteoError, VigilanceMeteoFranceProxy import voluptuous as vol from homeassistant.const import CONF_MONITORED_CONDITIONS import homeassista...
# *_*coding:utf-8 *_* import getpass import sys import typing import click import pandas as pd from rich.console import Console import warnings import pymysql from sqlstar.core import DatabaseURL from sqlstar.interfaces import ConnectionBackend, DatabaseBackend from sqlstar.utils import check_dtype_mysql warnings.fil...
""" The purpose of this code is to create the pytorch-geometric graphs, create the Data files, and to load the train/val/test data It can be run on sherlock using $ /home/groups/rondror/software/sidhikab/miniconda/envs/test_env/bin/python pdbbind_dataloader.py all /oak/stanford/groups/rondror/projects/combind/flexibil...
from mcu.utils import elastic2D # Ref: https://doi.org/10.1021/jacs.8b13075 # Elastic tensors AlB6_1 = [379.9,438.4,23.1,159.6] AlB6_2 = [383,375.3,33.6,132.1] AlB6_3 = [395.1,401,44,173.6] AlB6_4 = [229.9,194.2,7.1,80.3] AlB6_5 = [242.2,171.1,15.6,57.1] AlB6_6 = [149.3,92.2,24.9,63.2] # define a list of elastic ten...
""" Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distrib...
# Implementation based on tf.keras.callbacks.py # https://github.com/tensorflow/tensorflow/blob/v2.2.0/tensorflow/python/keras/callbacks.py from typing import Union import wandb from .callback import Callback class WandbLogger(Callback): """ Callback that streams epoch results to tensorboard events folder...
import argparse import os import shutil import subprocess import tempfile import threading import time from .converters import PandocToPDFConverter from .conf import conf from .subproc import run_cmd def get_src_context(src: str = None, src_ext: str = ""): _src_ext = src_ext if src_ext != "" else "markdown" ...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home'), url(r'^stream/$', views.ActivityResourceView.as_view(), name='stream'), url(r'^drumkit/$', views.DrumKitView.as_view(), name='drumkit'), ]
"""Deactivate all pins.""" from . import config as cg cg.quiet_logging(False) def deactivate(): """Deactivate the pins.""" cg.send('\nStart: Deactivating all PWM pins') cg.set_pwm(cg.get_pin('Haptics', 'pin_buzzer'), 0) cg.set_pwm(cg.get_pin('Haptics', 'pin_shaker'), 0) for pin_color in ['red', ...
from serial.threaded import ReaderThread as ReaderThreadBase class ReaderThread(ReaderThreadBase): def __init__(self, port, serial_instance, protocol_factory): super().__init__(serial_instance, protocol_factory) self.__port = port @property def port(self): return self.__port
# Generated by Django 3.2.7 on 2021-09-12 07:42 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('kutub', '0015_manuscript_seal_description'), ] operations = [ migrations.AddField( model_name='manuscript', name='su...
from pathlib import Path import os import sys # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: ...
import sys, os, json, ast, requests from time import time as tm, sleep as slp from datetime import datetime as dt from itertools import cycle from pyquery import PyQuery as pq_ from browse import browse_url_profile_details from user_agents import user_agents data_dir = 'profile_data/' class indeed_resumes_details(o...
#!/usr/bin/python3 # lpoDB.py by Muhammad Hafidz from datetime import date, datetime, timedelta from tkinter import messagebox import sqlite3 import lpoWeb class lpoDB(): ''' # A database module class to keep of Wind Speed, Air Temperature, and Barometric Pressure for specific dates. # The module's functi...
# Keypirinha: a fast launcher for Windows (keypirinha.com) import keypirinha as kp import keypirinha_util as kpu from .lib import everything_ipc as evipc import os.path import threading import time import traceback class Everything(kp.Plugin): """Search for files and folders via Everything""" CONF...
""" Test the position module. """ import dataclasses import math from pytest import fixture from highlevel.robot.controller.motion.position import PositionController, tick_to_mm from highlevel.robot.entity.configuration import Configuration from highlevel.util.geometry.vector import Vector2 @fixture(name='configura...
from situations.complex.yoga_class import YogaClassScheduleMixin from venues.relaxation_center_zone_director import VisitorSituationOnArrivalZoneDirectorMixin from venues.scheduling_zone_director import SchedulingZoneDirector class ParkZoneDirector(YogaClassScheduleMixin, VisitorSituationOnArrivalZoneDirectorMixin, Sc...
import unittest from py3status_lbl.lenovo_battery_level import BatteryInfoModel, BatteryLevelElement class MyTestCase(unittest.TestCase): def test_convert_linux_battery_status_to_data_model(self): expected_battery_info = {'History (charge)': '', 'History (rate)': '', ...
""" Divide a given video into multiple shots using the kernel temporal segmentation library. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # from __future__ import unicode_literals import os from scipy.misc import imresize from PIL import Image from sk...
import logging import os import shutil import numpy as np from itertools import permutations import tensorflow as tf import model_fn.model_fn_2d.util_2d.graphs_2d as graphs from model_fn.model_fn_base import ModelBase from model_fn.util_model_fn.losses import batch_point3_loss, ordered_point3_loss class ModelPolygo...
import openpyxl import MySQLdb import datetime import numpy as np import sys import cv2 import os A2Z = [chr(i) for i in range(65, 65+26)] defaultRowHeight = 15 baseColWidth = 10 def fetchData(id): sql = MySQLdb.connect( user=os.environ['MYSQL_USER'], passwd=os.environ['MYSQL_PASSWORD'], host=os.environ['MYSQL_...
def _get_runfile_path(ctx, f): """Return the runfiles relative path of f.""" if ctx.workspace_name: return "${RUNFILES}/" + ctx.workspace_name + "/" + f.short_path else: return "${RUNFILES}/" + f.short_path def _impl(ctx): runfiles = ctx.attr._sh_tpl.default_runfiles.files.to_list() ...
import logging from typing import Any, List import enlighten from ib_insync.wrapper import RequestError from .signal_handler import SignalHandler, ExitSignalDetectedError from .contracts_db_connector import ContractsDbConnector from .ib_details_db_connector import IbDetailsDbConnector from .tws_connector import TwsCo...
from flask import Flask, request, redirect, url_for, render_template from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer from werkzeug.utils import secure_filename import librosa import torch import os app = Flask(__name__) where_to_save_files = "/home/aymenha2021/PycharmProjects/flaskProject1/uploads" tokeniz...
""" Main script for grammar AssignmentStatement1 (version 1) ## author Morteza Zakeri, (http://webpages.iust.ac.ir/morteza_zakeri/) ## date 20201029 ## Required - Compiler generator: ANTLR 4.x - Target language(s): Python 3.8.x ## Changelog ### v2.0.0 - A lexer and parser for simple grammar without any attribu...
from functools import update_wrapper from django.conf.urls import url from django.core.paginator import Paginator from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.encoding import escape_uri_path, iri_to_uri from django.utils.t...
import os import urllib import torch from torch.utils import model_zoo import shutil import datetime class CheckpointIO(object): ''' CheckpointIO class. It handles saving and loading checkpoints. Args: checkpoint_dir (str): path where checkpoints are saved ''' def __init__(self, checkpo...
#170401011 Berfin Okuducu import socket import time import subprocess import shlex import pickle import datetime from datetime import datetime host = "127.0.0.1" port = 142 baslangic=datetime.now() client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((host,port)) zaman,address=client.recvfrom(1024...
from common.tools.endianness import LittleEndian from common.hash.md import MDHashFunction class MD4(MDHashFunction): # Custom implementation of MD4. A = 0x67452301 B = 0xefcdab89 C = 0x98badcfe D = 0x10325476 @classmethod def get_OID(cls): return '\x06\x08\x2a\x86\x48\x8...
#!/usr/bin/python2.7 import argparse def get_sequence_lengths(labelfile): lengths = [0] with open(labelfile, 'r') as f: content = f.read().split('\n')[2:-2] # skip header and '#' at the end of the file for line in content: if line == '#': lengths.append(0) ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. import logging import cv2 import numpy as np from augly.video.augmenters.cv2 import BaseCV2Augmenter, VideoDistractorByShapes logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class VideoDistractorByDots(BaseCV2Augmenter): ...
from functools import wraps from flask import request from app.models.models import User from app.custom_http_respones.responses import Success, Error success = Success() error = Error() def token_required(f): @wraps(f) def decorated(*args, **kwargs): access_token = None if 'Authorization' in...
# Generated by Django 3.2.12 on 2022-03-18 13:20 import autoslug.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('tunes', '0002_initial'), ] operations = [ migrations.AddField( model_name='stations', name='slug', ...
# coding: utf-8 # Copyright Luna Technology 2016 # Matthieu Riviere <mriviere@luna-technology.com> PORTAL_FORMS = [ { 'pk': 1, 'portal': { 'name': 'HADDOCK', 'pk': 1 }, 'name': 'HADDOCK server: the Easy interface', 'original_url': 'http://haddock.sc...
import time import numpy as np from petastorm.pytorch import DataLoader from collections import namedtuple import torch from functools import partial import sys class DummyReader(object): @property def is_batched_reader(self): return True def stop(self): pass def join(self): ...
import sys from typing import List, Dict, Any, Tuple, Set import logging import numpy as np import pandas as pd from d3m import container, utils from d3m.metadata.pipeline import Pipeline, PrimitiveStep from d3m.metadata.base import ArgumentType from d3m.metadata import hyperparams from common_primitives.dataset_to_d...
import tempfile from functools import partial from pathlib import Path import tus from aiohttp import web from aiohttp_tus import setup_tus from tests.common import get_upload_url, TEST_FILE_NAME, TEST_FILE_PATH NUMBER = 5 async def test_mutltiple_tus_upload_urls(aiohttp_client, loop): upload = partial(tus.up...
import sys, os # Import libraries import psycopg2 # import frameworks from flask import abort # import config, utils from config import db_config class Database: def __init__(self, table=None, columns=None): self.conn = self.conn(db_config) self.__table__ = table self.__column__ = columns ...
name = "comlib" from comlib.lib import BackyardCom
#Python imports import os import requests from typing import List #Local import from commands.utils.colors import error_message from commands.utils.graph import wrapper_graphs from config import IMAGE_FOLDER def check_file_name(filename:str)->bool: """Validate the file format""" if '.' not in filename: ...
from __future__ import ( absolute_import, division, print_function, unicode_literals, ) from random import randint from tempfile import gettempdir from uuid import uuid4 from jsonschema import ValidationError import pytest from reles import configure_mappings from reles.validators import CustomDraft4...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 18 16:03:41 2020 @author: juanporras """ import pandas as pd import numpy as np import json import urllib.request from urllib.request import urlopen import datetime import time config = {'displayModeBar': False} from cleaning_datas import df O...
#Yudha Prasetyo_Tugas_Pertemuan13 def listdata(): nama1 = input("Input Nama ke-1: ") nilai1 = input("Input Nilai ke-1: ") nama2 = input("Input Nama ke-2: ") nilai2 = input("Input Nilai ke-2: ") nama3 = input("Input Nama ke-3: ") nilai3 = input("Input Nilai ke-3: ") return nama1, nilai1, nama2, ...
import pandas def lambda_handler(event, context): return pandas.__version__
import logging from collections import deque from typing import Type, Dict, Iterator, Union import pika import scrapy from scrapy import signals, Request from scrapy.crawler import Crawler from scrapy.exceptions import CloseSpider, DontCloseSpider from scrapy.http import Response from twisted.internet import reactor f...
import numpy as np from typing import Union, Tuple, Dict class Agent(object): def get_action(self, obs:np.ndarray, stochastic:bool=True)-> Tuple[Union[int, np.ndarray, Dict], float]: raise NotImplementedError def update(self, obs:np.ndarray, act:Union[int, np.ndarray, Dict], blogp:float, reward:float...
from __future__ import absolute_import, division, print_function, unicode_literals from jinja2 import BytecodeCache class InMemoryBytecodeCache(BytecodeCache): def __init__(self): self._storage = {} def clear(self): self._storage.clear() def load_bytecode(self, bucket): try: ...
class StreamKey: ''' 一条流的加密信息 含有下列属性 - 加密方法 - key的uri - key内容 - keyid - 偏移量 - 其他属性 -> 根据流类型而定 含有下面的方法 - 设置key内容 - 设置iv - 保存为文本 - 从文本加载 ''' def __init__(self): self.method = 'AES-128' # type: str self.uri = None # type: str self.key = b'...
import re from typing import Tuple from urllib.parse import ParseResult, urlparse from api2ch.config import BOARDS, hostname_mirrors def prettify_bytes(size: float) -> str: for unit in ('Б', 'Кб', 'Мб', 'Гб', 'Тб'): if size < 1024.0: break size /= 1024.0 return f'{size:.0f} {unit}...
import sys import operator class Solution: def layerbylayer(self, nlayer): layerlength = self.n - nlayer * 2 # layer starts from 0 if not layerlength: return None if layerlength == 1: self.ans[nlayer][nlayer] = self.nownum else: nowx, nowy = nla...
#! /usr/local/Python_envs/Python3/bin/python3 import paramiko import time from getpass import getpass import re host = 'csr1.test.lab' username = 'admin' password = 'admin' # host = 'ios-xe-mgmt-latest.cisco.com' # username = 'developer' # password = 'C1sco12345' print(f"\n{'#' * 55}\nConnecting to the Device {host}...