text
stringlengths
3.07k
22.1k
""" Module for formatting songs into strings. Contains functions to create search queries and song titles and file names. """ import re import warnings from typing import List, Optional from pathlib import Path from yt_dlp.utils import sanitize_filename from spotdl.types import Song VARS = [ "{title}", "{ar...
# -*- coding: utf-8 -*- """ import_qualtrics_surveys- Uses Qualtrics API to automate the import and activation of the meaning map patch rating surveys. @author: <NAME> Modified by <NAME> Modified by Zoe Loh for NYU_Depth2 Dataset """ # %% 010: Import modules and define relative folder path # Set your p...
from dataclasses import dataclass import os from pathlib import Path from typing import Any, Dict, Optional, Union from .config import Config from .errors import Error, MethodError, NotSdistError, NotVCSError, NotVersioningitError from .logging import log, warn_bad_version from .methods import VersioningitMethod from ....
from __future__ import absolute_import from sfepy import data_dir import six filename_mesh = data_dir + '/meshes/3d/special/cube_cylinder.mesh' if 0: from sfepy.discrete.fem.utils import refine_mesh refinement_level = 1 filename_mesh = refine_mesh(filename_mesh, refinement_level) material_2 = { 'name...
def warn(*args, **kwargs): pass import warnings old=warnings.warn warnings.warn = warn import sklearn.model_selection as ms import imgaug warnings.warn=old import os import keras import random import imageio import numpy as np import traceback import random import cv2 as cv class PredictionItem: def __init__(...
#!/usr/bin/python import os import argparse import glob try: from cl.info.globals import DEFAULT_METRICS, AVAILABLE_METRICS except ImportError: DEFAULT_METRICS = ["WER", "CER"] AVAILABLE_METRICS = ["WER", "CER", "PER"] class NoEpochsTrained(Exception): pass _metric_maps = {m[0].lower(): m for m in AVAILAB...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import numpy as np import os import six import time from collections import OrderedDict from .utils import batch_indices import theano import theano.tensor...
try: i2c.deinit() except: pass """This class implements a BASIC interpreter that presents a prompt to the user. The user may input program statements, list them and run the program. The program may also be saved to disk and loaded again. orginal port : https://github.com/richpl/PyBasic Modified by BeBoX. 2021...
import pygame import numpy as np import sys from white import White from black import Black import cursors def map_update(w_flag, s_flag, pos): if w_flag and s_flag: sound.play() pygame.draw.circle(screen, White.color, pos, White.radius, White.width) if not w_flag and s_flag: sound.pla...
# -*- coding: utf-8 -*- """ ------------------------------------------------- Project Name: Poker-414 File Name: tools.py Author: Tridagger Email: <EMAIL> Create Date: 2021/11/24 ------------------------------------------------- """ from collections import Counter from core.poker import PokerCard def sort_card(cards)...
import ast import collections import functools class CodeModelError(Exception): pass class ReturnDictError(CodeModelError): pass class ScopeTracker(ast.NodeVisitor): """NodeVisitor that tracks its current scope. Scopes are named using a dot notation, with ``global`` as the outermost scope nam...
import os import re import textwrap from typing import List import aiohttp from discord import Color, Embed, utils from discord.ext.commands import Cog, CommandError, Context, command from discord.ext.commands.errors import CommandInvokeError import html2text from bot import config from bot.core.bot import Bot with ...
################################ # EvoMan FrameWork - V1.0 2016 # # Author: <NAME> # # <EMAIL> # ################################ import sys import numpy import random import Base from Base.SpriteConstants import * from Base.SpriteDefinition import * from sensors import Sensors tilemap = 'evoman/map2.tm...
from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import Classroom,Topic,ClassroomTeachers from posts.models import Assignment,SubmittedAssignment,Assig...
from __future__ import division, print_function, absolute_import import glob import os import os.path as osp from ..dataset import ImageDataset from SoccerNet.Downloader import SoccerNetDownloader as SNdl import zipfile class Soccernetv3(ImageDataset): """Soccernet-v3 train and valid sets. When set as "source" in...
from __future__ import print_function, absolute_import, division # makes these scripts backward compatible with python 2.6 and 2.7 # Importing the base class from mdof_base_model import MDoFBaseModel from co_simulation_tools import RecursivelyValidateAndAssignDefaults # Other imports import numpy as np from scipy im...
import numpy as np import random import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler def parameter_initializer(data): """ 初始化权值 """ w1=data[:12].reshape(4,3) b1 =data[12:15].reshape(1,3) w2 =data[15:18].reshape(3,1) b2 =data[18].reshape(1,1) return w1, b1, w2, b2 def ...
import pygame import random from .. import scenes import math from .. import container from . import plasma from . import anchors from . import mutator from . import decor from . import gapfiller from . import converter from . import prep from . import rooms from .rooms import Room from . import architect from . impor...
import fenics as fe import numpy as np import matplotlib.pyplot as plt import sys plt.rcParams.update({'font.size': 12}) fe.set_log_level(40) # -- Constants rho = 1 r0 = 0.5 alpha = 1 E = 3e6 h0 = 0.05 beta = E*h0*np.sqrt(np.pi) nu = 0.046 KR = 8*np.pi*nu A0 = np.pi*r0**2 Q0 = 0 def matMult(A,x): return [ A[0][0...
import math import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + math.exp(-x)) # Function to know if we have a CCW turn def CCW(p1, p2, p3): if (p3[1]-p1[1])*(p2[0]-p1[0]) >= (p2[1]-p1[1])*(p3[0]-p1[0]): return True return False # Main function: def create_convex_hull(S): """take...
import bisect import json import numpy as np import pandas as pd import utils def get_params(param_file, passenger): # read in parameters with open(param_file, 'r') as infile: TRAIN_PARAMS = json.load(infile) FITTED_PARAMS = {'log_decay': TRAIN_PARAMS['log_decay']} for feat, val in zip(TRAI...
import os import time from typing import Tuple from grpc._channel import _Rendezvous from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel from clarifai_grpc.grpc.api import service_pb2, service_pb2_grpc from clarifai_grpc.grpc.api.status import status_code_pb2 DOG_IMAGE_URL = "https://samples.clarifai....
import urllib.request import re import webbrowser import os import sublime, sublime_plugin import json #ctrl+alt+w selection un url class OpenWebCommand(sublime_plugin.TextCommand): def run(self,edit): #recuperation des selections faites sur l'editeur tabRegion=self.view.sel() for laRegion in tabRegion: ch...
# The following imports NEED to be in the exact order from cadCAD import configs ######### ADD FOR PRINTING CONFIG from cadCAD.configuration.utils import * from cadCAD.engine import ExecutionMode, ExecutionContext, Executor from src.sim import config exec_mode = ExecutionMode() exec_ctx = ExecutionContext(context=ex...
import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense,Conv2D, MaxPool2D, Flatten from tensorflow.keras.models import Model from sklearn.decomposition import PCA """ USAGE: This file is meant to be used as a library/module which is imported into other programs in order to test the algorit...
# emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # -*- coding: utf-8 -*- # ex: set sts=4 ts=4 sw=4 noet: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and...
#!/usr/bin/python3 #adjust parameters ReadLen, AmpLen and Stringent at the start of the script prior to executing. Defaults for GFP at respectively 150, 157 and "Yes". #quit if old python version import sys if sys.version_info[:2] < (3,0): print("This script is written for python 3.0 or above, please upgrade to...
from threading import RLock from meross_iot.supported_devices.abilities import * from meross_iot.supported_devices.timeouts import SHORT_TIMEOUT, LONG_TIMEOUT from meross_iot.supported_devices.protocol import AbstractMerossDevice, l def to_rgb(rgb): if rgb is None: return None elif isinstance(rgb, in...
import sys from maya import OpenMaya, OpenMayaUI, cmds from rjSkinningTools import ui, utils from . import getSkinnedVertices # ---------------------------------------------------------------------------- WINDOW_TITLE = "Tweak Vertex Weights" WINDOW_ICON = "tweakVertexWeights.png" ORANGE_STYLESHEET = "QLabel{color:...
import re import json import logging import time from tests.common.utilities import wait, wait_until logger = logging.getLogger(__name__) SYSTEM_STABILIZE_MAX_TIME = 300 MONIT_STABILIZE_MAX_TIME = 420 OMEM_THRESHOLD_BYTES=10485760 # 10MB def check_services(dut): logger.info("Checking services status on %s..." % ...
# # TM1637.py # # python library for driving TM1637 based led displays # <NAME>, 2018 # # resources: # https://os.mbed.com/components/TM1637-LED-controller-48-LEDs-max-Keyboa # https://sourceforge.net/projects/raspberry-gpio-python # # requires gpio permissions: sudo adduser <userid> gpio # # # MIT...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import abc import six from cliff.command import Command from cliff.lister import Lister from cliff.show import ShowOne from jexia_cli.utils import with_authentication from jexia_sdk.http import HTTPClientError LOG = logging.getLogger(__name__) CONSTRAINT...
import asyncio import json import time from multiprocessing import Process from pathlib import Path from typing import Any, Dict, Tuple import pytest from suzieq.poller.controller.credential_loader.static import StaticLoader from suzieq.poller.controller.source.netbox import Netbox from suzieq.shared.exceptions import...
# -*- coding: utf-8 -*- # # Authors: Swolf <<EMAIL>> # Date: 2021/3/4 # License: MIT License """ High-gamma dataset. """ import re from typing import Union, Optional, Dict, List, Tuple from pathlib import Path import numpy as np import h5py import mne from mne.io import Raw from mne.channels import make_standard_monta...
#!/usr/bin/env python import logging import json import pika import threading import time from exception import ConstructorError from exception import OperationError from exception import NotcallableError from util import Util logger = Util.getLogger(__name__) class Engine: def __init__(self, **kwargs): ...
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import math import pickle import time from datetime import datetime import boto3 import botocore from dateutil.tz import tzlocal...
""" This class implements the SuperVectorizer, which is a preprocessor used to automatically apply encoders to different types of data, without the need to manually categorize them beforehand, or construct complex Pipelines. """ # Author: <NAME> <<EMAIL>> | https://github.com/LilianBoulard import sklearn import nu...
from __future__ import unicode_literals import re import time import logging import socket from netmiko.cisco_base_connection import CiscoBaseConnection show_trace = 0 if show_trace > 1: logger = logging.getLogger('netmiko_connection') logger.setLevel(logging.DEBUG) def trace(fmt, *args): if show_trace <...
import contextlib import re import sys import itertools as it import typing as ty from collections import deque from typing import List, TextIO, Tuple import click import numpy as np import ujson as json import spacy from typing_extensions import Literal, TypedDict T = ty.TypeVar("T") spacy.tokens.Span.set_exte...
# -*- coding: utf-8 -*- """ Created on Tue Feb 18 16:16:28 2020 @author: sxm6202xx """ import os import random import json from shutil import copyfile from ast import literal_eval from DictionaryGeneration import FindIntersectingPercentage import pickle # Folder where the Hierarchy JSON Folder resides data_folder = ...
r"""The ``images`` module provides the core functionality of MPoL via :class:`mpol.images.ImageCube`.""" import numpy as np import torch import torch.fft # to avoid conflicts with old torch.fft *function* from torch import nn from . import utils from .coordinates import GridCoords from .gridding import _setup_coords...
# -*- coding: utf-8 -*- # pylint: disable-msg= """ Created on Mon Jul 28 18:18:20 2014 This module defines the abstraction pattern to describe "Ventricular Couplets", a rhythm pattern consisting of two consecutive ventricular extrasystoles between two normal complexes. @author: <NAME> """ from kardioml.segmentation....
import pyspark import sagemaker_pyspark from pyspark import SparkConf from pyspark.sql import SparkSession, DataFrame from datetime import datetime, timedelta import argparse import logging import boto3 import botocore import time import os from typing import Tuple logger = logging.getLogger('__name__') logger.setLev...
import collections from functools import partial, reduce, lru_cache import simplejson as json import pandas as pd import numpy as np from .core import parallel, render_html, listify, add, CORD_CHALLENGE_PATH, BIORXIV_MEDRXIV, \ NONCOMM_USE_SUBSET, CUSTOM_LICENSE, COMM_USE_SUBSET, find_data_dir from pathlib import P...
import abc import io import re import json import yaml import requests from collections import OrderedDict, defaultdict from django.core import exceptions from django.utils.module_loading import import_string import tabulator from .. import utils from ..ingest_settings import UPLOAD_SETTINGS #######################...
""" Additional layers. """ import torch from torch import nn from torch.nn import init from torch.autograd import Variable import torch.nn.functional as F from utils import constant, torch_utils class LSTMLayer(nn.Module): """ A wrapper for LSTM with sequence packing. """ def __init__(self, emb_dim, hidden_d...
#! /usr/bin/env python # SPDX-FileCopyrightText: Copyright 2021, <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-3-Clause # SPDX-FileType: SOURCE # # This program is free software: you can redistribute it and/or modify it # under the terms of the license found in the LICENSE.txt file in the root # directory of this so...
from sqlalchemy.orm import Session from sqlalchemy.exc import IntegrityError from fastapi import HTTPException from ..db import models, schemas from ..utils import * from datetime import datetime import time import subprocess import docker def get_running_apps(): apps_list = [] dclient = docker.from_env() ...
from collections import defaultdict, OrderedDict, MutableMapping, Hashable import os import pdb import sys import random import math import csv import tensorboardX class TensorboardManager: def __init__(self, path): self.writer = tensorboardX.SummaryWriter(path) def update(self, split, step, vals): ...
import nltk import sys import os from os.path import expanduser from nltk.tag.senna import SennaTagger from nltk.corpus import stopwords stopwords = stopwords.words('english') #phrase_list=[] path =sys.argv[1] ''' Extract leaves of noun & verb phrases from the tree ''' def generate_phrase_file(st,chunker,fname): p...
"""A client to obtain metadata and text content from bioRxiv (and to some extent medRxiv) preprints.""" import re import logging import requests import datetime logger = logging.getLogger(__name__) # Browser link at https://connect.biorxiv.org/relate/content/181 collection_url = 'https://connect.biorxiv.org/relate/...
""" .. module:: graphelement.py :platform: Linux .. moduleauthor:: <NAME> <<EMAIL>> """ from serialization import serializer from graph import elementtype GENERIC_VERTEX = 'generic_vertex' class GraphElement(object): ''' This class is the in-memory representation of an existing graph element. It is a ...
import logging import math import pickle import sys from enum import Enum import cv2 import numpy as np from matplotlib import pyplot as plt from scipy import ndimage as nd from scipy import signal as sg from scipy.ndimage import zoom from skimage.feature import peak_local_max from pysal.esda.getisord import G_Local ...
""" This file is a part of the Kithare programming language source code. The source code for Kithare programming language is distributed under the MIT license. Copyright (C) 2021 Kithare Organization builder/downloader.py Defines a ThreadedDownloader that helps in downloading dependencies in the background """ impor...
from index import db, bcrypt import networkx as nx import numpy as np from sklearn.metrics.pairwise import cosine_similarity from collections import Counter import operator # class User(db.Model): # id = db.Column(db.Integer(), primary_key=True) # email = db.Column(db.String(255), unique=True) # password =...
# Currently the reference source for this code in this form is the # 'Curt' branch here: # # https://github.com/clolsonus/GMS-Feature-Matcher/tree/Curt # # This version has been modified to better match the naming # conventions of the original C++ version of the algorithm. It also # has some structure copying and ...
#!/usr/bin/env python # Copyright 2017 Google Inc. 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 requir...
from robot_class import robot from math import * import random import numpy as np import matplotlib.pyplot as plt import seaborn as sns # -------- # this helper function displays the world that a robot is in # it assumes the world is a square grid of some given size # and that landmarks is a list of landmark position...
import torch.nn as nn import math import torch.utils.model_zoo as model_zoo import torch from torch.autograd import Function, Variable import numpy as np __all__ = ['ResNet', 'resnet50'] model_urls = { 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', } def conv3x3(in_planes, out_planes,...
# # This file is part of LiteX. # # Copyright (c) 2019-2021 <NAME> <<EMAIL>> # SPDX-License-Identifier: BSD-2-Clause from enum import IntEnum from migen import * from migen.genlib.cdc import PulseSynchronizer from litex.soc.interconnect.csr import * from litex.soc.interconnect import stream # Constants -----------...
# Copyright 2014 The Swarming Authors. All rights reserved. # Use of this source code is governed by the Apache v2.0 license that can be # found in the LICENSE file. """Integration with webapp2.""" # Disable 'Method could be a function.' # pylint: disable=R0201 import functools import json import logging import weba...
from blaze.expr import * from blaze.expr.split import * from datashape import dshape from datashape.predicates import isscalar, isrecord, iscollection t = symbol('t', 'var * {name: string, amount: int32, id: int32}') a = symbol('a', '1000 * 2000 * {x: float32, y: float32}') def test_path_split(): expr = t.amount...
import numpy as np import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable from mpl_toolkits.axes_grid1.axes_size import AxesX, AxesY, Fraction class PlotIndexTracker(object): def __init__(self, ax, mother_ax, x, y, orientation='vertical', **kw...
# Using a Multiple Layer Network # --------------------------------------- # 使用多层神经网络层构造神经网络 # We will illustrate how to use a Multiple # Layer Network in TensorFlow # # Low Birthrate data: # # Columns(列) Variable(值) Abbreviation # ----------------------------------------------------------...
import re from collections import OrderedDict from copy import deepcopy from modpipe import Done VAR_NAME_RE = re.compile("^[A-Z0-9abcdexyz]+$") STUDY_VARIABLE_RE = re.compile("^([^:]+):\s([A-Za-z0-9\- \:\(\)\/\.\,'\$\[\]\#]+)$") RACE_SUMMARIES = {"Race summary, 3 categories", "Race-ethnicity summ...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # # 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 applica...
from datetime import datetime as dt import codecs, glob, os, shutil, subprocess, sys, time import util try: from envbash import load_envbash except: print ("envbash not found, install it by typing") print ("\tpip install envbash") print ("\tReference: https://pypi.org/project/envbash/") exit(1) def cad(arg...
from collections import namedtuple from ply import lex, yacc reserved = { 'sum': 'SUM', 'sums': 'SUM', 'product': 'PRODUCT', 'products': 'PRODUCT', 'integral': 'INTEGRATE', 'integrals': 'INTEGRATE', 'integrate': 'INTEGRATE', 'antiderivate': 'INTEGRATE', 'antiderivative': 'INTEGRATE...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
""" mcpython - a minecraft clone written in python licenced under the MIT-licence (https://github.com/mcpython4-coding/core) Contributors: uuk, xkcdjerry (inactive) Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence Original game "minecraft" by Mojang Studios (www.m...
# Copyright (c) 2019-2021, NVIDIA CORPORATION & AFFILIATES. 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 ...
import os import sys import torch import numpy as np from BrainMaGe.models.networks import fetch_model from pathlib import Path import matplotlib.pyplot as plt from compare_utils import ( postprocess_prediction, postprocess_save_output, postprocess_output, dice, get_mask_image, get_input_image ...
from datetime import datetime, timedelta from django.utils.translation import ugettext as _, ugettext_noop from dimagi.utils.decorators.memoized import memoized from corehq.apps.api.es import ReportCaseES from corehq.apps.cloudcare.api import get_cloudcare_app, get_cloudcare_form_url from corehq.apps.reports.datatables...
# # -*- coding: utf-8 -*- # Copyright 2019 Cisco and/or its affiliates. # GNU General Public License v3.0+ # (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) """ The nxos telemetry utility library """ from __future__ import absolute_import, division, print_function __metaclass__ = type import re from copy im...
# Copyright (c) 2013 Mirantis, Inc. # # 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...
############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
#!/usr/bin/env python3 # import sys import os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import argparse import datetime import Libraries.arguments as ar import Libraries.tools.general as gt import Libraries.tools.zabbix as zt import Classes.AppConfig as AppConfig import requests imp...
from collections import OrderedDict from .. import utils __all__ = [ "Layer", "MergeLayer", ] # Layer base class class Layer(object): """ The :class:`Layer` class represents a single layer of a neural network. It should be subclassed when implementing new types of layers. Because each lay...
# -*- coding: utf-8 -*- """ Created on Fri Oct 4 10:06:21 2019 @author: Kiera """ import random import time import argparse import os import numpy as np from cluster import total_lennard_jones_potential, shortest_distance_of_cluster def get_cluster_from_file(file): """ takes file as input ...
from typing import Optional, Tuple, Callable, Union, List import logging import numpy as np import torch from gpytorch import ExactMarginalLogLikelihood from gpytorch.constraints import GreaterThan from gpytorch.likelihoods import GaussianLikelihood from torch import Tensor from torch.distributions import Normal from ...
import math import os import torch import torch.distributions.constraints as constraints import pyro from pyro.optim import Adam, SGD from pyro.infer import SVI, Trace_ELBO, config_enumerate import pyro.distributions as dist from pyro.infer.autoguide import AutoDelta from pyro import poutine from pyro.poutine import tr...
""" Create and access groups of databases, each configured from different settings. """ __author__ = '<NAME> <<EMAIL>>' __date__ = '4/29/14' import glob import os import re from . import dbconfig, query_engine, util from six.moves import filter # aliases _opj = os.path.join _opx = os.path.splitext class CreateQueryE...
import networkx as nx import numpy as np import torch from torch_geometric import utils from torch_geometric.data import Data, InMemoryDataset NODE_PRIMITIVES = [ # 'none', 'input_0', 'input_1', 'inter_node', 'output' ] OP_PRIMITIVES = [ 'identity', 'max_pool_3x3', 'avg_pool_3x3', ...
import torch import math import numpy as np from i3dpt import I3D, Unit3Dpy from utils import kernels from opts import args class modI3D(torch.nn.Module): def __init__(self, modality, wts, dog, load, mean=False, random=False): super(modI3D, self).__init__() # Have to be different self.m...
# Copyright 2021 <NAME> # # 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 writing, software ...
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np import os from cil.io import TXRMDataReader from cil.processors import TransmissionAbsorptionConverter from cil.plugins.tigre import FBP from cil.utilities.display import show2D, show_geometry from cil.recon import FDK from cil.io import NEXUSDataWr...
# coding:utf-8 import gc import os import numpy as np import pandas as pd from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from sklearn.model_selection i...
import numpy as np import pysam import subprocess import argparse import os, pdb from collections import Counter MIN_MAP_QUAL = 10 BEFORE_EXT = 0 # def merge_beds(beds, bedtools_path): # with open('.combined.bed', 'w') as out: # subprocess.call(['cat'] + beds, stdout=out) # # with open('.sorted.bed'...
import re import sublime_plugin try: # Python 3 from .haxe_generate_code_helper import * except (ValueError): # Python 2 from haxe_generate_code_helper import * class HaxeGenerateGetSet(sublime_plugin.WindowCommand): @staticmethod def poll(ctx): view = ctx.view cmds = [] i...
from __future__ import absolute_import, division, print_function import numpy as np import pandas as pd from itertools import product import units import moments def _format_obs_history(obs_history, field, save_to_disk=None): """ Parameters ---------- obs_history : Pandas.DataFrame field : Pandas.D...
# coding: utf-8 # Evolution of "Odd galaxies" found in the "zone of avoidance" in lambda vs eps plot. # # 160500811, 160500745, 3566300002, 2917600065, 2917600001, # 1000200001, 3641500003, 3999000032, 3999000015, 3999000001, 3641300444 # In[1]: import pickle import matplotlib.pyplot as plt import numpy as np fro...
def vector_size_check(*vector_variables): # value = 0 # last_value = 0 # for vector in vector_variables: # value = len(vector) # if last_value == 0: # last_value = len(vector) # else: # if value != last_value: # return False # return True return ...
# -*- coding: utf-8 -*- import pytest import pysbd GOLDEN_DA_RULES_TEST_CASES = [ ("<NAME>. Mit navn er Jonas.", ["<NAME>.", "Mit navn er Jonas."]), ("Hvad er dit navn? Mit nav er Jonas.", ["Hvad er dit navn?", "Mit nav er Jonas."]), ("There it is! I found it.", ["There it is!", "I found it."]), ("My name is <NAME>...
import os import re import json import numpy as np from typing import Dict, List, Union from utils import get_unique_order_preserving from settings import RANDOM_SEED def load_squad(data_path: str, return_flat: bool=False) -> Union[List, Dict]: """Load a SQuAD format dataset""" with open(os.path.expanduser(da...
import pandas as pd import geopandas as gpd import shapely import seaborn as sns import matplotlib import matplotlib.pyplot as plt RED = "#A01914" BLUE = "#4F6DB8" GREY = "#C0C0C0" BLUE_TO_RED = [ # https://vis4.net/palettes/#/9|d|002d6e,a7bffa,ffffbf|ffffbf,fdad97,720000|1|0 '#002d6e', '#375d9c', '#708fcc', '#ad...
from typing import List from pip._vendor.distlib.compat import raw_input from termcolor import colored from data_set_info_data_class.data_class.data_set_info import DataSetInfo from data_set_remover import Remover from data_set_remover.classes.data_class.data_for_criteria_remove import DataForCriteriaRemove from data...
import torch from torch.optim.lbfgs import LBFGS from core.math import mmd, cg, safe_div from torch.distributions.normal import Normal from core.model.policy_with_value import PolicyWithValue from core.common import StepDictList, SampleBatch, ParamDict # global cache for speed-up mmd calculation mmd_cache = {} def ...
import glob import os import re import pandas as pd from util import Util def save_pickle_from_csv(root_dir="./../input/", merge_method=None): if merge_method is None: merge_method = [["tokyo"], [y for y in range(2008, 2020)], [5, 9]] dataset = BasicDataset(root_dir, merge_method) d...
""" The data_cleaner module is used to clean missing or NaN values from pandas dataframes (e.g. removing NaN, imputation, etc.) """ import pandas as pd import numpy as np import logging from sklearn.preprocessing import Imputer import os from scipy.linalg import orth log = logging.getLogger('mastml') def flag_outli...
""" Temperature scaling on a validation set.... From this... https://arxiv.org/pdf/1706.04599.pdf """ from seg_utils import * from seg_models import ResNet_UNet, ResNet_UNet_ExtraConv, ResNet_UNet_Dropout from keras.models import Model from keras.layers import Softmax, Reshape, Layer from keras.initializers imp...