text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket, sys, types, getopt
languageNames = {'de':'German',
'en':'English',
'en_US':'US English',
'tib':'Tibetan'}
class MaryClient:
specificationVersion = "0.1"
"""Python implementation of a ... |
from maslite import Agent, AgentMessage
from collections import namedtuple
__description__ = """The scheduling demo presented in <NAME>'s PhD thesis (https://goo.gl/YbHVzi).
"""
class Order(AgentMessage):
def __init__(self, sender, receiver, order_items):
"""
:param sender: Agent class or Agent u... |
# Copyright (c) 2016-2021, <NAME>
# All rights reserved.
#
# 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... |
from collections import OrderedDict
import json
from enum.enum import Enum
from ValidateStrings import getUnicode, getStr
from utils.DictPrint import dict2Str
class Order(Enum):
ASC,DESC=False,True
__author__ = 'jgarc'
class InfoTableException(Exception):
pass
class InfoRow():
def __init__(self):
... |
""" Support level3 operator test cases.
"""
import tvm
import numpy as np
from tvm import relay
from tvm.relay.ir_pass import infer_type
from tvm.relay.ir_builder import IRBuilder, func_type
from tvm.relay.env import Environment
def test_unary_identity():
for op in [relay.zeros_like, relay.ones_like]:
ib ... |
from __future__ import absolute_import
from __future__ import unicode_literals
from os import getcwd
from sys import stdout
from re import escape as re_escape
from uuid import uuid1
from locale import getpreferredencoding
from codecs import getwriter
try:
from hashlib import md5
except ImportError:
import md5
... |
import torch
from torch.nn import functional as F
from .main_loop_modules import RDL
def ce_forward(model, x, y, *args, **kwargs):
return F.cross_entropy(model(x)[1], y, reduction="mean"), torch.tensor(0)
def equiv_transfer_forward(model, x, y, teacher_model, config=None):
b = x.shape[0]
x = x.reshape(... |
"""
仅支持224的图像输入
参数:通道数最宽64,空间通过两个大卷积降维到52
最好调一调,没有res结构,网络不宜过宽过深,空间上应该添加更多卷积,卷到足够小再avgpool到1x1
毕竟将224*224*3 的特征 ===映射===> 2*3 的仿射矩阵;
目前通道数为:3-64-32-(32*52*52)-32-6, 通道设计成bottleneck那样较好,节省参数,现在是哥窄口瓶子
空间采样:224--conv-->218--max-->109--conv-->105--max-->52
显然卷积核感受野较小(18),最好保证最后的空间感受野覆盖224区域内一个人的大小
所以该模块网络结构比较僵硬,transfer... |
import cv2 as cv2
import imutils
import numpy as np
import math
import linemodel
import controlstepper
# define names of each possible ArUco tag OpenCV supports
# noinspection PyUnresolvedReferences
ARUCO_DICT = {
"DICT_4X4_50": cv2.aruco.DICT_4X4_50,
"DICT_4X4_100": cv2.aruco.DICT_4X4_100,
"DICT_4X4_250"... |
'''
Copyright (c) 2020 by <NAME>, <EMAIL>
Copyright (c) 2013 by JustAMan at GitHub
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 rig... |
import openpyxl
from openpyxl.utils import get_column_letter
import re
from SubjestClass import *
from DataBase import Schedule
from utils import translate_weekday
import UserClass
from threading import *
from time import time, sleep
import os
GroupList = []
subjects = {}
multisubjects = {}
exams = []
def Parser_T... |
"""
Node classification Het Trainer Implementation
"""
from . import register_trainer
from .base import BaseNodeClassificationHetTrainer, EarlyStopping
import torch
from torch.optim.lr_scheduler import (
StepLR,
MultiStepLR,
ExponentialLR,
ReduceLROnPlateau,
)
import torch.nn.functional as F
from ..mo... |
#!/usr/bin/env python
from datetime import datetime
import multiprocessing
from ratelimiter import RateLimiter
import requests
import signal
import sys
import time
import dill
from six.moves import queue
import stopit
from ada import const
from ada import events
from ada import log
from os import environ as env
# Im... |
# coding: utf-8
import os
from math import log
import pickle
from collections import defaultdict, Counter
import numpy as np
from scipy.optimize import curve_fit
from .base import NeighborsBasedMethod
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(... |
import numpy as np
from bathy_smoother import LP_bathy_tools
from bathy_smoother import LP_tools
from bathy_smoother import bathy_tools
import matplotlib.pyplot as plt
# This code is adapted from the matlab code
# "LP Bathymetry" by <NAME>
# http://drobilica.irb.hr/~mathieu/Bathymetry/index.html
# For a description o... |
from urllib.parse import urljoin
import logging # pylint: disable=C0302
from flask import redirect
from flask_restx import Resource, Namespace, fields, reqparse
from flask_restx import resource
from src.queries.get_tracks import get_tracks
from src.queries.get_track_user_creator_node import get_track_user_creator_node... |
#!/usr/bin/env python
#encode=utf-8
#vim: tabstop=4 shiftwidth=4 softtabstop=4
#Created on 2013-8-17
#Copyright 2013 <NAME>
import inspect
import logging
import sys
import uuid
from eventlet import greenpool
from eventlet import pools
from eventlet import semaphore
from glance.rpc import common as... |
import click
import requests
import grequests
import math
from urlparse import urlparse
from functools import partial
from tabulate import tabulate
import csv
@click.command()
@click.pass_obj
@click.option('--limit', '-l', default=50, help='Limit results. Set to 0 for all.')
@click.option('--pretty-print', '-pp', is_... |
#----------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#------------------------------------------------------------------... |
"""Utilities for tasks
TODOs:
1. 2019.04.16-jef: A better structure for this and 'tasks' module would be
to make a 'tasks' subpackage folder, put 'tasks' in __init__.py, and put
this file into a new file there called 'utils'.
"""
import os
import time
from io import BytesIO
from typing import Dict, List, ... |
import os
import numpy as np
import pandas as pd
from collections import OrderedDict
from scipy.stats import rankdata, gumbel_r
from scipy import interpolate
import joblib
import json
from . import (
COMPOUNDS_FILENAME,
COMPOUND_IDENTIFIER_COLUMN,
SMILES_COLUMN,
VALUES_FILENAME,
VALUES_COLUMN,
... |
import copy
import functools
import itertools
import json
import operator
import os
import random
from typing import Optional, List, Tuple, Set, NamedTuple, Dict
import numpy as np
from PythonExtras import file_tools
from Siamese.data_types import PatchDesc, SupportSetDesc, TupleInt, CoordMap, RandomSetSampleDesc, SH... |
#!/usr/bin/python
import numpy as np
import sys
import json
USE_TF_FB = False
if USE_TF_FB:
import tensorflow as tf
with open("MFCC_params.json", "r") as f:
params = json.load(f)
with open("MFCC_params.h", "w") as f:
for k, v in params.items():
f.write("#define\t{:16}\t{}\n".format(k, int(v) if k != "PREEMP_FACTO... |
import argparse
import json
import os
import pathlib
import re
from dataclasses import dataclass, field
def dataset_subdataset_name_format_check(val_str):
regex = re.compile(r"^[^:]*:[^:]*$")
if (val_str is not None) and (not regex.search(val_str)):
raise argparse.ArgumentTypeError("dataset_subdataset... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy import coordinates
from datetime import datetime
from astropy.time import Time
from astropy.table import Table
import os
# os.environ['SIRAHPIPE_DIR'] = '/home/mi/ztf/sirah_target_pipe'
class Broker():
def... |
# Copyright (c) 2019 Sony Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
#!/usr/bin/env python
from __future__ import (absolute_import, division, print_function)
from queue import Queue
from subprocess import Popen, PIPE
import code
import errno
import fcntl
import logging
import os
import struct
import sys
import termios
import threading
W3MIMGDISPLAY_ENV = "W3MIMGDISPLAY_PATH"
W3MIMGDIS... |
# -*- coding: utf-8 -*-
import numpy as np
from GalaxyDynamicsFromVc import units
#%%
class Potential:
pass
class DM_halo(Potential):
def __init__(self, Mvir_in_1e11Msun, cvir, Delta_vir=200.0, h_cosmo=0.678):
self._Mvir_in_1e11Msun = Mvir_in_1e11Msun
self._Mvir_in_Msun = self.Mvir_in_1e11... |
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 25, 'legend.handlelength' : 1.5
, 'legend.markerscale': 1.})
plt.rc('xtick', labelsize=25)
plt.rc('ytick', labelsize=25)
## -2 and -3 slopes in the loglog space
ks = np.array([1.e-3,1])
Es2 = .2e-4*(ks**(-2))
Es3 = .5e-6*(ks**... |
import os
import math
import IPython
import numpy as np
import torch
import shutil
from torch.autograd import Variable
INPUT = 'input'
OUTPUT = 'output'
CONV3X3 = 'conv3x3-bn-relu'
CONV1X1 = 'conv1x1-bn-relu'
MAXPOOL3X3 = 'maxpool3x3'
NUM_VERTICES = 7
MAX_EDGES = 9
EDGE_SPOTS = NUM_VERTICES * (NUM_VERTICES - 1) / 2 ... |
#!/usr/bin/env python3
import click
import numpy as np
from cause.preprocessor import RawStatsLoader
from cause.preprocessor import RawSampleStatsLoader
from cause.preprocessor import FeatureExtractor
from cause.preprocessor import DatasetCreator
from cause.preprocessor import SamplesDatasetCreator
from cause.preproce... |
#!/usr/bin/env python
# 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, Versio... |
import numpy as np
import os
import matplotlib.pyplot as plt
import PIL.Image as Image
import torch
from sklearn.cluster import MiniBatchKMeans, KMeans
from sklearn import decomposition
from scipy.sparse import csr_matrix
import torchvision
import torch.nn as nn
from torchvision import transforms
import torch.nn.functi... |
'''
Basic test scene made using Chelone
'''
import random
import math
import json
import tkinter as tk
from time import time
import sound
from Chelone import init, Sprite, SpriteLoader, check_keys
from BoxPhys import get_collision_displacement
chelone = None
playsound = lambda a: 0
sound_finished = lambda a: Fal... |
#!/usr/bin/env python3
import os
import functools
import subprocess
import numpy as np
import pandas as pd
from multiprocessing import Pool
from sklearn.model_selection import train_test_split
import deepmp.utils as ut
import deepmp.merge_h5s as mh5
names_all = ['chrom', 'pos', 'strand', 'pos_in_strand', 'readname... |
"""Executor utility module for locally scheduled tasks."""
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from enum import Enum
import _io
from os.path import abspath, join
from psutil import Process, NoSuchProcess, TimeoutExpired, wait_procs
from subprocess import Popen
from uuid ... |
# patent search attempt 2
# uses TF-IDF and sematch keyword comparison
INPUT_WEEKS = 1
NUM_KEYWORDS = 10 # how many keywords to take from TF-IDF
NUM_SYNONYMS = 5 # how many keywords to take from TF-IDF
PREVIEW_MAX_WORDS = 50 # how long the search result text should be
import time
import bz2
import pickle
import _p... |
from sklearn.linear_model import LogisticRegression
import os
import pandas as pd
import mord as m
import numpy as np
from scipy.stats import *
def convertOrdinalCategory(dataset, covariates, treatment, nbrOfQuantile):
bin_labels = []
for i in range(1, nbrOfQuantile + 1):
bin_labels.append(i)
... |
"""
Ingest flight scheduled from REST API into Google BigQuery using Cloud Dataflow (Apache Beam).
Author:
Contact:
license: GPL v3 - PLEASE REFER TO DEB/LICENSE FILE
"""
import argparse
import json
import os
import sys
import typing
from copy import copy
from datetime import datetime, timedelta
from time import sl... |
"""
Some custom distance metrics and similarity measures.
"""
import numpy as np
from numba import njit, float64, int64
from numba.types import Tuple
@njit(fastmath=True)
def distance_norm_3tensors(x, y, shape=(1, 1, 1), norm_type=(2, 2, 2)):
"""
Distance between two 3rd order (rank 3) tensors under the speci... |
import logging
from enum import Enum
from pathlib import Path
from typing import List, Literal, Optional
from pydantic import Field, NonNegativeInt, PositiveInt
from pydantic.class_validators import validator
from hydrolib.core.io.ini.models import INIBasedModel, INIGeneral, INIModel
from hydrolib.core.io.ini.util im... |
from inspect import signature
from types import FunctionType
import numpy as np
from pyqtgraph import IsocurveItem
import data_slicer.utilities as util
class ModelError(Exception) :
""" Base class for :class:`Model <data_slicer.model.Model>` related
errors.
"""
pass
class UndefinedModelError(Model... |
import numpy as np
import random
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from sklearn.linear_model import LogisticRegression
from lib.graph import *
from lib.classify import Classifier, read_node_label
from lib.grarep import GraRep
from lib import tadw
from lib import node2vec
from lib impor... |
import random
import subprocess
import sys
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
try:
import pygame
except:
install("pygame")
import pygame
pygame.font.init()
s_width = 800
s_height = 700
play_width = 300 # this / 10 = width
play_height = ... |
#<NAME>
#Summer 2020
#Adapted from
#Generated code -- CC0 -- No Rights Reserved -- http://www.redblobgames.com/grids/hexagons/
#IMPORTS
import collections
import math
#Define the x y point for pixels
Point = collections.namedtuple("Point", ["x", "y"])
Axial_Point = collections.namedtuple("Axial_Point", ['q', 'r'])
... |
"""
Sklearn models
--------------
Group of utitilies to explore the application of different perturbations and
sklearn models.
"""
import copy
import multiprocessing
from joblib import Parallel, delayed
import time
class Sklearn_permutation_test:
"""The class to operate perturbation tests using sklearn models ... |
'''Tensorflow model for speech recognition'''
import tensorflow as tf
from deepsphinx.vocab import VOCAB_SIZE, VOCAB_TO_INT
from deepsphinx.utils import FLAGS
from deepsphinx.lm import LMCellWrapper
from deepsphinx.attention import BahdanauAttentionCutoff
def encoding_layer(
input_lengths,
rnn_inputs,
... |
import io
import json
import os
from datetime import date
from datetime import datetime
from datetime import time
from types import MappingProxyType
import pytest
import tomlkit
from tomlkit import dump
from tomlkit import dumps
from tomlkit import load
from tomlkit import loads
from tomlkit import parse
from tomlk... |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import numpy as np
import pybullet as p
import pybullet_data
import time
import math
from sklearn.preprocessing import normalize
## Hyper Params
MAX_EPISODE_LEN = 150 # Number of steps for one training episode
REWARD_FACTOR = 10
BOUND_ANGLE... |
# standard imports
import multiprocessing
import os
import sys
# third parties from imports
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
# libraries import
from common.backoff import execute_request
from common.exceptions import manage_generic_exception
from commands.... |
from __future__ import print_function
from collections import defaultdict
import unittest
from aoc_utils.data import data_text
from aoc_utils.char_map import CharMap
from aoc_utils.geometry import add_coordinates
class TestRouteParser(unittest.TestCase):
def test_simple_route(self):
example = '^WNE$'
... |
#
# This file is part of Bakefile (http://bakefile.org)
#
# Copyright (C) 2008-2013 <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 limita... |
# from https://github.com/eriklindernoren/Keras-GAN/blob/master/dcgan/dcgan.py
from __future__ import print_function, division
#from keras.datasets import mnist
from keras.layers import Input, Dense, Reshape, Flatten, Dropout
from keras.layers import BatchNormalization, Activation, ZeroPadding2D
from keras.layers.adva... |
import logging
from pathlib import Path
from typing import List, Mapping
from mopidy import backend
from mopidy.models import Album, Artist, Image, Ref, SearchResult, Track
from . import Extension
from .index_files import AlbumIndex, AlbumIndexTrack, StationIndex
from .hash import make_hash
from .search_index import ... |
"""
register a micro service
"""
import datetime
import time
import boto3
CLIENT = boto3.client('servicediscovery')
def list_namespaces(namespace_name):
"""
list namespaces
:param namespace_name:
:return:
"""
namespace_id = None
list_ns_resp = CLIENT.list_namespaces()
try:
... |
"""Huggingface datasets FLEET challenge dataset script."""
import logging
import json
import numpy as np
from hydra.utils import instantiate
from fewshot.utils import get_hash
import datasets
from fewshot.challenges import registry
from fewshot.utils import ExampleId
logger = logging.getLogger('datasets.challenge')
_... |
import binascii
import datetime
import glob
import hashlib
import json
import logging
import subprocess
import time
from multiprocessing import Process, Lock, Manager
from os import path
import pygame
from flask import Flask, render_template, request
import settings
import util
from rfid import RFID
logger = logging... |
import cv2
import numpy as np
#cwd(),dir()
import os
#ocr
from PIL import Image
import pytesseract
import argparse
#small object removal
from skimage import morphology
#
import matplotlib.pyplot as plt
from matplotlib import interactive
def Show(img,title="image"):
#comment line below in and... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from progressor import progress_map
import csv
import sys
import json
import numpy as np
from sklearn.metrics import roc_auc_score
from sklearn.linear_model import LogisticRegression
class Explanati... |
import argparse
import logging
import time
import cv2
import numpy as np
import math
from tf_pose.estimator import TfPoseEstimator
from tf_pose.networks import get_graph_path, model_wh
logger = logging.getLogger('TfPoseEstimator-WebCam')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging... |
# __BEGIN_LICENSE__
# Copyright (c) 2015, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All rights reserved.
#
# The xGDS platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance... |
#!/usr/bin/env python3
# Copyright 2017 The Imaging Source Europe GmbH
#
# 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 a... |
"""Define Home Assistant-related functionality."""
import argparse
from dataclasses import dataclass
from typing import Any, Dict, Optional, Union
from ecowitt2mqtt.const import (
DATA_POINT_CO2,
DATA_POINT_DEWPOINT,
DATA_POINT_FEELSLIKE,
DATA_POINT_GLOB_BAROM,
DATA_POINT_GLOB_BATT,
DATA_POINT_... |
#!/usr/bin/env pyton
# -*- coding: utf-8 -*-
"""
This module is written for the purposes of elements modeling for accelerator:
1: manually define magnetic elements one by one and model the machine;
2: interpret lattice file (.lte file) to be modeled elements;
2: update (EPICS databases)/(EPICS PVs) with ne... |
"""
This is the main class for our neuralRisk application
Copyright 2016 Charis - <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 rig... |
import os
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import cv2
import sys
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from keras.models import Model
from keras.layers import *
from keras.optimizers import Adam
fr... |
from fer import FER
import matplotlib.pyplot as plt
import cv2
import json
import os
import random as rand
from pathlib import Path
DATA_PATH = "./"
# Unit Tests (there isn't much to test)
def test_output_format_cv():
model = DefaultCVModel(sample_rate=2, verbose=True)
model.OUTPUT_PATH = './output/'
prin... |
#!/usr/bin/env python
import glob
import os
import re
import shutil
import zipfile
import tarfile
import stat
import copy
import types
from subprocess import Popen
from servicemanager.service.smservice import SmMicroServiceStarter
from servicemanager.service.smjvmservice import SmJvmService, SmJvmServiceStarter
from ... |
"""
Copyright 2015, <NAME>.
All rights reserved.
Licensed under the BSD 3-clause License. See LICENSE.txt or
<http://opensource.org/licenses/BSD-3-Clause>.
"""
import unittest
try:
from unittest.mock import patch, MagicMock
except ImportError:
from mock import patch, MagicMock
from lib import quiz
from lib.fla... |
import matplotlib.pyplot as plt
import numpy as np
from tadlib.hitad.aligner import *
import cooler, itertools, sys
from neoloop.visualize.bigwig import plot_y_axis
class sigTrack(object):
def __init__(self, fil, res=25000, col=3, skiprows=0):
sig = {}
with open(fil, 'r') as source:
f... |
from __future__ import unicode_literals
from collections import defaultdict
from importlib import import_module
import errno
import os
import sys
from django.apps import apps
from django.conf import settings
from django.db.migrations.graph import MigrationGraph
from django.db.migrations.loader import MigrationLoader... |
# Copyright 2018-2021 the .NET Foundation
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This package contains the pywwt tests. This particular module contains some
infrastructure to help with the image-output tests, which can be pretty finicky.
"""
__all__ = ['assert_widget_image', 'wait_for_tes... |
from flask import Flask,jsonify,request
import os
import json
import codecs
import xlwt
from flask_apscheduler import APScheduler
import time
import random
import math
class Config(object):
JOBS=[
{
'id':'Backup-Daily',
'func':'__main__:Backup_Daily',
'args':(),
... |
import logging
import time
from urllib.parse import unquote as urldecode
from threading import Thread, Event
from flask_babel import gettext as _
from config import LOG_NAME
logger = logging.getLogger(LOG_NAME)
class TaskRunnerInitError(RuntimeError):
pass
class TaskDaemon(Thread):
"""任务守护线程
"""
... |
# coding=utf-8
import matplotlib.pyplot as plt
import tensorflow as tf
import multiprocessing
import numpy as np
import threading
import shutil
import gym
import os
from helpers import json_helper
CKP_DIR = './checkpoint/'
LOG_DIR = './logs'
ENV_NAME = "CartPole-v0"
GLOBAL_ENV = gym.make(ENV_NAME)
STATE_SPACE, ACT... |
import unittest
import riemann
from riemann import utils
from riemann.tx import sapling
from riemann.tests.tx.helpers import sapling_helpers
class SaplingTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def setUp(self):
riemann.select_networ... |
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse
from mpl_toolkits.mplot3d import Axes3D, axes3d
import matplotlib.animation as animation
def anim(j):
Mercury.PLT._offsets3d = Mercury.CRD[j]
Venus.PLT._offsets3d = Venus.CRD[j... |
# -*- coding: utf-8 -*-
"""
@create: 2019-05-30 22:17:18.
@author: ppolxda
@desc:
"""
import six
import datetime
from functools import partial
from .errors import InputError
SUB_OP_FUNC = ['$addToSet', '$each']
OP_FUNCS = ['$max', '$min', '$inc', '$currentDate',
'$unset', '$set', '$setOnInsert', '$rename... |
import numpy as np
import copy
from sklearn.preprocessing import MinMaxScaler
from itertools import product as iter_prod
from functions.sub_actuarial import get_CFs_vectorized
def prep_data(x, scale_age = (0,120), scale_freq = (0,1)):
'''
Prepare the dataframe such that it represents the desired format of ... |
import os
import struct
import collections
import subprocess
import mmap
import portio
iopl_flag = False
root_flag = False
PCIConfigHeader = collections.namedtuple('PCIConfigHeader',
['pcie_loc',
'vendor_id',
... |
# -*- coding: utf-8 -*-
# This code is under the GNU Affero General Public License
# http://www.gnu.org/licenses/agpl-3.0.html
""" Administration frontend for courses and related areas
"""
import datetime
import _strptime # import should prevent thread import blocking issues
# ask Google about: ... |
#!/usr/bin/python3
# IMPORTS
import rpm
from datetime import datetime
import sys
# CLASSES
class Info:
name = "Rpm Query"
version = "0.1.0"
description = (
"Description:\n"
" Utility to get basic info about installed rpm packages in both human and machine readable format.\n"
)
... |
"Useful utilities"
from functools import lru_cache
from .constants import NROWS, START_7AD, START_8AD, FIRST_RUN
from .db import app_exec, dq_exec
from .model import all_fields
class EndOfDataException(Exception):
"We've hit the end, captain!"
pass
def field_desc(field):
"Given short name (e.g. plikecou... |
import requests, json
import spotipy
import datetime
import psycopg2
import base64
#Authorization of application with spotify
#Return auth url
def app_authorization(client_id, redirect_uri, scope, state, spotify_auth_url):
url_args = "client_id=" + client_id + "&response_type=code&redirect_uri=" + redirect_uri + "... |
import math
from pathlib import Path
import os
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel
import torch.distributed as dist
from torch.optim.lr_scheduler import LinearLR, MultiStepLR, SequentialLR
from torch.utils.data import RandomSampler, Da... |
#!/usr/bin/env python
# encoding: utf-8
# pocket-random.py -- randomly pick up some items from Pocket
# Copyright (c) 2016 <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 re... |
import pylab
def welcomeAndInstructions():
'''
Show a welcome message and instructions.
'''
print("Welcome to Music Database!")
print("s: load songs\na: load artists\nt: load top 10\nl: load sales\np: print a table – songs, artists, top10\n\
q: query database - songs, artists\nc: sales chart\nw: write ... |
from collections import namedtuple
from pathlib import Path
from typing import Dict
from typing import List
from typing import Tuple
import cftime
import csv
import datetime
import logging
import netCDF4 as nc
import numpy as np
import tempfile
import xml.etree.ElementTree as ET
NAMESPACES = {"pi": "http://www.wldel... |
#!/usr/bin/env python
"""Control panel system level (SL) temperature control
Author: <NAME>
Date created: 2009-10-14
Date last modified: 2019-05-21
"""
import wx,wx3_compatibility
from temperature import temperature
from oasis_chiller import oasis_chiller as oasis
from EditableControls import ComboBox,TextCtrl
from log... |
# Software License Agreement (BSD License)
#
# Copyright (C) 2012, <NAME>
# 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
# ... |
#!/usr/bin/env python3
########################################################################################################################
# ASTgen
# Created by <NAME>
# This code reads in the location of AstropathPaths.csv and Astrodef.csv <mpath>
# and generates SlideIDs for all specimens within... |
from threading import Thread, Event, Lock
import queue
import inspect
import struct
import socket
import select
import os
import time
import textwrap
from messages import ProtocolMessage, IntroductionMessage
from messages import MessageMessage, ErrorMessage
### -------------------------------------------------------... |
import re
import sys
import subprocess
import os
import platform
import argparse
import pandas as pd
from docx import Document
from docx.shared import Inches, Cm, Mm, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.table import WD_TABLE_DIRECTION, WD_TABLE_ALIGN... |
import os
import numpy as np
import torch
import torch.utils.data
from torchvision.transforms.transforms import RandomCrop, ToTensor, Normalize, Compose
import random
import math
import cv2
#from converter import make_hm_regr, pred2box
def order_p1_p2(x1, y1, x2, y2):
if x1 > x2:
return x2, y2, x1, y1
... |
import json
import cv2
import numpy as np
def json_back_to_boxes(vid_dir, det_name):
total_forceps_boxes = []
with open(vid_dir+det_name) as json_file:
data = json.load(json_file)
for frame, frame_detections in data.items():
forceps_boxes = []
for detections in frame_de... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import glob
import h5py
import copy
import math
import torch
import numpy as np
import torch.nn as nn
from util import quat2mat
import torch.nn.functional as F
from torch.autograd import Variable
from ops.transform_functions import PCRNetTransform as ... |
#!/usr/bin/env python
"""
Simulate the simplifie Mouse environment.
Each episode is trying to put the cat in the middle of the image.
"""
# Core Library
import logging
from utils.logging_level import LOGGING_LEVEL
logging.basicConfig(level=LOGGING_LEVEL)
log = logging.getLogger('mouse_env')
log.setLevel(LOGGING_LEVEL... |
import cv2
import os
import numpy as np
from feature_extraction import features
from tkinter import *
from tkinter.ttk import *
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from tkinter import font
from PIL import Image, ImageTk
import pandas as pd
from mat... |
from argparse import ArgumentParser
from collections import Counter
from io import StringIO
import logging
import os
import pickle
from multiprocessing import Pool, Process, cpu_count
import sys
from tempfile import NamedTemporaryFile
from intent.igt.grams import write_gram
from intent.igt.igtutils import rgp
from int... |
from functools import partial
from typing import Literal, Optional, Tuple
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter, MultipleLocator, FixedFormatter
from qutip import qfunc, wigner
from sync_calcs import spin_husimi_qfunc, spin_S_measure
t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.