text stringlengths 3.07k 22.1k |
|---|
"""
Command classes for Distutils/setup.py to assist with Python package building/usage/management.
For basic :class:`.BumpCommand` usage, see either the class documentation itself, or the :py:mod:`.bump` module
documentation.
**Registering distutils commands in setup.py**
Below is a very basic setup.py showing how ... |
import numpy as np
import torch
from scipy.ndimage import convolve
from scipy.ndimage.morphology import distance_transform_edt
from skimage.morphology import label
from inferno.io.transform import Transform
import inferno.utils.python_utils as pyu
import inferno.utils.torch_utils as tu
import logging
logger = loggin... |
"""
Profile measurement.
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
from physicslab.curves import gaussian_curve, gaussian_curve_FWHM
from physicslab.utility import _ColumnsBase, get_name
def process(data, **kwargs):
""" Bundle method.
... |
from ast import Mod
from enum import Enum
import random
import uuid
import networkx as nx
import matplotlib.pyplot as plt
from mesa import Agent, Model
from mesa.time import RandomActivation
from mesa.datacollection import DataCollector
from mesa.space import NetworkGrid
def perceived_proposal_value(model):
"""Re... |
from datetime import datetime
import os
import sys
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
sys.path.append('..')
from input_pipeline.morph_kCH_log import input_pipeline
from configs.cfg_morph_estimation_kCH_setting_A import ConfigMorphV0 as Config
from networks import model_compara... |
import SBCcode.MonteCarlo.PICOcalGlobalLikelihood_v2_jz as pcgl
import numpy as np
from iminuit import Minuit, describe, Struct
from iminuit.util import make_func_code
# import sys
import ipdb
# Minuit target functions can only take scalar arguments, so fake the function signature
class Chi2Functor:
def __init__(... |
import argparse
import os.path
import re
import Bio.PDB
class Superimposer():
""" This function aligns two PDB structures using the Bio.PDB module in Biopython.
Based on <NAME>en function: https://gist.github.com/andersx/6354971
TODO check:
https://warwick.ac.uk/fac/sci/moac/people/students/peter_cock/... |
import nltk
import sys
from nltk import pos_tag
import pandas as pd
import spacy
from utils_A import *
from nltk.corpus import stopwords, wordnet, words, treebank
from spacy.lang.en.stop_words import STOP_WORDS
nlp = spacy.load("en_core_web_sm", disable=["tokenizer", "parser","ner", "textcat", "custom"])
multiword_ex... |
from collections import defaultdict
from datetime import datetime
from glob import glob
from multiprocessing import Pool
from os.path import join, isfile
from re import findall, search
from statistics import mean
from benchmark.utils import Print
class ParseError(Exception):
pass
class LogParser:
def __ini... |
import enum
import numpy as np
from .mathscene import Path
from .mathscene import Arc
from .svg import SVGNode
from .gcode import GCode
from .mathscene import AABB
from .mathscene import euclidian_distance
from .optimizer import PenPath
from .optimizer import greedy_tsp
from .optimizer import remove_repeated_ops
from... |
#!/usr/bin/env python3
import argparse
import getpass
import os
import pathlib
import subprocess
import sys
CONFIG = "/etc/mail-server"
DATA = "/var/lib/mail-server"
RUN = "/run/mail-server"
ROOT = os.path.abspath(os.path.dirname(__file__))
TOOLS = os.path.join(ROOT, "tools")
class Config:
def __init__(self, do... |
from blueprints.influxdb import *
# from main import *
from flask import Flask, render_template, request, redirect, url_for, flash, session, send_from_directory, send_file,Blueprint,current_app
from flask_bootstrap import Bootstrap
import random, datetime
from functools import wraps
import time
import functools
import... |
import lib
import numpy as np
from skimage import metrics
from scipy.optimize import minimize as sciminimize
import matplotlib.pyplot as plt
import os
import sys
# Default MAXITER
MAXITER = 25
# Default TOLERANCE
TOLERANCE = 10e-3
# Methods Dictionary
methods = {
"naive": {"phi": lambda _: 0, "dphi": lambda _: 0... |
#!/usr/bin/env python3
"""
Converts the btab output of Ergatis ncbi-blast to GFF3
Example input:
GluR_4 3300 BLASTN Trinity.fasta comp93586_c0_seq1 26 2208 2180 1 99.6 0.0 2139 4240 len=2337 path=[1:0-1874 1876:1875-1882 1884:1883-2336] 1 Plus 2337 ... |
import numpy as np
from GraphAdjList import *
import time
def align(graph1, graph2, a, b, lamb_da):
sim_score = similarity_score(graph1, graph2, a, b)
P = 0 # unused variable!?!
# vertices list of graph1 and graph2
V1 = graph1['vertex']
V2 = graph2['vertex']
# size of V1 and V2
n_v1 = len... |
# -*- coding: utf-8 -*-
import json
from typing import Optional as Option, Union, Dict, Any, Callable
from base64 import b64encode
from os.path import join
from re import sub
from datetime import datetime, timedelta
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptograp... |
# Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import re
from openvino.tools.mo.front.extractor import raise_no_node, raise_node_name_collision
from openvino.tools.mo.utils.error import Error
from openvino.frontend import InputModel # pylint: disable=no-name-in-module,import-error... |
import io
import base64
import datetime
import pandas as pd
import altair as alt
import streamlit as st
def df_format(dataframe, sender):
"""Formats the Dataframe and removes the redundant columns whether the log files are for
receiver or sender device
Args:
dataframe ([dataframe]): Input data... |
import numpy as np
from numba import njit
from matplotlib import pyplot as plt
import ReferenceModification.LibFunctions as lib
class ScanSimulator:
def __init__(self, number_of_beams=10, fov=np.pi, std_noise=0.01):
self.number_of_beams = number_of_beams
self.fov = fov
self.std_noise = st... |
"""
Train a model on TACRED.
"""
import os
from datetime import datetime
import time
import numpy as np
import random
import argparse
from shutil import copyfile
import torch
import pickle
import yaml
import torch.nn as nn
import torch.optim as optim
from data.loader import DataLoader
from model.rnn import RelationMo... |
import os,re
from brick_general import ChattyBrickTask
from waflib import Task,Errors,Node,TaskGen,Configure,Context,Logs
def configure(conf):
"""This function gets called by waf upon loading of this module in a configure method"""
conf.load('brick_general')
conf.find_program('abstract', var='CADENCE_ABSTRACT')
... |
from .svg_parser_utils import *
import OpenGL.GL as gl
import math
EPSILON = 0.001
class vec2(object):
def __init__(self, *args):
if isinstance(args[0], vec2):
self.x = args[0].x
self.y = args[0].y
elif isinstance(args[0], list):
self.x, self.y = args[0]
... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 16 13:18:17 2017
@author: jamesleech
"""
import math
import matplotlib.pylab as plt
import numpy as np
from scipy.optimize import curve_fit
#---------Select dataset from below:--------------
#dataset = 'data58'
dataset = 'data60'
#dataset = 'r2_a_b_c_x_y_z_v'
#----... |
# -*- coding: utf-8 -*-
from flask import request, render_template, jsonify, url_for, redirect, g
from .models import User, Picture
from index import app, db, celery, es
from sqlalchemy.exc import IntegrityError
from .utils.auth import generate_token, requires_auth, verify_token, verify_sms_code, encrypt_simple_info, ... |
import numpy as np
import pandas as pd
import xgboost as xgb
from matplotlib import pyplot
from pathlib import Path
from xgboost import XGBClassifier, plot_importance
from sklearn.model_selection import GroupKFold, ParameterGrid
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.utils import shuffle
from... |
import os
# os.environ["CUDA_VISIBLE_DEVICES"]="1"
import ipdb
import matplotlib
matplotlib.use('Agg')
from tqdm import tqdm
import time
import numpy as np
from utils.Config import opt
from data.dataset import Dataset, DataLoader
from models.faster_rcnn_vgg16 import FasterRCNNVGG16
from models.faster_rcnn_resnet impo... |
import numpy as np
import numpy.linalg
import scipy
import scipy.linalg
import scipy.optimize
import matplotlib.pyplot as plt
from ode_solvers import *
from scipy.linalg import expm
from numpy.linalg import solve, norm
from numpy import *
def exp_euler_long(f, Df, y0, t0, T, N):
"""
Exponentielles... |
# Copyright 2022 The Sigstore Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
"""Computational geometry functions.
This module contains various computational geometry functions related to linear
programming.
"""
__author__ = '<NAME>'
__all__ = ['intersection', 'polytope_vertices', 'polytope_facets',
'halfspace_intersection', 'interior_point', 'order']
from collections import namedt... |
import argparse
import os, time
import torch
import shutil
import numpy as np
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
im... |
import numpy as np
import sys
sys.path.insert(1,'../functions')
from matplotlib import pyplot as plt
from sentinelhub import BBox, CRS, DataCollection, SHConfig
## -- for testing
# 1.) check type of image_height,width
# 2.) check type of bbox
# 3.) if any input value is None return value error.
def get_coord_matrix... |
#ATS:flux SELF FluxDirect 800000
"""A flux machine for ATS
"""
from __future__ import print_function
from ats import machines, debug, atsut
from ats import log, terminal
from ats import configuration
from ats.atsut import RUNNING, TIMEDOUT, PASSED, FAILED, BATCHED, CREATED, SKIPPED, HALTED, EXPECTED, ... |
import asyncio
import logging
from typing import Dict
from typing import List
from typing import Optional
from heisenbridge.command_parse import CommandParser
from heisenbridge.private_room import PrivateRoom
from heisenbridge.private_room import unix_to_local
class NetworkRoom:
pass
class ChannelRoom(PrivateR... |
from abc import abstractmethod
import math
import generator
import magma
import mantle
from from_magma import FromMagma
from configurable import Configurable, ConfigurationType
from const import Const
class FeatureGenerator(Configurable):
def __init__(self):
super().__init__()
class CoreGenerator(Featur... |
import numpy as np
from ml_from_scratch.utils import calculate_entropy
class DecisionNode():
"""Class that represents a decision node or leaf in the decision tree
Parameters:
-----------
feature_i: int
Feature index which we want to use as the threshold measure.
threshold: float
T... |
import numpy as np
import ot
import scg_optimizer
from utils import dist,reshaper,hamming_dist
from scipy import stats
from scipy.sparse import random
from IPython.core.debugger import Tracer
class StopError(Exception):
pass
def init_matrix(C1,C2,p,q,loss_fun='square_loss'):
""" Return loss matrices and... |
import math as mt
import numpy as np
class x:
def __init__(self,*args, alternative = None):
print("This class is not yet made, thus it is called x!")
class InitialValueConstants():
def __init__(self,):
# A class specifically pertaining the constants to solve the initial value problems
... |
import scipy.io as io
from os.path import join
from scipy import signal
import numpy as np
import pickle
import matplotlib.pyplot as plt
def load_sway_file(path, verbose=False):
"""Loads a postural sway matlab data file"""
data = io.loadmat(path)['data']
if verbose:
#check sampling frequency
... |
import sys, cv2, time, os
from UI import Ui_TabWidget
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QFileDialog,QTabWidget
from PyQt5.QtCore import QTimer, QThread, pyqtSignal, Qt
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QLabel,QWidget, QProgressBar
from py_util impor... |
"""
A visible, clickable button.
Changes color when interacted with (clicked. on hover) and calls the defined methods.
"""
from dataclasses import dataclass
from typing import Optional
import cocos
from shimmer.components.mouse_box import (
MouseBoxDefinition,
MouseBox,
EVENT_HANDLED,
)
from shimmer.data... |
""" AutoMechanic Chemical Identifier (AMChI) generating functions
BEFORE ADDING ANYTHING, SEE IMPORT HIERARCHY IN __init__.py!!!!
"""
import itertools
from automol import util
import automol.formula
from automol.graph.base._core import atom_keys
from automol.graph.base._core import atoms_neighbor_atom_keys
from automo... |
'''
Author: Ligcox
Date: 2021-04-06 15:20:21
LastEditors: Ligcox
LastEditTime: 2021-08-20 01:24:33
Description: Color filter, through the inheritance of Class 'imageFilter', realize the color filtering in different scenarios
Apache License (http://www.apache.org/licenses/)
Shanghai University Of Engineering Science
Co... |
"""A multi-layer perceptron for classification of MNIST handwritten digits."""
from __future__ import absolute_import, division
from __future__ import print_function
from jax.api import jit, grad
from jax.config import config
from jax import hessian as hess
import jax.numpy as np
import jax.random as random
from jax.f... |
#!/usr/bin/env python
""" Lenstra–Lenstra–Lovász lattice basis reduction algorithm wrapper
for Merkle-Hellman Knapsack encrypted ciphertext
"""
from __future__ import print_function
import sys
from liblll import *
from copy import deepcopy
# This reads the binary from MSB left to LSB right (big endian)
def BigEndian... |
# Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import copy
import http.client
import logging
import os
import sys
import warnings
from contextlib import contextmanager
from dataclasses import dataclass
from logging import Handler, Logg... |
"""Train Neural Network
Adapted from CS230 code examples for computer vision.
Source: https://github.com/cs230-stanford/cs230-code-examples/tree/master/pytorch
"""
import argparse
import logging
import os
import numpy as np
import torch
import torch.optim as optim
from torch.autograd import Variable
from tqdm import... |
import sys
sys.path = ["."] + sys.path
from petlib.ec import EcGroup
from petlib.bn import Bn
from hashlib import sha256
import math
## ######################################################
## An implementation of the ring signature scheme in
##
## <NAME> and <NAME>. "One-out-of-Many Proofs:
## Or How to Le... |
import pandas as pd
import scanpy as sc
import numpy as np
import stlearn as st
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
import sys
from h5py import Dataset, Group
#################### get the whole training dataset
rootPath = os.path.dirname(sys.path[0])
os.c... |
# coding: utf-8
# Copyright 2019 IBM 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... |
import numpy as np
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
from sklearn.cluster import DBSCAN
from sklearn.model_selection import train_test_split
from scipy import stats
import copy
from .basic import singleCellData, baseTool, infoTable
from .vis import plot_2demb, plot_2demb_labels
"... |
import numpy as np
from paddle.fluid import layers as F
from paddle.fluid.framework import Variable, in_dygraph_mode
from paddle.fluid import core, dygraph_utils
from paddle.fluid.layers import nn, utils
from paddle.fluid.data_feeder import check_variable_and_dtype
from paddle.fluid.param_attr import ParamAttr
from pad... |
import tensorflow as tf
import numpy as np
import time
from tqdm import tqdm
from sklearn.model_selection import train_test_split
from scipy.stats import kendalltau
from contextual_decomposition import ContextualDecompositionExplainerTF
from gradients import GradientExplainerTF
from neural_interaction_detection impor... |
"""This file contains the Matrix object."""
from __future__ import annotations
from typing import Union, Callable
import copy
class Matrix:
"""A matrix
Instance Attributes:
- shape: shape of the matrix
Private Instance Attributes:
- _row_count: The number of rows
- _col_count: The number of... |
from typing import List
import os
import shutil
import functools
from pathlib import Path
import tempfile
import json
import pytest
from pytest_cases import parametrize
import pandas as pd
from toffy.settings import QC_COLUMNS, QC_SUFFIXES
from toffy.fov_watcher import RunStructure
def generate_sample_fov_tiling_e... |
###############################
# #
# Virtual High Speed Camera #
# #
###############################
#
# Author: <NAME>
# Date: 26.11.2018
# License: MIT License https://opensource.org/licenses/MIT
# Description: This program is an independent... |
import json
import logging
from django.core.serializers.json import DjangoJSONEncoder
from django.templatetags.static import static
from django.utils.translation import gettext_lazy as _
from django.utils.translation import get_language
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool... |
import base64
import itertools
import os
import shutil
import uuid
from pathlib import Path
from typing import Union, Mapping
from fastapi import APIRouter, Depends, UploadFile, File, HTTPException
from .configurations import Configuration, get_configuration
from .models import (
Projects, ProjectSnippet, Project... |
import numpy as np
import sklearn.datasets as skdata
from sklearn.linear_model import Perceptron
'''
Name: Doe, John (Please write names in <Last Name, First Name> format)
Collaborators: Doe, Jane (Please write names in <Last Name, First Name> format)
Collaboration details: Discussed <function name> implementation ... |
"""A room where players gather to play a game"""
# Online multiplayer doesn't work yet, but the
# rough idea is there. For now, I'll just remove
# the option from the main menu and leave this as is.
import random
import socket
import threading
import tkinter.messagebox
from enum import IntEnum
from queue import Queu... |
from enum import IntEnum, unique
import itertools
from color import Color32, remap_color
from utils import integer_to_bytes
@unique
class SpecialColor(IntEnum):
None_ = 0
Face = 1 # Uses the color of the face (based on a rainbow)
ColorWheel = 2 # Uses how hot the die is (based on how much its bei... |
# The MIT License (MIT)
#
# Copyright (c) 2020 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, me... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8 ff=unix ft=python ts=4 sw=4 sts=4 si et
"""
pip-licenses
MIT License
Copyright (c) 2018 raimon
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 t... |
# -*- coding: utf-8 -*-
"""
Created at 2019/12/8
@author: <NAME>
"""
import RPi.GPIO as GPIO
import pyaudio
import struct
import wave
import matplotlib.pyplot as plt
import numpy as np
import twstock
from scipy.io import wavfile
import librosa
from tensorflow import keras
from tflite_runtime.interpreter import Interpre... |
# Copyright (C) 2019 Facesoft Ltd - All Rights Reserved
import pickle
import json
import numpy # needs to be installed
import flatbuffers # needs to be installed
from flatbuffers.number_types import UOffsetTFlags
# types generated from schema
from .FacesoftFlatbuffersSchema import SerializedTriMesh
from .Fac... |
#! /usr/bin/python
# -----------------------------------------------------------------------------------------------------------------------------
# GENERAL
# -----------------------------------------------------------------------------------------------------------------------------
#
# author: <NAME>
# mail: <EMAIL>... |
"""
Copyright 2016 Yahoo Inc.
Licensed under the terms of the 2 clause BSD license.
Please see LICENSE file in the project root for terms.
"""
from caffe.proto import caffe_pb2
import google.protobuf as pb
from caffe import layers as L
from caffe import params as P
import caffe
from lego.hybrid import ConvReLULego
f... |
import itertools
from abc import ABCMeta, abstractmethod
from collections import deque
from typing import Sequence, Optional, TypeVar, Tuple, List, Generic, cast
from electronics_model import *
import math
class ESeriesUtil:
"""Helper methods for working with the E series of preferred numbers."""
@staticmethod
... |
import asyncio
import asyncssh
import json
import re
from slugify import slugify
from core import app, utils, data
from core.ctrl import servers, recipes, sites, mailer, services, notifications
async def run_client(server, tasks=[], recipe=None, service_installer=False):
result = {
'status': False,
... |
import sqlite3
from sqlite3 import Error
import os
import argparse
import shutil
# Handles background code
class EFNote:
"""
Enables use of formattable note taking in the command line
"""
def __init__(self, main_path):
"""
Initializes class variables
"""
# Listen for
... |
"""
"""
import os
import datetime as dt
import numpy as np
import pandas as pd
import xarray as xr
from scipy import sparse
from scipy.linalg import cho_factor, cho_solve
# import eoxmagmod
import chaosmagpy as cp
from ..env import REFRAD, ICOS_FILE, DATA_EXT_DIR
from .time import to_mjd2000
def eval_global_grid(sh... |
"""TODO."""
from __future__ import print_function, absolute_import
import sys
import numpy as np
from numbskull.inference import *
from numbskull.learning import *
from numbskull.timer import Timer
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
def run_pool(threadpool, threads, func, arg... |
import asyncio
from aiohttp import web
import aiohttp
import aiohttp_jinja2
import jinja2
import json
import os
import traceback
import re
import feedparser
import time
import appdaemon.homeassistant as ha
import appdaemon.conf as conf
import appdaemon.dashboard as dashboard
# Setup WS handler
app = web.Application(... |
import json
import os
import os.path as p
from os.path import expanduser, abspath
import shutil
import gzip
import struct
from functools import partial
from pathlib import Path
import time
import menpo
import menpo3d
from menpo.shape.mesh import TexturedTriMesh
import numpy as np
from landmarkerio import CacheFile
... |
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
import collections.abc
import re
from typing import Dict, Union
from azure.ai.ml.constants import InputOutputModes, AssetTypes
from azure.a... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
*t4mon* - T4 monitoring functional tests
"""
from __future__ import print_function, absolute_import
import re
import tempfile
from os import sep
from test.functional_tests import base as b
import pandas as pd
import pytest
from t4mon import collector
from t4mon.sftp... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
import json
import os
import time
from typing import List, Dict
from urllib.error import HTTPError
from urllib.request import urlretrieve
import requests
import tweepy
import twx
import vk
from django.conf import settings
from django.template.loader im... |
import os
from flask import Flask, render_template, redirect, request, url_for
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
from os import path
if path.exists("env.py"):
import env
app = Flask(__name__)
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
app.config["MO... |
# coding=utf-8
# Following the patterns set in sklearn/preprocessing/imputation.py as much as possible.
from sklearn import warnings
import numpy as np
import numpy.ma as ma
from scipy import sparse
from scipy import stats
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils import check_arr... |
'''
Step 1: Find length-1 sequential patterns
(1) Scan database, count support, generate projection
(2) generate frequential prefix pattern (length-1 pattern)
'''
if __name__ == '__main__':
import pseudo_projection as pp
else:
try:
import my_library.pseudo_projection as pp
excep... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: <NAME>
import re
import os
import time
import json
import sys
import inspect
import importlib
import logging
import ares.doc
DSC = {
'eng': '''
:category: Markdown
:rubric: PY
:type: Base class
:dsc:
## Markdown Framework
This framew... |
import tensorflow as tf
from tensorflow import keras
import numpy as np
import argparse
import json
from model import buildDiscriminator, buildGenerator
parser = argparse.ArgumentParser(description='Train the model for detecting false positives')
parser.add_argument('--epochs', type=int, help='The number of epochs to... |
"""This is the controller for the admin portion of the site.
The admin pages allow CRUD operations on courses and assignments.
"""
from autograder import app, db
from autograder.models import Course, Assignment, Testfile, Unittest
from autograder.admin_forms import CourseForm, AssignmentForm, NewTestFileForm, TestFil... |
"""Main module."""
from scipy.stats import kurtosis
import numpy as np
import pandas as pd
def get_kurtosis_feature_split(data):
"""
Get attribute split according to Kurtosis Split
:param data: the dataset of the node
:returns:
- feature_index: the attribute index to split
- feature_split: the attribute val... |
# -*- coding: utf-8 -*-
"""Main module of pylexique."""
from collections import OrderedDict, defaultdict
from collections.abc import Sequence
import pkg_resources
import json
from math import isnan
# import faster_than_csv as csv
import csv
from csv import reader
import pandas as pd
from dataclasses import dataclass
... |
import argparse
import collections
import json
import math
from nectar import corenlp
from nltk.corpus import wordnet as wn
from nltk.stem.lancaster import LancasterStemmer
import os
from pattern import en as patten
import random
import re
from termcolor import colored
import sys
OPTS = None
CORENLP_P... |
# -*- coding: utf-8 -*-
"""Quick implementations of simple plugin interfaces.
Blankets allow to reduce boilerplate code in plugins by simplifying the way
common interfaces are registered.
For instance, this is how template helpers are generally added using the
:py:class:`~ckan.plugins.interfaces.ITemplateHelpers` in... |
import tkinter as tk
from random import choice
from collections import Counter
from tkinter import messagebox
SIDE = 25
class Tetris(tk.Toplevel):
"""The tetris game"""
WIDTH = 10 * SIDE
HEIGHT = 20 * SIDE
def __init__(self, parent):
super().__init__(parent)
self.geometry("500x600")
... |
import pickle
import random
import socket
import logging
import socketserver
import numpy as np
from utils import *
# compatible with Windows
socket.SO_REUSEPORT = socket.SO_REUSEADDR
class SignatureRequestHandler(socketserver.BaseRequestHandler):
user_num = 0
ka_pub_keys_map = {} # {id: {c_pk: bytes, s_... |
import simplejson
from pathlib import Path
import copy
import csv
import os
import sys
# TODO: Use logger object instead of printing output to console.
# TODO: Better handling of deeply-nested JSON files.
def str2bool(str) -> bool:
"""Converts str to bool.
When importing a JSON, bools are ... |
import nixio
import os
import inspect
import logging
import weakref
import datetime as dt
from tqdm import tqdm
from importlib import import_module
from .base.stimulus import Stimulus
from .utils.mappings import DataType, type_map
from .base.repro import ReProRun
from .utils.timeline import Timeline
from .utils.util i... |
# -*- coding: utf-8 -*-
import numpy
class Dummy():
def __init__(self):
'''nothing to do here'''
def calc_pm1(self, exp_vars):
return self.__sum_exp_vars(exp_vars)
def calc_pm2(self, exp_vars):
return self.__sum_exp_vars(exp_vars) * 2
def calc_pm10(self, exp_vars):
... |
#
# spyne - Copyright (C) Spyne contributors.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This libra... |
# <NAME>
#! /usr/bin/env python
#
# Example program using irc.bot.
#
# <NAME> <<EMAIL>>
# slight modifications by <NAME>
"""A simple example bot.
This is an example bot that uses the SingleServerIRCBot class from
irc.bot. The bot enters a channel and listens for commands in
private messages and channel traffic. Com... |
# -*- coding: utf-8 -*-
# @Tme : 2020/12/01 16:00
# @Author : zhiming.qian
# @Email : <EMAIL>
import argparse
import os
import os.path as osp
import time
from configs import cfg
from mvt.utils.config_util import (
get_task_cfg,
convert_to_dict,
get_dataset_global_args,
get_dict_from_list,
)
from... |
import requests
from ch_app import models
import json
import logging
logger = logging.getLogger(__file__)
""""
Funções de complemento para as views
"""
def powerReles(action=None, ip=None):
for t in models.R_wifi.objects.filter(type="LUZ"):
if str(t.type2) == 'RGB':
if action == 'ON' and len... |
import datetime
import logging
import re
from cockroach.call import Call
from cockroach import errors
from cockroach.methods import Methods
from cockroach.proto import api_pb2, data_pb2
from cockroach.txn_sender import TxnSender
from cockroach import util
txn_retry_options = util.RetryOptions(
backoff=datetime.ti... |
import numpy as np
from tqdm import tqdm
from itertools import chain, combinations
def divisors(num):
"""Returns all divisors of a given integer"""
divs = []
for x in range (1, num):
if (num % x) == 0:
divs.append(x)
return divs
def powerset(iterable):
"""Returns the powerset... |
import scipy as sp
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from .support import newtons_method_metalog, pdfMetalog_density
import types
#TODO have to add summary function
def summary(m):
print(' -----------------------------------------------\n',
'Summary o... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
#<NAME> cs528 Final Project
#Simulation of gas particles with partial wall
#Simulation starts by putting all particles on the left side of a wall.
#The wall is removed midway through? At start?
import numpy
import matplotlib.pyplot as plt
import random
import math
i... |
from datetime import datetime
import bz2
import json
import os
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.schema import Index
from sqlalchemy.sql.expression import case
import sqlalchemy
from .exception import OnHttpReqException
_SQLAlchemyORMBase... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.