text stringlengths 3.07k 12.6k |
|---|
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
import numpy as np
from scipy import integrate
from floris.utils.tools import valid_ops as vops
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #
# MISCELLANEOUS #
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++... |
import time, os, sys
import numpy as np
import signal
import random
from alarmexception import AlarmException
from getch import _getChUnix as getChar
from colorama import init, Fore, Back, Style
init()
HEIGHT=40
WIDTH=90
PADDLE_LEN = 10
INPUT_CHAR=''
LIVES = [20]
LEVEL = [1]
SCORE = [0]
START = [0]
START_LVL = [0]
FAL... |
# Copyright 2016-2021, Pulumi 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 t... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 28 13:20:36 2020
@author: ambar
"""
'''
Imports
'''
import glob
from astropy.io import fits
import numpy as np
import matplotlib.pyplot as plt
from astropy.nddata import CCDData
import astropy.units as u
import ccdproc
import os
########################################... |
import cowsay
import gtts
import os
import random
import yaml
from pathlib import Path
from zalgo_text import zalgo
from discord import Embed
from discord.ext import commands
from discord.ext.commands import Context, Cog, command, cooldown
from discord.ext.commands.errors import BadArgument
from discord.file import Fi... |
"""Create a self extracting executable
"""
import argparse
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
try:
from importlib.resources import read_text, files
except ImportError:
from importlib_resources import read_text, files
from . import VERSI... |
"""
This module contains all the code that is necessary to facilitate the updating
of the simulation and other objects from the interface, and also for sending
information back to the interface.
"""
import copy
from twisted.logger import Logger
from ..util.dict import difference, merge
class Handler():
"""
The... |
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pytest
from cycler import cycler
def test_colorcycle_basic():
fig, ax = plt.subplots()
ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']))
for _ in range(4):
ax.plot(range(10), range(10))
assert [l.get_color() ... |
import boto3
import json
import logging
import os
SUCCESS = "SUCCESS"
FAILED = "FAILED"
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
if 'LOG_LEVEL' in os.environ:
if os.environ['LOG_LEVEL'] == 'DEBUG':
logger.setLevel(logging.DEBUG)
if os.environ['LOG_LEVEL'] == 'INFO':... |
import argparse
import asyncio
import html
import json
import xml.etree.ElementTree as ET
from pathlib import Path
import aiohttp
import export
data_dir = Path('data')
data_dir.mkdir(parents=True, exist_ok=True)
def param_to_request_body(action, param):
res = '''<v:Envelope xmlns:v="http://schemas.xmlsoap.org/... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2020-2021 Alibaba Group Holding Limited.
#
# 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/LI... |
## Main entrance for the universal energy management (UEMS).
# Documentation for the UMES.
# \author: <NAME>
# \mail: <EMAIL>
# \date: 20 November 2017
# The following packages are required to deploy UEMS
# 1) Python 3.6+
# 2) MySQL
# 3) Zeromq
# 4) APScheduler
# 5) Gurobi*(academic use only)
# 6) Mosek*(academic use ... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
from scrapy import Item,Field
class BasicInfoItem(Item):
basic_id = Field()
city_id = Field()
city_name = Field()
district_name = Field()
distric... |
from typing import Set, Optional, Iterable
from django.urls import reverse
from lazy import lazy
from annotation.models import ClinVar, ClinVarVersion
from classification.enums import SpecialEKeys
from classification.views.classification_export_utils import ExportFormatter, AlleleGroup
from library.django_utils impor... |
"""
This is a sample implementation for working PyTorch Geometric with DeepChem!
"""
import torch.nn as nn
from deepchem.models.torch_models.torch_model import TorchModel
class GAT(nn.Module):
"""Graph Attention Networks.
This model takes arbitary graphs as an input, and predict graph properties. This model is
... |
# -*- coding: utf-8 -*-
import pytest
from osf.models import RegistrationSchema
from osf.exceptions import ValidationValueError
@pytest.mark.django_db
class TestRegistrationSchema:
@pytest.fixture()
def schema_name(self):
return 'Preregistration Template from AsPredicted.org'
@pytest.fixture()
... |
'''Train CIFAR10 with PyTorch.'''
from __future__ import print_function
import sys
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import config as cf
import torchvision
import torchvision.transforms as transforms
import os
import ar... |
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 18 16:21:13 2017
@author: <NAME>
This code is modified based on https://github.com/KGPML/Hyperspectral
"""
import tensorflow as tf
import numpy as np
import scipy.io as io
from pygco import cut_simple, cut_simple_vh
from sklearn.metrics import accuracy_score
import matpl... |
#!/usr/bin/env python
'''
Calculate the RNA-seq reads coverage over gene body.
This module uses bigwig file as input.
'''
#import built-in modules
import os,sys
if sys.version_info[0] != 2 or sys.version_info[1] != 7:
print >>sys.stderr, "\nYou are using python" + str(sys.version_info[0]) + '.' + str(sys.version_info... |
#!/usr/bin/env python
"""
Formatters for REDbot output.
"""
from collections import defaultdict
from configparser import SectionProxy
import inspect
import locale
import sys
import time
from typing import Any, Callable, List, Dict, Type, TYPE_CHECKING
import unittest
import thor
from thor.events import EventEmitter... |
"""Performs naive Bayes on the data from a given subreddit.
"""
import math
import datetime
import pandas as pd
from sklearn.naive_bayes import MultinomialNB
import numpy as np
import bag_of_words as bow
import sentimentAnalyzer as sa
MODEL = MultinomialNB()
def extract_features(data_frame: pd.DataFrame) -> pd.Data... |
# Utilities for integration with Home Assistant (directly or via MQTT)
import logging
import re
_LOGGER = logging.getLogger(__name__)
class Instrument:
def __init__(self, component, attr, name, icon=None):
self._attr = attr
self._component = component
self._name = name
self._con... |
#!/usr/bin/env python
#
# This code was copied from the data generation program of Tencent Alchemy
# project (https://github.com/tencent-alchemy).
#
#
# Copyright 2019 Tencent America LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in com... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def manual_cross_entropy(
logits: torch.Tensor, labels: torch.Tensor, weight: torch.Tensor
) -> torch.Tensor:
ce = -weight * torch.sum(labels * F.log_softmax(logits, dim=-1), dim=-1)
return torch.mean(ce)
class DetConBLoss(nn.Module):
... |
"""
DICT(IONARY) (DATA)SET
A group of functions to assist with handling lists of dictionaries, which is
how JSONL files will tend to be handled.
You would use these methods instead of something like Pandas if you are dealing
with potentially huge datasets and only require to be able to do simple
processes on the data... |
import asyncio
import itertools
from typing import Optional, Dict, Any, Union, List
import logging
import websockets
import json
from web3 import Web3
from .subscription import Subscription
from .methods import RPCMethod
from .contract import DeployedContract
from .types import Wei, Address, HexString
from .transport ... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import warnings
import numpy as np
import cv2
try:
import skimage.io
except ImportError:
pass
def ensure_float01(img, dtype=np.float32, copy=True):
""" Ensure that an image is encoded using a float p... |
#!/usr/bin/env python
# Taken from:
# https://github.com/castorini/anserini/blob/master/src/main/python/trec-covid/index_cord19.py
import os
import shutil
import tarfile
import requests
import argparse
from bs4 import BeautifulSoup
from tqdm import tqdm
from pathlib import Path
from urllib.request import urlretrieve
... |
import enum
import random
from typing import Dict, Iterable, List, Tuple, Optional, NamedTuple
from emoji import descriptions, spec_parser
from emoji.core import Emoji, Gender, Modifier
from syllables import count_syllables
def _load_resources() -> Tuple[Dict[Emoji, str], List[Modifier]]:
"""Loads emojis and des... |
import os
import http.cookiejar
import datetime
from datetime import datetime
import requests
import time
import mutagen
from mutagen import *
from mutagen.easyid3 import EasyID3
from mutagen.flac import FLAC
import json
from tqdm import tqdm
from pydub import AudioSegment
from pathlib import Path
import ... |
import re
from . import dun_string_reader as dsr
subsection_types = {'tspan' : ['dun', 'tspan' ],
'states' : ['dun', 'states' ],
'params' : ['dun', 'params' ],
'rxns' : ['dun', 'rxn... |
"""
Classes for Bayesian optimization
Created on Jul 9, 2019
@author: <NAME> (<EMAIL>)
Copyright 2019 Xilinx, Inc.
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 ... |
from bs4 import BeautifulSoup
# import BeautifulSoup
import requests
import json
from os import path
import os
import datetime
import time
import urllib
#pip3 install Beautifulsoup4
import nonebot
import requests
from aiocqhttp import MessageSegment
from jieba import posseg
from lxml import etree
from no... |
from pathlib import Path
import json
from arcgis import mapping, features
from GitHub.HelperScripts import get_funcs
from other.my_secrets import MySecrets
def clone_folder(
source_folder,
target_folder,
source_gis,
target_gis,
copy_data=True,
search_existing_items=True,
ignore_item_type=N... |
import functools
import re
from django.db import connections, connection
from six import text_type
import sqlparse
from . import app_settings
EXPLORER_PARAM_TOKEN = "$$"
# SQL Specific Things
def passes_blacklist(sql):
clean = functools.reduce(lambda sql, term: sql.upper().replace(term, ""), [t.upper() for t... |
import json
from enum import Enum
from typing import Dict, Optional, List, Any, Union
from toolkit.ev3.simulation.runtime import Runtime
class Motor:
def __init__(self, type: str) -> None:
self.__type = type
self.__speed = 0
self.__angle = 0
self.__count = 0
@property
def... |
import torch
from pykeops.torch import LazyTensor
from tqdm import tqdm
# Dimension specifications:
# B: Samples in Batch
# N: Number of points to cluster
# E: Dimensionality of the space the points are embedded in
class MeanShiftStep(torch.nn.Module):
GAUSSIAN_KERNEL = 'gaussian'
FLAT_KERNEL = 'flat'
EP... |
#!/usr/bin/env python3 -O
import argparse
import subprocess
import sys
def usage():
print("%s target_host target_port" % sys.argv[0])
if len(sys.argv) < 3:
usage()
sys.exit(1)
target_host = sys.argv[1]
target_port = sys.argv[2]
KEX_ALGORITHMS = {
'curve25519-sha256@libssh.org': [],
'diffie-h... |
import torch
import numpy as np
class FFNet(torch.nn.Module):
"""Simple class to implement a feed-forward neural network in PyTorch.
Attributes:
layers: list of torch.nn.Linear layers to be applied in forward pass.
activation: activation function to be applied between layers.
"""
... |
import os
import re
import collections
import shutil
import traceback
from os.path import join
from xml.dom import minidom
print("Start")
a = []
rpt = []
Folders = []
Address = []
def list_duplicates(seq):
global t
t = False
seen = set()
seen_add = seen.add
seen_twice = set( x for x in seq if x in... |
#!/usr/local/bin/python3
import random
import ipaddress
from randmac import RandMac
from urllib.parse import urlparse
import dns.resolver
import re
import hashlib
import time
import json
from kafka import KafkaProducer
import user_profile_hash_maker as uphm
import argparse
import configparser
# Parse configs
cfg = co... |
carbohydrate_min_length = 3
carbohydrate_chain_length_including_start_C = 3
def is_glycan(a_category):
for _ in a_category["types"]:
if "Glycan" in _:
return True
return False
def add_carbohydrate_output(output, type_, mass, num_c_atoms, num_o_atoms, atom_list, full_atom_dic):
output... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 02:08:15 2020
@author: sss
Naive Bayes Algorithm
Given a review is positive what is the probability an individual word is positive
P(class|data) = (P(data|class) * P(class)) / P(data)
P(class|data) = probability of class given the provided data... |
#!/usr/bin/python
import subprocess
import distutils.spawn
from os.path import exists
import psutil
from ansible.module_utils.basic import AnsibleModule
DOCUMENTATION = r'''
---
module: sysinfo
version_added: "0.1"
short_description: Get system information.
description: Module which gathers summarized information ... |
import argparse
import logging
import os
import random
import math
import ransac.core as ransac
from ransac.models.conic_section import ConicSection
import cv2
import numpy as np
logging.basicConfig(level=logging.DEBUG, format='%(asctime)-15s [%(levelname)s] %(message)s')
parser = argparse.ArgumentParser()
parser.add... |
import hashlib
import math
import struct
import time
class CurryError(BaseException):
def __init__(self, error_message):
self.error_message = error_message
class SeedGenerator:
def __init__(self, validator):
self._validator = validator
self._seed_base = time.time() * 1000
sel... |
"""
@name: Modules/Web/web_server.py
@author: <NAME>
@contact: <EMAIL>
@copyright: 2012-2020 by <NAME>
@note: Created on Apr 3, 2012
@license: MIT License
@summary: This module provides the web server(s) service of PyHouse.
This is a Main Module - always present.
Open 2 web servers.
open server... |
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.metrics import mean_squared_error
from agents.stew.utils import create_diff_matrix
import numpy as np
import gym
from agents.EwR... |
import pandas as pd
from .paramdb import *
from .file import *
from .utils import *
from doit.tools import run_once
def print_nested_df(orig):
dfs = [None]
def dedf(x):
if isinstance(x, pd.DataFrame):
i = len(dfs)
dfs.append(x)
return f"df{i}"
return x
dfs[0] = orig.applymap(dedf)
f... |
import abc
from typing import Iterable, Iterator, List, Optional
from .accesses import SimpleAccessReader
from .processor import AccessInfo, OfflineProcessor, OnlineProcessor
from .storage import Storage
from ..workload import Access, FileID
__all__ = [
'Access',
'AccessInfo',
'FileID',
'SimpleAccessReader',
'St... |
import copy
from musicscore.basic_functions import flatten
class Tree(object):
"""
A simple Tree class
"""
def __init__(self, label=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self._children = []
self._up = None
self._leaves = []
self.label = lab... |
import numpy as np
from scipy.optimize import brentq
from yt.fields.field_detector import \
FieldDetector
from pygrackle import \
add_grackle_fields, \
FluidContainer, \
chemistry_data
from pygrackle.yt_fields import \
_data_to_fc, \
_get_needed_fields
from yt.config import ytcfg
from yt.funcs ... |
import re
import string
from collections import defaultdict
import numpy as np
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer
from nltk.tokenize import TweetTokenizer
from scipy import linalg
def process_tweet(tweet):
"""Process tweet function.
Input:
tweet: a string containing... |
"""
Sniper Bot - Python edition
Created by sheepy0125, inspired by DankMemer
02/10/2021
"""
#############
### Setup ###
#############
# Import
from utils.tools import Logger
from discord import Embed, Game, Message, User, Intents, Embed
from discord.ext import commands
from discord_slash import SlashCommand, SlashCont... |
import os
import sys
import subprocess
import traceback
sys.path.append(snakemake.config['args']['mcc_path'])
import scripts.mccutils as mccutils
import config.tepid.tepid_post as config
def main():
insertions_bed = snakemake.input.insertions_bed
deletions_bed = snakemake.input.deletions_bed
insertions_su... |
# Results plotter.
#
# https://github.com/stefanvanberkum/CD-ABSC
import numpy as np
import pandas as pd
import statsmodels.formula.api as sm
from plotnine import aes, element_text, geom_point, ggplot, stat_smooth, theme
global embedding_dim, rest_path, target_path, ft_path, save_path
def main():
"""
Plots ... |
import errno
import json
import logging
import os
import platform
import uuid
from functools import wraps
from pathlib import Path
from typing import Any, Callable, Dict, Optional, TypeVar
from mixpanel import Consumer, Mixpanel
import datahub as datahub_package
logger = logging.getLogger(__name__)
DATAHUB_FOLDER =... |
#!/usr/bin/env python3
import argparse
import clang.cindex as clang
from clang.cindex import Index
import sys
import re
class Function:
def __init__(self, name, signature, ret, display, args):
self.name = name
self.signature = signature
self.ret = ret
self.display = display
... |
from typing import NamedTuple, Tuple, Optional
from .data_types import Vec3, Vec4
from .packet_buffer import PacketBuffer
from .packet_component import PacketComponent, PacketComponentArray
from .version import Version
class MarkerSetDescription(PacketComponent, NamedTuple(
"MarkerSetDescriptionFields",... |
import pygame
from settings import *
from support import *
from random import choice, randint
from tile import Tile
from player import Player
from ui import UI
from weapon import Weapon
from enemy import Enemy
from particles import AnimationPlayer
from magic import MagicPlayer
from upgrade import Upgrade
class Level:... |
import analytics
import logging,time,subprocess
from bson.objectid import ObjectId
from os import listdir,environ,makedirs,path
import sys,time
import graypy
from pymongo import MongoClient
import settings
analytics.write_key = settings.ANALYTICS_KEY
analytics.identify('downloader', traits={
'email': settings.REPO... |
import re
import numpy as np
from numpy.core.einsumfunc import _parse_einsum_input
from paderbox.array.segment import segment_axis
__all__ = [
'split_complex_features',
'merge_complex_features',
'tbf_to_tbchw',
'morph',
]
def split_complex_features(X):
""" Split a complex valued input array int... |
#!/usr/bin/env python3
"""Investigates the distribution for link Markov models.
The link Markov model is based on the linking behavior of a given
linkograph. Since the links in a linkograph are determined by
ontology, the transition model is depending on the ontology. This
script creates a sequence of random Markov m... |
#!/usr/bin/env python3
# Arguments:
# -h: help, -v: verbose mode -m mpi-tasks
import os, sys, argparse, subprocess
#------------------------------------------------
def guess_mpi_cmd(mpi_tasks, cpu_allocation, verbose):
if verbose: print('os.uname=', os.uname())
node_name = os.uname()[1]
if verbose: prin... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class FaceMeshBlock(nn.Module):
"""This is the main building block for architecture
which is just residual block with one dw-conv and max-pool/channel pad
in the second branch if input channels doesn't match output chann... |
from __future__ import division
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import Imputer, MinMaxScaler, StandardScaler, OneHotEncoder
from sklearn.feature_selection import VarianceThreshold
import pandas as pd
from clumpy.unique_threshold import UniqueThre... |
import datetime
import json
import math
import numbers
import os
import pickle
import random
import re
import statistics
from collections.abc import MutableMapping
from datetime import datetime, timedelta
from resource import RUSAGE_SELF
from resource import getrusage as resource_usage
from time import time as timestam... |
#!/usr/bin/env python3
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
import argparse
import logging
import os
import pathlib
from typing import Optional
import math
from tqdm import tqdm
import path_to_kapture_localization # noqa: F401
import kapture_localization.utils.logging
from kapture_localiza... |
# Combine multiple images into one.
from __future__ import print_function
import os
import random
import csv
from xml.etree import ElementTree
from xml.dom import minidom
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
import xml.etree.cElementTree as ET
from PIL import Image
def writeToXml(i... |
# ===============================================================================
#
# Copyright (c) 2013-2017 Qualcomm Technologies, Inc.
# All Rights Reserved.
# Confidential and Proprietary - Qualcomm Technologies, Inc.
#
# ===============================================================================
"""
Create... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Copyright 2019 Huawei Technologies Co.,Ltd.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy of the
# License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unle... |
import yaml
import sys
import os
import pathlib
import zipfile
import shutil
import tarfile
import errno
# Read YAML file
def main(argv):
command_name = 'mkisofs'
target_directory = 'target'
if sys.version_info[0] != 3 or sys.version_info[1] < 6:
print("This script requires Python version 3.6+")
... |
from PIL import Image, ImageDraw
import sys
import math, random
from itertools import product
from utils.ufarray import *
import numpy as np
def perform_dws(dws_energy, class_map, bbox_map,cutoff=0,min_ccoponent_size=0, return_ccomp_img = False):
bbox_list = []
dws_energy = np.squeeze(dws_energy)
class_m... |
"""
Turning radar PPIs into Cartesian grids. Processing the Australian
National archive.
@creator: <NAME> <<EMAIL>>
@institution: Monash University and Bureau of Meteorology
@date: 12/04/2021
.. autosummary::
:toctree: generated/
buffer
check_rid
extract_zip
get_radar_archive_file
mkdir
r... |
import itertools
import requests
from geosolver import settings
import networkx as nx
__author__ = 'minjoon'
class SyntaxParse(object):
def __init__(self, words, directed, undirected, rank, score):
self.words = words
self.directed = directed
self.undirected = undirected
self.rank =... |
import io
import os
import time
import subprocess
import sdi_utils.gensolution as gs
import sdi_utils.set_logging as slog
import sdi_utils.textfield_parser as tfp
import sdi_utils.tprogress as tp
try:
api
except NameError:
class api:
queue = list()
class Message:
def __init__(s... |
import argparse
import base64
import json
import os
import pickle
import sys
from datetime import datetime, timedelta, timezone
from functools import wraps
import boto3
import botocore
import keyring
__version__ = "0.4.0"
ACCOUNT_MAPPING_FILENAME = os.path.expanduser("~/.aws/accounts")
KEYRING_SERVICE_NAME = "aws_lo... |
from pymongo import MongoClient
from pymongo.database import Database
import requests
import json
import schedule
import datetime
import os
from tweet import Tweet
from threading import Thread
now = datetime.datetime.now()
CUR_TIMESTAMP = int(datetime.datetime(year=now.year, month=now.month, day=now.day, hour=now.ho... |
# 어휘 사전과 워드 임베딩을 만들고, 학습을 위해 대화 데이터를 읽어들이는 유틸리티들의 모음
import tensorflow as tf
import numpy as np
import re
import codecs
from config import FLAGS
class Dialog():
_PAD_ = "_PAD_" # 빈칸 채우는 심볼
_STA_ = "_STA_" # 디코드 입력 시퀀스의 시작 심볼
_EOS_ = "_EOS_" # 디코드 입출력 시퀀스의 종료 심볼
_UNK_ = "_UNK_" # 사전에 없는 단어를 나타내는 ... |
#
# 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
# distributed under ... |
#!/usr/bin/env python3
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# 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 Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This p... |
"""
Goal - Calculate distance travelled by each fish
Date - Mar 11 2021
"""
import os
import pathlib
from pprint import pprint
import numpy as np
from scipy import stats
from scipy.spatial import distance
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import trajectorytools as tt
import trajec... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
import warnings
warnings.filterwarnings(action='once')
data = None;
matData = None;
def initData(csvName):
data = pd.read_csv(csvName)
matData = pd.DataFrame(columns=['Name','Diameter','Length','Reduced Diamter','Area','Reduce... |
import json
from .database import redis_db
def get_redis_list(redis_list_key):
python_standard_list = []
for i in range(0, redis_db.llen(redis_list_key)):
# print(redis_db.lindex(redis_list_key, i))
python_standard_list.append(float(redis_db.lindex(redis_list_key, i)))
return python_standa... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib.figure import Figure
from matplotlib import rcParams
def dBofHz(inputHz):
'''... |
from multiprocessing.pool import Pool
from os import makedirs
from os import remove
from os.path import exists, join
from shutil import rmtree
from subprocess import check_output
import boto3
from invoke import task
from tasks.python import run_python_codegen
from tasks.util.codegen import find_codegen_func, find_cod... |
"""
Here, the code to get the heatmap of individual channels is present.
It assumes that a pretrained model of type GazeStaticSineAndCosineModel is passed on.
One has the option to choose the layer of which the heatmap is desired.
"""
from typing import List, Tuple
import matplotlib.pyplot as plt
import numpy as np
im... |
# -*- coding: utf-8 -*-
import lemoncheesecake.api as lcc
from lemoncheesecake.matching import require_that, is_true, is_false
from common.base_test import BaseTest
SUITE = {
"description": "Method 'check_erc20_token'"
}
@lcc.prop("main", "type")
@lcc.prop("positive", "type")
@lcc.tags(
"api", "database_api... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
from copy import deepcopy
from datetime import datetime, timedelta
from itertools import compress
Item = namedtuple("Item", ['index', 'value', 'weight'])
def enough_space(cur_sel, items, capacity):
"""
Check current selection agai... |
"""
Adapted from https://github.com/pybind/cmake_example
"""
import os
import platform
import re
import shutil
import subprocess
import sys
import sysconfig
from distutils.command.build_ext import build_ext
from distutils.core import Distribution, Extension
from distutils.version import LooseVersion
from typing import ... |
'''
This script is to get anchors and pos/neg weights
'''
import os
import h5py
import json
import math
import numpy as np
import h5py
import random
import time
import threading
from sklearn.cluster import KMeans
sample_ratio = 1.0
c3d_resolution = 16
stride = 4
sample_num = 1
n_anchors = 128
tiou_... |
#!/usr/bin/env python
# coding: utf-8
from websocket import create_connection
import json
import psutil
import os
import datetime
import time
import configparser
import sys
import requests
import secrets
import distro
from hashit import make_hash
#Provide full path, if you are using a systemd service
conf_file = 'mo... |
#!/usr/bin/env python
import logging
import sys
from pathlib import Path
from typing import Dict, Iterator, Optional, Tuple, Union
import fire
from benchmarker.cli.l5.common.utils import save_t5_kleister_cache
from benchmarker.data.model.feature import Feature
from benchmarker.data.reader import Corpus, qa_strategies... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.constants import k,h,c
from scipy.optimize import curve_fit
from numba import njit,jit
import emcee
@njit
def Planck(lamb,T):
"""
Black-body radiation; Bnu.
Args:
lam: (float) wavelength [m]
T: (float) te... |
# ______________________________________________________________________________
# The Wumpus World
class Gold(Thing):
def __eq__(self, rhs):
'''All Gold are equal'''
return rhs.__class__ == Gold
pass
class Bump(Thing):
pass
class Glitter(Thing):
pass
class Pit(Thing):
pass
cl... |
"""
"""
from __future__ import division, print_function, unicode_literals
import Pyro4
import numbers
import sys
try:
import numpy as np
except ImportError:
import fake_numpy as np
if sys.version_info >= (3, 0):
str_types = (str,)
else:
str_types = (str, unicode)
class NeedsSubMeta(Exception):
pa... |
#Coded by <NAME>
#02/09/2018 latest version.
#Copyright (c) <2018> <<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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.