text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 22 06:43:26 2020
@author: paras
"""
from flask import Flask, request
import flask
import joblib
import pandas as pd
import numpy as np
app = Flask(__name__)
#///////////////////////////////////////////////////////////////////////
def find_bmi(data):
bmi = data['... |
#
# Copyright (c), 2016-2020, SISSA (International School for Advanced Studies).
# All rights reserved.
# This file is distributed under the terms of the MIT License.
# See the file 'LICENSE' in the root directory of the present
# distribution, or http://opensource.org/licenses/MIT.
#
# @author <NAME> <<EMAIL>>
#
"""
T... |
import struct
from twisted.internet.protocol import Protocol, Factory, ClientFactory
from twisted.internet import reactor
import bitarray
from enum import Enum
import logging
import dtoc_bencode
REQUEST_PIECE_SIZE = 0X4000
class BTProtocolStates(Enum):
handshake_sent = 1
connected = 2
class BTClientFactory(... |
import os
from typing import List, Dict, Callable, Tuple
import pandas as pd
from flowpipe import Graph, INode, Node, InputPlug, OutputPlug
from insurance_claims.record_types import *
# let's invent some kind of overhead that goes into processing the claim
CLAIM_VALUE_PROCESSING_OVERHEAD_RATE = 0.05
# threshold to ... |
import os
import time
import json
import argparse
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import foolbox
import scipy.io as io
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime
from utils import L1, L2, NumpyEncoder
from provable_robustness_max_li... |
import os
import cv2
import numpy as np
import pandas as pd
from datetime import datetime
#to save our model periodically as checkpoints for loading later
from keras.callbacks import ModelCheckpoint, TensorBoard
#popular optimization strategy that uses gradient descent
from keras.optimizers import Adam
from sklearn.mo... |
from copy import copy
import pytest
import networkx as nx
import random
from networkx.utils import (
create_py_random_state,
create_random_state,
discrete_sequence,
dict_to_numpy_array,
dict_to_numpy_array1,
dict_to_numpy_array2,
flatten,
is_string_like,
iterable,
groups,
ma... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Command-line tool for simulating predictive datasets from MrBayes' output.
"""
import argparse
import csv
import os
import shutil
import sys
from collections import namedtuple
from contextlib import ExitStack
from itertools import islice
from math import fabs
import... |
"""Rider name database helper object.
This module provides a simple object helper for manipulating the
rider namebank database. Methods are provided for retrieving rows
by license no and for searching by name.
namebank objects are intended to be used in a 'with' context eg:
with namebank() as n:
matches = n.... |
import errno
import logging
import os
import shutil
from collections import defaultdict
from contextlib import contextmanager
from psycopg2.errors import UndefinedFile
from .connection import get_connection_cursor
from .misc import format_lsn
logger = logging.getLogger(__name__)
def compare_slots(s1, s2, dbid='dat... |
# problem, during test, the corresp should also be changed..
import argparse
from nltk.corpus import wordnet as wn
import re
import torch
import pickle
import json
import numpy as np
import torch.nn.functional as F
parser = argparse.ArgumentParser()
parser.add_argument('--dataset', default='vgbansal', type=str, hel... |
from itertools import product
import pandas as pd
from fiber.config import OCCURRENCE_INDEX
from fiber.dataframe.helpers import get_name_for_interval
from fiber.dataframe import merge_to_base, column_threshold_clip
from fiberutils.cohort_utils import threshold_clip_time_series, pivot_time_series
from sklearn.dummy imp... |
#!/usr/bin/env python
"""Script to run SeleniumLibrary acceptance tests.
Tests are executed using Robot Framework and results verified automatically
afterwards using `robotstatuschecker` tool. The tool can be installed using
`pip install robotstatuschecker` and more information about it can be found
from: https://gith... |
import os
from models import *
from django import forms
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import Context, RequestContext, loader
from django.conf import settings
from django.core.mail import send_mail
from django.contrib.auth.decorators import login_requ... |
"""Transformation for inserting refrecence count inc/dec opcodes.
This transformation happens towards the end of compilation. Before this
transformation, reference count management is not explicitly handled at all.
By postponing this pass, the previous passes are simpler as they don't have
to update reference count op... |
from tkinter import *
from geometry import Bounds, Point2D, Vector2D
import sys
import time
import urllib.request as request
import subprocess
import os
import ctypes
from socketIO_client_nexus import SocketIO, BaseNamespace
import threading
import queue
'''
queues for sharing information across threads for multiplaye... |
# -*- coding: utf-8 -*-
# Copyright 2014-2015 Red Hat, 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 applica... |
#!/usr/bin/env python3
import os
import pickle
import pytest
from copy import copy
try:
import conftest
except ImportError:
from . import conftest
import numpy as np
from geofun2 import *
def test_version():
assert get_version() == "0.0.2"
def test_angle_mod():
assert angle_mod(0) == 0
assert... |
from swmmio.defs.constants import red, purple, lightblue, lightgreen, black, lightgrey, grey
from swmmio.defs.config import FONT_PATH
from swmmio.graphics.utils import circle_bbox, length_bw_coords, angle_bw_points, midpoint
from PIL import Image, ImageDraw, ImageFont, ImageOps
from time import strftime
import math
imp... |
## Reference: Quantum Associative Memory - <NAME>
## arXiv:
## \date: 15-02-2018 - 27-02-2018
## \repo: https://gitlab.com/prince-ph0en1x/QuInE
## \proj: Quantum-accelerated Genome-sequencing
###################################################################################################
# ... |
import logging
import json
import re
from typing import List, Dict
from google.cloud import bigquery
from google.api_core import exceptions
from .transform_utils import TransformationHelper, SQLFlavor
from . import utils
LOGGER = logging.getLogger(__name__)
# tone down snowflake connector logging level.
logging.get... |
'''
@brief:
a tensorflow implementation of GGNN
@author:
<NAME> (2018-8-21)
'''
import numpy as np
import tensorflow as tf
class MLP(object):
def __init__(self,
output_size,
scope='mlp_dropout',
n_layers=2, size=1024, activation=tf.nn.relu,
... |
from pypy.objspace.flow.model import Variable, mkentrymap, flatten, Block
from pypy.tool.algo.unionfind import UnionFind
class DataFlowFamilyBuilder:
"""Follow the flow of the data in the graph. Builds a UnionFind grouping
all the variables by families: each family contains exactly one variable
where a va... |
# Copyright 2016 Hewlett Packard Enterprise Development LP
#
# 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 ... |
"""
MIT License
Copyright (c) 2022 CrazzzyyFoxx
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... |
import matplotlib.pylab as plt
import numpy as np
import os
import natsort as ns
import dicom
from scipy.ndimage import morphological_gradient,sobel
from scipy.ndimage.morphology import binary_erosion
from skimage import feature
import nibabel as nib
def dice_coefficient(A,B):
return 2.0*np.logical_and(A,B).sum()/... |
#!/usr/bin/env python
"""
Illumination control.
Hazen 04/17
"""
import os
from PyQt5 import QtCore, QtWidgets
import storm_control.sc_library.halExceptions as halExceptions
import storm_control.sc_library.parameters as params
import storm_control.hal4000.halLib.halDialog as halDialog
import storm_co... |
#!/usr/bin/python
#
# Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
#
from __future__ import print_function
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import object
import os
import sys
import errno
import subprocess
import time
import ... |
#!/usr/bin/env python
"""
this file holds the serializer and deserializer of the idlenesses of the Destinations.
IdlenessLogger:
serializer, called during the shutdown of topoplanner.py
+ pickles the Destinations in the appropriate "idleness/$(env)/dumps/$(robotnum)/" subfolder
+ prints... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import ast
import te... |
# -*- coding: utf-8 -*-
from enum import Enum
from typing import Set, Dict, Optional, Tuple, Union
from random import randint
import uuid
# This is the process dictionary that is used to store all processes of
# the Actinia wrapper
from openeo_grass_gis_driver.actinia_processing.actinia_interface import \
Actinia... |
import argparse
import csv
import sqlite3
import sys
from os import listdir
from os.path import isfile, join
#SC2 related imports
import sc2reader
from sc2reader.engine.plugins import SelectionTracker, APMTracker
banned_units = ['Beacon']
games_columns = {
'hash': 'varchar(255) NOT NULL PRIMARY KEY',
'team_1... |
# -*- coding: utf-8 -*-
"""
This module contains the checker mode, a base class for code checker modes.
"""
import logging
from pyqode.core.api import TextBlockUserData
from pyqode.core.api.decoration import TextDecoration
from pyqode.core.api.mode import Mode
from pyqode.core.backend import NotRunning
from pyqode.core... |
import os
import gym
import time
import logging
import numpy as np
import tensorflow as tf
from common.multiprocessing_env import SubprocVecEnv
from tqdm import tqdm
from env_model_minigrid import create_env_model
from a2c import get_actor_critic, CnnPolicy
from common.minigrid_util import num_pixels, mode_rewards, pi... |
"""This script will get verification nodes pk as inputs and export all results into a json file
It is only a template solution for how to store the results for showing in
the aiidalab-sssp app. In the long term, I plan to transfor these json file into mongodb
database and held a API on the dokku server able to be quer... |
import numpy as np
from numba import jit
def detect_poles(xyz, neighbourthr = 0.5, min_point_num = 3, dis_thr = 0.08, width_thr = 10, fov_up=30.67, fov_down=-10.67, proj_H = 32, proj_W = 250, lowest=0.1, highest=6, lowthr = 1.5, highthr = 0.7, totalthr = 0.6):
range_data, proj_vertex, _ = range_projection(xyz,
... |
## @module FeatSeqPercentModel
# Feature to output the percentile that a session is at along a progression of gameplay timestamp features. Depends
# heavily on the logic used to produce the quantiles file. The following exemplifies current implementation:
#
# Example: A game has 10 checkpoints. Joey has reached 3/10 ch... |
import requests
import urllib
import uuid
import importlib_metadata
import json
import base64
import logging
from collections import namedtuple, defaultdict, ChainMap
from typing import List
__all__ = [
'KafkaRestClient', 'KafkaRestClientException',
'TopicPartition', 'KafkaMessage'
]
log = logging.getLogger(... |
from types import ModuleType
import json
import platform
import time
import string
import warnings
import requests
from . import error, resources, session, __version__
from .page_iterator import CollectionPageIterator
# TODO: Consider using six here instead
try:
import urllib.parse as urlparse
except ImportError... |
"""
Semantic features
"""
import argparse
import json
import math
import subprocess
import sys
import tempfile
from gensim.models.word2vec import Word2Vec
from . import tagme
import summaryrank
from summaryrank.util import ElapsedTimeIndicator, SaveFileLineIndicator
class ESACosineSimilarity(summaryrank.Feature):
... |
import math
import pandas as pd # type: ignore
import numpy as np # type: ignore
import pyfolio as pf # type: ignore
from typing import Optional, List, Dict, Iterable, Tuple
from decimal import Decimal
from bankroll.model import *
from bankroll.marketdata import *
from dataclasses import asdict
def etf(portfolio: ... |
import tcod as libtcod
from dodge.constants import ComponentType, InputCommands
from dodge.game.state import GameStatus
import dodge.utils as utils
class InputHandler(object):
def __init__(self):
self.key = libtcod.Key()
# TODO: Change from silly if/else to a map
def get_keyboard_input(self, game... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: <NAME>
@Contact: <EMAIL>
@File: model.py
@Time: 2018/10/13 6:35 PM
"""
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
def knn(x, k):
inner = -2 * torch.matmul(x.transpose(2, 1), x)
xx = torch.sum(x ** 2, dim=1, kee... |
# Copyright 2016-2018, Rigetti Computing
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
QuantumFlow Gate Decompositions
"""
from typing import Sequence, Tuple
import itertools
import numpy as np
from numpy import ... |
#!/usr/bin/env python3
"""
Query an installed extension.
Format configuration (-F, --fconfig): Use -F to specify custom formatting
configuration. The syntax is as follows:
key=<number> Set key to the value of <number>
key Set key to the value True
key=True Set key to the ... |
#!/usr/bin/env python
"""Random baseline for the PAN19 hyperpartisan news detection task"""
# Version: 2018-09-24
# Parameters:
# --inputDataset=<directory>
# Directory that contains the articles XML file with the articles for which a prediction should be made.
# --outputDir=<directory>
# Directory to which the p... |
import os
from functools import partial
from kivy.properties import NumericProperty, BooleanProperty, ObjectProperty, StringProperty
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.gridlayout import GridLayout
fr... |
import calendar
import logging
from datetime import date, timedelta
import sqlalchemy as sa
from sqlalchemy import and_
from markupsafe import escape
from galaxy import model, util
from galaxy.web.base.controller import BaseUIController, web
from galaxy.web.framework.helpers import grids
from galaxy.webapps.reports.c... |
from contextlib import contextmanager
from functools import partial
from itertools import chain
from typing import List, Optional, Tuple, Dict, Any, Type, Union, Callable
from django.contrib.auth.base_user import AbstractBaseUser
from ..exceptions import UnknownMessageTypeError, MessengerException
from ..models impor... |
#############################################################################################################
#<NAME>
#
# Trash Classification Project
#############################################################################################################
#Library imports
import numpy... |
from pycket.base import W_Object
from pycket.error import SchemeException
from pycket import values, values_string
from pycket import regexp
from rpython.rlib.rsre import rsre_core, rsre_char, rsre_re
from rpython.rlib import buffer, jit, rstring
from rpython.rlib.objectmodel import spe... |
# Copyright (c) 2017-2019 Uber Technologies, Inc.
# SPDX-License-Identifier: Apache-2.0
import torch
from torch import nn
from contextlib import ExitStack
import pyro
import pyro.distributions as dist
from pyro import poutine
from pyro.contrib.util import (
tensor_to_dict, rmv, rvv, rtril, lexpand, iter_plates_t... |
import re
import argparse
__all__ = ["GlasgowAppletError", "GlasgowApplet", "GlasgowAppletTool"]
class GlasgowAppletError(Exception):
"""An exception raised when an applet encounters an error."""
class GlasgowApplet:
all_applets = {}
def __init_subclass__(cls, name, **kwargs):
super().__init_... |
#!/usr/bin/python3
import gi
gi.require_version('Gtk', '3.0')
import sys, os, threading, re, gettext
from gi.repository import Gio, Gtk, GLib, GObject, Pango, GdkPixbuf
gettext.install("placesCenter@scollins", os.environ['HOME'] + "/.local/share/locale")
def launch(path):
fileObj = Gio.File.new_for_path(path)
... |
# ******************************************************************************
# Copyright 2017-2018 Intel 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.apa... |
# This file is directly taken from a code implementation shared with me by <NAME> al., authors of the paper https://arxiv.org/abs/2002.09564
# GitHub: https://github.com/PrateekMunjal
# ----------------------------------------------------------
# code modified from VAAL codebase
import os
import torch
import... |
import os
import subprocess
import numpy as np
import pandas as pd
import networkx as nx
import multiprocessing
from multiprocessing import Pool
# DESCRIPTION:
'''
This library includes all the function which are necessary to compute the orbits
and the distance from an edge list with gene names. All is prepared t... |
#
# Copyright 2016-2019 Games Creators Club
#
# MIT License
#
import math
import traceback
import pyroslib
import pyroslib.logging
from pyroslib.logging import LOG_LEVEL_INFO
from rover import Rover, normaiseAngle, angleDiference
from challenge_utils import AgentClass, Action, WaitSensorData, WarmupAction, PID
SQ... |
"""
numwords.py
https://github.com/ramueller11/py-numwords
Interconvert English words with whole numbers.
Example:
int2words('555') = 'five hundred fifty five'
words2int('one') = 1
words2int('first') = 1
words2int('a hundred') = 100
words2int('none') = 0
words2int('negative ten') = -10
"""
... |
#!/usr/bin/env python3
import logging
logging.basicConfig(level=logging.WARN)
import csv
import glob
import math
import multiprocessing
import os
import sys
import time
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import git ... |
# Copyright 2019-, <NAME> and the QuantumFlow contributors
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
QuantumFlow: Gates specific to QASM
Qiskit has two names for each gate: the name of the class object (with a ... |
import numpy as np
import cv2
from homography import calcHomographyLinear, calcHomography, stitchPanorama, cylindericlMap
def DEBUG(*args):
if LVL >= 1:
print("[DEBUG]", *args)
class Model(object):
__slots__ = ('val', 'th', 'd', 'n')
def fit(self, X, Y):
raise NotImplementedError
de... |
from urllib.request import urlopen, HTTPError
import json
import pandas as pd
import random
import re
import time
from datetime import datetime
import logging
logging.basicConfig(filename='reddit_scraping.log', level=logging.INFO)
# collect posts from subreddits pertaining to the vaccine
# collect comments from t... |
"""
This program allows to run Omnirobot Gym Environment as a module
"""
import numpy as np
import cv2
import zmq
from gym import spaces
import torch as th
import matplotlib.pyplot as plt
import seaborn as sns
import yaml
from scipy.spatial.transform import Rotation as R
from environments.srl_env import SRLGymEnv
fro... |
# SPDX-License-Identifier: Apache-2.0
"""
Place holder for all ONNX operators.
"""
import sys
import numpy as np
from scipy.sparse.coo import coo_matrix
import onnx
from ..common.data_types import DataType
from ..common._topology import Variable
from .automation import get_rst_doc
def ClassFactory(class_name, op_nam... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... |
#
# Copyright 2019 The FATE Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from __future__ import annotations
import contextlib
import errno
import functools
import importlib.resources
import os.path
import shutil
import stat
import subprocess
import sys
import tempfile
from types import TracebackType
from typing import Any
from typing import Callable
from typing import Generator
from typing... |
import unittest, os, sys, shutil, tempfile
import numpy as np
import numpy.testing as nt
from astropy.io import fits
from copy import deepcopy
if __name__ == '__main__':
print('Run this instead:')
print('python setup.py test -m desispec.test.test_pixgroup')
sys.exit(1)
from ..test.util import get_frame_da... |
#!/usr/bin/env python
"""
Sign in MJ.NET and scrape today's result.
"""
from getpass import getpass
import sys
from scrapy import cmdline, Spider, FormRequest
from scrapy.linkextractors import LinkExtractor
from scrapy.shell import inspect_response
MJ_NET_URL = 'https://www.sega-mj.net/mjac_p'
MJ_NET_URL_SIGN_IN = f... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
#!/usr/bin/python
#------------------------------------------------------------
# IMPORTS
#------------------------------------------------------------
# External modules
import pygame
from pygame.locals import KMOD_ALT, K_F4, QUIT, KEYDOWN, KEYUP, Rect
from random import randint
import config
#---------... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from os.path import join, dirname
sys.path.insert(0, join(dirname(__file__), '../../../'))
import torch
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import os
import time
import random
import argparse
import numpy a... |
"""
Pygments-based highlighting lexers for DELPH-IN formats.
"""
import re
from pygments.lexer import RegexLexer, include, bygroups
from pygments.style import Style
from pygments.token import (
Text, Number, String,
Keyword, Name, Operator, Punctuation,
Comment, Error
)
__version__ = '1.0.0'
_tdl_break... |
import numpy as np
import sys
import do_mpc
from casadi import * # symbolic library CasADi
import datetime
import math
def xytri(t):
r = 1.0
T = 1
omga = 2 * math.pi / T
x = r * sin(omga * t)
y = r * cos(omga * t)
# print(x, y)
return x, y
model_type = 'continuous' # either 'discrete' or ... |
# Copyright 2021 ETH Zurich, Media Technology Center
#
# 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... |
from dataclasses import dataclass
from typing import List
import numpy as np
import streamlit as st
import altair as alt
from suzieq.gui.stlit.guiutils import gui_get_df, SuzieqMainPages
from suzieq.gui.stlit.pagecls import SqGuiPage
@dataclass
class StatusSessionState:
'''Session state for status page'''
p... |
class BlockInfo(object):
"""\brief Container class for describing a block to the outside world.
"""
def __init__(self, type, scheduling_type, gates, params_schema, params_example,\
variables, human_desc, short_desc, thread_exclusive=False):
"""\brief Initializes class
\para... |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from fairseq import utils
from fairseq.modules import (
LayerNorm,
PositionalEmbedding,
)
from .tiny_resnet import TinyResNet
from .oracle import SimulTransOracle
class PAController(nn.Module):
def __init__(self, args, src_di... |
# Functions to find blocks of free time given a
# list of events and some other parameters.
# Author: <NAME>
import arrow
def free(e_list, op_hr, op_min, c_hr, c_min, day_range, min_len):
"""
Return a list of free times as well as a list of busy times stripped
of all personal info, ready to upload to a d... |
import argparse
import os
import numpy as np
from scipy import misc
import imageio
import torch
import torch.nn as nn
import torch.nn.functional as F
import cv2
import json
from collections import OrderedDict
from skimage import img_as_ubyte
from data.cocostuff_loader import *
from data.vg import *
from model.plgan_25... |
from datetime import date
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.db import models
class UserResource(models.Model):
category_options = (
('user_manual', 'User Manual'),
('install_guide', 'Install ... |
# set the processing to GPU
# set CUDA_VISIBLE_DEVICES=1 & python BERT_QA_model.py
# ********** Phase 1: Import Libaries **********
import tensorflow as tf
import tensorflow_hub as hub
from official.nlp.data.squad_lib import generate_tf_record_from_json_file
from official.nlp.bert.input_pipeline import create_squad_... |
# 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
# d... |
import numpy as np
import torch as t
import torch.nn as nn
import torch.nn.functional as F
import models.utils.dist_adapter as dist
class BottleneckBlock(nn.Module):
def __init__(self, k_bins, emb_width, mu):
super().__init__()
self.k_bins = k_bins
self.emb_width = emb_width
self.mu... |
"""Parser for KSP save file"""
from collections import OrderedDict
import re
def parse_savefile(sfs, sfs_is_path=True):
"""Parses an SFS file
Params:
sfs: str; the path to the SFS file to read or a string containing data read from an sfs.
sfs_is_path (optional, default True): bool; whet... |
import numpy as np
import pytest
import scipy.sparse
from unittest.mock import Mock
from rasa.nlu import train
from rasa.nlu.classifiers import LABEL_RANKING_LENGTH
from rasa.nlu.config import RasaNLUModelConfig
from rasa.nlu.constants import (
TEXT_ATTRIBUTE,
SPARSE_FEATURE_NAMES,
DENSE_FEATURE_NAMES,
... |
from io import BufferedReader
import os
import pprint
from . import data_types
from . import read_utils
pp = pprint.PrettyPrinter(indent=4)
class SiaParseError(Exception):
pass
def read_header(sia_file: BufferedReader):
header = sia_file.read(4)
if header != b"SHSM":
raise SiaParseError("Expext... |
# (C) Datadog, Inc. 2010-2017
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
from urlparse import urljoin
import os
# 3rd party
import mock
import json
from tests.checks.common import AgentCheckTest, Fixtures
# IDs
CLUSTER_NAME = 'SparkCluster'
# Resource manager URI
RM_ADDRES... |
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.patches as patches
from scipy.stats import poisson
# from os import path
def prepare_dist(ax, curves, dist, xlimit=(0,100), title=None):
x = range(xlimit[1])
ax.set_xlim(xlimit)
for c in curves:
y = dist(x, c... |
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
import torch
import torch.nn.functional as F
import constants
def batch_get_occupied_idx(v, batch_id,
xmin=(0., 0., 0.),
xmax=(1., 1., 1.),
crop_size=.125, overlap=False):
if not torch.is_tensor(... |
from abc import ABC, abstractmethod
import os
import numpy as np
from .problem import Problem
class RE(Problem, ABC):
'''
Tanabe, Ryoji, and <NAME>. "An easy-to-use real-world multi-objective optimization problem suite." Applied Soft Computing (2020): 106078.
'''
n_var = None
n_obj = None
xl =... |
# coding: utf-8
# 沢山のインポート
import logging
import os
import sys
import json
import traceback
import datetime
import asyncio
import re
import pip
try:
import nextcord
from nextcord.ext import commands
from nextcord import Interaction
from util import n_fc
# from util import database
from cogs im... |
#!/usr/bin/python3
import os
import sys
from time import gmtime, strftime, localtime
from datetime import datetime, date, timedelta
import LitMimic as lm
import smtplib
import shutil
import time
import subprocess as sp
import shlex
import struct, fcntl
class TimeService:
DateTimeFormat = "%Y%m%d_%H-%M-%S"
def ... |
import math
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from .gcn import GCNEncoder, EdgePredictor
from .post_process import calc_point_squre_dist, pass_through_third_point
from .post_process import get_predicted_points, get_predicted_directional_points, pair_marking_points
from... |
import os
from os.path import join, basename, isfile
import uuid
import zipfile
import glob
import logging
import json
import csv
import time
import datetime
from subprocess import Popen
import matplotlib
matplotlib.use('Agg') # noqa
import matplotlib.pyplot as plt
import torch
from torch import optim
from torch.util... |
"""
desispec.io.xytraceset
======================
I/O routines for XYTraceSet objects
"""
import os.path
import time
import numpy as np
from astropy.io import fits
from ..xytraceset import XYTraceSet
from desiutil.log import get_logger
from .util import makepath
from . import iotime
def _traceset_from_image(wavemin... |
import dateutil.parser
import demistomock as demisto # noqa: F401
from CommonServerPython import * # noqa: F401
from typing import Any, Dict, Union, Optional, Tuple
DEMISTO_OCCURRED_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
DEMISTO_INFORMATIONAL = 0.5
ORCA_API_TIMEOUT = 30 # Increase timeout for ORCA API
ORCA_API_LIMIT = 500... |
# -*- coding: utf-8 -*-
from werkzeug.datastructures import FileStorage
from ifplus.restful.patched import fields
class Models(object):
"""Restful基本模型"""
def __init__(self, ns):
self.ns = ns
self.errno = ns.model(u'VFSErrno', {
u'errno': fields.Integer(title=u'错误码', description=u'... |
##########################################################################
#
# Copyright 2007-2019 by <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 witho... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.