text stringlengths 3.07k 22.1k |
|---|
import numpy as np
from typing import Dict, List, Optional, Tuple
import torch
from torch import Tensor, nn
from detectron2.data.detection_utils import convert_image_to_rgb
from detectron2.modeling import Backbone
from detectron2.structures import Boxes, ImageList, Instances
from detectron2.utils.events import get_eve... |
#!/usr/bin/env python
# coding: utf8
#
# Copyright (c) 2021 Centre National d'Etudes Spatiales (CNES).
#
# This file is part of demcompare
# (see https://github.com/CNES/demcompare).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# ... |
""" Radio interferometric calibration using an expectation maximisation algorithm
See the SDP document "Model Partition Calibration View Packet"
In this code:
- A single model parition is taken to be a list composed of (skymodel, gaintable) tuples.
- The E step for a specific model partition is the sum of the parti... |
from distutils.core import Command, DistutilsFileError
import os
import plistlib
import stat
import subprocess
from cx_Freeze.common import normalize_to_list
__all__ = ["bdist_dmg", "bdist_mac"]
class bdist_dmg(Command):
description = "create a Mac DMG disk image containing the Mac " \
"application bund... |
import random
import subprocess
from functools import partial
import sys
import threading
from datetime import datetime, timedelta
from itertools import chain
from os import path
from time import sleep
from typing import Callable, Iterable, Union
from datetimerange import DateTimeRange
from loguru import logger
from s... |
import torch.nn as nn
import math
from transformers import BertModel
import torch
# from torchcrf import CRF
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn import LayerNorm
from .lsoftmax import LSoftmaxLinear as Lsoftmax
class Biobert_fc(nn.Module):
def c... |
# Copyright 2021 <NAME> <<EMAIL>>
# Author: <NAME> <<EMAIL>>
#
# 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... |
import numpy as _np
from openpnm.models import _doctxt
__all__ = [
"generic_hydraulic",
"hagen_poiseuille",
"hagen_poiseuille_power_law",
"valvatne_blunt",
]
@_doctxt
def generic_hydraulic(
target,
pore_viscosity='pore.viscosity',
throat_viscosity='throat.viscosity',
size_factors='th... |
#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2014-2020 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.ec... |
# diststats.py - Distance distribution descriptors
# -----------------------------------------------
# This file is a part of DeerLab. License is MIT (see LICENSE.md).
# Copyright(c) 2019-2021: <NAME>, <NAME> and other contributors.
import numpy as np
import warnings
import copy
from scipy.signal import find_p... |
import sys
sys.path.append("..")
from utils import utils, responses, decorators
from django.http import HttpResponse, HttpRequest
from django.views import View
from rest_framework.views import APIView # For swagger
from profileapp.models import Profile
from placeapp.models import Place
from pathapp.models import Path... |
# Import game state, action and player class, random module
Game2048State = __import__('2048_game').Game2048State
Game2048Action = __import__('2048_game').Game2048Action
Game2048Player = __import__('2048_game').Game2048Player
import random
import math
import numpy as np
import torch as tr
import pickle as pk
import mat... |
from transformers import BertTokenizer, BertModel
import torch
import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
plt.rcParams.update({'font.size': 30, 'legend.fontsize': 20})
plt.rc('font', size=25)
plt.rc('axes', titlesize=25)
import sys
sys.path.append(".... |
"""
Handling different type of returns (korteriomandid/kinnisasi)
"""
import asyncio
import logging
import os
from collections import defaultdict
import geopandas as gpd
import pandas as pd
import src.query as qry
import src.async_query as aq
import src.modification as mod
import src.constants as c
import src.datafra... |
#!/usr/bin/env python3
# Copyright (c) 2016-2017 Intel Corporation
#
# 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, cop... |
import glob
import os
import pickle
from typing import Union
import deepdish as dd
import numpy as np
import torch
from torch import Tensor
from torch_geometric.data import Data
from torch_geometric.data import InMemoryDataset
Array = Union[Tensor, np.ndarray]
def format_ggm_data(P: Array, adj: Array, marginalP: Ar... |
"""
Drivers for reading and writing a variety of formats and compression.
"""
import bz2
import logging
import gzip
import sys
import msgpack
import six
from gpsdio.base import BaseDriver as _BaseDriver
from gpsdio.base import BaseCompressionDriver as _BaseCompressionDriver
logger = logging.getLogger('gpsdio')
... |
import sys
import os
import json
def check_conflicts(a, b, key, scope):
a_set = set([x[key] for x in a])
b_set = set([x[key] for x in b])
conflicts = set.intersection(a_set, b_set)
for conflict in conflicts:
entries = [x for x in a if x[key] == conflict] + [x for x in b if x[key] == conflict]
... |
#!/usr/bin/env python3
import os
import random
import argparse
import requests
import urllib3
from urllib.parse import urlparse, urljoin
from bs4 import BeautifulSoup
headers = { 'user-agent' : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.190 Safari/537.... |
# Sub-functions for 1D heat transfer code
# __main__ will main_args a non-linear 1D heat transfer analysis
# <NAME>
# OFR Consultants
# 15/05/2019
# Conversion from DegC to DegK
import numpy as np
from matplotlib import pyplot as plt
def ISO834_ft(t):
# returns the ISO curve where t is [s]
tmin = t / 60
... |
import matplotlib as mpl
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import seaborn as sns
from src.utils import get_points_to_plot
# Standard colors for uniform plots
COLOR_SILVER = '#C0C0C0'
COLOR_SILVER_RGB = (192 / 255, 192 / 255, 192 / 255) + (0.2... |
import asyncio
from asyncio import create_task
from datetime import datetime, time, timedelta
from typing import List
import pytest
from pendulum import from_timestamp
from eascheduler.const import local_tz
from eascheduler.errors import FirstRunInThePastError
from eascheduler.executors import AsyncExecutor
from easc... |
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
# the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accom... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
def weights_init(m):
if isinstance(m, (nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(m.weight)
if m.bias is not None:
nn.init.constant_(m.bias, 0.0)
class Net(nn.Mo... |
from collections import defaultdict, Counter
from copy import deepcopy
from typing import Dict, List, Tuple, Optional
from omegaconf import OmegaConf
import numpy as np
import sys
from .._pixsfm import _keypoint_adjustment as ka
from .. import base, features, logger
from ..util.misc import to_ctr, to_optim_ctr
def f... |
import argparse
import logging
import os
import shutil
import threading
import time
from pathlib import Path
from typing import Callable, Optional, Dict
from uuid import UUID, uuid4
from antareslauncher.data_repo.data_repo_tinydb import DataRepoTinydb
from antareslauncher.main import MainParameters, run_with
from anta... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 18 10:02:01 2020
@brief: Control the state and speed of adiMotor
@description: Capture commands from the user, via GUI or
CLI, and translate them to serial command. Constants are
used to construct commands.
@author: <NAME>
@last-modified: 2020-11-09
"""
import logging
im... |
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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 us... |
from os import WEXITED
import torch
import sys
# import os
# sys.path.append(os.environ["HOME"]+"/vision/")
import torchvision # https://pytorch.org/vision/stable/models.html
from pathlib import Path
from torch.onnx import TrainingMode
import onnx
import argparse
import warnings
get_model={
# Semantic Segmentation... |
from time import time
from datetime import datetime
from pyrogram import Client, filters
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from config import BOT_USERNAME
START_TIME = datetime.utcnow()
START_TIME_ISO = START_TIME.replace(microsecond=0).isoformat()
TIME_DURATION_UNITS = (
... |
from SvgValidator import convertpng
import json
import re
import os
from urllib.parse import quote, unquote
from PyQt5 import QtCore, QtGui, QtSvg
from PyQt5.QtGui import QBrush, QColor, QPainter, QPen, QPixmap
from PyQt5.QtWidgets import QMainWindow, QWidget
from Common import BS, FLAGS, TR, maybeName
def _quote(s... |
# 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... |
# Copyright (c) 2020 fortiss GmbH
#
# Authors: <NAME>, <NAME>, <NAME> and
# <NAME>
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import logging
import os
from bark.core.world.agent import Agent
from bark.core.models.behavior import BehaviorStati... |
#! /usr/bin/env python
#
# Copyright (c) 2021 Arista Networks, Inc. All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.
#
# Tool to create backup of CVP.
# Modified to SCP or SFTP files off box
import argparse
from subprocess import call
import pexpect
from cryptography.fernet import Fernet
imp... |
# -*- coding: utf-8 -*-
###############################################################################
# This file is part of metalibm (https://github.com/kalray/metalibm)
###############################################################################
# MIT License
#
# Copyright (c) 2018 Kalray
#
# Permission is here... |
import director
import os
import sys
import argparse
import yaml
class DRCArgParser(object):
def __init__(self):
self._args = None
self._parser = None
self.strict = False
def getArgs(self):
if self._args is None:
self.parseArgs()
return self._args
def ... |
import numpy as np
from scipy.optimize import minimize
from scipy import optimize
# array operations
class OrthAE(object):
def __init__(self, views, latent_spaces, x = None, knob = 0):
# x: input, column-wise
# y: output, column-wise
# h: hidden layer
# views and late... |
from Optimizador.C3D import *
t = -1
e = -1
def getEncabezado():
content = "from goto import with_goto\n"
content += "from Instrucciones.TablaSimbolos.Tabla import Tabla\n"
content += "from Instrucciones.Sql_insert import insertTable\n"
content += "from Instrucciones.Sql_drop import DropTable,DropData... |
import os
import sys
import argparse
import pkg_resources
import yaml
import libcloud
import click
import click_spinner
from terminaltables import AsciiTable
from .manage import NodeManager
DEFAULT_LANG = 'en'
BASE_PATH = os.path.dirname(os.path.realpath(__file__))
CONTEXT_SETTINGS = {'help_option_names': ['-h', '--... |
"""Backend of ATM interface for xmlrpc
Key for codes used in communication functions:
pvc = pin_verify()
pkv = private_key_verify()
ilw = inner_layer_write()
bbb = check_balance()
www = withdraw()
"""
import logging
import struct
import serial
import ciphers
from random import randint
class Bank:
"""Interface ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import operator
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode # Python 2
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
from ... |
import nltk
from nltk.stem import PorterStemmer
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet as wn
import inflect
import pandas as pd
import json
import logging
"""
Receives csv of NL questions, and generates the 'store.js' ... |
# Type checkers don't like the wrapper names not existing.
# mypy: ignore-errors
# pytype: disable=module-attr
import errno
import resource
import sys
from typing import Any, ContextManager, Dict, Iterable, List, Optional, Tuple, Union, cast
import psutil
from . import _cache
__version__ = "0.2.0"
if sys.platform.s... |
from pycoin.block import Block
from pycoin.coins.bitcoin.ScriptTools import BitcoinScriptTools
from pycoin.coins.bitcoin.Tx import Tx
from pycoin.contrib.who_signed import WhoSigned
from pycoin.ecdsa.secp256k1 import secp256k1_generator
from pycoin.message.make_parser_and_packer import (
make_parser_and_packer, sta... |
from typing import Tuple, Optional
import torch
from torch import nn, Tensor
from datasets.deep_fashion import ICRBCrossPoseDataloader
from modules.discriminators.patch_gan import PatchGANDiscriminator
from modules.generators.unet import UNETWithSkipConnections
from utils.filesystems.local import LocalFolder, LocalCa... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import base64
import requests
# noinspection PyCompatibility
from requests.compat import str, bytes
from six import with_metaclass
from .aes_256_cbc import AES_256_CBC
from .keepass_http_credential import KeePassHTTPCredential
from .keepass_http_exceptions im... |
from coalib.bearlib.languages.LanguageDefinition import LanguageDefinition
from coalib.bears.LocalBear import LocalBear
from coalib.results.HiddenResult import HiddenResult
from coalib.results.Result import Result, RESULT_SEVERITY
from coalib.results.SourceRange import SourceRange
from coalib.results.AbsolutePosition i... |
#%%
CUDA_LAUNCH_BLOCKING="1"
import gc, sys, os
sys.path.append("..")
from tqdm import tqdm
from time import time
import pickle
import numpy as np
import pandas as pd
import datatable as dt
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
import torch
import torch.nn as ... |
'''
- parse BGP tables from http://bgp.potaroo.net/index-bgp.html
- plot and output the stats about prefix count & address space covered
- fetch covered address space and partition the space by prefix length
- output sorted list of prefixes:
prefix_int prefix_len cidr_network
16909060 32 1.2.3.4/32
Usage:
... |
import matplotlib.pyplot as plt
import nltk
import os
from collections import Counter
from itertools import product
from statistics import mean, mode, median
nltk.download('stopwords')
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from nltk.tokenize import TweetTokenizer, word_... |
# Copyright 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Manage tree status."""
from __future__ import print_function
import httplib
import json
import os
import re
import socket
import urllib
import urllib... |
import enum
from datetime import datetime
from geoalchemy2.types import Geometry
from app import db
class SessionType(enum.Enum):
mapped = 'MappedSession'
web = 'WebSession'
class MappedSession(db.Model):
id = db.Column(db.Integer, primary_key=True)
session_type = db.Column(db.Enum(SessionType), d... |
try:
import pygame, os, time
except:
print('cmd run: pip3 install pygame -i https://mirrors.aliyun.com/pypi/simple')
exit()
from pygame.locals import *
from game import Game
from ai import Ai
from config import *
# config = Development()
config = SupperFast()
FPS = config.FPS
SIZE = config.SIZE
DEBUG = co... |
from fontTools.cffLib import PrivateDict
from fontTools.cffLib.specializer import stringToProgram
from fontTools.misc.testTools import getXML, parseXML
from fontTools.misc.psCharStrings import (
T2CharString,
encodeFloat,
encodeFixed,
read_fixed1616,
read_realNumber,
)
from fontTools.pens.recordingP... |
""" letnet.py
Implementation of lenet5
Reference:
https://zhuanlan.zhihu.com/p/51714932
https://blog.csdn.net/qq_27825451/article/details/102457051
https://blog.csdn.net/weixin_41695564/article/details/80240106
https://geektutu.com/post/tensorflow-mnist-simplest.html
keras
https://blog... |
import os
import logging
import functools
from typing import Dict, List
from sqlalchemy import create_engine, inspect, Table
from sqlalchemy.schema import CreateSchema
from snowflake.sqlalchemy import URL, TIMESTAMP_NTZ
from snowflake.connector.errors import ProgrammingError
from snowflake.connector.network import Rea... |
import warnings
warnings.filterwarnings('ignore')
import argparse
import numpy as np
import pandas as pd
from src.data.load_data import read_params
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImpu... |
# Copyright 2014-present PlatformIO <<EMAIL>>
#
# 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... |
import numpy as np
def Elmt_Init():
NoElementDim = 2
NoElementNodes = 3
NoElementHistory = 0
ElementDofNames = ["UX", "UY"]
ElementMaterialNames = ["E", "nu"]
ElementPostNames = ["UX", "UY", "SigMises"]
return NoElementDim, NoElementNodes, ElementDofNames, NoElementHistory, ElementMaterial... |
# coding: utf-8
# In[1]:
exp_name = 'dpl_034a'
# In[2]:
import os
# In[3]:
import torch
import torch.nn as nn
import torchvision
from torch.autograd import Variable
from torch.nn import functional as F
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# In... |
# Copyright 2021 The TensorFlow 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... |
from ustruct import pack, unpack, unpack_from, pack_into
from micropython import const
from microbit import pin8, pin13, pin14, i2c, sleep
LEFT = 0 #: Left, either a left turn, or the left motor.
RIGHT = 1 #: Right, either a right turn, or the right motor.
BOTH = 2 #: Indicates both motors.
FORWARD = 1 #: Forward dire... |
# Load necessary libraries
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import re
import stanza
from nltk.corpus import stopwords
import argparse
stanza.download('sv', processors='tokenize,pos,lemma,depparse')
nlp = stanza.Pipeline(lang='sv', processors='tokenize,pos,lemma,depparse')
def def... |
import json
import os
import sys
from collections import OrderedDict
import numpy as np
import pip
from six.moves import input
from artemis.fileman.config_files import get_config_value
from artemis.config import get_artemis_config_value
from artemis.remote.utils import get_ssh_connection
def get_remote_installed_pac... |
"""
Copyright (c) 2022 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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writin... |
#!/usr/bin/env python
"""This module is not a part of the Estonian coreference system but an auxiliary module"""
"""It applies stratified cross validation for the selection of the most performat classifier to be used by the testing module"""
___author__ = "<NAME>"
__license__ = "LGPL"
__version__ = "1.0.0"
__maintai... |
#!/usr/bin/env python
#
# Copyright 2017 Bedag Informatik AG.
#
# 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... |
import os
import json
import cv2
import base64
import numpy as np
from flask import Flask, send_from_directory, request, Blueprint, url_for
from flask_restplus import Resource, Api, reqparse, fields
from matchvec.process import predict_class, predict_objects
from werkzeug.datastructures import FileStorage
from werkzeug... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
The class :class:`~.Showcase0` can be converted to various target formats as
can be seen in "main" of this file.
There are several examples:
.. literalinclude:: /../hwtLib/examples/showcase0.v
:language: verilog
:caption: Verilog Std IEEE 1364-2001
:linenos:... |
from collections import defaultdict
from helpers import memoize
from copy import deepcopy
from enum import Enum
import os
from math_utils import *
# Complex numbers in Python! == i + nj (x + ny), good for coordinates
# complex*+imaginary to rotate left/ccw, complex*-imaginary to rotate right/cw
# For example:
# Rotate... |
"""
Write various parts of a Chemkin mechanism file
"""
from chemkin_io.writer import reaction as writer_reac
from chemkin_io.writer import thermo as writer_therm
from chemkin_io.writer import _util as util
def write_chemkin_file(elem_tuple=None, spc_dct=None, spc_nasa7_dct=None,
rxn_param_dct... |
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
# cross entropy and center loss
class CrossEntropyDistill(torch.nn.Module):
"""Cross entropy loss with label smoothing regularizer.
Reference:
Szegedy et al. Rethinking the Inception Architecture for Comp... |
"""
Test Driven Learning Project.
Desenvolva TDD e programação com TDD e programação!
Módulo novice.
The MIT License (MIT)
Copyright (c) 2016 <NAME> <<EMAIL>>
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 ... |
# Copyright 2020-present Kensho Technologies, LLC.
"""Create different samples from stemmed/section filtered chunks."""
import json
import logging
import os
import re
from typing import Dict, List, Union
import pandas as pd
from wikiwhatsthis import argconfig
from wikiwhatsthis import patterns
logger = logging.getL... |
import importlib
import logging
import os
import sys
from django.core.management.base import BaseCommand, CommandError
from library.models import Work, WorkAlternativeTitle, WorkType
from .components import default_work_parser
# get logger
logger = logging.getLogger(__name__)
class WorkAlternativeTitleCreator:
... |
import os
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QVBoxLayout, QLabel, QGroupBox, QFormLayout, QLineEdit, \
QTextEdit, QWidget, QHBoxLayout
# import Config
class SimpleMessageDialog(QDialog):
def __init__(self, title="", message=""):... |
import os, hashlib, json, base64, random, time
# Print coloured debug messages if True
debug_messages = True
def debug(message, status='debug'):
if debug_messages:
colours = {
"grey": "\033[0;37m",
"yellow_bold": "\033[1;33m",
"red": "\033[0;31m",
"green": "\... |
"""
Usage:
python retail_data_gen.py create_product_catalog <l1-count> <l2-avg-count> <l3-avg-count>
python retail_data_gen.py create_product_catalog 12 20 90
python retail_data_gen.py create_stores 100
python retail_data_gen.py create_customers 10000
python retail_data_gen.py create_sales_data 202... |
# -*- coding: utf-8 -*-
'''
This is a modification of the SeparableConv2D code in Keras,
to perform just the Depthwise Convolution (1st step) of the
Depthwise Separable Convolution layer.
'''
from __future__ import absolute_import
from keras import backend as K
from keras import initializers
from keras import regular... |
# Copyright 2012 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 a... |
# Copyright 2021 Toyota Research Institute. All rights reserved.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
import torchvision.models as models
from .image import image_grid
def upsample(x):
"""Upsample input tensor by a factor... |
# This code is used to generate an analysis html for the results of the mturk batch of project -
# Explainable KBC (id=1365457).
# It requires the html book file (generated by @get_turk_data.py), and the results.csv downloaded from mturk.
# It then generates an analysis html file if all the HITs are valid, if Not it ge... |
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from matplotlib.gridspec import GridSpec
from matplotlib.ticker import FormatStrFormatter
mpl.rc('xtick', labelsize=14)
mpl.rc('ytick', labelsize=14)
mpl.rc('axes', labelsize=14)
mpl.rc('font', **{'family': 'Times New Roman', 'sans-se... |
#!/usr/bin/python
import re
import time # for time.sleep() . if not needed then remove
MESSAGE_TYPE = 'msgtype'
LF = '\n'
class MsgTicker(object):
MsgType = MESSAGE_TYPE
Agressor = 'Aggressor'
CurPair = 'CurPair'
Price = 'Price'
TxDate = 'TxDate'
TxTime ... |
from string import ascii_lowercase, digits
from random import randint
import sys
def set_grid(grid_size, numberofmines):
empty_grid = [[0 for i in range(grid_size)] for i in range(grid_size)]
global show
show = [[False for i in range(grid_size)] for i in range(grid_size)]
show_grid(empty_grid)
min... |
''' Non-simple compressible flow.
Calculate quasi-1D compressible flow properties with varying area, friction, and heat addition.
"One-dimensional compressible flows of calorically perfect gases in which only a single driving potential is
present are called simple flows" [1]. This module implements a numerical solutio... |
import sys
from os import path
from PyQt5.QtGui import *
from PyQt5 import QtWidgets, uic, QtGui
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from decimal import Decimal
def show_warning(message_text, informative_text):
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)... |
import torch
import numpy as np
import torch.backends.cudnn as cudnn
from tqdm import tqdm
from net.models import Xception_dilation, deeplabv3plus_en
from sklearn.metrics import accuracy_score
from apex import amp
from dataset.my_datasets import MyTestDataSet_seg
from torch.utils import data
import torch.nn.fu... |
# Copyright 2014 Rackspace
# 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 app... |
# -*- coding: utf-8 -*-
from io import BytesIO
from icemac.addressbook.interfaces import IKeywords
from mock import patch
import gocept.country.db
import icemac.addressbook.interfaces
import pytest
import zope.component
@pytest.fixture('function')
def example_data():
"""Construct an import file which contains err... |
import io
import os
import shutil
import sys
import time
import numpy as np
import tensorflow as tf
from .utils import flatten_percell_output
"""Utils function for vizualisation and logging"""
class Tee(object):
"""Tee object to log stdout to a file"""
def __init__(self, filename='log.txt'):
self.s... |
#!/usr/bin/env python
import os
os.environ['GEVENT_RESOLVER'] = "ares"
import gevent.monkey
gevent.monkey.patch_all()
import urlparse
import sys
import os
import logging as log
import bottle
from bottle import template, tob, ERROR_PAGE_TEMPLATE
try:
from pymongo import MongoClient
except ImportError:
Mon... |
import argparse
import logging
from time import sleep
import boto3
from botocore.exceptions import ClientError, EndpointConnectionError
logging.basicConfig(level=logging.INFO)
# exit code explanation:
# 2: security group not found
# 3: endpoint connection error
def parse_args():
parser = argparse.ArgumentParse... |
import numpy as np
import tensorflow as tf
from tensorflow.contrib import layers
from tensorflow.contrib import rnn
from tensorflow.python.ops.metrics_impl import metric_variable
# lstmnet:
# features dict:
# sequence_vals: [ BATCH_SIZE, SEQUENCE_LENGTH, INPUT_DIMENSION]
# Maybe later: Hin
# Maybe later: Context info... |
import socket
import logging
from six import iteritems, itervalues
from flask import render_template, request, json
from flask_cors import CORS
try:
import flask_login as login
except ImportError:
from flask.ext import login
from pyspider.libs import utils, sample_handler, dataurl, result_dump
from pyspider.... |
# from __future__ import division
import astf_path
from trex.astf.api import *
import yaml as yml
from pprint import pprint
import argparse
import sys
import trex.examples.astf.ndr_bench as ndr
# find NDR benchmark test
def ndr_benchmark_test(high_mult, low_mult, server='127.0.0.1', iteration_duration=20.00,
... |
import os
import pathlib
import argparse
import torch
from tqdm import tqdm
import numpy as np
from PIL import Image
from torchvision import transforms
from utils.util import psnr, get_divider_str, psnr_PIL
import logging
import matplotlib.pyplot as plt
import torch
from dataloader.datasets import SRDataset
from torch.... |
import random
import time
from copy import copy
from pm4py.algo.discovery.dfg.adapters.pandas import df_statistics
from pm4py.algo.filtering.pandas.attributes import attributes_filter
from pm4py.algo.filtering.pandas.end_activities import end_activities_filter
from pm4py.algo.filtering.pandas.start_activities import s... |
from enum import Enum
from typing import Protocol, Any, SupportsFloat, Dict, Sequence, Optional, List, TypeVar, Generic
from torch import Tensor
from torch.utils.data import Dataset
class CumulativeStatistic:
def __init__(self):
self.values_sum = 0.0
self.overall_count = 0.0
self.average ... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json
import seaborn as sns
from sklearn.preprocessing import LabelEncoder, StandardScaler, OneHotEncoder
import random, sys, os
import tensorflow as tf
import pickle
np.random.seed(13)
random.seed(22)
tf.set_random_seed(13)
cl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.