text stringlengths 3.07k 12.6k |
|---|
# coding=utf-8
# Copyright 2020 The TensorFlow Datasets 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 appl... |
# Copyright 2020-2022 Cambridge Quantum Computing
#
# 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... |
import pyone
import functools
from multiprocessing import Process
import logging
# Logging Parameters
logger = logging.getLogger(__name__)
file_handler = logging.handlers.RotatingFileHandler(
'katana.log', maxBytes=10000, backupCount=5)
stream_handler = logging.StreamHandler()
formatter = logging.Formatter('%(asct... |
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
import argparse
import numpy as np
from scipy.sparse import hstack
from sklearn.feature_extraction import DictVectorizer
import matplotlib.pyplot as plt
from scipy.stats ... |
"""Library integration with Random123."""
from __future__ import division, absolute_import
__copyright__ = "Copyright (C) 2016 <NAME>"
__license__ = """
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 So... |
#!/usr/bin/env python3
# Copyright (C) 2019 TU Dresden
# Licensed under the ISC license (see LICENSE.txt)
#
# Authors: <NAME>, <NAME>
import argparse
import cProfile
import logging
import os
import shlex
import sys
import inspect
import traceback
import typing
from dataclasses import dataclass
from glob import glob
... |
#!/usr/bin/env python3
import re
import os
import sys
import subprocess
from Bio import SeqIO
def help():
print('''
Usage:
------------
gff2fasta.py -gff <file> -fasta <file> [-attr <attr>]
Description:
------------
Requires BEDtools. Extracts seqs from -fasta for features in -gff
using the attribute from -g... |
"""Implements a Mixture Density LSTM Network for predicting the future latents
based on past latents
"""
import torch
import torch.nn as nn
import torch.nn.functional as f
from torch.distributions.normal import Normal
class _MixtureDensityLSTMBase(nn.Module):
def __init__(self, NUM_LATENTS: int, NUM_ACTIONS: ... |
# This file is part of PyOP2
#
# PyOP2 is Copyright (c) 2012, Imperial College London and
# others. Please see the AUTHORS file in the main source directory for
# a full list of copyright holders. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted ... |
# Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software an... |
from __future__ import annotations
from typing import List, Optional
import math
class Node(object):
def __init__(self, parent: Optional[Pair], isright: bool):
self.parent = parent
self.isright = isright
class Pair(Node):
def __init__(self, parent: Optional[Pair], isright: bool):
su... |
import os
import sys
import subprocess
# Local imports
from .version import NEOPO_VERSION
from .common import NEOPO_DEPS
from .common import ProcessError, UserError, particle_cli, running_on_windows
from .utility import print_help, handle_missing_file, unexpected_error
from .workbench import install_or_update, workben... |
import discord
import discord.commands
from typing import *
if TYPE_CHECKING:
from bot import DiscordBot
# Defines a custom button that contains the logic of the game.
# The ['TicTacToe'] bit is for type hinting purposes to tell your IDE or linter
# what the type of `self.view` is. It is not required.
class Ti... |
# --- Revised 3-Clause BSD License ---
# Copyright Semtech Corporation 2022. 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 of source code must retain the above copyright ... |
from django.contrib.gis.db import models
from django.contrib.gis.db.models.functions import Distance
from django.db import transaction
from django.utils import timezone
from django.utils.timezone import localtime, now
from django.utils.translation import ugettext_lazy as _
from parkings.models.mixins import Timestampe... |
# -*- coding: utf-8 -*-
"""
gagepy.utils
~~~~~~~~~~~~
Utility helper functions for gagepy.
:authors: 2016 by <NAME>, see AUTHORS
:license: United States Geological Survey (USGS), see LICENSE file
"""
import os
import numpy as np
import datetime
import re
def get_file_paths(dirname, file_ext):
... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/master/LICENSE
from __future__ import absolute_import
import sys
import gc
import pytest
import numpy
import awkward1
py27 = 2 if sys.version_info[0] < 3 else 1
def test_refcount1():
i = numpy.arange(12, dtype="i4").reshape(3, 4)
a... |
# Copyright 2021 The Cirq Developers
#
# 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 ... |
from typing import List, Sequence, Tuple
from .usfm_marker import UsfmStyleType, UsfmTextProperties
from .usfm_stylesheet import UsfmStylesheet
from .usfm_token import UsfmToken, UsfmTokenType
class UsfmParser:
def __init__(self, stylesheet: UsfmStylesheet) -> None:
self._stylesheet = stylesheet
def... |
import os.path
import sys
import cv2
import numpy as np
import scipy.ndimage as ndi
from deepliif.postprocessing import overlay, refine, remove_cell_noise, remove_background_noise, \
remove_small_objects_from_image
def align_seg_on_image(input_image, input_mask, output_image, thresh=100, noise_objects_size=100)... |
"""Python component of pytangular: serializes a schema to JSON."""
import colander as c
from sqlalchemy import types
from json import dumps
colander_types = { # maps SQLAlchemy types to colander types
types.Boolean: c.Boolean,
types.String: c.String,
types.Unicode: c.String,
types.UnicodeText: c.Str... |
import os
import stat
import signal
import subprocess
import time
import random
import string
import psutil
from testing.common.database import (
Database, DatabaseFactory, get_unused_port
)
__all__ = ['RabbitMQServer', 'RabbitMQServerFactory']
SEARCH_PATHS = [
'/usr/lib/rabbitmq/bin', # archlinux
'/usr... |
# -*- coding: utf-8 -*-
''' Contains tests for reading and modification of econfigurations '''
from __future__ import absolute_import
def test_get_econfig_W():
from aiida_fleur.tools.element_econfig_list import get_econfig
assert get_econfig('W', full=False) == '[Kr] 5s2 4d10 4f14 | 5p6 6s2 5d4'
assert g... |
import time
import numpy as np
import torch
import torch.nn.functional as F
import wandb
from torch import nn
from torch.nn import CrossEntropyLoss
from torch.nn.utils import prune
from torchvision.models import inception, inception_v3, SqueezeNet
from tqdm import tqdm
import os
import simplify
from tests.benchmark_m... |
import json
import logging
import contextvars
from typing import TypeVar
from abc import abstractmethod, ABC
from graphql.language import parse
from graphql.language.ast import (
OperationDefinitionNode,
OperationType
)
from pygraphy.utils import (
is_union,
is_list,
is_optional,
patch_indents
)... |
import csv
import pickle
import torch
import threading
import math
import random
import pandas as pd
from tqdm import trange
from package.definition import logger
from package.utils import save_pickle
class MultiLoader():
"""
Multi Data Loader using Threads.
Args:
dataset_list (list): list of Bas... |
import base64
import functools
import getpass
import hashlib
import os
import random
import re
import subprocess
import sysconfig
import types
from ctypes import cdll
from torch.utils import cpp_extension
from . import config
from . import exc
def cache_dir():
return f"/tmp/torchinductor_{getpass.getuser()}"
... |
import _thread
import array
import logging
import signal
import struct
import sys
import threading
from time import sleep, time
import usb
from usb.core import Configuration, Device
from .coremedia.consumer import AVFileWriter, SocketUDP, Consumer
from .meaasge import MessageProcessor
logging.basicConfig(level=loggin... |
# <NAME>'s Kaggle Utilities
# Copyright 2019 by <NAME>, Open Source, Released under the Apache License
# For more information: https://github.com/jeffheaton/jh-kaggle-util
#
# Tune for XGBoost, based on: https://towardsdatascience.com/fine-tuning-xgboost-in-python-like-a-boss-b4543ed8b1e
#
from util import *
from xgb... |
from dataclasses import dataclass
from typing import Dict, Set, List, Tuple, Optional
from padmini.constants import Tag
class VyakaranaException(Exception):
pass
@dataclass
class Term:
"""A *term* is a generalized version of an *upadesha*. In addition to
upadeshas, the *term* concept includes abhyāsa... |
"""Common get info functions for mpls"""
# Python
import re
import logging
# pyats
from pyats.utils.objects import find, R
# Genie
from genie.libs.sdk.libs.utils.normalize import GroupKeys
from genie.libs.parser.utils.common import Common
from genie.libs.sdk.libs.utils.normalize import GroupKeys
from genie.metaparse... |
"""
Converts tsv format to coco format
ic: img_id class_id img_data_base64
od: img_id [{"class": class_name, "rect": [L, T, R, B], "diff": 0}, ...] img_data_base64
"""
import logging
import json
import os
from .utils import verify_and_correct_box_or_none, guess_encoding, decode64_to_pil, zip_folder, TSV_FORMAT_L... |
"""Util functions for the Pinhole Camera."""
# Copyright (c) 2021 <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 u... |
"""A set of functions to help build ODE models with complete
sets of standard events, etc. based on function specifications
provided in a format similar to that for sloppyModels.
<NAME>.
2008: This is superceded by GDescriptor class. See PyDSTool/tests/
"""
from __future__ import absolute_import, print_funct... |
from __future__ import annotations
import json
import logging
import os
import pickle
import shutil
from typing import List, Tuple, Dict
import joblib
import networkx as nx
from ConfigSpace import Configuration
from sklearn.ensemble import VotingClassifier
from slugify import slugify
from dswizard.core.constants imp... |
#import pytorch stuff
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
#import others
import re
import time
import math
import copy
import random
from tqdm import tqdm
import sys
import matplotlib.pyplot as plt
import os
class configs:
epoch = 10
b... |
from random import randint
import numpy as np
from ase import Atoms
from ase.constraints import dict2constraint
from ase.calculators.calculator import get_calculator, all_properties
from ase.calculators.calculator import PropertyNotImplementedError
from ase.calculators.singlepoint import SinglePointCalculator
from as... |
#!c:\users\hooma\documents\github\spinesegmentation\segmentation_test\scripts\python.exe
"""
Extracts a sub-volume from a medical image.
Copyright (C) 2013 <NAME>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Softwar... |
#!/usr/bin/python3
"""Exports Dyson Pure Hot+Cool (DysonLink) statistics as Prometheus metrics."""
import argparse
import functools
import logging
import sys
import time
import threading
from typing import Callable, Dict, List
import prometheus_client
import libdyson
import libdyson.dyson_device
import libdyson.exce... |
import numpy as np
import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from adjustText import adjust_text
from artpalettes import *
import matplotlib
matplotlib.use('Agg')
# default parameters for matlab
FONT_SIZE = 7
font = {'size': FONT_SIZE}
matplotlib.r... |
import logging
from enum import Enum
from aiohttp import ClientConnectionError, ClientSession, ServerTimeoutError
from retry import retry
_CMD_STATUS = "status"
_CMD_POWER_ON = "power/on"
_CMD_POWER_OFF = "power/off"
_CMD_SET_TEMP = "set/setpoint"
_CMD_ROTATION = "set/feature/rotation"
_ROTATION_ON = 0
_ROTATION_O... |
"""
Supervisor Blueprint
====================
Can be used as a provider to the application blueprint,
or used standalone by adding program templates under a `programs-available`
and enable them manually with the `programs` setting.
**Fabric environment:**
.. code-block:: yaml
blueprints:
- blues.superviso... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, \
unicode_literals
import numpy as np
import six
from word_embedding_loader import WordEmbedding
UNK_ID_CANDIDATES = [b'<unk>', b'<UNK>']
def infer_unk_id(vocab):
"""
Args:
vocab (dict): Mapping from words... |
import numpy as np
import json
import pandas as pd
from sys import stdout
from natsort import natsorted
class CellType:
def __init__(self, name, ignoreNA = False):
self.name = name
self.score = self.avgp = 0.0
self.weak_support = []
self.strong_support = []
self.subtypes = None
self.ignoreNA = ignoreNA
... |
import torch
import torch.utils.dlpack
import sys
import os
# \todo need to figure out where to put the lib/tnn.so binary so that it adheres to
# usual import semantics
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'lib'))
import tnnlib
einsum_symbols = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN... |
#!/usr/bin/env bash
# crazy black magic from:
# https://unix.stackexchange.com/questions/20880/how-can-i-use-environment-variables-in-my-shebang
# this block of code is valid in both bash and python.
# this means if this script is run under bash, it'll
# call this script again using BAG_PYTHON. If
# this script is ru... |
import threading
import os, sys
import time
import logging
import subprocess
import struct, socket
import flow_common
import run_env
from pyDatalog import pyDatalog
from commit_ovs import commit_flows
from onexit import on_parent_exit
from tp_utils import pipe
from run_env import get_extra
from tuplesync import update_... |
# ======================================================================
# Copyright CERFACS (November 2018)
# Contributor: <NAME> (<EMAIL>)
#
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and/or redistribute ... |
__author__ = 'jonpsull'
from es_logger.interface import ConsoleLogEventRegex
from es_logger.interface import EventGenerator
import json
import logging
import os
import re
from stevedore import driver, ExtensionManager
LOGGER = logging.getLogger(__name__)
class ConsoleLogEvent(EventGenerator):
"""
Load regex... |
from __future__ import division, print_function, absolute_import
import weakref
import numpy as np
from collections import OrderedDict
from ...framework.observer import Listener, Observable
from .primitive import MDPPrimitive
class StateDistribution(object):
"""Probability Distribution.
This class handles ... |
# -*- coding:utf-8 -*-
#
# utils.py
"Utils Module."
import numpy as np
import pandas as pd
import networkx as nx
def pairwise_distances_distinct(
particle_positions_1, particle_positions_2, box_lengths
):
"""Returns pairwise distance matrix between 2 distinct sets of particle
positions accounting for pe... |
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, 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 ... |
# Copyright (c) 2013, RC and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import getdate, nowdate
class UnbilledSupplierOrdersReport(object):
def __init__(self, filters=None):
self.filters = frappe._dict... |
import copy
import itertools
class VialException(Exception):
pass
class Vial:
def __init__(self, num, layers):
self.num = num
self.layers = layers
def mix_in(self, vial):
if self.is_full():
raise VialException
piece = vial.get_top_piece()
... |
import sys
import numpy as np
import faiss
import math
import argparse
import pandas as pd
class Initializer:
def __init__(self, args):
self.args = args
self.long_long_size = 8
self.long_size = 4
self.int_size = 2
self.output_file_binary_components = args.binary_components... |
import os
import sublime
import sublime_plugin
import re
import subprocess
import tempfile
import shutil
from subprocess import Popen, PIPE
settings = None
class Settings:
def __init__(self):
package_settings = sublime.load_settings("RustAutoComplete.sublime-settings")
package_settings.add_on_ch... |
"""ESMValTool CMORizer for GRACE.
Tier
Tier 3
Source
https://podaac.jpl.nasa.gov/dataset/TELLUS_GRAC-GRFO_MASCON_CRI_GRID_RL06_V2
Last access
20211019
Download and processing instructions
- Go to the above link
- Click the tab "Data Access"
- Log in with Earthdata account
- Download the following files:
... |
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test /vsistdin/
# Author: <NAME> <even dot rouault at mines dash parid dot org>
#
###############################################################################
#... |
"""
Example of linear regression using Gibbs taken from <NAME>'s slides at:
http://www.cs.toronto.edu/~radford/csc2541.S11/week3.pdf
p(y|x, beta_0, beta_1, y_sigma) = N(beta_1*x + beta_0, y_sigma)
p(beta_0) = N(beta_0_mu, beta_0_sigma)
p(beta_1) = N(beta_1_mu, beta_1_sigma)
p(1/y_sigma^2) = Gamma(y_sigma_alpha, 1/y_s... |
import pickle
from datetime import datetime, timedelta
from pathlib import Path
from cryptography.fernet import Fernet
from robin_stocks.tda.globals import DATA_DIR_NAME, PICKLE_NAME
from robin_stocks.tda.helper import (request_data, set_login_state,
update_session)
from robin_stoc... |
from pathlib import Path
from typing import Tuple, Type, Dict, Union, Optional
import numpy as np
import torch
from kekas.callbacks import OneCycleLR, Callbacks
# Callback, Callbacks, ProgressBarCallback, \
# PredictionsSaverCallback, OneCycleLR, SimpleLossCallback, MetricsCallback, \
# TBLogger, LRFinder, C... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
from http import HTTPStatus
import random
from unittest.mock import MagicMock
import pytest
import requests
from airbyte_cdk.models import SyncMode
from source_notion.streams import NotionStream, Users
@pytest.fixture
def patch_base_class(mocker):
# M... |
"""
Audit helpers.
Helper functions for audit_report and user_audit_report.
"""
import os
import json
import csv
import requests
import datetime
from time import time
from docx import Document
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
from contextlib import suppress
data_typ... |
#!/usr/bin/env python
import gzip
import traceback
import json
import re
from multiprocessing import Pool
from collections import defaultdict
from sortedcontainers import SortedList
EMPTY_TABLE = """
CREATE TABLE IF NOT EXISTS {table} (
id varchar(20) UNIQUE,
page varchar(200) UNIQUE,
lab... |
# Copyright 2014 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file acc... |
#!/usr/bin/env python3
"""
The toolbox for kinetic library related tasks
"""
import logging
import os
from collections import OrderedDict
from copy import deepcopy
from rmgpy import settings
from rmgpy.chemkin import load_chemkin_file
from rmgpy.data.base import Entry
from rmgpy.data.kinetics import KineticsLibrary
f... |
"""Tests the script entry to the live monitoring program by calling its run
method with different combinations of script arguments.
"""
import pytest
# The virtual, pseudorandom port is setup as a session fixture in conftest.py
def get_sargs(args):
"""Returns the list of arguments parsed from sys.argv.
"""
... |
import os
import scipy.io as sio
import cv2
import numpy as np
BasePath = os.path.dirname(os.path.dirname(__file__))
FullImgMean = os.path.join(BasePath, "utils", "places_mean_resize.mat")
HeadImgMean = os.path.join(BasePath, "utils", "imagenet_mean_resize.mat")
def transformData(input_img, mean_img):
transfor... |
import numpy as np
from scipy.ndimage.filters import laplace
import scipy.constants as const
from physunits import m, cm, mm, nm, um, keV
import matplotlib
import matplotlib.pyplot as plt
from scipy.ndimage import gaussian_filter
from scipy.ndimage import zoom
plt.rcParams['figure.dpi'] = 150
def thicc(x, R):
# #... |
"""Some definitions to interact with the command line."""
import subprocess
from os import remove, path, popen
from ytmdl import defaults, prepend
from shutil import which
import ffmpeg
from simber import Logger
from rich.prompt import Confirm, Prompt
logger = Logger("Utility")
def exe(command):
"""Execute the ... |
# -*- coding: utf-8 -*-
"""
.. codeauthor:: <NAME> <<EMAIL>>
.. codeauthor:: <NAME> <<EMAIL>>
"""
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from src.models.resnet import ResNet18, ResNet34, ResNet50
from src.models.context_modules import get_context_module
from src.models.mode... |
import argparse
import matplotlib.pyplot as plt
import numpy as np
import scipy.optimize
import functools
import operator
import random
from typing import Any, Callable, List, Tuple
from nptyping import NDArray
class Link:
"""
Callable constructor for Denavit-Hartenberg Matrices of some D-H parameters.
... |
import math
import random
import warnings
import PIL
import PIL.Image
import numpy as np
import torch
import torchvision.transforms.functional as TF
class CenterCrop(object):
"""
"""
def __init__(self, size):
if not (isinstance(size, tuple)):
size = (size, size)
self.size =... |
from types import SimpleNamespace
from django.test import SimpleTestCase
from .. import utils
from .testcase import EmailSignalTestCase
class TestConvertToPrimitive(SimpleTestCase):
"""Unittests for the `convert_to_primitive` utility function."""
def test_convert_to_true(self):
"""Test the `convert_t... |
"""
This module holds objects that get returned from "einfo" calls.
"""
#Standard Library
from typing import Union, List, Optional, Dict
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .api import CitationMatcherEntry
from .api import API
#Third Party
#----------------------
from bs4 import Beautifu... |
from flask import (
Flask,
make_response,
jsonify,
request,
render_template,
send_from_directory,
abort,
redirect,
Response,
)
from flask_cors import CORS
from JavPy.functions import Functions
import json
import os
import JavPy.utils.config as config
import JavPy.utils.buggyauth as a... |
from .single_tile_affine_renderer import SingleTileAffineRenderer
import numpy as np
import tinyr
from enum import Enum
class BlendType(Enum):
NO_BLENDING = 0
AVERAGING = 1
LINEAR = 2
MULTI_BAND_SEAM = 3
class MultipleTilesAffineRenderer:
BLEND_TYPE = {
"NO_BLENDING" : 0,
... |
from os.path import join, isdir
from os import listdir, mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import sys
import time
dataset_path = './data'
sub_sets = ['GOT-10k_Train_split_01','GOT-10k_Train_split_02','GOT-10k_Train_split_03','GOT-... |
# flake8: noqa
# @TODO: code formatting issue for 20.07 release
from typing import Dict, List, Union
from collections import Counter
import logging
import queue
import threading
import time
from alchemy.logger import Logger
import visdom
from catalyst.core.callback import (
Callback,
CallbackNode,
Callbac... |
#!/usr/bin/python
# coding: utf8
"""
Statistics
be careful of the dimension ordering:
d,n,p or n,d,p
"""
import numpy as np
def hotelling_1sample(x):
"""
Calcule la statistique associée au test d'Hotelling de nullité de la moyenne.
Un test est effectué pour chaque voxel.
Le calcul est (partielleme... |
#!/usr/bin/python
""" PN CLI COMMANDS EXECUTION"""
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later... |
# Released under the MIT License. See LICENSE for details.
#
"""Networking related functionality."""
from __future__ import annotations
import copy
import threading
import weakref
from enum import Enum
from typing import TYPE_CHECKING
import _ba
if TYPE_CHECKING:
from typing import Any, Union, Callable, Optional... |
# Copyright 2019, OpenCensus 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 applicable law or agreed to in w... |
import os
import sys
import zmq
import time
import shutil
import logging
import tempfile
import argparse
import threading
from ami import LogConfig
from ami.comm import Ports
logger = logging.getLogger(__name__)
class SimSync:
"""Class for simulating timestamp synchronization for AMI data sources.
This cl... |
import os
import re
import time
def timeit(f):
def wrapped(*args, **kwargs):
start = time.perf_counter()
result = f(*args, **kwargs)
print(f"{f.__name__} took: {time.perf_counter() - start}s")
return result
return wrapped
def replaceRules(rule, rules):
# Recursively replace reference to rules wi... |
from transformers.models.gpt2.modeling_tf_gpt2 import shape_list
from NonResidualAttention import CustomSearchFunction
import transformers.generation_tf_utils as GenUtils
import tensorflow as tf
import numpy as np
import tqdm
class HFDecodingContainer(GenUtils.TFGenerationMixin):
def __init__(self, promptModelS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys
import time
from collections import deque
from functools import partial
DATASIZE = 30000
MAX_NESTING_LEVELS = 100
BF_COMMANDS = {
'MOVE_RIGHT': '>',
'MOVE_LEFT': '<',
'INCREMENT': '+',
'DECREMENT': '-',
'WRITE_CHAR': '.',
... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
# TSFRESH
from tsfresh.feature_extraction import extract_features
from tsfresh.utilities.dataframe_functions import impute
def split_dataset(gb_df, date_col, pred_col):
gb_df = gb_df.sort_values(by=[date_col])
X =... |
#!/usr/bin/env python3
import scanner
# ------------------------------------------------------------------------------
# Classes for holding source code entities
class Module(object):
def __init__(self):
self.brief = ''
self.detail = ''
self.functions = set()
self.calls = set()
class Function(object):
... |
import struct
import numpy as np
import json
import nibabel.nicom.dicomwrappers as dcmwrapper
from pytest import approx
import autovps.dataset.siemens as siemens
from autovps.dataset import svsdata
DIM_TOL = .1
def test_orientations():
""" Test that the axis string is correctly recovered
"""
siemens_or... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import os
import boto3
import cv2
import math
import numpy as np
from botocore.exceptions import ClientError
from MediaReplayEnginePluginHelper import OutputHelper
from MediaReplayEnginePluginHelper import... |
""" This module deals with the formatting and processing of strings
where either otherwise not provided or as a wrapper function
for convience.
"""
import copy
import os
import secrets
import shutil
import ifa_smeargle.core as core
def remove_prefix(string, prefix):
""" This function removes the prefix string of... |
import collections
import datetime
import json
import run
import dash
import dash_core_components as dcc
import dash_html_components as html
import ha as ha
import plotly
import psutil
from _plotly_utils.colors.qualitative import Plotly
from dash.dependencies import Input, Output
import numpy as np
import halcon as ha
... |
#!/bin/env python
# $Id: Updates.py 3349 2014-11-28 14:09:26Z bnv $
# Author: <EMAIL>
# Date: 5-Apr-2007
__author__ = "<NAME>"
__email__ = "<EMAIL>"
import time
import json
try:
import httplib as http
from Tkinter import *
except ImportError:
import http.client as http
from tkinter import *
import Utils
impor... |
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, absolute_import, division
#!/usr/bin/python
"""
problem 72
weblink:
description:
Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction.
If we list the s... |
#!/GPFS/zhangli_lab_permanent/zhuqingjie/env/py3_tf2/bin/python
'''
@Time : 20/10/14 上午 09:37
@Author : zhuqingjie
@User : zhu
@FileName: Camera_Calibration.py
@Software: PyCharm
'''
'''
摄像机标定
问题:
使用摄像头拍摄较密集的圆盘时(本实验8*9),离中心区域越远的圆盘畸变越大,导致影响实验结果。
目的:
使用摄像机标定可以很大的改善拍摄畸变的问题,可以使实验计算结果更加准确。
摄像机标定步骤:
1,打印出标定图像(标准棋盘... |
'''网络结构定义'''
from __future__ import absolute_import, print_function
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
class _ImagePool(nn.Module):
def __init__(self, in_ch, out_ch):
super().__init__()
self.pool = nn.AdaptiveAvgPool2d(1)... |
import re
import time
import threading
from enum import Enum
from typing import List, Optional, NamedTuple
from controller import Robot
from sr.robot.vision import (
Face,
Vector,
PolarCoord,
Orientation,
tokens_from_objects,
polar_from_cartesian,
)
Cartesian = NamedTuple("Cartesian", (
("... |
from collections import defaultdict, OrderedDict
import numpy as np
from scipy import signal
from scipy.sparse import csr_matrix, hstack
import pandas as pd
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.cluster import MiniBatchKMeans
from sklearn.feature_extraction.text import TfidfVectorizer
fr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.