content
stringlengths
5
1.05M
import sys f = sys.argv[1] with open(f) as handle: for new_line in handle: try: cmi = float(new_line.split()[0]) if len(new_line.split()[1:]) < 20: continue if cmi >= 0.4: print(new_line.strip()) except: pass
"""! @brief Examples of usage and demonstration of abilities of clustering algorithms from cluster module. @authors Andrei Novikov (pyclustering@yandex.ru) @date 2014-2020 @copyright BSD-3-Clause """ from random import random, randint from math import floor import matplotlib.pyplot as plt from pyclustering.nnet i...
import os import sys from os.path import dirname, join, exists from django.core.management.commands import makemessages class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2018, 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any...
import os import typing import numpy import pandas from sklearn import model_selection from d3m import container, exceptions, utils as d3m_utils from d3m.metadata import base as metadata_base, hyperparams from d3m.base import primitives __all__ = ('KFoldDatasetSplitPrimitive',) class Hyperparams(hyperparams.Hyper...
# python face_model.py -i "../data/image/face/han2.JPG" -o "../data/image/face/han.JPG" import os import time import cv2 import argparse import numpy as np from skimage.transform import resize from scipy.spatial import distance from keras.models import load_model from keras.utils.vis_utils import plot_model ap = argp...
# coding: utf-8 """ RadioManager RadioManager # noqa: E501 OpenAPI spec version: 2.0 Contact: support@pluxbox.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from radiomanager_sdk.models.broadcast_relations_model_type ...
# Copyright 2018/2019 The RLgraph authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
# import library socket karena menggunakan IPC socket import socket # definisikan IP untuk binding TCP_IP = '127.0.0.1' # definisikan port untuk binding TCP_PORT = 5005 # definisikan ukuran buffer untuk menerima pesan BUFFER_SIZE = 4096 # buat socket (bertipe UDP atau TCP?) s = socket.socket(socket.AF_INET, socke...
import torch import torch.nn as nn from torch.jit import ScriptModule, script_method, trace import math device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') def create_gaussian_window(window_size, channel): def _gaussian(window_size, sigma): gauss = torch.Tensor([math.exp(-...
from functools import reduce def largest_product(series, size): if len(series) < size or size < 0 or any(not x.isdigit() for x in series): raise ValueError(r".+") digits = [int(x) for x in series] max_product = 0 for i in range(len(digits) - size + 1): max_product = max(max_product, ...
from datetime import datetime import pytest from pastypy import Paste TEST_SITE = "https://paste.zevs.me" def get_content(test_name): return f"---\nTest: {test_name}\nTime: {datetime.utcnow().timestamp()}" def create_paste(test_name): return Paste(content=get_content(test_name), site=TEST_SITE) def tes...
import numpy as np arr = np.c_[np.array([1, 2, 3]), np.array([4, 5, 6])] arr2 = np.c_[np.array([[1, 2, 3]]), 0, 0, np.array([[4, 5, 6]])] print(arr) print(arr2)
# coding: utf8 """供插件调用的接口, 说话、消息反馈、生成带二维码的页面等""" from voice import tts from yiwa.db import DataConveyor from tdcode import qr_code from flask import render_template, request def say(text): """机器对外说话""" try: tts.say(text) return True except: return False def feedback(informatio...
from .HyHelper_traj import * from .HyHelper_plot import * from .HyHelper_filters import * from .AutoSplit import * print('All files imported successfully. Welcome to HyHelper!')
# Chang Wei Tan, Angus Dempster, Christoph Bergmeir, Geoffrey I Webb # # MultiRocket: Effective summary statistics for convolutional outputs in time series classification # https://arxiv.org/abs/2102.00457 import numpy as np from numba import njit from catch22A.catch22_full import sb_binarystats_mean_longstretch_1, ...
import sys sys.path.append('/usr/local/lib/python3.4/dist-packages/') import numpy as np def bruteforce(P, Q): solQ=[] for q in Q: md=np.linalg.norm(P[0]-q) mi=0 for i in range(len(P)): if np.linalg.norm(np.subtract(P[i],q))<md: md=np.linalg.norm(np.subtract(P[i],q)...
from .conftest import client def test_entity_404(): res = client.get("/entities/banana") assert res.status_code == 404, res def test_entity_fetch(): res = client.get("/entities/Q7747") assert res.status_code == 200, res data = res.json() assert data["id"] == "Q7747" assert data["schema"]...
import psutil import os import PASSWORDS import pprint import time from alert_to_mail import send_email from custom_logger import get_logger # psutil.Process(pid=4196, name='chrome.exe', status='running', started='2020-12-09 09:55:34') def get_process_list(): """Return last 10 items sorted dict processes by proce...
from unittest import TestCase from rasa_integration_testing.common.identifier import Identifier ELEMENTS = ["en-US", "pay_bill", "initial"] class TestIdentifier(TestCase): def test_equals(self): self.assertEqual(Identifier(*ELEMENTS), Identifier(*ELEMENTS)) def test_length(self): self.asser...
# coding: utf-8 """ Gitea API. This documentation describes the Gitea API. # noqa: E501 OpenAPI spec version: 1.15.3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility libr...
# coding=utf-8 """Variant on standard library's cmd with extra features. To use, simply import cmd2.Cmd instead of cmd.Cmd; use precisely as though you were using the standard library's cmd, while enjoying the extra features. Searchable command history (commands: "history") Run commands from file, save to file, edit ...
import logging import picamera class MultiSocketOutput(object): def __init__(self): self.connections = {} self.logger = logging.getLogger("camera") def write(self, s): remove = [] for name, conn in self.connections.items(): try: conn.sendall(s) except socket.error as msg: self.logger.error('so...
### # Copyright (c) 2017, Athanasius # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, a...
import cv2 import numpy as np import matplotlib.pyplot as plt from skinDetector import SkinDetector def openCloseMask(mask, iterations = 2): # Create structural element shape = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (6,6)) # perform opening and closing on the image until all the blobs have been ...
import pytest import requests # from time import sleep COMPONENT_INDEX_URL = "http://identidock:5000" COMPONENT_MONSTER_BASE_URL = COMPONENT_INDEX_URL + '/monster' def test_get_mainpage(): # print('component tester sleeping for 1 sec to let the identidock app to be ready adn also start its server') # sleep(1) p...
# Copyright 2014 - Rackspace Hosting # # 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 ...
#!/usr/bin/python3 import angr import claripy proj = angr.Project( 'crackme', main_opts = {'base_addr': 0x0}, load_options = {'auto_load_libs': False} ) # Flag is 10 characters flag = claripy.BVS("flag", 8 * 10) state = proj.factory.entry_state(stdin = flag) # Silence the warnings state.options.add(angr.opti...
from requests import get from support import extract import re URL = "http://randomfactgenerator.net/" def random_fact(): response = get(URL) fact = extract(r"<div id=\\'z\\'>.+?<br/>", "<div id=\\'z\\'>", "<br/>", str(response.content)) fact_updat...
import numpy as np def calc_bins(labels, probs, num_bins=10): bins = np.linspace(0.1, 1, num_bins) confs = np.max(probs, axis=1) binned = np.digitize(confs, bins) # Save the accuracy, confidence and size of each bin bin_accs = np.zeros(num_bins) bin_confs = np.zeros(num_bins) bin_sizes = ...
b, bR, bS, a, aS = input().split() b, bR, bS, a, aS = [int(b), int(bR), int(bS), int(a), int(aS)] bM = (bR - b) * bS aM = 0 aR = a while aM < bM: aR += 1 aM += aS print(aR)
from estudent.grade import Grade from estudent.grade_calculator import GradeCalculator from unittest import TestCase class GradeCalculatorTestCase(TestCase): def setUp(self): self.failing_grade = Grade(value=1) self.passing_grade = Grade(value=5) self.poor_grade = Grade(value=2) def ...
# coding=utf-8 # Copyright 2021 The Uncertainty Baselines 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 ap...
import discord,time,asyncio from discord.ext import commands from discord.ext.commands import errors, converter,command from ..Utils. util_func import random_color from discord.ext import tasks import random class MyHelpCommand(commands.MinimalHelpCommand): async def send_bot_help(self, map): emb = discord...
############################################################ # -*- coding: utf-8 -*- # # # # # # # # # ## ## # ## # # # # # # # # # # # # # # # ## # ## ## ###### # # # # # # # # # Python-based Tool for interaction with the 10micron mounts # GUI with PyQT5 fo...
""" This file as been modified extensively to implement SLAM in RPLidar Concepts taken from rpslam.py : BreezySLAM Python with SLAMTECH RP A1 Lidar https://github.com/simondlevy/BreezySLAM Consume LIDAR measurement file and create an image for display. Adafruit invests time and resources providing this open source ...
#!/usr/bin/env python3 # # Copyright (c) 2019, The OpenThread Authors. # 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 # ...
import unittest from ml_model_abc import MLModel from model_beam_job.ml_model_operator import MLModelPredictOperation # creating an MLModel class to test with class MLModelMock(MLModel): # accessing the package metadata display_name = "display name" qualified_name = "qualified_name" description = "des...
#!/usr/bin/env python import pytest """ Test 1823. Find the Winner of the Circular Game """ @pytest.fixture(scope="session") def init_variables_1823(): from src.leetcode_1823_find_the_winner_of_the_circular_game import Solution solution = Solution() def _init_variables_1823(): return solution ...
""" List of place types and place qualifiers. Auto-generated with `python -m scripts`. """ # START recognized_placetypes = { "*": { "article": "a", "display": "*", "preposition": "in", }, "Crown dependency": { "article": "a", "display": "Crown dependency", "p...
from __future__ import unicode_literals from celery import Celery from celery.signals import celeryd_init from core.config.config import yeti_config celery_app = Celery('yeti') class CeleryConfig: BROKER_URL = 'redis://{}:{}/{}'.format(yeti_config.redis.host, yeti_config.redis.port, yeti_config.redis.database)...
from setuptools import setup, find_packages setup( name="tljh-voila-gallery", version="0.0.1", entry_points={ "tljh": ["tljh_voila_gallery = tljh_voila_gallery"], "console_scripts": [ "build-gallery-images = tljh_voila_gallery.build_images:main", "install-builder-uni...
import queue def addToQueue(screen): string = queue.convertToVideoString(screen) if string is not None: result = screen.queue.addItem(string) if not result: #TODO: Properly handle error. print("Error adding to queue. Non-unique description") screen.queue.listJob...
from PIL import Image img = Image.open(r'e:\image.jpg') img.show()
if __name__ == '__main__': total_students = int(input()) if total_students >= 2 and total_students <= 5: student_with_grades = [] grades = set() students_with_second_lowest_grade = [] for _ in range(total_students): name = input() grade = float(input()) ...
import json import logging from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func from iotfunctions import bif from iotfunctions.metadata import EntityType from iotfunctions.db import Database from iotfunctions.enginelog import EngineLogging import datetime as dt EngineLogging.configure_console...
from django.urls import path from .views import PostListView,PostDetailView,PostCreateView from . import views urlpatterns=[ path('new/', PostCreateView.as_view(), name='post-create'), ]
import asyncio from transformers import pipeline from transformers import AutoTokenizer, AutoModelForSequenceClassification model_name = "Recognai/zeroshot_selectra_medium" model = AutoModelForSequenceClassification.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) classificator = pipe...
from urllib2 import Request, urlopen, URLError import json from time import sleep from datetime import date def main(lat="19.430", long_str="-99.135", airport="MEX"): try: with open('data.all.txt', 'r') as f: elems = json.loads(f.read()) resp = [] aux(resp,...
# (C) Copyright 2020 IBM Corp. # (C) Copyright 2020 Inova Development Inc. # 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-...
from tkinter import * import time import random pob1 = 10 #X pob2 = 90 #Y pob3 = 60 #X pob4 = 140 #Y pod1 = 150 #Triangle haut gauche pod2 = 170 #Triangle haut droit pod3 = 160 #Triangle bas pot1 = -1 pot2 = 19 pot3 = 9 jumping = False decoractive = False decortempactive = False fenetre = Tk() #can...
import flask import json import datetime from .util import NumericRangeEncoder def add_user_action( cursor, evidence_id, action, description, old_value, ): auth = flask.current_app.config['auth'] comment = '{}; {}'.format(auth.current_user().name, flask.request....
#!/usr/bin/env python """Interface to the MultiMarkdown parser.""" import os.path import platform import ctypes import ctypes.util from .download import SHLIB_EXT from .defaults import DEFAULT_LIBRARY_DIR _MMD_LIB = None _LIB_LOCATION = None def load_mmd(): """Loads libMultiMarkdown for usage""" global _MMD...
"File contains definitions of types that are used in tables." STRING = ['str', 'string'] INTEGER = ['int', 'integer'] BIG_INTEGER = ['bigint', 'big int', 'big integer'] SMALL_INTEGER = ['small int', 'short'] FLOAT = ['float'] DOUBLE = ['double', 'decimal'] TIMESTAMP = ['timestamp', 'time stamp'] NULL = ['null', 'none'...
# Copyright 2016-present CERN – European Organization for Nuclear Research # # 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...
import logging import logging.config def configure_logger(log_path, loglevel='DEBUG'): logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'console_formatter': { 'format': '%(levelname)-8s '+ '[%...
train | |--flownetc6 | | | |--spatial_correlation_sample | |--back2future | |--spatial_correlation_sample |--consensus_exp_masks
import os have_session_bus = bool(os.environ.get('DBUS_SESSION_BUS_ADDRESS'))
from returns.io import IO def test_equality(): """Ensures that containers can be compared.""" assert IO(1) == IO(1) assert str(IO(2)) == '<IO: 2>' assert hash(IO((1, 2, 3))) def test_nonequality(): """Ensures that containers are not compared to regular values.""" assert IO(1) != 1 assert...
import unittest from GlasswallArchiveManager import ArchiveManager class TestArchiveManagerMethods(unittest.TestCase): def setUp(self): self.gw = ArchiveManager("./test_artefacts/glasswall.archive.manager.dll") with open("./test_artefacts/test_data/test_file_001.zip", "rb") as f: ...
import aes128 import Print import os import shutil import json import listmanager from Fs import Nsp as squirrelNSP from Fs import Xci as squirrelXCI from Fs.Nca import NcaHeader from Fs import Nca from Fs.File import MemoryFile import sq_tools from Fs import Type as FsType import Keys from binascii impor...
from rest_framework import serializers from . import models class PumpSerializer(serializers.ModelSerializer): #city = CitySerializer() #town = TownSerializer() #sector = SectorSerializer() class Meta: model = models.Pump fields = '__all__' class SectorSerializer(serializers.ModelS...
from pathlib import Path from clld.db.meta import DBSession def test_Config_replacement_key(): from clld.db.models.common import Config assert Config.replacement_key('X', 'Y') == '__X_Y__' assert Config.replacement_key(None, 'Y') == '__NoneType_Y__' def test_Files(db, tmp_path): from clld.db.model...
import mock import pytest def test_setup_rpio(gpio, patch_open): gpio.setup(10, gpio.OUT) patch_open.assert_any_call('/sys/class/gpio/export', 'w+') patch_open().__enter__().write.assert_any_call('10') patch_open.assert_any_call('/sys/class/gpio/gpio10/value', 'wb+', buffering=0) patch_open.asse...
class FimDeJogos: def __init__(self, ambiente, simboloCampoVazio): self.IAmbiente = ambiente self.ISimboloCampoVazio = simboloCampoVazio # verifica se o campo ainda tem posições vazias def velha(self): simbolo = self.ISimboloCampoVazio if simbolo not in self.IAmbiente.getCam...
""" The object is set up to use the Python "with" syntax as follows: from maya.debug.PlaybackOptionsManager import PlaybackOptionsManager,PlaybackOptions with PlaybackOptionsManager() as mgr: mgr.setOption( 'minTime', 1.0 ) mgr.setOption( 'maxTime', 10.0 ) mgr.setOption( 'loop', 'once'...
from .signup_setting import SignupSetting from .signup_user_response import SignupUserResponse from .user_custom_field import UserCustomField from .base import BaseEmail __all__ = ["SignupSetting", "SignupUserResponse", "UserCustomField", "BaseEmail"]
# ***************************************************************** # Copyright 2013 MIT Lincoln Laboratory # Project: SPAR # Authors: Jill Poland # Description: Unit tests for the server harness log file # parser # ***********************************************...
from ..utils import format_table, norm_percent, are_all from .arg_init import init_arg from .fault_analyzer_decorator import FaultAnalyzerDecorator class FaultAnalyzerBase(FaultAnalyzerDecorator): def __init__(self, comp, **kwargs): super().__init__(comp, **kwargs) self.nb_faults = 0 se...
#------------------------------------------------------------------------------- # # Project: EOxServer <http://eoxserver.org> # Authors: Fabian Schindler <fabian.schindler@eox.at> # #------------------------------------------------------------------------------- # Copyright (C) 2013 EOX IT Services GmbH # # Permission...
import urllib.request,json from app.models import Quote def get_quote(): path="http://quotes.stormconsultancy.co.uk/random.json" with urllib.request.urlopen(path) as url: url_data=url.read() formated_data=json.loads(url_data) #tie url data to quote object properties id=forma...
import arcade class Window(arcade.Window): def __init__(self): super().__init__(800, 600) self.text = "" self.center_x = self.width / 2 self.center_y = self.height / 2 def setup(self): arcade.set_background_color(arcade.color.AMETHYST) self.text_list.append(arc...
"""Module for Page""" from .master_page import MasterPage class Page(MasterPage): """This class is used to define a custom Page in a report, inherits some defaults from Master""" def __init__(self, title, page_variables, partial_template): self.page_variables = page_variables self.sections = {}...
from __future__ import annotations from dataclasses import dataclass, field from functools import cached_property from pathlib import Path from tempfile import TemporaryDirectory from time import monotonic from types import TracebackType from typing import Callable, ContextManager, List, Optional, Type, Union from ri...
import random import string import logging import argparse from multiprocessing import Pool from functools import wraps from pathlib import Path import errno import os import signal import time import json import util # configure logging log = logging.getLogger(__name__) FILE_DIR = Path(__file__).parent.resolve() RO...
#recebendo os inputs com valores v1 = float(input('Digite o 1º valor... ')) v2 = float(input('Digite o 2º valor... ')) v3 = float(input('Digite o 3º valor... ')) #tipos de triângulo: #0-não é triângulo; #1-equilátero; #2-isóceles; #3-escaleno tipo = 0 #verificando se é realmente triângulo if v1+v2 > v3 and v1+v3 > v...
import sqlite3 from biicode.client.exception import ClientException import os class SQLiteDB(object): def __init__(self, dbfile_path): if not os.path.exists(dbfile_path): par = os.path.dirname(dbfile_path) if not os.path.exists(par): os.makedirs(par) dbf...
#! /usr/bin/env python """ Strip a program/library after it is created. Since creating the file and modifying it occurs in the same task, there will be no race condition with other tasks dependent on the output. For other implementation possibilities, see strip_hack.py and strip_on_install.py """ from waflib import...
class Solution: def XXX(self, strs: List[str]) -> str: res=strs[0] for i in range(1,len(strs)): b=strs[i] if b=="": return b if len(b)<len(res): res=res[:len(b)] while res and res!=b: res=res[:-1...
#!/usr/bin/python2.7 # Copyright 2015 Ethan Smith import logging import ConfigParser import DeepThaw import os import itertools config = ConfigParser.RawConfigParser() config.read('config.cfg') logging.basicConfig(level=config.getint('logs', 'level')) dataStore = DeepThaw.storage('data') toAnalyze = os.listdir('dat...
import os from datetime import timedelta from flask import Flask, render_template, url_for, request, jsonify from flask_login import LoginManager, current_user, login_user, login_required, logout_user from flask_wtf import CSRFProtect from werkzeug.utils import redirect, secure_filename from School146.data import db_...
from torch.autograd import Variable from torch.autograd.function import Function, once_differentiable from torch._thnn import type2backend from . import _all_functions from torch.nn.modules.utils import _single, _pair, _triple # NB: Looking for MaxPool2d or AvgPool2d? They're natively implemented by ATen. # Look at...
from . import models from . import routes
catlog = ['cellpose_plg']
import re import string from mimetypes import guess_type from os import path from ujson import dumps as json_dumps from aiofiles import open as open_async COMMON_STATUS_CODES = { 200: b'OK', 400: b'Bad Request', 404: b'Not Found', 500: b'Internal Server Error', } ALL_STATUS_CODES = { 100: b'Continu...
# Generated by Django 2.1.5 on 2019-09-05 05:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0017_auto_20190905_1034'), ] operations = [ migrations.AlterModelOptions( name='reportpost', options={'verbo...
"""Integrate HALO Home into home assistant.""" import logging from halohome import Connection from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from .const import CONF_LOCATIONS, DOMAIN, PLATFORMS LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass...
import pygame from vector import Vector2 from constants import * import numpy as np class Node(object): def __init__(self, x, y): self.position = Vector2(x, y) self.neighbors = {UP:None, DOWN:None, LEFT:None, RIGHT:None, PORTAL:None} self.access = {UP:[PACMAN, BLINKY, PINKY, INKY, CLYDE, F...
# # Copyright 2016 CognitiveScale, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
from django.apps import AppConfig class HtConfig(AppConfig): name = 'ht_web_service.apps.ht' def ready(self): from .import signals
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import hashlib import json import datetime import pandas as pd import os import numpy as np import requests import re import traceback from itertools import islice from browseCloudServiceAuthorizer import BrowseCloudServiceAu...
from __future__ import print_function import tensorflow as tf import numpy as np import random import TensorflowUtils as utils import read_data as scene_parsing import datetime import BatchDatsetReaderAtt as dataset from six.moves import xrange from skimage import io, color import math from scipy import signal from sc...
from selenium import webdriver from selenium.webdriver.chrome.options import Options import time import os import sqlite3 abs_path = os.getcwd() split = os.path.split(abs_path) workflow_db_path = os.path.join( split[0], "pipeline/deplatformr_open_images_workflow.sqlite") workflow_db = sqlite3.connect(workflow_db...
import geckodriver_autoinstaller from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.common.excep...
import numpy as np import tensorflow as tf def get_angles(pos, i, embedding_size): angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(embedding_size)) return pos * angle_rates def positional_encoding(max_len, embedding_size): angle_rads = get_angles(np.arange(max_len)[:, np.newaxis], ...
#!/usr/bin/env python """ Exceptions for ioccheck """ class Error(Exception): """Generic exception for non-recoverable exceptions.""" class IOCException(Exception): """Generic exception raised for issues pertaining to IOCs.""" class IOCNotFoundError(Exception): """Raised when can not find an IOC.""" ...
# -*- coding: utf-8 -*- import factory from ..models import Blog class BlogFactory(factory.django.DjangoModelFactory): """ Factory to create instance of a Blog. """ title = factory.Faker("text", max_nb_chars=50) class Meta: model = Blog
"""Test the colorlog.colorlog module.""" import sys import pytest def test_colored_formatter(create_and_test_logger): create_and_test_logger() def test_custom_colors(create_and_test_logger): """Disable all colors and check no escape codes are output.""" create_and_test_logger( log_colors={}, r...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from utils.misc import length2mask from models.vlnbert_init import get_vlnbert_models class VLNBertCMT(nn.Module): def __init__(self, args): super().__init__() print('\nInitalizing the VLN-BERT model ...') ...
# coding: utf-8 import pprint import re import six class TextWatermark: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is j...