text stringlengths 3.07k 22.1k |
|---|
"""
Basic text classification
---
This tutorial demonstrates text classification starting from plain text
files stored on disk. You'll train a binary classifier to perform sentiment
analysis on an IMDB dataset. At the end of the notebook, there is an exercise
for you to try, in which you'll train a multiclass classifie... |
# -*- coding: utf-8 -*-
from copy import deepcopy
from itertools import groupby
from typing import Union, List
from operator import attrgetter
from monty.json import MSONable
from pydefect.analysis.defect import Defect
from pydefect.util.logger import get_logger
from pymatgen.analysis.structure_matcher import Structu... |
# coding=utf-8
######################################################################
##|# -------- modARP : ARP management module for MANGLE -------- #|###
##|# - It is responsible for handling ARP requests and replies - #|###
##|# - in order to avoid triggering switch's security measures - #|###
##|# - while still pr... |
import logging
import uuid
import json
import re
import types
import datetime
import pytz
from django.db import models
from django.utils import timezone
from django.conf import settings
from django_countries.fields import Country
from audit.mixins import AuditableMixin
from dirtyfields import DirtyFieldsMixin
from djan... |
from pprint import pprint
from collections import OrderedDict
from wtforms_jsonschema2.fab import FABConverter
from wtforms_jsonschema2.conditions import oneOf
from unittest import TestCase
from flask_appbuilder import AppBuilder
from flask import Flask
from flask_appbuilder import ModelView
from flask_appbuilder.model... |
# -*- coding:utf-8 -*-
# @author :adolf
import os
import numpy as np
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from dataset import UNetSegmentationDataset as Dataset
from loss import DiceLoss
from data_aug.transforms import get_transforms
from unet_model im... |
import tensorflow as tf
from deepctr.input_embedding import preprocess_input_embedding
from deepctr.layers.core import MLP, PredictionLayer, NumericFeatureColumnLayer, EmbeddingFeatureColumnLayer
from deepctr.layers.interaction import CIN
from deepctr.layers.utils import concat_fun
from deepctr.utils import check_featu... |
""" Module for risk-exploiting landmark identification scenario
- Scenario is derived from ergo_spread_small.py which is, in turn, derived from simple_spread.py
- N-agents must disribute themselves to cover N-landmarks
- Reward is based on the distance from each landmark to the closest agent (identical_reward case)
- O... |
# -*- coding: utf-8 -*-
"""
This module implements :class:`SpikeTrainList`, a pseudo-list
which supports a multiplexed representation of spike trains
(all times in a single array, with a second array indicating which
neuron/channel the spike is from).
"""
import numpy as np
import quantities as pq
from .spiketrain imp... |
import datetime
import uuid
import threading
import ipyleaflet
import ipywidgets as widgets
import traitlets
from ..models import XYZ
from ..types import Image
from . import parameters
from .clearable import ClearableOutput
class ScaleFloat(traitlets.CFloat):
"Casting Float traitlet that also considers the em... |
# -*- coding: utf-8 -*-
import os
import sys
import requests
import xmltodict
from six.moves import queue as Queue
from threading import Thread
import re
import json
# Setting timeout
TIMEOUT = 10
# Retry times
RETRY = 5
# Medium Index Number that Starts from
START = 0
# Numbers of photos/videos per page
MEDIA_NU... |
import math
from typing import List, Union
import hydra
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from omegaconf import OmegaConf
from torch.cuda.amp import autocast
from torch.nn import CTCLoss
from deepspeech_pytorch.real_dtw import compute_dtw
from deepspeech_p... |
import asyncio
import discord
from discord.ext import commands
import ffmpeg
import media_cache
import os
import random
import re
import subprocess
from subprocess import Popen
import video_creator
import youtube_dl
class Corruption(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.use_yt... |
import random
import albumentations as A
import cv2
import numpy as np
import torch
__all__ = ["BoxesDropout", "CoarseDropoutWithBboxes"]
class BoxesDropout(A.DualTransform):
"""
Remove objects and fill image & mask corresponding to removed bboxes.
"""
def __init__(
self,
max_object... |
import numbers
from collections import namedtuple
from functools import total_ordering
from math import isclose
import numpy as np
from .utils import name_generator
from .utils import color_generator
from .utils import normal_noise_generator
from .utils import uniform_noise_generator
from .utils import timesequence_gen... |
"""
HyperFlex HTML Plug-In Automated Installer v2
Author: <NAME>
Contact: <EMAIL>, <EMAIL>
Summary: The HyperFlex HTML Plug-In Automated Installer automates installing
the Cisco HyperFlex HTML Plug-In for VMware vCenter.
Notes: Tested on Cisco HyperFlex HTML Plug-In for VMware vCenter 2.1.0, HyperFlex 5.... |
import inspect
from auditlog.models import AuditlogHistoryField
from auditlog.registry import auditlog
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.fields import ArrayField
from django.core.valida... |
"""
This module provides the ChemicalSystem class for managing quantities related
to elements, composition, and element-element interactions.
"""
from typing import List, Dict, Collection, Tuple, Any
import itertools
import numpy as np
import ase
from ase import symbols as ase_symbols
reference_X = dict(X=0, H=2.2, ... |
#!/usr/bin/env python
"""Filter a FASTA, FASTQ or SSF file with SAM/BAM mapping information.
When filtering an SFF file, any Roche XML manifest in the input file is
preserved in both output files.
This tool is a short Python script which requires Biopython 1.54 or later
for SFF file support. If you use this tool in s... |
from flask import request, url_for, jsonify
from flask_api import FlaskAPI, status, exceptions
from api.DBmodels import Accounts, Gimnasio
from datetime import datetime
from bson import ObjectId
import json
import random
class GymAPI(object):
#USUARIOS
#Obtener todos los usuarios
def get_all_users... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
kuehbach at fhi - berlin . mpg . de
parser for file formats
processtype: post-processing/analyze
methodgroup: aptfim
methodtype: parser
methodvariant: rrng file format, ###MK::give more detail what this format is
2021/03/01
"""
import os, sys, glob, re
import numpy as... |
#!/usr/bin/env python
import sys
import optparse
try:
# Ubuntu deps: gfortan libblas-dev liblapack-dev
# pip deps: numpy scipy
from math import sqrt
from scipy.optimize import root
import numpy as np
except ImportError:
# Allow this script to be used for global FDR even
# if these dependenc... |
import random
from pathlib import Path
import shutil
from typing import Union, List, Type, Tuple, Iterable
import pytest
import ycbvideo.frame_access
from ycbvideo.loader import Loader
@pytest.fixture()
def loader(dataset):
return Loader(dataset)
def check_frame_items(frames: Iterable[ycbvideo.frame_access.Fr... |
import os
import re
import functools as ft
import itertools as it
import operator
import numpy as np
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from concurrent.futures import as_completed as cf_as_completed
import multiprocessing
try:
from pyrosetta import rosetta a... |
import os
import argparse
import pickle
import csv
import torch
from torch.utils.data import DataLoader
from transformers import GPT2Tokenizer, GPT2LMHeadModel
from tqdm import tqdm
from src.model.data_full import PromtDataset
from src.model.pipeline import copy_data_to_device, init_random_seed
from typing import List... |
import torch
import numpy as np
from tqdm import tqdm
from pytorch3d.loss import chamfer_distance
from NURBSDiff.surf_eval import SurfEval
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from geomdl import NURBS, multi, exchange, operations
from geomdl.visualization imp... |
import os.path
import pprint
import csv
import re
import argparse
import pathlib
from googleapiclient import errors
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# ... |
from warnings import warn
from os.path import join
from cobra.core import Model
from cobra.flux_analysis.gapfilling import GapFiller
from .likelihood import LikelihoodAnnotation
from .templates.util import read_json_file, create_boundary
from .templates.universal import create_universal_metabolite, metabolite_json_sc... |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
import pickle
import numpy as np
from torch.utils.data.dataset import Dataset
from pymatgen.core.structure import Structure
#... |
from math import tanh
from pysqlite2 import dbapi2 as sqlite
def dtanh(y):
#this effectively creates a smaller change multiplier when the value is closest to 0 (when the slope is steepest) P_D controller?
return 1.0-y*y
class SearchNet:
def __init__(self, dbname):
self.con = sqlite.connect(dbname)
def __del__(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2012 <NAME> <mkalewski at cs.put.poznan.pl>
#
# This file is a part of the Simple Network Simulator (sim2net) project.
# USE, MODIFICATION, COPYING AND DISTRIBUTION OF THIS SOFTWARE IS SUBJECT TO
# THE TERMS AND CONDITIONS OF THE MIT LICENSE. YOU SHOULD HAVE RECEI... |
#!/usr/bin/env python
#
# brief: soylent calculator
# author: bto
# date: Jun 2013
#
# resources:
# nutritiondata.self.com
# ars.usda.gov
#
# Notes:
# - Radical diet changes never seem to work. keeping a food diary and making
# incremental changes based on overamounts/deficiencies works better
# - It's easy to m... |
"""
Module that contains the command line app.
Why does this file exist, and why not put this in __main__?
You might be tempted to import things from __main__ later, but that will cause
problems: the code will get executed twice:
- When you run `python -mtravis2docker` python will execute
``__main__.py`` a... |
################################################################################
# Copyright (c) 2019-2020, National Research Foundation (Square Kilometre Array)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the... |
import re
import tempfile
import pandas as pd
import camelot
import pandas as pd
import requests
import us
import textract
from can_tools.scrapers.official.base import StateDashboard
from can_tools.scrapers import variables, CMU
from typing import Any, Dict
class FloridaCountyVaccine(StateDashboard):
has_locatio... |
from typing import TYPE_CHECKING, Type, Iterator, Optional, Union, Dict, Iterable
from ..exceptions import RequestError
try:
import simplejson as json
except ImportError:
import json
if TYPE_CHECKING:
from pyrtable._baseandtable import _BaseAndTableProtocol
from pyrtable.filters.base import BaseFilt... |
from argparse import ArgumentParser
import random
from re import A
import cv2
from copy import deepcopy
from pathlib import Path
from joblib import Parallel, delayed
from matplotlib import pyplot as plt
import numpy as np
import open3d as o3d
import Regions as RG
from tqdm import tqdm
from data_processing.segmentation... |
from Node_Depths import nodeDepths, BinaryTree
def findNode(nodes, id):
if id==None:
return None
for node in nodes:
if node["id"] == id:
n = BinaryTree(node['value'])
n.left = findNode(nodes, node['left'])
n.right = findNode(nodes, node['right'])... |
# -*- coding: utf-8 -*-
# @Time : 2021/01/03 23:42:24
# @Author : ddvv
# @Site : https://www.cnblogs.com/ddvv
# @File : mmdt.py
# @Software: Visual Studio Code
# @Desc : None
import os
import platform
import numpy as np
from ctypes import *
from python_mmdt.mmdt.common import mmdt_load,mmdt_s... |
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
from a816.cpu.cpu_65c816 import snes_opcode_table, AddressingMode, get_opcodes_with_addressing
from a816.parse.errors import ScannerException
from a816.parse.scanner import Scanner
from a816.parse.tokens import TokenType, EOF
opcodes = snes_opcode_table.keys()
opcodes_without_operand = get_opcodes_with_addressing(Addr... |
#! /usr/bin/env python
import sys
import numpy as np
import pandas as pd
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import logomaker as lm
from collections import defaultdict
from fonts.ttf import Roboto
from matplotlib import font_manager
font_manager.fontManager.addfont(Roboto)
N = ["A... |
import httplib2
import os, sys
import logging
import time
import socket
import logging
from concurrent import futures
import threading
import json
from googleapiclient import discovery, errors
from googleapiclient.http import HttpRequest
from oauth2client import client, _helpers
from oauth2client.file import Storage
... |
"""
--------------------------
OFFLINE OPTIMAL BENCHMARK:
---------------------------
It uses IBM CPLEX to maximise the social walfare of a current network structure and task list by solving the current environment given the usual problem restrictions.
This represents the upper bound of the social walfare.
In order ... |
__author__ = 'feliciaan'
import json
from threading import Thread
import requests
from flask import url_for, render_template, abort, redirect, Blueprint, flash, session, request
from flask_login import current_user, login_required
import random
from datetime import datetime
from app import app, db
from models import O... |
# -*- coding: utf-8 -*-
# */
# * Licensed to the Apache Software Foundation (ASF) under one
# * or more contributor license agreements. See the NOTICE file
# * distributed with this work for additional information
# * regarding copyright ownership. The ASF licenses this file
# * to you under the Apache License, Versi... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... |
"""
Visual demonstrations of anarchy system.
viz.py
"""
import random
import os
import PIL.Image
from . import rng, cohort
MAX_RANDOM = rng.ID_MASK
def builtin_next():
"""
Returns random numbers using built-in random.
"""
return random.randint(0, MAX_RANDOM)
def demo_prng():
"""
Creates... |
# Test crys.rpdf() against reference results. Test 2 AlN structs from
# examples/rpdf/rpdf_aln.py and one random trajectory with selections (2 atom
# types) and time average.
#
# See examples/rpdf/ for more examples and VMD comparisons, esp. regarding
# nearest neighbors.
#
# See utils/gen_rpdf_ref.py for how the refer... |
import torch
from torch import nn
from contextpath import build_contextpath
import warnings
warnings.filterwarnings(action='ignore')
class ConvBlock(torch.nn.Module):
def __init__(self,
in_channels,
out_channels,
kernel_size=3,
stride=2,
... |
"""
functions for loading (writing?) data from disk
"""
from ..util import paths, download
from .. import config
from astropy.table import Table
from astropy.io import ascii
from zipfile import ZipFile
import os
import numpy as np
# load yanny reader and writer (this works for platePlans.par)
# but it does not for the... |
import scipy.stats
from colour import Color
import numpy as np
import pandas as pd
import os
import tempfile
import zipfile
import glob
import quandl
import plotly as py
import plotly.graph_objs as go
import plotly.offline as offline_py
from sklearn.preprocessing import Normalizer
offline_py.init_notebook_mode(connecte... |
import logging
import time
import traceback
from collections import Counter
import discord
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np
import pandas as pd
from bot import SentdeBot
from discord.ext import commands, tasks
from discord.ext.comm... |
import os
import sys
import pdb
class knapsack_data_processing:
def __init__(self, data):
self._data = data._data
self.item_set = {}
self.items = {}
self.ItemList = []
products = data._data['product'][None]
trials = data._data['trial'][None]
counter = 1
for i in products:
for j in trials:
item_... |
from sklearn.neighbors import NearestNeighbors
import cv2 as cv
import os
import asyncio
import websockets
import time
import socket
import threading
import struct
UTILS = os.path.join(os.getcwd(),"utils")
DATA = os.path.join(os.getcwd(),"data")
ID_DIR = os.path.join(DATA,"id")
ID_PATH = os.path.join(ID_DIR,"id.txt... |
from django.db import models
from django.conf import settings
from django.dispatch import receiver
from django.contrib.humanize.templatetags.humanize import naturaltime
from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import AES, PKCS1_OAEP
import secrets
import json
import os
from orbit.fields import Gende... |
# inspired from: https://github.com/openai/CLIP/issues/83
# https://github.com/openai/CLIP/issues/83
import json
import os
import random
import wandb
import clip
from clip import model
import torch
from torch import autograd
import tqdm
from torch import nn, optim
from PIL import Image
from pathlib import Path
from col... |
from __future__ import print_function, division
import asyncio
import functools as ft
import ipywidgets as ipw
import serial
import serial.tools.list_ports
def get_port(vid, pid):
try:
port = next(p for p in serial.tools.list_ports.comports()
if p.vid == vid and p.pid == pid)
exce... |
'''
Basic functions for reading binaries and EEG manipulation
Submodule of the Modular EEg Toolkit - MEET for Python.
Author:
-------
<NAME>
gunnar[dot]waterstraat[at]charite.de
'''
from . import _np
from . import _path
from . import _packdir
def readBinary(fname,num_channels,channels='all',readnum_dp='all',
... |
from pymongo import MongoClient
from pymongo.cursor import Cursor
from pymongo.command_cursor import CommandCursor
from microngo.pagination import Pagination
class Microngo(object):
def __init__(self, *args, **kwargs):
'''
:param str db: Database name. This param is optional, you can use :func:`~microngo.Microngo... |
# Tools for working with IMP8/ISEE data
import os
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt
import spacepy.datamodel as dm
import spacepy.time as spt
import spacepy.datamanager as dman
import spacepy.plot as splot
def readIMP8plasmafile(fname):
"""
ftp://space.mit.edu/pub/plasm... |
import cv2
import rawpy
import numpy as np
from math import pi
from math import sin
from colour_demosaicing import demosaicing_CFA_Bayer_Menon2007
# TODO: Fix white balance, demosaic, srgb, add crhoma denoise
# def black_white_level(input_, black_point, white_point):
# white_factor = 65535. / (white_point - bla... |
#!/usr/bin/env python
"""
Calculate the error (for simulations) between the known
peak locations and the peak locations returned by the analysis.
Note: This measures the error and *not* the recall. If only 1
in 100 peaks is found but their locations agree exactly with
the known locations then this will be considered g... |
# ==============================================================================================================
# MIT License
# 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
... |
import time
import math
class Ability():
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
self._lv = 0
self.cooldown_arr_backup = self._cooldown_arr
self.timestamp = 0
def intro(self):
print("This is lv %s %s \n %s attack" %(self.lv, self.name, self._dmg))
def ability_cost(self, champ):
if s... |
# -*- encoding=utf8 -*-
__author__ = "Administrator"
from airtest.core.api import *
auto_setup(__file__)
#每日
def Exit():
if exists(Template(r"tpl1583563297011.png", record_pos=(-0.456, -0.243), resolution=(1136, 640))):
touch(Template(r"tpl1583563297011.png", record_pos=(-0.456, -0.243), resolution=(1136,... |
import vdomr as vd
from mountaintools import client as mt
import numpy as np
import json
class JobView(vd.Component):
def __init__(self, compute_resource_client):
vd.Component.__init__(self)
self._compute_resource_client = compute_resource_client
self._job = None
self._back_handler... |
import base64
import os
import random
import string
from collections import OrderedDict
import pytest
from ledger.ledger import Ledger
from ledger.serializers.json_serializer import JsonSerializer
from ledger.serializers.compact_serializer import CompactSerializer
from ledger.compact_merkle_tree import CompactMerkleTr... |
import inspect
import os
import pdb
import random
import sys
import time
import datasets
import numpy as np
import torch
import transformers
from datasets import load_dataset, load_metric
from matplotlib import pyplot as plt
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.sampler import Sequen... |
"""
WORK IN PROGRESS
-- does not do anything useful at this point
"""
import six
import xarray as xr
from xr.core.pycompat import (
PY3, OrderedDict, basestring, iteritems, suppress)
class DFMMergeMap(xr.backends.AbstractDataStore):
def __init__(self,file_pattern):
"""
Open a set of DFM map ... |
#!/usr/bin/env python3
import _version
import csv
import gpxpy
from gpxpy.geo import get_course, distance, Location, LocationDelta
from datetime import datetime
from datetime import timedelta
import logging
from czml3 import Document, Packet, Preamble
from czml3.properties import (
# Billboard,
Clock,
Colo... |
from Unstructured import MyMesh, rand_Amesh_gen, rand_grid_gen, grid
from pyamg.gallery.diffusion import diffusion_stencil_2d
from pyamg.gallery import stencil_grid
from numpy import sin, cos, pi
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay
import scipy
import fem
import networkx as nx
import num... |
from hypothesis.verifier import (
falsify,
assume,
Unfalsifiable,
Unsatisfiable,
Verifier
)
from hypothesis.specmapper import MissingSpecification
from hypothesis.searchstrategy import (
SearchStrategy,
MappedSearchStrategy,
one_of,
SearchStrategies,
strategy_for
)
from coll... |
import numpy as np
from numba import njit
from global_variables import *
@njit(fastmath=True)
def unison_shuffled_copies(a):
np.random.seed(1)
p = np.random.permutation(len(a))
return p
@njit(fastmath=True)
def select_actors(events, step):
actors = np.nonzero(events[step])[0]
interactions = ev... |
from collections import Counter, defaultdict
import numpy as np
from sklearn.random_projection import GaussianRandomProjection
from sklearn.decomposition import PCA
import scipy.sparse as sparse
from preprocessing.transforms import transform_trees, inverse_transform_trees
import config
from tqdm import tqdm
from math i... |
from __future__ import print_function
import os
import subprocess
from pprint import pformat
from contextlib import contextmanager
from pyne import nucname
USE_COLOR = (os.name is 'posix')
DEFAULT_RC_FILE = "defaultrc.py"
DEFAULT_PLUGINS = ("bright.xsgen.pre", "bright.xsgen.make_mc_input",
"brigh... |
import pytest
import os
import numpy as np
from dae.pedigrees.loader import FamiliesLoader
from dae.variants.attributes import Inheritance
from dae.backends.vcf.loader import VcfLoader
@pytest.mark.parametrize(
"fixture_data",
[
"backends/effects_trio_dad",
"backends/effects_trio",
... |
import ast
import datetime as dt
from bdshare import get_current_trade_data, get_basic_hist_data
from rest_framework import viewsets, permissions, generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.exceptions import ValidationError
from django.shortcuts i... |
import json
import requests
from requests import exceptions
import redo
import ice
from ice import entities
ICE_AGENT_URL = 'http://dl.bintray.com/glestaris/iCE/v2.1.0/ice-agent'
class CfgRegistryClient(object):
"""Registry client configuration"""
def __init__(self, host, port):
"""Creates a registr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
## Copyright 2012 Memoria team
##
## 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-... |
import math
from .enums import StreamState
from .heat_range import HeatRange, merge_heat_range
from .plot_segment import PlotSegment
OVERALL_HEAT_TRANSFER_COEFFICIENT = {
StreamState.LIQUID: {
StreamState.LIQUID: 300.0,
StreamState.GAS: 200.0,
StreamState.LIQUID_EVAPORATION: 1000.0
},
... |
from xml.dom import minidom
import glob
import numpy as np
from skimage import color
from scipy import stats
import argparse
import math
import matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
import os
import json
def parse_xml(path):
colormap_xml = minidom.parse(path)
items = colormap_xml... |
#!/usr/local/bin/env python
from __future__ import division
import numpy as np
from numpy import array
from numpy.random import sample as rs
from numpy import newaxis as na
import pandas as pd
from scipy.stats import sem
import seaborn as sns
import string
import matplotlib.pyplot as plt
def update_Qi(Qval, reward, ... |
"""
description: Neural Bilateral Grid Training
@author: <NAME> (<EMAIL>)
@author: QZheng
"""
import os
import time
import argparse
import numpy as np
import tensorflow as tf
from tensorflow.python.client import timeline
from data_loader import dataLoader
from network import DenoiserGuideNet
from image_utils import ... |
import os
import io
from reportlab.lib import pagesizes
from reportlab.lib.colors import Color, white
from reportlab.lib.styles import ParagraphStyle as PS
from reportlab.lib.utils import simpleSplit
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
... |
# Copyright (c) 2019 - now, Eggroll 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 ... |
#!python
# Copyright 2017 by <NAME>.
# License: BSD, see LICENSE for more details.
"""
Thanks to Maarek for first inspiration
http://forum.ubuntu-fr.org/viewtopic.php?id=415396
Change history:
- 2015-09-19 accept non-ascii tags
- 2015-12-04 new command-line options `before` and `after`
"""
from __future__ import ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sunday Jan 17 13:44:56 2020
@author: <NAME>
"""
from keras.layers.core import Activation
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import OneHotEncoder
from sklearn.metrics import confusion_matrix
from keras.layers import Le... |
"""
A mechanism for watching a list of files or directories.
Any remote file system that supports the get/put api copies files
locally when "opened". A machanism is needed to check for changes
and copy the files back.
Different file systems have different methods for noftifying
when a file is changed. A callback s... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'homeway'
__copyright__ = 'Copyright © 2022/05/13, homeway'
import os
import os.path as osp
import sys
import inspect
import torch
import torch.nn.functional as F
from tqdm import tqdm
import copy
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(i... |
import sys
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append('../../')
import chardet
import time
import os
import random
import pandas as pd
import json
import requests
import captain
import logging
import argparse
import subprocess
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__... |
import os
import math
import argparse
import tensorboardX
import torch.optim as optim
import horovod.torch as hvd
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torch.utils.data.distributed
from tqdm import tqdm
from dataloaders import *
from torchvision.models import alexnet
from optimiz... |
import sys
import json as json
import ast
import os
import random
from tqdm import tqdm
import pdb
import re
################ From py-150k ################
def read_file_to_string(filename):
f = open(filename, 'rt')
s = f.read()
f.close()
return s
def parse_file(filename):
string = read_file... |
"""
Core
"""
import os
import numpy as np
import scipy.signal
import obspy
import seisnn.example_proto
import seisnn.io
import seisnn.plot
import seisnn.sql
class Metadata:
"""
Main class for metadata.
"""
id = None
station = None
starttime = None
endtime = None
npts = None
delt... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 7 15:29:26 2019
@author: dantitussalajan
"""
import numpy as np
# adding some useful columns; data is dataframe that must contain the mentioned columnms -- see the parquet function
# best add it for all data at the begining
def useful_updates1(d... |
#!/usr/bin/env python3
import time
import os
import signal
import logging
import numpy as np
import json
import asyncio
import argparse
import jsonschema
from katsdptelstate import endpoint
import katsdpservices
from katsdpcal.control import create_server, create_buffer_arrays, FlagsStream
from katsdpcal.pipelinepro... |
""".. Line to protect from pydocstyle D205, D400.
Demultiplexing
==============
Split FASTQ file into separate files, one for each sample barcode.
Saved FASTQ files contain sequences where sample barcode, random
barcode, and adapter sequences are removed. Random barcode is moved into
the header line, since it is nee... |
#!/usr/bin/env python3
#
# bspwm.py
#
# (c) 2016 <NAME>
import gi
import os
import re
import sys
import json
import select
import socket
import _thread
import netifaces
import subprocess
gi.require_version('Notify', '0.7')
from gi.repository import Notify
import utils
I3STATUS_PATH = '/opt/i3status/i3status'
I3... |
import spotipy
from dotenv import load_dotenv
import os
import json
from pprint import pprint
import time
class Track:
__slots__ = ['uri', 'track_name', 'album_name', 'artist_name', 'track_id', \
'popularity', 'acousticness', 'energy', 'valence', 'loudness', 'tempo', \
'danceability', 'liveness', '... |
import csv
import json
import pickle
import jax
from jax import jit, vmap, lax
import jax.numpy as np
from ncl.learners.fisher.approx import full
def save_params(params, result_dir):
with open('%s/params.p' % result_dir, 'wb') as f:
pickle.dump(params, f)
def save_all_states(state, result_dir, init=Fals... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.