text stringlengths 6.04k 39.5k |
|---|
import numpy as np
from random import choice
## Note: Non-smooth surfaces or bad triangulations may lead to non-spiral orderings of the vertices.
## Common issue in badly triangulated surfaces is that there exist some edges that belong to more than two triangles. In this
## case the mathematical definition of the spir... |
#!/usr/bin/env python3
from time import sleep
from typing import Any, AnyStr
import os
import json
import argparse
import datetime
import re
import urllib.parse
import requests
BASE_URL = "https://api.fanbox.cc/"
BASE_LOCAL_DIR = "./posts/"
BASE_LOCAL_PROFILE_DIR = "./profile/"
def save_json(data:Any, dir:str):
... |
#!/usr/bin/env python3
import sys, gzip, pickle, argparse
from pylca.pylca import LCA
from collections import defaultdict
def main():
parser = argparse.ArgumentParser(prog='ganon benchmark evaluation', conflict_handler="resolve", add_help=True)
parser.add_argument('-k', metavar='<ranks>', required=False, dest... |
# Import TensorFlow >= 1.10 and enable eager execution
import tensorflow as tf
tf.enable_eager_execution()
import os
import time
import numpy as np
import matplotlib.pyplot as plt
# path_to_zip = tf.keras.utils.get_file('facades.tar.gz', cache_subdir=os.path.abspath('.'), extract=True,
# ... |
# coding: utf-8
__author__ = 'ZFTurbo: https://kaggle.com/zfturbo'
import datetime
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.cross_validation import KFold
from sklearn.metrics import roc_auc_score
from scipy.io import loadmat
from operator import itemgetter
import random
import os
impor... |
# -*- coding: utf-8 -*-
r"""
Torsion subgroups of elliptic curves over number fields (including `\QQ`)
AUTHORS:
- <NAME>: original implementation over `\QQ`
- <NAME>: original implementation over number fields
- <NAME>: rewrote p-primary part to use division
polynomials, added some features, unified Number Field ... |
#! /usr/bin/env python3
"""Working with groups and users in vk"""
import sys
import json
import os
import time
from .vkreq import apply_vk_method, Executor
from ..utils import exception_handler
def _mkdir_rec(*dir_chain):
"""Recursive mkdir. For example, use `_mkdir_rec('a', 'b', 'c')` to create
directory '... |
# -*- coding: utf-8 -*-
import copy
from typing import Union
import numpy as np
def temperature(
t: np.array,
fire_load_density_MJm2: float,
fire_hrr_density_MWm2: float,
room_length_m: float,
room_width_m: float,
fire_spread_rate_ms: float,
beam_location_heigh... |
# ------------------------------------------------------------
# Load libraries ---------------------------------------------
from typing import List
import sys
import os
from copy import deepcopy
import numpy as np
import pandas as pd
from itertools import product
from datetime import datetime
from timeit impor... |
# Copyright (c) 2021 - Jojo#7791
# Licensed under MIT
import asyncio
import logging
from contextlib import suppress
from datetime import datetime, timezone
from typing import Dict, List, Literal, Optional, Tuple, Union
import discord
from redbot.core import Config, commands
from redbot.core.bot import Red
from redbot... |
from math import pi
from collections import namedtuple
import scipy.signal
import torch
from e3nn import o3
from e3nn.o3 import FromS2Grid, ToS2Grid
def _find_peaks_2d(x):
iii = []
for i in range(x.shape[0]):
jj, _ = scipy.signal.find_peaks(x[i, :])
iii += [(i, j) for j in jj]
jjj = []
... |
# -*- coding: utf-8 -*-
"""Robust SVM solver implementation from the CVXOPT documentation
Taken verbatim from http://cvxopt.org/examples/mlbook/robsvm.html
Copyright 2004-2018, <NAME>, <NAME>, and <NAME>.
"""
from cvxopt import spmatrix, matrix, sparse, normal, mul, div, solvers, \
lapack, blas, base, misc, sqr... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Module for utility functions.
tcrdist2 authors UPDATED THE FOLLOWING CODE TO PYTHON 3
USING COMMIT e825c333f0f9a4eb02132e0bcf86f0dca9123114 (Jan 18, 2019)
ORIGINAL OLGA CODE CAN BE FOUND AT:
https://github.com/zsethna/OLGA
Copyright (C) 2018 <... |
"""gRPC broadcast thread"""
import abc
import logging
import multiprocessing as mp
import os
import queue
import signal
import threading
import time
from concurrent import futures
from functools import partial
import grpc
from grpc._channel import _Rendezvous
from loopchain import configure as conf, utils as util
fr... |
#!/usr/bin/python
# -*- coding: utf-8 -*
# log function
"""
:description:
common log related module
"""
from __future__ import print_function
__all__ = [
'debug', 'info', 'warn', 'critical',
'init_log_instance', 'set_log_level',
'ROTATION', 'INFINITE',
're_init_log_instance', 'get_inited_logger_na... |
from tkinter import *
from functools import partial
from datetime import *
try:
from functions import *
except ModuleNotFoundError:
error_window = Tk()
error_window.geometry('445x110+300+300')
error_window.minsize(445, 110)
error_window.maxsize(445, 110)
error_window.title('Modulo não encontrado... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# rule_engine/engine.py
#
# 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... |
# Copyright 2018 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
from mlgames.board import Board
import numpy as np
BOARD_SIZE = 9
STARTING_WALLS = 10
def a(arr):
return np.array(arr)
ALLOWED_PLAYER_MOVE_DIFFS = [
a([0, 1]),
a([1, 0]),
a([0, -1]),
a([-1, 0])
]
ONLY_ALLOWED_IF_PLAYER_INBETWEEN_DIFFS = [
a([0, 2]),
a([2, 0]),
a([0, -2]),
a([-2, 0])
]
ALLOWED_WALL_START_... |
from random import randint
from copy import copy
from itertools import product
import scene, ui
main_color = 'darkslategray'
stop_color = 'maroon'
class Block(scene.ShapeNode):
def __init__(self, row, clo):
super(Block,self).__init__()
self.x = row
self.y = clo
self.b_pos = [self.x, self.y]
sel... |
import sys,time,datetime,copy,subprocess,itertools,pickle,warnings
import numpy as np
import scipy as sp
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib as mpl
import scipy.sparse as spm
from .StatTool import Quasi_Newton,Bayesian_Smoothing
def Estimate_exp(Data,t,prior=[],opt=[]):
... |
from huobi.client.generic import GenericClient
#from huobi.client.account import AccountClient
from huobi.client.trade import TradeClient
from huobi.constant import *
from keys import *
from huobi.client.market import MarketClient
from huobi.utils import *
import requests
import datetime
import time
def trace_profit(b... |
import collections
import logging
from .. import models as tools_models
from ..loader import model as loader_models
from ..models import TreeModel, Item
from . import lib
from ...lib import MasterVersionType
from ... import style
from ...vendor import qtawesome
from ...vendor.Qt import QtCore
log = logging.getLogger... |
import time
import numpy as np
import scipy.integrate
import scipy.linalg
import ross
from ross.units import Q_, check_units
from .abs_defect import Defect
from .integrate_solver import Integrator
__all__ = [
"Rubbing",
]
class Rubbing(Defect):
"""Contains a rubbing model for applications on finite elemen... |
"""
αβ探索による、普通の固定深さの探索。
重いので3手が限界。
N手読み
- ルートノードを作成し、子への実現確率を計算。
- search(root, N, -inf, +inf)
search(node, d, alpha, beta):
- if d <= 1:
- return eval_children(node)
- node.pv = None
- nodeに対する合法手を列挙。
- 子ノードをすべて作成し、孫への実現確率を計算。
- このノードが詰みの時、return -inf
- 実現確率の高い子ノード順に、
- move
- alpha = max(alpha, -search(child,... |
import os
import zipfile as zf
from cryptography.fernet import Fernet as fn
import random
import string
import json
import time
ver_control = 0
software_name = 0
creator = 0
def globalVariable(ver="v0.0.4", soft_name="Project Ultra Backup", author="Anjal.P"):
global ver_control, software_name, creator
ver_c... |
import json
import logging
from flask import Blueprint, render_template, request, flash, redirect, url_for, abort
from flask_login import current_user, login_required
from thewarden.node.utils import (
dojo_add_hd,
dojo_auth,
dojo_status,
tor_request,
dojo_get_settings,
dojo_multiaddr,
dojo_... |
import os
import os.path
import random
import asyncio
import aiohttp
import discord
import json
import datetime
from discord import Game
from discord.ext import commands
from discord.ext.commands import Bot
from discord.utils import find
import cdobtserverdata
import cdobtuserdata
###################################... |
import math
import numpy as np
import torch
from torch import optim
from torch import nn
import torch.utils.data
from torch.nn import (
BatchNorm1d,
Dropout,
LeakyReLU,
Linear,
Module,
ReLU,
Sequential,
Sigmoid,
)
from torch.autograd import Variable
import warnings
from .data_sampler im... |
import GPy
import numpy as np
from GPy.inference.latent_function_inference.posterior import PosteriorExact as Posterior
from GPy.util.linalg import pdinv, dpotrs, tdot, dtrtrs, dpotri, symmetrify
from GPy.util import diag
from scipy import stats
log_2_pi = np.log(2*np.pi)
def __setattr_patch__(self, name, val):
#... |
import numpy as np
import pdb
# import spiking function
from spiking_ulils import label_encoder
from spiking_ulils import Conv2d, BatchNorm2d, Relu
from spiking_ulils import Flatten
from spiking_ulils import Linear
import argparse
parser = argparse.ArgumentParser()
# quantization level
parser.add_argument('--k', type... |
from urllib.request import urlopen
import sys
import re
import datetime
import json
#cat basket_10036_columns2.txt | cut -f2 | sed '1d' > basket_10036_columns3.txt
begin_time = datetime.datetime.now()
error_report = []
lost_columns = []
def get_input():
if len(sys.argv) > 2:
input_columns_file = sys.a... |
#-*-coding utf-8-*-
import asyncio
import json
import traceback
from pprint import pformat
from configparser import ConfigParser
from dynaconf import settings
from loguru import logger
from web3 import Web3, WebsocketProvider
from web3._utils.events import construct_event_topic_set, get_event_data
from web3.exceptions ... |
"""Tools to easily make multi voxel models"""
import numpy as np
from numpy.lib.stride_tricks import as_strided
from tqdm import tqdm
from dipy.reconst.ivim import BOUNDS, f_D_star_error, IvimFit
from dipy.core.ndindex import ndindex
from dipy.reconst.quick_squash import quick_squash as _squash
from dipy.reconst.bas... |
# ------------------------------------------
# CSWin Transformer
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# written By <NAME>
# ------------------------------------------
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
import warnings
f... |
import secrets
from typing import List
from asyncio import create_task
import re
from discord.ext.commands import Cog, Context
import discord
from lib.status_codes import StatusCodes as sc
from lib.pool_types import PoolType
from lib.config import logger, FAKE_GUILD_IDS
from src.auto_response import GuildAutoResponse... |
# -*- coding: utf-8 -*-
# sys
import json
import traceback
import os.path
import math
from datetime import datetime
# flask
from flask import Flask, request
from sqlalchemy import exc
from pushjack import GCMClient, APNSClient
# config
from config.config import _logging, db, platform_model_config, settings
logger =... |
"""
Unittest for MuellerMatrix class.
"""
import unittest
import numpy as np
from numpy.testing import assert_array_almost_equal
from crystalpy.polarization.MuellerMatrix import MuellerMatrix
def _generate_matrix():
matrix = np.asarray([[0.3259811941363535, 0.47517601596586845, 0.5518825026595213, 0.3096975897... |
#
# CanvasObject.py -- base class for shapes drawn on ginga canvases.
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import numpy as np
from collections import namedtuple
from ginga.misc import Callback, Bunch
from ginga import trcalc, colors
from . imp... |
import numpy as np
#Format layer name preventing collisions
def format_layer_name(name):
if type(name) is not str:
name = name.name
if "." in name:
splitname = name.split(".")[-1]
if "tf" in name or "tensorflow" in name:
splitname = splitname + "_tf"
return spli... |
import pprint
import copy
from collections import defaultdict
from itertools import groupby
from numpy import array
from six.moves import xrange, StringIO
from scrapely.extraction.pageobjects import AnnotationTag
from scrapely.extraction.regionextract import (
RecordExtractor, BasicTypeExtractor, RepeatedDataExt... |
# (C) Copyright 2014-2017 Hewlett Packard Enterprise Development LP
#
# 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 ap... |
import os
import re
import sys
import copy
import json
import time
import random
import xml.dom.minidom
import requests
import pyqrcode
import traceback
from . import config
from .exception import WeChatBotError
from .storage import Store, Cache
import logging
UNKNOWN = 'UNKNOWN'
SUCCESS = '200'
SCANNED = '201'
... |
# -*- coding: utf-8 -*-
# Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for the flash module."""
from __future__ import print_function
import os
import sys
import mock
from chromite.cl... |
#######################################################################
#
# Vali-XD-Skins Control for Dreambox/Enigma-2
# Coded by Vali (c)2009-2011
#
# This plugin is licensed under the Creative Commons
# Attribution-NonCommercial-ShareAlike 3.0 Unported License.
# To view a copy of this license, visit http:/... |
"""
An example that uses TensorRT's Python api to make inferences.
"""
import ctypes
import os
import shutil
import random
import argparse
import time
import cv2
import numpy as np
import pycuda.autoinit
import pycuda.driver as cuda
import tensorrt as trt
MAX_OUTPUT_BBOX_COUNT = 1000 #must match with 'MAX_OUTPUT_BBOX... |
#! charset UTF 8
from PyQt5 import QtWidgets, uic
from PyQt5 import QtGui
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QMainWindow, QDesktopWidget, QPushButton, QInputDialog, QLineEdit, QFileDialog, QAction
from PyQt5.QtGui import QPixmap, QIcon
from PyQt5.QtGui import *
from PyQt5.QtCore... |
import argparse
import tqdm
import os
import pickle as pkl
import scipy as sp
import torch
from pprint import pprint
import utils as ut
from torchvision import datasets, transforms
from model import Classifier, CD_Simu, Cycle_Cons, Encoder, Decoder, Discriminator
from unet_model_cond_warp import Cycle_Con... |
'''
Custom base classes for admin interface, for both the top-level admin page
and for inline forms.
'''
import logging
from django import template
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import helpers
from django.contrib.admin.exceptions import DisallowedModelAdmin... |
import pytest
from jikken import MultiStageExperiment
from jikken.database import ExperimentQuery, MultiStageExperimentQuery
from jikken.experiment import Experiment
@pytest.fixture()
def db_one_experiment(jikken_db, one_experiment):
_id = jikken_db.add(one_experiment)
yield jikken_db, _id
@pytest.fixture()... |
import argparse
import datetime as dt
import pickle
import csv
from operator import itemgetter
import gensim.models as models
import mlflow
from tqdm import tqdm
from .blocking import execute_blocking
from .utils import *
NGT_NOT_FOUND = ANNOY_NOT_FOUND = FAISS_NOT_FOUND = False
try:
import ngtpy
except Module... |
from enum import Enum
class NomCode:
"""
Enumeration representing the different nomenclatoral codes found in biology for scientific names.
Nomenclature codes or codes of nomenclature are the various rulebooks that govern biological taxonomic
nomenclature, each in their own broad field of organism... |
import os
import sys
import itertools
import matplotlib
import numpy as np
import tensorflow as tf
import collections
from lib import plotting
from q20game import Q20Env
from util import sigmoid
from network import PolicyNetwork, ValueNetwork, RewardNetwork, ObjectAwareRewardNetwork
os.environ["CUDA_VISIBLE_DEVICES"] ... |
#!/usr/bin/env python3
import os
import glob
import logging
import ctypes
import unittest
import ast
from time import sleep
import threading
import multiprocessing as mp
from queue import Empty
import socket
from shutil import which, rmtree, copyfile
import numpy as np
from astropy.time import Time, TimeDelta
import h... |
# The Admin4 Project
# (c) 2014 <NAME>
#
# Licensed under the Apache License,
# see LICENSE.TXT for conditions of usage
import adm
from wh import shlexSplit, xlt, Menu, floatToSize, prettyDate, prettySize,\
sizeToFloat
import wx
import re
from _imap import GetImapDate, decodeUtf7, encodeUtf7
class Mailbox(adm.No... |
import torch
import torch.nn as nn
import numpy as np
from model_base import Model
from nets.featnet import FeatNet
from nets.occnet import OccNet
from nets.viewnet import ViewNet
from nets.embnet2D import EmbNet2D
from nets.embnet3D import EmbNet3D
import torch.nn.functional as F
from utils_basic import *
import ut... |
# encoding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import argparse
import numpy as np
import shutil
import random
import time
from tqdm import tqdm
import torch
import torch.nn as nn
import t... |
import pandas as pd
import numpy as np
import os
import sys
def calc_prec_recall_f_score(a, b, d):
p = b/a
r = b/d
f = 1/((1/p) + (1/r))
return p, r, f
def find_common_links_ABIDE_review(in_file1, in_file2, out_file_path):
# print(in_file1)
# print(in_file2)
# print(out_file_path)
A... |
"""
MiPow PlayBulbs plugin for Domoticz
Author: Logread,
inspired by the plugin developed by zaraki673 (https://github.com/papagei9/python-mipow) that no longer seems
to be maintained
Compatibility: Linux only
Requires:
1) MiPowPlayBulbAPI.py module (in same github repo)
2) BluePy: See https:... |
# Copyright 2018-2019 <NAME>)
# SPDX-License-Identifier: Apache-2.0
from robotScenarioBase import *
from FalconsCoordinates import Vec2d, RobotPose
from math import pi
import logging
# Script for Robocup World Championship 2018, tech challenge run 1
# Conditions:
# two robots, wifi on, normal MSL field and lighting... |
"""
CCT 建模优化代码
作者:赵润晓
日期:2021年5月21日
"""
from cctpy import *
from hust_sc_gantry import HUST_SC_GANTRY
import time
import numpy as np
# 可变参数
# 动量分散
momentum_dispersions = [-0.05, -0.0167, 0.0167, 0.05]
# 每平面、每动量分散粒子数目
particle_number_per_plane_per_dp = 12
# 每个机架(束线)粒子数目
particle_number_per_gantry = len(
momentum_... |
import numpy as np
import torch
import yaml
def convert_to_yolo_labels(bbox, S, B, number_of_classes=20):
label = torch.zeros((S, S, (5 * B + number_of_classes)))
for box in bbox:
x, y, w, h, c = box
x_idx = int(x * S)
y_idx = int(y * S)
x_cell = (x * S) - int(x * S)
y... |
#!/usr/bin/env python
# @file: run_per_target_sequence_recovery.py
# @brief: Calculate sequence recovery over individual targets
# @author: <NAME> (<EMAIL>)
import sys, os
import numpy as np
from pyrosetta import *
from optparse import OptionParser, IndentedHelpFormatter
_script_path_ = os.path.dirname(os.path.realpa... |
#
# Copyright 2017 The TensorFlow 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 os
from datetime import datetime, timedelta
import pytz
import numpy as np
import scipy.io as io
import utm
import yaml
from munch import Munch, munchify
from scipy.ndimage import median_filter
import scipy.signal as sig
def loadmat(filename, check_arrays=False, **kwargs):
"""
Big thanks to mergen on ... |
import sys, os, glob
sys.path.append("../.")
sys.path.append("../data/")
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch.nn import MSELoss, L1Loss
from torch.optim import Adam
from PIL import Image
import argparse, json, torchvision
import scipy.io
import helper.canon_supervised_dataset as ds... |
# -*- coding: utf-8 -*-
"""WebSocket middleware for sending messages to clients."""
# Part of Trebek (https://github.com/whutch/trebek)
# :copyright: (c) 2018 <NAME>
# :license: MIT (https://github.com/whutch/trebek/blob/master/LICENSE.txt)
import asyncio
from collections import deque
import itertools
import json
impo... |
################################################################################
# ImageViewer widgets/toolbar implementation
################################################################################
from PyQt4 import QtCore, QtGui, QAxContainer
from core.modules.vistrails_module import Module
from packages.spre... |
from flask import Flask, stream_with_context
from flask import request, jsonify, Response
import inspect
import json
from functools import wraps
import requests
import time
import traceback
import asyncio
import os
# import aiohttp.web
# import aiohttp_debugtoolbar
# from aiohttp_debugtoolbar import toolbar_middleware_... |
#!@PYTHON@ -tt
import sys
import stat
import re
import os
import time
import logging
import atexit
import hashlib
import ctypes
sys.path.append("@FENCEAGENTSLIBDIR@")
from fencing import fail_usage, run_command, atexit_handler, check_input, process_input, show_docs, fence_action, all_opt
from fencing import run_delay
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ## ###############################################
#
# interfaceTools.py
# Contains all the tools for creating an interface
#
# Autor: <NAME>
# License: MIT
#
# ## ###############################################
from tkinter import * # Carga módulo tk (widgets estánd... |
# ACT likelihood, ported 11/6/2016 <NAME>, updated for DR4 on 4/11/2020
# original fortran by <NAME>, <NAME> 2016
import os, sys
import numpy as np
from scipy.io import FortranFile # need this to read the fortran data format
from scipy import linalg # need this for cholesky decomposition and inverse
import pkg_resou... |
from __future__ import print_function
import os
import signal
import socket
import struct
import subprocess
import sys
import unittest
import random
import time
import tempfile
import plasma
USE_VALGRIND = False
def random_object_id():
return "".join([chr(random.randint(0, 255)) for _ in range(plasma.PLASMA_ID_SI... |
# -*- coding: utf-8 -*-
import copy
import logging
import os
import re
import shutil
from subprocess import PIPE
from subprocess import Popen
from subprocess import STDOUT
from . import maven_utils
from . import web_utils
from pnc_cli.tools.maven_utils import MavenArtifact
git_version = None
scm_status_cache = {}
... |
import os
import json
from typing import (
Any,
Callable,
Iterator,
Optional,
TypedDict,
Union,
cast,
Generator,
overload,
)
import uuid
import mimetypes
import pickle
import random
from telegram.ext import Dispatcher, CallbackContext
from telegram.utils import helpers
from telegram ... |
#
# OtterTune - models.py
#
# Copyright (c) 2017-18, Carnegie Mellon University Database Group
#
from collections import OrderedDict
from pytz import timezone
from django.contrib.auth.models import User
from django.db import models, DEFAULT_DB_ALIAS
from django.utils.datetime_safe import datetime
from django.utils.tim... |
import numpy as np
from phonopy import Phonopy
from phonopy.structure.dataset import get_displacements_and_forces
from aiida.engine import WorkChain
from aiida.plugins import WorkflowFactory, DataFactory
from aiida.orm import Bool, Float, Int, QueryBuilder, Group, load_node, Code
from aiida.engine import while_, if_, c... |
'''
Calculate an optimized configuration based on overall memory, cpu, and sensible defaults.
Will configure spark and yarn.
The formula will be run on 5 node t2.large cluster hosted in AWS. t2.large nodes have 2 vcpus, and 8gb of memory each.
4 nodes are designed as yarn node managers. The formula will run with defa... |
# -*- coding: utf-8 -*-
import lxml.etree
import lxml.html
import weakref
import traceback
class RbElementMixin( object ):
def __enter__( self ):
self.tree()._push( self )
return self
def __exit__( self, exc_type, exc_value, tb ):
if exc_type :
print('[Rb]... |
# Copyright (c) 2021 by xfangfang. All Rights Reserved.
#
# Using potplayer as DLNA media renderer
#
# Macast Metadata
# <macast.title>PotPlayer Advanced</macast.title>
# <macast.renderer>PotplayerRenderer</macast.title>
# <macast.platform>win32</macast.title>
# <macast.version>0.4</macast.version>
# <macast.host_versi... |
import os
import re
import sphinx
import sys
import urllib
import html
from docutils import nodes
from docutils.parsers.rst import directives
from jinja2 import Template
from pkg_resources import parse_version
from sphinxcontrib.plantuml import generate_name # Need for plantuml filename calculation
try:
from sp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Built-in imports
import warnings
# 3rd party imports
import numpy as np
import xarray as xr
# Local imports
from .resample import resample
from .datetime642unix import datetime642unix
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright 2020-2021"
__... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2005 <NAME> <<EMAIL>>
# Copyright (C) 2004-2005 <NAME> <<EMAIL>>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The te... |
#!/usr/bin/env python
""" TUI based Python Chess Program """
from __future__ import print_function
import os
CLEAR='clear'
# CLEAR='cls' # For Windows
ch = [[' '] * 8 for i in range(8)]
def init():
ch[0][0] = 'R '
ch[0][1] = 'N '
ch[0][2] = 'B '
ch[0][3] = 'Q '
ch[0][4] = 'K '
ch[0][5] = ... |
import os, sys, json, warnings, logging as log
import pandas as pd, tqdm, dpath
import annotate, collect
from pprint import pprint
def make_items(iter_labeled_meta, iter_all_meta, n_unlabeled, read_rows):
'''Generate metadata from gold-standard and unlabled'''
labeled_items = [(meta, read_rows(meta['url'... |
import scipy.sparse as sparse
import matplotlib.pyplot as plt
import scipy.io as io
from math import sqrt, atan, cos, sin, pi, atan2
import numpy as np
from nutils import *
cc = list('gbcmy')
def plot_opt_splitting2(e, w, W):
df = 0.01
w_span = np.arange(w,W+2.0*pi*df,2.0*pi*df)
J_span2 = np.em... |
import argparse
import os
import glob
import imageio
import OpenEXR
import cv2
import Imath
import numpy as np
def exr_loader(EXR_PATH, ndim=3):
"""Loads a .exr file as a numpy array
Args:
EXR_PATH: path to the exr file
ndim: number of channels that should be in returned array. Valid values ... |
#!/usr/bin/env python
"""Retrieve a remote file via http to a local file.
Note: at exit attempts to abort all outstanding transfers and delete the output files.
To do: try polling while connected instead of using a progress callback.
The advantages are:
- fewer calls (except over a slow connection)
- can implement a... |
import os
import datetime
import random
import discord
import asyncio
from discord.ext import commands
import aiohttp
from io import BytesIO
# import requests
from modules.image_functions import randomFile, makeColorImg
import modules.checks as checks
from gtts import gTTS
try:
URBANDICTKEY = os.environ["URBANDI... |
# coding=utf-8
# Copyright 2021 Google Health Research.
#
# 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... |
from __future__ import annotations
from typing import *
import pathlib
import re
import shlex
import textwrap
from metapkg import packages as mpkg
from metapkg import tools
from metapkg.packages import repository
from metapkg.targets import base as targets
from metapkg.targets import generic
from metapkg.targets.pack... |
import os
import torch
import torchvision
from tensorboardX import SummaryWriter
from tqdm import tqdm
import cv2 as cv
from torchvision import transforms
import numpy as np
from dataset.dataset import AdaMattingDataset
from dataset.pre_process import composite_dataset, gen_train_valid_names
from net.adamatting import... |
# Copyright 2015 The Bazel 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 applicable la... |
import numpy as np
import os
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from scipy import stats
from scipy.spatial import distance
import math
import pickle
from sklearn.neighbors import KNeighborsClassifie... |
# -*- coding: utf-8 -*-
"""
@File: patent2vec.py
@Description: This is a module for generating document embedding for patents.
This application,
1. Creates Patent2Vec model
2. Initializes Patent2Vec model's weights
with pre... |
# @Author: JC
import requests
import json
from lxml import etree
from tool import read_json_file_to_object
from tool import get_html
from tool import save_object_to_json_file
from tool import save_html_response_to_html_file
from tool import read_txt_file_to_list
from tool import Logger
from login import get_cookie_from... |
# %%
import warnings
warnings.filterwarnings(action='ignore')
import os, pickle
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow import keras
from gensim import models
from gensim.models import word2vec
from keras.preprocessing import sequence
# from keras.preproce... |
"""
Module for typing and typechecking JSON
This module offers functions for introspecting the JSON types of
python object representing JSON, including those created with
`@jsonable <jsonable>`, as well as typechecking JSON values against
type hints.
"""
from __future__ import annotations
import functools
import iter... |
"""
A set of model classes to model hierarchies of objects following Directed Acyclic Graph structure.
The graph traversal queries use Postgresql's recursive CTEs to fetch an entire tree of related node ids in a single
query. These queries also topologically sort the ids by generation.
"""
from copy import deepcopy
f... |
"""Basic classes for creating a pygame application"""
import pygame, math, sys
from glob import glob
from pygame.locals import *
from recordclass import RecordClass
class TrueEvery:
"""This is a functor that creates a function that returns true once every {self.count} calls"""
def __init__(self, count: int, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.