text
stringlengths
3.07k
22.1k
from collections import defaultdict from django.conf import settings from django.db import models from datetime import datetime from django.contrib.postgres.fields import JSONField from django.core.exceptions import ValidationError from django.db.models.signals import post_save from django.dispatch import receiver impo...
#!/usr/bin/env python import datetime import os import shutil import subprocess import yaml TEST_CASES = [("test_sys_2n_l0_l1.py", "2n_l0_l1.yaml", ["node1"]), ("test_sys_2n_l0_l1.py", "2n_l0_l1.yaml", ["node2"]), ("test_sys_2n_l0_l2.py", "2n_l0_l2.yaml", ["node1"]), ("test_s...
""" MoinMoin edit log class This is used for accessing the global edit-log (e.g. by RecentChanges) as well as for the local edit-log (e.g. PageEditor, info action). TODO: * when we have items with separate data and metadata storage, we do not need the local edit-log file any more (because ev...
from TP1.metodos_numericos import Biseccion from TP1.metodos_numericos import Secante from TP1.metodos_numericos import NewtonRaphson from TP1.metodos_numericos import NewtonRaphsonModificado from TP1.Graficador import * #from calculadoraAlfaLambda import * from TP1.calculadora_nueva import * import numpy as n...
import base64 import cStringIO import gzip import hashlib from tempfile import NamedTemporaryFile import requests import urllib3 from google.api_core import retry from google.auth.exceptions import GoogleAuthError from google.cloud import storage, exceptions from requests.adapters import HTTPAdapter from urllib3.util....
import pydash import math FIXED_DIGITS = 8 def area_to_rect(map, area): grid_map = pydash.get(map, 'metadata.gridmap') if pydash.has(grid_map, 'origin') is False: raise Exception('metadata.gridmap.origin is undefined') if pydash.has(grid_map, 'scale_m2px') is False: raise Exception('meta...
import csv class Student: def __init__(self, fields): self.fields = fields # hash table of user fields students = [] # a list of dicts that describe a student language_prof = {"elementary": 1, "limited": 2, "intermediate": 3, "nearly_proficient": 4} def lookup(proficiency): return language_prof[proficiency] ...
import GPflow import tensorflow as tf from GPflow.tf_hacks import eye import numpy as np import unittest from reference import * def referenceUnivariateLogMarginalLikelihood( y, K, noiseVariance ): return -0.5 * y * y / ( K + noiseVariance ) - 0.5 * np.log( K + noiseVariance ) - 0.5 * np.log( np.pi * 2. ) def...
"""A `when(1)`-style simple calendar tool.""" # https://docs.python.org/3/library/functions.html#eval # https://docs.python.org/3/library/ast.html#ast.literal_eval # https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html # http://newville.github.io/asteval/ from pathlib import Path import re import clic...
from string import Template import numpy as np scanSumTmpl = Template(""" typedef struct ScanResult { unsigned scan, reduction; } ScanResult; typedef struct ScanStorage { unsigned sums[$warpSize]; } ScanStorage; __forceinline__ __device__ unsigned warpScanSum(unsigned value) { int laneId = threadIdx.x % $warp...
# Copyright 2019 The TensorFlow Hub 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 app...
import socket from threading import Lock import msgpack try: import msgpack_numpy msgpack_numpy.patch() except ImportError: # msgpack_numpy is optional pass class Client: def __init__(self, host='localhost', port=5000): """Client object. Args: host (str, optional): ho...
import numpy as np import config from optimizers import get_optimizer import copy from scipy.special import expit as sigmoid # Sigmoid function """ NOTE: - Only use dropout during training """ class FullyConnected: def __init__(self, input_dim, output_dim, ...
#!/usr/bin/env python import copy import json import logging from abc import ABCMeta, abstractmethod from typing import Dict, Any, Union from psycopg2 import pool, extensions, extras from psycopg2._psycopg import AsIs from psycopg2.extensions import register_adapter from credentials import pg_localhost from enums.key...
import argparse import resource import typing from evalutils import * from lccv import lccv from commons import * import logging import json def parse_args(): default_path = '~/experiments/lccv_sensitivity/' parser = argparse.ArgumentParser() parser.add_argument('--experiment_idx', type=int) parser.a...
from __future__ import unicode_literals import pytz from django.contrib.auth import get_user_model from django.contrib.postgres.fields import JSONField from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) from datetime import datetime from django.db.models impo...
#! /usr/bin/env python import os import argparse import datetime import torch import torchtext.data as data import torchtext.datasets as datasets import model import train import mydatasets import pandas as pd import glob import time from GPyOpt.methods import BayesianOptimization parser = argparse.ArgumentParser(d...
# ------------------------------------------------------------------------------ # From an mp.data.datasets.dataset_segmentation.SegmentationDataset, create a # mp.data.pytorch.PytorchDataset. There are different types of datasets: # # PytorchSeg2DDataset: the length of the dataset is the total number of slices # (fo...
#!/usr/bin/env python import argparse import datetime import os import re import subprocess import tarfile import time from collections import defaultdict import utilities.log_util as ut_log import utilities.s3_util as s3u import boto3 from boto3.s3.transfer import TransferConfig S3_REFERENCE = {"east": "czi-hca",...
import functools from jax import vjp, jacobian, jvp, grad from jax.flatten_util import ravel_pytree from jax.tree_util import tree_map import jax.numpy as np from .sde_utils import time_reflect_ito, diag_jac, time_reflect_stratonovich from .sdeint import ito_integrate, stratonovich_integrate, _sdeint_ito from .brown...
# -*- coding:utf-8 -*- import logging import xlrd import time import traceback from xlrd.sheet import Cell from csvkit.utils import get_file, exit, str2bool from csvkit.const import * from csvkit.exceptions import DropException, IgnoreException, AbortException from csvkit.network import MetricSender DEFAULT_METRIC =...
import csv import datetime import json import random import mido import math from mido.midifiles.midifiles import MidiFile from LoadingRotationBar import LoadingRotationBar class Serializable(): def importFile(self, file: str) -> None: pass def exportFile(self, file: str) -> None: pass # R...
from enum import Enum, IntEnum, IntFlag from ..models import db class ManagementFlag(IntFlag): """This enum of integer bitwise OR flags represents all the fields available as part of the ``ManagementFlag`` option to the ``InstallApplication`` command.""" NOTHING = 0 REMOVE_APP_WITH_ENROLLMENT = 1 ...
import logging from typing import Optional from django.db import transaction from rest_framework.reverse import reverse from rest_framework.serializers import Serializer, CharField, ChoiceField, BooleanField from purplship.core.utils import DP, DF from purpleserver.core.gateway import Shipments, Carriers from purplese...
"""Core functionality and interface of pghistory""" from django.db import connection from django.db import models from django.db.models import sql from django.db.models.sql import compiler import pgtrigger from psycopg2.extensions import AsIs import pghistory.constants _registered_events = {} class Event: """F...
# Menory Puzzle.py #By Oliver <EMAIL> import random, pygame,sys from pygame.locals import * FPS=60 #屏幕刷新频率 WINDOWWIDTH = 640 #窗口宽度 WINDOWHEIGHT = 480 #C窗口高度 REVEALSPEED = 8 #BOX一次揭开或者覆盖的块数 BOXSIZE = 40 #BOX的大小 GAPSIZE = 10 #BOX间的间隙宽度 BOARDWIDTH = 10 #一行的box个数 BOARDHEIG...
""" MIT License Copyright (c) 2021 <NAME> 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 use, copy, modify, merge, publish, distri...
# Copyright 2019 Mycroft AI 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 writin...
# coding: utf-8 # In[7]: # 1. Predict with pre-trained Mask RCNN models # =============================================== # # This article shows how to play with pre-trained Mask RCNN model. # # Mask RCNN networks are extensions to Faster RCNN networks. # :py:class:`gluoncv.model_zoo.MaskRCNN` is inherited from #...
# Copyright 2015 The TensorFlow 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 applica...
from mininet.topo import Topo from mininet.node import Node from mininet.net import Mininet import yaml class Error(Exception): """Base class for exceptions in this module.""" class NoSuchPlc(Error): """Raised when an attack targets a PLC that does not exist""" class TooManyNodes(Error): """Raised whe...
# Copyright: 2019, NLnet Labs and the Internet.nl contributors # SPDX-License-Identifier: Apache-2.0 import http.client import re import socket import ssl import time from collections import defaultdict from urllib.parse import urlparse from celery import shared_task from django.conf import settings import unbound fr...
""" Global configuration variables """ import sys from warnings import warn from numbers import Number # Make it safe to assume Python 3 when testing version if sys.version_info.major < 3: raise RuntimeError("theano_shim requires Python 3. You are using {}." .format(sys.version)) from collect...
#!/usr/bin/env python # -*- coding: utf-8 -*- from .version import __version__ from .partition import Partition, PartitionItem from . import utils from os import listdir, path from threading import Lock, Thread import traceback import random import falcon import time import json import logging class STATUS: OK =...
import math import numbers from typing import Union, Optional, List import torch import torch.nn as nn import torch.nn.functional as F from torch.types import _int, _size, Number # noinspection PyTypeChecker def gaussian_kernel(sigma: Union[_int, _size], dim: _int = 2, kernel_size: Optional[Union[_int, _size]] = Non...
from __future__ import annotations import abc import math import uuid import random import timeit import numpy as np from bitarray import bitarray from yalla.hashing.hashers import XxHasher64 class ItemCounter(metaclass=abc.ABCMeta): @abc.abstractmethod def unique_count(self) -> int: pass @abc.a...
# Copyright 2018 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
import functools import os import sys import threading import pkg_resources from .executor import Context, Tasks, TaskError from .paths import in_dir, paths_for_shell tasks = Tasks() @tasks.register('dependencies', 'additional_assets', 'bundles', 'collect_static_files', 'take_screenshots', 'compile...
# coding: utf-8 import random __author__ = 'salvia' import json class InvalidInstruction(Exception): pass class BadInstructionCall(Exception): pass def str_instruction(self): return ( '<%s instance at %i: opcode=%i, n_arg=%i, mnemonic=%s>' % (self.get_name(), id(self), self.opcode, s...
#!/usr/bin/env python3 # # Copyright 2015 Dovetail Genomics LLC # # from __future__ import division from __future__ import print_function from builtins import str from builtins import range from builtins import object from past.utils import old_div import sys import string import random tt = str.maketrans("ACTGactg"...
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import numpy import pandas from copy import copy from collections import OrderedDict from indra.databases import uniprot_client from indra.databases import hgnc_client from indra.literature import pubmed_client from ...
import re import requests import json import urllib3 import psutil from colorama import Fore # Disable warnings for insecure requests urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) # If fiddler is open, it uses a proxy to send requests, if not send them normally if "Fiddler.exe" in (p.name() for ...
# -*- coding: utf-8 -*- # # Copyright 2015 Google 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-2.0 # # Unless requir...
#!/usr/bin/env python3 """ Read the log output from a howdesbt test job, and extract the useful information. """ from sys import argv,stdin,stdout,stderr,exit from re import compile def usage(s=None): message = """ usage: cat job_log_file | convert_howdesbt_job_log [options] --howdesbt the log ...
#!/usr/bin/env python # # Copyright 2018 - The Android Open Source Project # # 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...
import json import subprocess import requests from shutil import copyfile from distutils.dir_util import copy_tree import urllib.request import urllib from urllib.parse import urlparse import os import sys import argparse import time from socket import error as SocketError from snakemake.io import expand workflows=['...
import os, sys, tempfile import datetime, time, re from seiscomp import mseedlite as mseed def _timeparse(t, format): """Parse a time string that might contain fractions of a second. Fractional seconds are supported using a fragile, miserable hack. Given a time string like '02:03:04.234234' and a for...
''' key_finding.py Kristin given a list of chord, parse the best key sequene from the chord reference: Krumhansl-Schmuckler key-finding algorithm http://rnhart.net/articles/key-finding/ ''' import sys, os import numpy as np from music21 import * from mido import * import mido # data_dir = "../POP909/" data_dir =...
#!/usr/bin/python3 from bs4 import BeautifulSoup import os.path import shutil ''' Super Duper Importer ''' ################################### # Paths and Directories ################################### goldenRoot = 'golden/' leRoot = 'resources/website/' leImages = 'resources/website/static/images/' ############...
from init import * from methods import * from models import * from datasets import * def arg_parser(): p = argparse.ArgumentParser() p.add_argument('--index', type=int) p.add_argument('--dataset', type=str, choices={ 'mnist', 'cifar10', 'cifar100'}) p.add_argument('--batch', type=in...
import time from typing import Iterable, List, Dict, Union import logging from blatann.nrf import nrf_types from blatann import uuid, exceptions logger = logging.getLogger(__name__) class AdvertisingFlags(object): LIMITED_DISCOVERY_MODE = 0x01 GENERAL_DISCOVERY_MODE = 0x02 BR_EDR_NOT_SUPPOR...
#!/usr/bin/env python import os import sys import csv import collections import logging import json import datetime import time from lxml import html, etree import pprint pp = pprint.PrettyPrinter(indent=4) import requests # get the logger log = logging.getLogger('') OLAC_LANGUAGE = collections.namedtuple('OLAC_LANG...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
import os import importlib import numpy as np import matplotlib.pyplot as plt from sklearn.manifold import TSNE import seaborn as sns import torch import torchvision from torchvision import datasets, transforms from torch import nn, optim from torch.utils.data import DataLoader from torchvision.utils import save_image,...
import json import requests import argparse import os import sys import time from multiprocessing.pool import ThreadPool as Pool pool_size = 1 bought = [] def worker(item,mnemonic): try: getprice(item,mnemonic) except: print('error with item') def screen_clear(): # for mac and linux(here, ...
import os import numpy as np import random from PIL import Image import matplotlib.pyplot as plt from math import floor def zero(): return np.random.uniform(0.0, 0.01, size = [1]) def one(): return np.random.uniform(0.99, 1.0, size = [1]) def noise(n): return np.random.uniform(-1.0, 1.0, size = [n, 4096...
#!/usr/bin/env python3 from __future__ import print_function import logging import os import re from argparse import ArgumentParser from importlib import import_module from subprocess import check_call, STDOUT, Popen, CalledProcessError import coloredlogs import cpuinfo import platform import config from core.enviro...
""" Cubic spline planner Author: <NAME>(@Atsushi_twi) """ import math import numpy as np import bisect from numpy.lib.shape_base import dsplit class Spline: """ Cubic Spline class """ def __init__(self, s_distance_list, waypoints_list): # Spline(self.s_distance_list, waypoints_x_list) sel...
from typing import Callable, Sequence, Tuple from .agents.base_agent import BaseAgent import numpy __all__ = [ "CompositeScenarios", "CircleCrossingScenario", "SquareCrossingScenario", "CircleCrossing6Scenario", "CircleCrossing12Scenario" ] class BaseScenario(): def __init__(self, seed: int=...
import re import logging import importlib from collections import OrderedDict from django.utils import six from django.conf import settings from django.conf.urls import url as make_url, include from djsw_wrapper.utils import Singleton, Template, Resolver, LazyClass from djsw_wrapper.makers import SwaggerViewMaker, Sw...
""" Methods and class for PhotoInfo exposing SearchInfo data such as labels Adds the following properties to PhotoInfo (valid only for Photos 5): search_info: returns a SearchInfo object search_info_normalized: returns a SearchInfo object with properties that produce normalized results labe...
import pandas as pd import numpy as np import scipy.stats import matplotlib as plt from scipy.stats import norm from scipy.optimize import minimize def drawdown(ret_ser: pd.Series): """ Lets Calculate it: 1. Compute wealth index 2. Compute previous peaks 3. Compute Drawdown - which is the wealth v...
import time import asyncio import json import operator import ccxt from uxapi import register_exchange from uxapi import UXSymbol from uxapi import UXPatch from uxapi import WSHandler from uxapi.helpers import ( hmac, contract_delivery_time ) @register_exchange('bitmex') class Bitmex(UXPatch, ccxt.bitmex): ...
# coding: utf-8 import dataclasses import typing import serpyco from guilang.description import Description from guilang.description import Part from guilang.description import Type from rolling.action.base import WithResourceAction from rolling.action.base import WithStuffAction from rolling.action.base import get_w...
#!/usr/bin/env python3 # # Miscellaneous miniirc_extras utilities # from __future__ import annotations import collections, functools, miniirc, re, socket from . import AbstractIRC, error as _error, Hostmask from ._classes import _DummyIRC as DummyIRC, _namedtuple as namedtuple, \ VersionInfo, deprecated from ._num...
# -*- coding: utf-8 -*- """Windows Event Log resources database reader.""" import re try: from pysqlite2 import dbapi2 as sqlite3 except ImportError: import sqlite3 # TODO: Move the generic sqlite3 code to a different spot e.g. lib/. class Sqlite3DatabaseFile(object): """Class that defines a sqlite3 database ...
from flask import Flask, abort, redirect, render_template, render_template_string, request, Markup, make_response import json import random import ssl import asyncio from django.core.validators import URLValidator from django.core.exceptions import ValidationError app = Flask(__name__) validChars = 'abcdefghijklmnopq...
import random from collections import deque import numpy as np def sign(val): if val > 0: return 1 elif val < 0: return -1 else: return 0 def calc_gravity(x, y): """ 座標 (x, y) に働く重力のベクトルを返す :param x: :param y: :return: """ if abs(x) > abs(y): ...
#!/usr/bin/env python3 from aiohttp import ClientSession from aiohttp.web import Application, RouteTableDef, AppRunner, TCPSite, Response, json_response, HTTPForbidden from argparse import ArgumentParser from asyncio import run, sleep, wait_for, CancelledError try: import simplejson as json except ImportError: ...
from ..ir_code import IrInstruction from ..ir_type import IrTypePtr, IrTypeStruct, IrTypePtr, IrTypeArray, IrTypeVector, IrAddressSpace from ..ir_value import IrValueExpr from ..ir_expr import IrExpressionConstant from be_typing import TYPE_CHECKING class IrInstAlloca(IrInstruction): def __init__(self, result, ty...
import sherpa from tqdm.notebook import tqdm SHERPA_PARAMETER_TYPE_MAPPER = { 'choice':sherpa.Choice, 'continuous':sherpa.Continuous, 'discrete':sherpa.Discrete, } CLASS_SUFIX_MAPPER = { 'categorical':'__USE_FEATURE_CATEGORICAL', 'numerical':'__USE_FEATURE_NUMERICAL', 'layer':'__LAYER', 'em...
import asyncio import copy import io import logging import textwrap import time import traceback import typing from contextlib import redirect_stdout import discord from discord.ext import commands from util.data.data_backup import DataBackups # from util.logger import Logger from util.messages import MessagesUtil fr...
from sqlite3 import OperationalError from unittest import TestCase, mock from unittest.mock import patch from web_python_2018_04_ht06_orm.core import connect, Scheme, BaseModel, BaseField, QuerySet Scheme.getInstance().database = 'local.db' class StubParentModel(BaseModel): id = BaseField(type=int, pk=True) ...
import sys import pygame import ball import display import game import paddle # Inititizes the game and set the screen name pygame.init() pygame.display.set_caption("Pong") # Creating all the objects and variable in the game. ball = ball.Ball() right_paddle = paddle.Paddle("right") left_paddle = pad...
from PyQt5 import QtCore, QtGui, QtWidgets import qdarkstyle from threading import Thread from collections import deque from datetime import datetime import time import sys import cv2#, torch from PIL import Image as im from utils.augmentations import letterbox import imutils import numpy as np class CameraWidget(QtW...
from imutils.object_detection import non_max_suppression import numpy as np import imutils import os import cv2 import requests import time import argparse import time import base64 # Our module to make requests to the server import auth # TODO: Implement face mask detection ''' Usage: python src/main.py -i PATH_TO_...
import os import sys import numpy as np import random ROOT_DIR = os.path.abspath('../') sys.path.append(ROOT_DIR) def space_NMS(box_a,box_b):#((x1,y1),(x2,y2)) width_a=abs(box_a[0][0]-box_a[1][0]) width_b=abs(box_b[0][0]-box_b[1][0]) height_a=abs(box_a[0][1]-box_a[1][1]) height_b=abs(box_b[0][1]-...
from __future__ import print_function import math import random from simanneal import Annealer import networkx as nx import time class recalculatebySA(Annealer): upk = 1.1 upmax = 5 def anneal(self): """Minimizes the energy of a system by simulated annealing. Parameters state : an ...
import re import sublime from collections import defaultdict from collections import namedtuple from . import utils from . import buffer_metadata CompletionList = namedtuple("CompletionList", "completions priority exclude_lower_priority") Documentation = namedtuple('Documentation', 'doc_regions doc_html_variables on_n...
"""Wrap tempfile to give you pathlib.Path.""" import pathlib import shutil import tempfile from typing import IO, Any, Optional, Union # pylint: disable=unused-import class removing_tree: # pylint: disable=invalid-name """Check if the path exists, and if it does, calls shutil.rmtree on it.""" def __init__...
import asyncio from enum import Enum from typing import Optional, Callable import async_timeout from yate.asyncio import YateAsync from yate.protocol import MessageRequest class ChannelEventType(Enum): PLAYBACK_END = 1 DTMF = 2 class YateIVR(YateAsync): def __init__(self): super().__init__() ...
# -*- coding: utf-8 -*- import json, sys def load_data(json_file): f = None data = None try: f = open(json_file, 'r') data = json.loads(f.read()) except: print(sys.exc_info()) print('Default data is used instead of "{}".'.format(json_file)) default_data = { "fragment_comp": { ...
""" .. See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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....
# ============================================================================== # Copyright 2019 - <NAME> # # NOTICE: 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, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: ai ts=4 sts=4 et sw=4 nu from __future__ import (unicode_literals, absolute_import, division, print_function) import logging from django.http import Http404, JsonResponse from django.utils import timezone from django.shortcuts import render,...
import logging import voluptuous as vol import serial.tools.list_ports from datetime import datetime # from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH from homeassistant import config_entries from homeassistant.core import callback # from homeassistant import data_entry_flow # from . import get_coordinator f...
import os import sys import xml.etree.ElementTree as ET from config import Config from galaxy.api.types import Achievement class TropConf: def __init__(self, trophies_path): self.path = os.path.join(trophies_path, 'TROPCONF.SFM') self.tree = ET.parse(self.path) self.root = self.tree.getr...
# -*- coding: utf-8 -*- """ Created on Tue Aug 30 08:57:31 2016 @author: nicholas """ import sys import logging import shutil # import subprocess import glob import os import unittest # import multiprocessing from Bio import SeqIO from Bio.SeqRecord import SeqRecord from argparse import Namespace from unittest.mock i...
from yattag.simpledoc import dict_to_attrs, html_escape, attr_escape, SimpleDoc, DocError try: range = xrange # for Python 2/3 compatibility except NameError: pass __all__ = ['Doc'] class SimpleInput(object): """ class representing text inputs, password inputs, hidden inputs etc... """ ...
import re from .exceptions import ParseError from .types import ParsedUrl from .const import XSD_STRING, RDF_LANGSTRING __all__ = [ 'REGEX_BCP47', 'KEYWORD', 'ABSOLUTE_IRI', 'parse_url', 'unparse_url', 'parse_link_header', ] REGEX_BCP47 = re.compile(r'^[A-Z]{1,8}(-[A-Z0-9]{1,8})*$', re.I) KEYWORD = re.comp...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np from tqdm import tqdm import argparse import os import random import data_loader import model os.makedirs('checkpoints', exist_ok=True) parser = argparse.ArgumentParser() # training set-up parser.add_a...
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
#!/usr/bin/env python3 import re import os import sys import time import argparse import threading from subprocess import run, PIPE, DEVNULL current_dir = os.path.dirname(os.path.abspath(__file__)) def run_time(func): def wrapper(*args, **kwargs): print('Starting extracting apks,waiting...') star...
#!/usr/bin/env python3 # ===================== # Зависнуть над маркером # ===================== from turtle import circle import numpy as np import rospy import cv2 import cv2.aruco as aruco from sensor_msgs.msg import Image from cv_bridge import CvBridge from aruco_calibration import Calibration as clb from drone_a...
import logging import time import xlsxwriter from src.iot23 import get_feat_selection_name, get_data_sample_name, get_sample_row_count, get_data_sample_name_short from src.iot23 import decode_cls_label def export_stats_xls(output_dir, exp_stats_dict, output_file_name='stats....
# -*- coding: utf-8 -*- """ Created on Tue May 24 15:42:14 2016 Author: <NAME> """ from __future__ import print_function import schiene import datetime import time import os import sys, getopt import threading def sanitize(req): """Enhance the information content""" # get current time now = datetime.dateti...
#!/usr/bin/env python # # you can monitor the availability of the index with something like this: # # watch "echo \"\`date +'%Y-%m-%d %H:%M:%S '\` \`curl -s http://wallace.jcu.io/api/namesearch/?term=lion | wc -w\`\" >> resultcount.log" # # ...which will log the number of words in the search response every two #...
from typing import Any, Dict from uuid import UUID import pytest from sqlalchemy import text QUERY = text( """ select data::jsonb, xyz.wal, xyz.is_rls_enabled, xyz.users, xyz.errors from pg_logical_slot_get_changes( 'rls_poc', null, null, 'include-pk', '1', 'include...
# 2020 국어 정보 처리 시스템 경진 대회 출품작 # Team 리프: 영화 리뷰 분석 시스템 from model import ABSAModel from crawler.utils import MovieCrawler import logging import numpy as np MOVIE_ASPECT = ["연기", "배우", "스토리", "액션", "감정", "연출", "반전", "음악", "규모"] SIM_WORD_LIST = [["연기", "연극"], ["배우", "캐스팅", "모델"], ["스...
import os from functools import partial from typing import Callable, Optional import numpy as np import torch import yaml from fire import Fire from glog import logger from joblib import cpu_count from tensorboardX import SummaryWriter from torch import nn from torch.nn import functional as F from torch.nn.parallel im...