text stringlengths 2 999k |
|---|
"""
# Copyright 2021 Huawei Technologies Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
"""
Compute the plane wave decomposition for an incident broadband plane wave
on an open circular array using a modal beamformer of finite order.
"""
import numpy as np
import matplotlib.pyplot as plt
import micarray
from micarray.util import db
Nsf = 50 # order of the incident sound field
N = 30 # order of... |
# file eulexistdb/manager.py
#
# Copyright 2010,2011 Emory University Libraries
#
# 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
#
... |
class Soma:
def __init__(self):
self.numeroDeCartas = list()
def set_numeroDeCartas(self, numero):
if numero == '':
numero = '1'
numero = numero[:]
self.numeroDeCartas.extend(numero)
def get_numeroDeCartas(self):
... |
import torch, math
from torch.optim.optimizer import Optimizer
# RAdam + LARS
class Ralamb(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0):
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay)
self.buffer = [[None, None, None] for in... |
# RUN: %PYTHON %s | FileCheck %s
import gc
import io
import itertools
from mlir.ir import *
def run(f):
print("\nTEST:", f.__name__)
f()
gc.collect()
assert Context._get_live_count() == 0
# Verify iterator based traversal of the op/region/block hierarchy.
# CHECK-LABEL: TEST: testTraverseOpRegionBlockIterat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pypepa documentation build configuration file, created by
# sphinx-quickstart on Thu Jul 18 15:33:13 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autog... |
from django.urls import path
from . import views
urlpatterns = [
path('StatsClass', views.index),
path('BasicProbability', views.basic_prob),
]
|
class DigitalSignatureScheme(object):
def get_public_key(self):
return self.public_key
def sign(self, messsage):
raise NotImplementedError
def verify(self, message, signature):
raise NotImplementedError
|
"""
Created by Michele Bianco, 9 July 2021
"""
import numpy as np, pkg_resources
from tqdm import tqdm
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras import backend as K
from tensorflow.python.ops import nn_ops
from tensorflow.python.framework import ops
from tensorflow.... |
# coding: utf-8
"""
Sunshine Conversations API
The version of the OpenAPI document: 9.4.5
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from sunshine_conversations_client.configuration import Configuration
from sunshine_conversations_client.undefine... |
import cv2 as cv
import numpy as np
import os
def preprocess(labels_path, sep_labels_path):
# list all files on labels_path
labels_filenames = os.listdir(labels_path)
count = 0
for label_filename in labels_filenames:
label_path = os.path.join(labels_path, label_filename)
print(f'segme... |
"""EPR Socket interface."""
from __future__ import annotations
import abc
import logging
from contextlib import contextmanager
from typing import TYPE_CHECKING, Callable, ContextManager, List, Optional, Tuple, Union
from netqasm.logging.glob import get_netqasm_logger
from netqasm.qlink_compat import (
EPRRole,
... |
# Copyright 2020 Google LLC. 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... |
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... |
import pandas
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as st
from pylab import rcParams
df = pandas.read_csv('rewards_loc3.csv')
ucb,ts,ovr,egr,egr2,agr,agr2,efr,ac,aac,sft = df['ucb'],df['ts'],df['ovr'],\
df['egr'],df['egr2'],df['agr'],df['agr2'],df['efr'],df['ac'],df['aac'],df['sft']
... |
XXXXXXX FFFFXFFFFXXXXXXXXX
|
from datetime import datetime
from dino.config import UserKeys, RedisKeys, SessionKeys
from dino.db.rdbms.models import Channels
from dino.db.rdbms.models import Rooms
from test.base import BaseTest
from test.db import BaseDatabaseTest
class DatabaseSqliteTest(BaseDatabaseTest):
def setUp(self):
self.set... |
import pandas as pd
__author__ = 'slei'
class AddHeuristicTSP:
""" Finds the shortest path using a heuristic method """
def __init__(self, cities_df):
self.df = cities_df
self.edges = list((t.origin, t.destination) for t in df.itertuples())
self.distance = dict([((t.origin, t.destina... |
import numpy as np
from scipy.spatial.distance import euclidean
from typing import Union
import pandas
class CLOSE(object):
def __init__(self, data: pandas.DataFrame, measure: Union[str, callable] = 'mse', minPts: int = None, output: bool = False,
jaccard: bool = False, weighting: bool = False, ... |
import discord
from discord.ext import commands
from Modules import CONSTANT
from Modules.Checks import check_if_role_or_bot_spam
class Roles(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command()
@check_if_role_or_bot_spam()
async def role(self, ctx: comman... |
from django.db import models
from django.forms import ModelForm
from django.forms import TextInput
from .models import agendamento
#import datetime
#class frm_agendamento(forms.ModelForm):
#
# data_agendamento = forms.DateField(label="Data",initial=datetime.date.today)
# horario_inicio = forms.TimeField(label="In... |
# Copyright 2020 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, sof... |
# a = 2
print("check this file")
|
# technical
from .base_output import BaseOutput
# default
from .matplotlib_plot import MatplotlibPlot
from .extrema_printer import ExtremaPrinter
# with external dependencies
# import are respective __init__ methods
# hack-ish, but works (and I am not aware of a more proper way to do so)
from .bokeh_plot import Bo... |
#!/usr/bin/env python3
# Copyright (c) 2016 The Sikacoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test Hierarchical Deterministic wallet function."""
from test_framework.test_framework import SikacoinTest... |
import torch.nn as nn
import torch
from torch.autograd import Variable
import math
import torch.utils.model_zoo as model_zoo
from commons.siam_mask.models.features import Features
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://dow... |
import tensorflow as tf
from tensorflow.python.client import device_lib
def get_available_gpus():
local_device_protos = device_lib.list_local_devices()
return [x.name for x in local_device_protos if x.device_type == 'GPU']
gpus = get_available_gpus
def split_nest(nest, num_or_size_splits, axis=0):
"""... |
# import gevent.monkey
# gevent.monkey.patch_socket()
from pyEtherCAT import MasterEtherCAT
import time
import os
#============================================================================#
# C95用の簡易EtherCATパッケージです。
# 本来は細かいパケットに付いて理解を深めた上で仕組みを構築していきますが、
# 説明も実験も追いつかず、ひとまずGPIOで高速にON/OFF出来る部分だけを纏めました。
# 動作は Linux(R... |
"""Porcupine is a simple editor.
You are probably reading this because you want to learn how Porcupine
works or write fun plugins for it. I recommend getting started with the
plugin API documentation:
https://akuli.github.io/porcupine/
"""
import sys
import appdirs
version_info = (0, 99, 2) # this is updated ... |
from .PCA import PCA
from .InvariantsMiner import InvariantsMiner
from .LogClustering import LogClustering
from .LR import LR
from .SVM import SVM
from .DecisionTree import DecisionTree
from .IsolationForest import IsolationForest
from .DeepLog import DeepLog
from .Autoencoder import Autoencoder
from .AutoencoderLSTM i... |
import abc
class AbstractClassifier:
""" Abstract class with specific methods for classifier models (training, validation and test) """
def __init__(self):
pass
@abc.abstractmethod
def train(self, config, train_data):
"""
Classifier training.
:param config: Model con... |
import frappe
def execute():
# there is no more status called "Submitted", there was an old issue that used
# to set it as Submitted, fixed in this commit
frappe.db.sql("""
update
`tabPurchase Receipt`
set
status = 'To Bill'
where
status = 'Submitted'""") |
a = <warning descr="Python version 3.0, 3.1, 3.2, 3.3, 3.4, 3.5 do not support backquotes, use repr() instead">`imp.acquire_lock()`</warning>
|
import os
import unittest
import tempfile
from unittest import mock
import uuid
import mlflow
import mlflow.db
import mlflow.store.db.base_sql_model
from mlflow.entities.model_registry import (
RegisteredModel,
ModelVersion,
RegisteredModelTag,
ModelVersionTag,
)
from mlflow.exceptions import MlflowEx... |
# Copyright (c) 2014-2017, NVIDIA CORPORATION. All rights reserved.
import itertools
import os
import shutil
import tempfile
import mock
from nose.tools import raises, assert_raises
try:
from . import parse_s3
from digits.tools.mock_s3_walker import MockS3Walker
import_failed = False
except ImportError:... |
import re
import time
import typing
import logging
from calendar import monthrange
from datetime import datetime
from collections import Iterable
from heapq import heappush, heappop
from . import types # noqa
from . exceptions import BrokerError
from . interfaces import App, Plugin, Logger
from . utils import cached_p... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from .api import RendezvousHandler, RendezvousParameters
from .api import rendezvous_handler_registry as handler_... |
#!/usr/bin/env python3
from app import app, db, functions
from app.functions import Color
import subprocess
import os
import shlex
import shutil
from config import Config
from datetime import datetime
from cryptography.fernet import InvalidToken
from app.cipher import CipherTest, Cipher, new_cipher_key, encrypt, decryp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Software License Agreement (BSD License)
#
# Copyright (c) 2021, Kei Okada
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions... |
import unittest
from almdrlib.session import Session
import re
MOCK_AUTH = {
"authentication": {
"user": {
"id": "589B64BB-AE91-4FA9-A6D8-37AC6759BB5D",
"account_id": "2",
"created": {
"at": 1443713420,
"by": "693BA145-78C0-4C77-AC1A-53854... |
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
# Copyright 2018-9 New Vector Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... |
import numpy as np
import sys
import gpflow
import VFF
from time import time
from config import *
dim = sys.argv[1]
rep = sys.argv[2]
print('vff: dimension {}, replicate {}'.format(dim, r))
# data
data = np.load('data/data_dim{}_rep{}.npz'.format(dim, 0))
# full_gp
def prodkern(dim):
return gpflow.kernels.Pro... |
import pandas as pd
from datanator.util import rna_halflife_util
import datetime
import datanator.config.core
import datetime
from pymongo.collation import Collation, CollationStrength
class Halflife(rna_halflife_util.RnaHLUtil):
def __init__(self, cache_dir=None, server=None, src_db=None, protein_col=None,
... |
import os
from pathlib import Path
import numpy as np
import pytest
from jina import Flow, Document
from jina.clients import Client
from jina.logging.profile import TimeContext
from jina.parsers import set_client_cli_parser
from typing import Dict
from jina import DocumentArray, Executor, requests
class DumpExecuto... |
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
from threading import Thread
import functools
_thread_by_func = {}
class TimeoutException(Exception):
"""
Raised when a function runtime exceeds the limit set.
"""
pass
class ThreadMethod(Thre... |
# Copyright 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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 b... |
from .operation import Operation
|
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
# -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
#... |
# -*- coding: utf-8 -*-
from PySide2 import QtCore, QtGui, QtWidgets
import json
import core_functions as cf
import numpy as np
from UI_labeled_slider import LabeledSlider
class Ui_AssignGroup(object):
def setupUi(self, AssignGroups):
# Note: this is not how it should be done but currently I don't know
... |
# Dictionary
class Dict_word_jumbler(object):
def __init__(self):
self.dict = self.build_dict()
def build_dict(self):
""""Build a dictionary to hold all of the words/letters"""
dic = {}
f = open("/usr/share/dict/words", "r")
word_list = f.readlines()
for word in ... |
import pickle
dict1 = {'Python ':90,'Java ':95,'C++ ':85}
f = open('bin)file.dat','wb')
pickle.dump(dict1,f)
f.close() |
"""
Testing ResGraphNet
"""
import datetime
import numpy as np
import pandas as pd
import torch
import os
import os.path as osp
import matplotlib.pyplot as plt
import sys
sys.path.append("..")
import func.cal as cal
device = "cuda:0" if torch.cuda.is_available() else "cpu"
# device = "cpu"
l_x = 60 ... |
# -*- coding: utf-8 -*-
"""
===================== OpenStereotaxy module for FreeCAD =======================
This Python module for FreeCAD allows the user to calculate the chamber-centered
coordinates of the target structure(s). Based on this data, the module will
generate surface meshes (exported in .stl format ready ... |
import numpy as np
def FNS(scores):
domination = np.all(scores[:, None, :] <= scores[None, :, :], axis=2) # domination[i, j] = "i dominuje j"
domination &= np.any(scores[:, None, :] < scores[None, :, :], axis=2)
Nx = domination.sum(0)
Pf = []
ranks = np.zeros(scores.shape[0])
r = 0
Q = n... |
"""
Misc functions.
"""
import ipaddress
import datetime
import hashlib
import json
import netaddr
import netifaces
import os
import re
import requests
import scapy.all as sc
import subprocess
import sys
import threading
import time
import traceback
import uuid
import server_config
IPv4_REGEX = re.compile(r'[0-9]{... |
# Project: py-trans
# Author: Itz-fork
import aiohttp
from .language_codes import _get_full_lang_name, _get_lang_code
from .errors import check_internet_connection, UnknownErrorOccurred
class Async_PyTranslator:
"""
Async PyTranslator Class
Note:
Before Trying to Translate Create an instance of ... |
# -*- coding: utf-8 -*-
"""API for working with saved queries for assets."""
import warnings
from typing import Generator, List, Optional, Union
from ...constants.api import MAX_PAGE_SIZE
from ...exceptions import NotFoundError, ResponseError, ApiWarning
# from ...features import Features
from ...parsers.tables impor... |
"""
Miscellaneous package utilities.
.. include:: ../include/links.rst
"""
from itertools import chain, combinations
from IPython import embed
import numpy
def all_subclasses(cls):
"""
Collect all the subclasses of the provided class.
The search follows the inheritance to the highest-level class. I... |
import math
import tensorflow as tf
import os
import struct
import pdb
import numpy as np
from datasets import dataset_factory
from nets import nets_factory
import nets.resnet_v2 as resnet_v2
from preprocessing import preprocessing_factory
slim = tf.contrib.slim
def merge_predictions(predictions_fn):
'''
Merge... |
# -*- coding: utf-8 -*-
from logging import getLogger
from time import time, strftime
from BTrees.IIBTree import IITreeSet
from Products.CMFCore.utils import getToolByName
from Products.Five.browser import BrowserView
from plone.uuid.interfaces import IUUID, IUUIDAware
from zope.interface import implementer
from zope.... |
from __future__ import division
import sys, os
def run(args):
for path in args:
problem = None
if (not os.path.isfile(path) or os.path.islink(path)):
problem = "not a regular file"
else:
try:
file_content = open(path, "rb").read()
except Exception:
problem = "no read acc... |
"""
One of the central problems in statistics is to make estimations — and quantify
how good these estimations are — of the distribution of an entire population
given only a small (random) sample. A classic example is to estimate the average
height of all the people in a country when measuring the height of a randomly
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Iterable
def flatten(input_arr, output_arr = None):
if output_arr is None:
output_arr = []
for t in input_arr:
if isinstance(t, Iterable):
flatten(t, output_arr)
else:
output_arr.append(t)
... |
# Copyright 2018 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... |
"""
ArcBall.py -- Math utilities, vector, matrix types and ArcBall quaternion rotation class
>>> unit_test_ArcBall_module ()
unit testing ArcBall
Quat for first drag
[ 0.08438914 -0.08534209 -0.06240178 0.99080837]
First transform
[[ 0.97764552 -0.1380603 0.15858325 0. ]
[ 0.10925253 0.97796899 0.1778779... |
import os
import boto3
import fsspec
import pytest
from moto import mock_s3
from datasets.filesystems import (
COMPRESSION_FILESYSTEMS,
HfFileSystem,
S3FileSystem,
extract_path_from_uri,
is_remote_filesystem,
)
from .utils import require_lz4, require_zstandard
@pytest.fixture(scope="function")
... |
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
from base_app.serializers import CustomUserSerializer
from rest_framework import serializers
from task_app.models import TaskFile
class TaskFileCreateSerializer(serializers.ModelSerializer):
'''Serializer for creating task files'''
author = CustomUserSerializer(read_only=True)
class Meta:
model ... |
# encoding: utf-8
import datetime
import re
import requests
from ckan.common import config
from ckan.common import asbool
from six import text_type, string_types
from ckan.common import _, json
import ckan.lib.maintain as maintain
log = __import__('logging').getLogger(__name__)
class License(object):
"""Doma... |
from sklearn.datasets import fetch_20newsgroups
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import CountVectorizer
# Define the category map
category_map = {'talk.politics.misc': 'Politics', 'rec.autos': 'Autos',
... |
from loguru import logger
from flask import request
from flasgger import swag_from
from flask_restful import Resource
from jwt.exceptions import ExpiredSignatureError
from ada_friend_app.modulo.cripto import Sha256
from ada_friend_app.modulo.jwt_auth import Token
from ada_friend_app.api.resposta_api import Resposta
fr... |
# Copyright (c) 2019 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... |
import argparse
from rasa.cli.arguments.default_arguments import (
add_nlu_data_param,
add_out_param,
add_data_param,
add_domain_param,
)
def set_convert_arguments(parser: argparse.ArgumentParser):
add_data_param(parser, required=True, default=None, data_type="Rasa NLU ")
add_out_param(
... |
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
class Simulation:
def __init__(self, init_investment, stock_returns, strategy, predicted_movements=None):
self.init_investment = init_investment
self.predicted_movements = predicted_movements
self.stock_retur... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from distutils.core import setup
setup(
name='yanccm',
packages=[
'controller',
'sot',
'ncservice',
'ncservice.configDb',
'ncservice.ncDeviceOps',
'ncservice.ncDeviceOps.threaded',
'view'],
version='0.0.2',
license='MIT',
description='''YANCCM... |
from terregex.mlr import Node, NodeList, Literal, NotLiteral, \
In, Negate, Range, Category, MinRepeat, MaxRepeat, \
SubPattern, Branch, Any, parse
from terregex.transform import Transformer |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PrinseqLite(Package):
"""PRINSEQ will help you to preprocess your genomic or metagenomic
... |
import gzip
import sys
def ParseFields(line):
fields = {}
var = line.rstrip("\n").lstrip("#").lstrip(">").split("\t")
for x in range(0, len(var)):
fields[var[x]] = x
return fields
def StripLeadLag(line):
var = line.rstrip("\n").lstrip("#").lstrip(">").split("\t")
return var
#Checks if... |
"""
Unit test for Linear Programming
"""
import sys
import numpy as np
from numpy.testing import (assert_, assert_allclose, assert_equal,
assert_array_less, assert_warns, suppress_warnings)
from pytest import raises as assert_raises
from scipy.optimize import linprog, OptimizeWarning
from sc... |
import unittest
from pyowm.agroapi10.polygon import Polygon, GeoPoint, GeoPolygon
class TestPolygon(unittest.TestCase):
geopoint= GeoPoint(34, -56.3)
geopolygon = GeoPolygon([
[[2.3, 57.32], [23.19, -20.2], [-120.4, 19.15], [2.3, 57.32]]
])
def test_polygon_fails_with_wrong_parameters(self):... |
def convert_request_to_dictionary(request, fields):
emp = {}
for field in fields:
if field in request.json:
emp[field] = request.json[field]
del emp["identity"]
return emp |
import os
from pydub import playback
from playsound import playsound
from simpleaudio import play_buffer
import winsound
from manuscript.tools.counter import Counter
def play_sound(sound, block=True):
if sound is not None:
prefix = "tmp"
with Counter(prefix) as counter:
tmp_file = os.... |
from telegram import ReplyKeyboardMarkup, KeyboardButton
def get_keyboard():
contact_button = KeyboardButton('Отправить контакты', request_contact=True)
location_button = KeyboardButton('Отправить локацию', request_location=True)
my_keyboard = ReplyKeyboardMarkup([['Анекдот', 'Начать'],
... |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
# Also available under a BSD-style license. See LICENSE.
"""Queries the pytorch op registry and generates ODS and CC sourc... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or module... |
import spacy
from spacy.lang.en import English
from spacy.util import minibatch, compounding
from spacy.util import decaying
class ExperimentParam:
def __init__(self, TRAIN_DATA: list, max_batch_sizes: dict, model_type='ner',
dropout_start: float = 0.6, dropout_end: float = 0.2, interval: float =... |
from example_system import serializer
from example_system.bike import Bike
from example_system.human import Human
def run_example() -> None:
krzysztof = Human(name="Krzysztof", age=37)
giant_bike = Bike(brand="Giant", model="Contend AR")
krzysztof_json = serializer.serialize(krzysztof)
print(krzyszto... |
'''
Created by auto_sdk on 2020.11.25
'''
from dingtalk.api.base import RestApi
class OapiSmartdeviceBatcheventPostRequest(RestApi):
def __init__(self,url=None):
RestApi.__init__(self,url)
self.device_event_vos = None
def getHttpMethod(self):
return 'POST'
def getapiname(self):
return 'dingtalk.oapi.smartd... |
import pandas as pd
import io
from joblib import load
import logging
logging.getLogger().setLevel(logging.INFO)
def generate_data():
new_data = pd.DataFrame({
'Pclass':[3,2,1],
'Sex': ['male', 'female', 'male'],
'Age':[4, 22, 28]
})
return new_data
def load_model():
try:
... |
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Generic, Type, TypeVar, Union
from .devices import I2CDevice
from .parsers import RegisterParser
from .typing import RegisterState
BlockType = TypeVar("BlockType")
class RegisterBlock(Generic[BlockType], ABC):
"""
Abstract ... |
"""A flexible Python library for atomic structure generation."""
|
import sys
import time
from TOSSIM import *
from TossimHelp import *
t = Tossim([])
sf = SerialForwarder(9002)
throttle = Throttle(t, 10)
nodecount = loadLinkModel(t, "linkgain.out")
loadNoiseModel(t, "meyer.txt", nodecount)
# Set debug channels
print "Setting debug channels..."
t.addChannel("printf", sys.stdout);
t... |
import asyncio
import logging
import time
from datetime import datetime
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple
from blspy import PrivateKey, G1Element
from seno.cmds.init_funcs import check_keys
from seno.consensus.block_rewards import calculate_base_farmer_reward
from seno.... |
import torch
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
# import sys
# sys.path.append("../simulated_fqi/")
from simulated_fqi import NFQNetwork, ContrastiveNFQNetwork
import matplotlib.pyplot as plt
import numpy as np
def train(x, y, groups, network, optimizer):
predicted... |
"""
WSGI config for tw project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_M... |
import torch
def combine_masks_with_batch(masks, n_obj, th=0.5, return_as_onehot = False):
""" Combine mask for different objects.
Different methods are the following:
* `max_per_pixel`: Computes the final mask taking the pixel with the highest
probability for every object.
# ... |
class Task(object):
def __init__(self,name):
self.name = name
pass
def run(self):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.