text stringlengths 3.07k 22.1k |
|---|
#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
import configparser
import argparse
import os
import sys
import logging
import datetime
ofx = {
'VERSION': '220',
'OFXHEADER': '200',
'SECURITY': 'NONE',
'ENCODING': 'USASCII',
'CHARSET': '1252',
'COMPRESSION': 'NONE',
'OLDFIL... |
from typing import Any
from typing import Collection
from typing import Dict
from typing import Optional
from typing import Tuple
import torch
class Callback:
r"""Base class for callbacks where all methods do nothing.
Each method is called by the :py:class:`CallbackHandler` at specific times
during the ... |
import fiona
import geohash
import os
import rtree
import ujson as json
from collections import OrderedDict, defaultdict
from shapely.geometry import Point, Polygon, MultiPolygon
from shapely.prepared import prep
from shapely.geometry.geo import mapping
from geodata.polygons.area import polygon_bounding_box_area
DEF... |
import numpy as np
from scipy.special import ellipe, ellipk
def curl(quantity, spacing=(1, 1, 1), mesh=None,
vector_grad=None):
r"""
Return 3D curl.
"""
if not vector_grad:
dx, dy, dz = spacing
if mesh:
dx = mesh[0][0, 1, 0] - mesh[0][0, 0, 0]
dy = mesh[... |
"""Unit tests for glue-supported APIs."""
from random import randint
from uuid import uuid4
import boto3
import pytest
import sure # noqa # pylint: disable=unused-import
from botocore.exceptions import ParamValidationError
from botocore.client import ClientError
from moto import mock_glue
@mock_glue
def test_creat... |
#!/usr/bin/env python3
# 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 itertools
import json
import os.path as osp
import numpy as np
import pytest
import quaternion
import habitat_s... |
import json
import logging
import os
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.urlresolvers import reverse
from django.db import transaction
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import... |
import torch
import torch.nn as nn
import os, glob
import optuna
import numpy as np
from CNN import CNN
from DataHelper import BertHelper
from torch.utils.data import DataLoader
from tqdm import tqdm
from collections import OrderedDict
from sklearn.metrics import f1_score
from transformers import AdamW, get_... |
# Copyright (c) 2015 Red Hat, 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 agreed to in writ... |
"""
Functions to determine the current status of a job
Once a job is submitted to the cluster is goes through three statuses:
pending, running and finished.
Each status is marked by a specific condition of files and directories that
are present in the `sub_dir` (the directory from which the job was submitted).
While... |
from collections import namedtuple
#from process_logs import BenchmarkResult, process_client_logs
from pyrem.host import RemoteHost
from pyrem.task import Parallel
import argparse
import benchmark
import csv
import datetime
import time
import json
import os
import os.path
import subprocess
import time
# A set of bench... |
#!/usr/local/autopkg/python
#
# Copyright 2013 <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 ... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.python.ops import math_ops
# from tensorflow_addons.seq2seq import BahdanauAttention
# NOTE: linter has a problem with the current TF release
#pylint: disable=no-value-for-parameter
#pylint: disable=unexpected-keyword-arg
class Linear(keras.layers.L... |
"""Utils for handling video files and streams."""
import pathlib
import time
import warnings
from typing import cast, List, Optional, Tuple
import numpy as np
import cv2
from .utils import PathLike
class VideoCapture:
"""A thin wrapper simplifying the use of `cv2.VideoCapture`.
Actually I would recommend u... |
'''
helper for holding simple custom functions i reuse loads
'''
import numpy as np
import cv2
from scipy import ndimage as nd
font = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 0.5
lineType = 2
def threshold_array(arr):
arr[arr <= 125] = 0
arr[arr > 125] = 255
return arr
''' helper for localisation '''
def m... |
#! /usr/bin/env python3
#
# gridscapereader.py - read data from gridscape over the VPN or locally or by magic
#
'''
gridscapereader.py - read data from one or more gridscape runs and iterations.
'''
import numpy as np
import pandas as pd
import urllib.request
import json
import io
from os.path import expanduser
from ... |
import graphene
from lingvodoc.schema.gql_holders import (
LingvodocObjectType,
CompositeIdHolder,
CreatedAt,
Relationship,
SelfHolder,
FieldHolder,
ParentLink,
MarkedForDeletion,
Position,
client_id_check,
del_object,
ResponseError,
TranslationHolder,
Translation... |
# ========================================================================
#
# Copyright NumFOCUS
#
# 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/license... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import unittest
from flask import Flask
from werkzeug.routing import BuildError
from coaster.db import db
from .test_models import Container, NamedDocument, ScopedNamedDocument
# --- Test setup ---------------------------------------------------------... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from __future__ import print_function
import itertools
import json
import engine.primitives as primitives
from engine.core.requests import Request
def get_product_exhaust(sets, bound):
""" Return the product of the input sets exhaustively
... |
# DTT Script to transform the original INRIA Aerial Image Labeling Dataset
# (https://project.inria.fr/aerialimagelabeling/) to images apropriate to feed
# into the pix2pix implementation based on https://github.com/mrzhu-cool/pix2pix-pytorch
# 17/01/2021
import argparse
import os
from os import lis... |
#!/usr/bin/env python3
#
# Copyright (c) Contributors to the Open 3D Engine Project.
# For complete copyright and license terms please see the LICENSE at the root of this distribution.
#
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
#
import argparse
import logging
import os
import pathlib
import platform
import re... |
# encoding: utf-8
"""
@author: gallupliu
@contact: <EMAIL>
@version: 1.0
@license: Apache Licence
@file: data_utils.py
@time: 2018/3/3 12:02
"""
import re
import os
import sys
import csv
import jieba
import logging
import multiprocessing
import numpy as np
import pandas as pd
from gensim.models import Word2Vec
from... |
# -------------------------------------------------------------------------------
# Copyright IBM Corp. 2017
#
# 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/licens... |
import sys
from itertools import chain
from functools import reduce
from operator import mul
from numpy import intp, bool_, array
import numpy.testing
from pytest import fail
from hypothesis.strategies import (integers, none, one_of, lists, just,
builds, shared, composite)
from hyp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import operator
import xml.etree.ElementTree as ET
from collections import namedtuple
from itertools import islice
from math import sin, cos, atan2, radians, sqrt
LatLon = namedtuple('LatLon', 'lat, lon')
def distance(x, y):
"""Implements https:/... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2020-2021 <NAME> and <NAME>
#
# Distributed under terms of the BSD 3-Clause license.
"""Functions related to plotting depth with matplotlib."""
import os
import copy
import pathlib
import argparse
import tempfile
import multiprocessing
fro... |
#!/usr/bin/env python3
# coding=utf-8
import argparse
import codecs
from codecs import StreamWriter
import io
import os
import queue
import re
import sys
import threading
from types import FrameType
from typing import BinaryIO, List, TextIO, Tuple, Union
try:
from blessed import Terminal
_term = Terminal()
e... |
#DeepPasta data examination with same methods for same regions and truth values
from __future__ import print_function
import keras
from keras.models import Sequential, Model, load_model
from keras import backend as K
import tensorflow as tf
import isolearn.keras as iso
import os
import pandas as pd
import numpy as n... |
# -*- coding: utf-8 -*-
"""
Serialization functions for the SimpleMRS format.
"""
from pathlib import Path
from delphin.util import Lexer
from delphin import predicate
from delphin.lnk import Lnk
from delphin.sembase import (role_priority, property_priority)
from delphin import variable
from delphin.mrs import (
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# c1219/data.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of condi... |
import datetime
import json
import uuid
from functools import wraps
import jwt
import six
from werkzeug.local import LocalProxy
from flask import request, jsonify, current_app
try:
from flask import _app_ctx_stack as ctx_stack
except ImportError: # pragma: no cover
from flask import _request_ctx_stack as ctx... |
# --------------------------------------------------------
# Domain adpatation training
# Copyright (c) 2019 valeo.ai
#
# Written by <NAME>
# --------------------------------------------------------
import os
import sys
from pathlib import Path
import os.path as osp
import numpy as np
import torch
import torch.backend... |
import re
from odoo import api, models, fields, _
from odoo.exceptions import UserError
from datetime import datetime
EMAIL_REGEX = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})*(\.\w{2,3})+$'
PHONE_REGEX = '^[0-9]{7,13}$'
def regex_validation_message(field, regex, message):
if field:
if not re.search(rege... |
#!/usr/bin/env python
# coding=UTF-8
import argparse
import os
import random
import sys
import numpy as np
import torch
import torch.utils.data as Data
import cv2
import functools
from utils.EvalDataLoader import EvalDataset
from utils.file_utils import xmlparser
import torchvision
from torch.autograd import Variable
... |
from .output import OutputType, Output, Normalization
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def draw_attribute(data, outputs, path=None):
if isinstance(data, list):
num_sample = len(data)
else:
num_sample = data.shape[0]
id_ = 0
for ... |
# -*- coding: utf-8 -*-
"""
Data generators to load images
"""
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from helperFunctions import parse_name, rotation_matrix, classes, eps
from axisAngle import get_y, get_R
from quaternion import get_y as get_quaternion
from PIL import I... |
# Copyright 2019 Northern.tech AS
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
"""
Project: pubsne
Authors:
kceades
"""
# importing from files I wrote
import snmc
import tools
import snetools
# imports from standard packages
import os
import numpy as np
from sklearn.decomposition import PCA
from mfa import FactorAnalysis
import pickle
from multiprocessing import Process
from threading import T... |
import glob
import os
import sys
import time
import cv2
import numpy as np
import png
from ip_basic import depth_map_utils
from ip_basic import depth_map_utils_orig
from ip_basic import vis_utils
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--dataset', default='kitti')
parser.ad... |
"""
Verify hand-eye calibration by transforming all dataset point clouds and
visualizing them overlapped.
Running this sample requires the dataset (robot poses and point clouds)
and the output transformation matrix of the Hand-Eye calibration.
The transformation will be done to different robot frames, depending on
th... |
"""
A set of functions that are useful for pre-processing textual data: uniformizing the words, spelling, etc.
The MIT License (MIT)
Copyright (c) 2021 <NAME> (<EMAIL>) & Stanford Geometric Computing Lab
"""
import re
contractions_dict = {
"ain't": "am not",
"aren't": "are not",
"can't": "cannot",
"c... |
# Copyright © 2019 Splunk, 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 agreed to in writing, software
... |
import torch
from artemis.experiments import ExperimentFunction
from artemis.experiments.experiment_record import ExperimentRecord
from artemis.general.checkpoint_counter import do_every
from artemis.general.duck import Duck
from artemis.general.should_be_builtins import izip_equal
from artemis.plotting.db_plotting imp... |
"""Conversão de Texto x Objeto
Recebe uma string, Autômato, no padrão definido e
separada as informações presentes na sting e as salva
em cada atributo da estrutura de dicionário.
"""
def texto_para_obj(texto):
linhas = texto.split("\n")
estrutura = {}
estrutura['n_estados'] = linhas[0]
estrutura['ini... |
import gym
import gymcpu
from gymcpu.envs.cpu_env00 import CPUEnv00
from gymcpu.envs.cpu_env01 import CPUEnv01
from gymcpu.envs.cpu_env02 import CPUEnv02
import ray
import ray.rllib.agents.ppo as ppo
from ray.tune.registry import register_env
import numpy as np
import subprocess
import os
import shutil
import signal
... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
import torch
import numpy as np
from config import *
class ConcreteGate(torch.nn.Module):
def __init__(self, shape, device):
super().__init__()
self.eps = GATE_EPS
self.device = device
self.hard = GATE_HARD
self.l0_penalty = GATE_PENALTY
self.local_rep = GATE_LOCAL_R... |
#!/usr/bin/env python
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>, based on code from <NAME>
# --------------------------------------------------------
"""
Demo script showing detections in sample i... |
from typing import Any, Dict, Tuple, Union
import logging
import torch
from torch import nn
from catalyst.callbacks.batch_overfit import BatchOverfitCallback
from catalyst.callbacks.checkpoint import CheckpointCallback
from catalyst.callbacks.criterion import CriterionCallback
from catalyst.callbacks.early_stop impor... |
from __future__ import absolute_import
__author__ = 'katharine'
import calendar
import collections
import datetime
import dateutil.parser
from dateutil.tz import tzlocal
import logging
import requests
import struct
import time
import traceback
from uuid import UUID
import urllib
import pypkjs.PyV8 as v8
from libpebbl... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import numpy as np
import argparse
import pprint
import pdb
import time
import logging
import glob
import pandas as pd
import scipy.misc
import torch
from functools import partial
import p... |
import os
from dataclasses import dataclass
from typing import Generator, Tuple, List
from django.contrib.postgres.aggregates import ArrayAgg
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import QuerySet, Exists, OuterRef, Q, F, Case, When
from django.db.models.expressions import Combined... |
import os
from time import sleep
from functools import wraps
from threading import Event
from traceback import print_exc
from inspect import getframeinfo, stack
import PIL
from helpers import setup_logger
from ui.utils import to_be_foreground
logger = setup_logger(__name__, "info")
def internal_callback_in_backgrou... |
# -*- coding: utf-8 -*-
try:
from collections.abc import Mapping # python 3.8
except ImportError:
from collections import Mapping
from collections import OrderedDict
import dask
import dask.array as da
from dask.highlevelgraph import HighLevelGraph
import numpy as np
try:
import xarray as xr
except Imp... |
import cv2
import math
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
# def draw_point(img, landmarks):
# img = np.array(img).copy()
# h, w = img.shape[:2]
# l = math.sqrt(h * h + w * w)
# for idx, point in enumerate(landmarks):
# point = np.around(point).astype(np... |
from abc import ABCMeta, abstractmethod
from pyzshcomplete.utils.zsh_constants import ZshConstants
class ArgumentAdapterInterface(metaclass=ABCMeta):
'''
DO NOT subclass from this class directly, as it doesn't contain the
completion generation logic. See ArgumentAdapter.
Defines the interface to be ... |
import socket
import ssl
import struct
import json
import base64
import logging
from typing import List
from .message import BinaryMessage
from .common import AbstractRobot, RobotStates, BatteryStatus, PowerModes
logger = logging.getLogger(__name__)
class RobotClient(AbstractRobot):
CLEAN_PLAY = 1
CL... |
from __future__ import print_function
import copy
import logging
import re
import statistics as s
import sys
log = logging.getLogger(__name__)
def main():
balancer = IRQBalancer()
current_balanced_info = balancer.get_balanced_irq_info()
print("Current Balance Info: \n",
"\tstdev: %10f".rjust(4)... |
# Copyright <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
... |
import os
import time as Time
from math import *
import datetime
utc_format='%Y-%m-%dT%H:%M:%S'
recordID = 0
cardID = 1
tradeType = 2 #tradeType=21/22 means subway on/off, 1 means bus on
time = 3
TrafficLine = 4
station = 5
lon=6
lat=7
def calcDistance(lat1, lon1, lat2, lon2):
#Calculate the great circle distance... |
#Code for computing approximate differential privacy guarantees
# for discrete Gaussian and, more generally, concentrated DP
# See https://arxiv.org/abs/2004.00010
# - <NAME> <EMAIL> 2020
import math
import matplotlib.pyplot as plt
import discretegauss as dg
# Begin with some code to compute aDP guarantees for discr... |
#!/usr/bin/env python
# ===================================================================================
# Copyright (C) 2021 Fraunhofer Gesellschaft, <NAME>. All rights reserved.
# ===================================================================================
# This Acumos software file is distributed by Fraun... |
import numpy as np
from numpy.testing import assert_allclose, run_module_suite
import numpy.testing
import pyccl as ccl
# Set tolerances
TOLERANCE = 1e-4
def test_redshift_analytic():
"""
Compare the redshift functions to an analytic toy case.
"""
# Redshift input
z_lst = [0., 0.5, 1., 1.5, 2.]
... |
import cv2
import argparse
import numpy as np
from keras.models import load_model
from keras.preprocessing import image
arr_out = []
arr_result = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
model=load_model('fmodelwts... |
"""
Created on Wed Jan 14 23:01:57 2020
@author: <NAME> <<EMAIL>>
"""
import numpy as np
import os
import re
import subprocess
import sys
from typing import Dict, Union
try:
import torch
except:
pass
# backwards compatibility after refactoring
from pysmtb.image import assign_masked, annotate_image, pad, col... |
# -*- coding: utf-8 -*-
"""
werkzeug.urls
~~~~~~~~~~~~~
This module implements various URL related functions.
:copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import urlparse
from werkzeug._internal import _decode_unicode
... |
import os
import pytz
import requests
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
from datetime import timedelta, datetime
from auditlog.registry import auditlog
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.m... |
#!/usr/bin/env python3
from __future__ import print_function
from __future__ import division
import sys
import os
import subprocess
import time
import datetime
import signal
def actuallyprint(msg):
print(msg)
sys.stdout.flush()
def autoconfig(bucket_weight_bytes, cache_size_bytes):
cache_size_nodes = int(... |
import dill
import os
import yaml
import numpy as np
import skimage.io
import pandas as pd
from pathlib import Path
from .store.parameters import Param
from .store.dataset import TIFFSeries, MultipageTIFF, ND2, H5
# https://stackoverflow.com/a/2121918
import sys
from morphodynamics.store import results
sys.modules['m... |
# Call as downstream classification, e.g.
# python -m CLAPPVision.vision.visualise --model_path ./logs/your_simulation --model_num 299 --encoder_type 'vgg_like' --model_splits 6 --train_module 6 --module_num 6 --batch_size 100
################################################################################
import to... |
import numpy as np
from sklearn.manifold import MDS
from sklearn.metrics import euclidean_distances
import scipy
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import os
from matplotlib.image import BboxImage
from matplotlib.transforms import Bbox, TransformedBbox
from pycocotools.coco import COCO
from an... |
from datetime import timedelta
from django.urls import reverse
from django.utils import timezone
from jcasts.shared.template import (
absolute_uri,
active_link,
approx_timesince,
colorpicker,
format_duration,
login_url,
markup,
normalize_url,
pagination_url,
re_active_link,
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
CHANNELS_layer1 = [4, 8, 12, 16]
CHANNELS_layer2_7 = [4, 8, 12, 16]
CHANNELS_layer8_13 = [4, 8, 12, 16, 20, 24, 28, 32]
CHANNELS_layer14_19 = [4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64]
class Conv2dBlock(nn.Module):
... |
import argparse
import cv2
import numpy as np
import glob
import time
import matmul_inference
import inpaint_inference
import os
INPUT_SIZE = 512 # input image size for Generator
ATTENTION_SIZE = 32 # size of contextual attention
MULTIPLE = 6
NPTYPE = np.float32
def sort(str_lst):
return [s for s in sorted(str... |
from common import ScanMode, ScanResult
import collections
import cv2
import functools
import json
import numpy
import os
from typing import Dict, Iterator, List, Tuple
# The expected color for the video background.
BG_COLOR = (194, 223, 228)
WOOD_COLOR = (115, 175, 228)
# Mapping from background colors (in BGR for... |
import numpy as np
import random
import os
import pandas as pd
from .raw_transaction_processing import run as run_preprocess
from .data_interface import GraphContainer
from .TGN_data_obj import Data as TGNData
from .data_fetchers import fetchers
add_zero = lambda mask, add: np.concatenate([np.array([False]),mask]... |
# Copyright 2020 DeepMind Technologies Limited.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
import numpy as np
import torch
import dgl
import torch.nn as nn
from rdkit import Chem
from rdkit.Chem import rdmolops
# A mapping between the bond types and the number of bonds.
bond_dict = {"SINGLE": 0, "DOUBLE": 1, "TRIPLE": 2, "AROMATIC": 3}
# A mapping between edge types and bond types.
e_type_to_bond = {
... |
#!/usr/bin/env python
# coding: utf-8
import argparse
import json
import shutil
import sys
import tarfile
import textwrap
import time
from glob import glob
from pathlib import Path
from typing import Union, Optional
import wandb
from dotenv import load_dotenv
from loguru import logger
from birdfsd_yolov5.model_utils... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
"""
.. module:: utilities
:platform: Unix, Windows
:synopsis: A helper module for Curve and Surface classes
.. moduleauthor:: <NAME>
"""
import decimal
import math
# A float range function, implementation of http://stackoverflow.com/a/7267280
def frange(x, y, step):
""" An implementation of a ``range()... |
#!/usr/bin/env python3
##########################################################
## <NAME>, <NAME> & <NAME> ##
## Copyright (C) 2019-2021 Lauro Sumoy Lab, IGTP, Spain ##
##########################################################
'''
Calls MINTMap to create tRNA profile
'''
## useful imports
import time
impor... |
"""
Main module of the ev3dev2simulator. Starts the server thread listening for incoming connections and
starts the simulator itself. The simulator and server threads are started based on the arguments given.
"""
import argparse
import sys
import os
from ev3dev2simulator.config.config import load_config, get_world_co... |
#!/usr/bin/env python
"""
This simple example is used for the line-by-line tutorial
that comes with pygame. It is based on a 'popular' web banner.
Note there are comments here, but for the full explanation,
follow along in the tutorial.
"""
#Import Modules
import os, pygame, sys, errno, os.path
from pygame.locals imp... |
# Problem Name: Underscorify Substring
# Problem Description:
# Write a function that takes in two strings: a main string and a potential substring of the main string. The function should return a version of the main string with every instance of the substring in it wrapped between underscores.
# If two or more insta... |
# coding: utf-8
from base64 import b64encode, b64decode
from cStringIO import StringIO
from mako.template import Template
from os.path import join
from pyPdf import PdfFileReader, PdfFileWriter
from weasyprint import HTML
from re import match, sub, UNICODE
class TemplateError(Exception):
pass
cl... |
from abaqusConstants import *
from .ConnectorOptions import ConnectorOptions
from .ConnectorPotentialArray import ConnectorPotentialArray
from .TangentialBehavior import TangentialBehavior
# Prevent circular import
class DerivedComponent:
pass
class ConnectorBehaviorOption:
"""The ConnectorBehaviorOption o... |
from data.load_dataset import MultipleDataLoader
from lib.utils.training_stats import TrainingStats
from lib.utils.evaluate_depth_error import validate_rel_depth_err, recover_metric_depth
from lib.models.diverse_depth_model import *
from lib.core.config import cfg, merge_cfg_from_file, print_configs
from lib.utils.net_... |
from argparse import ArgumentParser
from bz2 import open as bz2_open
from enum import Enum
from pathlib import Path
from pickle import load as pickle_load
from typing import List, Optional
from torch.nn import Linear, LSTM, Module, Sequential
from torch.optim import Adam, SGD
from torch.optim.lr_scheduler import StepL... |
import logging
import os
from dj.choices import Choices
from django.conf import settings
from django.db import models
from django.db.models import F
from django.db.models.manager import Manager
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from ralph.assets.models impor... |
#!/usr/bin/env python -u
import argparse
import sys
import os
import time
import datetime
import random
start_time = str(time.time())
def getOptions(args=sys.argv[1:]):
parser = argparse.ArgumentParser(description="Parses command.")
parser.add_argument("-r", "--remote", help="Remote url")
parser.add_a... |
"""Import a DICOM tarball into a study dataset"""
from os import listdir
from os import makedirs
from os import rename
import os.path as op
import shutil
from datalad.consts import ARCHIVES_SPECIAL_REMOTE
from datalad.consts import DATALAD_SPECIAL_REMOTES_UUIDS
from datalad.interface.base import build_doc, Interface
f... |
import datetime
import itertools
import logging
import pickle
from typing import List, Tuple
import click
import matplotlib
import numpy as np
import pandas as pd
from matplotlib import figure
from sklearn.linear_model import ElasticNet
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
fr... |
import numpy as np
import pandas as pd
import vrp.io as io
def single_capacity_cost(warehouse, matrix):
'''
Calculate the symmetric cost of single trips
from a warehouse to each city and back again.
Parameters:
-------
warehouse - int or str
index / postcode sector of the warehouse. A... |
import os
import sys
import pandas as pd
import numpy as np
import openrouteservice as ors
import folium
import geopandas as gpd
import networkx as nx
import osmnx as ox
import geojson
from tqdm import tqdm, trange
import random as rn
from sklearn.metrics.pairwise import haversine_distances
from math import radians
ox... |
# Copyright 2014 VMware, 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 required by a... |
from random import shuffle
import tensorflow as tf
import tensorflow_text as tf_text
from tf_transformers.data import TFReader
from tf_transformers.utils import tf_utils
def split_fn(item, delimiter_pattern):
text_splitted = tf_text.regex_split(item['text'][0], delimiter_pattern, keep_delim_regex_pattern=' ', n... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 UPR.
#
# CuOR is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Blueprint definitions."""
from __future__ import absolute_import, print_function
import datetime
from operator import ite... |
# (Be in -*- python -*- mode.)
#
# ====================================================================
# Copyright (c) 2006-2008 CollabNet. All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also availabl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.