text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from bokeh.plotting import figure
from bokeh.palettes import Paired
from bokeh.models import Legend, NumeralTickFormatter
def get_attr_from_item(item, attr_name, deli, tp):
return tp(item[len(attr_name + deli):])
def print_usage(argv):
print('Usage... |
import tensorflow as tf
import numpy as np
import tensorflow as tf
import numpy as np
import os
def xavier_init(size):
in_dim = size[0]
xavier_stddev = 1. / tf.sqrt(in_dim / 2.)
return tf.random_normal(shape=size, stddev=xavier_stddev)
def sample_z(mu, log_var):
eps = tf.random_normal(shape=tf.sh... |
from typing import Tuple
import tensorflow as tf
from tensorflow.python.ops import gen_array_ops
def decode_png(filename: str, channels: int = 1):
"""
Read image from `filename` with `channels`.
Parameters
----------
filename : str
A filename to read.
channels : int, optional
... |
# Copyright (c) 2019, NVIDIA CORPORATION. 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 applic... |
from __future__ import print_function
# 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, Versio... |
"""
This script contains functions that
create data in the Neo4j database.
"""
import platform
from GraphOfDocs.utils import clear_screen
from GraphOfDocs.algos import *
# Initialize an empty set of edges.
edges = {}
# Initialize an empty list of unique terms.
# We are using a list to preserver order of ap... |
import random
from typing import Union
from uuid import UUID
from copy import deepcopy
from django.urls import reverse
from factory.fuzzy import FuzzyDate
from fdi.models import Investments, FinancialYear, SectorTeamTarget, MarketTarget
from fdi.tests.base import FdiBaseTestCase
from fdi.factories import InvestmentFa... |
import argparse
import os
from pathlib import Path
from glob import glob
from bidsonym.defacing_algorithms import (run_pydeface, run_mri_deface, run_mridefacer,
run_quickshear, run_deepdefacer, run_t2w_deface)
from bidsonym.utils import (check_outpath, copy_no_deid, check_meta_... |
# -*- coding: utf-8 -*-
import base64
import hashlib
import os
import struct
import sys
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from my_modules.getch import getch
def main():
"""メイン処理"""
argv = sys.argv
a... |
#!/usr/bin/env python3
import argparse
import datetime
import glob
import inspect
import json
import os
import pandas
import subprocess
import git_hashes
import codespeed_upload
def get_script_dir():
return os.path.dirname(inspect.getabsfile(get_script_dir))
SCRIPTDIR = get_script_dir()
REPO = os.path.join(SCRI... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Módulo 'writers' de pydatajson
Contiene los métodos para escribir
- diccionarios con metadatos de catálogos a formato JSON, así como
- listas de diccionarios ("tablas") en formato CSV o XLSX
"""
import io
import json
import logging
import os
import openpyxl as pyxl
im... |
#!/usr/bin/env python3
# Flask imports
from functools import wraps
import os
from flask import Flask, render_template, request, redirect, url_for, flash, \
jsonify
# sign in imports
from flask import session as login_session
import random
import string
# converts the info to real response to be send off to client... |
"""Opens the source file of Python modules in a program of choice."""
import sys
from argparse import ArgumentParser, Action
import os
import os.path
from abc import ABCMeta, abstractmethod
from collections.abc import Iterable # noqa: F401
from importlib import import_module
from contextlib import contextmanager, E... |
# -*- coding: utf-8 -*-
"""spacecraft.py
"""
import concurrent.futures
import datetime
import heliosat
import logging
import multiprocessing
import numpy as np
import os
import spiceypy
from .caching import cache_add_entry, cache_entry_exists, cache_generate_key, cache_get_entry
from .datafile import DataFile
from .... |
# -*- coding: utf-8 -*-
from blog.blogDB import get_db
def global_exception(origin_func):
def wrapper(self, *args, **kwargs):
try:
u = origin_func(self, *args, **kwargs)
return u
except Exception:
return '0'
return wrapper
class Manager:
def __init__(sel... |
# Spaces, comments and some functions have been removed from the original file to save memory
# Original source: https://github.com/adafruit/Adafruit_CircuitPython_BME680/blob/master/adafruit_bme680.py
import time
import math
from micropython import const
from ubinascii import hexlify as hex
try:
import struct
except... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This scripts contains pymc3 implementaiton of the ED-HMM and DU-RW models.
We used this funcitons for esitmating posterior distribution over
free model parameters, either from the behavioral or simulated data.
"""
from pymc3.distributions.timeseries import scan
from ... |
"""Copy records from the first KGTK file to the output file,
building one column (usually node2) from discrete subfields.
TODO: Need KgtkWriterOptions
"""
from argparse import _MutuallyExclusiveGroup, Namespace, SUPPRESS
from pathlib import Path
import sys
import typing
from kgtk.kgtkformat import KgtkFormat
from kg... |
# Training on non Augmented data only
# Works only on combination of eGEMAPS and MSF features. Can be altered if necessary
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'}
import sys
sys.path.insert(1, '../')
import json
import pandas as pd
import numpy as np
from sklearn import prepro... |
"""This module contains a class, Model, that represents the agent-based models.
It interfaces the C++ simulation code with the rest of the software application
which is in Python. """
from collections import OrderedDict
import numpy as np
from common.parameters import CORE_RADIUS, FIELD_SIZE, N_GLOBAL_STATS
from com... |
"""
pycraigslist.query.search
~~~~~~~~~~~~~~~~~~~~~~~~~
Gets and parses posts from a Craigslist query.
"""
import re
from pycraigslist.query import sessions
def fetch_posts(url, filters, **kwargs):
"""Yields every post from a Craigslist query as a dictionary with string values;
provided a URL and query fil... |
import threading
import multiprocessing
import collections
import itertools
from ..primitives import bundle
from ..primitives import chain
from .. import signals
from ..chainsend import eager_send
CPU_CONCURRENCY = multiprocessing.cpu_count()
class StoredFuture(object):
"""
Call stored for future execution... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class DQN(nn.Module):
def __init__(self, n_action_space):
super(DQN, self).__init__()
self.s1 = nn.Sequential(
nn.C... |
# dep
# amod - Match 790 out of 1012 with 0.7806324110671937
# > dobj - 0.8958904109589041 - 327/365
# > nmod - 1.0 - 8/8
# > pobj - 0.801007556675063 - 318/397
# > poss - 0.8333333333333334 - 5/6
# appos - Match 69 out of 133 with 0.518796992481203
# > conj - 0.9090909090909091 - 10/11
# > nmod - 1.0 - 4/4
# cc - Matc... |
import os
import json
import random
import datetime
from fubot_config import *
def calculate_frames_and_chunks(num_frames, split, minC, maxC):
f = int(num_frames * split)
c = int(f / maxC)
if f - (c * maxC) > minC:
c += 1
return f, c
def chunk_frames(num_frames, split_params):
#read para... |
# Copyright 2019 PerfKitBenchmarker 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... |
""" @package forcebalance.interaction Interaction energy fitting module.
@author <NAME>
@date 05/2012
"""
from __future__ import division
from builtins import str
from builtins import range
import os
import shutil
import numpy as np
from forcebalance.nifty import col, eqcgmx, flat, floatornan, fqcgmx, invert_svd, kb,... |
# The followings are the DenseNets module, the training was actually taken place in the `run_dense_net.py` file.
# Sorry, I really like Pycharm (and to be fair, Pytorch is so much an easier language to debug)
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2'
from models import DenseNet
from data_providers.utils import... |
from itertools import zip_longest
import itertools
import tensorflow as tf
from functools import reduce
from operator import mul
import numpy as np
import re
VERY_BIG_NUMBER = 1e30
VERY_SMALL_NUMBER = 1e-30
VERY_POSITIVE_NUMBER = VERY_BIG_NUMBER
VERY_NEGATIVE_NUMBER = -VERY_BIG_NUMBER
def add_summary_zero_fraction(t... |
'''
From <NAME> KDD 2019: "The dataset gives the occupancy rate (between 0 and 1) of 963 car lanes of San Francisco
bay area freeways. The measurements are sampled every 10 minutes fromJan. 1st 2008 to Mar. 30th 2009. This dataset
has been notably usedin [ 4] for classication tasks. We aggregate the data to 366 daily ... |
import copy
import logging
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import gui
from settings.config_objs.constants import NotSet
logger = logging.getLogger(__name__)
class AbstractConfigWidget:
def get_value(self):
raise NotImplementedError()
def set_value(self, value):
rai... |
# -*- coding: utf-8 -*-
"""
Create vertical grid in WRF using smooth stretching functions.
Authors
-------
<NAME> and <NAME>
- stretching functions
<NAME> and <NAME>
- plotting, testing
"""
import numpy as np
from scipy import integrate, interpolate
import os
import matplotlib.pyplot as plt
import xarray as... |
#!/usr/bin/env python3
"""This file contains useful functions that can be used elsewhere in yabt.
"""
import sys
import os
import gzip
import shutil
import json
import zipfile
import tarfile
import subprocess
def untar(tar_file, output_dir):
"""Untar a gzipped tar file to a given directory.
"""
tarfile_obj = t... |
from time import sleep
from typing import List, Union, Dict
from privex.loghelper import LogHelper
from tests.base import PrivexBaseCase
from privex.helpers import thread as modthread, LockConflict, random_str, OrderedDictObject
from privex.helpers.thread import BetterEvent, event_multi_wait_all, event_multi_wait_any... |
import cassiopeia.type.dto.common
import cassiopeia.type.core.common
if cassiopeia.type.dto.common.sqlalchemy_imported:
import sqlalchemy
import sqlalchemy.orm
@cassiopeia.type.core.common.inheritdocs
class PlayerStatsSummaryList(cassiopeia.type.dto.common.CassiopeiaDto):
"""
Args:
playerSta... |
from socket import error
import dtl.wrt.wrt_hdfs as sv
from bs4 import BeautifulSoup
from datetime import date
import datetime
from est.db.cur import con_cur
import pandas as pd
import requests
import proxyscrape
import subprocess
import re
class Error(Exception):
"""Base class for other exceptions"""
pass
cl... |
import numpy as np
from numpy.core.fromnumeric import shape
import scipy.io as scio
import torch
from typing import Union, Tuple, List
import path
def get_balanced_sub_idx(y, mask_train):
from collections import Counter
ytr = y[mask_train]
counter = Counter(ytr.tolist())
p = min(counter.val... |
"""--- Day 19: Go With The Flow ---"""
class Device():
def __init__(self, puzzle_input):
self.registers = [0 for _ in range(6)]
self.ip_register = int(puzzle_input[0].split()[1])
self.ip = self.registers[self.ip_register]
self.instructions = puzzle_input[1:]
self.cmds = {
... |
"""Controls digital outputs added with a 74HC595 shift register.
Description
-----------
A CircuitPython program that interfaces a 74HC595 serial-in parallel-out shift
register IC to add digital outputs to a CircuitPython compatible board.
Circuit
-------
- A 74HC595 shift register IC is connected to the board's SP... |
'''
Created on 1 mai 2021
@author: CNRA, arxit
'''
from __future__ import absolute_import
from builtins import object
import os.path
import xml.etree.ElementTree as ET
from qgis.PyQt.QtCore import QFile, QIODevice, QVariant
from qgis.core import *
from . import main
class GeometryType(object):
'''
Geometry ... |
# -*- coding: utf-8 -*-
# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules
# Copyright (C) 2020-2021, <NAME> <<EMAIL>>
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt
# for license details.
"""
"""
import pytest... |
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import sys
from random import sample, shuffle, random, randint
from math import floor, ceil
class Individual:
def __init__(self, problem = None):
if problem:
s = [sample(["0", "1"], 1)[0] for _ in range(problem.m)]
... |
"""Code for getting the data loaders."""
import numpy as np
import torch
import torchvision.datasets as dset
import torchvision.transforms as transforms
import os
import utils
from torch._utils import _accumulate
def get_loaders(args, mode='eval', dataset=None):
"""Get data loaders for required dataset."""
i... |
#The MIT License (MIT)
#Copyright (c) 2012 <NAME>, (chilimannen)
#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, mod... |
import argparse
import os
import os.path as osp
import torch
import mmcv
from mmaction.apis import init_recognizer
from mmcv.parallel import collate, scatter
from mmaction.datasets.pipelines import Compose
from mmaction.datasets import build_dataloader, build_dataset
from mmcv.parallel import MMDataParallel
import nump... |
"""
The implementation of Transformer encoder mainly follows to the following link:
https://github.com/Lsdefine/attention-is-all-you-need-keras
"""
import numpy as np
from keras import backend as K
from keras.callbacks import Callback
from keras.layers import Activation, Dense, Dropout, Conv1D
from keras.layers import ... |
import numpy as np
from netCDF4 import Dataset
import cm4twc
from tests.test_time import get_dummy_output_time_and_bounds
from tests.test_components.test_component import time_resolutions
# expected raw values for states/transfers/outputs after main run
# (null initial conditions, no spinup run, 12-day period)
exp_re... |
########################################
# MIT License
#
# Copyright (c) 2020 <NAME>
########################################
'''
Test the "parameters" module.
'''
from helpers import check_parameters, compare_with_numpy, rndm_gen
import json
import helpers
import minkit
import numpy as np
import os
import pytest
help... |
import matplotlib
matplotlib.use('Agg')
import os, sys
import yaml
from argparse import ArgumentParser
from tqdm import tqdm
import copy
import imageio
import numpy as np
from skimage.transform import resize
from skimage import img_as_ubyte
import torch
import torch.nn.functional as F
from modules.generator import Oc... |
import asyncio
import random
import logging
from dataclasses import dataclass
from datetime import timedelta, datetime, timezone
from typing import Optional, List, TYPE_CHECKING, Dict
from gif_pipeline.chat import Chat, Channel
from gif_pipeline.chat_config import ScheduleOrder
from gif_pipeline.helpers.helpers import... |
'''
<NAME>
3-5-19
Library for RN2903
This library can be used to send messages between two LoRa devices P2P style,
and to connect end devices to a LoRa gateway.
See README for more details.
command and command_response can send commands to the rn2903
command just sends the command
command_response send... |
from django.conf import settings
from django.template import defaultfilters
from django.utils.translation import gettext_lazy as _
from django.views.generic import ListView
from django_cradmin import javascriptregistry
from django_cradmin.viewhelpers import listbuilder
from django_cradmin.viewhelpers.mixins import Com... |
"""Read various spatial vector formats into a Spark DataFrame.
Basic usage
===========
Read the first layer from a file or files into a single Spark DataFrame:
Example:
>>> sdf = read_vector_files(
path="/path/to/files/",
suffix=".ext",
)
Filename pattern matching
=========================
... |
#!/usr/bin/env python3
import pandas as pd
import matplotlib
import mne
import argparse
from mne_bids import BIDSPath, read_raw_bids, get_entity_vals
from glob import glob
import os.path as op
from pathlib import Path
from mne.preprocessing.nirs import optical_density
from mne_nirs.preprocessing import peak_power, scal... |
#!/usr/bin/python
#
# Copyright (c) 2014,2016, <NAME>
"""Computes statistics from activity on Gerrit changes
To use the script, you need a to have an SSH key configured on the Gerrit
server. To get started, run the script with
gerrit-activity.py --all --legend
to see the types of statistics it can produce, and t... |
# Copyright (c) 2022 <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, copy, modify, merge, publish, distribute,... |
"""Test team module and included endpoints.
We won't mock any api calls just to make sure they haven't changed on us.
"""
from nbapy import team
team_id = "1610612738" # Celtics
player_id = "2544" # <NAME>
class TestList:
@staticmethod
def test_teams():
team_list = team.TeamList().teams()
... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from __future__ import print_function
import matplotlib.pyplot as plt
import matplotlib.colors as plt_colors
import numpy as np
import scipy.io
import scipy.stats
from rnmu.pme.line import Line
import rnmu.pme.stats as stats
def plot_soft_line(ax, line, sigma, box, n_levels=64, color='r', alpha=0.8):
x_min, x_max... |
import numbers
from sig_utils import *
src_folder = "./test/expressions/"
build_folder = "./test/expressions/"
eigen_types = ["matrix", "vector", "row_vector"]
test_code_template = """
TEST(ExpressionTest{overload}, {function_name}{signature_number}) {{
{matrix_argument_declarations}
auto res_mat = stan::math::{f... |
import json
import math
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def getDictRewards(dict):
return dict['reward']
def getDictPossRewards(dict):
return dict['reward_possible']+1
def getSideEffectScore(dict):
try:
sideEffectDict = dict['side_effects']
amount,total = sideEffectDict['... |
import os
import cv2
import math
import numpy as np
import pandas as pd
import csv
import time
import argparse
import json
from keras.models import Sequential
from keras.layers.convolutional import Convolution2D
from keras.layers.pooling import MaxPooling2D
from keras.layers import Dense, Dropout, Flatten, Lambda, Acti... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
"""
Word Definition:
Fiducial is (especially of a point or line) assumed as a fixed basis of comparison.
STN is Spatial Transformer Network
TPS is Thin... |
from alento_bot import StorageManager, cache_transformer
from eve_module.storage.eve_config import EVEConfig
from pathlib import Path
import logging
import typing
import yaml
import os
logger = logging.getLogger("main_bot")
class RegionData:
def __init__(self, path: str = None, state: dict = None, name: str = "... |
# coding=utf-8
"""
Copyright 2016 Load Impact
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 writi... |
import logging
import tempfile
from typing import Callable
from typing import Dict
from typing import List
from typing import Tuple
import numpy as np
from osgeo import gdal
from te_schemas.datafile import DataFile
from te_schemas.productivity import ProductivityMode
from te_schemas.results import Band
from . import ... |
# event/registry.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Provides managed registration services on behalf of :func:`.listen`
arguments.... |
import streamlit as st
import streamlit.components.v1 as stc
import pandas as pd
from file_utils import file_uploads, FileDownloader
import streamlit.components.v1 as components
import textwrap # SVG testing
import base64
from logger import logger
import os
## CUSTOM COMPONENTS
# https://docs.streamlit.io/en/stable... |
# -*- coding: utf-8 -*-
"""This module provides the *yfinance* compatible requests.
These requests are derived from the Yahoo base classes, but all classes provide
*yfinance.Ticker* compatible properties. So, some return a dict, some return
Pandas series and some return a Pandas dataframe, just like *yfinance* does.
"... |
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
import logging
from itertools import combinations
import multiprocessing
from typing import Dict, List, Optional, Tuple, Set
import gc
from tqdm import tqdm
from kapture_localization.utils.logging import getLogger
import kapture_localization.utils.path_t... |
"""Manages the imaging context. This take a string and returns a dictionary containing:
* Predict function
* Invert function
* image_iterator function
* vis_iterator function
"""
import logging
import numpy
from data_models.memory_data_models import Visibility, Image
from ..image.gather_scatter import image_sc... |
from loguru import logger
from kafka import KafkaProducer
import pydantic
import sys
import enum
from typing import List, Optional, Union, Dict, Callable, TypedDict, TextIO, Awaitable
from datetime import time, timedelta
from logging import Handler
class Message(str):
record: TypedDict
class Sinks(enum.Enum):
... |
#encoding: utf-8
import json, codecs, pickle, requests, os, sys
from clint.textui import progress
try:
#python 3
from queue import Queue
except ImportError:
#python2
from Queue import Queue
from threading import Thread
import os.path
from multiprocessing import Process
from multiprocessing import JoinableQueue
try... |
"""
This Module handles aspects of the agent architecture's decision-making and gameplay.
"""
# pylint: disable=import-error
import random
from ..RobotBehaviorList.RobotBehaviorList import RobotRoles
from ..RobotBehaviorList.RobotBehaviorList import RobotRolesBehaviorsMap
import numpy as np
import os
import pandas as p... |
import __builtin__
import contextlib
import imp
import mock
from testify import assert_equal
from testify import setup
from testify import setup_teardown
from testify import test_case
from testify import test_discovery
from testify import test_runner
from .test_runner_subdir.inheriting_class import InheritingClass
fro... |
import os, re, json
import sys, codecs
import datetime, time
from django.conf import settings
from django.core.files.storage import FileSystemStorage
from openrobots.openrobots_config import *
def add_parameters_in_file (in_file, output_file, parameters, file_id):
'''
Description:
The function will ge... |
# Copyright 2021 NREL
# 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
# distri... |
'''
*****************************************************************************************
*
* ===============================================
* Nirikshak Bot (NB) Theme (eYRC 2020-21)
* ===============================================
*
* This script is to implement Task 1B of N... |
# -*- coding: utf-8 -*-
# Função de decisão:
# Onde: w^T.x+b = w1.x1 +...+ wn.xn + b é o termo de polarização, é o vetor de peso das características.
# Interpretação do resultado:
# Se o resultado for positivo a classe será prevista como classe positiva (1) Caso contrário a classe será prevista como classe ... |
""" refer from https://github.com/zceng/LVCNet """
import torch
import torch.nn as nn
import torch.nn.functional as F
class KernelPredictor(torch.nn.Module):
''' Kernel predictor for the location-variable convolutions'''
def __init__(
self,
cond_channels,
conv_in_channels,
... |
import requests
import json
import time
import threading
from .marathonevents import *
from performance.driver.core.classes import Observer
from performance.driver.core.events import TickEvent, TeardownEvent, StartEvent
from performance.driver.core.reflection import subscribesToHint, publishesHint
from performance.dr... |
import torch
import torch.nn as nn
import numpy as np
from gns import graph_network
from torch_geometric.nn import radius_graph
from typing import Dict
class LearnedSimulator(nn.Module):
"""Learned simulator from https://arxiv.org/pdf/2002.09405.pdf."""
def __init__(
self,
particle_dimensions... |
import unittest
import numpy as np
from spherical_geometry import *
class TestSphereDistance(unittest.TestCase):
def test_same_start_and_end_have_zero_distance(self):
"""for a range of lats and longs test that identical start and end points map to zero distance"""
for lat1 in range(-90, 90, 5):
... |
# Made by VERBATIM
# IDs and Names:
# 21403007 <NAME>
# 21202377 <NAME>
# 21503756 <NAME>
"""
We have implemented a simple, specialized forward chaining (FC) to identify the animal(s) if all the required
information is given in advance, except the ones that program supposed to find by triggering and firing th... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
from functools import partial
from machinable import Mixin
import tensorflow as tf
from tensorflow.python.client import device_lib
from tensorflow.python.framework.ops import device
tf.compat.v1.disable_v2_behavior()
try:
from tensorflow.python import i... |
import pandas as pd
import numpy as np
from gym import spaces, Env
from typing import List, Optional, Tuple, Dict
from AdvisorClass import Advisor, SimpleAdvisor
import timeit
def scale(df,cols,scaling):
df[cols]/= scaling
return df
MAX_STEPS = 1400
WINDOW_SIZE = 65
INITIAL_FORTUNE = 10000
BID... |
"""
A suite of functions for manipulating 2d and 1d spectra.
"""
import scipy
from astropy.io import fits as pyfits
def resample1d(data,coeffs,axis,const=0.0,offset=0.):
"""
resample1d(data,coeffs,axis,const=0.0,offset=0.)
Resamples 2d spectra in x or y direction.
Inputs:
data - input data array
coeffs... |
from torch.nn import functional as F
from models.DLCT.utils import PositionWiseFeedForward
import torch
from torch import nn
from models.DLCT.attention import MultiHeadBoxAttention as MultiHeadAttention
from ..relative_embedding import BoxRelationalEmbedding, GridRelationalEmbedding, AllRelationalEmbedding
class Self... |
import anki_vector
from anki_vector.events import Events
import cv2 as cv
import numpy as np
import time
import math
# Constants
Debug = False
# milliseconds per main loop execution
MainLoopDelay = 20
HeadTilt = anki_vector.robot.MIN_HEAD_ANGLE + anki_vector.util.degrees(5.0)
LiftHeight = 0.0
class Camera:
FovH =... |
import cv2 as cv
import numpy as np
from skimage.measure import compare_ssim
####### 接口函数为is_continue()、continue_frames()、cut_clips() #######
def matches(current, next):
queryImage = current
trainingImage = next # 读取要匹配的灰度照片
sift = cv.xfeatures2d.SIFT_create() # 创建sift检测器
kp1, des1 = sift.de... |
import numpy as np
from scipy import optimize
__author__ = '<NAME> & <NAME>'
class NeuralNetwork(object):
"""A feedforward neural network that capable of regression or classification.
Requires Numpy to run and takes in ndarray inputs.
"""
# CONSTANTS
SUM_OF_SQUARES_TYPE = "Sum of Squares"
C... |
"""
Copyright 2018 Novartis Institutes for BioMedical Research Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... |
"""
usage: count_dim.py foo.snt bar.ptn
count M-scheme dimension
Author: <NAME>
Modified by: https://github.com/GaffaSnobb
"""
from functools import lru_cache
import sys, math, time, multiprocessing
from typing import TextIO, Tuple
def _readline_sk(
fp: TextIO,
) -> list:
"""
Skips lines starting with ... |
from Queue import Queue
from collections import defaultdict, deque
import time
import config
from isolation.indexes.GlobalLockIndex import GlobalLockIndex
from isolation.indexes.SidetrackQueryIndex import SidetrackQueryIndex
from policies.AbstractPolicy import AbstractPolicy
from queries.PredicateLock import NotSchedu... |
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publi... |
import os
import argparse
import numpy as np
import tensorflow as tf
from PIL import Image
from six.moves import cPickle as pickle
def gaussian_filter_(kernel_shape, ax):
x = np.zeros(kernel_shape, dtype = float)
mid = np.floor(kernel_shape[0] / 2.)
for kernel_idx in range(0, kernel_shape[2]):
fo... |
"""
Quintic Polynomials Planner
author: <NAME> (@Atsushi_twi)
Ref:
- [Local Path planning And Motion Control For Agv In Positioning](http://ieeexplore.ieee.org/document/637936/)
The MIT License (MIT)
Copyright (c) 2016 - 2021 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of ... |
"""
.. _the_cook:
The Cook
========
This game takes place in a typical house and consists in
finding the right food item and cooking it.
Here's the map of the house.
::
Bathroom
+
|
+
Bedroom +--+ Kitchen +----+ Backyard
... |
"""Validate router configuration variables."""
# Standard Library
import os
import re
from typing import Any, Dict, List, Tuple, Union, Optional
from pathlib import Path
from ipaddress import IPv4Address, IPv6Address
# Third Party
from pydantic import (
StrictInt,
StrictStr,
StrictBool,
PrivateAttr,
... |
import pandas as pd
import os
import torch
import argparse
import numpy as np
import json
import matplotlib.pyplot as plt
import torch.nn.functional as F
from utils import smooth
from utils import detect_with_thresholding
from utils import get_dataset, normalize, interpolate
from utils import mask_to_detections, load_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.