text stringlengths 3.07k 22.1k |
|---|
import numpy as np
import os
import time
from sklearn import svm
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.metrics import accuracy_score
from grakel import datasets
from grakel import GraphKernel
from... |
import torch
import torch.nn as nn
# from models import Model
from models import Model
from torch.utils.data import DataLoader
import cv2
import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from datasets import *
from matplotlib.ticker import NullLocator
image_path = '... |
"""The tests for the Cast Media player platform."""
# pylint: disable=protected-access
import asyncio
from typing import Optional
from unittest.mock import patch, MagicMock, Mock
from uuid import UUID
import pytest
from homeassistant.exceptions import PlatformNotReady
from homeassistant.const import EVENT_HOMEASSISTA... |
import gym
import time
import random
import numpy as np
from collections import deque
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
os.system('export CUDA_VISIBLE_DEVICES=""')
import gc
import os
import tensorflow as tf
import keras.backend.tensorflow_backend as KTF
def get_session(gpu_fraction=0.7):
'''Ass... |
# -*- coding: utf-8 -*-
'''
General management and processing of queues.
============================================
This runner facilitates interacting with various queue backends such as the
included sqlite3 queue or the planned AWS SQS and Redis queues
The queue functions such as `insert`, `delete`, and `pop` can... |
from collections import deque
import cv2
import logging
import multiprocessing
from multiprocessing import Process
import numpy as np
import os
from cvutils import CVFrame, CVVideoCapture, CVAcceptanceTest
from cvutils.cvmisc import generate_multiprocessing_final_pass_ranges
from cvutils.cvprogresstracker import C... |
# Copyright (c) 2019 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 appli... |
import sys
import math
import time
import logging
import numpy as np
from scipy import spatial
import cv2
from shapely.geometry import Polygon, JOIN_STYLE
from polylidar import MatrixDouble, Delaunator, bilateral_filter_normals
M2TOCM2 = 10000
CMTOM = 0.01
ORANGE = [249, 115, 6]
ORANGE_BGR = [6, 115, 249]
def a... |
# Modified from https://github.com/AlexYangLi/KGCN_Keras
import os
import random
from collections import defaultdict
import numpy as np
import pandas as pd
from config import Config
from utils import pickle_dump, pickle_load
random.seed(14)
np.random.seed(14)
def read_item2entity_file(item2entity_path, item_voca... |
import sys
from copy import deepcopy
from time import time
import numpy as np
import scipy.integrate
from krylov import krylov_prop,krylov_prop_ada
from eom import cmfeom_spfs
from optools import precompute_ops
from cy.wftools import (overlap_matrices,compute_density_matrix,
invert_density_mat... |
from pygame import*
#variables
surface_width = 900
surface_height = 700
ch_size = 90
border_left = 0
border_top = 0
border_right = surface_width - ch_size
border_bottom = surface_height - ch_size
#window
window = display.set_mode((surface_width, surface_height))
display.set_caption("Ping Pong")
clock ... |
import random as rd
class Demineur :
def __init__(self):
self.hauteur = 20
self.largeur = 20
self.nb_joueurs = 1
def initialisation(self, plateau):
"""Empty the plate and set the correct configuration"""
demineur_initialisation(plateau)
def termine(self, plateau... |
# -*- coding: utf-8 -*-
# **********************************
# Author: Lizi
# Contact: <EMAIL>
# **********************************
from layers import *
Cell_Operation = {
'MatchCost_Cell': lambda genotype: MatchCost_1_Cell(genotype),
'Concat_Cell': lambda genotype: Concat_Cell(genotype),
'R... |
# Copyright 2020 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 in writing, ... |
import os
import threading
import time
import tkinter.messagebox
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from ttkthemes import themed_tk as tk
from mutagen.mp3 import MP3
from pygame import mixer, error
root = tk.ThemedTk()
root.get_themes()
root.set_theme("radiance")
statusbar = ... |
# coding: utf-8
from __future__ import division, print_function
import numpy as np
import tensorflow as tf
import cv2
import random
# 只针对一个样本的信息
def parse_line(line):
'''
Given a line from the training/test txt file, return parsed
pic_path, boxes info, and label info.
return:
pic_path: string... |
#!/usr/bin/env python3
# coding=utf-8
import json
from utils import *
import os
config_dir, config_file_dir, lock_file_dir = get_config_dir()
if os.path.exists(lock_file_dir):
SUBSCRIBE_URL = get_config_value('SUBSCRIBE_URL')
SERVER_JSON_FILE_PATH = get_config_value('SERVER_JSON_FILE_PATH')
CONFIG_JSON_FIL... |
# -*- coding: utf-8 -*-
from weakref import WeakKeyDictionary
from itertools import product
__version__ = '0.1.1'
_DATA = WeakKeyDictionary()
_INDEXES = WeakKeyDictionary()
_FORMATTERS = WeakKeyDictionary()
class Dict(dict):
def __getattr__(self, key):
try:
return self[key]
except Ke... |
import inspect
from functools import wraps
from inspect import Parameter
from typing import NamedTuple, Union, Tuple, Dict, Any, List
from enum import Enum
class FillingMode(Enum):
NOT_FILLED = 0
PLACEHOLDER = 1
FILLED_BY_DEFAULT = 2
FILLED = 3
class Placeholder:
pass
_ = Placeholder()
Binding = Di... |
import numpy as np
import argparse
from argparse import RawTextHelpFormatter
from windygridworld import WindyGridWorld
from agents import Agent
import matplotlib.pyplot as plt
lr = 0.7
episodes = 200
steps = 8000 #max number of steps before termination
epsilon = 0.05
numSeeds = 50
verbose = False
def runwindy(update,... |
from __future__ import print_function
import argparse
import imp
import random
import numpy as np
import itertools
import os
import pickle
from sklearn.model_selection import StratifiedKFold, GridSearchCV
from sklearn.svm import SVC
from sklearn.metrics import make_scorer
from sklearn.metrics import confusion_matrix
... |
import math
import numba
import numpy as np
from numba import cuda
__all__ = ['rotate_iou_gpu_eval']
@numba.jit(nopython=True)
def div_up(m, n):
return m // n + (m % n > 0)
@cuda.jit(device=True, inline=True)
def rbbox_to_corners(corners, rbbox):
# generate clockwise corners and rotate it clockwise
angl... |
import os
import time
import glob
import numpy as np
import argparse
import json
from detection_evaluation.nuscenes_eval_core import NuScenesEval
from detection_evaluation.label_parser import LabelParser
import co_utils as cu
def parse_args():
parser = argparse.ArgumentParser(description='arg parser')
# parser... |
import asyncio
import os
import binascii
import time
from typing import Dict
import async_timeout
from spruned.dependencies.connectrum import ElectrumErrorResponse
from spruned.dependencies.connectrum import StratumClient
from spruned.dependencies.connectrum import ServerInfo
from spruned.application.context import c... |
##### Implementation of FedAvg #####
##### importing libraries #####
import copy
import random, argparse
import torch
import numpy as np
import options.options as option
from tqdm import tqdm
from torch import utils as vutils
from data import create_dataset, create_dataloader
from solvers import create_solver
from ut... |
from torch.utils.data import Subset, Dataset, random_split
from PIL import Image
from anomaly_detection.base.torchvision_dataset import TorchvisionDataset
import os
import torchvision.transforms as transforms
from cv2 import imread, IMREAD_UNCHANGED, IMREAD_GRAYSCALE
import numpy as np
# DEPTH_MEAN=1.8502674
# DEPT... |
################################################################################
# Copyright (c) 2017-2020, National Research Foundation (Square Kilometre Array)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the... |
import time
import logging
from copy import copy
from ophyd import (PVPositioner, PVPositionerPC, EpicsMotor)
from ophyd import (EpicsSignal, EpicsSignalRO)
from ophyd import (Component as C)
from ophyd import get_cl
from ophyd.ophydobj import Kind
from .conftest import AssertTools
logger = logging.getLogger(__name__... |
from gmshnics.make_mesh_cpp import build_mesh
from gmshnics.utils import second
from gmshnics.meshsize import set_facet_distance_field
from collections import defaultdict
from functools import reduce, wraps
import dolfin as df
import numpy as np
import operator
import gmsh
import ufl
def occ(tdim, fdim):
'''
... |
import logging
import os
import tempfile
from django.contrib import messages
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponseRedirect, HttpResponse
from django.template.response import TemplateResponse
from django.utils.encoding import force_text
from django... |
#!/usr/bin/env python
# coding: utf-8
import subprocess
import os
import platform
import sys
from math import pi, atan2
sys.path.append('/usr/share/inkscape/extensions')
import inkex
import simplepath
import simplestyle
from simpletransform import parseTransform, applyTransformToNode
def get_n_points_from_path(nod... |
import os
import torch
import time
from sklearn.model_selection import KFold
from collections import defaultdict
from tqdm import tqdm
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from src.utils.functions import reset_weights
class BaseTrainer:
... |
import os
import errno
import numpy as np
import json
from math import pi
import pandas as pd
import seaborn as sns
from scipy import stats
from decimal import Decimal
from collections import Counter
import matplotlib.pyplot as plt
from bokeh.plotting import figure, show, output_file,save
import redacted_logging as rlo... |
#!/usr/bin/env python
# vim:softtabstop=4:ts=4:sw=4:expandtab:tw=120
import argparse
import json
import os
import sys
import re
import tempfile
import traceback
gVerbose = 0
def enum(**enums):
return type('Enum', (), enums)
LogSeverity = enum(ERROR=0, WARNING=1, INFO=2, DEBUG=3)
def _get_log_severity_str(sever... |
import unittest
import numpy
import chainer
from chainer import cuda
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
import einsum
@testing.parameterize(*testing.product_dict(
[
# 1 array
{'subs': 'ij->j',
... |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
"""
Internal napari hook implementations to be registered by the plugin manager
"""
import os
import shutil
from typing import Any, List, Optional, Union
import numpy as np
from napari_plugin_engine import napari_hook_implementation
from ..types import (
FullLayerData,
LayerData,
ReaderFunction,
Write... |
import scipy
import numpy as np
import scipy.interpolate as interp
import scipy.ndimage.filters as filt
import matplotlib.pyplot as plt
def flag_outliers(signal,
thresh_stdv=4,
buffer=10,
visualize=False):
""" Flag outliers based on median abs deviation.
... |
import itertools as it
import warnings
import pandas as pd
from src.config import POPULATION_GERMANY
from src.create_initial_states.create_initial_immunity import create_initial_immunity
from src.create_initial_states.create_initial_infections import (
create_initial_infections,
)
def create_initial_conditions(... |
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import brevitas.nn as qnn
from common import *
class DCGAN_gen(nn.Module):
def __init__(self, out_channels, config):
super(DCGAN_gen, self).__init__()
self.config = config
self.in... |
"""
Analysis by Term
==========================================================================
"""
import ipywidgets as widgets
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import display
from nltk.corpus.reader.ieer import documents
import techminer.c... |
"""
Define functions for updating the public keys associated with certain token
issuers and retrieving the public key which can be used to verify a given JWT.
The public keys should be stored on the flask app in a `jwt_public_keys`
attribute, which will be a dictionary mapping issuer URLs (`iss` in a JWT) to
ordered d... |
#!/usr/bin/env python
# encoding: utf-8
import threading
import npyscreen
import serial
from serial.tools import list_ports
from apscheduler.schedulers.background import BackgroundScheduler
from pynput.keyboard import Key, KeyCode, Controller
from enum import Enum
class SerialReader:
scheduler = None
job = No... |
import torch
import torch.nn as nn
import logging
from cormorant.cg_lib import SphericalHarmonicsRel
from cormorant.models.cormorant_levels import CormorantAtomLevel, CormorantEdgeLevel
from cormorant.nn import RadialFilters
from cormorant.nn import InputLinear, InputMPNN
from cormorant.nn import OutputLinear, Outp... |
from __future__ import unicode_literals
import copy
import os
import re
import subprocess
import tempfile
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend as crypto_defaul... |
# coding: utf-8
from __future__ import annotations
import re
from collections import OrderedDict
from dataclasses import dataclass, field
from typing import (
Any,
Dict,
Iterable,
List,
Type,
TypeVar,
Union,
)
from . import PROJECT_MODULE
UsedByModuleType = TypeVar('UsedByModuleType', bou... |
import re
from itertools import product
from collections import defaultdict, namedtuple
from trove.dataloaders.contexts import Span, Relation
def get_text(words, offsets):
s = ''
for i, term in zip(offsets, words):
if len(s) == i:
s += term
elif len(s) < i:
s += (' ' * ... |
#!/bin/env python2
# coding: utf-8
import copy
import operator
from collections import defaultdict
def depth_iter(mydict, ks=None, maxdepth=10240,
intermediate=False, empty_leaf=False,
is_allowed=None):
ks = ks or []
dickeys = sorted(mydict.keys())
for k in dickeys:
... |
import os.path
import collections
import re
import math
import itertools
INPUT=os.path.join(os.path.dirname(__file__), "input.txt")
with open(INPUT) as f:
data = f.read()
INPUT=os.path.join(os.path.dirname(__file__), "test_input.txt")
with open(INPUT) as f:
testdata = f.read()
def get_walls(tile_map):
yiel... |
#!/usr/bin/env python
# coding: utf-8
# # This is a TF Estimator end-to-end baseline solution
#
# **For local run**
#
# Tested with
#
# ```
# numpy==1.13.3
# scipy==0.19.1
# tensorflow-gpu==1.4.0
# tqdm
# ```
#
#
# I want to show usage of Estimators with custom python datagenerators.
#
#
# Detailed documentatio... |
""" VGG16 network Class
Adapted from <NAME>'s code: https://github.com/gurkirt/realtime-action-detection/blob/master/ssd.py
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import os
# adv
from models.grad_reversal import ReverseLayerF
import pdb
class MLP_Blo... |
from __future__ import division
import numpy as np
import math
def createBicubicCoefMatrices(num_of_quads):
"""
Returns a dictionary with the biquadractic point coefficients of its
neighbour vertices for each control point (i,j) = 1..4 on the bicubic patch,
in the form of four vectors of neighbouring... |
import os
import itertools
import numpy as np
import uproot as ur
import pandas as pd
from fair_hmumu import defs
from fair_hmumu.utils import timeit
class DatasetHandler:
def __init__(self, trn_conf, seed=42):
"""
Dataset handler. Split in training and test sets, get training batches.
A... |
# -*- coding: utf-8 -*-
import numpy as np
from scipy.optimize import minimize
from numba import njit
from math import erf, sqrt, exp
from time import time
from ._utils import _invertmatrix
def _rvs(params, size):
'''
Calculates random samples from ESAG distribution
Args:
params (ndarray [5,]... |
## ALL RIGHTS RESERVED.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writin... |
import json
from typing import Union, Dict, Any
import wagtail
from django import forms
from django.conf import settings
from django.db import models
from django.http.response import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.utils.text import Truncator
from du... |
#!/usr/bin/env python3
""""
Extract fragments for molecules in given SDF/SMILES files and save then into JSON files.
Usage:
python extract_fragments.py
-i (comma separated 3 input files with inactive molecules, first with active molecules, second with inactive
molecules, third with test ... |
#!/usr/bin/env python3
from typing import Dict, Any, List
import json
from functools import lru_cache
from datetime import datetime, date, time, timedelta
from pathlib import Path
import logging
import pytz
from mycfg import paths
BDIR = paths.jawbone.export_dir
PHASES_FILE = BDIR / 'phases.json'
SLEEPS_FILE = BDIR ... |
import numpy as np
import scipy.stats
from mesostat.utils.arrays import numpy_merge_dimensions, numpy_transpose_byorder, set_list_shapes, list_assert_get_uniform_shape
from mesostat.utils.matrix import offdiag_1D
# Test that along a given dimension all shapes are equal
def test_uniform_dimension(dataLst: list, dataD... |
# Databricks notebook source
from pyspark.sql import DataFrame
from pyspark.sql.types import StructType, IntegerType
from typing import List
import re
from pyspark.sql.functions import col, lit
import pyspark.sql.functions as F
# COMMAND ----------
def get_new_run_id(asset_name: str, run_id_field: str) -> int:
'''... |
import numpy as np
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as manim
from scipy.interpolate import griddata
from kNN__utils import *
class kNNClass(Distance):
def __init__(self, k=1):
super(kNNClass, self).__init__()
self._k = k
s... |
"""A contents manager that combine multiple content managers."""
# Copyright (c) IPython Development Team.
# (c) EGI Foundation
# Distributed under the terms of the Modified BSD License.
import os.path
from traitlets.traitlets import List, Unicode, Dict
from traitlets import import_item
from notebook.servi... |
"""Pycnophylactic Interpolation (contributed by @danlewis85)."""
# https://github.com/danlewis85/pycno/
import geopandas as gpd
import numpy as np
import pandas as pd
import rasterio
from numpy import (
absolute,
apply_along_axis,
asarray,
convolve,
copy,
nan,
nanmax,
nanmean,
nansu... |
from re import escape
from pyrogram.types.bots_and_keyboards.inline_keyboard_button import InlineKeyboardButton
from pyrogram.types.bots_and_keyboards.inline_keyboard_markup import InlineKeyboardMarkup
from pyrogram.types.messages_and_media import message
from nksama import bot
from nksama.plugins.helpers import call_b... |
import argparse
import bs4 as bs
import requests
import re
from time import sleep
from random import randint
from datetime import datetime
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36' +
'(KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
}
def utf_encoder(input_raw):
i... |
# Copyright (c) 2018 Trail of Bits, 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 ... |
#Clustering and transition counts for multiple PDB files
import pandas as pd
import numpy as np
import multiprocessing.dummy as mp
import matplotlib.pyplot as plt
import seaborn as sns
import imageio
import os
import PDB_Torsion_Angle_Calculator as tor_calc
import MD_PCA_Clustering as md_pca
import Gaussian_Mixture_Clu... |
#!/usr/bin/env python
#
# Copyright 2010 <NAME>, <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 la... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
#
# TODO: This file is unused and therefore untested and quite broken.
# It was work-in-progress to support monitoring Debian based on patch
# files instead of commits.
import os
import re
from datetime import datetime
import git
import Util.Con... |
# -*- coding: utf-8 -*-
"""
Native xdoctest interface to the collecting, executing, and summarizing the
results of running doctests. This is an alternative to running through pytest.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from xdoctest import dynamic_analysis as dynamic
f... |
# coding: utf-8
import argparse
import os.path
import shutil
import struct
import sys
import time
import zlib
import ctypes
import ctypes.wintypes as wintypes
import pathlib
import tkinter
import tkinter.messagebox
__version__ = "2.1.0"
USER_SOURCE_ID = 200
USER_COMMAND_ID = 201
RT_RCDATA = 10
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2016, NetApp, Inc
# 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
ANSIBLE_METADATA = {"metadata_version": "1.1",
"sta... |
'''
## Train ##
# Code to train Deep Q Network on OpenAI Gym environments
@author: <NAME> (<EMAIL>)
'''
import os
import sys
import argparse
import gym
import tensorflow as tf
import numpy as np
import time
import random
from utils.utils import preprocess_image, reset_env_and_state_buffer
from utils.... |
# http://www.bruunisejs.dk/PythonHacks/rstFiles/200%20PythonHacks.html
'''Cubic splines are used as yield curves.
Most textbooks, eg [Ralston]_ and [Press & all]_ on numerical mathematics talks
about the natural splines.
The following code is inspired by [Kiusalaas]_ allthough the coding follow my
my own derivation.
... |
from parser import Bvh
import numpy as np
import matplotlib.pyplot as plt
import sys
from mpl_toolkits.mplot3d import Axes3D
def _separate_angles(frames, joints, joints_saved_channels):
frame_i = 0
joints_saved_angles = {}
get_channels = []
for joint in joints:
_saved_channels = joints_saved_c... |
import random
from scipy.spatial.distance import squareform, pdist
import numpy as np
from sklearn import linear_model
import gibbs
from sklearn.neighbors import NearestNeighbors
from vae_ld.learning_dynamics import logger
class TwoNN:
""" Implementation of the ID estimator TwoNN from [1]
[1] Estimating the... |
import socket
import selectors
from io import BytesIO
import types
import struct
from pathlib import Path
import os
home = str(Path.home())
print("Home Directory: %s"%(home))
store_dir = home + "/rocket_data"
cmd = "mkdir " + store_dir
os.system(cmd)
SERVER_IP = ''
SERVER_VID_PORT = 5000
SERVER_TELEM_PORT = 5001
vid... |
"""
=============
testapp.tests
=============
Tests for Flask-And-Redis extension and for Comments app.
"""
from unittest import TestCase
import flask_redis
import redis as redis_py
from flask import Flask, url_for
from flask_redis import Redis
from flask_testing import TestCase as FlaskTestCase
from nose.plugins.a... |
import requests
class OpenshiftRestApi(object):
"""A class to simply Openshift API"""
DEFAULT_CONNECT_TIMEOUT = 5
DEFAULT_READ_TIMEOUT = 15
def __init__(self,
host='https://127.0.0.1',
headers=None,
verify_ssl=True):
self.api_host = host
... |
__author__ = 'gpipperr'
import datetime, time
import glob, filecmp, ntpath, shutil
import os, errno, sys, getopt
import hashlib
import subprocess
import io
import cx_Oracle
import locale
import configparser
# get FileType
def getFileType(file, command, magicFilePath):
# magicFilePath
result = "-2"
# Comm... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# *AIPND/ImageClassifierApp/predict.py
#
# reads in an image and a checkpoint then prints the most likely image class
# and it's associated probability.
# specs :
# The script reads in an image and a checkpoint to print the most likely image class & probaility
# Allow use... |
import time
import csv
import re
import datetime
# default timeout after 5 minutes (300s)
TIMEOUT = 300
# default number of intro points is currently 3
NUM_OF_INTRO_POINTS = 3
from connection.utils import establish_connection
from stem.control import EventType
from circuitAnalyzer import circCallback
from logAnalyze... |
import numpy as np
import cv2
# Identify pixels above the threshold
# Threshold of RGB > 160 does a nice job of identifying ground pixels only
def color_thresh(img, rgb_thresh=(160, 160, 160)):
# Create an array of zeros same xy size as img, but single channel
color_select = np.zeros_like(img[:,:,0])
# Req... |
import argparse
import math
import time
import torch
import torch.nn as nn
from torch.autograd import Variable
import random
import preprocess_data
from model import model
from torch import optim
from matplotlib import pyplot as plt
import numpy as np
import shutil
parser = argparse.ArgumentParser(description='PyTorc... |
"""Yea test class."""
import configparser
import itertools
import json
import os
import pathlib
import subprocess
import sys
import time
import requests
from yea import testcfg, testspec
def run_command(cmd_list, timeout=None, env=None):
env = env or os.environ
timeout = timeout or 300
print("INFO: RUN... |
import torch
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
from torch.distributions import Categorical
import networkx as nx
from graphgen.model import create_model
from utils import load_model, get_model_attribute
from dfscode.dfs_wrapper import graph_from_df... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Cloudera, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LIC... |
#
# Copyright (C) 2019 GreenWaves Technologies
#
# 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 agree... |
"""Example processing Bruker ODNP data and calcualting hydration parameters"""
import sys
import os
import copy
import numpy as np
sys.path.append("..")
import dnplab
# directory of base folder containing the numbered folders listed below
directory = "..topspin"
# folder number for p=0 point in ODNP set
folder_p0 =... |
"""
Functions for dealing with writing and tracking of files.
The most important part of this module is the backup mechanism.
Backups are identified by a (filepath, owner) pair--where owner is an
arbitraty string identifying the test component responsible for the file,
specifically its cleanup.
preserve() does the ba... |
""" Dependency: Crypto """
from Crypto import Random
from Crypto.Hash import MD5, SHA, SHA256, SHA512, HMAC
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from jkspy.helpers import writeFile, readFile
def randbytes(length):
return Random.new().read(length)
HASH_ALGORITHMS = { 'MD5':MD5,
'SHA':SH... |
# -*- coding:utf-8 -*-
# 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 "Lic... |
#!/usr/bin/python2.4
# Copyright 2009, Google 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 list of... |
import streamlit as st
import pandas as pd
from wordcloud import WordCloud
import spacy
import es_core_news_lg
import matplotlib.pyplot as plt
import unicodedata
from yellowbrick.text import FreqDistVisualizer
from sklearn.feature_extraction.text import CountVectorizer
import webbrowser
import os
from data_acquisition... |
#!/usr/bin/env python
"""Computes the raw detections using the DPM.
Additionally, estimates 3D pose for each detection."""
import itertools
import os
import argparse
import logging
import math
from collections import namedtuple
from nyc3dcars import SESSION, Photo, Detection, Model, VehicleType, IMAGE_DIR
from sq... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Dexciss Technology and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.model.naming import make_autoname
import json
# from erpn... |
"""
Copyright (c) 2020 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WI... |
from pathlib import Path
from typing import Any, Iterable, Mapping, Optional, Sequence, Tuple
from attr import attrib, attrs
from attr.validators import instance_of
from immutablecollections.converter_utils import _to_tuple
from vistautils.parameters import Parameters
from vistautils.scripts import downsample_key_val... |
""" partial code adapted from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix """
import torch
import torch.nn as nn
import torch.nn.init as init
from .sync_batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, DataParallelWithCallback
from .MSSSIM import msssim
class Generator(nn.Module):
... |
"""
Create classes for running on multiple threads
20160323 <NAME>
"""
try:
from Queue import Queue, Empty, Full
except:
from queue import Queue, Empty, Full
import logging
import sys
import threading
from time import time as _time
import numpy as np
class DateQueue_Threading(Queue):
"""
DateQueue... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.