text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
import math
import tensorflow as tf
from jack.tfutil import misc
from jack.tfutil import segment
def attention_softmax(attn_scores, length=None):
if length is not None:
attn_scores += misc.mask_for_lengths(length, tf.shape(attn_scores)[2])
return tf.nn.softmax(attn_scores)
... |
#
# Copyright Cloudlab URV 2020
#
# 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 writin... |
class DumpStack(gdb.Command):
def __init__ (self):
super (DumpStack, self).__init__ ("dump-stack", gdb.COMMAND_USER)
def invoke (self, arg, from_tty):
frame = gdb.selected_frame()
sp = int(frame.read_register("sp"))
i = gdb.selected_inferior()
print("current stack @", he... |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2021 Eotvos Lorand University, Budapest, Hungary
from utils.codegen import format_type, get_all_extern_call_infos
from utils.extern import extern_has_tuple_params
from compiler_common import generate_var_name
from more_itertools import unique_everseen
#[ #include "dpd... |
# Copyright 2016 Google Inc. 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 ... |
from .moabs import *
from .fastqc import Fastqc
from .trim import Trim
from .utils import *
from .NumExtractor import *
from .bedtools import Bedtools
from pandas import DataFrame
from .bsplot import *
import os
from datetime import datetime
def computeQC(name,fastqc,param={}):
'''
Computing function for qc. R... |
# Code derived from tensorflow/tensorflow/models/image/imagenet/classify_image.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tarfile
import warnings
from collections import defaultdict
import numpy as np
impo... |
import pickle
import torch
from torch.utils.data import Dataset, DataLoader
import numpy as np
import torchvision.transforms as transforms
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torch import nn
import torch.nn.functional as Fun
import random
print(torch.cuda.current_... |
import albumentations as A
import colorednoise as cn
import librosa
import numpy as np
from albumentations.core.transforms_interface import ImageOnlyTransform
def get_transforms(config: dict, phase: str):
transforms = config.get('transforms')
if transforms is None:
return None
else:
if tr... |
import argparse
import json
import multiprocessing
import time
from abc import ABCMeta, abstractmethod
from pprint import pprint
from typing import Tuple, Optional, Dict, Any
import os.path
import sys
import h5py
from keras import optimizers
import keras.backend
import numpy as np
import gym
from kerl.common.agent im... |
"""scilifelab lib module"""
import os
import re
import subprocess
import shlex
from cStringIO import StringIO
from fabric.api import task, run, execute, cd, settings, local
from fabric.network import disconnect_all
from datetime import datetime
from scilifelab.utils.misc import filtered_walk
from scilifelab.utils.mi... |
"""
Residential Efficiency outputs
------------------------------
output functions for Residential Efficiency component
"""
import os.path
import numpy as np
from pandas import DataFrame
from config import COMPONENT_NAME
import aaem.constants as constants
from aaem.components import comp_order, definitions
## compo... |
# Copyright 2020 The SQLFlow 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 applicable law o... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.d (the "License");
# you may not use this file except in compliance with the License
""" Userbot module containing commands related to the \
Information Superhighway (yes, Internet). """
import asyncio
... |
import typing
from typing import Dict, Optional
from mypy.checker import TypeChecker
from mypy.nodes import AssignmentStmt, ClassDef, Expression, ImportedName, Lvalue, MypyFile, NameExpr, SymbolNode, \
TypeInfo
from mypy.plugin import FunctionContext, MethodContext
from mypy.types import AnyType, Instance, NoneTyp... |
# Foremast - Pipeline Tooling
#
# Copyright 2018 Gogo, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... |
from fabric.context_managers import cd, shell_env
from fabric.contrib.files import exists
from fabric.operations import run, sudo
from offregister_fab_utils.apt import apt_depends
from offregister_fab_utils.fs import cmd_avail
from offregister_fab_utils.git import clone_or_update
from offutils import update_d
def ins... |
"""Implement some local attention and masked attention operation"""
from mindspore.common import Tensor
from mindspore import ops, dtype as mstype, numpy as np
def pytorch_topk(x:Tensor, k, dim=-1):
topk_op = ops.TopK()
if dim == -1:
return topk_op(x, k)
else:
dims = x.ndim
last_di... |
#!/usr/bin/env python
u"""
nsidc_subset_altimetry.py
Written by <NAME> (07/2018)
Program to acquire and plot subsetted NSIDC data using the Valkyrie prototype
CALLING SEQUENCE:
to use a bounding box:
python nsidc_subset_altimetry.py --bbox=-29.25,69.4,-29.15,69.50 ILVIS2
to use start and end time:
python nsid... |
#!/usr/bin/env python
import math
# Math
def distancia_euclidiana(p1, p2):
total = 0
for i in range(len(p1)):
total += (p1[i] - p2[i]) ** 2
return math.sqrt(total)
def escala_normalizada(x, v_max, v_min):
return (x - v_min) / (v_max - v_min)
# Util
def ler_arquivo(filename, keys):
a... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 08:24:59 2020
Performs intra-run analysis that compares multiple
benchmarks' data for a single run. This allows the user
to visualize the performance across multiple benchmarks
for a single run.
This script can be run as a standalone script to generate the intra-run
... |
# -*- coding: utf-8 -*-
"""
:Module: ``streetview``
:Author: `<NAME> <http://www.dradrian.com>`_
:Organisation: `Warwick Business School <http://www.wbs.ac.uk/>`_, `University of Warwick <http://www.warwick.ac.uk/>`_.
This is a light module for downloading photos from Google street view. The
functions allow you to ret... |
# Copyright (c) 2020 Cisco and/or its affiliates.
# 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 ag... |
from flask import Flask
from flask import request, json
from PIL import Image
import PIL
import os , io , sys
import numpy as np
import base64
import cv2
from skimage import transform
from texturizing import *
import glob
from pathlib import Path
import random
import shutil
from tensorflow.keras.models import load_mod... |
#
#
# Implementation of the GCT Algorithm
# As outlined in Cambouropoulos et. al. 2014
# Available at: http://www.coinvent-project.eu/fileadmin/publications/icmc-smc2014-GCT-submitted.pdf
#
#
from music21 import chord
from music21 import pitch
from random import choice as rand_choice
from numpy import argmin
def dfs(... |
import pytest
import jet
# pylint: disable=unused-argument
@pytest.mark.parametrize("dtype", ["complex64", "complex128"])
class TestTensor:
def test_default_constructor(self, dtype):
"""Tests that the default constructor is called."""
tensor = jet.Tensor(dtype=dtype)
assert tensor.indices... |
import itertools
import re
import sys
import operator
from collections import defaultdict, namedtuple
from dataclasses import dataclass
from enum import Enum
from itertools import product
from math import prod
from queue import PriorityQueue
from typing import List, Dict, Any, Tuple
import aocd
from . import aoc_year
f... |
"""Performs face alignment and stores face thumbnails in the output directory."""
# MIT License
#
# Copyright (c) 2016 <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 restr... |
"""
feast_classes stores the basic classes used by FEAST.
Additional classes are stored in DetectionModules directory and leak_objects.
"""
import random
import numpy as np
from .leak_class_functions import leak_objects_generator as leak_obj_gen
import pickle
from .simulation_functions import set_kwargs... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# FIXME: A more reliable way to get this task done should be implementing the dumper in llvm-objdump.
import os
import sys
import re
import subprocess
import argparse
import shutil
import bisect
import logging
import io
import shlex
FUNCTION_BEGIN_LINE = re.compile(r'^([0... |
import unittest
from bson import ObjectId
from datacentric.platform.context import Context
from datacentric.platform.storage import DataSet
from tests.data_sample import *
from tests.temporal_test_context import TemporalTestContext
def save_base_record(context: Context, data_set_id, record_id, record_index) -> Obje... |
import numpy
from numba import jit, prange
from numpy.typing import ArrayLike
from scipy.ndimage import correlate as scipy_ndimage_correlate
__fastmath = {'contract', 'afn', 'reassoc'}
__error_model = 'numpy'
def numba_cpu_correlate(image: ArrayLike, kernel: ArrayLike, output=None):
# Kernel must have odd dimeni... |
import discord
import itertools
import re
import platform
import os
import datetime
import typing
import asyncio
from uptime import _uptime_linux as linux_uptime
from subprocess import Popen, PIPE
from distro import linux_distribution as distro_info
from discord.ext import commands
from utils.checks import is_channel_a... |
"""
Tests for fileio module
"""
# author: <NAME> (arm61)
import unittest
from datetime import datetime
import os.path
import pytest
import yaml
from orsopy.fileio.orso import Orso, OrsoDataset
from orsopy.fileio.data_source import (DataSource, Experiment, Sample,
Measurement, I... |
#!/usr/bin/python
import unittest
import unittest.mock
import wpVitalsTender as wpvt
import json
def mock_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, content_file, status_code):
self.content_file = content_file
self.status_code = status_code
def j... |
import ci_reduce.common as common
import numpy as np
import os
def has_wrong_dimensions(exp):
# check meant to catch simulated data
# or other rare anomalies where GFA images do not have the
# correct dimensions
for im in exp.images.values():
sh = im.image.shape
if (sh[0] != 1032) or (... |
##
# File: OeDepictCompareTests.py
# Author: jdw
# Date: 28-Oct-2019
# Version: 0.001
#
# Updates:
#
##
"""
A collection of tests to compare assigned and computed features.
"""
__docformat__ = "restructuredtext en"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__license__ = "Apache 2.0"
import logging
import os... |
# BioPandas
# Author: <NAME> <<EMAIL>>
# License: BSD 3 clause
# Project Website: http://rasbt.github.io/biopandas/
# Code Repository: https://github.com/rasbt/biopandas
import os
import numpy as np
import pandas as pd
from biopandas.mmcif import PandasMmcif
from biopandas.testutils import assert_raises
from nose.to... |
import copy
import io
import re
import xml.etree.ElementTree as ET
from contextlib import redirect_stdout
from typing import Optional
from musicxml.generate_classes.utils import musicxml_xsd_et_root, xml_xsd_et_root
from musicxml.util.helprervariables import xml_name_first_character_without_colon, name_character_witho... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: <NAME>
# License: MIT
import nlopt
import numpy as np
from . import dolfin as df
from .complex import *
from .materials import tensor_const
from .utils import array2function, function2array, mpi_print, project_iterative, tanh
df.parameters["allow_extrapolation"... |
#!/usr/bin/env python
def parse_input():
from optparse import OptionParser, OptionGroup
import sys
# initialize parser
parser = OptionParser()
# define options
group = OptionGroup(parser, 'Basic options')
group.add_option('--data',
type='string',
... |
import logging
import uuid
from abc import ABC, abstractmethod
from pathlib import Path
import numpy as np
import pandas as pd
import pickle5 as pickle
import sklearn
from sklearn.preprocessing import StandardScaler
import apollo
from apollo.models import make_estimator
logger = logging.getLogger(__name__)
class... |
from overrides import overrides
from typing import List, Iterator, Any
import numpy
from contextlib import contextmanager
import json
import logging
import sys
import pdb
import torch
import spacy
import allennlp
from allennlp.predictors.predictor import Predictor
from allennlp.data import Instance
from allennlp.com... |
import discord
from discord.ext import commands
from __main__ import send_cmd_help
class battleship:
"""Play battleship with one other person"""
def __init__(self, bot):
self.bot = bot
@commands.group(pass_context=True, no_pm=True)
async def battleship(self, a):
if a.invoked_subcommand is None:
await send_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 <NAME>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
... |
"""
Playlist class
Manages a list of songs, providing both static sequential & randomized play queues along
with the ability to fade in the next song in the queue by N-seconds.
Does the best it can to avoid ctype's memory leaks.
"""
import enum
import pathlib
from pathlib import Path
import random
imp... |
import numpy as np
import logging
import sys, os, re
try:
from tasmanian.utils.sam_reads import reads
except Exception:
# Either tests or base_dir, it's downstream of ../tasmanian/tasmanian/
p = os.path.abspath(os.path.dirname(__file__))
#p = re.search("(.*tasmanian/tasmanian/).*",p).group(1)
p_st... |
# -*- coding: utf-8 -*-
import SDL_DS3231 as sdl
REG_ALARM1_S=7
REG_ALARM1_M=8
REG_ALARM1_H=9
REG_ALARM1_D=10
REG_ALARM2_M=11
REG_ALARM2_H=12
REG_ALARM2_D=13
REG_CONTROL=14
REG_STATUS=15
def byte_to_bits(b):
"""Wandelt Byte (Int 0-255) in ein Array mit 8 True/False-Werten um. Achtung, das niederwertige Bit ist link... |
#!/usr/bin/env nemesis
#
# ======================================================================
#
# <NAME>, U.S. Geological Survey
# <NAME>, GNS Science
# <NAME>, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copyright (c)... |
__package__ = 'Krypton.Base'
import functools
import glob
import inspect
import json
import logging
import os
import pathlib
import threading
import time
import traceback
from collections import defaultdict
from enum import Enum
from typing import Dict, Union, List
import pandas as pd
from ._Statics import GlobalSta... |
import abc
from gppylib.mainUtils import ExceptionNoStackTraceNeeded
from gppylib.operations.detect_unreachable_hosts import get_unreachable_segment_hosts
from gppylib.parseutils import line_reader, check_values, canonicalize_address
from gppylib.utils import checkNotNone, normalizeAndValidateInputPath
from gppylib.gp... |
#!/usr/bin/env python3
import logging
import click
import numpy as np
from os.path import abspath, dirname, join
from gym.spaces import Tuple
from mujoco_py import const, MjViewer
from mae_envs.viewer.env_viewer import EnvViewer
from mae_envs.wrappers.multi_agent import JoinMultiAgentActions
from mujoco_worldgen.util.e... |
#!/usr/bin/env python
import numpy as np
from datetime import *
import time as t
import os, sys
from get_osr_gridded_by_day_hr import *
import pickle
import scipy.ndimage.filters
import xarray as xr
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import *
from matplotlib.colors import BoundaryNorm
def readS... |
import discord
import os
from discord.ext import commands
import json
from discord import Intents
#importing random stuff lol
import asyncio
import random
bot = commands.Bot(command_prefix=commands.when_mentioned_or("sex!")) #ass sexy bot prefix
#for checking if bot online yet, printing out to the terminal (bored)
@b... |
import hashlib
import json
import random
BELA, CRNA, PRAZNO = "W", "B", "p"
class Uporabnik:
def __init__(self, uporabnisko_ime, zasifrirano_geslo, igre = dict({})):
self.uporabnisko_ime = uporabnisko_ime
self.zasifrirano_geslo = zasifrirano_geslo
self.igre = igre
@staticmethod
... |
"""
Get the parameters of the stars in the known sample which I detect.
"""
import os
import pandas as pd
import numpy as np
import StarData
import Correct_CCF_Temperatures
import HDF5_Helpers
SAMPLE_HIP = [1366, 3300, 12719, 13165, 15338, 17563, 22840, 22958, 24902,
26063, 26563, 28691, 33372, 44127, ... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Plots Main Widget.
"""
# Third party imports
from qtpy.QtCore import Qt, Signal
from qtpy.QtWidgets import QSpinBox
# Local imports
from spyder.api.config.decor... |
import nltk
import string
from nltk.corpus import stopwords
import ast
from nltk.stem import WordNetLemmatizer
import pdb
import argparse
from nltk.tokenize import sent_tokenize, word_tokenize
import gensim
from gensim.models import Word2Vec
stop_words=set(stopwords.words('english'))
stop_words.add('-lrb-')
stop_words... |
from urllib.parse import quote
from urllib import request
import requests, random, json, os, subprocess, math
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from bs4 import BeautifulSoup
username, password = open("credentials.cfg", "r").read().split("\n") if os.path.isfile("credentials.cfg"... |
# coding: utf-8
"""Converts corpora from the topic-labeling package format to the simple semsim format."""
import argparse
import csv
import json
import re
from pathlib import Path
from typing import Generator, List, Union, Tuple, Iterator
import pandas as pd
from tqdm import tqdm
from semsim.constants import PathL... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : Ampel-alerts/ampel/alert/FilterBlock.py
# License : BSD-3-Clause
# Author : vb <<EMAIL>>
# Date : 03.05.2018
# Last Modified Date: 21.05.2021
# Last Modified By : vb <<EMAIL>>
from logging import LogRecord
from typin... |
# coding=utf-8
import os
import shutil
import sys
import argparse
import yaml
from requests.exceptions import HTTPError
import logging
import logging.config
import pkg_resources
from typing import TYPE_CHECKING
from . import __version__
from .alma import Alma
from .data import Table
from .config import config
from .u... |
import numpy as np
from numpy import linalg
import argparse
from csv import reader
from random import seed
def linear_kernel(x1, x2):
return np.dot(x1, x2)
def radial_kernel(x, y, sigma=5.0):
return np.exp(-linalg.norm(x - y) ** 2 / (2 * (sigma ** 2)))
class SVM:
def __init__(self, kernel=linear_kerne... |
import os
import sys
import pytest
from pandas import DataFrame
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import portfolio
import autocolors
class BlankArgs:
time_period = None
time_interval = None
class BlankStocksConfig:
tickers = {}
def __getitem__(self, key... |
import copy
grammar = []
new_grammar = []
terminals = []
non_terminals = []
I_n = {}
shift_list = []
reduction_list = []
action_list = []
rule_dict = {}
SR = []
RR = []
def Conflict():
global SR, RR, shift_list, reduction_list
conflict = False
for S in shift_list:
for R in reduction_list:
if S[:2] == R[:2]:
... |
import tensorflow as tf
import dirt
import dirt.lighting
import dirt.matrices
import normalizations as norm
def downsample(filters, size, apply_batchnorm=True):
initializer = tf.random_normal_initializer()
result = tf.keras.Sequential()
result.add(
tf.keras.layers.Conv2D(filters, size, strides=2... |
import sys
import os
import string
import collections
import codecs
import re
import json
import traceback
import getopt
from string import Template
TypeMapping = {
"INT" : "int",
"STRING" : "string",
"BOOL" : "bool",
"FLOAT" : "float",
"STRING_ID" : "StringID",
"RES_PATH" : "Resourc... |
""" Universidad Yachay Tech
<NAME>
Curso de Web Programming
Prof. <NAME>
"""
import os
import requests
from helpers import login_required
from flask import Flask, session, redirect, render_template, request, flash, jsonify, make_response
from flask_session import Session
from sqlalchemy import create_engine
from sq... |
import logging
import sys
import uuid
from functools import partial
import numpy as np
import tqdm
from sklearn.base import (
BaseEstimator,
ClusterMixin,
TransformerMixin,
clone,
)
from sklearn.utils.validation import check_is_fitted
from divik.core import (
configurable,
maybe_pool,
shar... |
#
# Copyright 2022 @Yves33, @sandhawalia
#
# 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 i... |
import argparse
import requests
from bs4 import BeautifulSoup
valid_content_types = [
'text/html',
]
crawling_headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36",
"accept-language": "en-US,en;q=0.8",
"Accept-En... |
'''
EnzymeML (c) University of Manchester 2018
EnzymeML is licensed under the MIT License.
To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
@author: neilswainston
'''
# pylint: disable=too-many-instance-attributes
import sys
import xml.sax
from libsbml import UNIT_KIND_MOLE, UNIT_KIND_S... |
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from multiprocessing import Process, Queue, TimeoutError
from multiprocessing.connection import Connection
from numpy import ndim, ndarray
from queue import Empty
plt.style.use('fivethirtyeight')
def default_fig(**kwargs):
""" Genera... |
import datetime
import logging
from typing import Dict, Tuple
from ortools.sat.python import cp_model
from allocation.allocation_models import (
ALLOCATION_PRECISION,
AllocatedEvent,
AllocationData,
AllocationEvent,
AllocationOccurrence,
AllocationSpace,
)
logger = logging.getLogger(__name__)... |
#!/usr/bin/python3
# Setup IaaS Provider
#
# This script is for setting up and IaaS provider in WGM.
# It takes 2 arguments, provider id and type.
# Once ID is verified, based on provider type we leverage certain other libraries to setup the specific provider
# Digitalocean, AWS, Google, Azure, ect.
# Usage:
# ./... |
# Copyright 2021 Sony Group 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 ... |
from kraken.core.maths import Xfo
from kraken.core.maths import Vec3
from kraken.core.objects.components.base_example_component import BaseExampleComponent
from kraken.core.objects.attributes.attribute_group import AttributeGroup
from kraken.core.objects.attributes.integer_attribute import IntegerAttribute
from krake... |
__author__ = 'zwding'
__version__ = '1.0'
import json
import time
import os
import argparse
import numpy as np
import cv2
import tqdm
from collections import defaultdict
from pycocotools import mask as maskUtils
from deep_image_matting.core.matter import Matter, binary_mask_to_polygon, binary_mask_to_rle
from generate... |
import re
import os
import sys
import math
import random
import numpy as np
import pandas as pd
from Bio import SeqIO
from PyDAIR.io.PyDAIRIO import *
from PyDAIR.utils.PyDAIRUtils import *
class PyDAIRSimGeneSet:
"""PyDAIRSimGeneSet class.
The class is for sampling sequences of single of V, D or J gene.... |
import os
import h5py as hf
from omnibelt import unspecified_argument
import numpy as np
import torch
from torch.nn import functional as F
import torchvision
from ... import util
from ...data import register_dataset, Batchable, Deviced, Downloadable, ImageDataset
from .transforms import Interpolated
class T... |
#!/usr/bin/env python
import random
import rospy
from std_srvs import srv
from tf.transformations import quaternion_from_euler
from math import pi,cos,sin
from visualization_msgs.msg import Marker
from visualization_msgs.msg import MarkerArray
from geometry_msgs.msg import Vector3,Pose,Point, Quaternion,Transform,Tran... |
"""Tracing function and controls"""
import inspect
import linecache
import re
from copy import copy
from types import FrameType, FunctionType, ModuleType
from typing import Any, Dict, List, Optional, Tuple, Callable
from .complexity import is_complexity_tracing_enabled
from .memory_footprint import MemoryFootprint
f... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import numpy as np
LCOS_X_SIZE, LCOS_Y_SIZE, LCOS_PIX_SIZE = 800, 600, 20e-6
YL, XL = np.mgrid[:LCOS_Y_SIZE, :LCOS_X_SIZE]
def zeros_lcos(dtype=None):
return np.zeros((LCOS_Y_SIZE, LCOS_X_SIZE), dtype=dtype)
class LCOS:
xsize = LCOS_X_SIZE
ysize = LCOS_Y_SIZE
pix_size = LCOS_PIX_SIZE
XL, YL = np... |
from bisect import bisect_left
from .form.utils import docval, getargs, popargs, call_docval_func, get_docval
from .form.data_utils import DataIO, RegionSlicer
from .form import get_region_slicer
from . import register_class, CORE_NAMESPACE
from .base import TimeSeries
from .core import NWBContainer, NWBTable, NWBTab... |
# [파이썬 크롤러 만들기](https://jione-e.tistory.com/28)
# [Source Code for Package lxml.html](https://lxml.de/api/lxml.html-pysrc.html)
import os, sys
import json
import time
import re
import openpyxl
# from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, Alignment
import requests
import lxml.html as et... |
"""
measure_adjacency.py
Measures adjacency of TrakEM2 files. For each layers, extracts all of the
adjacency lists. Fills in any gaps in the boundary path to make the boundary
continuous (TrakEM2 only includes a subset of points on the boundary). Determines
the bounding box for each area list. Identifes which bound... |
#!/usr/bin/python3
# download dragon_support.zip for file dependencies
import sys
import time
sys.path.append("./shared")
from sbmloader import SBMObject # location of sbm file format loader
from ktxloader import KTXObject # location of ktx file format loader
from sbmath import m3dDegToRad, m3dRa... |
from nlu import SemanticNLU
from rasa_nlu import RasaNLU
from question import QuestionAnswer
from models import *
from goals import *
from error import *
from helpers import *
from app import logger
state_machine = {
"home": {
"create_procedure": "creating",
"execute": "executing",
"edit": ... |
import numpy as np
import pdb
import torch
def boxlist_nms(boxlist, nms_thresh, max_proposals=-1, score_field="score"):
"""
Performs non-maximum suppression on a boxlist, with scores specified
in a boxlist field via score_field.
Arguments:
boxlist(BoxList)
nms_thresh (float)
m... |
import asyncio
import json
from dataclasses import asdict
from typing import Any, Optional, Union
import aiohttp
import sanic
from .decorators import SlashOption
from .enums import CommandType
from .response import _DiscordResponse
from .errors import *
__all__ = ("HTTP", "Route")
class Route:
BASE: str = "htt... |
from flask import Blueprint, request, abort, redirect, url_for, render_template
from flask_login import current_user, login_required
from flask_paginate import Pagination
from app import app
from app.module.voter import Voter
from app.module.voter.form import VoterForm, VoterRegisterForm, VoterLoginForm
from app.helper... |
import numpy as np
from sklearn.model_selection import StratifiedKFold, train_test_split, GroupShuffleSplit, ShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, precision_score, recall_score, roc_curve
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors.nearest_centroid ... |
# To load labelme .json files and convert to COCO .json format
# 'bbox' won't be filled, but fille to 'cord' attribute instead.
# Input:
# json_root: path to .json files from labelm software
# Output:
# dst_root: output path to the COCO-like .json file
import json
import os
from collections import OrderedDict
from... |
from dbinspector.map import find_entries, read_uniprot_data, read_refseq_data
import pandas as pd
from dbinspector.exceptions import QueryNotFoundError, InputError
import dbinspector.startup
import logging
from typing import Dict, Optional, List
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
def... |
# 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 writing, software
# distribu... |
import torch
import os
import argparse
import json
from datetime import datetime as dt
import sys
from rdkit import RDLogger
from seq_graph_retro.molgraph.mol_features import ATOM_FDIM
from seq_graph_retro.molgraph.mol_features import BOND_FDIM, BINARY_FDIM
from seq_graph_retro.models.model_builder import build_model,... |
import numpy as np
import cv2
import scipy.io as sio
# Make sure that caffe is on the python path:
caffe_root = '../../' # this file is expected to be in {caffe_root}/sfd_test_code
import os
os.chdir(caffe_root)
import sys
sys.path.insert(0, 'python')
import caffe
def detect_face(net, image, shrink):
if shrink... |
from .exceptions import ImportingError, ImportingHTTPError
from .settings import DOTPODCAST_DOMAIN
IMPORTERS = (
'dpx.hosting.importers.wp.WordPressImporter',
'dpx.hosting.importers.rss.RssAsHtmlImporter',
'dpx.hosting.importers.rss.RssImporter'
)
CATEGORY_TERMS = {
'Arts': 'https://%s/taxonomies/sub... |
# coding:utf-8
from datetime import datetime, timedelta
from threading import Thread
from time import sleep
from database import DataBaseHandler, time_step
from api import get_api
from after_retrievers import after_timedelta
from date_time_retrievers import retrieve_datetime
from text_retrievers import retrie... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.