text stringlengths 3.07k 12.6k |
|---|
from collections import namedtuple, ChainMap
from contextlib import contextmanager, AbstractContextManager, ExitStack
from dataclasses import dataclass
import logging
import time
from types import TracebackType
from typing import (
ChainMap as TypingChainMap,
Iterator,
Mapping,
MutableMapping,
Optio... |
# linux-utils: Linux system administration tools for Python.
#
# Author: <NAME> <<EMAIL>>
# Last Change: June 24, 2017
# URL: https://linux-utils.readthedocs.io
"""
Atomic filesystem operations for Linux in Python.
The most useful functions in this module are :func:`make_dirs()`,
:func:`touch()`, :func:`write_content... |
""" Defines the class Validator."""
import torch
import lattice
class Validator:
"""
Validates the energy of model with variance approximately below the given tolerance.
Args (of __init__):
model (lattice.Model): the drift to validate
Args (of __call__):
atol_var (Float): absolute toler... |
#!/usr/bin/env python
import argparse
import gzip
from collections import defaultdict
import pandas as pd
gzopen = lambda f: gzip.open(f, "rt") if f.endswith(".gz") else open(f)
def build_tax(tax_file, output):
"""
Takes in the file to the order level in classification_txt rule
and parses those to put t... |
#!/usr/bin/python
# Copyright: (c) 2018, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see LICENSE-GPLv3.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0 (see LICENSE-APACHE2.txt or http://www.apache.org/licenses/LICENSE-2.0)
from __future__ import absolute_import, division, print_function... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
#!/usr/bin/env python3
import sys
import os
import re
import math
import argparse
import pathlib
import threading
from joblib import Parallel, delayed
import pandas as pd
# Generate gene array
# This function is for joblib parallel
def generate_gene_array(line, gene_array):
values = line.strip("\n").split("\t"... |
import imutils
from imutils.perspective import four_point_transform
from imutils import contours
import numpy as np
import cv2
import os
import pandas as pd
def show_image(image):
img = imutils.resize(image, width=600)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
def remove_edge... |
# Copyright 2020 Google LLC, University of Victoria, Czech Technical University
#
# 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 ... |
import sys
import torch
import numpy as np
from math import pi
from torch.distributions import Normal, Categorical
from .geoml.curve import CubicSpline
import math
class DistSqKL(torch.autograd.Function):
@staticmethod
def forward(ctx, net, p0, p1):
device = "cuda" if torch.cuda.is_available() else "c... |
import numpy as np
import pytest
from topfarm.tests import npt
from topfarm.constraint_components.boundary import PolygonBoundaryComp
@pytest.mark.parametrize('boundary', [
[(0, 0), (1, 1), (2, 0), (2, 2), (0, 2)],
[(0, 0), (1, 1), (2, 0), (2, 2), (0, 2), (0, 0)], # StartEqEnd
[(0, 0), (0, 2), (2, 2), (2... |
# Copyright (c) 2018 gevent. See LICENSE for details.
# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False
from __future__ import print_function, absolute_import, division
import sys
import traceback
from greenlet import settrace
from greenlet import getcurrent
from gevent.util import format_r... |
import datetime
from sys import platform
from typing import NamedTuple
from urllib.parse import quote
from urllib.parse import urlencode
mobile = "https://mobile.twitter.com"
base = "https://api.twitter.com/2/search/adaptive.json"
class SearchParams(NamedTuple):
url: str
params: list
serial_query: str
... |
import numpy as np
from yt.testing import assert_allclose_units, fake_random_ds, requires_file
from yt.units import cm, s # type: ignore
from yt.utilities.answer_testing.framework import data_dir_load
from yt.visualization.volume_rendering.off_axis_projection import off_axis_projection
def random_unit_vector(prng):... |
# Copyright 2019 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 __future__ import unicode_literals
import pytest
import mock
import os
import tempfile
import responses
from flask import Flask
from flask_dance.contrib.jira import make_jira_blueprint, jira
from flask_dance.consumer import OAuth1ConsumerBlueprint
from flask_dance.consumer.storage import MemoryStorage
from oauthl... |
from abc import ABC
from dataclasses import dataclass
from enum import IntEnum
from typing import Any, Dict, List, Tuple, Type, Union
try:
from functools import cached_property
except:
from backports.cached_property import cached_property
import numpy as np
from scipy.stats import beta, rv_continuous
from co... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
import itertools
import json
import random
from abc import ABC
from pathlib import Path
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset as TorchDataset
from typing import Callable, List, Iterable, Tuple
from deepproblog.dataset import Dataset
from deepproblog.query i... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: <NAME> 刘祥德
@license: (C) Copyright 2019-now, Node Supply Chain Manager Corporation Limited.
@contact: <EMAIL>
@software:
@file: categories.py
@time: 2020/8/12 10:46
@version 1.0
@desc:
"""
import json
import os
from flask_restplus import Namespace, Resource, reqpar... |
# ____ ___ _ _ _____ ___ ____
# / ___/ _ \| \ | | ___|_ _/ ___| _ __ _ _
# | | | | | | \| | |_ | | | _ | '_ \| | | |
# | |__| |_| | |\ | _| | | |_| |_| |_) | |_| |
# \____\___/|_| \_|_| |___\____(_) .__/ \__, |
# |_| |___/
# Config Class
# MIT License
... |
#!/usr/bin/env python
# Note that this should be used with original GALFIT.
from glob import glob
from astropy.io import fits as pyfits
import os, sys, getopt
"""make_images.py - Create images for galfitm spiralsim test
As well as creating singe-band images from the model feedmes, this
routine produces mul... |
import sys
from time import sleep
from celery import Celery
from fabric import state
from fabric.api import cd, local, quiet, run, settings
from kombu import Queue
from logger import logger
from sqlalchemy import create_engine
from perfrunner import celerylocal, celeryremote
from perfrunner.helpers.misc import log_ph... |
import argparse
import os
import dotenv
from spotidl import utils, spotify, downloader, config, exceptions, metadata
from . import __version__
# loading .env vars
dotenv.load_dotenv()
def cli_args() -> argparse.Namespace:
"""
Contains and parses all command line arguments for the application.
"""
... |
"""HandleImport transformation takes care of importing user-defined modules."""
from pythran.passmanager import Transformation
from pythran.tables import MODULES, pythran_ward
from pythran.syntax import PythranSyntaxError
import gast as ast
import logging
import os
logger = logging.getLogger('pythran')
def add_file... |
#-*- coding: utf-8 -*-
""" Helper functions / methods / classes """
import os
import signal
import sys
import threading
import time
import traceback
from builtins import input
from uuid import uuid4
from voiceplay.logger import logger
from .crashlog import send_traceback
class Singleton(type):
"""
Single... |
#!/usr/bin/env python
"""NBConvert is a utility for conversion of IPYNB files.
Commandline interface for the NBConvert conversion utility. Read the
readme.rst for usage information
"""
#-----------------------------------------------------------------------------
#Copyright (c) 2013, the IPython Development Team.
#
#... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from compas.geometry.basic import subtract_vectors
from compas.geometry.basic import subtract_vectors_xy
from compas.geometry.basic import cross_vectors
from compas.geometry.basic import cross_vectors_xy... |
import os
import sys
import urllib.request
from bs4 import BeautifulSoup
import test_parser
def remove_empty_lines(s):
i = 0
while i < len(s) and s[i] == '\n':
i += 1
s = s[i:]
i = len(s) - 1
while i >= 0 and s[i] == '\n':
i -= 1
s = s[:i+1]
i = len(s)
while True:
... |
import numpy as np
import rospy
from ros_rl.msg import EnvAct, EnvObs, EnvDescMsg
from ros_rl.srv import GetEnvDesc, GetEnvDescResponse
from std_srvs.srv import Empty, EmptyResponse
from ros_rl.utils.thing import ThingDesc, ThingfromDesc, ThingDescfromMsg, ThingfromMsg
INACTIVE = 0
ACTIVE = 1
FINISHED = 2
state_map =... |
# Copyright (C) 2021 Nippon Telegraph and Telephone Corporation
# 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/LICE... |
import os
import struct
from amitools.binfmt.BinImage import *
from amitools.binfmt.Relocate import *
from KickRom import KickRomAccess
class RomEntryRaw:
def __init__(self, name, data, relocs=None):
self.name = name
self.data = data
self.relocs = relocs
def get_size(self):
return len(self.data)... |
import pygame
import random
from enum import Enum
from collections import namedtuple
import numpy as np
pygame.init()
font = pygame.font.Font('arial.ttf', 25)
#font = pygame.font.SysFont('arial', 25)
class Direction(Enum):
RIGHT = 1
LEFT = 2
UP = 3
DOWN = 4
Point = namedtuple('Point', 'x, y')
# rgb colors
WHITE... |
# -*- coding: utf-8 -*-
"""
website.tcp.services
~~~~~~~~~~~~~~~~
TCP Proxy services api.
"""
import os
import sys
import subprocess
from flask import flash, current_app
from flask.ext.babel import gettext
from website.services import exec_command
from website import db
from website.tcp.models import Con... |
from flask import Flask, request, jsonify, make_response, request, render_template, session, flash
import jwt
from datetime import datetime, timedelta
from functools import wraps
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, render_template, redirect, url_for
from flask import request
import r... |
# -*- coding: utf-8 -*-
#
# PublicKey/PKCS8.py : PKCS#8 functions
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual,... |
# coding: utf-8
import logging
import os
import sys
import time
import psutil
import platform
import pytest
import signal
import ray
import ray.cluster_utils
from ray._private.test_utils import (
run_string_as_driver_nonblocking,
wait_for_pid_to_exit,
wait_for_condition,
)
logger = logging.getLogger(__na... |
from pyxnat import Interface
import os.path as op
from . import skip_if_no_network
_modulepath = op.dirname(op.abspath(__file__))
fp = op.join(op.dirname(op.abspath(__file__)), 'central.cfg')
print(fp)
central = Interface(config=fp)
proj_1 = central.select.project('surfmask_smpl2')
subj_1 = proj_1.subject('CENTRAL05... |
import re
from .atoms import Production, NTerm, Term, Value
def strip_comments(stream):
"""Strip comments, tail comments, but keep # in quotations."""
switch = '\'"'
quoted = False
quotation = None
triplet = 0
mulline = False
commented = False
code = ''
for num, i in enumerate(str... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
from enum import Enum
import re
class Parame... |
# ===============================================================================
# Copyright 2014 <NAME>
#
# 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/LI... |
import time
import asyncio
from enum import Enum
from collections import deque
from typing import Any, Optional
from .typedefs import Message
from .errors import MaxConcurrencyReached
__all__ = (
'BucketType',
'Cooldown',
'CooldownMapping',
'MaxConcurrency',
)
class BucketType(Enum):
default = ... |
from __future__ import unicode_literals
from urllib.parse import urlparse
import youtube_dl
import aiohttp
import aiofiles
import os
from random import randint
from pyrogram import filters
from wbb import app, SUDOERS, arq, MAIN_CHATS
from wbb.utils.errors import capture_err
from wbb.utils.pastebin import paste
__MODU... |
import math
import numpy as np
from scipy.sparse import csc_matrix
def lag(mat, lagged, N, lag_number, fill=np.NaN):
height = int(mat.shape[0] / N)
for i in range(N):
start_row = i * height
end_row = start_row + height
mat_i = mat[start_row:end_row, :]
lagged_i = l... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module that contains console widgets
"""
from __future__ import print_function, division, absolute_import
import logging
from io import StringIO
from Qt.QtCore import Qt, QSize, QStringListModel
from Qt.QtWidgets import QSizePolicy, QLineEdit, QTextEdit, QCompleter... |
#!/usr/bin/python3
import socket
import base64
import json
import sys
import threading
import time
import asyncio
from asyncio import Future
from typing import (
Awaitable,
)
class IOStream():
def __init__(self, socket: socket.socket) -> None:
self.socket = socket
self.socket.setblocking(Fa... |
import os
import yaml
from .exceptions import (
InvalidRuleSchema,
RuleVersionNotSupport,
RuleTypeNotSupport,
RuleAlreadyExist,
)
from rostran.core.settings import RULES_DIR
class RuleClassifier:
TerraformAliCloud = "terraform/alicloud"
TerraformAWS = "terraform/aws"
CloudFormation = "clou... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Implementation for Single Image Haze Removal Using Dark Channel Prior.
Reference:
http://research.microsoft.com/en-us/um/people/kahe/cvpr09/
http://research.microsoft.com/en-us/um/people/kahe/eccv10/
"""
import numpy as np
from PIL import Image
from guidedfilter impo... |
#!/usr/bin/env python3
import numpy as np
import os, os.path
import subprocess
def string_label_to_label_vector(label_string, outcome_maps):
label_vec = []
for label_val in label_string.split('#'):
(label, val) = label_val.split('=')
cur_map = outcome_maps[label]
label_ind = ... |
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor
from markdown.treeprocessors import Treeprocessor
import xml.etree.ElementTree as ET
import re
START_SECTION = r"~~([SCHFNDA])([^~]*)~~"
END_SECTION = r"~~/([SCHFNDA])~~"
class OCXMetadata(Extension):
"""Python-Markdown ext... |
# Copyright 2017 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 required by applicable law or a... |
#!/usr/bin/env python3
# Python server to manage the turret
import os
import sys
import argparse
import serial
import serial.tools.list_ports
from threading import Thread
from time import sleep
import colorama
from colorama import Fore
from colorama import Style
from SimpleWebSocketServer import WebSocket
if os.path... |
# Copyright (c) 2010 - 2020, Nordic Semiconductor ASA
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list o... |
"""
Visualization auxiliary operations.
add_map_legend,
generate_color,
rgb,
hex_rgb,
cmap_hex_color,
get_cmap,
save_wkt
"""
from typing import List, Optional, Text, Tuple
from branca.element import MacroElement, Template
from folium import Map
from matplotlib.cm import get_cmap as _get_cmap
from matplotlib.colors ... |
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Index, Integer, String
# from sqlalchemy.dialects.postgresql import array_agg
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import relationship
from sqlalchemy.sql.functions import GenericFunctio... |
from enum import Enum
import re
try:
import requests
except ImportError:
raise RuntimeError('Requests is required for hibp.')
try:
import gevent
from gevent import monkey
from gevent.pool import Pool
except ImportError:
raise RuntimeError('Gevent is required for hibp.')
monkey.patch_all(threa... |
# ------------------------------------------------------------------------------
# Copyright (c) ETRI. All rights reserved.
# Licensed under the BSD 3-Clause License.
# This file is part of Youtube-Gesture-Dataset, a sub-project of AIR(AI for Robots) project.
# You can refer to details of AIR project at https://aiforro... |
import json
import os.path
import os
import wimbledon
CONFIG_DIR = os.path.expanduser("~/.wimbledon")
HARVEST_CREDENTIALS_PATH = CONFIG_DIR + "/.harvest_credentials"
SQL_CONFIG_PATH = CONFIG_DIR + "/.sql_config"
WIMBLEDON_CONFIG_PATH = CONFIG_DIR + "/.wimbledon_config"
GITHUB_CREDENTIALS_PATH = CONFIG_DIR + "/.github... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import
import re
from math import isinf, isnan
from future.utils import text_type, binary_type, iteritems
from ._compat import singledispatch
from .nodes import * # noqa
@singledispatch
def node_encoder(obj): # noqa
"""Convert python objec... |
import numpy as np
import copy
from util.util import *
from heuristics.greedy_tsp import greedy as greedy_tsp
from graph.graph import Graph
from util.prim import *
# prefer concorde
try:
from concorde.tsp import TSPSolver
CONCORDE_AVAILABLE = True
#CONCORDE_AVAILABLE = False
except ImportError:
CONC... |
from __future__ import absolute_import
from email.utils import parsedate, formatdate
import mimetypes
import os
import os.path
import re
from time import gmtime
from wsgiref.headers import Headers
class StaticFile(object):
gzip_path = None
def __init__(self, path):
self.path = path
self.hea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# I waive copyright and related rights in the this work worldwide
# through the CC0 1.0 Universal public domain dedication.
# https://creativecommons.org/publicdomain/zero/1.0/legalcode
# Author(s):
# <NAME> <<EMAIL>>
""" Present a consolodated event stream from messa... |
from typing import Optional
ERROR_REQUIRED = 'This field is required.'
ERROR_NOT_VALID = 'Format not valid.'
class _Null(object):
def __repr__(self):
return '<null>'
def __bool__(self):
return False
def __nonzero__(self):
return False
null = _Null()
def check_params(params)... |
"""
Convert the mapping in JSON generated by process_artists scripts to an SQL database for production use
"""
import sqlite3
import json
from pathlib import Path
database = Path("../app/data/Enhanced-AMQ-Database.db")
song_database_path = Path("../app/data/expand_mapping.json")
artist_database_path = Path("../app/d... |
import logging
import time
from typing import Dict, List, Union
import numpy as np
from pymatgen.electronic_structure.core import Spin
from amset.constants import int_to_spin, numeric_types
from amset.electronic_structure.symmetry import (
rotation_matrix_to_su2,
similarity_transformation,
)
from amset.log im... |
import argparse
import os
import os.path as osp
import mmcv
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from mmpose.apis import multi_gpu_test, single_gpu_test
from mmpose.core import wrap_fp16_model
from mmpose.dat... |
"""
Imbalance metrics.
Author: <NAME>, agilescientific.com
Licence: Apache 2.0
Copyright 2022 Agile Scientific
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/L... |
# Copyright 2018 BLEMUNDSBURY AI LIMITED
#
# 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 ... |
import requests
import ast
def curveNumber(lat, lon):
return "Hello, World!"
# Retrieve rainfall data from the NOAA Precipitation Frequency Data Server
# https://hdsc.nws.noaa.gov/hdsc/pfds/pfds_map_cont.html?bkmrk=sc
def rainfallData(lat, lon):
# Request data from NOAA
requestURL = "https://hdsc.nws.noa... |
__author__ = 'DafniAntotsiou'
import mujoco_py
from numpy import array
from copy import deepcopy
import numpy as np
def GetBodyPosDist(bodyId, refbodyId, m):
bodyPos = array([0, 0, 0], dtype='f8')
if refbodyId < 0:
return bodyPos
while bodyId > refbodyId:
bodyPos += m.body_pos[bodyId]
... |
import torch
import torch.nn as nn
import functools
from .simple_layers import SimpleLayerBase, SimpleOutputBase, SimpleModule, SimpleMergeBase
from ..layers.utils import div_shape
from ..train.outputs_trw import OutputClassification as OutputClassification_train
from ..train.outputs_trw import OutputEmbedding as Outp... |
import pandas as pd
import json
from pathlib import Path
from Bio import Entrez
from datasetmaker.datasetmaker import DatasetMaker
from abc import abstractmethod
class FastaDatasetMaker(DatasetMaker):
def __init__(self):
self.column_names = ['pdb_code', 'chain',
'chain_type',... |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHE... |
import discord, copy, os, datetime, inspect
discordToken = "<token>"
webhook = '<url>'
def parse_time(dt):
months = ['янв.', 'фев.', 'мар.', 'апр.', 'мая', 'июня', 'июля', 'авг.', 'сен.', 'окт.', 'ноя.', 'дек.']
return ['%s %s %s' % (dt[2], months[dt[1]-1], dt[0]), '%s:%s:%s' % (str(dt[3]).zfill(2), str(dt[4]).zf... |
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. 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 re... |
import RPi.GPIO as GPIO
import time
import threading
import subprocess
import requests
import Adafruit_DHT
from pprint import pprint
import sys
import datetime
import jwt
import paho.mqtt.client as mqtt
import random
from Proximity import Proximity
from Presion import Presion
from puerta import Puerta
from Ultrasonic i... |
# Copyright (c) 2013 Mirantis 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 writi... |
"""Voice room generator module."""
import copy
from typing import Dict, Optional, Union
from discord import (
CategoryChannel, HTTPException, InvalidData, Member, PermissionOverwrite,
Role, TextChannel, VoiceChannel
)
from ophelia.output.output import disp_str, send_message
from ophelia.utils.discord_utils im... |
#!/usr/bin/env python3
import argparse,array,can,json,os,queue,re,signal,time
from threading import Thread
flap_max_extend = 12
device_command_ids = { 'roof':0x64,'flap':0x65 }
device_commands = { 'open': 0x00, 'close': 0x01, 'opening': 0x02, 'closing': 0x03, 'error': 0x04, 'heartbeat':0xfe, 'stop':0xff }
incoming_... |
import math
from abc import ABC, abstractmethod
from qibo import K
from qibo.abstractions import callbacks as abstract_callbacks
from qibo.abstractions.states import AbstractState
from qibo.config import EIGVAL_CUTOFF, raise_error, log
class BackendCallback(abstract_callbacks.Callback, ABC):
def __geti... |
#!/usr/bin/env python
# coding: utf-8
"""This script pulls business entity data from the workflow database and generates markdown
files for use as training data in the CRF NLP process. """
import configparser
import math
import psycopg2
import psycopg2.extras
from datetime import date
import datetime
def dbconnect()... |
#!/usr/bin/env python3
from io import TextIOWrapper
from bs4 import BeautifulSoup
import re
import argparse
DEFAULT_TEMPLATE = "template.html"
DEFAULT_OUTPUT = "gen.html"
DEFAULT_INPUT = "input.txt"
class Section:
"""
Parsed section of text.
OOP isn't really necessary for this, but it does make it sligh... |
import re
import os
import subprocess
from functools import lru_cache
from typing import Dict, List
import pandas as pd
from helpers import (
NOW,
RemoteCommand,
Settings,
create_settings,
nix_build,
spawn,
flamegraph_env,
read_stats,
write_stats,
scone_env
)
from network import... |
# -*- coding: utf-8 -*-
__author__ = 'ZFTurbo: https://kaggle.com/zfturbo'
from a00_common_functions import *
import tifffile
import sys
print('Command line arguments: {}'.format(sys.argv))
if len(sys.argv[1:]) == 1:
INPUT_TRAINING_PATH = sys.argv[1]
else:
INPUT_TRAINING_PATH = '../input/training/'
OUTPUT_B... |
"""Platform for Miele button integration."""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any, Final
import aiohttp
from homeassistant.components.button import ButtonEntity, ButtonEntityDescription
from homeassistant.core import HomeAssistant
from homeassistan... |
import itertools
import logging
import operator
import os
from typing import Mapping, Sequence
import orjson
from peewee import (
CharField,
DateTimeField,
FixedCharField,
ForeignKeyField,
IntegerField,
IPField,
Model,
ModelSelect,
ModelUpdate,
SqliteDatabase,
)
from playhouse.s... |
from .utils import VectorAndNumbers
from .algorithm import Algorithm
from .individual import Individual
from .job import Job
from .problem import Problem
from SALib.sample.saltelli import sample as sobol_sample
from SALib.sample.morris import sample as morris_sample
from SALib.sample.fast_sampler import sample as fast... |
"""
Evidence Lower Bound (ELBO) for Functional Variational Inference (FVI)
Depth experiments. Gaussian, Laplace and reverse Huber Likelihoods
"""
import torch
import math
from .utils.torch_utils import bmat_inv_logdet, bdiag_prod
def weight_aleatoric(c):
dist = torch.distributions.normal.Normal(0., 1.)
... |
# -*- coding: utf-8 -*-
from functools import reduce
from itertools import zip_longest
from math import ceil
from math import floor
from math import log
from scipy import ndimage
import numpy as np
def morton_array(shape):
"""
Return array with Morton numbers.
Inspired by:
https://graphics.stanford... |
from typing import List
import gluonnlp as nlp
import numpy as np
from gluonnlp.data import BERTSentenceTransform
__all__ = ['TextDataTransform', 'BERTDataTransform']
class TextDataTransform(object):
"""
Python class for performing data pre-processing on the text dataset.
This class is constructed using... |
import numpy as np
gauss_len = 100
gaussian_amp = 0.2
def gauss(amplitude, mu, sigma, delf, length):
t = np.linspace(-length / 2, length / 2, length)
gauss_wave = amplitude * np.exp(-((t - mu) ** 2) / (2 * sigma ** 2))
# Detuning correction Eqn. (4) in Chen et al. PRL, 116, 020501 (2016)
ga... |
#Copyright [2020] [Indian Institute of Science, Bangalore]
#SPDX-License-Identifier: Apache-2.0
from calculate_means import calculate_means
from calculate_r0 import calculate_r0
from calibrate import calibrate
from joblib import Parallel, delayed
import os
from selenium import webdriver
from selenium.webdriver.chrome.... |
import os
import gc
import utils
import pandas as pd
import numpy as np
import pickle as pkl
from datetime import date
from keras.layers.normalization import BatchNormalization
from keras.models import Sequential, Model
from keras.layers import Input, Embedding, Dense, Flatten, Concatenate, Dot, Reshape, Add, Subtrac... |
"""Provides a YAML loader"""
import itertools
import os
import logging
import voluptuous as vol
import yaml
from yaml.reader import Reader
from yaml.scanner import Scanner
from yaml.parser import Parser
from yaml.composer import Composer
from yaml.constructor import SafeConstructor
from yaml.resolver import Resolver
... |
# --- built in ---
import os
import time
import argparse
import functools
from datetime import datetime
# --- 3rd party ---
import ray
from ray import tune
# --- my module ---
import unstable_baselines as ub
from unstable_baselines.algo.ppo import PPO
from experiments import BaseExperiments
from experiments.ppo.config... |
# coding: utf-8
"""
Timefred is a beautiful and intelligent time tracker for the command line. Visit the
project page (https://github.com/giladbarnea/timefred) for more details.
Usage:
tf (o|on) <name> [start time = "now"]
tf (f|stop) [end time = "now"]
tf (s|status)[+]
tf (t|tag) <tag> [time = "now"]
Add ... |
from pathlib import Path
import argparse
import json
import glob
import sys
from matplotlib import pyplot as plt
import numpy as np
def roc_graphs(fprs, tprs, names, aucs, savename, minx=0.85):
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
plt.figure() # figsize=(10, 10)
ax = plt.axes(xscale='log', xli... |
from functools import total_ordering
from transfinite.util import is_finite_ordinal, as_latex, exp_by_squaring
class OrdinalConstructionError(Exception):
pass
@total_ordering
class Ordinal:
"""
An infinite ordinal less than epsilon_0.
This class describes an ordinal in Cantor Normal Form using
... |
#!/usr/bin/env python
"""
:Abstract: Given an abundance table, calculate pairwise Spearman's Rho of the columns.
:Date: 02/15/2017
:Author: <NAME>
"""
import sys
import argparse
from traceback import format_exc
from time import localtime, strftime
from itertools import combinations
from phylotoast.util import parse_ma... |
from utils.misc import isnotebook
if isnotebook():
from tqdm import tqdm_notebook as tqdm
else:
from tqdm import tqdm
import numpy as np
import torch
from torch_geometric.data import Data
from torch_geometric.utils import remove_self_loops
from utils.load_dataset import load_data, load_zinc_data, load_ogb_data,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.