text stringlengths 3.07k 12.6k |
|---|
"""
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, software
distrib... |
from __future__ import annotations
from typing import *
from sklearn.metrics import classification_report # type:ignore
from DataLoader import ImageClass, SamplingMethod,Places365Dataset, DataPoint, prettystr, max_enum_idx
from random import randint
class MisMatchedDimensionsError(Exception):
def __init__(self, ... |
#!/usr/bin/env python3
import argparse
import logging
import re
import sys
from subprocess import check_output
from typing import Any, Dict, List, Optional
from github import Github
from parse_pr import parse_pr_body, type_mapping
def main() -> None:
parser = argparse.ArgumentParser(description="Prepare next T... |
# Copyright 2021 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, ... |
import numpy as np
from sklearn.tree import plot_tree
from mlsummary.classification._classification_functions import _class_pred, _store_X, _scatter_class, \
_features_important, _prior, _cv_results
class SoftmaxRegressionSummary:
def __init__(self, obj, X=None, X_train = None, y_pred=None, y_true=None,
... |
# 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, so... |
#! /usr/bin/env python
"""Generate the OpenGLContext shader tutorials from '''-string marked-up source code"""
from __future__ import absolute_import
from __future__ import print_function
import re,os,sys,textwrap, datetime
from genshi.template import TemplateLoader
import logging
from six.moves import range
log = logg... |
import reversion
from django.utils.timezone import now
from rest_framework import status
from rest_framework.reverse import reverse
from reversion.models import Version
from datahub.company.constants import BusinessTypeConstant
from datahub.company.models import Company
from datahub.company.test.factories import Compa... |
# coding=utf-8
#
# Copyright (c) 2010-2015 Illumina, Inc.
# All rights reserved.
#
# This file is distributed under the simplified BSD license.
# The full text can be found here (and in LICENSE.txt in the root folder of
# this distribution):
#
# https://github.com/Illumina/licenses/blob/master/Simplified-BSD-License.tx... |
# -*- coding: utf-8 -*-
"""
Индекс всех receiver нейронов в домене
"""
from openre.vector import Vector
from openre.metadata import ExtendableMetadata
from openre.data_types import types
class ReceiverIndex(object):
"""
Индекс принимающих нейронов
i = 0..количество IS_RECEIVER нейронов
i - адрес IS_REC... |
import os
import torch
import torchvision.transforms as transforms
import torchvision.models as torchmodels
import numpy as np
import shutil
import json
from EfficientObjectDetection.utils import utils_detector
from EfficientObjectDetection.dataset.dataloader import CustomDatasetFromImages
from EfficientObjectDetectio... |
import os
import redis
import datetime
import fcntl
import time
from webrecorder.utils import load_wr_config
# ============================================================================
class StorageCommitter(object):
def __init__(self, config):
self.redis_base_url = os.environ['REDIS_BASE_URL']
... |
from connect.eaas.core.dataclasses import (
ExtensionPayload,
Logging,
Message,
MessageType,
parse_message,
Repository,
Schedulable,
Service,
SettingsPayload,
TaskInput,
TaskOptions,
TaskPayload,
transform_data_to_legacy,
)
TASK_DATA = {
'options': {
'ta... |
import os
from os_android_apk_builder.bp import _general_utils
import os_tools.logger_handler as lh
from os_android_apk_builder.objs.KeyStoreProperties import KeyStoreProperties
from os_android_app_version_changer.objs.VersionProperties import VersionProperties
from os_file_handler import file_handler as fh
from os_an... |
import argparse
import datetime
import config
import constants
import query_client
import utils
def process_command_line():
"""Interpret parameters in command line"""
parser = argparse.ArgumentParser(prog='openVulnQuery', description='Cisco OpenVuln API Command Line Interface')
parser.set_defaults(outpu... |
# -*- coding: utf-8 -*-
## @package inversetoon.data.curve
#
# Curve data classes.
# @author tody
# @date 2015/07/17
import json
import numpy as np
from inversetoon.data.contour import Contour
from inversetoon.data.data import Data
from inversetoon.data.segment import IsophoteSegment
## Curve data c... |
import sys, os, time
from basic.constant import ROOT_PATH, DEFAULT_TPP
from basic.common import checkToSkip, niceNumber, printStatus, makedirsforfile
from basic.util import readImageSet
from util.simpleknn.bigfile import BigFile
from tagvote import DEFAULT_TAGGER, DEFAULT_K, DEFAULT_DISTANCE, DEFAULT_BLOCK_SIZE, NAME... |
import json
from data import read_instance_from_file
from gurobipy import *
from sys import argv
import itertools
import networkx as nx
def solve(n, pairs, k):
print('N:', n)
print('Pairs:', len(pairs))
print('Layers:', k)
def nodes_iter():
return itertools.product(range(n), range(n), range... |
"""
"Sub Main" that contains one function to start the training loop.
"""
import argparse
import re
import time
import jsonpickle
import mesh_tensorflow as mtf
import numpy as np
import tensorflow as tf2
from tensorflow.python.ops import summary_ops_v2 as summary
from tensorflow.python.tpu.device_assignment import de... |
import sys
from torchvision.models.resnet import Bottleneck, conv1x1, conv3x3
sys.path.append("../quantum-neural-network/qnn")
import torch
import torch.nn as nn
import numpy as np
from qnet import QNet
__all__ = ['resnet18']
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes... |
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .models import User, Listing, Bid, Watchlist, Comment
from .forms import listingForm
from ... |
"""
neuron.doc
===================
This module is used behind the scenes to generate docstrings of all HocObjects
of various types
To get general help on the neuron module try:
>>> import neuron
>>> help(neuron)
or in Jupyter
In []: import neuron
In []: neuron ?
From there, you can get help on the various objects... |
from __future__ import print_function
from builtins import object
import os
import click
from relaax.cmdl.cmdl import pass_context
from relaax.cmdl.cmdl import ENVIRONMENTS, ENVIRONMENTS_META
from relaax.cmdl.utils.backup import Backup
from relaax.cmdl.utils.commented_yaml import CommentedYaml
SPECIAL_CONFIG_LIST =... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright 2021-... <NAME> <<EMAIL>>.
# This program is distributed under the MIT license.
# Glory to Ukraine!
import enum
class DipTraceEnum(enum.Enum):
@classmethod
def from_str(cls, value: str):
for k, v in cls.__members__.items():
if v.value == value:
retur... |
"""
Вспомогательные функции-утилиты
"""
import json
import os as __os
import shutil as __shutil
import sys as __sys
__MESSAGE_EMPTY_ANSWER = 'Вы ничего не указали'
__MESSAGE_NOT_FOUND = 'Файл или папка не найдены по указанному пути.'
__MESSAGE_WRONG_ACTION_CHOICE = 'Неверный пункт меню!'
__QUESTION_CHOICE = 'Выберите ... |
import os
import sys
import hmac
import logging
import hashlib
from threading import Thread
from utils.duckling_mod import DucklingWrapperMod
from flask import Flask, request, jsonify, abort
from slackclient import SlackClient
from requests import post
app = Flask(__name__)
duckling_wrapper = DucklingWrapperMod()
... |
# still working need to implement UniformInt and frequency
"""
Create random number streams
from numpy.random import default_rng
seed1 = 1
gen1 = default_rng( seed1)
seed2 = 2
gen2 = default_rng( seed2)
rns1_1 = gen1.rand()
rns1_2 = gen1.rand()
rns2_1 = gen2.rand()
rns2_2 = gen2.rand()
"""
from numpy.random import ... |
""" Nox definitions for tests, docs, and linting
MIT License
(C) Copyright [2020] Hewlett Packard Enterprise Development LP
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, i... |
from requests import Request, Session
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse
import warnings
from time import sleep
from timeit import default_timer as timer
from datetime import timedelta
from threading import local
class SlowRequests:
'''
PARAMS:
* offset: Float... |
# Copyright (c) 2012--2013 King's College London
# Created by the Software Development Team <http://soft-dev.org/>
#
# 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, inclu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from typing import Type
from nonebot import on_command, Bot
from nonebot.adapters.cqhttp import Message, MessageSegment, escape
from nonebot.adapters.cqhttp.event import Event, MessageEvent, GroupMessageEvent
from nonebot.matcher import Matcher
from epicteller... |
import os
from copy import deepcopy
from multiprocessing import Pool, cpu_count
import networkx as nx
import pandas as pd
from analysis.statics import YEARS
from analysis.utils import (get_basic_parser, get_country,
get_crossreference_path, get_node_and_edge_files,
... |
from testandconquer import logger
from testandconquer.client import MessageType
from testandconquer.model import Schedule, ScheduleItem
from testandconquer.settings import Capability
class Serializer:
date_format = '%Y-%m-%dT%H:%M:%S.000Z'
@staticmethod
def serialize_config(*args, **kwargs):
ret... |
from .. import exceptions
def only_in_transaction(f):
def wrapped(world, *args, **kwargs):
if not world._transaction_in_progress:
raise exceptions.ProgrammingError('Method {} requires prior begin()'.format(f.__name__))
return f(world, *args, **kwargs)
return wrapped
class World():
... |
# -*- coding: utf-8 -*-
# pylint: disable=wrong-import-position
"""
Define a function for compensating for inherent "tails" when differencing two
numbers drawn from the same finite range.
Useful for, e.g., zenith or cos(zenith) error distributions.
"""
from __future__ import absolute_import, division, print_function... |
"""Spark utility functions."""
import itertools
import functools
from typing import (
Any,
Callable,
List,
Mapping,
Optional,
Sequence,
Tuple,
Union,
)
import pandas as pd
from pyspark.sql import (
Column as SparkCol,
DataFrame as SparkDF,
functions as F,
Window,
Win... |
# Support for the NeTV2 board
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex.soc.integration.soc_core import mem_decoder
from litex.soc.integration.soc_sdram import *
from litex.soc.integration.builder import *
from litex.soc.interconnect import wishbone
from litedram.modules... |
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
##############################
## HELPER FUNCTIONS/CLASSES ##
##############################
class KLSchedulerTypes:
CONSTANT = 0
MONOTONIC = 1
CYCLIC = 2
LINEAR = 0
SIGMOID = 1
EXPONENTIAL = 2
def scheduler_string():
return "Constan... |
import json
import pickle
from collections import defaultdict
from copy import deepcopy
from tqdm import tqdm
import numpy as np
from exp import ex
from utils import cut_sample, flatten_dict, copy
@ex.capture
def load_vist_text(path, sample):
with open(path, 'r') as f:
data = json.load(f)
data = dat... |
import os
import csv
import sys
import argparse
import shutil
import re
from datetime import datetime
from pybedtools import BedTool
from structuralvariant import GeneAnnotations, StructuralVariant, StructuralVariantRecords
csv.field_size_limit(sys.maxsize)
'''
crg.intersect.sv.reports.py
August 2018
Center for Com... |
from unittest import TestCase
import numpy as np
import unittest
import placentagen
import os
class Test_create_trees(TestCase):
def test_umilical_node(self):
thickness = (3.0 * 1 / (4.0 * np.pi)) ** (1.0 / 3.0) * 2.0
data_input = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]])
datapoints = p... |
import utils
DECODED = {}
SPECIAL = {}
def decode_string(rule):
parts = rule.split(' ')
variants = ['']
for rule in parts:
elements = DECODED.get(rule)
variants = [var + el for var in variants for el in elements]
return variants
def decode_simple(rule, key):
tmp = rule.split('"'... |
from django.db import models
from mxv.settings import AUTH_USER_MODEL
from datetime import date
from django.utils import formats
from django.db.models.deletion import CASCADE
from django.dispatch.dispatcher import receiver
from django.db.models.signals import post_save
from mxv.models import DefaultUrlParameter
# fiel... |
import csv
import random
import matplotlib.pyplot as plt
import math
SCALE = 1000
def get_distribution(count):
dist = []
for i in range(count):
dist.append(random.random())
s = sum(dist)
return [d / s for d in dist]
def gen_banks(count):
banks = []
total_debt = count * SCALE * 5
... |
# MIT License
#
# Copyright (c) 2017 <NAME>
#
# This file is part of excons.
#
# 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
# t... |
# 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 applic... |
from django.db import models
from django.conf import settings
from django.db.models import Count
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth.models import User
class Campaign(models.Model):
user = models.ForeignKey(
User, on_delete=models.CASCADE, default=None, null... |
import random
import numpy as np
from sklearn.datasets import load_iris
from sklearn import metrics
import JcesSc_V
from NMI import my_NMI
import matplotlib.pyplot as plt
iris_data = load_iris()
X = iris_data.data
label = iris_data.target
# print(X.shape)
# print(label.shape)
# X, label = JcesSc... |
from PyQt5.QtWidgets import QWidget, QCheckBox, QTreeWidget, QTreeWidgetItem, QPushButton, QLabel, QDialog, QVBoxLayout, QApplication, QLineEdit, QDateTimeEdit
from PyQt5.QtCore import pyqtSlot, QDateTime, QDate, pyqtSignal
from PyQt5.QtGui import QFont
import os
class ScheduleItem(QWidget):
deleted = pyqtSignal()... |
"""
A set of classes and functions used to manipulate bioRxiv preprints, published papers and hypothes.is posts.
"""
from typing import List, Dict
from . import HYPO
from hypothepy.v1.helpers import PermissionsHelper
from .utils import info
class AsDict:
"""
Serialize itself recursively to a dictionary with ... |
import logging
from typing import List, Union, Dict, Optional, Tuple
import torch
import torch.nn as nn
import flair.embeddings
import flair.nn
from flair.data import DataPoint, RelationLabel, Span
log = logging.getLogger("flair")
class RelationExtractor(flair.nn.DefaultClassifier):
def __init__(
... |
#
# FixPointCS
#
# Copyright(c) 2018 <NAME>, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, mer... |
#!/usr/bin/env python3
import torch
import torchtext
from torchtext import data
import pickle
import spacy
import random
import argparse
import os
#************************************************************
# About this scrip #
#Tokenizes, pad and slices poem extracts ... |
# 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.
import ctypes
import numpy as np
from torch_mlir.ir import *
fr... |
import io
import os
from typing import Iterable, List, Tuple
import numpy as np
import PIL.Image as Image
import torch
import torch.utils.data as data
from torch.nn import functional as F
from src import configs, util
import colour
class PreemptiveRandomSampler(data.Sampler):
def __init__(self, indices: List[int... |
"""Author: <NAME>"""
import numpy as np
from .xml_utils import save_XML, XML_calib, XML_mic
def DARP2016_MicArray():
"""
Returns the microphone coordinates for the 'near-field' planar microphone
array used in the 2016 experiments with the DARP open-jet wind tunnel at
the ISVR, Univ. of Southampton, UK... |
#dominate allows for cleaner html creation within python
import dominate
from dominate.tags import *
#ezgmail is a wrapper for the Google gmail API that facilitates our requests
import ezgmail
#datetime used to determine current day and yesterday
from datetime import datetime, timedelta
#tzlocal used to get local time ... |
# Author: <NAME>
# Contact me: www.github.com/gergf
# Python dependencies
import os
import sys
import argparse
import nibabel as nib
from subprocess import call
# Math and Machine Learning
import numpy as np
import tensorflow as tf
from scipy import ndimage
import matplotlib.pyplot as plt
# Own libraries
import... |
import csv
import sqlite3
import os
import json
import psycopg2
import copy
def format_col_for_create_table(cols):
col_names = "(" + cols[0]
value_names = "(?"
for i in range(1, len(cols)):
col_names += ", " + cols[i]
value_names += ", ?"
col_names += ")"
value_names += ")"
... |
"""
2D Game Design Project 1
Title : Earth Crusaders
Author: <NAME>
Version: 1.0
Date: 09/23/2021
#controls
UP, Down, Left, Right = Movement
space = fire repulsor beams
#Running the game
use python to run the main.py file
"""
import arcade
import pathlib
from enum import auto, Enum
# Game Window
window_width, windo... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn
from visdom import Visdom
def run_async(func):
from threading import Thread
from functools import wraps
@wraps(func)
def async_func(*args, **kwargs):
thread = Thread(target=func, args=args, kwargs=kwargs)
thread.st... |
import os
import sys
import lib_util
import lib_common
import lib_credentials
import win32api
import win32net
import win32con
import win32netcon
import win32security
import win32wnet # WNetAddConnection2
class Impersonate:
def __init__(self,login,password,domain):
# LOGON32_LOGON_NETWORK
# win32con.LOGON32_LOGON... |
import sys
import torch
import pandas as pd
import numpy as np
import argparse
from tqdm import tqdm
from pathlib import Path
from sklearn.metrics import precision_score, recall_score, f1_score
# from datasets import load_dataset # this has to be installed first using - !pip install datasets
# transformers package ca... |
'''
The MIT License (MIT)
Copyright (c) 2013 <NAME>.
'''
import threading
import multiprocessing
import signal
import sys
import ssl
from SimpleWebSocketServer import WebSocket, SimpleWebSocketServer, SimpleSSLWebSocketServer
from optparse import OptionParser
from conf import conf
from play import game_init
from engin... |
import numpy
import powerbox
from scipy import interpolate
from scipy.constants import c
from scipy.constants import Boltzmann
from .radiotelescope import beam_width
import time
def symlog_bounds(data):
data_min = numpy.nanmin(data)
data_max = numpy.nanmax(data)
if data_min == 0:
indices = numpy.... |
import os
import argparse
import glob
import re
import textwrap
import warn.warning
import warn.parser
def sdir():
return os.path.dirname(os.path.realpath(__file__))
def toMacro(string):
return string.upper().replace('-','_').replace('+', 'X')
if __name__ == '__main__':
parser = argparse.ArgumentParser(prog="war... |
from flask_restx import Namespace, Resource
from markupsafe import escape
from sqlalchemy.exc import OperationalError
from api.models.poplar_nssnp import (
ProteinReference as PoplarProteinReference,
SnpsToProtein as PoplarSnpsToProtein,
SnpsReference as PoplarSnpsReference,
)
from api.models.tomato_nssnp i... |
from datetime import datetime, timedelta
from django.conf import settings
from nose.tools import eq_
from kitsune.forums.models import Thread, Forum, ThreadLockedError
from kitsune.forums.tests import ForumTestCase, thread, post
from kitsune.forums.views import sort_threads
from kitsune.sumo.tests import get
from ki... |
'''
card.py
Created by <NAME> on 5/27/20.
Adapted to Python by <NAME> on 8/7/2021
Copyright © 2020 Say Goodnight Software. All rights reserved.
'''
from enum import Enum, unique
@unique
class EmojiCard(Enum):
c2 = "2♣"
c3 = "3♣"
c4 = "4♣"
c5 = "5♣"
c6 = "6♣"
c7 = "7♣"
c8 = "8♣"
c9 = "... |
#!/usr/bin/env python3
#===============================================================================
# finrich.py
#===============================================================================
# Imports ======================================================================
import json
from argparse import Argum... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import logging
from pathlib import Path
import re
from nipype.interfaces.base import (
traits,
TraitedSpec,
SimpleInterface,
File,
DynamicTraitedSpec,
isdef... |
"""Plot performance of classifiers for simulation data.
This program measures and reports the AUC of the FDensemble, Woc, and best
individual classifiers for NREPS replicate simulation data and differing
simulation parameter values. The different simulation parameters that are
varied are the number of base classif... |
import os
import pickle as pkl
import numpy as np
from matplotlib import pyplot as plt
import torch
import rasterio
from matplotlib import colors
from torch.utils.data import DataLoader
from image.data import N_CLASSES
from image.data import ITypeDataset
SUBSET_SZ = 256
def write_pth_subsets(in_, _out, start_ct=No... |
# -*- coding: utf-8 -*-
import jpype
import gc
import sys
import os
from os import path
from subprocess import call
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
import resource
except ImportError:
resource = None
pass
try:
xrange
except NameError:
xrange = ra... |
import json
from django.apps import apps
from rest_framework import generics, status
from rest_framework.response import Response
from dataservices import helpers, models, serializers
from dataservices.core import client_api
from dataservices.helpers import (
deep_extend,
get_multiple_serialized_instance_from... |
# -*- encoding: utf-8 -*-
#
# Copyright 2013 <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/LICENSE-2.0
#
# Unless required by applicable law o... |
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module for sending statistics to statsd."""
from __future__ import print_function
from chromite.lib import cros_logging as logging
# Autotest u... |
from . env import Env
import numpy as np
import tensorflow as tf
from utils.preprocess import remove_bg
from PIL import Image
class EnvTransform(Env):
def __init__(self, env):
super(Env, self).__init__()
self.env = env
@property
def action_space(self):
return self.env.action_s... |
import os, sys
import time
import math
import numpy as np
import tensorflow as tf
from learning import BaseLearner
from learning import loss_xe, loss_01, loss_xe_adv, loss_entropy
from uncertainty import ECE, plot_acc_rank, plot_acc_conf, bino_ci
class LearnerCls(BaseLearner):
"""classification learning class. I... |
import pytest
import os
import colander
from mdingestion.community.darus import DarusDatacite
from mdingestion.community.herbadrop import Herbadrop
from mdingestion.writer import B2FWriter
from mdingestion.core import B2FSchema
from tests.common import TESTDATA_DIR
def test_b2f_schema():
cstruct = {
'c... |
import json
import log_setup
import os
import wave
from concurrent import futures
import time
import grpc
import subprocess
from grpc_stubs.audio_to_text_pb2 import Response, SRTResponse, PunctuateResponse
from grpc_stubs.audio_to_text_pb2_grpc import add_RecognizeServicer_to_server, RecognizeServicer
from model_servic... |
import xml.etree.ElementTree as ET
import os
import re
import sys
import string
if len(sys.argv) < 2: exit(1)
filepath = sys.argv[1]
with open(filepath) as f:
data = f.read()
data = re.sub(f'[^{re.escape(string.printable)}]', '', data)
root = ET.fromstring(data)
def get_value(node, path):
v = node.find(path)
... |
# -*- coding: utf-8 -*-
"""The HDFS file entry implementation."""
from __future__ import unicode_literals
import stat
from dfdatetime import posix_time as dfdatetime_posix_time
from dfdatetime.interface import DateTimeValues
from dfvfs.lib import definitions as plaso_definitions
from dfvfs.lib.errors import BackEnd... |
"""
Provides accumulator objects to assist with building Syntax
"""
import re
class ListBuilder:
marker = "*"
indentation = " " * 2
item_count = 0
level = 0
def __init__(self, marker):
self.items = []
self.set_marker(marker)
def visit_list(self):
self.level += 1
... |
#!/usr/bin/env python
'''
Copyright (c) 2018, The Monero Project
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 of ... |
"""
Support for HomeSeer sensor-type devices.
"""
from pyhs3 import (
DEVICE_ZWAVE_BATTERY,
DEVICE_ZWAVE_FAN_STATE,
DEVICE_ZWAVE_LUMINANCE,
DEVICE_ZWAVE_OPERATING_STATE,
DEVICE_ZWAVE_RELATIVE_HUMIDITY,
HASS_SENSORS,
STATE_LISTENING,
)
from homeassistant.const import (
DEVICE_CLASS_BATT... |
from tests.sdk.queries.conftest import EXISTS
from tests.sdk.queries.conftest import IS
from tests.sdk.queries.conftest import IS_IN
from tests.sdk.queries.conftest import IS_NOT
from tests.sdk.queries.conftest import NOT_EXISTS
from tests.sdk.queries.conftest import NOT_IN
from py42.sdk.queries.fileevents.filters.clo... |
import logging
import os
import sys
import zipfile
from urllib.request import urlopen, urlretrieve
from selenium.webdriver import Chrome as _Chrome
from selenium.webdriver import ChromeOptions as _ChromeOptions
logger = logging.getLogger(__name__)
TARGET_VERSION = 83
__IS_PATCHED__ = 0
class Chrome:
def __new... |
#coding:utf8
"""
和检测相关的任务,任务可以通过异步方式执行,同时提供分析类方法
"""
import logging
import math
import colorsys
import io
import base64
import cv2
import time
import numpy as np
from configparser import ConfigParser
from os import path
from typing import Text
from PIL import Image
from ._base import Request, TEMP
from ..check import... |
'''BaseLinter version 0.1
Base Linter is a command-line interface app checks for sets of words in a text by order.
Each time the app encounters a word belonging to a set, it prompts you to choose which
of the words in the set. The app will replace the word in that position in the word
order in the text you are check... |
"""
Predict next tools in the Galaxy workflows
using machine learning (recurrent neural network)
"""
import sys
import numpy as np
import time
import os
import json
import h5py
# machine learning library
from keras.models import Sequential
from keras.layers import Dense, GRU, Dropout
from keras.layers.embeddings impo... |
import socket
import inspect
from time import sleep, time_ns
from struct import unpack
# main class to communicate with the MRS6000 sensor
class MRS6000:
def __init__(self, ip, port):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((ip, port))
def __del__(se... |
from json.decoder import JSONDecodeError
import subprocess
import logging
from logging import debug, info, warning, error, critical, exception
import json
import os
import importlib
from argparse import ArgumentParser
import sys
from concurrent.futures import ThreadPoolExecutor
from git.repo.base import Repo
import has... |
import asyncio
import datetime as dt
import logging
import random
from typing import Optional
from typing import Tuple
import disnake
from disnake.ext.commands import Bot
from disnake.ext.commands import Cog
from disnake.ext.commands import command
from disnake.ext.commands import Context
from disnake.ext.commands imp... |
from gpiozero import Button
from signal import pause
import time
from datetime import datetime, timedelta
import requests
from threading import Thread
import logging
import csv
from sys import argv
from random import randint
# Constants
INTERVAL = 5 # Tach sampling seconds
BPS_CUTOFF = 22 # Minimum number ... |
# -*- coding: utf-8 -*-
"""
Actions
========
This module contains important high level processing routines
author: <NAME>
email: <EMAIL>
"""
import os
import logging
import numpy as np
from skimage.transform import probabilistic_hough_line
from .models.segments import Panel, Figure, FigureRoleEnum
from .models.uti... |
import pytest
from summit.benchmarks import *
from summit.utils.dataset import DataSet
import numpy as np
import pandas as pd
import os
import pathlib
import shutil
import pkg_resources
import matplotlib.pyplot as plt
DATA_PATH = pathlib.Path(pkg_resources.resource_filename("summit", "benchmarks/data"))
@pytest.mark... |
import string
from collections import Counter
import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
# Import Data; Change as deemed necessary
data_train = pd... |
import gpytorch
from gpytorch.models import AbstractVariationalGP
from gpytorch.variational import CholeskyVariationalDistribution
from gpytorch.variational import VariationalStrategy
from gpytorch.mlls.variational_elbo import VariationalELBO
import torch
import gc
import numpy as np
from torch import Tensor
import ... |
"""
Cultural Evolution Simulation (Yummy_Recipe)
<NAME>
Final Project of B.sc Level in Computer Engineering
Task: Simulate changes in recipes within a population of Agents over several
generations depending on different rule sets.
"""
import time
import os
import Ana... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.