text stringlengths 3.07k 22.1k |
|---|
from functools import partial
from struct import Struct
import zlib
from Crypto.Cipher import AES
from Crypto.Hash import HMAC, SHA1
from Crypto.Util import Counter
from Crypto.Protocol.KDF import PBKDF2
def stream_unzip(zipfile_chunks, password=None, chunk_size=65536):
local_file_header_signature = b'\x50\x4b\x... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014 <NAME>
#
# Licensed under the terms of the BSD2 License
# See LICENSE.txt for details
# -----------------------------------------------------------------------------
# Local imports
from pyswmm ... |
import math
import pandas as pd
from itertools import islice
def linkage_tree(X, n_clusters=None, linkage='single', return_distance=False):
return True
def _single_linkage(*args, **kwargs):
kwargs['linkage'] = 'single'
return linkage_tree(*args, **kwargs)
def _complete_linkage(*args, **kwargs):
kw... |
import numpy as np
import pandas as pd
from core.peak_manager_V2 import Spectra, PeakManager
from utils.peacks_testannotatedV2 import TestAnnotated
from core.peak_manager_V2 import distance_matrix
from core.operation_research_tool import optimize_assegnation
from core.neighbor_based_assignment import get_avg_distanc... |
import streamlit as st
import numpy as np
import sounddevice as sd
import soundfile as sf
import os
import tempfile
from pydub import AudioSegment
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
from transformers import AutoConfig, Wav2Vec2FeatureExtractor, AutoTokenizer
from tran... |
from rest_framework import serializers
from rest_framework.relations import SlugRelatedField, PrimaryKeyRelatedField
from api.models.ApprovedFuel import ApprovedFuel
from api.models.ComplianceReportSchedules import ScheduleC, ScheduleCRecord, \
ScheduleARecord, ScheduleA, ScheduleBRecord, ScheduleB, ScheduleD, \
... |
#! /usr/bin/env python
"""Make static images of lyman results using PySurfer."""
import os.path as op
import sys
import argparse
from textwrap import dedent
from time import sleep
import numpy as np
from scipy import stats
import nibabel as nib
import matplotlib.pyplot as plt
from surfer import Brain
import lyman
fro... |
import sys
import asyncio
import time
import discord
import gspread
import os
import json
import help_text
from doc_scan import DocScanner
from datetime import datetime
client = discord.Client()
def print_log(text, delay=0.35):
"""Prints message with time in console and to log file"""
curTime = datetime.now... |
# All rights reserved
# <NAME>, Simpson Querrey Institute for Bioelectronics, Northwestern University, Evanston, IL 6208, USA
# This code reads one day data and randomly sample events for labeling
import shrd
import numpy as np
from numpy import genfromtxt
import sys
import os
import simpleaudio.functionche... |
# © Credits: @tofik_dn || https://github.com/tofikdn
# @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/Lunatic0de
from asyncio import QueueEmpty
from pytgcalls.types import Update
from pytgcalls.types.input_stream import InputAudioStream, InputStream
from tele... |
#!/usr/bin/env python3
import socket
import sys
import unittest
import threading
numports=1000
startport = 19000
port=5105
unix_path='/tmp/portmux.socket'
class BufferedSocketReader(socket.socket):
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, fileno=None):
super().__init__(... |
import numpy as np
import scipy
import scipy.linalg
import scipy.stats
class MeanConditionalNormal:
def __init__(self, mua, cova, linear, bias, covcond):
self.mua = mua
self.cova = cova
self.linear = linear
self.bias = bias
self.covcond = covcond
def to_natural(self):... |
#
# 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, Version 2.0
# (the "License"); you may not us... |
from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from codebase.models import SOURCE_TYPE, CodeBase, CodeElement,\
CodeElementKind
PREFIX = 'p'
SUFFIX = 's'
MIDDLE = 'm'
DECLARATION = 'd'
HIERARCHY = 'h'
HIERARCHY_D = 'hd'
... |
"""
Birth death process and reconstructed process for trees
"""
from math import *
import random
from rasmus import util, stats, treelib
def prob_birth_death1(ngenes, t, birth, death):
"""
Returns the probability that one lineage leaves 'ngenes' genes
after time 't'
"""
# special cases
if ... |
# -*- coding: utf-8 -*-
"""Command-line output
Contains most functions, classes, etc. to handle the output of data.
"""
from __future__ import print_function, unicode_literals
from __future__ import absolute_import
from __future__ import division
from abc import ABCMeta, abstractmethod, abstractproperty
from collecti... |
import uuid
from typing import Optional, List, Dict, cast
from util import XYZ, POINT_AT_TARGET
from task import Task
class MemoryNode:
TABLE_ROWS = ["uuid"]
PROPERTIES_BLACKLIST = ["agent_memory", "forgetme"]
TABLE: Optional[str] = None
@classmethod
def new(cls, agent_memory, snapshot=False) -> ... |
"""
# Reference papers
- [Very Deep Convolutional Neural Networks for Raw Waveforms]
(https://arxiv.org/abs/1610.00087)
"""
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import os
# import torchaudio
from torch.... |
import numpy as np
import tensorflow as tf
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'utils'))
# from box_util import get_3d_box
import utils.tf_util as tf_util
from tensorflow.python.o... |
from django.core import exceptions
from django.http import FileResponse, HttpResponse
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy as _
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.exceptions import ValidationError
from... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import numpy as np
import time
from progress.bar import Bar
from models.losses import FocalLoss, CenterLoss
from utils.utils import AverageMeter
from models.losses import RegL1Loss, RegLoss, NormR... |
# -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... |
import os
import socket
import ssl
from pathlib import Path
from typing import List, Dict, Optional, Any
import demistomock as demisto # noqa: F401
import pem
from CommonServerPython import * # noqa: F401
from cryptography import x509
from cryptography.hazmat.backends import default_backend
def parse_issuer_certif... |
#!/usr/bin/env python
# Forward telemetry to everyone attached to the AP.
import ConfigParser
import datetime
import logging
import logging.config
import os
import re
import select
import socket
import sys
import time
import struct
import clock
from pymavlink import mavutil
logging.config.fileConfig("/etc/sololink.c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import pytest
from cwl_utils.parser import load_document_by_uri
from dateutil.parser import parse as date_parse
from provenance import (
ArtefactFactory,
NXWorkflowFactory,
PromortArtefactSerializer,
main,
)
date_isoformat = "2022-01-01T00:00:0... |
import sys
import numpy as np
from scipy import special
from scipy import sparse
import argparse
from scipy.stats import truncnorm, poisson, gamma
from sklearn.metrics import mean_squared_error as mse
class SocialPoissonFactorization:
def __init__(self, n_components=100, max_iter=100, tol=0.0005, random_state=None, ... |
# Licensed under MIT license - see LICENSE.rst
# -*- coding: utf-8 -*-
"""Functions to deal with DECaLS sweep catalog.
The sweeps are light-weight FITS binary tables (containing a subset of the most
commonly used Tractor measurements) of all the Tractor catalogs for which
`BRICK_PRIMARY==T` in rectangles of RA, Dec.
... |
import os
import json
import numpy as np
import matplotlib.pyplot as plt
def compute_iou(box_1, box_2):
'''
This function takes a pair of bounding boxes and returns intersection-over-
union (IoU) of two bounding boxes.
'''
tlx1, tly1, brx1, bry1 = box_1
tlx2, tly2, brx2, bry2 = box_2
boxe... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
##########################################################################
## Summary
##########################################################################
'''
Creates flat table of decisions from our Postgres database and runs the prediction pipeline.
Starting point for running our models.
'''
################... |
# -*- coding: utf-8 -*-
# Copyright 2018, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
# pylint: disable=invalid-name
"""Main Qiskit visualization methods."""
import sys
from qiskit._util import _has_connection... |
"""Tileset and font related functions.
Remember to add the line ``import tcod.tileset``, as importing this module is
not implied by ``import tcod``.
"""
import os
from typing import Any, Tuple
import numpy as np
from tcod.loader import lib, ffi
import tcod.console
from tcod._internal import _check, _console
class... |
#!/usr/bin/env python3
#
# __init__.py
"""
A μ-library for constructing cascasing style sheets from Python dictionaries.
.. latex:vspace:: 10px
.. seealso:: `css-parser <https://github.com/ebook-utils/css-parser>`_, which this library builds upon.
"""
#
# Copyright © 2020-2021 <NAME> <<EMAIL>>
#
# Permission is her... |
# Copyright 2017 Pilosa Corp.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2... |
import sys,os
import numpy as np
import pandas as pd
import h5py, math
from collections import Counter
# Get Euclidean Norm minus One
def get_ENMO(x,y,z):
enorm = np.sqrt(x*x + y*y + z*z)
ENMO = np.maximum(enorm-1.0, 0.0)
return ENMO
# Get tilt angles
def get_tilt_angles(x,y,z):
angle_x = np.arctan2(x, np.sqr... |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import bisect
import tensorflow as tf
from tensorflow import keras
from tensorflow.python.ipu.ops import pipelining_ops
import logging
from typing import Optional
from .toy_model import ToyModel
from .resnet_models import ResNet18, ResNet34, ResNet50
from .cifa... |
import matplotlib
import numpy as np
import pudb
import rclpy
from cv_bridge import CvBridge, CvBridgeError
from rclpy.node import Node
from sensor_msgs.msg import Image
from std_msgs.msg import Header
import cv2
from terra_camera.waypoint import WaypointPublisher
from topological_nav.reachability import model_factory... |
import os
import sys
import shutil
import subprocess
import xarray as xr
import numpy as np
# Current, parent and file paths
CWD = os.getcwd()
CF = os.path.realpath(__file__)
CFD = os.path.dirname(CF)
# Import library specific modules
sys.path.append(os.path.join(CFD,"../"))
sys.path.append(os.path.join(CFD,"../pys... |
import string
from collections import Counter
from typing import List
from letter_values import letter_to_value, value_to_letter, word_to_value
from anagram_searcher import AnagramSearcher
from Ciphers.substitution import Action, use_caesar
from word_list import WordList
woordzoeker = """
<KEY>
""".strip().replace(' ... |
import torch
from torch import Tensor
from typing import List, Optional
import numpy as np
from numpy import linalg as LA
import math
def grad_proj(X, dX, inner='canonical'):
r"""project grad data onto Stiefel manifold
Args:
X (tensor): tensor of parameters in matrix form
dX (tensor): grad tens... |
from pmx import Model
from pmx.rotamer import load_bbdep
import argparse
import os
from helper import map_atom_string
from pmx.library import _aacids_dic
from pmx.rotamer import get_rotamers, select_best_rotamer
from os.path import basename
from multiprocessing import Process
# Argument parsers
def parse_... |
"""translate GUI actions to core-provided functions"""
import collections
import itertools
import tkinter as tk
import tkinter.messagebox as tk_msg
from functools import partial
import typing as T
from ..misc import tkstuff as mtk
from ..misc.tkstuff import dialogs as mtkd
from ..misc.tkstuff import forms as mtkf
fro... |
# stdlib
import datetime
import asyncio
# discord.py
import discord
from discord.ext import tasks
from discord.ext.commands.errors import CommandInvokeError
# Red-DiscordBot
from redbot.core import Config, commands, checks
# Current Plugin
from .time import human_timedelta, UserFriendlyTime
__autho... |
# -*- utf-8 -*-
r"""
_training_logger.py
~~~~~~~~~~~~~~~
Provides utilities to simplify and standardize logging in particular for training for training
with \p torch.
:copyright: (c) 2020 by <NAME>.
:license: MIT, see LICENSE file for more details.
"""
__all__ = ["TrainingLogger", "create_std... |
"""
*
* Copyright (c) 2018 Cisco Systems, Inc.
* 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
* notice, this lis... |
from functools import wraps
from flask import request, render_template, flash, redirect, url_for, \
session, Blueprint, g, abort
from flask_login import current_user, login_user, logout_user, \
login_required
from wtforms import PasswordField
from my_app import db, login_manager
from flask_admin import BaseView... |
# 23.10.2020
# Project Name: XYZ 3D CARTESİAN SİMULATOR
# Project Destination : G-CODE PARSER
# Author : <NAME>
from tkinter.filedialog import *
import tkinter as tk
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
import time
import threading
from matplotlib.figure impo... |
import os
import torch
import torch.nn as nn
from torchvision import models
from torchvision.models.utils import load_state_dict_from_url
from torchvision.models.resnet import Bottleneck, model_urls
import copy
import torch
import torch.nn as nn
from torchvision import models
from torch.nn.parameter import Parameter
... |
# <NAME>
# u/SbubbyBot for the the mods of r/Sbubby
import threading # to be able to run in threads
import praw # all the reddit i/o
import os # to get enviroment variables containing secrets
import psycopg2 # used for postgresql database stuff
from datetime import datetime # need to get current time for multiple... |
import os
import pickle
import numpy as np
from tqdm import tqdm
import torch
from self_supervised.data.io import loadmat
FILENAMES = {
('mihi', 1): 'full-mihi-03032014',
('mihi', 2): 'full-mihi-03062014',
('chewie', 1): 'full-chewie-10032013',
('chewie', 2): 'full-chewie-12192013',
}
class ReachN... |
import functools
import inspect
import warnings
from collections import namedtuple
from pathlib import Path
from typing import Callable, Dict, List, Tuple
from openeo_driver.errors import ProcessUnsupportedException
from openeo_driver.specs import SPECS_ROOT
from openeo_driver.utils import read_json
class ProcessPar... |
import math
import unittest
import numpy
import chainer
from chainer import backend
from chainer.backends import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
class CTCTestBase(object):
de... |
# -*- coding: utf-8 -*-
"""Advent of Code 2016 - Day 6: Probably a Fire Hazard."""
from typing import NamedTuple
from dataclasses import dataclass
import re
@dataclass
class Size:
"""A height and width in 2-dimensional space."""
cx: int = 0
cy: int = 0
def __add__(self, rhs):
"""Return the ... |
import bz2
import http.client
import mimetypes
import os
import sys
from datetime import timedelta
from distutils.dir_util import mkpath
from django.conf import settings
from django.core.exceptions import SuspiciousOperation
from django.db import models
from django.http import HttpResponse
from django.utils import tim... |
# -*- coding: utf-8 -*-
import sys
from getpass import getpass
import argparse
import pkg_resources
import pyperclip
from .generator import *
from .utils import *
from .constants import *
def show_password_entropy(passwd, word_list):
"""Displays the password entropy calculation results."""
entropy = calcula... |
import csv
import os.path
import tempfile
import urllib2
class DataSet:
def __init__(self, force_reload=False):
self.__force_reload = force_reload
def as_dictionary(self):
return self.validate(csv.DictReader(open(self.read_cache(), 'rb')))
def get_remote_url(self):
raise Excepti... |
"""
Custom datasets and loaders which could exclude certain classes.
Also enables returning the indices of selected instances.
"""
import os
from typing import Optional, Callable, Tuple, Any, Sequence
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision import datasets, transforms... |
# Copyright 2015 Confluent 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, s... |
###########################################################################
#
# boot.py
# Author: <NAME>
# Date: 1/24/2020
#
# This script will run at startup and will initialize the bluetooth module
# also sets the bluetooth to advertise
#
###########################################################################
i... |
from ctypes import windll, pointer, c_int
from ctypes.wintypes import DWORD
from ..keys import Keys
from ..key_binding import KeyPress
from ..win32_types import EventTypes, KEY_EVENT_RECORD, INPUT_RECORD, STD_INPUT_HANDLE
__all__ = (
'ConsoleInputReader',
'raw_mode',
'cooked_mode'
)
class ConsoleInputRe... |
import logging
import time
from decimal import Decimal
from helpers import cassandra_helper
try: import simplejson as json
except ImportError: import json
from flask import Flask, Blueprint, render_template, request, session, jsonify
# from routes.rest import get_session, \
# get_solr_session
app = Flask(__name__... |
# -*- coding: utf-8 -*-
"""
Loss functions for regression
"""
from __future__ import absolute_import, print_function, division
import tensorflow as tf
from niftynet.engine.application_factory import LossRegressionFactory
from niftynet.layer.base_layer import Layer
class LossFunction(Layer):
def __init__(self,
... |
import sys
import matplotlib
import petsc4py
# matplotlib.use('agg')
petsc4py.init(sys.argv)
import numpy as np
import pickle
from time import time
from codeStore import support_fun_table as spf_tb
from petsc4py import PETSc
from datetime import datetime
from tqdm import tqdm
# get kwargs
def get_problem_kwargs(**m... |
# standard modules
import re
import types
# third-party modules
import numpy as np
import pandas as pd
import pint
class Map(dict):
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
if isinstance(v,... |
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 6 18:14:52 2021
@author: Me
"""
import numpy as np
import matplotlib.pyplot as plt
from photutils.datasets import make_noise_image
from perlin_numpy import generate_perlin_noise_2d
import numba
from scipy.stats import multivariate_normal
from scipy.optimize i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import frappe
from frappe import msgprint
from frappe.utils import flt
def validate(doc,method):
for d in doc.items:
wh = frappe.get_doc("Warehouse", d.warehouse)
if wh.is_subcontracting_warehouse == 1:
frappe.throw(("Subcontracted Wareh... |
# Copyright The IETF Trust 2021 All Rights Reserved
import debug # pyflakes:ignore
import io
from django import forms
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from django.urls imp... |
from typing import List
import plotly.graph_objects as go
import numpy as np
from plotly.subplots import make_subplots
from ContainerLoading.Models.ItemModel import ItemModel
pallete = ['darkgreen', 'tomato', 'yellow', 'darkblue', 'darkviolet', 'indianred', 'yellowgreen', 'mediumblue', 'cyan',
'black', 'in... |
import re
from pathlib import Path
import numpy as np
import pandas as pd
def load_msa_lookup(data_path):
""" Loads a lookup table for various MSA specific attributes used
throughout the project.
:param data_path: a pathlib.Path() object, location of data file folder
:return msa_lookup: a dictionar... |
import idaapi
import idc
from threading import RLock
import itertools
import wrapt
from .qt import MenuManager
import traceback
class Update(object):
"""
A context manager that refreshes the UI on `__exit__`.
When nested, only the topmost context manager can update the UI.
This is used to make sure t... |
from app import db, login
from flask_login import UserMixin, LoginManager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import current_user
from statistics import stdev
@login.user_loader
def load_user(id):
return User.query.get(int(id))
enrolments = db.Table('enrolme... |
import pandas as pd
import numpy as np
import random
import time
import datetime
import sys
import os
from tqdm import tqdm
import torch
from torch.utils.data import TensorDataset, random_split, DataLoader, RandomSampler, SequentialSampler
from transformers import BertTokenizer, BertForSequenceClassificatio... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, <NAME>, TUM
# 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... |
# -*- coding: utf-8 -*-
#
#Created on Mon Apr 10 14:20:27 2017
#
#author: <NAME>
#
import numpy as np
import h5py
from .base import BaseMixture, _check_saving
def dist_matrix(points,means):
XX = np.einsum('ij,ij->i', points, points)[:, np.newaxis] # Size (n_points,1)
squared_matrix = np.dot(points,mea... |
import neuroml
import neuroml.writers as writers
import lems.api as lems
import xml.etree.ElementTree as ET
# This is available at https://github.com/OpenSourceBrain/OSB_API
import osb.metadata
import osb.resources
import sys
def channelpedia_xml_to_neuroml2(cpd_xml, nml2_file_name, unknowns=""):
in... |
""" Module for synthetic and real datasets with available ground truth feature importance explanations. Also contains
methods and classes for decisionRule data manipulation.
All of the datasets must be instanced first. Then, when sliced, they all return the observations, labels and ground
truth explanations, respectiv... |
import os, sys
import numpy as np
import torch
import config as cfg
import open3d as o3d
T_opengl_cv = np.array([
[1.0, 0.0, 0.0],
[0.0, -1.0, 0.0],
[0.0, 0.0, -1.0]
])
T_opengl_cv_homogeneous = np.array([
[1.0, 0.0, 0.0, 0.0],
[0.0, -1.0, 0.0, 0.0],
[0.0, 0.0, -1.0, 0.0],
[0.0, 0... |
import datetime
import os
import uuid
import zipfile
from io import BytesIO
import pyqrcode
import requests
import weasyprint
from django import forms
from django.conf import settings
from django.contrib import admin, messages
from django.core.exceptions import PermissionDenied
from django.db.models.query import Query... |
# 加载自定义包
from base_classes_funcs import *
from operators import *
def gen_alpha_tree(pset, min_, max_, output_type, data_classified_by_units, n_units,
data_type, dict_operators, dict_data_eval_info, patience=1000) -> list:
"""generates a legal alpha syntax tree.
:param patience: num... |
import os
import numpy as np
import logging
import meshpy
from meshpy import ObjFile
from autolab_core import RigidTransform
import dexnet.database.mesh_processor as mp
import dexnet.grasping.grasp_sampler as gs
import dexnet.grasping.grasp_quality_config as gqc
import dexnet.grasping.grasp_quality_function as gqf
fr... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
import torch
def convert(cv_image):
return cv_image[..., ::-1]
def sigmoid(x):
# x is an nparray
# This sigmoid will scale/translate in order to spread its input values over a wider range of outputs.
mean = np.mean(x)
variance = ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------------------------------... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy import optimize
import pandas as pd
from scipy.stats import binom, poisson
def cdf(x, func, max, step, *fargs):
"""calculate cdf for function. extra arguments (after x) for func in should be given in fargs
func is the abitra... |
# Copyright 2021 The Commplax 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 or agreed to in... |
import copy
import logging
import math
import random
import warnings
from typing import List, Tuple
import numpy as np
import pandas as pd
import torch
logger = logging.getLogger()
EXPL_LENGTHS_TRAIN_20 = [(1, 208),
(2, 299),
(3, 354),
(4, 37... |
import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
from SlidingWindowVideoTDA.VideoTools import *
from Alignment.AllTechniques import *
from Alignment.AlignmentTools import *
from Alignment.Alignments import *
from Alignment.DTWGPU import *
from Skeleton import *
from Weizmann import *
from Paper... |
import scipy.stats as stats
from scipy.special import erf
from functools import partial
import numpy as np
import sys
import os
########################################################################################################################
# Define the probability distribution of the random parameters... |
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
from .validators import phone_validator
ACTIVE_OPTIONS = (("active", "Active"), ("active", "Inactive"), ("active", "Archived"))
c... |
from functools import wraps
import os
import random
import re
import pytest
from flask.testing import FlaskClient
from flask import session
os.environ['PYDRILL_CONFIG'] = os.path.join(os.path.dirname(__file__), 'pydrill.cfg')
from pydrill import app, db, redis_store
from pydrill import models
from pydrill.jinja_env i... |
import enum
import functools
import sys
import typing
import caproto
import caproto._log as caproto_log
import caproto.threading
import numpy as np
_default_thread_context = None
class MisconfigurationError(Exception):
"""Misconfiguration blocks the calculation from continuing."""
...
class State(enum.Int... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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 appl... |
r"""
Adapted from https://github.com/pyro-ppl/pyro/blob/dev/examples/inclined_plane.py.
An experiment consists of a box sliding down an include plane of some length and degrees
(for example, 2 meters and 30 degrees incline). For each experiment, we measure the descent
time using a device with a known measurement err... |
# This file is a part of Lector, a Qt based ebook reader
# Copyright (C) 2017-2019 BasioMeusPuga
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your o... |
import pickle
from loader.vlog import VLOG
import torch
from loader.videodataset import my_collate
from torch.nn import Module
import torch.nn as nn
import ipdb
import torch
from utils.meter import *
import shutil
import math
def load_pickle(file):
with open(file, mode='rb') as f:
df = pickle.load(f, enco... |
# -*- coding: utf-8 -*-
# Copyright: (c) 2016 <NAME> <<EMAIL>>
# Copyright: (c) 2021 <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import locale
from ansible.module_... |
import logging
import numpy as np
import sklearn
import sklearn.mixture
from .metrics import calculate_lr_statistics
from .util import Xn_to_Xy, LR
LOG = logging.getLogger(__name__)
class CalibratedScorer:
def __init__(self, scorer, calibrator):
self.scorer = scorer
self.calibrator = calibrato... |
#
import os
import logging
from typing import Optional, Dict
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.animation import ImageMagickWriter
import torch
# configure matplotlib logger
logging.getLogger("matplotlib").setLevel(logging.WARNING)
if "PYCHARM_HOSTED" in os.environ:
... |
from typing import List
import datetime as dt
from datetime import timedelta
import requests
import os
import pickle
from typing import Dict, Tuple
import geopandas as gpd
import pandas as pd
import pytz, datetime
from shapely import wkt
from timezonefinderL import TimezoneFinder
from peaky_finders.data_acquisition.t... |
from pathlib import Path
import os
import numpy as np
import sys
from ..basesorter import BaseSorter
from ..utils import ShellScript
from spikeinterface.core import load_extractor
from spikeinterface.core import BinaryRecordingExtractor
from spikeinterface.extractors import YassSortingExtractor
class YassSorter(Ba... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.