text stringlengths 3.07k 22.1k |
|---|
from sklearn.linear_model import LinearRegression,SGDRegressor
from sklearn import svm,preprocessing
from sklearn.metrics import mean_squared_error,SCORERS,r2_score
from sklearn.model_selection import GridSearchCV, cross_val_score, KFold,train_test_split
from sklearn.neural_network import MLPRegressor
from sklearn.neig... |
import sys
import click
from dataclasses import dataclass
from multiprocessing.context import AuthenticationError
from rich.console import Console
from rich.table import Table
from rich.text import Text
from pyrsched.rpc import RPCScheduler
from halo import Halo
PYRSCHED_LOGO = "[italic bold][#e20074]P[/#e20074][whi... |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import requests
from loguru import logger
# Fontawesome (icons)
FA = "https://use.fontawesome.com/releases/v5.8.1/css/all.css"
# Logo
LOGO = "ht... |
#!usr/bin/env python3
""" This module contains all the functions to build the menu and the menu's
options handlers (ciphering functions, ..)
"""
import curses
from src.SHA1 import SHA1
from src.CramerShoup import CramerShoup
from src.Threefish import Threefish
from src._utils import (read_file)
from src._function... |
import argparse
import networkit as nk
import csv
import heapq as hq
def main(args):
edge_list = args.edgeList
out_dir = args.outDir
k = args.kvalue
edge_list_reader = nk.graphio.EdgeListReader('\t', 0, continuous=True, directed=True)
graph1 = edge_list_reader.read(edge_list)
graph, node_id_... |
# Copyright 2017: GoDaddy Inc.
import copy
import datetime
import json
import logging
import elasticsearch
import morph
from netmet import exceptions
from netmet.utils import worker
LOG = logging.getLogger(__name__)
# Use streaming API instead of this
# Elastic doesn't allow to query more than 10k elements (for t... |
"""Utilities for angiosperm.sqlite databases."""
import re
import sqlite3
from pathlib import Path
from typing import Union
DbPath = Union[Path, str]
def build_select(sql: str, *, limit: int = 0, **kwargs) -> tuple[str, list]:
"""Select records given a base SQL statement and keyword parameters."""
sql, param... |
import math
import numpy as np
from keras import backend as K
from keras.preprocessing import image
from keras.models import Model
from keras.layers.normalization import BatchNormalization
from keras.layers import Conv2D, Add, ZeroPadding2D, GlobalAveragePooling2D, Dropout, Dense
from keras.layers import MaxPool... |
# Copyright 2018-2021
# Institute of Neuroscience and Medicine (INM-1), Forschungszentrum Jülich 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/LICE... |
import re
import cv2
import random
import colorsys
import numpy as np
import tensorflow as tf
from core.config import cfg
import json
import datetime
num_With_Helmet = 0
num_Without_Helmet = 0
num_WithHelmet = int()
num_WithoutHelmet = int()
withouthelmet = []
withhelmet = []
dic01 = []
detection = []
num_id = 1
# Z... |
# Copyright (c) 2016-2018 <NAME>
# Licensed under Apache License v2.0
load(
"@bazel_toolbox//collections:collections.bzl",
"dict_to_struct",
"merge_structs",
"struct_to_dict",
)
load(
"//:internal.bzl",
"optional_arg_",
"transitive_resources_",
)
def web_internal_minify_html_impl(ctx):
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 13 09:50:51 2017
@author: mkonrad
"""
import math
import pytest
from hypothesis import given
import hypothesis.strategies as st
import numpy as np
from pdftabextract.geom import (pt, ptdist, vecangle, vecrotate, overlap, lineintersect,
... |
"""
For Tensor of inertia refer to http://en.wikipedia.org/wiki/Moment_of_inertia
"""
from __future__ import division
import sys
from math import *
import numpy
from numpy.core import *
import vtk
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
import vtkbone
import test_geometries
import traceback
impo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2020 tecnovert
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
"""
export TEST_RELOAD_PATH=/tmp/test_basicswap
mkdir -p ${TEST_RELOAD_PATH}/bin/{particl,monero}
cp ~/... |
#!/usr/bin/env python3
# Copyright (c) 2019 MindAffect B.V.
# Author: <NAME> <<EMAIL>>
# This file is part of pymindaffectBCI <https://github.com/mindaffect/pymindaffectBCI>.
#
# pymindaffectBCI is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publishe... |
import importlib
import multiprocessing
import numpy as np
import sys
import d3m.metadata.base as mbase
from d3m.container import List
from d3m.container.pandas import DataFrame
from d3m.primitive_interfaces.base import CallResult
from d3m.primitive_interfaces.transformer import TransformerPrimitiveBase
from d3m.meta... |
"""I/O plugin base classes for input to/from folders or zipfiles
"""
import errno
import glob
import zlib
import os
import shutil
from operator import itemgetter
from bson import json_util
from six.moves import input
from pax import utils, plugin
from pax.datastructure import make_event_proxy
class InputFromFolder(... |
import random
import time
import copy
import numpy as np
from line_search_methods import line_search_dict
from main_methods import main_method_dict
class Result:
comparables = [
'theta_name',
'main_method_name',
'line_search_name',
'permutation'
]
def __init__(self, resu... |
import sys
import os
ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, os.path.join(ROOT_DIR, "src"))
import util
import torch
import numpy as np
from model import make_model
from render import NeRFRenderer
import tqdm
import imageio
from dotmap import DotMap
from pyhocon i... |
#!/usr/bin/env python
"""
Script that starts the SSH agent for a connection based on the domain.
If the agent is already running, it won't start another.
Put something like this in your ~/.ssh/config file:
Match exec ~/bin/start_ssh_agent_by_domain.py --domain=mydomain.com \\
--control=~/.ssh/agent-my... |
import torch
import numpy as np
import random
import _pickle as pk
import config as default_config
from torch.utils.data import Dataset, DataLoader
from pytorch_metric_learning import samplers
import math
class SIMSDataset(Dataset):
def __init__(self, type, use_similarity=False, simi_return_mono=False,... |
def parse_line(line, extraction_map):
print("---------parsing line------")
key = get_key_for_line(line)
extraction_guide = extraction_map[key]
obj = get_blank_line_object()
flag = special_line_case(key)
answer_flag = special_answer_case(key)
if (flag == True):
line = escape_undersco... |
"""Suppoort for REST statistics."""
import logging
import requests
import time
import threading
import re
from homeassistant.components.sensor import DOMAIN as COMP_SENSOR
from homeassistant.components.binary_sensor import DOMAIN as COMP_BINARY_SENSOR
from homeassistant.const import (
CONF_NAME,
CONF_SENSORS,
... |
# coding=utf-8
'''
This script generates one (or multiple) .sh file that'll handle the generation of training examples (processed .csv files ultimately).
'''
import math
import os.path
import sys
from enum import Enum
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import utilities
PARENT_DIR = ''
OUTP... |
import nevergrad as ng
import argparse
import subprocess
import shlex
import numpy as np
from time import sleep
import pickle
import glob
import torch
import os
import shutil
from concurrent import futures
def get_file_name(dir_):
idx = np.random.randint(1)
fname = dir_ + str(np.random.randint(1,999999999,1)[0]) +... |
import numpy as np
def diff_of_means(data_1, data_2):
"""Difference in means of two arrays."""
# The difference of means of data_1, data_2: diff
diff = np.mean(data_1) - np.mean(data_2)
return diff
def _permutation_sample(data):
permuted_data = np.random.permutation(data)
... |
import sys
import numpy as np
from qtpy import QtCore, QtGui, QtWidgets
import matplotlib.pyplot as plt
from matplotlib.backends.qt_compat import QtCore, QtWidgets, is_pyqt5
if is_pyqt5():
from matplotlib.backends.backend_qt5agg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
else:
fr... |
# This module is part of Hypatia and is released under the
# MIT license: http://opensource.org/licenses/MIT
"""Sprites!
Tools for animation. Animation sources are GIFs from disk, which
have been made into an AnimatedSprite object. Stateful animations
which represent objects, e.g., :class:`Walkabout` represent... |
# @Author : <NAME> & <NAME>
# @Software: PyCharm
import keras.backend as K
from keras.engine.topology import Layer
import numpy as np
import tflearn
from dataset.data_utils import *
class Multiheads_Attention(Layer):
def __init__(self, multiheads, head_dim, mask_right=False, **kwargs):
"""
# Par... |
import os,sys,time,json,requests,re,random
def clear():
os.system("clear")
def balik():
f = input("\n\033[1;97m\t[\033[1;93mEnter To Back\033[1;97m]")
if f == "":
os.system("python sub.py")
else:
sys.exit("\033[1;91mexit\033[00m")
def load():
for x in range(1,101):
time.sleep(1... |
"""
Handles datasets for the manifold OT project
"""
import graphtools
import numpy as np
from scipy.stats import special_ortho_group
import sklearn.datasets as skd
import sklearn.metrics
from sklearn.neighbors import kneighbors_graph
import ot
import pygsp
class Dataset(object):
""" Dataset class for Optimal T... |
"""
Defines callback functions for the Dash app. This is how the application is able to dynamically update its content
(tables, graphs, etc.) based on the user input (search bar, dropdown, etc.).
"""
# -*- coding: utf-8 -*-
import base64
import datetime
import io
import json
from app import app
from data import par... |
import os
import sys
ROOT_DIR = os.path.abspath("../")
PROCESSED_PATH = os.path.join(ROOT_DIR, "../data/processed/")
MODEL_PATH = os.path.join(ROOT_DIR,"../models/")
sys.path.append(ROOT_DIR)
sys.path.append(os.path.join(ROOT_DIR,"experiments"))
sys.path.append(os.path.join(ROOT_DIR,"deprecated"))
sys.path.append(os.pa... |
# %% Chaotic LSTM
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
# Set problem dimensions
batch_size = 1
input_size = 1
hidden_size = 2
# Generator a grid of points 1d
def generate_points(pt1, pt2, s_list):
for s in s_li... |
import argparse
import unittest
import re
import math
from names import Names
class Transform:
def __init__(self, names):
self.names = names
self.rule = {}
self.forward = {}
self.backward = {}
def monotone_from_stat(self, stat):
for feature_name in self.names.feature_l... |
from __future__ import annotations
import json
import os
import re
import time
from typing import Dict, Optional, List
import requests
class JsonObject:
def __init__(self, data):
self._data = data
class Feature(JsonObject):
def __init__(self, data):
super().__init__(data)
self.feat... |
#!/usr/bin/env python
"""SimplyRETS SDK API client."""
__author__ = "Christopher and <NAME>"
__copyright__ = "Copyright 2015, SimplyRETS Inc. <<EMAIL>>"
__credits__ = ["<NAME>", "<NAME>"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
import sys
impo... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""This module contains the Combination_Grapher to graph ddos simulations"""
__Lisence__ = "BSD"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>, <EMAIL>"
__status__ = "Development"
from copy import deepcopy
import os
import matplotlib.pyplot as plt
from matplotlib.line... |
import hashlib
import json
from datetime import datetime, timezone
import requests
from mainnet_bootstrap import remcli, run, intToRemCurrency, get_chain_id, wallet_port
producers_quantity = 21
producers_supply = 500_000_000_0000
swapbot_stake = 1_000_0000
MINIMUM_PRODUCER_STAKE = 200_0000
sign_digest_url = f'htt... |
import numpy as np
import pickle
import json
import ruamel.yaml
import os
import pandas as pd
import sys
sys.path.append("/home/stian/Master_thesis_fork/st-gcn/tools")
from views.output_messages import duplicate_files_error_message
def humanize_time(secs):
mins, secs = divmod(secs, 60)
hours, mins = divmod(mi... |
#!/usr/bin/env python
"""
MIPhy - Minimizing Instability in Phylogenetics.
This program reconciles a multi-species phylogenetic tree of some gene family
with the underlying species tree, and clusters the gene tree into phylogenetic
groups. These groups each receive an instability score, used as a proxy of
adaptive evo... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Email: <EMAIL>
@Copyright: go-hiroaki
@License: MIT
"""
import os
import time
import torch
import vision
import metrics
import argparse
import numpy as np
import pandas as pd
from skimage.io import imread, imsave
import warnings
warnings.simplefilter(action='i... |
#!/usr/bin/env python
# ------------------------------------------------------------------------------------------------------%
# Created by "<NAME>" at 18:10, 06/04/2020 %
# ... |
"""
network3.py
~~~~~~~~~~~
A Theano-based program for training and running simple neural
networks.
Supports several layer types (fully connected, convolutional, max
pooling, softmax), and activation functions (sigmoid, tanh, and
rectified linear units, with more easily added).
When run on a CPU, this program is much ... |
import numpy as np
from func import arr_stat, RESULT_DIR
def tpr95(in_data, out_data, is_diff=False):
return 0
# calculate the falsepositive error when tpr is 95%
start = np.min(np.array([in_data, out_data]))
end = np.max(np.array([in_data, out_data]))
gap = (end - start) / 10000
Y1 = out_data... |
#!/usr/bin/python
# Copyright 2020 Makani Technologies LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
import inspect
import logging
import regex as re
import traceback
import sys
if sys.version_info[0] >2:
PY3K=True
else:
PY3K=False
import six
from collections import OrderedDict
log=logging.getLogger(__name__)
def _get_all_subclasses(cls, include_base = False):
"""
Get all subclasses of a given ... |
import networkx as nx
import numpy as np
# [2020-07-15] nx1 downgrade
#
# * set_attributes() functions - not found
# * Iteration over .nodes() => nodes_iter(data=True) or __iter__() - Done
# * Acessing .nodes() attrs => .node[] - Done
# * Iteration over .neighbors => .neighbors_iter() - Done
# * Edge... |
from __future__ import absolute_import, division, print_function
from . import imgproc
import os
import six
import glob
import numpy as np
import pandas as pd
import skimage.io as skio
import sklearn.utils as sklu
import pulse2percept as p2p
def _loads_data_row_a16(row):
# Electrodes have legacy names in datafi... |
#!/usr/bin/env python3
"""
Find the session agenda and the list of speakers announced to speak.
The result should look like this:
- agenda item number (1, 2, ...)
- agenda item description
- agenda item list of speakers
The end of the agenda is reached when there is the item "Entschuldigt
waren ..." or the ... |
import argparse
from tqdm import tqdm
from math import ceil
import torch
import torch.nn.functional as F
from torch_geometric.data import DenseDataLoader
import torch_geometric.transforms as T
from torch_geometric.nn import DenseSAGEConv, dense_diff_pool
from torch.utils.data import random_split
from torch_geometric.d... |
from sqlalchemy import create_engine, Column, Table, ForeignKey, MetaData
from sqlalchemy.orm import relationship # , foreign
from sqlalchemy.ext.declarative import declarative_base # DeclarativeBase
from sqlalchemy import (
Integer, String, Date, DateTime, Float, Boolean, Text)
from scrapy.utils.project import g... |
# -*- coding: utf-8 -*-
import pytest
import json
import time
from data_feeder_plugins.resilientfeed.resilient_common import DBSyncFactory
DB_FILE = "/tmp/test_{}.sqlite3".format(time.time())
@pytest.fixture
def db_conn():
return DBSyncFactory.get_dbsync(202, DB_FILE, None, None, None) # org_id, sqllite_file, db_... |
from mmdet.core import (bbox2roi, bbox_mapping, merge_aug_bboxes,
merge_aug_masks, merge_aug_proposals, multiclass_nms)
import torch.nn.functional as F
class RPNTestMixin(object):
def simple_test_rpn(self, x, img_meta, rpn_test_cfg):
rpn_outs = self.rpn_head(x)
proposal_inp... |
import re
import random
import string
from datetime import datetime, time
from pytz import UTC
def array_info(arr):
"""
returns ndims, *lengths
"""
if not isinstance(arr, (list, tuple, set)):
return 0,
subs = set([array_info(elem) for elem in arr])
if len(subs) > 1:
raise ValueE... |
import collections
import copy
import random
from typing import List, Tuple, Optional
import pytest
import numpy as np
import dill as pickle
from poker_ai.games.short_deck.state import ShortDeckPokerState
from poker_ai.games.short_deck.player import ShortDeckPokerPlayer
from poker_ai.poker.card import Card
from poker... |
import numpy as np
class Grid():
@staticmethod
def get_ZNl(N):
r"""
it produces index set ZNl=\underline{\set{Z}}^d_N :
ZNl[i][j]\in\set{Z} : -N[i]/2 <= ZNl[i] < N[i]/2
"""
ZNl = []
N = np.atleast_1d(np.array(N, dtype=np.int))
for m in range(N.size):
... |
"Module to handle vcf files"
import logging
import yaml
from .constants import (
COLON,
COMMA,
DOT,
EQUALS,
NEW_LINE,
PIPE,
SEMICOLON,
SLASH,
TAB,
TYPES,
VCF_FILEFORMAT,
VCF_HEADER
)
LOG = logging.getLogger(__name__)
class INFOParser:
"""
Class to custo... |
"""
pre_post_specificity.py
Plot of p_s^pre vs. p_s^post in the adult. Cells fall into one of
four categories: (+,+), (+,-), (+,-) or (-,-) indicated by red, yellow,
orange and blue, respectively. Table gives the fraction of neurons in each
category. Outlier neurons in the last category (-,-) are labeled. Homologou... |
import pathlib
import re
from typing import Tuple, List, Union
import pandas as pd
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from matplotlib import colors, patches
import matplotlib.lines as mlines
from experiments.dataset import _BaseDataset
from experiments.dataset import _BasicClas... |
#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#
from flask import Flask, render_template, request
# from flask.ext.sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandl... |
"""
Wrappers for tools for calculation of evolutionary
couplings from sequence alignments.
Authors:
<NAME>
"""
from collections import namedtuple
import re
import pandas as pd
from evcouplings.utils.system import (
run, valid_file, create_prefix_folders,
verify_resources, ResourceError
)
def parse_plmc_... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2016-2019 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
import os
import sys
import math
from collections.abc import Iterable
import shutil
import time
# For some reason this fixes some problems on Windows
os.system('')
class frange:
def __init__(self, start, end=None, step=None):
self.start = None
self.end = None
self.step = None
if end is None:
self.end = f... |
from utilities.python_path_utility import append_to_pythonpath
append_to_pythonpath(['feature_extractors/reid_strong_baseline'
,'feature_extractors/ABD_Net'
,'detectors/mmdetection'
,'evaluation/py_motmetrics'
,'trackers/fair/src/l... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Retrieve bikeshare stations metadata."""
# pylint: disable=invalid-name
from io import BytesIO
from typing import Dict, List
from urllib.request import urlopen
from zipfile import ZipFile
import geopandas as gpd
import pandas as pd
import pandera as pa
import requ... |
from . import database
from . import support
from .index import Index
from .random import Random
import hashlib
import json
import numpy as np
import os
import tensorflow as tf
class Input:
def __init__(self, config):
klass, training_path, validation_path, testing_path = \
Input._identify(conf... |
from __future__ import annotations
import asyncio
import uuid
from typing import Optional, Tuple, Sequence, Awaitable, Any, Dict
from meadowrun.azure_integration.azure_meadowrun_core import (
_ensure_managed_identity,
ensure_meadowrun_resource_group,
get_default_location,
)
from meadowrun.azure_integratio... |
#!/usr/bin/env python
from copy import deepcopy
import math
import numpy
import random
from threading import Thread, Lock
import sys
import actionlib
import control_msgs.msg
import geometry_msgs.msg
import moveit_commander
import moveit_msgs.msg
import moveit_msgs.srv
import rospy
import sensor_msgs.msg
import tf
imp... |
# Code for MedT
import torch
import lib
import argparse
import torch
import torchvision
from torch import nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.utils import save_image
import torch.nn.functional as F
import os
import matplotli... |
import os, re
timereg = re.compile('(\d+):(\d+).(\d)')
rootdir = os.path.abspath('./NBAGamesDatabase')
#DOMAIN: year
#RANGE: array of [[boxscore location, pbp location, DD/MM/YYYY], ...]
def getGameFiles(year):
rootdir2 = rootdir + '/' + year
games = []
dirs1 = os.listdir(rootdir2)
for dir1 in ... |
"""
This module contiains various mathematical models for a modelica model.
"""
from typing import Any, Dict, List, Union
import casadi as ca
SYM = Union[ca.SX, ca.MX]
class CasadiModel:
def __init__(self, sym, *args, **kwargs):
self.sym = sym
# handle user args
for k, v in kwargs.item... |
import numpy as np
import random
from pyrosetta import *
def gen_rst(npz, tmpdir, params):
dist,omega,theta,phi = npz['dist'],npz['omega'],npz['theta'],npz['phi']
# dictionary to store Rosetta restraints
rst = {'dist' : [], 'omega' : [], 'theta' : [], 'phi' : [], 'rep' : []}
########################... |
"""Module with different loggers for rtd models and its components.
`RtdLogger` is main abstract class that all other loggers implement.
Loggers handle non-fatal events (info, debug, warning and non-fatal
error messages) as well as internally stored intermediate process data.
General guidelines:
- **Skip logging and... |
import pytest
import mjooln as mj
def test_volume():
assert mj.Path('/').is_volume()
def test_folder(tmp_folder, tmp_files):
_num_test_files = len(tmp_files)
with pytest.raises(mj.FolderError):
mj.Folder(str(tmp_files[0]))
folder = mj.Folder.join(tmp_folder, 'new_folder')
assert len(tmp_... |
#!/usr/bin/env python3
""" This entry knows how to make other entries.
"""
from copy import deepcopy
import logging
import os
def walk(__entry__):
"""An internal recursive generator not to be called directly
"""
ak = __entry__.get_kernel()
assert ak != None, "__entry__'s kernel should be defined"
... |
import torch
import torch.nn as nn
import torch.nn.functional as func
from torch.distributions import Normal
from torch.nn.utils import spectral_norm
from torch.utils.data import Dataset
from torchvision.datasets import MNIST, CIFAR10
from torchvision.transforms import ToTensor
from torchsupport.data.io import make_d... |
""" Converts texts to datapoints, and the other way around.
Will be made mostly obsolete after the planned transition to a database is done.
"""
import pandas as pd
import helper_funcs
import launch_utils
channels = launch_utils.read_configs()["data_channels"]
def find_all_positions_of_character(istr, character):
... |
import itertools
import numpy as np
from scipy.sparse.csgraph import shortest_path
class Node:
def __init__(self, value, index, meta={}):
self.in_edges = []
self.out_edges = []
self.value = value
self.index = index
self.meta = meta
def __repr__(self):
return f... |
import os
import time
import fcntl
import platform
import subprocess
import tempfile
from pyroute2 import IPDB
from pyroute2 import IPRoute
from pyroute2 import NetNS
from pyroute2 import NSPopen
from pyroute2.common import uifname
from pyroute2.netns.process.proxy import NSPopen as NSPopenDirect
from pyroute2 import n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (C) 2016-2020 Centre National d'Etudes Spatiales (CNES), CSSI, CESBIO 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 ... |
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/... |
from data.utils import load_data_torch
import pickle
from torch.nn import Module
from src.utils import *
from src.layers import *
import sys
import time
import os
import matplotlib.pyplot as plt
sys.setrecursionlimit(8000)
with open('data/decagon_et.pkl', 'rb') as f: # the whole dataset
et_list = pickle.load(f... |
# Imports here
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
from torchvision import datasets, transforms, models
from PIL import Image
import json
from collections import OrderedDict
# Set up model
def setup_model(structure = 'vgg16',... |
#Programming Chals
from random import randint
# RSA Flags
from .libctf import make_fermat_chal, make_bsa, make_hba, make_rsa, make_common_mod
# Classical Ciphers
from .libctf import make_hill, make_affine
from .libctf import make_masterhacker, make_fizzbuzz
"""
CTFClub Project
By <NAME> <<EMAIL>>
Licensed AGPLv3 Or l... |
# Code adapted from:
# https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb
# See THIRD-PARTY-NOTICES.TXT
from object_detection.utils import visualization_utils as vis_util
from object_detection.utils import label_map_util
from object_detection.utils import ops... |
#!/usr/bin/env python
import os
import struct
from queue import Queue
import time
import threading
import socket
import sys
import signal
import ntpath
# Getting currunt path
currunt_path_temp = os.path.abspath(__file__)
currunt_path = os.path.split(currunt_path_temp)[0] + "/"
server_host = ""
server_port = ""
if (... |
import read_data as rd
import numpy as np
from collections import Counter
from sklearn.metrics import accuracy_score
from tqdm import tqdm
import matplotlib.pyplot as plt
attributes = rd.attributes[1:]
attributes = [(i, attr) for i, attr in enumerate(attributes)]
nodes = []
graph = {}
def my_plot(train, valid, test,... |
'''
This benchmark performs convergence tests on multiple realizations of the 2D Branin function.
Details of the 2D Branin function can be found at https://www.sfu.ca/~ssurjano/branin.html.
This particular version uses 8 realizations of the Branin function, each with a different
set of parameters. The code samples thes... |
import pandas as pd
import dash
from dash import html, dcc
import dash_bootstrap_components as dbc
from dash_extensions.javascript import Namespace
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from dash_tabulator import DashTabulator
from . import tools as T
ns = Nam... |
import os
import shutil
import pkg_resources
import pickle
import dreambeam
from antpat import radfarfield
from antpat.io.NECread import readNECout_tvecfuns
from antpat.reps.hamaker import convDPE2LOFARcc, convLOFARcc2DPE
class FeedWiz(object):
def __init__(self):
feed_paths = self._get_feed_paths()
... |
'''
a module for processing json raw info to serialize info
'''
import bilibiliSpider
import ToolBox
from Config import spider_config
import csv
from multiprocessing import Pool
import os
import time
default_spider = bilibiliSpider.bilibili_spider()
default_output_path = spider_config.output_path
default_spider.mas_pr... |
"""
This file is part of SleekBot. http://github.com/hgrecco/SleekBot
See the README file for more information.
"""
import datetime
import time
import logging
from sleekbot.commandbot import botcmd
from sleekbot.plugbot import BotPlugin
class seenevent(object):
""" Represent the last know activity of a u... |
# coding=utf-8
"""
数据源解析模块以及示例内置数据源的解析类实现
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import numpy as np
import pandas as pd
from .ABuSymbol import EMarketTargetType
from ..CoreBu.ABuFixes import six
from ..UtilBu import ABuDate... |
"""
The BatchImage module defines Mask Objects and Marker Objects.
Most importantly it defines BatchImage Objects which are aggregations
of masks and markers (maybe a tiff stack...).
Additionally, it defines the functions used to analyze the overlaying of
masks and markers. A typical pseudo-code usage definition is as... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import io
import os
import sys
import zlib
import argparse
import contextlib
import concurrent.futures
import pdfrw
import numpy as np
from PIL import Image, TiffImagePlugin
import imgautocompress
__version__ = '0.3'
def xobj_getimg(obj):
if obj['/Subtype'] != '... |
import codecs
import gzip
import os
import pickle
from typing import Callable, Optional
import numpy as np
from flaxseed.utils.data import Dataset
from flaxseed.utils.download import download_url
__all__ = ["MNIST", "FashionMNIST", "KMNIST"]
class MNIST(Dataset):
"""`MNIST <http://yann.lecun.com/exdb/mnist/>`... |
import bcolz, os, time
import numpy as np
from sklearn.model_selection import train_test_split
import keras
from keras import backend as K
from keras.callbacks import ModelCheckpoint,EarlyStopping
from keras.utils.np_utils import to_categorical
from keras.preprocessing import image
from keras.models import Se... |
#import pdb
#import math
#import warnings
#import numpy as np
import torch
#import torch.nn as nn
#import torch.nn.functional as F
from torch.autograd.function import Function
__all__ = ['Quantize_W', 'Quantize_A', 'Quantize_E']
def min_max(x, group):
''' calculate min max or mins maxs for group-wise with inpu... |
import sys
import click
import numpy as np
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication
@click.group()
def main():
pass
@main.command()
@click.argument('prbfile', nargs=1)
def prb_check(prbfile, font_size=33):
'''
check prb by visualization
'''
from spiketag.base impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.