content
stringlengths
5
1.05M
import os import time import logging import numpy as np from sklearn.metrics import roc_auc_score import torch import torch.nn as nn from torch.utils.data import DataLoader from . import mlp_model from . import utils_experiment as utils from .dataloader import Hit_Pair_Dataset ######################################...
from sane_doc_reports.domain.Element import Element from sane_doc_reports.conf import DEBUG import sane_doc_reports.populate.utils as utils from sane_doc_reports.styles.utils import style_cell class ErrorElement(Element): """ Used to indicate errors in the elements (better for debugging problems in the genera...
import pandas as pd import pytest from cli.ACME_evaluation import * class Namespace: def __init__(self, **kwargs): self.__dict__.update(kwargs) @pytest.mark.skip def test_get_precision_hand(): # one label per peak output_peaks = pd.DataFrame(data={'mass_idx': [1, 10, 100], 'time_idx': [1, 10, 10...
import sublime, sublime_plugin import os from .. import util from ..global_vars import * def get_flow_path(): flow_path = [] flow_path = os.path.join(NODE_MODULES_BIN_PATH, "flow") is_from_bin = True settings = util.get_project_settings() if settings and settings["project_settings"]["flow_cli_custom_path...
#coding=utf-8 # coding=utf-8 ''' Created on 2014-1-5 @author: ETHAN ''' from django.conf.urls import url from doraemon.project.views import project_issue_view issue_router=[url(r"^(\d{1,9})/issue/(all)$",project_issue_view.index), url(r"^(\d{1,9})/issue/(\d{1,9})$",project_issue_view.index), ...
#!/usr/bin/python3 """ Interface to XAC joystick (joystick_uart.ino) via serial UART port. MIT License Copyright (c) 2021 gdsports625@gmail.com 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 wi...
import random #Adam Levin moves = {"tackle": range(18, 26), "pk thunder": range(10, 36), "psi heal": range(10, 20) class Character: "Define our general Character which we base Ness and Starman off of." #The error isn't what the debug says it is. def __init__(self, health): self.health = health...
import cv2 import numpy as np from threading import Thread, Lock from time import time import torch class Detection: running = False lock = None model = None frame = None predictions = None tracker = None def __init__(self): device = torch.device('cuda:0' if torch.cuda.is_availab...
from argparse import ArgumentParser #https://github.com/manga-py/manga-py/blob/d89501a0f78d498f85114320d6123f59d328a905/manga_py/cli/_args_general.py#L4 def _gen_args(args_parser: ArgumentParser, version) : args = args_parser.add_argument_group('General options') args.add_argument( '-v', '--ve...
from itertools import product import hcuppy.utils as utils from hcuppy.ccs import CCSEngine class UFlagEngine: def __init__(self): fn = "data/ICD10PCS_utilizationflagformats_FY2019_1.csv" self.utilmap = utils.read_utilflag(fn) self.cepr = CCSEngine(mode="pr") def get_uflag(self, rev_l...
import discord import os import datetime import random TOKEN = os.environ['DISCORD_BOT_TOKEN'] client = discord.Client() weekday=datetime.date.today().weekday() owner_id = "459936557432963103" @client.event async def on_ready(): print('Hello World,対話botプログラム「Project-ririna-」、起動しました') # メッセージ受信時に動作する処理 @clien...
import os.path import discord import covers from os import path client = discord.Client() base_path = path.dirname(__file__) relative_path = 'token' token_path = os.path.join(base_path, relative_path) token = open(token_path, 'r').read() @client.event async def on_ready(): print('We have logged in as {0.user}'...
from jinja2 import Environment, FileSystemLoader, select_autoescape import json from livereload import Server from more_itertools import chunked import os import math env = Environment( loader=FileSystemLoader('.'), autoescape=select_autoescape(['html', 'xml'])) def create_pages(): #Создание главной ст...
import tensorflow as tf import tensorflow.keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import tensorflow as tf import tensorflow.keras from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense import numpy as np import pandas as pd impor...
# Copyright 2019-2021 ETH Zurich and the DaCe authors. All rights reserved. """ Implementation of the performance instrumentation report. """ import json import numpy as np import re from collections import defaultdict from dace.properties import EnumProperty, make_properties, Property from dace import dtypes @make_...
# -*- coding: utf-8 -*- """Parses a log file and uploads it to a server.""" import os import re import errno import zipfile import tarfile import logging import traceback import csv import pandas as pd import datetime logger = logging.Logger(__name__) logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.se...
from pyspider.helper.date import Date from pyspider.helper.logstash_formatter import LogstashFormatterV1 from pyspider.config import config import logging import logging.handlers class Log: FORMAT = LogstashFormatterV1() def __init__(self): self.error_handler = self.create_file_handler('error', 'ERRO...
import os import json import subprocess from selfdrive.swaglog import cloudlog from selfdrive.version import version from common.api import api_get from common.params import Params def get_imei(): return subprocess.check_output(["getprop", "oem.device.imeicache"]).strip() def get_serial(): return subprocess.chec...
from .set_groups_base import SetGroupsBase import xarray as xr import netCDF4 import os class SetGroupsAZFP(SetGroupsBase): """Class for setting groups in netCDF file for AZFP data. """ def set_env(self, env_dict): """Set the Environment group in the AZFP netCDF file. AZFP includes additi...
{{year}}
import logging import random from itertools import zip_longest from io import StringIO from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from . import models logger = logging.getLogger(__name__) def generate_teams(hackathon, team_size=3, max_team_size=6,...
from django.db import models from videos.models import Video from django.contrib.auth.models import User # Create your models here. class Block(models.Model): video = models.OneToOneField(Video,on_delete=models.CASCADE) user = models.OneToOneField(User,on_delete=models.CASCADE) start_time = models.DateTime...
from dataclasses import fields from tkinter import Image from django import forms from .models import Image # class Upload(forms.Form): # image = forms.ImageField(label='Choose Image') class Upload(forms.ModelForm): class Meta: model = Image fields = ('image',)
from sqlalchemy import Table, Column, Integer, ForeignKey from sqlalchemy.orm import relationship from . import db, bcrypt class User(db.Model): id = db.Column(db.Integer(), primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) username = db.Column(db.S...
import torch from PIL import Image from os import listdir from os.path import join from torch.utils.data.dataset import Dataset from torchvision.transforms import Compose, RandomCrop, ToTensor, ToPILImage, CenterCrop, Resize def isImage(filename: str) -> bool: return any(filename.endswith(ext) for ext in ['.png', '.j...
import copy from .data_validation import data_validation """ Every time a task is fetched, we have to merge the task's data values with the workflow object. We store these separately because a workflow's blocks configuration can change. If it does, we want to reflect these changes on any task that is not completed. ...
from fanstatic.config import convert_config from fanstatic import make_injector, make_publisher, make_fanstatic def test_convert_config(): d = { 'versioning': 't', 'recompute_hashes': 'false', 'bottom': 'True', 'force_bottom': 'False', 'rollup': 0, 'somethingelse': ...
# python3 # pylint: disable=g-bad-file-header # Copyright 2021 DeepMind Technologies Limited. 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...
import copy class Interior(): __banios_completos = 0 __banios_medios = 0 __habitaciones = 0 __cuartos_de_lavado = 0 def set_banios_completos(self, banios_completos): self.__banios_completos = banios_completos def get_banios_completos(self): return self.__banios_completos ...
import MateriaClass from trello import TrelloClient import connectSQLite import configuration import logging logging.basicConfig(filename='Running.log',level=logging.INFO, format='%(asctime)s:%(levelname)s:%(message)s') def create(subjCod, task_title): config = configuration.load_config_file('polical.yaml') c...
"""Initial Migration Revision ID: e91b61c6c62b Revises: 5bd202370d85 Create Date: 2020-10-26 17:07:40.759641 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e91b61c6c62b' down_revision = '5bd202370d85' branch_labels = None depends_on = None def upgrade(): ...
#!/usr/bin/env python import os, sys import numpy as np import pandas as pd import pickle import shutil from gryffin import Gryffin #========================= # Define helper functions #========================= def full_measurement(a_ix, b_ix, c_ix, df): row = df.loc[(df['frag_a_ix']==a_ix) & ...
import subprocess n = 0 while True: n += 1 nstr = str(n) subprocess.call(["ulimit -t 120; python ~/tstl/generators/randomtester.py --nocover --timeout 120 --full --output bug" + nstr], shell=True)
# # PySNMP MIB module H3C-VOH323CALLSTAT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-VOH323CALLSTAT-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:24:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (d...
# coding: utf-8 # ## Pothole Detection # #### Load important libraries # In[1]: import cv2 import numpy as np import pygame import time import smtplib import sys from matplotlib import pyplot as plt # In[2]: file_name = 'pothole.jpg' #file name can be passed as an commandline argument. if sys.argv[1] != None...
# Copyright (c) 2017 Cisco Systems # 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 applicable...
from copy import deepcopy from pulp import LpVariable, LpBinary from pulp.pulp import LpProblem from bmw_solver_qprogmods.bmw_parser import BMWProblem from bmw_solver_qprogmods.general_ip_constraints import * from bmw_solver_qprogmods.ip_sat_maxsat import * from bmw_solver_qprogmods.ip_scheduling import * from bmw_so...
from .build_queue_widget import JenkinsBuildQueue from .build_table_widget import JenkinsBuildTable from .executor_status_widget import JenkinsExecutorStatus from .footer_widget import JenkinsFooter from .header_widget import JenkinsHeader from .job_info_widget import JenkinsJobInfo from .button_widget import JenkinsBu...
# -*- coding: utf-8 -*- """ Created on Thu Dec 5 18:54:43 2019 @author: Brandon """ import numpy as np import matplotlib.pyplot as plt h=1e-5 t=0 w0=0.4 T=1 g=2 gt=5 Einit=0.1 E_dtinit=0.1 Ts=[] E=Einit E_dt=E_dtinit E_arr=[] E_dt_arr=[] E_dt2init=-w0**2*(E)-(1/T)*E_dt+(g-gt*(E)**2)*E_dt while t<=30: E_dt2=-w...
from random import gammavariate as gamma from time import sleep while 1 == 1: print(gamma(1,2), end="\r") sleep(0.05)
""" read single source of truth from shipped labextension's package.json """ import json from pathlib import Path __js__ = json.loads((Path(__file__).parent / "labextension/package.json").read_text()) __version__ = __js__["version"]
import random adjectives = ['burnt', 'wide', 'narrow', 'green', 'red', 'yellow', 'tall', 'big', 'small', 'forked', 'dark'] features = ['lake', 'forest', 'canyon', 'draw', 'creek', 'mesa', 'desert', 'plain', 'swamp', 'hill', 'mountain', 'river', 'valley', 'brush'] def make_name_desc(): ...
from __future__ import annotations # from numba import jit ''' The MIT License (MIT) Copyright (c) 2014 Michael Hirsch reference: http://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm * The best way to Numba JIT this would probably be in the function calling this, to include the loop itself inside t...
#!/usr/bin/env python ## ## Copyright (c) 2014-present, Facebook, Inc. ## All rights reserved. ## ## This source code is licensed under the University of Illinois/NCSA Open ## Source License found in the LICENSE file in the root directory of this ## source tree. An additional grant of patent rights can be found in the ...
# coding: utf-8 from quokka.core.app import QuokkaModule module = QuokkaModule("media", __name__, template_folder="templates") # Register the urls if needed # from .views import ListView, DetailView # module.add_url_rule('/media/', view_func=ListView.as_view('list')) # module.add_url_rule('/media/<slug>/', view_func=...
import fastapi_jwt_auth import pytest from fastapi.testclient import TestClient from app.main import app from .test_signup import test_create_user @pytest.fixture(scope="module") def test_app(): yield TestClient(app) def test_create_task(test_app): test_create_user(test_app) response = test_app.post( ...
def VP_dado_A(A, p, tx): """ Caculo do valor presente (VP) dado uma série uniforme (A) :param VP: Valor Presente :param p: Periodos :param tx: taxa de juros :return: Valor futuro """ r = (1+tx)**p - 1 q = tx*(1+tx)**p vp = A*(r/q) return vp A = float(input('Insira o valor da pr...
from ..bbDatabases import HeirarchicalCommandsDB from ..bbConfig import bbConfig import importlib commandsDB = HeirarchicalCommandsDB.HeirarchicalCommandsDB(bbConfig.numCommandAccessLevels) def loadCommands(): global commandsDB commandsDB.clear() for modName in bbConfig.includedCommandModules: tr...
import os import sys import importlib from collections import defaultdict sys.path.insert(0, '/n/groups/htem/Segmentation/shared-nondev/cb2_segmentation/analysis_mf_grc') from tools_pattern import get_eucledean_dist '''Load data''' import compress_pickle fname = '/n/groups/htem/Segmentation/shared-nondev/cb2_segment...
from os import PathLike from pathlib import Path from typing import List, Optional, Union import numpy as np import pandas as pd import starfile import typer from .dask import create_cluster from .mdoc import prepare_mdoc_dataframe from .stack_images import stack_image_files, stack_image_files_mmap from .utils impor...
import logging import redis from datapackage_pipelines.utilities.extended_json import json class RedisBackend(object): KIND = 'redis' def __init__(self, host=None, port=6379, username=None, password=None): self.redis = None if host is not None and len(host) > 0: conn = redis.St...
# -*- coding: utf-8 -*- # Copyright (c) 2017 The cableloss developers. All rights reserved. # Project site: https://github.com/questrail/cableloss # Use of this source code is governed by a MIT-style license that # can be found in the LICENSE.txt file for the project. """Provide the cable loss for the specified cable t...
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import sys import json import pymongo from pymongo.errors import DuplicateKeyError from pymongo.errors import CursorNotFound import utils.database_helper as dbh import utils.file_handling as fh def insert_one(collection, mail_address_string, leak_name): tr...
#!/usr/bin/env python import timeit import re import math def e34(): n = 3 t = 0 while n < 200000: s = 0 for d in map(int, str(n)): s += math.factorial(d) if n == s: print "Digit Factorial: %d == %d" %(n, s) t += n n += 1 print "Sum of...
# -*- coding: utf-8 -*- """ Routing module. """ import datetime, os, pprint import flask from availability_service.utils import app_helper, log_helper ## setup app = flask.Flask(__name__) log = log_helper.setup_logger() log.debug( u'log initialized at %s' % unicode(datetime.datetime.now()) ) ## routes @app.rout...
# for x in range(4): # for y in range(3): # print(f"({x},{y})") # print("#####") # """ Multiplication table """ # for i in range(1, 11, 1): # print (f"Table of {i}") # for j in range(1, 11, 1): # print(f"{i} x {j}") """ Print F char""" # numbers = [5, 2, 5, 2, 2] # ...
# -*- coding: utf-8 -*- import pytest from hagworm.extend.asyncio.base import Utils, TimeDiff from hagworm.extend.asyncio.task import RateLimiter pytestmark = pytest.mark.asyncio # pytest.skip(allow_module_level=True) class TestHTTPClient: async def test_rate_limiter(self): async def _temp(): ...
import ast import os from types import FunctionType from typing import Dict, List, Optional, Sequence, Set, Tuple, Type, Union import airfly import regex as re from airfly._ast import ( Assign, BinOp, Call, Comment, Constant, Expr, ImportFrom, Module, Name, Pass, RShift, ...
""" Proxy lets us inspect the standard in/out/err for a thread. This is helpful when a thread is started in a context where it is difficult to observe the I/O. For example, an async thread spun up on the gateway will write directly to the wrapper log via print, which is extremely inconvenient. The streams...
# Copyright 1999-2017 Alibaba Group Holding Ltd. # # 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 o...
import scrapy # Scrapy serialization of fetched product information class ProductInfoItem(scrapy.Item): asin = scrapy.Field() category = scrapy.Field() rank = scrapy.Field() dimensions = scrapy.Field()
import sys import unittest from testutils import * import dbapi20 def main(): add_to_path() import pyodbc from optparse import OptionParser parser = OptionParser(usage="usage: %prog [options] connection_string") parser.add_option("-v", "--verbose", action="count", help="Increment test v...
from unittest import TestCase from schematics.types import StringType, ModelType, IntType, BooleanType from schematics_factory import model, nested class TestFactory(TestCase): def test_simple_factory(self): my_model = model({ 'str': StringType() }) my_instance = my_model({ ...
# https://github.com/miracle2k/onkyo-eiscp/issues/49 import os from os import path import yaml def construct_tuple(loader, node): return tuple(yaml.SafeLoader.construct_sequence(loader, node)) yaml.SafeLoader.add_constructor('tag:yaml.org,2002:seq', construct_tuple) with open('eiscp-commands.yaml', 'r') as f:...
#!/usr/bin/env python from distutils.core import setup setup(name = 'django-html5-boilerplate', version = '0.1', description = 'Scripts for creating and builing Django projects based on HTML5 Boilerplate', author = 'Damian Moore', author_email = '', url = 'https://github.com/damianmoore/django-htm...
# # This file is part of USB3-PIPE project. # # Copyright (c) 2019-2020 Florent Kermarrec <florent@enjoy-digital.fr> # SPDX-License-Identifier: BSD-2-Clause import unittest from migen import * from usb3_pipe.common import TSEQ, TS1 from usb3_pipe.training import TSChecker, TSGenerator class TestTraining(unittest.T...
from output.models.ms_data.regex.re_l22_xsd.re_l22 import ( Regex, Doc, ) __all__ = [ "Regex", "Doc", ]
#!/usr/bin/env python import numpy as np import sys import subprocess import argparse from collections import namedtuple as nt def append_line_to_array(line, array, index): """Append line of floats to a numpy array""" line_floats = [string_to_float(i) for i in line.split()] for num in line_floats: ...
import json from mythril.ether.soliditycontract import SolidityContract from mythril.laser.ethereum.svm import GlobalState, MachineState from mythril.laser.ethereum import svm from tests import * SHA256_TEST = [ (0,False) for i in range(6)] RIPEMD160_TEST = [ (0,False) for i in range(6)] ECRECOVER_TEST = [ (0,Fals...
from pygame import * x = 10 y = 10 x1 = 900 y1 = 900 BLACK = (0,0,0) class GameSprite(sprite.Sprite): def __init__(self, player_image, player_x, player_y, x_speed,y_speed):#добавила скорость по x и по y super().__init__() self.image = transform.scale(image.load(player_image),(65,65)) ...
from __future__ import unicode_literals from future.builtins import range from mezzanine.conf import settings from mezzanine.core.managers import DisplayableManager from mezzanine.utils.urls import home_slug class PageManager(DisplayableManager): def published(self, for_user=None, include_login_required=False):...
# -*- coding: utf-8 -*- """ Created on Sat Apr 11 16:20:00 2020 @author: Genocs @description: Simple linear model y = mx + b. The pipeline logs are written using tensorboard """ from __future__ import absolute_import, division, print_function, unicode_literals # Import TensorFlow import tensorflow as tf # I...
#!/usr/bin/env python3 import localpath from libcpu.devices import Register from libcpu.opcode_builder import OpcodeArg from libcpu.opcodes import opcodes from typing import TextIO def generate_casmdefs(rdfile: TextIO) -> None: rdfile.write("#bits 8\n") rdfile.write("#ruledef\n") rdfile.write("{\n") ...
# -*- coding: utf-8 -*- # %% [markdown] # # Beam Search # # In `chapter_seq2seq`, we discussed how to train an encoder-decoder with input and output sequences that are both of variable length. In this section, we are going to introduce how to use the encoder-decoder to predict sequences of variable length. # # As in th...
import unittest from cdlib.algorithms import louvain import networkx as nx import numpy as np from cdlib import evaluation class FitnessFunctionsTests(unittest.TestCase): def test_link_modularity(self): g = nx.karate_club_graph() communities = louvain(g) mod = evaluation.link_modularity...
# Copyright 2018 Akretion (http://www.akretion.com). # @author Sébastien BEAU <sebastien.beau@akretion.com> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from odoo import fields, models class ProductCategory(models.Model): _inherit = "product.category" media_ids = fields.Many2many("storag...
from typing import Any, Union from positional_linked_list import PositionalLinkedList from data_structures.linked_lists import SinglyLinkedList class PositionalSinglyLinkedList(PositionalLinkedList, SinglyLinkedList): """A positional singly linked list is a positional list implemented based on a singly linked l...
class Solution: def maxDistToClosest(self, seats): spacetmp = 0 space = 0 for seat in seats: if seat == 0: spacetmp += 1 if seat != 0: space = max(space,spacetmp) spacetmp = 0 return max( int(m...
"""Class :py:class:`DMQWControl` is a Data Manager QWidget with control fields ============================================================================== Usage :: # Run test: python lcls2/psana/psana/graphqt/DMQWControl.py from psana.graphqt.DMQWControl import DMQWControl w = DMQWControl() Created ...
import re from django.utils.functional import Promise from extutils.url import is_valid_url from ._base import BaseField, FieldInstance from .exceptions import ( FieldInvalidUrlError, FieldMaxLengthReachedError, FieldRegexNotMatchError, FieldEmptyValueNotAllowedError ) class TextField(BaseField): DEFAULT_M...
# -*- coding: utf-8 -*- """ Created on Sat Feb 27 10:37:37 2021 @author: Lakhan KumawatN """ #C:/Users/Lakhan Kumawat/Downloads/chromedriver_win32/chromedriver.exe from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_cond...
db = 'sqlite'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import urllib.request import io import zipfile import pandas # install pandas by "pip install pandas", or install Anaconda distribution (https://www.anaconda.com/) # Warning: the data processing techniques shown below are just for concept explanation, which are not best-...
from django import template from django.utils.safestring import mark_safe from django.utils.encoding import force_unicode import markdown from markitup.fields import render_func register = template.Library() @register.filter(name="markdown") def markdown_filter(value): """Processes the given value as Markdown, ...
import pandas as pd from google.cloud import storage import os from datetime import datetime, timedelta import joblib import yfinance as yf from datetime import datetime, timedelta import re from flask import Flask app = Flask(__name__) # In[2]: #!pip install simplejson #!pip install google.cloud #...
from app.api import pages from app.views.api import serialize from flask import request __author__ = 'fernando' def get_pages(): result = pages.get_pages(request.args.to_dict()) return serialize(result) def get_page(slug): result = pages.get_page(slug) return serialize(result)
import torch from torch.nn.parameter import Parameter from torch.optim import SGD import numpy as np import matplotlib.pyplot as plt from ConfigSpace.hyperparameters import UniformFloatHyperparameter from xbbo.configspace.space import DenseConfigurationSpace from xbbo.search_algorithm.pbt_optimizer import PBT from xb...
from . import db class SettingsModel(db.Model): __tablename__ = 'settings' id = db.Column(db.Integer, primary_key=True) created_at = db.Column(db.DateTime(timezone=True)) updated_at = db.Column(db.DateTime(timezone=True)) deleted_at = db.Column(db.DateTime(timezone=True), index=True) name = d...
from machine import Pin, RTC led = Pin(2, Pin.OUT, value=1) rtc = RTC()
from .handler import Handler, CHANNEL
import os import math import argparse import numpy as np from tabulate import tabulate def main(): parser = argparse.ArgumentParser() parser.add_argument('--res-dir', type=str, default='', help='Path to the results') parser.add_argument('--shot-list', type=int, nargs='+', default=[10], help='') args =...
from flask import session from flask_socketio import emit, join_room, leave_room import random from Crypto.Cipher import AES import os from .. import socketio @socketio.on('joined', namespace='/chat') def joined(message): """Sent by clients when they enter a room. A status message is broadcast to all people i...
# -*- coding: utf-8 -*- from openprocurement.caravan.runners.killer import ( GracefulKiller, ) class BaseRunner(object): def __init__(self): self.killer = GracefulKiller()
# Generated by Django 2.2.21 on 2021-05-19 06:59 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ("application_form", "0009_blank_rejection_description"), ] operations = [ migrations.RemoveField( model_name="hasoapartmentpriority", ...
"""Redis client module.""" from typing import AsyncIterator import aioredis from aioredis import Redis async def init_redis_pool(host: str, password: str) -> AsyncIterator[Redis]: pool = await aioredis.from_url(f"redis://{host}", password=password) yield pool pool.close() await pool.wait_closed()
import os import sys import time import shutil import json import numpy as np from PIL import Image from matplotlib import cm import matplotlib.pyplot as plt from skimage import io from tqdm.notebook import tqdm import torch import torch.nn as nn import torch.nn.functional as F import torchvision from torch.utils...
""" Target Problem: --------------- * A classifier for the diagnosis of Autism Spectrum Disorder (ASD) Proposed Solution (Machine Learning Pipeline): ---------------------------------------------- * LDA -> Voting Classifier Input to Proposed Solution: --------------------------- * Directories of training a...
# -*- coding: utf-8 -*- """Utilities for documentation.""" import textwrap from functools import partial from typing import Any, Callable, List, Optional, TypeVar, Union, cast import yaml __all__ = [ 'get_docdata', 'parse_docdata', ] X = TypeVar('X') DOCDATA_DUNDER = '__docdata__' def get_docdata(obj: X...
# -*- coding: utf-8 -*- """Predicate functions for nodes based on their incident edges' relations.""" from typing import Set from ...graph import BELGraph from ....constants import CAUSAL_RELATIONS, RELATION from ....dsl import BaseEntity __all__ = [ "has_in_edges", "has_causal_out_edges", "has_causal_i...
from dataclasses import asdict from dataclasses import dataclass from json import dumps from json import loads from json import load from statistics import pvariance from typing import List # NB: This is a set of models that make it easy to work w/ JSON files. They # may need to be re-implemented for SQL or some other...