text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
"""
Copyright (c) 2019, by the Authors: <NAME>
This script is freely available under the MIT Public License.
Please see the License file in the root for details.
The following code snippet will convert the keras model files
to the freezed .pb tensorflow weight file. The resultant TensorFlow model
... |
from re import I
import sys
import time as tt
from itertools import cycle
TESTCASE = sys.argv[1] if len(sys.argv) > 1 else ""
DEBUG = True
"""
C: number of contributors
P: number of projects
contributors: K(name), V(contributor)
projects: K(name), V(project)
"""
def main():
# PARSE
C, P = sy... |
import os
import sys
import subprocess
import pathlib
try:
import pymake
except:
msg = 'Error. Pymake package is not available.\n'
msg += 'Try installing using the following command:\n'
msg += ' pip install https://github.com/modflowpy/pymake/zipball/master'
raise Exception(msg)
try:
import fl... |
#!/usr/bin/env python
"""
fitting
Phenome library
biolog data fitting functions
"""
from ductape.common.utils import compress, smooth
try:
from scipy.optimize.minpack import curve_fit
except ImportError:
# Old version of SciPy, manual addition of curve_fit
# This three functions are borrowed from the... |
import torch
from torch import nn
import torch.nn.functional as F
class Flatten(nn.Module):
def forward(self, x):
bs = x.size(0)
return x.view(bs, -1)
class GaussianNoise(nn.Module):
def __init__(self, sigma=0.1):
super().__init__()
self.sigma = sigma
self.noise = tor... |
import pandas as pd
import os
from tqdm import tqdm
import json
def news():
paths = os.listdir('文本分类数据集/ClassFile')
label = []
text = []
for path in tqdm(paths):
if path == '.DS_Store':
continue
p = '文本分类数据集/ClassFile/' + path
file_path = os.listdir(p)
fo... |
"""
A collection of tests covering user management in DC/OS.
Assume that access control is activated in Master Admin Router (could be
disabled with `oauth_enabled`) and therefore authenticate individual HTTP
requests.
One aspect of DC/OS user management is that once authenticated a user can add
other users. Unauthent... |
import re
from inspect import signature
from typing import Optional
import pytest
from sklearn.utils import all_estimators
numpydoc_validation = pytest.importorskip("numpydoc.validate")
# List of modules ignored when checking for numpydoc validation.
DOCSTRING_IGNORE_LIST = [
"Birch",
"FeatureHasher",
"F... |
"""Common fixtures to be used across tests."""
from typing import Any, Dict
import os
import pytest
import yaml
from fideslang import models
from fidesctl.core.config import get_config
from fidesctl.core import api
TEST_CONFIG_PATH = "tests/test_config.toml"
TEST_INVALID_CONFIG_PATH = "tests/test_invalid_config.toml... |
"""CTS object proxies"""
import xml.sax
from xml.sax.handler import ContentHandler
from typing import NamedTuple, Any, List
from sap.adt.core import mod_log
# pylint: disable=too-few-public-methods
class Element(NamedTuple):
"""Intermediate XML element representation"""
attributes: Any
children: List
... |
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# 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, inc... |
import datetime
import importlib
def get_sample_bc(sample_bc_list):
sample_bc_dic={}
with open(sample_bc_list) as input:
for line in input:
if line.strip():
[sample, bc]=line.strip().split()
sample_bc_dic[bc]=sample
return sample_bc_dic
def get_prefix(prefix_list):
# items split by space or tab
... |
# -*- coding: utf-8 -*-
"""
Krystek (1985) Correlated Colour Temperature
============================================
Defines *Krystek (1985)* correlated colour temperature :math:`T_{cp}`
computations objects:
- :func:`colour.temperature.uv_to_CCT_Krystek1985`: Correlated colour
temperature :math:`T_{cp}` compu... |
# Copyright 2016 Pinterest, 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... |
import json
import time
import re
import requests
from lxml import html
from pprint import pprint
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
# author: adrian_young
# github: https://github.com/adrianyoung/
# description: th... |
"""
Provides functionality for mailboxes.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/mailbox/
"""
import asyncio
import logging
from contextlib import suppress
from datetime import timedelta
import async_timeout
from aiohttp import web
from aioht... |
import json
from os import listdir
from os.path import isfile
from os.path import join
from termcolor import colored
from graphbrain.cli import wrapper
from graphbrain.colored import colored_atom
from graphbrain.colored import colored_edge
from graphbrain.colored import colored_type
from graphbrain.hyperedge import b... |
import os
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import auc
from sklearn.metrics import roc_curve
def set_matplotlib_font(font_weight="bold", font_size=10):
font = {
"weight": font_weight,
"size": font_size
}
matplotlib.rc("font", **font)
... |
# -*- coding: utf-8 -*-
import os
import random
import shutil
import unittest
from collections import defaultdict
import six
from six import StringIO
import networkx as nx
from networkx.algorithms.traversal.depth_first_search import dfs_edges
import anadama2
import anadama2.grid.sge
import anadama2.backends
from anad... |
from typing import Callable, Generator, Iterable, Optional, Set
from scmrepo.git import Git
from dvc.exceptions import InvalidArgumentError
from .base import (
EXEC_BASELINE,
EXEC_NAMESPACE,
EXPS_NAMESPACE,
EXPS_STASH,
ExpRefInfo,
)
def exp_refs(scm: "Git") -> Generator["ExpRefInfo", None, None... |
# Copyright 2017 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
#
# Unless required by applicable law or agreed to in wri... |
"""Parses struct and union definitions in header file.
Expects file content without comments and preprocessor definitions.
"""
import re
from .params_info import Param
from .params_info import parse_one_param
from .params_info import split_param_to_type_and_name
from .parse_enums import parse_enum
from .utils import... |
from sympy import var, sqrt, exp, simplify, S, integrate, oo, Symbol
from sympy.physics.hydrogen import R_nl, E_nl, E_nl_dirac
from sympy.utilities.pytest import raises
var("r Z")
def feq(a, b, max_relative_error=1e-12, max_absolute_error=1e-12):
a = float(a)
b = float(b)
# if the numbers are close enough... |
"""
Copyright (c) 2018-2022 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
Unless required by applicable law or agreed to in wri... |
"""Numeric integration of data coming from a source sensor over time."""
from decimal import Decimal, DecimalException
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
CONF_METHOD,
... |
"""
Organization API endpoints - create/update/delete/list organizations
"""
import uuid
import flask
import sqlalchemy
from .. import model, util
from . import util as web_util
from .blueprint import web_api
@web_api.route("/organization")
@util.cross_origin(methods=["GET"])
def list_organizations():
result =... |
# -*- encoding: utf-8 -*-
'''
@File : rest_client.py
@License : (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2021/4/2 19:15 <NAME> 1.0 None
'''
import sys
import traceback
from datetime im... |
#!/usr/bin/python
# Copyright (c) 2017, 2018, 2019 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT... |
import json
import torch
import opennre
import sys
import os
import argparse
import logging
import random
import numpy as np
def set_seed(seed):
"""set random seed"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
parser = argpars... |
import nig
import os
import random
import re
__author__ = '<NAME>'
class Grammar:
def __init__(self, syntax_file, working_dir='.', start_symbol=None,
start_attributes=frozenset({})):
self.rules = self._read_syntax_from_file(
filename=syntax_file, working_dir=working_dir)
... |
from vyper.exceptions import TypeMismatch
def test_return_type(get_contract_with_gas_estimation):
long_string = 35 * "test"
code = """
struct Chunk:
a: Bytes[8]
b: Bytes[8]
c: int128
chunk: Chunk
@external
def __init__():
self.chunk.a = b"hello"
self.chunk.b = b"world"
self.chunk.c =... |
from copy import deepcopy
from time import sleep
from datetime import datetime, timedelta
from corehq.util.metrics import create_metrics_event
from custom.icds_reports.cache import icds_quickcache
from custom.icds_reports.const import LocationTypes
from custom.icds_reports.reports.awc_infrastracture import get_awc_in... |
import re
import pytest
from tests.common.helpers.assertions import pytest_assert
from tests.common.utilities import wait_until
pytestmark = [
pytest.mark.topology('any')
]
logger = logging.getLogger(__name__)
# Helper functions
def get_dict_stdout(gnmi_out, certs_out):
""" Extracts dictionary from redis ou... |
from typing import List, Optional
from django.http import HttpRequest
from datetime import date
from ..models import (
Invoice, Student, Service,
InvoiceStatusChangeLog,
InvoicePayment, Subject,
)
from django.db import transaction
OFFSET = 15
def get_invoices_per_page(page: int = 0) -> List[Invoice]:
... |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import logging
import requests
from indra.config import get_config
from indra.literature import pubmed_client
# Python3
try:
from functools import lru_cache
# Python2
except ImportError:
from functo... |
"""MNIST database of handwritten digits
Based on https://nextjournal.com/gkoehler/pytorch-mnist
"""
import torch
import torchvision
from matplotlib import pyplot as plt
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
batch_size_train = 64
batch_size_test = 1000
# specify transform ... |
# Copyright (C) 2004-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PRO... |
import rospy
import sys
from sensor_msgs.msg import Image, LaserScan
import matplotlib.pyplot as plt
import time
import numpy as np
import cv2
import base64
from geometry_msgs.msg import PoseStamped
print("**************************HELLO I AM ROBOROACH!**************************")
print("********************I WILL FIN... |
import numpy as np
import scipy as sp
# Get the matrix inverse square root of a symmetric matrix with eigenvalue
# thresholding. This is particularly useful for calculating preconditioners.
def get_sym_matrix_inv_sqrt(hessian, ev_min=None, ev_max=None):
hessian_sym = 0.5 * (hessian + hessian.T)
eig_val, eig_v... |
import yaml
import argparse
import numpy as np
from attrdict import AttrDict
import torch
import torch.utils.data as data_utils
from torch.autograd import Variable
from models.generator import Generator
from models.discriminator import discriminator
from dataset import CatsDataset
def weights_init(m):
classnam... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from .utils import (
Wallet, HDPrivateKey, HDKey
)
from .network import *
import inspect
def generate_mnemonic(strength=128):
_, seed = HDPrivateKey.master_key_from_entropy(strength=strength)
return seed
def generate_child_id()... |
#!/usr/bin/env python3
#
# Copyright (C) [2020] Futurewei Technologies, Inc.
#
# FORCE-RISCV is 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
... |
# -*- coding: utf-8 -*-
"""
This module contains backports to support older Python versions.
They contain the backported code originally developed for Python. It is
therefore distributed under the PSF license.
"""
#
# (C) Python Software Foundation, 2001-2014
# (C) with modifications from Pywikibot team, 2015
#
# Dist... |
import asyncio
import json
import subprocess
from os.path import isfile
from typing import Dict, Optional
import discord
from discord.ext import commands
from util.create_file import create_file_if_not_exists
from util.json import writeJSON
SERVER_LIST = ("thetis", "remote", "annacis", "anvil", "bowen", "lulu")
OTHE... |
# Copyright 2016 WiseDoge
# 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 ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Source: http://pybrain.org/docs/tutorial/fnn.html
import matplotlib
matplotlib.use('Qt4Agg')
from pybrain.datasets import ClassificationDataSet
from pybrain.utilities import percentError
from pybrain.tools.shortcuts import buildNetwork
from pybrain.supervised.trainers im... |
from django.contrib import admin
from django.conf.urls.defaults import patterns, url
from django.db import transaction
from django.db.models.fields.related import RelatedField
from django.contrib.admin.actions import delete_selected
from django.utils import timezone
from .views import NewTournamentRoundView
from .mode... |
import pymysql
from pypinyin import lazy_pinyin
# 创建表search_xfbm_jb
from utils.db_connection import ZB_DB_DICT, FX_DB_DICT, fx_pymysql, zb_pymysql
sql1 = """
create table search_xfbm_jb(
jb int not null,
xfbm varchar(64),
xfbm_alpha varchar(64)
);
"""
# 创建表search_qh_zrdw_jb
sql2 = """
create ... |
from sklearn.model_selection import train_test_split
from keras.callbacks import ModelCheckpoint
from keras.layers import Input
from keras.layers.core import RepeatVector
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import Bidirectional
from keras.models import Model
from keras.preprocessing impor... |
#!/usr/bin/env python3
import codecs
import json
import os
from urllib.request import urlopen
import yaml
def load_config(directory):
_repo_config = {}
for _basedir, _, _filenames in os.walk(directory):
for _filename in _filenames:
if not _filename.endswith('.yaml'):
cont... |
#!/usr/bin/python3
"""Paste subtitles into other subtitles at a given timestamp."""
import datetime
import logging
import srt
from types import GeneratorType
from . import _cli
from . import _utils
log = logging.getLogger(__name__)
def paste(subs, copy, timestamp, space=datetime.timedelta(0), block=False):
""... |
# QEMU Monitor Protocol Python class
#
# Copyright (C) 2009, 2010 Red Hat Inc.
#
# Authors:
# <NAME> <<EMAIL>>
#
# This work is licensed under the terms of the GNU GPL, version 2. See
# the COPYING file in the top-level directory.
import json
import errno
import socket
import logging
class QMPError(Exception):
... |
import sys
import copy
import os.path as osp
from typing import Optional
import torch
import torch.utils.data
from torch_sparse import SparseTensor, cat
class ClusterData(torch.utils.data.Dataset):
r"""Clusters/partitions a graph data object into multiple subgraphs, as
motivated by the `"Cluster-GCN: An Effi... |
def __generate_server_classic(fname):
code = r'''#!/usr/bin/env python
# Code from: https://github.com/tomerfiliba-org/rpyc
"""
classic rpyc server (threaded, forking or std) running a SlaveService
usage:
rpyc_classic.py # default settings
rpyc_classic.py -m forking -p 12345 ... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import os
i... |
"""
Utilities for flagging zones for refinement in a dataset
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with th... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import si... |
import logging
from time import time
import six
from django.db import models, DatabaseError
from django.core.urlresolvers import reverse
from django.conf import settings
from . import app_settings
from explorer.utils import (passes_blacklist, swap_params, extract_params, shared_dict_update, get_connection,
... |
"""
Prints a comparison between different serializers.
Compares results based on size of the output, and time taken to (de)serialize.
"""
from __future__ import print_function
from timeit import default_timer as perf_timer
import sys
import datetime
import decimal
import uuid
import Pyro4.util
import Pyro4.errors
impo... |
"""Transformations related to cameras.
See :doc:`camera` for more information.
"""
import numpy as np
from .transformations import invert_transform, transform
def make_world_grid(n_lines=11, n_points_per_line=51, xlim=(-0.5, 0.5),
ylim=(-0.5, 0.5)):
"""Generate grid in world coordinate frame.... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 22:47:23 2015
@author: Joakim
Python version: 3.4.1
Reads a website, determines wheter a package is old or new.
If package is old, downloads a newer one.
Else, does nothing.
NOTE:
This is a raw version, it does not work in conjunction with other codes.
Yet.
"""
i... |
import pygame
from queue import PriorityQueue
WIDTH = 700
screen = pygame.display.set_mode((WIDTH , WIDTH))
pygame.display.set_caption("A star algorithm Visualizer")
LIGHT_GREEN = (128, 255, 128)
DARK_GREEN = (0, 153, 51)
BLUE = (0, 255, 0)
YELLOW = (255, 255, 0)
WHITE = (255, 255, 255)
OBSCOLOR = (0, 3... |
# coding: utf-8
import math
import torch
from torch.nn.parameter import Parameter
import torch.nn as nn
import torch.nn.functional as F
# EvolveGCN: Evolving Graph Convolutional Networks for Dynamic Graphs
# For more information, please refer to https://arxiv.org/abs/1902.10191
# We modify and simplify the code of Ev... |
#!/usr/bin/env python3
import sys
import math
import numpy as np
import sympy as sp
from rednose import KalmanFilter
from rednose.helpers.ekf_sym import EKF_sym, gen_code
from selfdrive.locationd.models.constants import ObservationKind
i = 0
def _slice(n):
global i
s = slice(i, i + n)
i += n
return s
cla... |
import torch
from torch import nn
import numpy as np
class GCN(nn.Module):
""" Graph convolution unit (single layer)
"""
def __init__(self, num_state, num_node, bias=False):
super(GCN, self).__init__()
self.conv1 = nn.Conv1d(num_node, num_node, kernel_size=1)
self.relu = nn.ReLU(in... |
graph_client_dict = {}
current_server = None
reloaded_graph = None
# Called for every client connecting
def new_client(client, server):
global reloaded_graph
client['lock'] = True
if client['id'] not in graph_client_dict :
# If some other client has left (cf. client_left())
if reloaded_graph :
graph_client... |
from os import truncate
from sacremoses import MosesPunctNormalizer
from sacremoses import MosesTokenizer
from sacremoses import MosesDetokenizer
from subword_nmt.apply_bpe import BPE, read_vocabulary
import codecs
from tqdm import tqdm
from indicnlp.tokenize import indic_tokenize
from indicnlp.tokenize import indic_de... |
import os
import time
import json
import logging
import torch
from pprint import pprint
from easydict import EasyDict as edict
import yaml
def save_state(net, acc, epoch, loss, config, ckpt_path, is_best=False):
print('Saving..')
state = {
'net': net,
'acc': acc,
'epoch': epoch,
... |
from django.db import transaction
from rest_framework import status
from rest_framework.exceptions import NotFound
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.mixins import ListModelMixin
from rest_framework.generics import GenericAPIView, ListCreateAPIView,... |
"""Login.gov/authorize is redirected to this endpoint to start a django user session."""
import logging
from django.conf import settings
from django.contrib.auth import get_user_model, login
from django.core.exceptions import SuspiciousOperation
from django.http import HttpResponseRedirect
from django.utils import tim... |
# Copyright (c) 2014, MapR Technologies
#
# 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 agree... |
import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile, rmtree
from typing import Generator
import datasets.config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.load import dataset_module_factory, import_main_c... |
import importlib
import subprocess
import sys
import os
import time
import traceback
from pathlib import Path
from typing import List, Union, Dict
from rich import traceback as rich_traceback
from hexagon.domain.tool import ActionTool
from hexagon.domain.tool.execution import ToolExecutionData
from hexagon.domain.env... |
# python3 steven
import cv2
import argparse
import numpy as np
# ----------------------------------------------
# usgae: python yolo_opencv.py -i dog.jpg -c yolov3.cfg -w ./darknet-master/yolov3.weights -cl yolov3.txt
# usgae: python yolo_opencv.py -i dog.jpg -c yolov3.cfg -w ./darknet-master/yolov3.weights -... |
import numpy as np
import itertools
import matplotlib.pyplot as plt
from skimage.transform import resize
from vai_.utils.utils import rect_factors
from scipy.signal import savgol_filter
def plot_images(images, titles=None, pixel_range=(0, 255), cmap=None, merge_shape=None, resize='smin', retain=False, savepath=None):... |
from django.db import models
from imagekit.models import ImageSpecField
from imagekit.models.fields.utils import ImageSpecFileDescriptor
from imagekit.registry import generator_registry, unregister
from imagekit.specs import SpecHost, create_spec_class
from imagekit.specs.sourcegroups import ImageFieldSourceGroup
fro... |
from torch.utils.data import DataLoader, random_split
from torch.utils.tensorboard import SummaryWriter
from dataset import HANDataset
import torch
import torch.nn as nn
import time
import numpy as np
from config import Config
from tqdm import tqdm
import os
from pathlib import Path
from evaluate import evaluate
import... |
import os
import json
import numpy as np
import torch
from tqdm.auto import tqdm
from models import CNN
from configs import CnnConfig
from utils import load_json
import cv2
import glob
def replace_nan(x, y):
x = 0.0 if np.isnan(x) else x
y = 0.0 if np.isnan(y) else y
return x, y
def draw_hands(
im... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
#fuction:client
from hashlib import sha1
import_flag = True
try:
from ckuser.sqlhelper.MySQLHelper import MySQLHelp
from ckuser.sqlhelper.RedisHelper import RedisHelp
from ckuser.config import *
except Exception:
import_flag = False
if import_flag == True:
pass
else:
fro... |
#!/usr/bin/env python
# Copyright (c) 2014 CensoredUsername
#
# 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, mod... |
import numpy as np
import scipy.linalg
from time import time
from abc import ABC, abstractmethod
class BaseRSVD:
def __init__(self, Q, **kwargs):
start = time()
self._U, self._D, self._Vh = self._compute(Q, **kwargs)
self._duration = {'Factorization': time() - start}
@property
def ... |
"""For evaluating and plotting losses for every segmentation (eg, every year)
Designed to handle the different Loss, mean/median bias and different
TimeSegmenator.
How to use:
-Pass the forecasted and observed data via the constructor
-Call the method evaluate_loss() to evaluate the loss for a given
... |
import unittest
from unittest import TestCase
from colored import fg, bg, attr
from microproxy.viewer.console import (
ColorText, TextList, StatusText, Header,
Request, Response, construct_status_summary,
construct_color_msg)
from microproxy.context import (
ViewerContext, HttpRequest, HttpResponse)
... |
"""
This file deals with all of the email functions.
"""
import logging
from flask import render_template, current_app
from flask_mail import Message
from ..app import db_session
from ..proxies import current_repo
from ..models import Email, Subscription, User, Post
from ..utils.render import render_post
logger = l... |
import os
import sys
import re
import pathlib
from . import OperatorHeader
from . import OperatorTypeResolver
from . import OperatorSets
from . import OperatorStubs
from .OnnxWrapper import OnnxSchema
from . import OperatorInfo
from . import args
import itertools
def note(text, verbosity=0 ):
if verbosity <= args.... |
import time
import pytest
from essentials.caching import Cache, ExpiringCache, lazy
@pytest.mark.parametrize(
'cache',
[Cache(), ExpiringCache(lambda _: False)]
)
def test_cache__getitem_throws_keyerror(cache: Cache):
with pytest.raises(KeyError):
cache["cat"]
@pytest.mark.parametrize(
'cac... |
import cv2
import numpy as np
import pandas as pd
import torch
import torch.backends.cudnn as cudnn
from torch.utils.data import DataLoader
from dataset import calculate_coverage_class, TestDataset
from metrics import precision
from processing import crf_batch
from transforms import downsample
image_size_original = 1... |
"""
#Trains a TCN on the IMDB sentiment classification task.
Output after 1 epochs on CPU: ~0.8611
Time per epoch on CPU (Core i7): ~64s.
Based on: https://github.com/keras-team/keras/blob/master/examples/imdb_bidirectional_lstm.py
"""
import os
import shutil
import keract # pip install keract
import keras
import mat... |
# pylint: disable=I0011,W0613,W0201,W0212,E1101,E1103
from __future__ import absolute_import, division, print_function
from distutils.version import LooseVersion
import tempfile
import io
import os
import sys
import pytest
from mock import patch, MagicMock
import numpy as np
try:
from IPython import __version__... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
class BehaviorContextTests:
spawner_initialized = (
"Successfully initialized an Empty Instance Sp... |
# -*- coding: utf-8 -*-
#
# Copyright © 2009- The Spyder Development Team
# Licensed under the terms of the MIT License
"""
Compatibility functions
"""
from __future__ import print_function
import sys
import collections
from . import PYQT4
from .QtWidgets import QFileDialog
from .py3compat import is_t... |
# 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 u... |
import random
from flags import VERBOSE_FLAG
OBJECTS_TYPES = {"user", "post", "comment", "location", "checkin", "page"}
ASSOCIATION_TYPES = {"liked", "tagged_at", "authored", "friend", "checked_in", "has_comment"}
INV_ASSOCIATION_TYPES = {"liked_by", "tagged", "authored_by", "friend", "locationed"}
##
# How to read... |
import logging
import click
from jccli import helpers as jccli_helpers
from jccli.jc_api_v1 import JumpcloudApiV1
from jccli.jc_api_v2 import JumpcloudApiV2
def abort_if_false(ctx, param, value):
# pylint: disable=unused-argument
"""
A click handler for user prompts
"""
if not value:
ctx.... |
import json
import os
import time
import sys
import gc
from onewire import OneWire
from machine import Pin
import uasyncio as asyncio
from nanoweb import HttpError, Nanoweb, send_file
from ubinascii import a2b_base64 as base64_decode
CREDENTIALS = ('foo', 'bar')
EXAMPLE_ASSETS_DIR = './example-assets/'
def get_time(... |
#!/usr/bin/env python3
from typing import Dict, Optional, AnyStr
import re
import signal
from time import sleep
from urllib.parse import urlencode
from urllib.request import urlopen
from urllib.error import HTTPError
from hashlib import sha256
from pid.decorator import pidfile
from djing.lib.messaging.sms import SmsSu... |
# Copyright (c) Microsoft Corporation and contributors.
# Licensed under the MIT License.
import numpy as np
import pytest
from numpy import allclose, array_equal
from numpy.linalg import norm
from numpy.testing import assert_allclose
from graspologic.embed.omni import OmnibusEmbed, _get_omni_matrix
from graspologic.... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from collections import deque
from tqdm import tqdm
from agents import BaseAgent
# --------------------
# MDP
# --------------------
class AccessQueueMDP:
"""
Example 10.2 - An access-control queuing task
States -- list of (number ... |
from enum import Enum
from typing import Any, List, Optional, Type, Union
import click
from click import Choice, Context, Parameter
from ape import accounts, networks
from ape.api.accounts import AccountAPI
from ape.exceptions import AccountsError
def _get_account_by_type(account_type: Optional[Type[AccountAPI]] = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.