text stringlengths 3.07k 12.6k |
|---|
import ast
import inspect
from dataclasses import dataclass
from pathlib import Path
from types import ModuleType
from typing import Dict, Iterator, List, Optional, Type
import numpy as np
from numpydoc.docscrape import ClassDoc, Parameter
import napari
from docs._scripts._table_maker import table_repr
from napari im... |
_required = object()
class Fixture(object):
"""Assistant for creating test fixtures.
This proxies all undefined attributes to its :class:`~sgmock.shotgun.Shotgun`
instance for easy tear-down of newly created entities. E.g::
# Create a fixture wrapping a mock Shotgun.
sg = Fi... |
from lxml import etree
import urlfinderlib.finders as finders
html = """
<html xmlns="xmlns">
<head>
<base href="http://domain.com">
<meta HTTP-EQUIV="REFRESH" content=0;url="meta">
<meta HTTP-EQUIV="REFRESH" CONTENT="0; URL=meta2">
<meta http-equiv="X-UA-Compatible" content="IE=e... |
from __future__ import unicode_literals
import click
from pyinfra import logger
from .connectors import EXECUTION_CONNECTORS
from .connectors.util import remove_any_sudo_askpass_file
from .exceptions import ConnectError, PyinfraError
from .facts import (
create_host_fact,
delete_host_fact,
get_fact_class... |
from server.utils.arx_utils import commafy, inform_staff
from evennia.utils import logger
from world.magic.models import Alignment, Affinity, Practitioner
import json
import sys
class MagicConsequence(object):
@classmethod
def load(cls, serialized_dict=None):
if not serialized_dict:
return... |
import glob
import uuid
import json
import requests
import copy,time
import os
import cv2
import numpy as np
from time import sleep
import pandas as pd
import logging
digitization = False
craft_line = "True"
craft_word = "True"
google_ocr= "True"
tess_ocr= "True"
language = "hi"
path = '/home/ubuntu/tesseract_evalu... |
import numpy as np
import pandas as pd
from sklearn.preprocessing import PolynomialFeatures # TODO: implement what I need from this package
class Design:
"""
Class Docstring.
"""
def __init__(self, experiments=None, levels=None):
"""
:param int experiments: Number of Experiments to d... |
from math import ceil
from typing import TYPE_CHECKING, Text, Union
from discordmenu.embed.base import Box
from discordmenu.embed.components import EmbedField, EmbedMain, EmbedThumbnail
from discordmenu.embed.text import LabeledText
from discordmenu.embed.view import EmbedView
from discordmenu.emoji.emoji_cache import... |
import torch
import torch.nn as nn
import numpy as np
class ConvBlock(nn.Module):
"""
A block of convolutional layers (1D, 2D or 3D)
"""
def __init__(self, dim, n_ch_in, n_ch_out, n_convs, kernel_size=3, bias = False):
super(ConvBlock, self).__init__()
if dim==1:
conv_op = nn.Conv1d
if dim==2:
co... |
# Copyright 2021 <NAME> (KRR-Oxford). 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 la... |
# Author: <NAME> <<EMAIL>>
# ARL Wrapping
import cffi
import numpy
from data_models.memory_data_models import Image, Visibility, BlockVisibility, GainTable
import pickle
ff = cffi.FFI()
def ARLDataVisSize(nvis, npol):
return (80+32*int(npol))*int(nvis)
def cARLVis(visin):
"""
Convert a const ARLVis ... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... |
from numbers import Number
from types import GeneratorType
import math
def norm(vector, power=2):
return math.fsum(abs(a)**power for a in vector)**(1/power)
def normalized(vector, power=2, cls=None):
if isinstance(vector, GeneratorType):
vector = tuple(vector)
cls = cls or type(vector)
n = n... |
#!/usr/bin/env python3
#Libraries and functions needed
import smbus #For using I2C bus
import math
import gpsd #For GPS Module
import datetime
#Initiliazation of I2C bus
bus = smbus.SMBus(1)
#Device Addresses
address = 0x68 # Sensor I2C address
address_mag = 0x0c #Sensor address for magnetometer
#Control Ad... |
#!/usr/bin/env python
import argparse
import collections
import csv
import datetime
import geoip2.database
import hashlib
import jinja2
import json
import logging
import os
import pprint
import requests
import socket
import typing
import urllib.request
import whois
HATE_SITES_CSV_DEFAULT_PATH = 'hate-sites.csv'
OUT... |
#!/usr/local/bin/python3.8
#
# DISCLAIMER: This script is not supported by Nutanix. Please contact
# <NAME> (<EMAIL>) if you have any questions.
# Last updated: 9/29/2018
# This script uses Python 3.7.
# NOTE:
# 1. You need a Python library called "requests" which is available from
# the url: http://docs.python-reques... |
# Copyright (c) <NAME> (<EMAIL>) and <NAME> (<EMAIL>)
#
# Please cite the following papers if you use any part of the code.
# - <NAME>, <NAME>, <NAME>, Deep Global Registration, CVPR 2020
# - <NAME>, <NAME>, <NAME>, Fully Convolutional Geometric Features, ICCV 2019
# - <NAME>, <NAME>, <NAME>, 4D Spatio-Temporal ConvNet... |
from gsheet_assignments import GsheetAssignments
from github import Github
import json
from buildlogs import coverage
from sys import argv
org = 'clean-s-1'
interest = 'test-failer'
title = 'clean-s-1-test-failer-assignment'
# interest = 'well-named'
# title = 'clean-s-1-well-named-assignment'
# interest = 'spring'
# ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Creates a dataset of distorted qr codes
"""
from typing import List, Tuple
import qrcode
import numpy as np
import random
import math
from PIL import Image
from pathlib import Path
from qrcode.image.styledpil import StyledPilImage
from qrcode.image.styles.moduledrawers... |
"""Cloud satellite manager
Here we use dotcloud to lookup or deploy the satellite server. This also
means we need dotcloud credentials, so we get those if we need them.
Most of this functionality is pulled from the dotcloud client, but is
modified and organized to meet our needs. This is why we pass around and
work wi... |
import os
import time
import fero
from fero import FeroError
from typing import Optional, Union
from marshmallow import (
Schema,
fields,
validate,
EXCLUDE,
)
from .common import FeroObject
class DataSourceSchema(Schema):
class Meta:
unknown = EXCLUDE
uuid = fields.UUID(required=True... |
import logging
import time
from abc import abstractmethod
from enum import Enum
from typing import Dict, Callable, Any, List
from schema import Schema
import sqlalchemy
from sqlalchemy.engine import ResultProxy
from sqlalchemy.orm import Query
from sqlalchemy.schema import Table
from sqlalchemy.engine.base import Eng... |
####################################
# File name: batch_project_elevation.py
# About: Process for batch converting elevation raster tiles.
# Author: <NAME> | Imagery & Remote Sensing Team | Esri
# Date created: 01/25/2021
# Date last modified: 01/25/2021
# Python Version: 3.7
###############################... |
import re
from astropy.table import vstack
from astroquery.jplhorizons import Horizons
import pandas as pd
pd.options.display.float_format = '{:,.4f}'.format
def decimal_to_hours(dec_time: float) -> (int, float, float):
"""transform decimal time into conventional time"""
hours = int(dec_time)
minutes = (... |
import cue.golibcue as lc
class CueError(Exception):
...
class CueValue:
def __init__(self, s):
if isinstance(s, str):
bs = s.encode('UTF-8')
out_cue_value_id = lc._cue_value_id_t()
res = lc.Compile(lc.byref(out_cue_value_id), lc.GoString(bs, len(s)))
if res is not None:
raise... |
# ==============================================================================
# This file is part of the SPNC project under the Apache License v2.0 by the
# Embedded Systems and Applications Group, TU Darmstadt.
# For the full copyright and license information, please view the LICENSE
# file that was distributed... |
"""
FSL shader generator tool
"""
import os, sys, argparse, subprocess, time
from inspect import currentframe, getframeinfo
# add fsl roots to path
fsl_root = os.path.sep.join(os.path.abspath(__file__).split(os.path.sep)[:-1])
forge_root = os.path.dirname(os.path.dirname(os.path.dirname(fsl_root)))
fsl_orbis_root ... |
# Copyright 2017 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... |
import torch
import torch.nn as nn
import torch.optim as optim
import os
from .utils import Logger
class Trainer:
def __init__(self, model, train_loader, config):
'''
config: device, checkpoints_dir, log_dir, print_every_batch, clip
learning_rate, learning_rate_decay, learn... |
#!/usr/bin/env python
# PySCUBA/src/PySCUBA/Tree_classes.py
# Author: <NAME> for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: <EMAIL>; <EMAIL>
"""Classes for flow or mass cytometry data processing, modified from the outdated 'fcm'
Python package by <NAME>.
"""
import re
import numpy as np
... |
from cmstk.structure.bravais import BaseBravais, TriclinicBravais
from cmstk.structure.bravais import MonoclinicBravais, OrthorhombicBravais
from cmstk.structure.bravais import TetragonalBravais, RhombohedralBravais
from cmstk.structure.bravais import HexagonalBravais, CubicBravais
from cmstk.structure.bravais import b... |
# SPDX-License-Identifier: Apache-2.0
# Licensed to the Ed-Fi Alliance under one or more agreements.
# The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
# See the LICENSE and NOTICES files in the project root for more information.
from datetime import datetime
from typing import List
... |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import ast
import argparse
import json
import os
import jieba.posseg as pseg
import numpy as np
# The JSON keys used in the original data files
JSON_ORI_TXT_KEY = "originalText"
JSON_ENTITIES_KEY = "entities"
JSON_START_POS_KEY = "start_pos"
JSON_END_POS_KEY = "end_pos"
... |
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.db import connections, router, transaction
from django.db.utils import IntegrityError
from django.test.testcases import TestCase
from ..models.model import ModelDefinition
from ..utils import remove_from_app... |
import json
from uuid import uuid4
from django.urls import reverse
from uritemplate import expand
from sso.oauth2.tests import OAuth2BaseTestCase
def address(addressee, country='DE', street_address='', region='', address_type='home'):
return {
'address_type': address_type,
'addressee': addressee... |
import pint
import sympy
import copy
from numbers import Real
from typing import Any, Optional, Union
from ueca.latex import translate_space_latex
ureg = pint.UnitRegistry()
ureg.default_system = "SI"
class PhysicsData:
def __init__(self, value: Any, unit: str, left_side: str = "",
symbol: Op... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module converts an AWS API Gateway proxied request to a WSGI request,
then loads the WSGI application specified by FQN in `.wsgi_app` and invokes
the request when the handler is called by AWS Lambda.
Inspired by: https://github.com/miserlou/zappa
Authors: <NAME> ... |
import os
import numpy as np
import pandas as pd
from itertools import chain, combinations
pd.set_option('display.max_rows', 1000)
bright_dark_csv = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'all_seven_note_modes_sorted_dark_to_bright.csv')
bd = pd.read_csv(bright_dark_csv)
# keep things simple for no... |
import random
import torch
import numpy as np
import random
import scipy.stats as st
def fix_seed(seed, deterministic=False):
### generate random seeds
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if deterministic:
torch.backends.cudnn.... |
import pyomo.environ as pe
from .BaseResource import BaseResource
import numpy as np
class Generator(BaseResource):
def initialize_model(self, model, scenes):
self.model = model
self.scenes = scenes
self.scene_iterator = self.model.scene_set
self.M = 1e3
#to create... |
# Code adapted from Tensorflow Object Detection Framework
# https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb
# Tensorflow Object Detection Detector
import numpy as np
import tensorflow as tf
import cv2
import time
class DetectorAPI:
def __init__(self, path... |
import xml.etree.ElementTree as ET
import re
SUBJECTID = {
"sberbank",
"vtb",
"gazprom",
"alfabank",
"bankmoskvy",
"raiffeisen",
"uralsib",
"rshb",
"beeline",
"mts",
"megafon",
"tele2",
"rostelecom",
"komstar",
"skylink",
}
SUBJECTID_TO_LABELS = {
"sberbank": "Сбер",
"vtb": "ВТБ",
"... |
#!/usr/bin/env python3
"""
This is the main file that contains the web server.
It uses flask.
"""
from flask import Flask, request, jsonify, render_template, url_for, make_response
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from db import DataBase
from config import read_config... |
import typing
from collections import OrderedDict
import pytest
from PartSegCore.class_generator import BaseSerializableClass, base_serialize_register
def setup_module():
from copy import deepcopy
from PartSegCore import class_generator
""" setup any state specific to the execution of the given module... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import io
import os
import logging
import numpy as np
import tensorflow as tf
from typing import Dict, Tuple, Optional, List
from examples.scenegen import net_def as net_module
from examples.scenegen import custom_reader as reader_module
from exa... |
import asyncio
import logging
import os
import time
from datetime import timedelta
import voluptuous as vol
import zigpy.exceptions as zigpy_exc
from homeassistant.components import websocket_api
from homeassistant.helpers.event import async_call_later, async_track_time_interval
from homeassistant.util.json import sa... |
"""
Implementation of the core of the MCMC sampler, which will make use of different kernels to
implement the different methods
A `Kernel` defines the transition probability.
Some kernels work directly with conditional probabilities :math:`p(x | y)` and :math:`p(y | x)`,
e.g. Gibbs sampling, while other methods use ... |
import os.path
import enum
# Environment variable names used to retrieve urls and api keys
# ----------------------------------------------------------------
# src is where ckan objects will be read from
# dest is where ckan objects will be written to
# CKAN_DO_NOT_WRITE_URL - This is used to protect the the prod ins... |
'''
@File : FDR_calu_write.py
@Time : 2020/8/15 4:10 下午
@Author : KeeeeepGoing(<NAME>)
@Version :
@Contact : <EMAIL>
@Desc :
'''
from typing import Dict, Any
import numpy as np
from decimal import Decimal
import pyBigWig
import scipy.stats as stats
from statsmodels.stats import multitest
from m... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division
from django.contrib.admin import site
from django.contrib.admin.options import csrf_protect_m
from django.contrib.admin.utils import unquote
from django.contrib.admin.widgets import ForeignKeyRawIdWidget, ManyToManyRawIdWidget
from django.core.u... |
# Copyright 2011 OpenStack Foundation
# Copyright 2013 Red Hat, 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
#
# Unl... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
import io
import tarfile
import itertools
from pathlib import Path
from contextlib import closing
import urllib.request as request
import pandas as pd
import networkx as nx
from tqdm import tqdm
tqdm.pandas()
def provide_taxdump(
url='ftp://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz',
file_mapping=N... |
#!/usr/bin/env python
import numpy as np
import pandas as pd
import logging
import logging.config
import os
from smos_tools.data_types.aux_distan_datatype import datatype, flag_datatype, flag_sea_ice_datatype
from smos_tools.logger.logging_config import logging_config
def read_aux_distan(filename):
"""
Read ... |
import unittest
import os, sys
def sample(input_filename, m, n, fn, fp):
# add option --use_cuts 0 to test without cutting plane
command = f'build/src-unigen/lumberjack {input_filename} -c {m} -m {n} -n {fn} -p {fp} | grep -Pzo \'.*solutions sampled(.*\\n)*\''
os.system(command)
class TestDolloSAT(unittes... |
"""A simple mock PyPI index api."""
from __future__ import absolute_import, division, print_function
import re
from collections import namedtuple
import os.path
import json
import datetime
import csv
import logging
import uuid
import struct
import time
import itertools
from future.utils import viewitems
HAS_DEPEND... |
import configparser
from datetime import datetime
import os
from pyspark.sql import SparkSession
from pyspark.sql.functions import udf, col, monotonically_increasing_id
from pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format
from pyspark.sql.types import StructType as R, StructField as ... |
"""
Functions for 2D matrix operations
"""
from typing import List, Tuple
def add(*matrix_s: List[list]) -> List[list]:
"""
>>> add([[1,2],[3,4]],[[2,3],[4,5]])
[[3, 5], [7, 9]]
>>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]])
[[3.2, 5.4], [7, 9]]
>>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], ... |
import logging
import re
from datetime import datetime
from pathlib import Path
from .makerules import pipeline_makerules
from .register import hash_value
from .schema import Schema
from .store.csv import CSVStore
from .store.item import ItemStore
collection_directory = "./collection"
def isodate(s):
return dat... |
import torch
import numpy as np
from ..domain import Domain, BoundaryDomain
from ...spaces import Points
class Circle(Domain):
"""Class for circles.
Parameters
----------
space : Space
The space in which this object lays.
center : array_like or callable
The center of the circle, ... |
"""
OpenVINO DL Workbench
Authentication Endpoints
Copyright (c) 2018 Intel 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
Unles... |
'''main.py - BMO (Braille More)
- Takes a picture with an attached rpi camera
- Processes the text from the image and puts it in a textfile
- Moves motors to represent braille characters
- Hooks up two buttons to control which characters are shown, and when to take a new image
'''
from servo import *
f... |
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
url = 'https://bbs-simulator.com/story'
chr... |
from __future__ import print_function
from __future__ import division
import os
import gdal
import pickle
import numpy as np
import scipy.misc as misc
import scipy.ndimage as ndimage
import matplotlib.pyplot as pl
def convert_lat_lon_to_xy(ds, coordinates):
lon_in, lat_in = coordinates
xoffset, px_w, rot1, ... |
"""Main script for running long experiments.
Given an experiment class, this script repeats the experiment for each number of
clients specified with the `--clients` option, and repeats the experiments the
number of times specified in `--repeat`. Each experiment is saved to a new
subdirectory of the automatically creat... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
import random
from lxml import etree
from typing import List
from nonebot.log import logger
from PIL import Image, ImageDraw
from PIL.Image import Image as IMG
try:
import ujson as json
except ModuleNotFoundError:
import json
from .base_handle import BaseHandle, BaseData
from ..config import draw... |
# 2021.07.04 modified
# 학습된 모델 이용해서 예측
import pymysql
import statiz_variables
import joblib
import pandas as pd
import numpy as np
import datetime
# get stadium id
def _get_stadium_id(stadium_name):
if stadium_name == '잠실':
return 'JS'
elif stadium_name == '고척':
return 'GC'
... |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from dataset import CelebA
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import numpy as np
import torch.utils.data as loader
# from torchsummary import summary
import tqdm
fro... |
#cython: language_level=3, boundscheck=False
from urllib.request import urlopen
import sys
import os
import shutil
import colorama
import collections
import zipfile
# initiate colorama if on windows
if os.name == 'nt':
colorama.init()
def unzip(source_filename, dest_dir):
with zipfile.ZipFile(source_filename)... |
from flask import Blueprint, request, jsonify, session, flash
from app.models import User, Post, Comment, Vote
from app.db import get_db
# Show error messages.
import sys
# Import decorator function to protect routes.
from app.utils.auth import login_required
bp = Blueprint('api', __name__, url_prefix='/api')
# Creat... |
#!/usr/bin/env python3
from tkinter import *
from tkinter import messagebox
import configparser
import xml.etree.ElementTree as ET
import grequests
import requests
import grequests
import xmltodict
# main program ################################################################
def main(*args):
# barcode
barcod... |
# Copyright 2020 Verily Life Sciences LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
"""Utils for plotting arrays in Metis."""
from metis import colors_config as cc
from metis import evaluation
i... |
'''
Created on Aug 28, 2013
@author: hpp
'''
import unittest
from task_finish import TaskTerminator
from xml.etree import ElementTree
class match_result_t(object):
'''
a match result struct
this is for testing
'''
meta_uuid = None
meta_name = None
instance_name = None
instance_id = No... |
#!/usr/bin/python3
#
# Version updater
# Copyright (C) 2016 <NAME>. All rights reserved.
#
# Please refer to readme.md for information about this source code.
# Please refer to license.txt for details about distribution and modification.
#
# Updates various version constants based on HASHCHECK_VERSION_STR in v... |
import inspect
import os
from typing import Any, Optional
from urllib.parse import urlparse, quote
from warnings import warn
from gemd.entity.link_by_uid import LinkByUID
def get_object_id(object_or_id):
"""Extract the citrine id from a data concepts object or LinkByUID."""
from gemd.entity.attribute.base_at... |
import pandas as pd
from astropy import coordinates
from astropy.coordinates import SkyCoord
from astropy import units as u
#from astroquery.ned import Ned #necessary for one method
#from astroquery.ned.core import RemoteServiceError #necessary for one method
#from dustmaps.sfd import SFDQuery
#not working under windo... |
#!/usr/bin/env python3
# -----------------------------------------------------------------------------
import socket
import time
from signal import signal, SIGINT
import fcntl, os
import errno
import sys
import struct
# -----------------------------------------------------------------------------
from settings_com... |
################################################################################
# Copyright (c) 2021 ContinualAI. #
# Copyrights licensed under the MIT License. #
# See the accompanying LICENSE file for terms. ... |
import base64
import json
import os
import re
from datetime import datetime, timedelta
from hashlib import sha256
from hmac import new as hmac
from typing import (Any, Dict, Iterator, List, NamedTuple, Optional, Pattern,
Set, TypeVar)
from urllib.parse import quote, unquote
import boto3
import boto... |
from typing import List, Optional
from memory_shaper.algorithm.FlashCardAlgo import get_modified_card, FlashCardAlgorithm
from memory_shaper.tmp_cards import CARDS, init_queue, get_queue
from flask import render_template, redirect, url_for, request, session
from app import app
from memory_shaper.app import new_sql_s... |
import requests
import json
import re
import threading
header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',... |
import re
import shlex
from io import BytesIO
from typing import List, Optional
from nonebot.rule import Rule
from nonebot import get_driver
from nonebot.typing import T_State
from nonebot.params import State, Depends
from nonebot.adapters.onebot.v11 import (
Bot,
Message,
MessageSegment,
MessageEvent,... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
import os
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from django.core.validators import MinLengthValidator
from django.db import models
from django.db.models.signals import post_delete
from dja... |
#!/usr/bin/python3
import sys, csv, argparse, traceback, time, socket
from raritan.rpc import Agent, usermgmt, HttpException
from raritan import zeroconf
HTTP_AGENT_TIMEOUT_DEFAULT = 5
ZEROCONF_TIMEOUT_DEFAULT = 4
USER_DEFAULT = "admin"
PASSWORD_DEFAULT = "<PASSWORD>"
class PduPasswordChangeData:
def __init__(se... |
import sys
import argparse
from os.path import isdir
import torch as t
from torch.utils.data import DataLoader
from torch.nn import BCELoss
from torch.optim import Adam, SGD
from gensim.models.fasttext import FastText
from py.data.JSONInMemoryDataset import JSONInMemoryDataset
from py.data.Util import json_files_in_di... |
"""
Copyright 2019 Samsung SDS
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 ... |
from pyneval.metric.utils import edge_match_utils
from pyneval.metric.utils.metric_manager import get_metric_manager
from pyneval.metric.utils import basic_utils
metric_manager = get_metric_manager()
class LengthMetric(object):
"""
length metric
"""
def __init__(self, config):
# read config
... |
import os.path as osp
import argparse
import numpy as np
import torch
import torch.nn.functional as F
import torch_geometric.transforms as T
from torch_geometric.nn import GCNConv, ChebConv # noqa
from torch.nn import Parameter
from sklearn.utils import class_weight
from sklearn.metrics import confusion_matrix
data... |
import BioLogic
import pandas as pd
import numpy as np
import glob
import os.path
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from numpy import matlib
'''
Finds nucleation overpotential through identifying the minimum (most negative) point in the numpy array voltage column.
plotGraph() and ba... |
from flask import Blueprint, render_template, request,session
import modules.load_data_postgre as ps
import url_handlers.filtering as filtering
from webserver import rdb, all_measurement, data, measurement_name, block, df_min_max
basic_stats_page = Blueprint('basic_stats', __name__, template_folder='basic_stats')
... |
"""This is used to:
1.get the Train and val Datast,
considering the train augument later
2.get the optimizer
"""
from dataset.Get_Dataset import GetDataset
from torch.utils.data import DataLoader
import torch.optim as optim
from utils.tools import make_dirs
import torch
import sys
import numpy ... |
# -*- coding: utf-8 -*-
import unittest
from abc import ABC
class GildedRose(object):
aged_brie = "Aged Brie"
sulfuras = "Sulfuras, Hand of Ragnaros"
conjured = "Conjured Mana Cake"
passes = "Backstage passes to a TAFKAL80ETC concert"
def __init__(self, items):
self.items = items
def... |
# Module to run tests on generating AbsSystem
from __future__ import print_function, absolute_import, division, unicode_literals
# TEST_UNICODE_LITERALS
import numpy as np
import os
import pytest
from astropy import units as u
from astropy.coordinates import SkyCoord
from linetools.isgm.abscomponent import AbsComp... |
'''
Reference Link: https://algorithmtutor.com/Data-Structures/Tree/Splay-Trees/
Data Structure:
1. Splay Tree is a type of Binary Search Tree that keeps the recently operated nodes at the root for
subsequent opertations. For ex: if we search a node, it will be moved to the root. This process is
called Spl... |
from typing import Tuple, Callable, Any, Optional, List
import numpy as np
from .parameters import TestingToDetection, Population
from autumn.core.inputs import get_population_by_agegroup
from autumn.settings import COVID_BASE_AGEGROUPS
from autumn.core.utils.utils import apply_moving_average
from autumn.model_feature... |
"""Representation of VOI Nearest Scooter Sensors."""
from datetime import timedelta
import logging
from geopy.distance import distance
import requests
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_BATTERY_LEVEL,
... |
import os
import re
import sys
import json
import math
import datetime
import subprocess
import logging
import coloredlogs
coloredlogs.install()
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
from typing import Dict, Callable
from docopt import docopt
from sh import montage
from typing import List
fro... |
"""
generate the nodes and weights for the Tanh-Sinh integration scheme
Use high precision mpmath library to pre-calculate the nodes and weight
and save them to a file.
the principal variable transformation x -> t which maps x in [0, b] to t in [-inf, inf]
x(t) = b/2(1 - g(t))
g(t) = tanh(pi/2 * sinh(t))
See... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.