edited_code
stringlengths
17
978k
original_code
stringlengths
17
978k
""" 火币合约接口 """ import re import urllib import base64 import json import zlib import hashlib import hmac import sys from copy import copy from datetime import datetime, timedelta from threading import Lock from typing import Sequence from vnpy.event import Event from vnpy.api.rest import RestClient, Request from vnpy....
""" 火币合约接口 """ import re import urllib import base64 import json import zlib import hashlib import hmac import sys from copy import copy from datetime import datetime, timedelta from threading import Lock from typing import Sequence from vnpy.event import Event from vnpy.api.rest import RestClient, Request from vnpy....
""" The piece of code that puts everything together. """ import random import sys import pyxel # When bumping to a higher Python requirement, please # modify this varible, basically to avoid users from # running with an old Python. EXPECTED_PYTHON = (3, 7) if sys.version_info < EXPECTED_PYTHON: s...
""" The piece of code that puts everything together. """ import random import sys import pyxel # When bumping to a higher Python requirement, please # modify this varible, basically to avoid users from # running with an old Python. EXPECTED_PYTHON = (3, 7) if sys.version_info < EXPECTED_PYTHON: s...
from datetime import datetime pixel_array_left = [18.25, 18.5, 24, 30.5, 29, 24.75, 26.25, 21, 26.25, 10.75, 16, 29, 34.75, 33, 41.75, 25.25, 13.75, 10, 17.5, 29.5, 18, 24.5, 21.5, 21.75, 10.75, 11.25, 25.75, 47.75, 39.5, 44.25, 46.25, 28.25, 11.75, 11, 16.25, 37.5, 41.25, 42.25, 42.5, 21, 11, 12, 20.25, 14.5, 15.75, ...
from datetime import datetime pixel_array_left = [18.25, 18.5, 24, 30.5, 29, 24.75, 26.25, 21, 26.25, 10.75, 16, 29, 34.75, 33, 41.75, 25.25, 13.75, 10, 17.5, 29.5, 18, 24.5, 21.5, 21.75, 10.75, 11.25, 25.75, 47.75, 39.5, 44.25, 46.25, 28.25, 11.75, 11, 16.25, 37.5, 41.25, 42.25, 42.5, 21, 11, 12, 20.25, 14.5, 15.75, ...
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
import os from typing import Dict, IO, Iterable, Union import pyteomics.mgf import spectrum_utils.spectrum as sus def get_spectra(source: Union[IO, str]) -> Iterable[sus.MsmsSpectrum]: """ Get the MS/MS spectra from the given MGF file. Parameters ---------- source : Union[IO, str] The MG...
import os from typing import Dict, IO, Iterable, Union import pyteomics.mgf import spectrum_utils.spectrum as sus def get_spectra(source: Union[IO, str]) -> Iterable[sus.MsmsSpectrum]: """ Get the MS/MS spectra from the given MGF file. Parameters ---------- source : Union[IO, str] The MG...
""" Author: Sara Blichner <s.m.blichner@geo.uio.no> Based on conv_ERA-interim.sh: # Author: Matthias Hummel <hummel@geo.uio.no> # and Inger Helene H. Karset <i.h.h.karset@geo.uio.no> # Date: 08.09.2016 # Modified by Moa Sporre 14.11.2017 """ import os import sys from glob import glob from pathlib import Path from sub...
""" Author: Sara Blichner <s.m.blichner@geo.uio.no> Based on conv_ERA-interim.sh: # Author: Matthias Hummel <hummel@geo.uio.no> # and Inger Helene H. Karset <i.h.h.karset@geo.uio.no> # Date: 08.09.2016 # Modified by Moa Sporre 14.11.2017 """ import os import sys from glob import glob from pathlib import Path from sub...
import os import pickle as pkl import typing from abc import abstractmethod from functools import lru_cache, partial from pathlib import Path import numpy as np from scipy.io import loadmat from sklearn.preprocessing import LabelEncoder, StandardScaler from braincode.abstract import Object from braincode.benchmarks i...
import os import pickle as pkl import typing from abc import abstractmethod from functools import lru_cache, partial from pathlib import Path import numpy as np from scipy.io import loadmat from sklearn.preprocessing import LabelEncoder, StandardScaler from braincode.abstract import Object from braincode.benchmarks i...
""" A convenient class to hold: - dataset creation - model train procedure - inference on dataset - evaluating predictions - and more """ #pylint: disable=import-error, no-name-in-module, wrong-import-position, protected-access import os import gc import logging from time import perf_counter from a...
""" A convenient class to hold: - dataset creation - model train procedure - inference on dataset - evaluating predictions - and more """ #pylint: disable=import-error, no-name-in-module, wrong-import-position, protected-access import os import gc import logging from time import perf_counter from a...
'''This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, dict, list, set, and tuple. * namedtuple factory function for creating tuple subclasses with named fields * deque list-like container with fast appends and pops on either end * Cha...
'''This module implements specialized container datatypes providing alternatives to Python's general purpose built-in containers, dict, list, set, and tuple. * namedtuple factory function for creating tuple subclasses with named fields * deque list-like container with fast appends and pops on either end * Cha...
import random from timeit import timeit from typing import List, Tuple from quicksort import quicksort_my_version, quicksort_book_version def create_random_list(numbers: int, range_: Tuple[int, int], duplicates: bool = True) -> List[int]: """ Generates list of random, unsorted numbers from given range. :...
import random from timeit import timeit from typing import List, Tuple from quicksort import quicksort_my_version, quicksort_book_version def create_random_list(numbers: int, range_: Tuple[int, int], duplicates: bool = True) -> List[int]: """ Generates list of random, unsorted numbers from given range. :...
"""Command line functions for calling the root mfa command""" from __future__ import annotations import argparse import atexit import multiprocessing as mp import sys import time from datetime import datetime from typing import TYPE_CHECKING from montreal_forced_aligner.command_line.adapt import run_adapt_model from ...
"""Command line functions for calling the root mfa command""" from __future__ import annotations import argparse import atexit import multiprocessing as mp import sys import time from datetime import datetime from typing import TYPE_CHECKING from montreal_forced_aligner.command_line.adapt import run_adapt_model from ...
""" PyGMT is a library for processing geospatial and geophysical data and making publication quality maps and figures. It provides a Pythonic interface for the Generic Mapping Tools (GMT), a command-line program widely used in the Earth Sciences. Besides making GMT more accessible to new users, PyGMT aims to provide in...
""" PyGMT is a library for processing geospatial and geophysical data and making publication quality maps and figures. It provides a Pythonic interface for the Generic Mapping Tools (GMT), a command-line program widely used in the Earth Sciences. Besides making GMT more accessible to new users, PyGMT aims to provide in...
import os import subprocess import sys import zipfile if (os.path.exists("build")): dl=[] for r,ndl,fl in os.walk("build"): dl=[os.path.join(r,k) for k in ndl]+dl for f in fl: os.remove(os.path.join(r,f)) for k in dl: os.rmdir(k) else: os.mkdir("build") cd=os.getcwd() os.chdir("src") jfl=[] for r,_,fl i...
import os import subprocess import sys import zipfile if (os.path.exists("build")): dl=[] for r,ndl,fl in os.walk("build"): dl=[os.path.join(r,k) for k in ndl]+dl for f in fl: os.remove(os.path.join(r,f)) for k in dl: os.rmdir(k) else: os.mkdir("build") cd=os.getcwd() os.chdir("src") jfl=[] for r,_,fl i...
from argparse import ArgumentParser, Namespace from pathlib import Path from gwpycore import basic_cli_parser from {{ cookiecutter.tool_name_slug }}.core.{{ cookiecutter.tool_name_slug }}_filter import {{ cookiecutter.tool_name_camel_case }}Filter def load_command_line(version: str, args) -> Namespace: """ Par...
from argparse import ArgumentParser, Namespace from pathlib import Path from gwpycore import basic_cli_parser from {{ cookiecutter.tool_name_slug }}.core.{{ cookiecutter.tool_name_slug }}_filter import {{ cookiecutter.tool_name_camel_case }}Filter def load_command_line(version: str, args) -> Namespace: """ Par...
from saltproc import DepcodeSerpent from saltproc import Simulation from saltproc import Materialflow from saltproc import Process from saltproc import Reactor from saltproc import Sparger from saltproc import Separator # from depcode import Depcode # from simulation import Simulation # from materialflow import Materia...
from saltproc import DepcodeSerpent from saltproc import Simulation from saltproc import Materialflow from saltproc import Process from saltproc import Reactor from saltproc import Sparger from saltproc import Separator # from depcode import Depcode # from simulation import Simulation # from materialflow import Materia...
from typing import Any, Dict, List, Optional import aiohttp from apple.cmds.units import units from apple.consensus.block_record import BlockRecord from apple.rpc.farmer_rpc_client import FarmerRpcClient from apple.rpc.full_node_rpc_client import FullNodeRpcClient from apple.rpc.wallet_rpc_client import WalletRpcClie...
from typing import Any, Dict, List, Optional import aiohttp from apple.cmds.units import units from apple.consensus.block_record import BlockRecord from apple.rpc.farmer_rpc_client import FarmerRpcClient from apple.rpc.full_node_rpc_client import FullNodeRpcClient from apple.rpc.wallet_rpc_client import WalletRpcClie...
import logging from traceback import format_exception from tinydb import TinyDB, Query import nextcord from nextcord.ext import commands def check_ping(guild_id_var): db = TinyDB('databases/pings.json') query = Query() values = str(list(map(lambda entry: entry["pingstate"], db.se...
import logging from traceback import format_exception from tinydb import TinyDB, Query import nextcord from nextcord.ext import commands def check_ping(guild_id_var): db = TinyDB('databases/pings.json') query = Query() values = str(list(map(lambda entry: entry["pingstate"], db.se...
from vkbottle.rule import FromMe from vkbottle.user import Blueprint, Message from idm_lp import const from idm_lp.database import Database from idm_lp.logger import logger_decorator from idm_lp.utils import edit_message user = Blueprint( name='auto_infection_blueprint' ) @user.on.message_handler(FromMe(), text...
from vkbottle.rule import FromMe from vkbottle.user import Blueprint, Message from idm_lp import const from idm_lp.database import Database from idm_lp.logger import logger_decorator from idm_lp.utils import edit_message user = Blueprint( name='auto_infection_blueprint' ) @user.on.message_handler(FromMe(), text...
import logging import typing from eth_utils import remove_0x_prefix from web3.utils.events import get_event_data from ocean_lib.models import balancer_constants from .btoken import BToken from ocean_lib.ocean import util from ocean_lib.web3_internal.wallet import Wallet logger = logging.getLogger(__name__) class B...
import logging import typing from eth_utils import remove_0x_prefix from web3.utils.events import get_event_data from ocean_lib.models import balancer_constants from .btoken import BToken from ocean_lib.ocean import util from ocean_lib.web3_internal.wallet import Wallet logger = logging.getLogger(__name__) class B...
""" Client ------ The database client module. """ from contextlib import contextmanager import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.engine.url import make_url from sqlalchemy.orm.exc import UnmappedError from sqlalchemy.orm.session import Session from . import core from .model import declarat...
""" Client ------ The database client module. """ from contextlib import contextmanager import sqlalchemy as sa from sqlalchemy import orm from sqlalchemy.engine.url import make_url from sqlalchemy.orm.exc import UnmappedError from sqlalchemy.orm.session import Session from . import core from .model import declarat...
"""build: Build documentation, requirements.txt, and run poetry build.""" from __future__ import annotations from pathlib import Path from typing import Any, cast import tomlkit import tomlkit.items from .utils import ANSI, _doSysExec, _getPyproject, _setPyproject def getProcVer(version: str) -> str: """Process ...
"""build: Build documentation, requirements.txt, and run poetry build.""" from __future__ import annotations from pathlib import Path from typing import Any, cast import tomlkit import tomlkit.items from .utils import ANSI, _doSysExec, _getPyproject, _setPyproject def getProcVer(version: str) -> str: """Process ...
# Modulo faq.py v1 #///---- Imports ----/// import re import os import logging from discord.ext import commands from faunadb import query as q from faunadb.objects import Ref from faunadb.client import FaunaClient #///---- Log ----/// log = logging.getLogger(__name__) #///---- Clase ----/// class FAQ(commands.Cog):...
# Modulo faq.py v1 #///---- Imports ----/// import re import os import logging from discord.ext import commands from faunadb import query as q from faunadb.objects import Ref from faunadb.client import FaunaClient #///---- Log ----/// log = logging.getLogger(__name__) #///---- Clase ----/// class FAQ(commands.Cog):...
import os import shutil from typing import NoReturn, Union from client.session import Session from common.module_base import ModuleBase from common.share_helper import share_drive_letter from common.update_returns import EmitError from messages import ExecutionRequest, ExecutionDone, ExecutionResponse from messages.wo...
import os import shutil from typing import NoReturn, Union from client.session import Session from common.module_base import ModuleBase from common.share_helper import share_drive_letter from common.update_returns import EmitError from messages import ExecutionRequest, ExecutionDone, ExecutionResponse from messages.wo...
import numpy as np from nemf import caller from nemf import worker from nemf.interaction_functions import * from copy import deepcopy import yaml # Model_Classes class model_class: # initialization methods # they are only used when a new model_class is created def __init__(self,model_path,ref_data_path=None): ...
import numpy as np from nemf import caller from nemf import worker from nemf.interaction_functions import * from copy import deepcopy import yaml # Model_Classes class model_class: # initialization methods # they are only used when a new model_class is created def __init__(self,model_path,ref_data_path=None): ...
"""Tests for the RunTaskCommand class""" from cumulusci.cli.runtime import CliRuntime from cumulusci.cli.cci import RunTaskCommand import click import pytest from unittest.mock import Mock, patch from cumulusci.cli import cci from cumulusci.core.exceptions import CumulusCIUsageError from cumulusci.cli.tests.utils imp...
"""Tests for the RunTaskCommand class""" from cumulusci.cli.runtime import CliRuntime from cumulusci.cli.cci import RunTaskCommand import click import pytest from unittest.mock import Mock, patch from cumulusci.cli import cci from cumulusci.core.exceptions import CumulusCIUsageError from cumulusci.cli.tests.utils imp...
from typing import Any, List, Dict, Tuple import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from torchvision import datasets, transforms import nni from ..interface import BaseTrainer from ...utils import register_trainer def get_default_transform(dataset: str) -> Any: ...
from typing import Any, List, Dict, Tuple import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader from torchvision import datasets, transforms import nni from ..interface import BaseTrainer from ...utils import register_trainer def get_default_transform(dataset: str) -> Any: ...
import asyncio from collections import defaultdict from enum import Enum from typing import Any from typing import DefaultDict from typing import Dict from typing import Iterable from typing import List from typing import Mapping from typing import MutableMapping from typing import Optional from typing import Sequence ...
import asyncio from collections import defaultdict from enum import Enum from typing import Any from typing import DefaultDict from typing import Dict from typing import Iterable from typing import List from typing import Mapping from typing import MutableMapping from typing import Optional from typing import Sequence ...
from django.conf import settings from django.contrib import messages from django.core.mail import send_mail from django.db import transaction from django.db.models import Count from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect, render from django.template.defaultfilters impor...
from django.conf import settings from django.contrib import messages from django.core.mail import send_mail from django.db import transaction from django.db.models import Count from django.http import HttpResponse from django.shortcuts import get_object_or_404, redirect, render from django.template.defaultfilters impor...
from __future__ import annotations import collections import datetime import functools import json import os import re import urllib.request from typing import Any from typing import Counter from typing import Mapping from typing import Pattern from typing import Sequence from bot.config import Config from bot.data i...
from __future__ import annotations import collections import datetime import functools import json import os import re import urllib.request from typing import Any from typing import Counter from typing import Mapping from typing import Pattern from typing import Sequence from bot.config import Config from bot.data i...
# Original work Copyright 2021-2022, Daniel Biehl (Apache License V2) # Original work Copyright 2016-2020 Robot Framework Foundation (Apache License V2) # See ThirdPartyNotices.txt in the project root for license information. # All modifications Copyright (c) Robocorp Technologies Inc. # All rights reserved. # # Licens...
# Original work Copyright 2021-2022, Daniel Biehl (Apache License V2) # Original work Copyright 2016-2020 Robot Framework Foundation (Apache License V2) # See ThirdPartyNotices.txt in the project root for license information. # All modifications Copyright (c) Robocorp Technologies Inc. # All rights reserved. # # Licens...
""" ASGI config for hear_me_django_app project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/asgi/ """ import os import sys from pathlib import Path from django.core.asgi import get_asgi_a...
""" ASGI config for hear_me_django_app project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/dev/howto/deployment/asgi/ """ import os import sys from pathlib import Path from django.core.asgi import get_asgi_a...
#!/usr/bin/env python3 from PIL import Image, ImageDraw, ImageFont, IptcImagePlugin, ExifTags from datetime import datetime from pathlib import Path import imghdr import time # Check if 'desired' directory exists, if not, create it! def dir_check_make(dir_path, dir_name): if not Path(dir_path).is_dir(): ...
#!/usr/bin/env python3 from PIL import Image, ImageDraw, ImageFont, IptcImagePlugin, ExifTags from datetime import datetime from pathlib import Path import imghdr import time # Check if 'desired' directory exists, if not, create it! def dir_check_make(dir_path, dir_name): if not Path(dir_path).is_dir(): ...
import os import h5py import yaml import logging import numpy as np from PIL import Image from scipy.spatial.transform import Rotation as R from progress.bar import Bar from multiprocessing import Pool, cpu_count from omegaconf import OmegaConf from tools.utils import io # from tools.visualization import Viewer from ...
import os import h5py import yaml import logging import numpy as np from PIL import Image from scipy.spatial.transform import Rotation as R from progress.bar import Bar from multiprocessing import Pool, cpu_count from omegaconf import OmegaConf from tools.utils import io # from tools.visualization import Viewer from ...
# -*- coding: utf-8 -*- from django.contrib.contenttypes.fields import GenericRelation from django.contrib.contenttypes.models import ContentType from django.db.models import ManyToManyRel from django.db.models.fields.related import RelatedField, lazy_related_operation from django.db.models.query_utils import PathInfo ...
# -*- coding: utf-8 -*- from django.contrib.contenttypes.fields import GenericRelation from django.contrib.contenttypes.models import ContentType from django.db.models import ManyToManyRel from django.db.models.fields.related import RelatedField, lazy_related_operation from django.db.models.query_utils import PathInfo ...
import datetime from wildfirepy.coordinates.util import SinusoidalCoordinate from wildfirepy.net.usgs.usgs_downloader import AbstractUSGSDownloader from wildfirepy.net.util.usgs import VIIRSHtmlParser __all__ = ['VIIRSBurntAreaDownloader'] class Viirs(AbstractUSGSDownloader): """ An Abstract Base Class Down...
import datetime from wildfirepy.coordinates.util import SinusoidalCoordinate from wildfirepy.net.usgs.usgs_downloader import AbstractUSGSDownloader from wildfirepy.net.util.usgs import VIIRSHtmlParser __all__ = ['VIIRSBurntAreaDownloader'] class Viirs(AbstractUSGSDownloader): """ An Abstract Base Class Down...
import datetime import json import requests from django.contrib.sessions.models import Session from rest_framework import status from rest_framework.exceptions import ValidationError from rest_framework.response import Response from connect.utils import attempt_json_loads from iotconnect.classes import AdHocAdapter f...
import datetime import json import requests from django.contrib.sessions.models import Session from rest_framework import status from rest_framework.exceptions import ValidationError from rest_framework.response import Response from connect.utils import attempt_json_loads from iotconnect.classes import AdHocAdapter f...
#!/usr/bin/python # Copyright 2021 Expedient # # 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 agr...
#!/usr/bin/python # Copyright 2021 Expedient # # 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 agr...
from pygears import gear from pygears.sim import sim_log from pygears.typing import Tuple, Uint TAddr = Uint['w_addr'] TData = Uint['xlen'] TReadRequest = TAddr TWriteRequest = Tuple[{'addr': TAddr, 'data': TData}] @gear async def register_file_write(request: TWriteRequest, *, storage): async with request as req...
from pygears import gear from pygears.sim import sim_log from pygears.typing import Tuple, Uint TAddr = Uint['w_addr'] TData = Uint['xlen'] TReadRequest = TAddr TWriteRequest = Tuple[{'addr': TAddr, 'data': TData}] @gear async def register_file_write(request: TWriteRequest, *, storage): async with request as req...
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from xdrlib import Packer, Unpacker from .end_sponsoring_future_reserves_result_code import ( EndSponsoringFutureReservesResultCode, ) from ..exceptions import ValueError __all__ = ["EndSponsoringFutureReserv...
# This is an automatically generated file. # DO NOT EDIT or your changes may be overwritten import base64 from xdrlib import Packer, Unpacker from .end_sponsoring_future_reserves_result_code import ( EndSponsoringFutureReservesResultCode, ) from ..exceptions import ValueError __all__ = ["EndSponsoringFutureReserv...
from pyzenfolio3.exceptions import APIError VALID_ENUM = { 'AccessMask': [ 'None', 'HideDateCreated', 'HideDateModified', 'HideDateTaken', 'HideMetaData', 'HideUserStats', 'HideVisits', 'NoCollections', 'NoPrivateSearch', 'NoPublicSea...
from pyzenfolio3.exceptions import APIError VALID_ENUM = { 'AccessMask': [ 'None', 'HideDateCreated', 'HideDateModified', 'HideDateTaken', 'HideMetaData', 'HideUserStats', 'HideVisits', 'NoCollections', 'NoPrivateSearch', 'NoPublicSea...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module containing commands related to the \ Information Superhighway (yes, Internet). """ from datetim...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module containing commands related to the \ Information Superhighway (yes, Internet). """ from datetim...
from __future__ import annotations import logging import os import subprocess import tempfile import textwrap import threading from logging import Logger from pathlib import Path from typing import TYPE_CHECKING, Any, Iterable, Mapping import tomli from pep517.wrappers import Pep517HookCaller from pip._vendor.pkg_res...
from __future__ import annotations import logging import os import subprocess import tempfile import textwrap import threading from logging import Logger from pathlib import Path from typing import TYPE_CHECKING, Any, Iterable, Mapping import tomli from pep517.wrappers import Pep517HookCaller from pip._vendor.pkg_res...
# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] # snippet-sourcedescription:[receive_message.py demonstrates how to retrieve messages from an Amazon SQS queue.] # snippet-service:[sqs] # snippet-keyword:[Amazon Simple Queue Service (Amazon SQS)] # snippet-keyword:[Python] #...
# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.] # snippet-sourcedescription:[receive_message.py demonstrates how to retrieve messages from an Amazon SQS queue.] # snippet-service:[sqs] # snippet-keyword:[Amazon Simple Queue Service (Amazon SQS)] # snippet-keyword:[Python] #...
# Copyright 2020 IBM Corporation # # 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, ...
# Copyright 2020 IBM Corporation # # 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, ...
"""Make / Download Telegram Sticker Packs without installing Third Party applications Available Commands: .kang [Optional Emoji] .packinfo .loda {for get stickers in a zip file}""" from telethon import events from io import BytesIO from PIL import Image import asyncio import datetime from collections import defaultdict...
"""Make / Download Telegram Sticker Packs without installing Third Party applications Available Commands: .kang [Optional Emoji] .packinfo .loda {for get stickers in a zip file}""" from telethon import events from io import BytesIO from PIL import Image import asyncio import datetime from collections import defaultdict...
""" ISA datatype See https://github.com/ISA-tools """ import json import logging import os import os.path import re import shutil import tempfile # Imports isatab after turning off warnings inside logger settings to avoid pandas warning making uploads fail. logging.getLogger("isatools.isatab").setLevel(logging.ERROR...
""" ISA datatype See https://github.com/ISA-tools """ import json import logging import os import os.path import re import shutil import tempfile # Imports isatab after turning off warnings inside logger settings to avoid pandas warning making uploads fail. logging.getLogger("isatools.isatab").setLevel(logging.ERROR...
#!/usr/bin/env python3 import logging import coloredlogs import json import requests from datetime import datetime from packaging import version log_level = None def get_logger(name=__name__, verbosity=None): ''' Colored logging :param name: logger name (use __name__ variable) :param verbosity: ...
#!/usr/bin/env python3 import logging import coloredlogs import json import requests from datetime import datetime from packaging import version log_level = None def get_logger(name=__name__, verbosity=None): ''' Colored logging :param name: logger name (use __name__ variable) :param verbosity: ...
# -*- coding: utf-8 -*- # ███╗ ███╗ █████╗ ███╗ ██╗██╗ ██████╗ ██████╗ ███╗ ███╗██╗ ██████╗ # ████╗ ████║██╔══██╗████╗ ██║██║██╔════╝██╔═══██╗████╗ ████║██║██╔═══██╗ # ██╔████╔██║███████║██╔██╗ ██║██║██║ ██║ ██║██╔████╔██║██║██║ ██║ # ██║╚██╔╝██║██╔══██║██║╚██╗██║██║██║ ██║ ██║██║╚██╔╝██║██║██║ █...
# -*- coding: utf-8 -*- # ███╗ ███╗ █████╗ ███╗ ██╗██╗ ██████╗ ██████╗ ███╗ ███╗██╗ ██████╗ # ████╗ ████║██╔══██╗████╗ ██║██║██╔════╝██╔═══██╗████╗ ████║██║██╔═══██╗ # ██╔████╔██║███████║██╔██╗ ██║██║██║ ██║ ██║██╔████╔██║██║██║ ██║ # ██║╚██╔╝██║██╔══██║██║╚██╗██║██║██║ ██║ ██║██║╚██╔╝██║██║██║ █...
# -*- coding: utf-8 -*- # standard library imports import json import os import re import sys import subprocess from glob import glob from pathlib import Path # first-party imports import click from loguru import logger from sequencetools.tools.basic_fasta_stats import basic_fasta_stats from sequencetools.helpers.file...
# -*- coding: utf-8 -*- # standard library imports import json import os import re import sys import subprocess from glob import glob from pathlib import Path # first-party imports import click from loguru import logger from sequencetools.tools.basic_fasta_stats import basic_fasta_stats from sequencetools.helpers.file...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals from os import path from collections import OrderedDict import numpy as np from scipy import stats import pandas as pd from sklearn import model_selection, metrics from . import six, utils ...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals from os import path from collections import OrderedDict import numpy as np from scipy import stats import pandas as pd from sklearn import model_selection, metrics from . import six, utils ...
"""Support for monitoring emoncms feeds.""" from datetime import timedelta import logging import requests import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, ) from homeassistant.const import ( ...
"""Support for monitoring emoncms feeds.""" from datetime import timedelta import logging import requests import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, STATE_CLASS_MEASUREMENT, STATE_CLASS_TOTAL_INCREASING, SensorEntity, ) from homeassistant.const import ( ...
# -*- coding: utf-8 -*- # # Copyright (c) 2018 Leland Stanford Junior University # Copyright (c) 2018 The Regents of the University of California # # This file is part of the SimCenter Backend Applications # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that...
# -*- coding: utf-8 -*- # # Copyright (c) 2018 Leland Stanford Junior University # Copyright (c) 2018 The Regents of the University of California # # This file is part of the SimCenter Backend Applications # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that...
import pandas as pd import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from matplotlib.ticker import StrMethodFormatter from sklearn.model_selection import train_test_split from sklearn import svm from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import mean_...
import pandas as pd import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from matplotlib.ticker import StrMethodFormatter from sklearn.model_selection import train_test_split from sklearn import svm from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import mean_...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.b (the "License"); # you may not use this file except in compliance with the License. # # """ Userbot module for having some fun with people. """ import asyncio import random import re import time from co...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.b (the "License"); # you may not use this file except in compliance with the License. # # """ Userbot module for having some fun with people. """ import asyncio import random import re import time from co...
""" BaseFilter classes and exception handling """ import copy import logging from typing import List, Mapping, Any from abc import ABC, abstractmethod from asldro.utils.general import map_dict logger = logging.getLogger(__name__) class BaseFilterException(Exception): """ Exceptions for this modules """ de...
""" BaseFilter classes and exception handling """ import copy import logging from typing import List, Mapping, Any from abc import ABC, abstractmethod from asldro.utils.general import map_dict logger = logging.getLogger(__name__) class BaseFilterException(Exception): """ Exceptions for this modules """ de...
import os import re WIKI_PATH = "../../../agk-steam-plugin.wiki/" error_count = 0 """ Page Tag Information: @page The rest of the line is the page name/Steam class for the file. Additional lines are for the page description. Method Tag Information @desc The method description. Can be multiple lines...
import os import re WIKI_PATH = "../../../agk-steam-plugin.wiki/" error_count = 0 """ Page Tag Information: @page The rest of the line is the page name/Steam class for the file. Additional lines are for the page description. Method Tag Information @desc The method description. Can be multiple lines...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 """ This provides a small set of effect handlers in NumPyro that are modeled after Pyro's `poutine <http://docs.pyro.ai/en/stable/poutine.html>`_ module. For a tutorial on effect handlers more generally, readers are encouraged to read ...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 """ This provides a small set of effect handlers in NumPyro that are modeled after Pyro's `poutine <http://docs.pyro.ai/en/stable/poutine.html>`_ module. For a tutorial on effect handlers more generally, readers are encouraged to read ...
# -*- coding: utf-8 -*- """Run a thermodynamics calculation in MOPAC""" import logging import seamm import seamm_util.printing as printing from seamm_util import units_class from seamm_util.printing import FormattedText as __ import mopac_step logger = logging.getLogger(__name__) job = printing.getPrinter() printer ...
# -*- coding: utf-8 -*- """Run a thermodynamics calculation in MOPAC""" import logging import seamm import seamm_util.printing as printing from seamm_util import units_class from seamm_util.printing import FormattedText as __ import mopac_step logger = logging.getLogger(__name__) job = printing.getPrinter() printer ...
import pygame from json import load from objects import Pawn achievements = load( open('.achievements.json') ) class Validator: """ Class used to validate movements and victory checking (a judge, basically) Parameters ---------- group : list[Pawn] A list of Pawn objects that are actually i...
import pygame from json import load from objects import Pawn achievements = load( open('.achievements.json') ) class Validator: """ Class used to validate movements and victory checking (a judge, basically) Parameters ---------- group : list[Pawn] A list of Pawn objects that are actually i...
""" This module is imported in the component_gallery.py and demonstrates how to style a Dash DataTable to look better with Bootstrap themes. To keep things organized: long descriptions and code examples are in text.py cards like a list of links are created in cheatsheet.py and imported here Cards for a light ...
""" This module is imported in the component_gallery.py and demonstrates how to style a Dash DataTable to look better with Bootstrap themes. To keep things organized: long descriptions and code examples are in text.py cards like a list of links are created in cheatsheet.py and imported here Cards for a light ...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Time: 2021-10-20 1:25 下午 Author: huayang Subject: """ from typing import * from itertools import islice import torch import torch.nn as nn from torch import Tensor from huaytools.pytorch.train.trainer import Trainer from huaytools.pytorch.train.callback import Ca...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Time: 2021-10-20 1:25 下午 Author: huayang Subject: """ from typing import * from itertools import islice import torch import torch.nn as nn from torch import Tensor from huaytools.pytorch.train.trainer import Trainer from huaytools.pytorch.train.callback import Ca...
import os import sys from threading import Thread from time import sleep, time from tkinter import Button, Entry, Frame, IntVar, Label, PhotoImage, StringVar, Tk from typing import Tuple from keyboard import add_hotkey, on_press_key, press_and_release, read_hotkey, remove_hotkey, unhook from mouse import click def r...
import os import sys from threading import Thread from time import sleep, time from tkinter import Button, Entry, Frame, IntVar, Label, PhotoImage, StringVar, Tk from typing import Tuple from keyboard import add_hotkey, on_press_key, press_and_release, read_hotkey, remove_hotkey, unhook from mouse import click def r...
import os import string import util import datetime import newdb import datafiles #import config database = newdb.get_db() __CAPITALIZATION_UPDATE_THRESHOLD = 0.03 # 5% def __capEquals(previous, new): if previous == 0: if new == 0: return True else: return False else: return abs(new /...
import os import string import util import datetime import newdb import datafiles #import config database = newdb.get_db() __CAPITALIZATION_UPDATE_THRESHOLD = 0.03 # 5% def __capEquals(previous, new): if previous == 0: if new == 0: return True else: return False else: return abs(new /...
import io from datetime import datetime from typing import Union, Any, Callable, Tuple, List, Coroutine, Optional from uuid import UUID import discord from PIL import Image from discord import Embed, User, Member, Permissions __all__ = [ 'create_embed', 'guess_user_nitro_status', 'user_friendly_dt', '...
import io from datetime import datetime from typing import Union, Any, Callable, Tuple, List, Coroutine, Optional from uuid import UUID import discord from PIL import Image from discord import Embed, User, Member, Permissions __all__ = [ 'create_embed', 'guess_user_nitro_status', 'user_friendly_dt', '...
""" MIT License Copyright (c) 2020 Myer 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, ...
""" MIT License Copyright (c) 2020 Myer 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, ...
from collections import Counter from copy import copy import json import numpy as np import re import logging from dadmatools.models.common.utils import ud_scores, harmonic_mean from dadmatools.utils.conll import CoNLL from dadmatools.models.common.doc import * logger = logging.getLogger('stanza') def load_mwt_dict(...
from collections import Counter from copy import copy import json import numpy as np import re import logging from dadmatools.models.common.utils import ud_scores, harmonic_mean from dadmatools.utils.conll import CoNLL from dadmatools.models.common.doc import * logger = logging.getLogger('stanza') def load_mwt_dict(...
# coding: utf8 from __future__ import unicode_literals import os from csv import reader import unittest from tempfile import mkdtemp from shutil import rmtree from six import PY3, text_type, binary_type from dataset import connect from datafreeze.app import freeze from datafreeze.format.fcsv import value_to_str from...
# coding: utf8 from __future__ import unicode_literals import os from csv import reader import unittest from tempfile import mkdtemp from shutil import rmtree from six import PY3, text_type, binary_type from dataset import connect from datafreeze.app import freeze from datafreeze.format.fcsv import value_to_str from...
from typing import ( Any, ClassVar, Dict, List, Sequence, Tuple, Type, Union, no_type_check, ) import anyio from sqlalchemy import Column, func, inspect, select from sqlalchemy.engine.base import Engine from sqlalchemy.exc import NoInspectionAvailable from sqlalchemy.ext.asyncio imp...
from typing import ( Any, ClassVar, Dict, List, Sequence, Tuple, Type, Union, no_type_check, ) import anyio from sqlalchemy import Column, func, inspect, select from sqlalchemy.engine.base import Engine from sqlalchemy.exc import NoInspectionAvailable from sqlalchemy.ext.asyncio imp...
from trading_ig.rest import IGService, IGException, ApiExceededException from trading_ig.config import config import pandas as pd from datetime import datetime, timedelta import pytest from random import randint, choice import logging import time from tenacity import Retrying, wait_exponential, retry_if_exception_type ...
from trading_ig.rest import IGService, IGException, ApiExceededException from trading_ig.config import config import pandas as pd from datetime import datetime, timedelta import pytest from random import randint, choice import logging import time from tenacity import Retrying, wait_exponential, retry_if_exception_type ...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module containing commands related to android""" import asyncio import re import os import time import mat...
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. # """ Userbot module containing commands related to android""" import asyncio import re import os import time import mat...
aluno={} aluno['nome']=str(input('Nome: ')) aluno['media']=float(input(f'Média de {aluno['nome']}: ')) if aluno['media'] < 7.0: aluno['situacao']='Reprovado' elif 5 <= aluno['media'] <7: aluno['situacao']='Recuperação' else: aluno['situacao']='Aprovado' for k, v in aluno.items(): print(f' - {k} é i...
aluno={} aluno['nome']=str(input('Nome: ')) aluno['media']=float(input(f'Média de {aluno["nome"]}: ')) if aluno['media'] < 7.0: aluno['situacao']='Reprovado' elif 5 <= aluno['media'] <7: aluno['situacao']='Recuperação' else: aluno['situacao']='Aprovado' for k, v in aluno.items(): print(f' - {k} é i...
import base64 import json import falcon import time import pymongo from datetime import datetime from dateutil.parser import parse from history import conf, Logger from dojot.module import Messenger, Config, Auth from wsgiref import simple_server # NOQA import os LOGGER = Logger.Log(conf.log_level).color_log() clas...
import base64 import json import falcon import time import pymongo from datetime import datetime from dateutil.parser import parse from history import conf, Logger from dojot.module import Messenger, Config, Auth from wsgiref import simple_server # NOQA import os LOGGER = Logger.Log(conf.log_level).color_log() clas...
import numpy as np import gym import wandb from rl_credit.examples.environment import ( DISCOUNT_FACTOR, VaryGiftsGoalEnv, ) from rl_credit.examples.train import train DISCOUNT_TIMESCALE = int(np.round(1/(1 - DISCOUNT_FACTOR))) DELAY_STEPS = 0.5 * DISCOUNT_TIMESCALE ########################################...
import numpy as np import gym import wandb from rl_credit.examples.environment import ( DISCOUNT_FACTOR, VaryGiftsGoalEnv, ) from rl_credit.examples.train import train DISCOUNT_TIMESCALE = int(np.round(1/(1 - DISCOUNT_FACTOR))) DELAY_STEPS = 0.5 * DISCOUNT_TIMESCALE ########################################...
# -*- coding:utf-8 -*- import os import logging from pathlib import Path import random import numpy as np import torch import torch.optim as optim from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from .util.progressbar import ProgressBar from .util.vocab import...
# -*- coding:utf-8 -*- import os import logging from pathlib import Path import random import numpy as np import torch import torch.optim as optim from torch.optim.lr_scheduler import ReduceLROnPlateau from torch.utils.tensorboard import SummaryWriter from .util.progressbar import ProgressBar from .util.vocab import...
import glob import json import logging import os import re import sys import textwrap from importlib.metadata import metadata, requires from typing import Any, Dict, List, Optional import click from pydantic import Field from pydantic.dataclasses import dataclass from datahub.configuration.common import ConfigModel f...
import glob import json import logging import os import re import sys import textwrap from importlib.metadata import metadata, requires from typing import Any, Dict, List, Optional import click from pydantic import Field from pydantic.dataclasses import dataclass from datahub.configuration.common import ConfigModel f...
"""Module with some useful decorators.""" import inspect import logging from typing import Callable, Tuple, Optional, Any, Union, Type from functools import wraps ExceptionType = Union[Type[Exception], Tuple[Type[Exception], ...]] class NonExistingException(Exception): """Stub for exception_handler.""" def e...
"""Module with some useful decorators.""" import inspect import logging from typing import Callable, Tuple, Optional, Any, Union, Type from functools import wraps ExceptionType = Union[Type[Exception], Tuple[Type[Exception], ...]] class NonExistingException(Exception): """Stub for exception_handler.""" def e...
"""Backup manager for the Backup integration.""" from __future__ import annotations from dataclasses import asdict, dataclass import hashlib import json from pathlib import Path import tarfile from tarfile import TarError from tempfile import TemporaryDirectory from typing import Any from securetar import SecureTarFi...
"""Backup manager for the Backup integration.""" from __future__ import annotations from dataclasses import asdict, dataclass import hashlib import json from pathlib import Path import tarfile from tarfile import TarError from tempfile import TemporaryDirectory from typing import Any from securetar import SecureTarFi...
import os import time from anadroid.Types import TESTING_FRAMEWORK, PROFILER from anadroid.testing_framework.AbstractTestingFramework import AbstractTestingFramework from anadroid.testing_framework.work.MonkeyWorkUnit import MonkeyWorkUnit from anadroid.testing_framework.work.WorkLoad import WorkLoad from anadroid.uti...
import os import time from anadroid.Types import TESTING_FRAMEWORK, PROFILER from anadroid.testing_framework.AbstractTestingFramework import AbstractTestingFramework from anadroid.testing_framework.work.MonkeyWorkUnit import MonkeyWorkUnit from anadroid.testing_framework.work.WorkLoad import WorkLoad from anadroid.uti...
# Smallest Difference # def smallestDifference(arrayOne=[], arrayTwo=[]): # ''' # Solution 1 - Brute force (aka: Naive approach) # # O(n^2) time | O(1) space # # arrayOne: a list of integers # arrayTwo: a list of integers # return: a list of two integers # ''' # closestPair = [] # c...
# Smallest Difference # def smallestDifference(arrayOne=[], arrayTwo=[]): # ''' # Solution 1 - Brute force (aka: Naive approach) # # O(n^2) time | O(1) space # # arrayOne: a list of integers # arrayTwo: a list of integers # return: a list of two integers # ''' # closestPair = [] # c...
from rest_framework.views import APIView import rest_framework.status as status from rest_framework.response import Response from rest_framework.request import Request from podcaststore_api.utils import json_or_raise from podcaststore_api.models.user import UserSerializer from django.contrib.auth.models import User fro...
from rest_framework.views import APIView import rest_framework.status as status from rest_framework.response import Response from rest_framework.request import Request from podcaststore_api.utils import json_or_raise from podcaststore_api.models.user import UserSerializer from django.contrib.auth.models import User fro...
"""Add License, Header. Use pkglts Problems: - name of a model unit? """ from __future__ import print_function from __future__ import absolute_import from path import Path import numpy import os.path import six class Model2Package(object): """ TODO """ num = 0 def __init__(self, models, dir=None, ...
"""Add License, Header. Use pkglts Problems: - name of a model unit? """ from __future__ import print_function from __future__ import absolute_import from path import Path import numpy import os.path import six class Model2Package(object): """ TODO """ num = 0 def __init__(self, models, dir=None, ...
from django.contrib import messages from django.shortcuts import render, redirect from scanner.scan import scan_code def home(request): return render(request, 'home.html') def scan(request): context = scan_code(request.user.profile) print(context) if context: print(context['unmatched_labels'...
from django.contrib import messages from django.shortcuts import render, redirect from scanner.scan import scan_code def home(request): return render(request, 'home.html') def scan(request): context = scan_code(request.user.profile) print(context) if context: print(context['unmatched_labels'...
#!/usr/bin/env python import uuid import time import tempfile from plaster.tools.utils import tmp """ Plaster Generator (gen) architecture Gen consists of one plumbum cli application and many "generators". Each run of gen invokes one generator. The Generators provide: * A schema. * A generate method which ...
#!/usr/bin/env python import uuid import time import tempfile from plaster.tools.utils import tmp """ Plaster Generator (gen) architecture Gen consists of one plumbum cli application and many "generators". Each run of gen invokes one generator. The Generators provide: * A schema. * A generate method which ...
# Import a speaker from the submission form # # Based on the quickstart template: https://developers.google.com/sheets/api/quickstart/python # # # # Logic: # - if the speaker submission is valid, not spam, and not already accepted # - extract important data into a yaml format # - download the avatar to file # # # ...
# Import a speaker from the submission form # # Based on the quickstart template: https://developers.google.com/sheets/api/quickstart/python # # # # Logic: # - if the speaker submission is valid, not spam, and not already accepted # - extract important data into a yaml format # - download the avatar to file # # # ...
from django.shortcuts import render, redirect from django.views.generic import FormView, TemplateView from django.urls import reverse, reverse_lazy from django.db import transaction from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model, login from django.contrib.auth.tok...
from django.shortcuts import render, redirect from django.views.generic import FormView, TemplateView from django.urls import reverse, reverse_lazy from django.db import transaction from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model, login from django.contrib.auth.tok...
""" Copyright (C) 2019-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved. This module provides an assortment of helper functions that Mussels depends on. 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 ...
""" Copyright (C) 2019-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved. This module provides an assortment of helper functions that Mussels depends on. 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 ...
#!/usr/bin/env python # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """pytorch dataset and dataloader implementation for chainer training.""" import torch import torch.utils.data import logging import numpy as np import string import re import ...
#!/usr/bin/env python # Copyright 2017 Johns Hopkins University (Shinji Watanabe) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """pytorch dataset and dataloader implementation for chainer training.""" import torch import torch.utils.data import logging import numpy as np import string import re import ...
import argparse from datetime import datetime import sqlite3 from sqlite3 import Error import re class ScratchPad: def __init__(self, db_file, args): self.db_file = db_file self.args = args self.create_connection() def handle_args(self): # If a command was specified, use it. O...
import argparse from datetime import datetime import sqlite3 from sqlite3 import Error import re class ScratchPad: def __init__(self, db_file, args): self.db_file = db_file self.args = args self.create_connection() def handle_args(self): # If a command was specified, use it. O...
# Copyright 2021 AI Singapore # 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, ...
# Copyright 2021 AI Singapore # 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, ...
#!/usr/bin/env python3 import os from pprint import pprint from ipaddress import IPv6Address from more_itertools import pairwise import itertools import pathlib import matplotlib.pyplot as plt import matplotlib.dates as mdates from analysis.parser.edge_challenge_response import main as parse_cr from analysis.parser....
#!/usr/bin/env python3 import os from pprint import pprint from ipaddress import IPv6Address from more_itertools import pairwise import itertools import pathlib import matplotlib.pyplot as plt import matplotlib.dates as mdates from analysis.parser.edge_challenge_response import main as parse_cr from analysis.parser....
""" contains class and methods for reading avro files and dirs """ import copy import os import json from avro_to_python.classes.node import Node from avro_to_python.classes.file import File from avro_to_python.utils.paths import ( get_system_path, get_avsc_files, verify_path_exists ) from avro_to_python.utils.e...
""" contains class and methods for reading avro files and dirs """ import copy import os import json from avro_to_python.classes.node import Node from avro_to_python.classes.file import File from avro_to_python.utils.paths import ( get_system_path, get_avsc_files, verify_path_exists ) from avro_to_python.utils.e...
from discord.ext import commands from .utils import checks, db, fuzzy, cache, time import asyncio import discord import re import lxml.etree as etree from collections import Counter DISCORD_API_ID = 81384788765712384 DISCORD_BOTS_ID = 110373943822540800 USER_BOTS_ROLE = 178558252869484544 CONTRIBUTORS_ROLE = 1...
from discord.ext import commands from .utils import checks, db, fuzzy, cache, time import asyncio import discord import re import lxml.etree as etree from collections import Counter DISCORD_API_ID = 81384788765712384 DISCORD_BOTS_ID = 110373943822540800 USER_BOTS_ROLE = 178558252869484544 CONTRIBUTORS_ROLE = 1...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ chipS2Extract.py -- A routine to extract a small subset from imagery in S3 object storage. Essential part of DIAS functionality for CAP Checks by Monitoring Author: Guido Lemoine, European Commission, Joint Research Centre License: see g...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ chipS2Extract.py -- A routine to extract a small subset from imagery in S3 object storage. Essential part of DIAS functionality for CAP Checks by Monitoring Author: Guido Lemoine, European Commission, Joint Research Centre License: see g...
import re from pathlib import Path import markdown from markdown.extensions.fenced_code import FencedBlockPreprocessor # highlightJS expects the class "language-*" but markdown default is "*" FencedBlockPreprocessor.LANG_TAG = ' class="language-%s"' CONTENT = Path(__file__).parent / "content" DEST = Path(__file__).p...
import re from pathlib import Path import markdown from markdown.extensions.fenced_code import FencedBlockPreprocessor # highlightJS expects the class "language-*" but markdown default is "*" FencedBlockPreprocessor.LANG_TAG = ' class="language-%s"' CONTENT = Path(__file__).parent / "content" DEST = Path(__file__).p...
import re import numpy as np from .exceptions import expected, typename from .formats import parse_number from .matrix import create_array from .preprocessors import planner, preprocessor, _drop_weak_columns int_type = (int, np.int64) def clean_numeric_labels(name, values, receiver): if values.dtype in (float, ...
import re import numpy as np from .exceptions import expected, typename from .formats import parse_number from .matrix import create_array from .preprocessors import planner, preprocessor, _drop_weak_columns int_type = (int, np.int64) def clean_numeric_labels(name, values, receiver): if values.dtype in (float, ...
from abc import abstractmethod, ABC from copy import copy from datetime import datetime from pathlib import Path from shutil import copyfileobj from typing import TYPE_CHECKING, Optional from . import Stream if TYPE_CHECKING: from . import File class Storage(ABC): @abstractmethod def get_stream(self, fi...
from abc import abstractmethod, ABC from copy import copy from datetime import datetime from pathlib import Path from shutil import copyfileobj from typing import TYPE_CHECKING, Optional from . import Stream if TYPE_CHECKING: from . import File class Storage(ABC): @abstractmethod def get_stream(self, fi...
from abc import ABC import pygame import numpy as np from tkinter import Tk from tkinter import messagebox from typing import Tuple, Optional, Dict from .maze import Maze from .base import Viewport, BoundType from ...enums import Colors from ...database import Database from ...sprites.object_to_color import Object...
from abc import ABC import pygame import numpy as np from tkinter import Tk from tkinter import messagebox from typing import Tuple, Optional, Dict from .maze import Maze from .base import Viewport, BoundType from ...enums import Colors from ...database import Database from ...sprites.object_to_color import Object...
""" Module contains all functions working on users page. Functions: users_page() edit_user(id) delete_user(id) check_session() """ import os import sys import urllib.parse from flask_login import login_user, login_required from flask import render_template, request, redirect, Blueprint, session sys.pa...
""" Module contains all functions working on users page. Functions: users_page() edit_user(id) delete_user(id) check_session() """ import os import sys import urllib.parse from flask_login import login_user, login_required from flask import render_template, request, redirect, Blueprint, session sys.pa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Christian Heider Nielsen" __doc__ = r""" Created on 22/03/2020 """ import copy from collections import namedtuple from enum import Enum from pathlib import Path from typing import Any, List, Mapping, Sequence, Tuple, Union import tor...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "Christian Heider Nielsen" __doc__ = r""" Created on 22/03/2020 """ import copy from collections import namedtuple from enum import Enum from pathlib import Path from typing import Any, List, Mapping, Sequence, Tuple, Union import tor...
import torch import ipywidgets as widgets import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 30, 'legend.fontsize': 20}) plt.rc('font', size=25) plt.rc('axes', titlesize=25) def format_attention(attention): squeezed = [] for layer_attention in attention: # 1 x num_hea...
import torch import ipywidgets as widgets import numpy as np import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 30, 'legend.fontsize': 20}) plt.rc('font', size=25) plt.rc('axes', titlesize=25) def format_attention(attention): squeezed = [] for layer_attention in attention: # 1 x num_hea...