text stringlengths 3.07k 22.1k |
|---|
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import sys, os
import time
import numpy as np
import random
import logging
import six
import cv2
import pickle
import gym
from .house... |
import numpy as np
import cv2
from skimage.measure import find_contours
import pycocotools.mask as maskUtils
def to_poly(rle):
mask = maskUtils.decode(rle)
padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)
padded_mask[1:-1, 1:-1] = mask
contours = find_contours(padded_mask... |
import collections
import logging
from functools import wraps
from http import HTTPStatus
from typing import List, Union
from flask import Blueprint
from flask import json, request, jsonify, Response
from openbrokerapi import errors
from openbrokerapi.response import (
BindResponse,
CatalogResponse,
Depro... |
# data analysis and wrangling
import os
import sys
import time
import multiprocessing
import tempfile
import pandas as pd
import numpy as np
import random as rnd
# machine learning
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import ... |
# ------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# -------------------------------------------------------------------... |
import argparse
import cv2
import numpy as np
def reprojection(uvs_A, depth_A, c2w_A, c2w_B, K, H, W):
n_uvs = uvs_A.shape[0]
us_A = uvs_A[:, 0]
vs_A = uvs_A[:, 1]
depths_A = depth_A[vs_A, us_A]
xyz_A_camera = (np.stack([us_A, vs_A, np.ones([n_uvs])], axis=1) * depths_A[:, None]) @ np.linalg.inv(... |
import json
import logging
import os
import sys
from argparse import Namespace
from pathlib import Path
from typing import List, Optional, Dict, Any
from electrumsv_sdk.constants import NameSpace
from electrumsv_sdk.sdk_types import SelectedComponent
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
class Par... |
#!/usr/bin/env python
import os
from datetime import datetime
import time
import tensorflow as tf
import re
# import select
# from IPython import embed
try:
# from models.read_util import data_producer as data_input
from models import resnet_con1d as resnet
# from models.read_util.tensorflow_input import... |
# Problem Name: River Sizes
# Problem Description:
# You are given a two-dimensional array (matrix) of potentially unequal height and width containing only 0s and 1s. Each 0 represents land, and each 1 represents part of a river. A river consists of any number of 1s that are either horizontally or vertically adjacent ... |
# MIT License
#
# Copyright (c) 2019 <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,... |
from keras.layers import Conv1D, MaxPooling1D, Activation, add, Dropout, Input
from keras.layers.normalization import BatchNormalization
from keras import initializers
from keras.engine import Layer, InputSpec
from keras.models import Model
#from keras.engine import input_layer
from keras import backend as K
from keras... |
"""
AssistedRateSpectest
"""
import collections
import datetime
import hashlib
import hmac
import json
import logging
import unittest
import uuid
import pytz
import requests
POSSIBLE_CURRENCIES = {'AUD', 'CAD', 'CHF', 'EUR', 'GBP', 'SEK', 'THB', 'USD'}
MIN_STAY_VIOLATION = 'MIN_STAY_VIOLATION'
TURNOVER_VIOLATION = '... |
import os
import discord
from discord.ext import tasks, commands
from dotenv import load_dotenv
import subprocess
import pyautogui
import time
import pandas as pd
import datetime
import requests
import json
import http.client
import asyncio
import csv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv... |
# Copyright (c) 2014, <NAME>. Please see the AUTHORS file for details.
# All rights reserved. Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.)
import sublime
import sublime_plugin
from collections import defaultdict
from datetime import datetime
from subprocess impo... |
# coding: utf8
# !/usr/env/python
"""terrainbento **BasicRt** model program.
Erosion model program using depth-dependent linear diffusion, soil production
by exponential weathering, stream power with spatially varying erodibility based
on two bedrock units, and discharge proportional to drainage area.
Landlab compone... |
import datetime
from app import db
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.ext.declarative import DeclarativeMeta
import json
class Server(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(35), nullable=False, unique=True)
port = db.Column(db.Stri... |
import torch
import torch.nn as nn
import numpy as np
import superp # parameters
import ann # generating model
import data # generating data
import loss # computing loss
import opt
import lrate
import prob
#################################################
# iterative training: the most important function
# it relies ... |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from download_epic import get_catalog
import os
import sys
from matplotlib.ticker import NullFormatter
def period2age(period, bv):
a, b, c, n = .4, .31, .4, .55
return (period / (a*(bv-c)**b) )**(1./n) * 1e-3
def get_EB... |
import os, sys, time, datetime
def get_run_sh(hdfs_env, hdfs_input, path_src, time_str, app_name, mem):
if time_str is None:
time_str = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
name_env = os.path.basename(hdfs_env)
name_input = os.path.basename(hdfs_input)
name_output = 'output_{}'.fo... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, stephen and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import throw, _
from frappe.utils import date_diff, add_days, flt, nowdate, getdate, cint
from frappe.model.document import Document... |
"""Create a conduit from the available information.
Can try to examine './.arcconfig' and '~/.arcrc' if not enough
information is provided.
"""
# =============================================================================
# CONTENTS
# -----------------------------------------------------------------------------
# p... |
from typing import List, Sequence
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.axes import Axes
from matplotlib.figure import Figure
from sklearn.metrics import roc_auc_score, roc_curve
from dfds_ds_toolbox.analysis.plotting_utils import (
_get_equally_grouped_data,
_... |
# coding=utf-8
# Copyright 2019 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
def gen_header(fHandler):
print("INORDER = ", file=fHandler)
for i in range(3072):
for j in range(8):
print("feat_%d_%d" % (i, j), file=fHandler)
print(";", file=fHandler)
print("", file=fHandler)
print("OUTORDER = ", file=fHandler)
for i in range(10):
print("decision_%d" % (i), file=fHandler)
print(... |
import threading
import tkinter as tk
from tkinter import *
from tkinter import ttk
import ipaddress
import automation.automation_core
class StartPage(tk.Frame):
"""
The application starts by asking you to provide your api key, checks it and set it to the AutomationCore Application
variable, and then r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 <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 the Software without restriction, including without limitation the ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# MNIST_tf_keras.py
# SciML-Bench
# Copyright © 2021 Scientific Machine Learning Research Group
# Scientific Computing Department, Rutherford Appleton Laboratory
# Science and Technology Facilities Council, UK.
# All rights reserved.
"""
Benchmark: MNIST_tf_keras
Clas... |
from typing import TypeVar
from kallikrein import Expectation, k, pending
from kallikrein.matchers import contain, equal
from kallikrein.matchers.tuple import tupled
from kallikrein.matchers.either import be_right
from kallikrein.matchers.match_with import match_with
from kallikrein.expectable import Expectable
from ... |
# ___________________________________________________________________________
#
# Prescient
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
# This software is ... |
import os
from tensorflow.keras.utils import get_file
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import ReLU
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Conv2DTranspose
from tensorflow.keras.layers impo... |
#
# Copyright 2021 Red Hat Inc.
# SPDX-License-Identifier: Apache-2.0
#
"""AWS Report Serializers."""
from django.utils.translation import ugettext as _
from pint.errors import UndefinedUnitError
from rest_framework import serializers
from api.report.serializers import FilterSerializer as BaseFilterSerializer
from api... |
'''
api.py
<NAME> and <NAME>, CS257 Carleton College, Professor <NAME>
Final Project 2021 Feburary
'''
import sys
import flask
import json
import config
import psycopg2
import calculate_effect
api = flask.Blueprint("api", __name__)
def get_db_connection():
''' return a connection object to the postgr... |
from django.core import mail
from django.test import TestCase, Client, override_settings
from .models import User, Post, Group
# Disable caching by using DummyCache
TEST_CACHE = {
'default': {
'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
}
}
class GeneralTest(TestCase):
def setUp(s... |
'''
Created on Sep 27, 2011
@author: sean
'''
from __future__ import print_function
from opencl import get_platforms, Context, Queue, Program, DeviceMemoryView, empty
from opencl import ContextProperties, global_memory, UserEvent, Event
from opencl.kernel import parse_args
import opencl as cl
import unittest
import c... |
import json
import time
from datetime import datetime
from FileSettings import WEATHER_FILE
from TimeOfDay import TimeOfDay
from WeatherJSON import WeatherEncoder
from WeatherShape import WeatherShape
from forecastiopy import *
from forecastiopy.FIOCurrently import FIOCurrently
from forecastiopy.FIODaily import FIODai... |
#!/usr/bin/env python3
def main():
peptide1 = list(input())
peptide2 = list(input())
graph = form_graph(peptide1, peptide2)
ford_bellman_search(graph)
path = form_peptide_path(graph)
peptide1_r, peptide2_r = path_peptides(peptide1, peptide2, path, graph)
print(-graph.v[graph.vi(graph.w -... |
import torch
import numpy as np
import argparse
import os
from dynaconf import settings
from datetime import datetime
from src.config import XLMRobertaConfig
from src.models import XLMRobertaClassificationModel
from src.preprocessing.multilabel.hatespeech.multilingual import JIGSAW_MULTILINGUAL_LABELS_TO_IDX
from src.... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import datetime
import hashlib
import logging
import time
from bisect import bisect_right
from collections import OrderedDict, defaultdict
fro... |
from typing import List, Tuple, Union
import numpy as np
import pytest
import torch
import torchtext
from ludwig.constants import LAST_HIDDEN, LOGITS
from ludwig.features.sequence_feature import SequenceInputFeature, SequenceOutputFeature
from ludwig.features.text_feature import _TextPreprocessing, TextInputFeature, ... |
#!/usr/bin/env python3
import os.path
import tensorflow as tf
import aug_helper
import warnings
from distutils.version import LooseVersion
import project_tests as tests
from moviepy.editor import VideoFileClip
import scipy.misc
import numpy as np
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= Loose... |
import matplotlib.pyplot as plt
import numpy as np
import os
from PIL import Image
os.makedirs("visual", exist_ok=True)
def show_mnist(n=20):
from tensorflow import keras
(x, y), _ = keras.datasets.mnist.load_data()
idx = np.random.randint(0, len(x), n)
x, y = x[idx], y[idx]
n_col = 5
n_row =... |
from pathlib import Path
import xml.etree.ElementTree as xmlet
import numpy as np
from astropy.io import fits
from utils import julday
import collections
def openP(path, name=None, path_to_xml=None, ms=None):
"""
Function to open a POEMAS file and return an `POEMAS` object.
Parameters
----------
p... |
import sys
import struct
import subprocess
from elftools.elf.elffile import ELFFile
from elftools.construct.lib.container import Container
from elftools.elf.enums import *
MAX_SIZE = (1024*1024*64)
from elftools.construct import (
UBInt32, Array, Struct
)
MIPS_RegInfo = Struct("MIPS_RegInfo",
UBInt32("r... |
from spending_manager import app, jwt, blocklisted
from spending_manager.models import User, Transaction, Account, TransactionType, Category
import spending_manager.utility as utility
from flask import jsonify, request, redirect, make_response
from flask_jwt_extended import get_jwt_identity, jwt_required
from datetime... |
#!/usr/bin/env python3
import os
import pickle
from torch.utils.data import Dataset
from torchvision import transforms
import numpy as np
import torch
from learn2learn.data.utils import download_file_from_google_drive, download_file
def download_pkl(google_drive_id, data_root, mode):
filename = 'mini-imagenet-... |
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
# 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.a... |
import datetime
import json
import logging
from urllib.parse import urlparse
import boto3
import readtime
from bs4 import BeautifulSoup
from django.conf import settings
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.core.files.stor... |
#!/usr/bin/env python3
# coding=utf-8
"""
Main executable for CREEPIEST framework
"""
import sys as sys
import os as os
import io as io
import logging as logging
import traceback as trb
import argparse as argp
import configparser as confp
import select as select
import datetime as dt
import random as rand
import cPro... |
from django.db.models import CharField, BooleanField, OneToOneField
from django.db.models import ManyToManyField, IntegerField, DateTimeField
from django.db.models import TimeField, FileField, Model, CASCADE, ForeignKey
from django_mysql.models import ListCharField
from django.contrib.auth.models import User
# from que... |
#!/usr/bin/env python
from __future__ import print_function # Python 2.7+ required
import os
import sys
import csv
import re
import argparse
from collections import Counter
try:
from humann import config
from humann.tools import util
except ImportError:
sys.exit("CRITICAL ERROR: Unable to find the HUMAnN... |
import argparse
import os
import random
import shutil
import time
import torch
import torch.nn as nn
import torch.optim
import torch.utils.data
import tensorboardX
from models.ERFNet import ERFNet, BoxERFNet
from models.ENet import ENet, BoxENet, BoxOnlyENet
model_names = ['ENet', 'BoxENet', 'BoxOnlyENet', 'ERFNet'... |
"""Interaction potentials."""
import math
import torch
from .pedped_1d import PedPedPotential, PedPedPotentialMLP
class PedPedPotential2D(torch.nn.Module):
"""Ped-ped interaction potential based on distance b and relative angle.
v0 is in m^2 / s^2.
sigma is in m.
"""
delta_t_step = PedPedPotent... |
# 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://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
import random
import p_types
import moves
import pokemon
def sortBySpeed(elm):
return elm['pokemon'].getSpeed()
def sortByPriority(elm):
return elm['move'].getPriority()
class Battle:
def __init__(self, battle_num, max_battles):
self.difficulty = battle_num/(max_battles+1)
s... |
#!/usr/bin/env python3
import copy
import json
import os
import subprocess
import sys
import time
import traceback
import pygraphviz as pgv
import requests
from colorama import Back, Fore, Style
import builder
import gen_test_api_plan as test_api
api_groups = test_api.parse(test_api.read_permission_matrix(
test... |
# -*- coding: utf-8 -*-
import calendar as cal
from datetime import date, datetime
import itertools
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from connect_calendar import Calendar
def get_calendar(year: int, month: int):
calendar_eu = cal.monthcalendar(year, month)
formatted = [0]+list(... |
import asyncio
import functools
import logging
import random
import typing as t
from asyncio import Lock
from functools import wraps
from weakref import WeakValueDictionary
from discord import Colour, Embed
from discord.ext import commands
from discord.ext.commands import CheckFailure, Command, Context
from bot.const... |
import math
import numpy as np
import torch
from torch import nn
class MultiheadAttention(nn.Module):
"""General purpose multihead attention implementation."""
def __init__(self, input_dim, proj_dim, n_heads=1, dropout=0.0,
attn_type='cross', initializer='xavier_uniform'):
assert pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from urllib import request
from obswebsocket import obsws, requests
import logger
import config
import event_manager
from string_util import replace_text, replace_value
import images
import threading
from time import sleep
SETTINGS = config.get_config()
ws = None
connec... |
# Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
import conf
import g
from grax.access_infer import Access_Infer
from grax.access_style import Access_Style
from grax.access_level import Access_Level
from grax.access_scope import Access_Scope
from gwis.exce... |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import os
import logging
import urllib
from ast import literal_eval as make_tuple
from calendar import month_name
from celery import shared_task
import requests
from django.c... |
#!/usr/bin/env python
"""
This is a working example of using a new PyTorch dataloading API called DataPipes
with Lhotse. It's not the final version and probably a lot of things will change.
Lhotse is a speech data representation library that brings various corpora into
a single format and interfaces well with PyTorch... |
# ==================================================================================================
# Copyright 2014 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... |
from datetime import datetime
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from App.Controllers.Functions.common impor... |
import numpy as np
import cv2 as cv
import random
from numpy.core.fromnumeric import resize
from PIL import Image
from skimage import data, exposure, filters
from skimage.util import noise, random_noise
from .func_line import *
def coin_toss(p=0.5):
pf = 1-p
ot, wt = [True, False], [p, pf]
res = random.... |
#!/usr/bin/env python3
"""
mDNS service browser for device identification
"""
import argparse
import logging
import time
import asyncio
from abc import ABC
from typing import cast, Optional, Union, Tuple, Set, List
from bitahoy_sdk.addon.scanner import NetworkScanner
from bitahoy_sdk.network_utils import IPv4
from ... |
from django.db import models
from contacts.models import Center, Contact, IndividualContactRoleZone, Zone
from schedulemaster.models import ProgramSchedule, ProgramMaster
import json
from config.models import Configuration, NotifyAuditModel
from django.core.exceptions import ValidationError
from smart_selects.db_fields... |
# pylint: disable-msg=C0111,C0103
import unittest
import mock
# pylint: disable-msg=F0401,E0611
from openmdao.main.api import Assembly, set_as_top
from openmdao.lib.components.api import MultiFiMetaModel
from openmdao.util.testutil import assert_rel_error
from openmdao.main.interfaces import implements, ISurrogate, ... |
"""
Support for STIB/MVIB information.
For more info on the API see :
https://opendata.stib-mivb.be/
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.XXX --> to do
"""
import asyncio
import logging
import datetime
import time
import voluptuous as vo... |
import types
try:
import keras
from keras.preprocessing import image as image_prep
except ImportError:
keras = None
from studio.util import logs
from PIL import Image
try:
from Queue import Full, Empty, Queue
except ImportError:
from queue import Full, Empty, Queue
from threading import Thread
i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys
import operator
import win32security
from winsys._compat import *
from winsys import core, exc, utils, accounts, constants
__all__ = ['x_ace', 'x_unknown_value', 'ACE_FLAG', 'ACE_TYPE', 'DACE_TYPE', 'SACE_TYPE', 'ACE', 'DACE',... |
import torch
import numpy as np
import logging
from copy import deepcopy
logger_py = logging.getLogger(__name__)
def sample_patch_points(batch_size, n_points, patch_size=1,
image_resolution=(128, 128),
sensor_size=np.array([[-1, 1],[-1, 1]]),
... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2009 by <NAME> <http://gustavonarea.net/>.
#
# This file is part of Booleano <http://code.gustavonarea.net/booleano/>.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to dea... |
# Copyright 2019 TerraPower, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
import numpy as np
def visit_row(r, visitor):
# print('visit_row ', r)
for c in range(9):
visitor(r, c)
def visit_col(c, visitor):
for r in range(9):
visitor(r, c)
def visit_box(rb, cb, visitor):
rb = rb*3
cb = cb*3
#print(r, rb)
#print(c, cb)
for rr in r... |
import numpy as np
import random
import copy
from collections import namedtuple, deque
from model import Actor, Critic
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e6) # replay buffer size
BATCH_SIZE = 512 # minibatch size
GAMMA = 0.99 # discount fact... |
from __future__ import print_function
from __future__ import absolute_import
#=======================================================================================================================
# Multilayer perceptron is given in a separate file since it is not available in the python version employed in
# the othe... |
import random
import util
from util import CacheError, ReplacementStrategy, WritePolicy
class Cache:
# capacity - size of the cache in bytes
# block_size - number of bytes in a block (mandatory a power of 2)
# associativity - directly mapped, fully associative or "K-WAY" (this format, where K is a numbe... |
"""Contains an APDU frame
Holds an APDU header and associated data.
APDUs encompass the following product types:
- (8) NOTAM-D, NOTAM-FDC, NOTAM-TFR, Unavail FIS-B Products
- (11) AIRMET
- (12) SIGMET, Convective SIGMET (WST)
- (13) SUA
- (14) G_AIRMET
- (15) CWA
- (16) NOTAM-TRA
- (17) NOTA... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import re
import os
import json
import heapq
import math
from collections import defaultdict
import networkx as nx
from networkx.readwrite import json_graph
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import igraph as ig
import pandas as pd
im... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------
# Khronos OpenGL CTS
# ------------------
#
# Copyright (c) 2017 The Khronos Group Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... |
"""
Experiment 1: swarm tec correlation
- for various background estimation sizes and artifact keys:
- collect random days
- get dtec prof
- interpolate swarm dne at the profile points
- estimate mean and covariance between the two
"""
import numpy as np
import pandas
from ttools im... |
import os
import cv2
import csv
import random
import pickle
import numpy as np
from glob import glob
from functools import reduce
from collections import defaultdict
def genHeatMap(w, h, cx, cy, r, mag):
"""
generate heat map of tracking badminton
param:
w: width of output heat map
h: height of o... |
from __future__ import print_function # future proof
import argparse
import sys
import os
import json
import re
import time
import pandas as pd
# pytorch
import torch
import torch.nn as nn
import torch.optim as optim
#import torch.utils.data
# torchtext
import torchtext
from torchtext.data import TabularDataset, Bu... |
from __future__ import print_function
import unittest
import numpy as np
from op_test import OpTest
from paddle.fluid.framework import default_main_program, Program, convert_np_dtype_to_dtype_, in_dygraph_mode
import paddle.fluid as fluid
import paddle.fluid.layers as layers
import paddle.fluid.core as core
from paddle... |
import Maxwell_Constants as glc
from Maxwell_Functions_Side import side1, side2, side3
################################################################################
### frame functions
################################################################################
def create_prof(f):
'''creates profile of n... |
import math
from datetime import timedelta
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin
from django.db.models import Max
from django.http import Http404, HttpRespo... |
import json
import pandas
import pandas as pd
import numpy as np
def generate_datatypes(data_df, columnOrder):
dataset_fields = data_df.columns.tolist()
dataset_types = []
dataset_typelist = []
labellist = []
# force d3mIndex to be returned first
dataset_typelist.append({'d3mIndex':'int64'})
... |
import torch
from torch import nn
import numpy as np
from torchvision.ops import nms
from mvt.cores.bbox.bbox_coders.box3d_coder import (
center_to_corner_box2d,
corner_to_standup_nd
)
from mvt.cores.bbox.bbox_transforms import limit_period_torch
def refine_detections(slice_box_preds, slice_cls_scores, slice_... |
#ATM.py
from graphics import *
from button import Button
class User:
def __init__(self, name, pin, checking, savings):
self.name = name
self.pin = pin
self.checking = float(checking)
self.savings = float(savings)
def setChecking(self, amount):
self.checking = amount
... |
# This file is part of PyOP2
#
# PyOP2 is Copyright (c) 2012, Imperial College London and
# others. Please see the AUTHORS file in the main source directory for
# a full list of copyright holders. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted ... |
"""
This code implements a probabilistic matrix factorization (PMF) per weeks 10 and 11 assignment of the machine learning module part of Columbia University Micromaster programme in AI.
Written using Python 3.7 and adjusted to ensure it runs on Vocareum.
Execute as follows:
$ python3 hw4_PMF.py ratings.csv
"""
fro... |
# coding:utf-8
# Copyright 2018 <NAME>
#
# 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... |
#!/usr/bin/env python
# This software is Copyright (c) 2018, <NAME> <ivan.freed at protonmail.com>
# and it is hereby released to the general public under the following terms:
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted.
#
# Tested with DiskCryptor 1.1.846.118 r... |
# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/custom-actions
from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.forms import FormValidationAction... |
import json
from dataclasses import dataclass
from typing import List, Optional, Set, Tuple, Union
from urllib.parse import urljoin
import aiohttp
from bs4 import BeautifulSoup, element
from . import consts
from .channel_config_handler import ChannelFileConfig
from .consts import logger
from .entities import Action, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pandagg.node import Object, Nested
from pandagg.node.mappings.abstract import Field, RegularField, ComplexField
from pandagg.exceptions import (
AbsentMappingFieldError,
InvalidOperationMappingFieldError,
)
from pandagg.tree._tree import Tree
def _mappings(... |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
import os
from numpy.testing import assert_allclose
import pytest
from jax import jit, random
import jax.numpy as jnp
import numpyro
import numpyro.distributions as dist
from numpyro.distributions.transforms import AffineTransform
f... |
import os, warnings, math
from functools import reduce
from PIL import Image
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
import rgpy.samplers
import rgpy.visualize
from rgpy.rbms import *
from rgpy.util import log_timer
from rgpy.standard import BlockRGTransform
default_psi_rbm = ... |
import unittest
import logging
import datetime
from nose.tools import raises
from mock import patch
import datman.fs_log_scraper as scraper
logging.disable(logging.CRITICAL)
class TestFSLog(unittest.TestCase):
fs_path = '/some/path/freesurfer/subject_id'
FS_date_format = '%a %b %d %X %Z %Y'
@patch('da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.