text stringlengths 3.07k 12.6k |
|---|
import numpy as np
import kmeans
import common
import naive_em
import em
toy_X = np.loadtxt("toy_data.txt")
def test_seeds(X, K):
print("\n############## KMEAN K=" + str(K) + " ###############")
mixture0, post0 = common.init(X,K,0)
mixture1, post1 = common.init(X,K,1)
mixture2, post2 = common.init(X,K,2)
mixtur... |
import torch
import numpy as np
import transforms3d
def compute_rotation_matrix_from_ortho6d(poses):
"""
Code from https://github.com/papagina/RotationContinuity
On the Continuity of Rotation Representations in Neural Networks
Zhou et al. CVPR19
https://zhouyisjtu.github.io/project_rotation/rotati... |
"""
conftest.py
Global PyTest fixtures
"""
import pytest
import json
import datetime
@pytest.fixture
def hl7_message():
return "\r".join(
[
"MSH|^~\\&|SE050|050|PACS|050|20120912011230||ADT^A01|102|T|2.6|||AL|NE|764|||||||"
+ "^fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:2A57:3C28^IPv... |
import pandas as pd
from .utils.constants import stats_counts, shooting_counts
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances
def transform_column(one_stats: pd.Series) -> pd.Series:
mean = one_stats.mean()
std = one_stats.std()
transformed = (one_stats - me... |
#!/usr/bin/python3
import logging as log
import os
import random
import re
import time
from signal import SIGTERM
import irc.bot
import requests
from api.decorator import retry_on_fail, threaded
from api.servicemanager import EntryTranslatorServiceManager
log.basicConfig(
filename='/opt/botjagwar/user_data/wikti... |
#!/usr/bin/env python3
"""
Telsis language translator
GUI using PySimpleGUI
Copyright (c) 2021 <NAME>
"""
import os
import sys
import io
try:
import PySimpleGUI as sg
except ImportError as e:
print("PySimeplGUI is needed to run the GUI.")
sys.exit(1)
from languages import *
USER_FONT_SIZE = 24
UI_FONT... |
import aerosandbox.numpy as np
def critical_mach(fineness_ratio_nose: float) -> float:
"""
Returns the transonic critical Mach number for a streamlined fuselage.
Fitted to data from Raymer "Aircraft Design: A Conceptual Approach" 2nd Ed., Fig. 12.28.
See figure + study + fit in: /studies/FuselageCriti... |
#! /d/python3/python
import argparse
import struct
import time
import pygame
import distutils.util
import sys
import os
from PyNTR.PyNTR import PyNTR
class InputState:
def __init__(self, client):
self.client = client
def update(self):
base = 0x10000000
combined_state = self.client.ReadU64(base + 0x1C)
[
... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright (c) 2016 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright... |
# Copyright 2018 Twilio, 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 agreed to in writing, ... |
#!/usr/bin/env python
# coding: utf-8
# # Model Specification
# This example solve a standard AR(1) process but with multiple noise measurements. If there are many parameters, we need more data for proper estimation.
# In[11]:
import numpy as np
import pandas as pd
import linkalman
import scipy
from linkalman.mode... |
# Copyright 2020 <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, subl... |
import os
import pandas as pd
from sqlalchemy import and_, func
from flask_apispec import MethodResource, doc, marshal_with, use_kwargs as use_kwargs_doc
from flask_restful import abort
from flask import Response, jsonify
from webargs import fields, validate
from webargs.flaskparser import use_kwargs
from flask_bcrypt ... |
#! /usr/bin/env python
import numpy as np
import cv2
import scipy.io
def modcrop(im, modulo):
sz = im.shape
h = int(sz[0]/modulo)*modulo
w = int(sz[1]/modulo)*modulo
ims = im[0:h, 0:w, ...]
return ims
def imresize(im_l, s):
if s<1:
im_l = cv2.GaussianBlur(im_l, (7,7), 0.5)
im_h =... |
import asyncio
import concurrent.futures
import functools
import logging
import subprocess
import time
import janus
import rospy
from async_generator import asynccontextmanager
logger = logging.getLogger(__name__)
def cancel_on_shutdown(task):
loop = asyncio.get_event_loop()
rospy.on_shutdown(lambda: loop.c... |
"""
Example demonstrating how to do the key rotation on the ledger.
Steward already exists on the ledger and its DID/Verkey are obtained using seed.
Trust Anchor's DID/Verkey pair is generated and stored into wallet.
Stewards builds NYM request in order to add Trust Anchor to the ledger.
Once NYM transaction is done, T... |
#!/usr/bin/env python3
from urllib.request import urlopen, Request
from dotenv import load_dotenv
from pathlib import Path
from datetime import datetime
import urllib, json, os, traceback, discord, sys, re, subprocess, requests, io
# sc_precision is the number of hastings per siacoin
sc_precision = 10 ** 24
CHANNEL... |
from __future__ import print_function
import argparse
import logging
import os
import warnings
import numpy as np
import torch.utils.data
from torch import optim
from torch.utils.data import SubsetRandomSampler
from torch.utils.tensorboard import SummaryWriter
from Colorization import utils
from Colorization.dataset... |
import unittest
import zserio
from testutils import getZserioApi
def _convertRgbToCmyk(rgb):
# see https://www.rapidtables.com/convert/color/rgb-to-cmyk.html
rr = rgb[0] / 255. * 100
gg = rgb[1] / 255. * 100
bb = rgb[2] / 255. * 100
k = 100. - max(rr, gg, bb)
c = round((100. - rr - k) / (100... |
"""
Module with functions for handling input and working with convergence and partial sum.
"""
from stack import Stack
from sympy import *
from funcs import add, subtract, multiply, divide, floor_divide, modulus, exponent
from sympy.parsing.sympy_parser import parse_expr
operators = {'+': (1, add), '-': (1, subtract),... |
from __future__ import annotations
import enum
from typing import Callable, Generic, Optional, TypeVar, Union
import joblib
import numpy as np
import sklearn.cluster
from sklearn.base import BaseEstimator, ClusterMixin
from typing_extensions import Literal
from ...misc.metrics import PRECOMPUTED, Metric, PairwiseMet... |
import pandas as pd
import os
import sys
sys.path.append('..')
from subprocess import getstatusoutput
import pandas as pd
from gpu import config
class DataBase(object):
""" An abstract class for datasets.
"""
def __init__(self, file, reset=False):
self.name = 'None'
self.file = file
self.columns = []
de... |
#!/usr/bin/env python
# pylint: disable=C0116
# This program is dedicated to the public domain under the CC0 license.
import logging
from typing import Dict
import phonenumbers
from telegram import ReplyKeyboardMarkup, Update, ReplyKeyboardRemove
from telegram.ext import (
Updater,
CommandHandler,
Message... |
from os import getpid
from logging import getLogger
from .utils import func_logger, format_hctl, ScsiCommandFailed
from .scsi import scsi_host_scan, scsi_add_single_device, remove_device_via_sysfs
from .scsi import do_report_luns, do_standard_inquiry, do_test_unit_ready, execute_modprobe_sg
from .getters import get_scs... |
import os
import glob
import numpy as np
__all__ = ['LinearResponse','ThirdOrderResponse','DensityMatrix','SpectralDensity']
class DensityMatrix(object):
"""
class for mqds density matrix data
"""
def __init__(self, method):
"""
takes reduced density matrix method as input
e.g.... |
import numpy as np
import pytest
# import pandas as pd # uncomment when the tests loading dl2_file are written
from lstchain.mc import (
read_sim_par,
calculate_sensitivity,
calculate_sensitivity_lima,
calculate_sensitivity_lima_ebin,
bin_definition,
ring_containment,
)
from lstchain.tests.test... |
import re
from typing import Tuple, Literal, Optional
from dataclasses import dataclass
from functools import partial
import parse
import ast
from . import utilities
TOKEN = re.compile(r"\{\{(.*?)\}\}")
class GeneratorError(Exception):
def __init__(self, file, *args, **kwargs):
super().__init__(*args, *... |
import pickle
import numpy as np
# Needs to be set after preprocessing
unigram_stats = None
emojis_dict = None
'''
Loads processed lexicons of training tweets
@return
list of tweet ids
list of training tweets
lsit of training targets
'''
def load_training_lexicons(scale=False):
wi... |
import sys
import warnings
if not sys.warnoptions:
warnings.simplefilter('ignore')
import numpy as np
import random
from ._utils import _softmax_class
from sklearn import metrics, datasets
from sklearn.naive_bayes import MultinomialNB
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.... |
# *- coding: utf-8 -*-
# pylint: disable=locally-disabled, bad-continuation
# pylint: disable=wildcard-import, unused-import, unused-wildcard-import
# pylint: disable=superfluous-parens, redefined-builtin
""" Project automation for Invoke.
"""
import os
import sys
import time
import shlex
import shutil
import signal
i... |
import copy
import random
from abc import ABCMeta
import pandas as pd
import numpy as np
from joblib import Parallel, delayed
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
from marmot.single_model import (PLSRCV, DartRegCV, ElasticNetCV, GBTRegCV,
... |
#!/usr/bin/python3
"""
Control loop pole placement library.
This library will grow to support many different pole placement methods.
Currently it only supports direct pole placement.
"""
__author__ = '<NAME> (<EMAIL>)'
import numpy
import scipy.linalg
import scipy.signal
import glog
class Error(Exception):
"""... |
"""Helper utils for export HybridBlock to symbols."""
from __future__ import absolute_import
import copy
import mxnet as mx
from mxnet.base import MXNetError
from mxnet.gluon import HybridBlock
from mxnet.gluon import nn
class _DefaultPreprocess(HybridBlock):
"""Default preprocess block used by GluonCV.
The ... |
# test__nosql_database.py
# Copyright 2019 <NAME>
# Licence: See LICENCE (BSD licence)
"""_nosql _database tests
Open and close a database on a file, not in memory.
"""
import unittest
import os
from ast import literal_eval
try:
import unqlite
except ImportError: # Not ModuleNotFoundError for Pythons earlier ... |
# Copyright (c) OpenMMLab. All rights reserved.
# Adapted from https://github.com/facebookresearch/pycls/blob/f8cd962737e33ce9e19b3083a33551da95c2d9c0/pycls/core/net.py # noqa: E501
# Original licence: Copyright (c) 2019 Facebook, Inc under the Apache License 2.0 # noqa: E501
import itertools
import logging
from typ... |
import errno
import http.server
import os
import ruamel.yaml as yaml
import shutil
from collections import abc
from jinja2 import Template
from pkg_resources import iter_entry_points, resource_stream
from ruamel.yaml.util import load_yaml_guess_indent
from . import git_utils
from . import mkdocs
from . import server
f... |
"""
Tests for the NURBS-Python package
Released under The MIT License. See LICENSE file for details.
Copyright (c) 2018 <NAME>
Tests geomdl.linalg module. Requires "pytest" to run.
"""
import pytest
from geomdl import linalg
GEOMDL_DELTA = 10e-6
def test_linspace():
start = 5
stop = 11
... |
# -*- coding: utf-8 -*-
"""
Align ramayana text with audio
Text source: https://github.com/vvasuki/purANam/tree/master/content/rAmAyaNam/AndhrapAThaH
Audio: https://archive.org/details/Ramayana-recitation-Sriram-harisItArAmamUrti-Ghanapaati-v2/
@author: <NAME>
"""
import os
import time
import re
import sys
import cs... |
"""
Copyright (c) 2016 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Apache License, Version 2.0 (the "License").
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
The code, technical concepts, and all information contained herein, are the property... |
from hashlib import md5
import math
import random
import re
import numpy as np
import pandas as pd
def _pprint(params):
"""prints object state in stable manner"""
params_list = list()
line_sep = ','
for i, (k, v) in enumerate(sorted(params.iteritems())):
if type(v) is float:
# use... |
"""
Create DL3 FITS file from given data DL2 file,
selection cuts and/or IRF FITS files.
Change the selection parameters as need be using the aliases.
The default values are written in the EventSelector and DL3FixedCuts Component
and also given in some example configs in docs/examples/
To use a separate config file f... |
"""Tests for stack-analyses, component-analyses, submit-feedback API via 3scale."""
import requests
import os
import time
from behave import when, then, given
from urllib.parse import urljoin
from src.parsing import parse_token_clause
from src.stack_analysis_common import contains_alternate_node
def threescale_previ... |
from __future__ import absolute_import, print_function, division
import sys
import numpy as np
import tensorflow as tf
# noinspection PyClassHasNoInit
import boml
Meta_Init_Method = ["MAML", "FOMAML", "WarpGrad", "MT-net"]
Meta_Init_Method = ["Reverse", "Truncated", "DARTS", "BA", "Implicit"]
METHOD_COLLECTIONS = [... |
"""
MIT License
Copyright (c) 2017 <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, distri... |
from functools import lru_cache
import json
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from django.utils import timezone
from guardian.utils import get_anonymous_user
from reversion import revisions
from _1327.documents.forms import A... |
from __future__ import absolute_import
from pyramid import httpexceptions
from pyramid.response import Response
from libweasyl.models.content import Submission
from libweasyl.text import slug_for
from weasyl import (
character, define, journal, macro, media, profile, searchtag, submission)
from weasyl.error impor... |
import argparse
import sys
import numpy as np
import pandas as pd
# my stuff
sys.path.append('src/')
import LoadTxt
import SourceParsers as sp
import SeferSort as ss
import SeferNames
from SectionNames import klalim, simanim, sifim
def build_mafteach(text):
""" Builds a Mafteach based on the given hebrew text.
... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
import itertools
import re
from collections import defaultdict, namedtuple
from dataclasses import dataclass
from itertools import product
from math import prod
from typing import List, Dict, Any, Tuple
import aocd
from . import aoc_year
from loguru import logger
aoc_day = 8
@dataclass
class AOCContext:
raw: Lis... |
# ===============================================================================
# Copyright 2013 <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/... |
"""
Modules performing small, commonly used tasks throughout the package.
"""
import numpy as np
from astropy.utils.misc import NumpyRNGContext
from ..custom_exceptions import HalotoolsError
__all__ = ('custom_len', 'find_idx_nearest_val', 'randomly_downsample_data',
'array_is_monotonic', 'unsorting_indic... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Set of functions to guide the dataloading process, and to clean up dataset.py.
Created on Wed 1 Oct, 2020.
Adapted from Jupyter notebook style (Colab).
@author: calmac
"""
# Standard packages for reading/processing data
import numpy as np
from numpy.random import ... |
import os
import re
import csv
from openmdao.api import CaseReader
from tabulate import tabulate
from whatsopt.logging import log, error
def load_from_csv(filename):
name = os.path.splitext(os.path.basename(filename))[0]
m = re.match(r"\w+__(\w+)", name)
if m:
name = m.group(1)
with open(file... |
# Copyright 2021 IBM 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 wri... |
#
# This source file is part of the EdgeDB open source project.
#
# Copyright 2008-present MagicStack Inc. and the EdgeDB 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... |
from tkinter import *
import time, threading, config
def popwindow(dic):
root = Tk()
screen_width = root.winfo_screenmmwidth()
screen_height = root.winfo_screenheight() #获取当前显示器分辨率
root.overrideredirect(True)
root.wm_attributes('-topmost',1) #置顶
root.attributes('-alpha',0.8)
root_width,... |
"""Setup an API."""
from typing import List, Any
from datetime import datetime, timedelta
from uuid import UUID
from math import sqrt
import logging
from fastapi import Depends, FastAPI, HTTPException
from starlette.middleware.cors import CORSMiddleware
from bson import ObjectId
from wirvsvirus import db, models, au... |
"""
web.py
Contains functions for interacting with web services.
Created by:
- <NAME> <https://github.com/neersighted>
Maintainer:
- <NAME> <https://github.com/lukeroge>
License:
GPL v3
"""
import json
import asyncio
import requests
# Constants
DEFAULT_SHORTENER = 'is.gd'
DEFAULT_PASTEBIN = 'snoonet... |
#!/usr/bin/env python
# <NAME> (<EMAIL>)
# Tue Jun 15 22:10:57 EDT 2021
if __name__ == '__main__':
from misc.timer import Timer
tt = Timer(f'start {__file__}')
#import sys, os.path, os, glob
import xarray as xr, numpy as np, pandas as pd
from numba import njit,guvectorize
from scipy.stats import t as stu
#impor... |
import pygame as p
from chess_engine import GameState, Move
import smart_move_engine
WIDTH = HEIGHT = 512
DIMENSION = 8
SQ_SIZE = HEIGHT // DIMENSION
MAX_FPS = 15
IMAGES = {}
p.display.set_caption('Chess')
'''
Init a global dict images.
'''
def loadImages():
pieces = ['wp', 'wR', 'wN', 'wB'... |
#!/usr/bin/env python3
import argparse
import json
import os
import sys
import yaml
import lxml.etree as ET
DATA_HOME = 'data/ts_output/'
XML_OUT = 'edition'
HTML_OUT = 'docs'
OFFSETS = { 'v01': 176, 'v02': 6, 'v03': 10, 'v04': 27,
'v05': 18, 'v06': 30, 'v07': 16, 'v08': 16,
... |
import random
import sys
from PyQt5.QtWidgets import QApplication
from client.Game import Game
from multiprocessing import Queue, Process
from client.TournamentWinner import DisplayWinner
def _start_tournament_(player1_id: str, player1_spacecraft: str,
player2_id: str, player2_spacecraft: st... |
import cv2
import torch.hub
import os
import model
from PIL import Image
from torchvision import transforms
from grad_cam import BackPropagation
import time
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import threading
import vlc
from os.path import dirname, join
current_dir = dirname(__file__)
#... |
from collections import OrderedDict
import numpy as np
# import torch
# import torch.optim as optim
from torch import nn as nn
from typing import Iterable
from torch.optim.optimizer import Optimizer
import rlkit.torch.pytorch_util as ptu
from rlkit.core.eval_util import create_stats_ordered_dict
from rlkit.torch.tor... |
import os
from tqdm import tqdm
import numpy as np
import pandas as pd
from random import sample, randint
import torch
import torch.nn as nn
from torchvision import datasets, transforms
from torch.utils.data import DataLoader, Dataset
import _init_paths
from mylib.voxel_transform import rotation
def square(d):
... |
import torch
from torch import nn
from curLine_file import curLine
def seq_max_pool(x):
"""
seq是[None, seq_len, s_size]的格式,
mask是[None, seq_len, 1]的格式,先除去mask部分,
然后再做maxpooling。
"""
seq, mask = x
seq = seq - (1 - mask) * 1e10
return torch.max(seq, 1)
def seq_mean_pool(x):
"""
... |
import numpy as np
import scipy.signal
from gym.spaces import Box, Discrete
import torch
import torch.nn as nn
from torch.distributions.normal import Normal
from torch.distributions.categorical import Categorical
def combined_shape(length, shape=None):
if shape is None:
return (length,)
return (lengt... |
# Copyright 2017-2020 typed_python 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 applicable law... |
#
# KTH Royal Institute of Technology
# DD2424: Deep Learning in Data Science
# Assignment 4
#
# <NAME> (<EMAIL>)
#
import re
import numpy as np
import dataset as dt
from joblib import Parallel, delayed
from collections import Counter
from os.path import exists
from model import RNNet
from utilities import unpickle, p... |
from fractions import Fraction
import click
import pytest
from validators.utils import validator
from click_params.base import RangeParamType, BaseParamType, ValidatorParamType, ListParamType
from click_params.numeric import DECIMAL, FRACTION, COMPLEX
class IntType(BaseParamType):
"""We use this custom type to ... |
import asyncio
import discord
from discord.ext import menus
from cogs.utils.DataBase.Items import items, item_convertor
class MarketMenu(menus.MenuPages):
def __init__(self, data, ctx, desc):
super().__init__(source=MarketSource([(1, data), (2, ""), (3, "")]),
clear_reactions_aft... |
import os
import numpy as np
import oct2py
from pilco.controller.linear_controller import LinearController
from pilco.controller.rbf_controller import RBFController
from pilco.util.util import squash_action_dist
octave = oct2py.Oct2Py()
dir_path = "pilco/test/matlab_code"
print(dir_path)
octave.addpath(dir_path)
d... |
#
# * This file is subject to the terms and conditions defined in
# * file 'LICENSE.txt', which is part of this source code package.
from .shared_properties import Publication, Person, CodeRepository, WebSite, Keyword, SoftwareVersion, object_attributes
from hashlib import md5
import uuid
def _mk_hashes(arg1, *arg... |
import os
import numpy as np
from src.general.directory_handling import load, getcolumnames
class PostProcess(object):
def __init__(self, trajectory_file):
self.trajectory_file = trajectory_file
self.data = load(self.trajectory_file)
self.column_names = getcolumnames(self.data)
def ... |
# Standard Libraries
import ipaddress
# Third party packages
from pydantic import validator, root_validator, Field
from pydantic.typing import Optional, List, Union, Literal
# Local package
from net_models.validators import validate_unique_name_field
from net_models.fields import *
from net_models.models import VendorI... |
import os.path
import datetime
import cv2
import numpy as np
from skimage.metrics import structural_similarity
from utils import preprocess, metrics
import lpips
import torch
loss_fn_alex = lpips.LPIPS(net='alex')
def train(model, ims, real_input_flag, configs, itr):
cost = model.train(ims, real_input_flag)
... |
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.ticker as ticker
import numpy as np
from .misc import to_numpy
import torchvision.utils
plt.switch_backend('agg')
pub = False
if pub:
ext = 'pdf'
dpi = 300
else:
ext = 'png'
dpi = None
def save_samples(sa... |
# !/usr/bin/env python
# -*-coding:utf-8 -*-
# PROJECT : web-common-service
# Time :2020/12/4 11:09
# Warning:The Hard Way Is Easier
import datetime
import functools
import uuid
import jwt
from flask import request, jsonify
"""
token加密主要通过jwt包来完成,
- token的刷新,通过一个专门的接口实现,当access_token 失效后,会利用fresh_token来获取新的... |
#!/usr/bin/env python3
import rospy
import cv2
import numpy as np
import yaml
import os
from pathlib import Path
# from remotecapture.msg import video
from sensor_msgs.msg import CameraInfo, Image
from remotecapture.srv import *
from cv_bridge import CvBridge, CvBridgeError
class imgRecorder(object):
"""Docstring... |
#!/usr/bin/env python3
import sys
import os
import pickle
from PokeBall import *
import random
import time
import math
import itertools
# import threading
goodTeam = []
timeAllowed = 120
fileList = ["data/l.matrix.p", "data/h.matrix.p"]
fileIndex = 0
methods = ["BestNext", "Annealing"]
method = 1
bestNextmany = 5... |
import time
from django.forms import model_to_dict
from django.http import JsonResponse
from django.views.decorators.http import require_POST, require_GET
from SevenLema.utils import require_login, add_page_info, require_post_param, require_get_param
from cmdb.models.dish import Dish
from cmdb.models.dish_order impor... |
"""
Class for the SDO/AIA instrument. Holds information about the cadence and
spatial and spectroscopic resolution.
"""
import warnings
import pkg_resources
import numpy as np
import asdf
import zarr
import astropy.units as u
from aiapy.response import Channel
from aiapy.psf import filter_mesh_parameters
from scipy.in... |
"""Integration test suite for ``repo_manager._groups.repository``."""
from copy import deepcopy
from typing import Dict
import pytest
from repo_manager._groups import repository
from repo_manager._util import HandlerRequest
from ..integration_test_utils import agithub_client # noqa pylint: disable=unused-import
fro... |
import errno
import json
import os
import time
from timeit import default_timer as timer
import jsonpickle
from audioled import configs, devices, filtergraph, audio, runtimeconfiguration, serverconfiguration
num_pixels = 300
device = None
switch_time = 10 # seconds
# define configs (add other configs here)
movingL... |
#! /usr/bin/env python
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Updates the chromium binaries used by devil.
This currently must be called from the top-level chromium src directory.
"""
import a... |
from __future__ import print_function
import mir_eval
import numpy as np
import soundfile as sf
from pystoi.stoi import stoi as source_stoi
import subprocess
import os
from copy import deepcopy as dc
import sys
def calc_sdr(degraded, reference):
"""
batch-wise SDR calculation for one audio file.
estimatio... |
import pandas as pd
import numpy as np
import h5py
"""
This module loads h5 files created by a DSM2 hydro or qual run.
All the input, geometry and data tables are available as pandas DataFrame objects
In addition there are convenience methods for retrieving the data tables as
DataFrame that represent time seri... |
'''
Created By ILMARE
@Date 2019-3-6
'''
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import sklearn
import cv2
def xavier_init(input_count, output_count, constant=1):
low = -constant * np.sqrt(6.0 / (input_count + output_count))
high = constant * np.sqr... |
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# [VPYTHON:BEGIN]
# python_version: "3"
# wheel: <
# name: "infra/python/wheels/pywin32/${vpython_platform}"
# version: "version:300"
# >
# [VPYTHON:END... |
import discord
from discord.ext import commands
import random
print(discord.__version__)
intents = discord.Intents(messages=True, guilds=True, reactions=True, members=True, presences=True)
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
game = discord.Game("Summertime S... |
# SPDX-FileCopyrightText: 2019 <NAME> for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_logging`
================================================================================
Logging module for CircuitPython
* Author(s): <NAME>
Implementation Notes
--------------------
**Hardware:**
**So... |
'''
- extract all pixel information from the images to a csv file
- use average pixel value of each channel and round to 12 decimals
- used columns "latitude" and "longitude" from occurrences and merge all information to one csv
- split trainset at 0.1 for validation set
- run XGBoost with all feature columns (35)
- pr... |
# %load train.py
import os
import time
import argparse
import mmcv
from mmcv import Config
from mmcv.parallel import MMDataParallel
from mmcv.runner import obj_from_dict, load_checkpoint, save_checkpoint
from mmcv.runner.log_buffer import LogBuffer
from mmdet.datasets import get_dataset, build_dataloader
from mmdet.mo... |
# Code copied from https://github.com/ethereum/py_ecc/blob/master/py_ecc/bn128/bn128_curve.py
#
# The MIT License (MIT)
#
# Copyright (c) 2015 <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 ... |
import os
from __main__ import slicer
import qt, ctk
#
# BenderWelcome
#
class BenderWelcome:
def __init__(self, parent):
import string
parent.title = "Bender Welcome"
parent.categories = [""]
parent.contributors = ["<NAME> (Kitware)"]
parent.helpText = """"""
parent.acknowledgementText = ""... |
from uuid import uuid4
from elasticsearch import helpers, AsyncElasticsearch
from elasticsearch._async.client.sql import SqlClient
from elasticsearch._async.client.utils import SKIP_IN_PATH, query_params
from elasticsearch.exceptions import NotFoundError
from ssl import create_default_context
from tracardi import con... |
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import argparse
import random
import StringIO
import sys
import zlib
# Generates synthetic Java... |
import random
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
def recall(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
recall_keras = true_positives / (possible_positives + K.ep... |
# Copyright 2017 MongoDB 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 agreed to in writing, sof... |
import decimal
import logging
from collections import deque
from insurrector import MFCR_DATE_FORMAT
from insurrector.calculators.utils import adjust_stock_data, get_stock_sales
logger = logging.getLogger("calculations")
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
class SalesCalculator(object):
def _... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.